posixmodule.c 450 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110
  1. /* POSIX module implementation */
  2. /* This file is also used for Windows NT/MS-Win. In that case the
  3. module actually calls itself 'nt', not 'posix', and a few
  4. functions are either unimplemented or implemented differently. The source
  5. assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
  6. of the compiler used. Different compilers define their own feature
  7. test macro, e.g. '_MSC_VER'. */
  8. #define PY_SSIZE_T_CLEAN
  9. #include "Python.h"
  10. #ifdef __VXWORKS__
  11. # include "pycore_bitutils.h" // _Py_popcount32()
  12. #endif
  13. #include "pycore_call.h" // _PyObject_CallNoArgs()
  14. #include "pycore_ceval.h" // _PyEval_ReInitThreads()
  15. #include "pycore_fileutils.h" // _Py_closerange()
  16. #include "pycore_import.h" // _PyImport_ReInitLock()
  17. #include "pycore_initconfig.h" // _PyStatus_EXCEPTION()
  18. #include "pycore_long.h" // _PyLong_IsNegative()
  19. #include "pycore_moduleobject.h" // _PyModule_GetState()
  20. #include "pycore_object.h" // _PyObject_LookupSpecial()
  21. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  22. #include "pycore_signal.h" // Py_NSIG
  23. #ifdef MS_WINDOWS
  24. # include <windows.h>
  25. # if !defined(MS_WINDOWS_GAMES) || defined(MS_WINDOWS_DESKTOP)
  26. # include <pathcch.h>
  27. # endif
  28. # include <winioctl.h>
  29. # include <lmcons.h> // UNLEN
  30. # include "osdefs.h" // SEP
  31. # include <aclapi.h> // SetEntriesInAcl
  32. # include <sddl.h> // SDDL_REVISION_1
  33. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  34. # define HAVE_SYMLINK
  35. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_SYSTEM */
  36. #endif
  37. #include "structmember.h" // PyMemberDef
  38. #ifndef MS_WINDOWS
  39. # include "posixmodule.h"
  40. #else
  41. # include "pycore_fileutils_windows.h"
  42. # include "winreparse.h"
  43. #endif
  44. #if !defined(EX_OK) && defined(EXIT_SUCCESS)
  45. # define EX_OK EXIT_SUCCESS
  46. #endif
  47. /* On android API level 21, 'AT_EACCESS' is not declared although
  48. * HAVE_FACCESSAT is defined. */
  49. #ifdef __ANDROID__
  50. # undef HAVE_FACCESSAT
  51. #endif
  52. #include <stdio.h> // ctermid()
  53. #include <stdlib.h> // system()
  54. /*
  55. * A number of APIs are available on macOS from a certain macOS version.
  56. * To support building with a new SDK while deploying to older versions
  57. * the availability test is split into two:
  58. * - HAVE_<FUNCTION>: The configure check for compile time availability
  59. * - HAVE_<FUNCTION>_RUNTIME: Runtime check for availability
  60. *
  61. * The latter is always true when not on macOS, or when using a compiler
  62. * that does not support __has_builtin (older versions of Xcode).
  63. *
  64. * Due to compiler restrictions there is one valid use of HAVE_<FUNCTION>_RUNTIME:
  65. * if (HAVE_<FUNCTION>_RUNTIME) { ... }
  66. *
  67. * In mixing the test with other tests or using negations will result in compile
  68. * errors.
  69. */
  70. #if defined(__APPLE__)
  71. #include <mach/mach.h>
  72. #if defined(__has_builtin)
  73. #if __has_builtin(__builtin_available)
  74. #define HAVE_BUILTIN_AVAILABLE 1
  75. #endif
  76. #endif
  77. #ifdef HAVE_BUILTIN_AVAILABLE
  78. # define HAVE_FSTATAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  79. # define HAVE_FACCESSAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  80. # define HAVE_FCHMODAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  81. # define HAVE_FCHOWNAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  82. # define HAVE_LINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  83. # define HAVE_FDOPENDIR_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  84. # define HAVE_MKDIRAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  85. # define HAVE_RENAMEAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  86. # define HAVE_UNLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  87. # define HAVE_OPENAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  88. # define HAVE_READLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  89. # define HAVE_SYMLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  90. # define HAVE_FUTIMENS_RUNTIME __builtin_available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  91. # define HAVE_UTIMENSAT_RUNTIME __builtin_available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  92. # define HAVE_PWRITEV_RUNTIME __builtin_available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
  93. # define HAVE_MKFIFOAT_RUNTIME __builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
  94. # define HAVE_MKNODAT_RUNTIME __builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
  95. # define HAVE_POSIX_SPAWN_SETSID_RUNTIME __builtin_available(macOS 10.15, *)
  96. #else /* Xcode 8 or earlier */
  97. /* __builtin_available is not present in these compilers, but
  98. * some of the symbols might be weak linked (10.10 SDK or later
  99. * deploying on 10.9.
  100. *
  101. * Fall back to the older style of availability checking for
  102. * symbols introduced in macOS 10.10.
  103. */
  104. # ifdef HAVE_FSTATAT
  105. # define HAVE_FSTATAT_RUNTIME (fstatat != NULL)
  106. # endif
  107. # ifdef HAVE_FACCESSAT
  108. # define HAVE_FACCESSAT_RUNTIME (faccessat != NULL)
  109. # endif
  110. # ifdef HAVE_FCHMODAT
  111. # define HAVE_FCHMODAT_RUNTIME (fchmodat != NULL)
  112. # endif
  113. # ifdef HAVE_FCHOWNAT
  114. # define HAVE_FCHOWNAT_RUNTIME (fchownat != NULL)
  115. # endif
  116. # ifdef HAVE_LINKAT
  117. # define HAVE_LINKAT_RUNTIME (linkat != NULL)
  118. # endif
  119. # ifdef HAVE_FDOPENDIR
  120. # define HAVE_FDOPENDIR_RUNTIME (fdopendir != NULL)
  121. # endif
  122. # ifdef HAVE_MKDIRAT
  123. # define HAVE_MKDIRAT_RUNTIME (mkdirat != NULL)
  124. # endif
  125. # ifdef HAVE_RENAMEAT
  126. # define HAVE_RENAMEAT_RUNTIME (renameat != NULL)
  127. # endif
  128. # ifdef HAVE_UNLINKAT
  129. # define HAVE_UNLINKAT_RUNTIME (unlinkat != NULL)
  130. # endif
  131. # ifdef HAVE_OPENAT
  132. # define HAVE_OPENAT_RUNTIME (openat != NULL)
  133. # endif
  134. # ifdef HAVE_READLINKAT
  135. # define HAVE_READLINKAT_RUNTIME (readlinkat != NULL)
  136. # endif
  137. # ifdef HAVE_SYMLINKAT
  138. # define HAVE_SYMLINKAT_RUNTIME (symlinkat != NULL)
  139. # endif
  140. # ifdef HAVE_UTIMENSAT
  141. # define HAVE_UTIMENSAT_RUNTIME (utimensat != NULL)
  142. # endif
  143. # ifdef HAVE_FUTIMENS
  144. # define HAVE_FUTIMENS_RUNTIME (futimens != NULL)
  145. # endif
  146. # ifdef HAVE_PWRITEV
  147. # define HAVE_PWRITEV_RUNTIME (pwritev != NULL)
  148. # endif
  149. # ifdef HAVE_MKFIFOAT
  150. # define HAVE_MKFIFOAT_RUNTIME (mkfifoat != NULL)
  151. # endif
  152. # ifdef HAVE_MKNODAT
  153. # define HAVE_MKNODAT_RUNTIME (mknodat != NULL)
  154. # endif
  155. #endif
  156. #ifdef HAVE_FUTIMESAT
  157. /* Some of the logic for weak linking depends on this assertion */
  158. # error "HAVE_FUTIMESAT unexpectedly defined"
  159. #endif
  160. #else
  161. # define HAVE_FSTATAT_RUNTIME 1
  162. # define HAVE_FACCESSAT_RUNTIME 1
  163. # define HAVE_FCHMODAT_RUNTIME 1
  164. # define HAVE_FCHOWNAT_RUNTIME 1
  165. # define HAVE_LINKAT_RUNTIME 1
  166. # define HAVE_FDOPENDIR_RUNTIME 1
  167. # define HAVE_MKDIRAT_RUNTIME 1
  168. # define HAVE_RENAMEAT_RUNTIME 1
  169. # define HAVE_UNLINKAT_RUNTIME 1
  170. # define HAVE_OPENAT_RUNTIME 1
  171. # define HAVE_READLINKAT_RUNTIME 1
  172. # define HAVE_SYMLINKAT_RUNTIME 1
  173. # define HAVE_FUTIMENS_RUNTIME 1
  174. # define HAVE_UTIMENSAT_RUNTIME 1
  175. # define HAVE_PWRITEV_RUNTIME 1
  176. # define HAVE_MKFIFOAT_RUNTIME 1
  177. # define HAVE_MKNODAT_RUNTIME 1
  178. #endif
  179. #ifdef __cplusplus
  180. extern "C" {
  181. #endif
  182. PyDoc_STRVAR(posix__doc__,
  183. "This module provides access to operating system functionality that is\n\
  184. standardized by the C Standard and the POSIX standard (a thinly\n\
  185. disguised Unix interface). Refer to the library manual and\n\
  186. corresponding Unix manual entries for more information on calls.");
  187. #ifdef HAVE_SYS_UIO_H
  188. # include <sys/uio.h>
  189. #endif
  190. #ifdef HAVE_SYS_TYPES_H
  191. /* Should be included before <sys/sysmacros.h> on HP-UX v3 */
  192. # include <sys/types.h>
  193. #endif /* HAVE_SYS_TYPES_H */
  194. #ifdef HAVE_SYS_SYSMACROS_H
  195. /* GNU C Library: major(), minor(), makedev() */
  196. # include <sys/sysmacros.h>
  197. #endif
  198. #ifdef HAVE_SYS_STAT_H
  199. # include <sys/stat.h>
  200. #endif /* HAVE_SYS_STAT_H */
  201. #ifdef HAVE_SYS_WAIT_H
  202. # include <sys/wait.h> // WNOHANG
  203. #endif
  204. #ifdef HAVE_LINUX_WAIT_H
  205. # include <linux/wait.h> // P_PIDFD
  206. #endif
  207. #ifdef HAVE_SIGNAL_H
  208. # include <signal.h>
  209. #endif
  210. #ifdef HAVE_FCNTL_H
  211. # include <fcntl.h>
  212. #endif
  213. #ifdef HAVE_GRP_H
  214. # include <grp.h>
  215. #endif
  216. #ifdef HAVE_SYSEXITS_H
  217. # include <sysexits.h>
  218. #endif
  219. #ifdef HAVE_SYS_LOADAVG_H
  220. # include <sys/loadavg.h>
  221. #endif
  222. #ifdef HAVE_SYS_SENDFILE_H
  223. # include <sys/sendfile.h>
  224. #endif
  225. #if defined(__APPLE__)
  226. # include <copyfile.h>
  227. #endif
  228. #ifdef HAVE_SCHED_H
  229. # include <sched.h>
  230. #endif
  231. #ifdef HAVE_COPY_FILE_RANGE
  232. # include <unistd.h>
  233. #endif
  234. #if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
  235. # undef HAVE_SCHED_SETAFFINITY
  236. #endif
  237. #if defined(HAVE_SYS_XATTR_H) && defined(HAVE_LINUX_LIMITS_H) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
  238. # define USE_XATTRS
  239. # include <linux/limits.h> // Needed for XATTR_SIZE_MAX on musl libc.
  240. #endif
  241. #ifdef USE_XATTRS
  242. # include <sys/xattr.h>
  243. #endif
  244. #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
  245. # ifdef HAVE_SYS_SOCKET_H
  246. # include <sys/socket.h>
  247. # endif
  248. #endif
  249. #ifdef HAVE_DLFCN_H
  250. # include <dlfcn.h>
  251. #endif
  252. #ifdef __hpux
  253. # include <sys/mpctl.h>
  254. #endif
  255. #if defined(__DragonFly__) || \
  256. defined(__OpenBSD__) || \
  257. defined(__FreeBSD__) || \
  258. defined(__NetBSD__) || \
  259. defined(__APPLE__)
  260. # include <sys/sysctl.h>
  261. #endif
  262. #ifdef HAVE_LINUX_RANDOM_H
  263. # include <linux/random.h>
  264. #endif
  265. #ifdef HAVE_GETRANDOM_SYSCALL
  266. # include <sys/syscall.h>
  267. # include <sys/random.h>
  268. #endif
  269. #ifdef HAVE_WINDOWS_CONSOLE_IO
  270. # define TERMSIZE_USE_CONIO
  271. #elif defined(HAVE_SYS_IOCTL_H)
  272. # include <sys/ioctl.h>
  273. # if defined(HAVE_TERMIOS_H)
  274. # include <termios.h>
  275. # endif
  276. # if defined(TIOCGWINSZ)
  277. # define TERMSIZE_USE_IOCTL
  278. # endif
  279. #endif /* HAVE_WINDOWS_CONSOLE_IO */
  280. /* Various compilers have only certain posix functions */
  281. /* XXX Gosh I wish these were all moved into pyconfig.h */
  282. #if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
  283. # define HAVE_OPENDIR 1
  284. # define HAVE_SYSTEM 1
  285. # include <process.h>
  286. #elif defined( _MSC_VER)
  287. /* Microsoft compiler */
  288. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
  289. # define HAVE_GETPPID 1
  290. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_APP | MS_WINDOWS_SYSTEM */
  291. # if defined(MS_WINDOWS_DESKTOP)
  292. # define HAVE_GETLOGIN 1
  293. # endif /* MS_WINDOWS_DESKTOP */
  294. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  295. # define HAVE_SPAWNV 1
  296. # define HAVE_EXECV 1
  297. # define HAVE_WSPAWNV 1
  298. # define HAVE_WEXECV 1
  299. # define HAVE_SYSTEM 1
  300. # define HAVE_CWAIT 1
  301. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_SYSTEM */
  302. # define HAVE_PIPE 1
  303. # define HAVE_FSYNC 1
  304. # define fsync _commit
  305. #endif /* ! __WATCOMC__ || __QNX__ */
  306. /*[clinic input]
  307. # one of the few times we lie about this name!
  308. module os
  309. [clinic start generated code]*/
  310. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
  311. #ifndef _MSC_VER
  312. #if defined(__sgi)&&_COMPILER_VERSION>=700
  313. /* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
  314. (default) */
  315. extern char *ctermid_r(char *);
  316. #endif
  317. #endif /* !_MSC_VER */
  318. #if defined(__VXWORKS__)
  319. # error #include <vxCpuLib.h>
  320. # error #include <rtpLib.h>
  321. # include <wait.h>
  322. # error #include <taskLib.h>
  323. # ifndef _P_WAIT
  324. # define _P_WAIT 0
  325. # define _P_NOWAIT 1
  326. # define _P_NOWAITO 1
  327. # endif
  328. #endif /* __VXWORKS__ */
  329. #ifdef HAVE_POSIX_SPAWN
  330. # include <spawn.h>
  331. #endif
  332. #ifdef HAVE_UTIME_H
  333. # include <utime.h>
  334. #endif /* HAVE_UTIME_H */
  335. #ifdef HAVE_SYS_UTIME_H
  336. # include <sys/utime.h>
  337. # define HAVE_UTIME_H /* pretend we do for the rest of this file */
  338. #endif /* HAVE_SYS_UTIME_H */
  339. #ifdef HAVE_SYS_TIMES_H
  340. # include <sys/times.h>
  341. #endif /* HAVE_SYS_TIMES_H */
  342. #ifdef HAVE_SYS_PARAM_H
  343. # include <sys/param.h>
  344. #endif /* HAVE_SYS_PARAM_H */
  345. #ifdef HAVE_SYS_UTSNAME_H
  346. # include <sys/utsname.h>
  347. #endif /* HAVE_SYS_UTSNAME_H */
  348. #ifdef HAVE_DIRENT_H
  349. # include <dirent.h>
  350. # define NAMLEN(dirent) strlen((dirent)->d_name)
  351. #else
  352. # if defined(__WATCOMC__) && !defined(__QNX__)
  353. # include <direct.h>
  354. # define NAMLEN(dirent) strlen((dirent)->d_name)
  355. # else
  356. # define dirent direct
  357. # define NAMLEN(dirent) (dirent)->d_namlen
  358. # endif
  359. # ifdef HAVE_SYS_NDIR_H
  360. # include <sys/ndir.h>
  361. # endif
  362. # ifdef HAVE_SYS_DIR_H
  363. # include <sys/dir.h>
  364. # endif
  365. # ifdef HAVE_NDIR_H
  366. # include <ndir.h>
  367. # endif
  368. #endif
  369. #ifdef _MSC_VER
  370. # ifdef HAVE_DIRECT_H
  371. # include <direct.h>
  372. # endif
  373. # ifdef HAVE_IO_H
  374. # include <io.h>
  375. # endif
  376. # ifdef HAVE_PROCESS_H
  377. # include <process.h>
  378. # endif
  379. # include <malloc.h>
  380. #endif /* _MSC_VER */
  381. #ifndef MAXPATHLEN
  382. # if defined(PATH_MAX) && PATH_MAX > 1024
  383. # define MAXPATHLEN PATH_MAX
  384. # else
  385. # define MAXPATHLEN 1024
  386. # endif
  387. #endif /* MAXPATHLEN */
  388. #ifdef UNION_WAIT
  389. /* Emulate some macros on systems that have a union instead of macros */
  390. # ifndef WIFEXITED
  391. # define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
  392. # endif
  393. # ifndef WEXITSTATUS
  394. # define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
  395. # endif
  396. # ifndef WTERMSIG
  397. # define WTERMSIG(u_wait) ((u_wait).w_termsig)
  398. # endif
  399. # define WAIT_TYPE union wait
  400. # define WAIT_STATUS_INT(s) (s.w_status)
  401. #else
  402. /* !UNION_WAIT */
  403. # define WAIT_TYPE int
  404. # define WAIT_STATUS_INT(s) (s)
  405. #endif /* UNION_WAIT */
  406. /* Don't use the "_r" form if we don't need it (also, won't have a
  407. prototype for it, at least on Solaris -- maybe others as well?). */
  408. #if defined(HAVE_CTERMID_R)
  409. # define USE_CTERMID_R
  410. #endif
  411. /* choose the appropriate stat and fstat functions and return structs */
  412. #undef STAT
  413. #undef FSTAT
  414. #undef STRUCT_STAT
  415. #ifdef MS_WINDOWS
  416. # define STAT win32_stat
  417. # define LSTAT win32_lstat
  418. # define FSTAT _Py_fstat_noraise
  419. # define STRUCT_STAT struct _Py_stat_struct
  420. #else
  421. # define STAT stat
  422. # define LSTAT lstat
  423. # define FSTAT fstat
  424. # define STRUCT_STAT struct stat
  425. #endif
  426. #if defined(MAJOR_IN_MKDEV)
  427. # include <sys/mkdev.h>
  428. #else
  429. # if defined(MAJOR_IN_SYSMACROS)
  430. # include <sys/sysmacros.h>
  431. # endif
  432. # if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
  433. # include <sys/mkdev.h>
  434. # endif
  435. #endif
  436. #ifdef MS_WINDOWS
  437. # define INITFUNC PyInit_nt
  438. # define MODNAME "nt"
  439. # define MODNAME_OBJ &_Py_ID(nt)
  440. #else
  441. # define INITFUNC PyInit_posix
  442. # define MODNAME "posix"
  443. # define MODNAME_OBJ &_Py_ID(posix)
  444. #endif
  445. #if defined(__sun)
  446. /* Something to implement in autoconf, not present in autoconf 2.69 */
  447. # define HAVE_STRUCT_STAT_ST_FSTYPE 1
  448. #endif
  449. /* memfd_create is either defined in sys/mman.h or sys/memfd.h
  450. * linux/memfd.h defines additional flags
  451. */
  452. #ifdef HAVE_SYS_MMAN_H
  453. # include <sys/mman.h>
  454. #endif
  455. #ifdef HAVE_SYS_MEMFD_H
  456. # error #include <sys/memfd.h>
  457. #endif
  458. #ifdef HAVE_LINUX_MEMFD_H
  459. # include <linux/memfd.h>
  460. #endif
  461. /* eventfd() */
  462. #ifdef HAVE_SYS_EVENTFD_H
  463. # include <sys/eventfd.h>
  464. #endif
  465. #ifdef _Py_MEMORY_SANITIZER
  466. # include <sanitizer/msan_interface.h>
  467. #endif
  468. #ifdef HAVE_FORK
  469. static void
  470. run_at_forkers(PyObject *lst, int reverse)
  471. {
  472. Py_ssize_t i;
  473. PyObject *cpy;
  474. if (lst != NULL) {
  475. assert(PyList_CheckExact(lst));
  476. /* Use a list copy in case register_at_fork() is called from
  477. * one of the callbacks.
  478. */
  479. cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
  480. if (cpy == NULL)
  481. PyErr_WriteUnraisable(lst);
  482. else {
  483. if (reverse)
  484. PyList_Reverse(cpy);
  485. for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
  486. PyObject *func, *res;
  487. func = PyList_GET_ITEM(cpy, i);
  488. res = _PyObject_CallNoArgs(func);
  489. if (res == NULL)
  490. PyErr_WriteUnraisable(func);
  491. else
  492. Py_DECREF(res);
  493. }
  494. Py_DECREF(cpy);
  495. }
  496. }
  497. }
  498. void
  499. PyOS_BeforeFork(void)
  500. {
  501. PyInterpreterState *interp = _PyInterpreterState_GET();
  502. run_at_forkers(interp->before_forkers, 1);
  503. _PyImport_AcquireLock(interp);
  504. }
  505. void
  506. PyOS_AfterFork_Parent(void)
  507. {
  508. PyInterpreterState *interp = _PyInterpreterState_GET();
  509. if (_PyImport_ReleaseLock(interp) <= 0) {
  510. Py_FatalError("failed releasing import lock after fork");
  511. }
  512. run_at_forkers(interp->after_forkers_parent, 0);
  513. }
  514. void
  515. PyOS_AfterFork_Child(void)
  516. {
  517. PyStatus status;
  518. _PyRuntimeState *runtime = &_PyRuntime;
  519. status = _PyRuntimeState_ReInitThreads(runtime);
  520. if (_PyStatus_EXCEPTION(status)) {
  521. goto fatal_error;
  522. }
  523. PyThreadState *tstate = _PyThreadState_GET();
  524. _Py_EnsureTstateNotNULL(tstate);
  525. #ifdef PY_HAVE_THREAD_NATIVE_ID
  526. tstate->native_thread_id = PyThread_get_thread_native_id();
  527. #endif
  528. status = _PyEval_ReInitThreads(tstate);
  529. if (_PyStatus_EXCEPTION(status)) {
  530. goto fatal_error;
  531. }
  532. status = _PyImport_ReInitLock(tstate->interp);
  533. if (_PyStatus_EXCEPTION(status)) {
  534. goto fatal_error;
  535. }
  536. _PySignal_AfterFork();
  537. status = _PyInterpreterState_DeleteExceptMain(runtime);
  538. if (_PyStatus_EXCEPTION(status)) {
  539. goto fatal_error;
  540. }
  541. assert(_PyThreadState_GET() == tstate);
  542. status = _PyPerfTrampoline_AfterFork_Child();
  543. if (_PyStatus_EXCEPTION(status)) {
  544. goto fatal_error;
  545. }
  546. run_at_forkers(tstate->interp->after_forkers_child, 0);
  547. return;
  548. fatal_error:
  549. Py_ExitStatusException(status);
  550. }
  551. static int
  552. register_at_forker(PyObject **lst, PyObject *func)
  553. {
  554. if (func == NULL) /* nothing to register? do nothing. */
  555. return 0;
  556. if (*lst == NULL) {
  557. *lst = PyList_New(0);
  558. if (*lst == NULL)
  559. return -1;
  560. }
  561. return PyList_Append(*lst, func);
  562. }
  563. #endif /* HAVE_FORK */
  564. /* Legacy wrapper */
  565. void
  566. PyOS_AfterFork(void)
  567. {
  568. #ifdef HAVE_FORK
  569. PyOS_AfterFork_Child();
  570. #endif
  571. }
  572. #ifdef MS_WINDOWS
  573. /* defined in fileutils.c */
  574. void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
  575. void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *, ULONG,
  576. FILE_BASIC_INFO *, FILE_ID_INFO *,
  577. struct _Py_stat_struct *);
  578. void _Py_stat_basic_info_to_stat(FILE_STAT_BASIC_INFORMATION *,
  579. struct _Py_stat_struct *);
  580. #endif
  581. #ifndef MS_WINDOWS
  582. PyObject *
  583. _PyLong_FromUid(uid_t uid)
  584. {
  585. if (uid == (uid_t)-1)
  586. return PyLong_FromLong(-1);
  587. return PyLong_FromUnsignedLong(uid);
  588. }
  589. PyObject *
  590. _PyLong_FromGid(gid_t gid)
  591. {
  592. if (gid == (gid_t)-1)
  593. return PyLong_FromLong(-1);
  594. return PyLong_FromUnsignedLong(gid);
  595. }
  596. int
  597. _Py_Uid_Converter(PyObject *obj, uid_t *p)
  598. {
  599. uid_t uid;
  600. PyObject *index;
  601. int overflow;
  602. long result;
  603. unsigned long uresult;
  604. index = _PyNumber_Index(obj);
  605. if (index == NULL) {
  606. PyErr_Format(PyExc_TypeError,
  607. "uid should be integer, not %.200s",
  608. _PyType_Name(Py_TYPE(obj)));
  609. return 0;
  610. }
  611. /*
  612. * Handling uid_t is complicated for two reasons:
  613. * * Although uid_t is (always?) unsigned, it still
  614. * accepts -1.
  615. * * We don't know its size in advance--it may be
  616. * bigger than an int, or it may be smaller than
  617. * a long.
  618. *
  619. * So a bit of defensive programming is in order.
  620. * Start with interpreting the value passed
  621. * in as a signed long and see if it works.
  622. */
  623. result = PyLong_AsLongAndOverflow(index, &overflow);
  624. if (!overflow) {
  625. uid = (uid_t)result;
  626. if (result == -1) {
  627. if (PyErr_Occurred())
  628. goto fail;
  629. /* It's a legitimate -1, we're done. */
  630. goto success;
  631. }
  632. /* Any other negative number is disallowed. */
  633. if (result < 0)
  634. goto underflow;
  635. /* Ensure the value wasn't truncated. */
  636. if (sizeof(uid_t) < sizeof(long) &&
  637. (long)uid != result)
  638. goto underflow;
  639. goto success;
  640. }
  641. if (overflow < 0)
  642. goto underflow;
  643. /*
  644. * Okay, the value overflowed a signed long. If it
  645. * fits in an *unsigned* long, it may still be okay,
  646. * as uid_t may be unsigned long on this platform.
  647. */
  648. uresult = PyLong_AsUnsignedLong(index);
  649. if (PyErr_Occurred()) {
  650. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  651. goto overflow;
  652. goto fail;
  653. }
  654. uid = (uid_t)uresult;
  655. /*
  656. * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
  657. * but this value would get interpreted as (uid_t)-1 by chown
  658. * and its siblings. That's not what the user meant! So we
  659. * throw an overflow exception instead. (We already
  660. * handled a real -1 with PyLong_AsLongAndOverflow() above.)
  661. */
  662. if (uid == (uid_t)-1)
  663. goto overflow;
  664. /* Ensure the value wasn't truncated. */
  665. if (sizeof(uid_t) < sizeof(long) &&
  666. (unsigned long)uid != uresult)
  667. goto overflow;
  668. /* fallthrough */
  669. success:
  670. Py_DECREF(index);
  671. *p = uid;
  672. return 1;
  673. underflow:
  674. PyErr_SetString(PyExc_OverflowError,
  675. "uid is less than minimum");
  676. goto fail;
  677. overflow:
  678. PyErr_SetString(PyExc_OverflowError,
  679. "uid is greater than maximum");
  680. /* fallthrough */
  681. fail:
  682. Py_DECREF(index);
  683. return 0;
  684. }
  685. int
  686. _Py_Gid_Converter(PyObject *obj, gid_t *p)
  687. {
  688. gid_t gid;
  689. PyObject *index;
  690. int overflow;
  691. long result;
  692. unsigned long uresult;
  693. index = _PyNumber_Index(obj);
  694. if (index == NULL) {
  695. PyErr_Format(PyExc_TypeError,
  696. "gid should be integer, not %.200s",
  697. _PyType_Name(Py_TYPE(obj)));
  698. return 0;
  699. }
  700. /*
  701. * Handling gid_t is complicated for two reasons:
  702. * * Although gid_t is (always?) unsigned, it still
  703. * accepts -1.
  704. * * We don't know its size in advance--it may be
  705. * bigger than an int, or it may be smaller than
  706. * a long.
  707. *
  708. * So a bit of defensive programming is in order.
  709. * Start with interpreting the value passed
  710. * in as a signed long and see if it works.
  711. */
  712. result = PyLong_AsLongAndOverflow(index, &overflow);
  713. if (!overflow) {
  714. gid = (gid_t)result;
  715. if (result == -1) {
  716. if (PyErr_Occurred())
  717. goto fail;
  718. /* It's a legitimate -1, we're done. */
  719. goto success;
  720. }
  721. /* Any other negative number is disallowed. */
  722. if (result < 0) {
  723. goto underflow;
  724. }
  725. /* Ensure the value wasn't truncated. */
  726. if (sizeof(gid_t) < sizeof(long) &&
  727. (long)gid != result)
  728. goto underflow;
  729. goto success;
  730. }
  731. if (overflow < 0)
  732. goto underflow;
  733. /*
  734. * Okay, the value overflowed a signed long. If it
  735. * fits in an *unsigned* long, it may still be okay,
  736. * as gid_t may be unsigned long on this platform.
  737. */
  738. uresult = PyLong_AsUnsignedLong(index);
  739. if (PyErr_Occurred()) {
  740. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  741. goto overflow;
  742. goto fail;
  743. }
  744. gid = (gid_t)uresult;
  745. /*
  746. * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
  747. * but this value would get interpreted as (gid_t)-1 by chown
  748. * and its siblings. That's not what the user meant! So we
  749. * throw an overflow exception instead. (We already
  750. * handled a real -1 with PyLong_AsLongAndOverflow() above.)
  751. */
  752. if (gid == (gid_t)-1)
  753. goto overflow;
  754. /* Ensure the value wasn't truncated. */
  755. if (sizeof(gid_t) < sizeof(long) &&
  756. (unsigned long)gid != uresult)
  757. goto overflow;
  758. /* fallthrough */
  759. success:
  760. Py_DECREF(index);
  761. *p = gid;
  762. return 1;
  763. underflow:
  764. PyErr_SetString(PyExc_OverflowError,
  765. "gid is less than minimum");
  766. goto fail;
  767. overflow:
  768. PyErr_SetString(PyExc_OverflowError,
  769. "gid is greater than maximum");
  770. /* fallthrough */
  771. fail:
  772. Py_DECREF(index);
  773. return 0;
  774. }
  775. #endif /* MS_WINDOWS */
  776. static PyObject *
  777. _PyLong_FromDev(dev_t dev)
  778. {
  779. #ifdef NODEV
  780. if (dev == NODEV) {
  781. return PyLong_FromLongLong((long long)dev);
  782. }
  783. #endif
  784. return PyLong_FromUnsignedLongLong((unsigned long long)dev);
  785. }
  786. #if (defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)) || defined(HAVE_DEVICE_MACROS)
  787. static int
  788. _Py_Dev_Converter(PyObject *obj, void *p)
  789. {
  790. #ifdef NODEV
  791. if (PyLong_Check(obj) && _PyLong_IsNegative((PyLongObject *)obj)) {
  792. int overflow;
  793. long long result = PyLong_AsLongLongAndOverflow(obj, &overflow);
  794. if (result == -1 && PyErr_Occurred()) {
  795. return 0;
  796. }
  797. if (!overflow && result == (long long)NODEV) {
  798. *((dev_t *)p) = NODEV;
  799. return 1;
  800. }
  801. }
  802. #endif
  803. unsigned long long result = PyLong_AsUnsignedLongLong(obj);
  804. if (result == (unsigned long long)-1 && PyErr_Occurred()) {
  805. return 0;
  806. }
  807. if ((unsigned long long)(dev_t)result != result) {
  808. PyErr_SetString(PyExc_OverflowError,
  809. "Python int too large to convert to C dev_t");
  810. return 0;
  811. }
  812. *((dev_t *)p) = (dev_t)result;
  813. return 1;
  814. }
  815. #endif /* (HAVE_MKNOD && HAVE_MAKEDEV) || HAVE_DEVICE_MACROS */
  816. #ifdef AT_FDCWD
  817. /*
  818. * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
  819. * without the int cast, the value gets interpreted as uint (4291925331),
  820. * which doesn't play nicely with all the initializer lines in this file that
  821. * look like this:
  822. * int dir_fd = DEFAULT_DIR_FD;
  823. */
  824. #define DEFAULT_DIR_FD (int)AT_FDCWD
  825. #else
  826. #define DEFAULT_DIR_FD (-100)
  827. #endif
  828. static int
  829. _fd_converter(PyObject *o, int *p)
  830. {
  831. int overflow;
  832. long long_value;
  833. PyObject *index = _PyNumber_Index(o);
  834. if (index == NULL) {
  835. return 0;
  836. }
  837. assert(PyLong_Check(index));
  838. long_value = PyLong_AsLongAndOverflow(index, &overflow);
  839. Py_DECREF(index);
  840. assert(!PyErr_Occurred());
  841. if (overflow > 0 || long_value > INT_MAX) {
  842. PyErr_SetString(PyExc_OverflowError,
  843. "fd is greater than maximum");
  844. return 0;
  845. }
  846. if (overflow < 0 || long_value < INT_MIN) {
  847. PyErr_SetString(PyExc_OverflowError,
  848. "fd is less than minimum");
  849. return 0;
  850. }
  851. *p = (int)long_value;
  852. return 1;
  853. }
  854. static int
  855. dir_fd_converter(PyObject *o, void *p)
  856. {
  857. if (o == Py_None) {
  858. *(int *)p = DEFAULT_DIR_FD;
  859. return 1;
  860. }
  861. else if (PyIndex_Check(o)) {
  862. return _fd_converter(o, (int *)p);
  863. }
  864. else {
  865. PyErr_Format(PyExc_TypeError,
  866. "argument should be integer or None, not %.200s",
  867. _PyType_Name(Py_TYPE(o)));
  868. return 0;
  869. }
  870. }
  871. typedef struct {
  872. PyObject *billion;
  873. PyObject *DirEntryType;
  874. PyObject *ScandirIteratorType;
  875. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  876. PyObject *SchedParamType;
  877. #endif
  878. newfunc statresult_new_orig;
  879. PyObject *StatResultType;
  880. PyObject *StatVFSResultType;
  881. PyObject *TerminalSizeType;
  882. PyObject *TimesResultType;
  883. PyObject *UnameResultType;
  884. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  885. PyObject *WaitidResultType;
  886. #endif
  887. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  888. PyObject *struct_rusage;
  889. #endif
  890. PyObject *st_mode;
  891. } _posixstate;
  892. static inline _posixstate*
  893. get_posix_state(PyObject *module)
  894. {
  895. void *state = _PyModule_GetState(module);
  896. assert(state != NULL);
  897. return (_posixstate *)state;
  898. }
  899. /*
  900. * A PyArg_ParseTuple "converter" function
  901. * that handles filesystem paths in the manner
  902. * preferred by the os module.
  903. *
  904. * path_converter accepts (Unicode) strings and their
  905. * subclasses, and bytes and their subclasses. What
  906. * it does with the argument depends on path.make_wide:
  907. *
  908. * * If path.make_wide is nonzero, if we get a (Unicode)
  909. * string we extract the wchar_t * and return it; if we
  910. * get bytes we decode to wchar_t * and return that.
  911. *
  912. * * If path.make_wide is zero, if we get bytes we extract
  913. * the char_t * and return it; if we get a (Unicode)
  914. * string we encode to char_t * and return that.
  915. *
  916. * path_converter also optionally accepts signed
  917. * integers (representing open file descriptors) instead
  918. * of path strings.
  919. *
  920. * Input fields:
  921. * path.nullable
  922. * If nonzero, the path is permitted to be None.
  923. * path.nonstrict
  924. * If nonzero, the path is permitted to contain
  925. * embedded null characters and have any length.
  926. * path.make_wide
  927. * If nonzero, the converter always uses wide, decoding if necessary, else
  928. * it always uses narrow, encoding if necessary. The default value is
  929. * nonzero on Windows, else zero.
  930. * path.suppress_value_error
  931. * If nonzero, raising ValueError is suppressed.
  932. * path.allow_fd
  933. * If nonzero, the path is permitted to be a file handle
  934. * (a signed int) instead of a string.
  935. * path.function_name
  936. * If non-NULL, path_converter will use that as the name
  937. * of the function in error messages.
  938. * (If path.function_name is NULL it omits the function name.)
  939. * path.argument_name
  940. * If non-NULL, path_converter will use that as the name
  941. * of the parameter in error messages.
  942. * (If path.argument_name is NULL it uses "path".)
  943. *
  944. * Output fields:
  945. * path.wide
  946. * Points to the path if it was expressed as Unicode
  947. * or if it was bytes and decoded to Unicode.
  948. * path.narrow
  949. * Points to the path if it was expressed as bytes,
  950. * or if it was Unicode and encoded to bytes.
  951. * path.fd
  952. * Contains a file descriptor if path.accept_fd was true
  953. * and the caller provided a signed integer instead of any
  954. * sort of string.
  955. *
  956. * WARNING: if your "path" parameter is optional, and is
  957. * unspecified, path_converter will never get called.
  958. * So if you set allow_fd, you *MUST* initialize path.fd = -1
  959. * yourself!
  960. * path.value_error
  961. * If nonzero, then suppress_value_error was specified and a ValueError
  962. * occurred.
  963. * path.length
  964. * The length of the path in characters, if specified as
  965. * a string.
  966. * path.object
  967. * The original object passed in (if get a PathLike object,
  968. * the result of PyOS_FSPath() is treated as the original object).
  969. * Own a reference to the object.
  970. * path.cleanup
  971. * For internal use only. May point to a temporary object.
  972. * (Pay no attention to the man behind the curtain.)
  973. *
  974. * At most one of path.wide or path.narrow will be non-NULL.
  975. * If path was None and path.nullable was set,
  976. * or if path was an integer and path.allow_fd was set,
  977. * both path.wide and path.narrow will be NULL
  978. * and path.length will be 0.
  979. *
  980. * path_converter takes care to not write to the path_t
  981. * unless it's successful. However it must reset the
  982. * "cleanup" field each time it's called.
  983. *
  984. * Use as follows:
  985. * path_t path;
  986. * memset(&path, 0, sizeof(path));
  987. * PyArg_ParseTuple(args, "O&", path_converter, &path);
  988. * // ... use values from path ...
  989. * path_cleanup(&path);
  990. *
  991. * (Note that if PyArg_Parse fails you don't need to call
  992. * path_cleanup(). However it is safe to do so.)
  993. */
  994. typedef struct {
  995. // Input fields
  996. const char *function_name;
  997. const char *argument_name;
  998. int nullable;
  999. int nonstrict;
  1000. int make_wide;
  1001. int suppress_value_error;
  1002. int allow_fd;
  1003. // Output fields
  1004. const wchar_t *wide;
  1005. const char *narrow;
  1006. int fd;
  1007. int value_error;
  1008. Py_ssize_t length;
  1009. PyObject *object;
  1010. PyObject *cleanup;
  1011. } path_t;
  1012. #define PATH_T_INITIALIZE(function_name, argument_name, nullable, nonstrict, \
  1013. make_wide, suppress_value_error, allow_fd) \
  1014. {function_name, argument_name, nullable, nonstrict, make_wide, \
  1015. suppress_value_error, allow_fd, NULL, NULL, -1, 0, 0, NULL, NULL}
  1016. #ifdef MS_WINDOWS
  1017. #define PATH_T_INITIALIZE_P(function_name, argument_name, nullable, \
  1018. nonstrict, suppress_value_error, allow_fd) \
  1019. PATH_T_INITIALIZE(function_name, argument_name, nullable, nonstrict, 1, \
  1020. suppress_value_error, allow_fd)
  1021. #else
  1022. #define PATH_T_INITIALIZE_P(function_name, argument_name, nullable, \
  1023. nonstrict, suppress_value_error, allow_fd) \
  1024. PATH_T_INITIALIZE(function_name, argument_name, nullable, nonstrict, 0, \
  1025. suppress_value_error, allow_fd)
  1026. #endif
  1027. static void
  1028. path_cleanup(path_t *path)
  1029. {
  1030. wchar_t *wide = (wchar_t *)path->wide;
  1031. path->wide = NULL;
  1032. PyMem_Free(wide);
  1033. Py_CLEAR(path->object);
  1034. Py_CLEAR(path->cleanup);
  1035. }
  1036. static int
  1037. path_converter(PyObject *o, void *p)
  1038. {
  1039. path_t *path = (path_t *)p;
  1040. PyObject *bytes = NULL;
  1041. Py_ssize_t length = 0;
  1042. int is_index, is_bytes, is_unicode;
  1043. const char *narrow;
  1044. PyObject *wo = NULL;
  1045. wchar_t *wide = NULL;
  1046. #define FORMAT_EXCEPTION(exc, fmt) \
  1047. PyErr_Format(exc, "%s%s" fmt, \
  1048. path->function_name ? path->function_name : "", \
  1049. path->function_name ? ": " : "", \
  1050. path->argument_name ? path->argument_name : "path")
  1051. /* Py_CLEANUP_SUPPORTED support */
  1052. if (o == NULL) {
  1053. path_cleanup(path);
  1054. return 1;
  1055. }
  1056. /* Ensure it's always safe to call path_cleanup(). */
  1057. path->object = path->cleanup = NULL;
  1058. /* path->object owns a reference to the original object */
  1059. Py_INCREF(o);
  1060. if ((o == Py_None) && path->nullable) {
  1061. path->wide = NULL;
  1062. path->narrow = NULL;
  1063. path->fd = -1;
  1064. goto success_exit;
  1065. }
  1066. /* Only call this here so that we don't treat the return value of
  1067. os.fspath() as an fd or buffer. */
  1068. is_index = path->allow_fd && PyIndex_Check(o);
  1069. is_bytes = PyBytes_Check(o);
  1070. is_unicode = PyUnicode_Check(o);
  1071. if (!is_index && !is_unicode && !is_bytes) {
  1072. /* Inline PyOS_FSPath() for better error messages. */
  1073. PyObject *func, *res;
  1074. func = _PyObject_LookupSpecial(o, &_Py_ID(__fspath__));
  1075. if (NULL == func) {
  1076. goto error_format;
  1077. }
  1078. res = _PyObject_CallNoArgs(func);
  1079. Py_DECREF(func);
  1080. if (NULL == res) {
  1081. goto error_exit;
  1082. }
  1083. else if (PyUnicode_Check(res)) {
  1084. is_unicode = 1;
  1085. }
  1086. else if (PyBytes_Check(res)) {
  1087. is_bytes = 1;
  1088. }
  1089. else {
  1090. PyErr_Format(PyExc_TypeError,
  1091. "expected %.200s.__fspath__() to return str or bytes, "
  1092. "not %.200s", _PyType_Name(Py_TYPE(o)),
  1093. _PyType_Name(Py_TYPE(res)));
  1094. Py_DECREF(res);
  1095. goto error_exit;
  1096. }
  1097. /* still owns a reference to the original object */
  1098. Py_SETREF(o, res);
  1099. }
  1100. if (is_unicode) {
  1101. if (path->make_wide) {
  1102. wide = PyUnicode_AsWideCharString(o, &length);
  1103. if (!wide) {
  1104. goto error_exit;
  1105. }
  1106. #ifdef MS_WINDOWS
  1107. if (!path->nonstrict && length > 32767) {
  1108. FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
  1109. goto error_exit;
  1110. }
  1111. #endif
  1112. if (!path->nonstrict && wcslen(wide) != (size_t)length) {
  1113. FORMAT_EXCEPTION(PyExc_ValueError,
  1114. "embedded null character in %s");
  1115. goto error_exit;
  1116. }
  1117. path->wide = wide;
  1118. path->narrow = NULL;
  1119. path->fd = -1;
  1120. wide = NULL;
  1121. goto success_exit;
  1122. }
  1123. bytes = PyUnicode_EncodeFSDefault(o);
  1124. if (!bytes) {
  1125. goto error_exit;
  1126. }
  1127. }
  1128. else if (is_bytes) {
  1129. bytes = Py_NewRef(o);
  1130. }
  1131. else if (is_index) {
  1132. if (!_fd_converter(o, &path->fd)) {
  1133. goto error_exit;
  1134. }
  1135. path->wide = NULL;
  1136. path->narrow = NULL;
  1137. goto success_exit;
  1138. }
  1139. else {
  1140. error_format:
  1141. PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
  1142. path->function_name ? path->function_name : "",
  1143. path->function_name ? ": " : "",
  1144. path->argument_name ? path->argument_name : "path",
  1145. path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
  1146. "integer or None" :
  1147. path->allow_fd ? "string, bytes, os.PathLike or integer" :
  1148. path->nullable ? "string, bytes, os.PathLike or None" :
  1149. "string, bytes or os.PathLike",
  1150. _PyType_Name(Py_TYPE(o)));
  1151. goto error_exit;
  1152. }
  1153. length = PyBytes_GET_SIZE(bytes);
  1154. narrow = PyBytes_AS_STRING(bytes);
  1155. if (!path->nonstrict && strlen(narrow) != (size_t)length) {
  1156. FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
  1157. goto error_exit;
  1158. }
  1159. if (path->make_wide) {
  1160. wo = PyUnicode_DecodeFSDefaultAndSize(narrow, length);
  1161. if (!wo) {
  1162. goto error_exit;
  1163. }
  1164. wide = PyUnicode_AsWideCharString(wo, &length);
  1165. Py_DECREF(wo);
  1166. if (!wide) {
  1167. goto error_exit;
  1168. }
  1169. #ifdef MS_WINDOWS
  1170. if (!path->nonstrict && length > 32767) {
  1171. FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
  1172. goto error_exit;
  1173. }
  1174. #endif
  1175. if (!path->nonstrict && wcslen(wide) != (size_t)length) {
  1176. FORMAT_EXCEPTION(PyExc_ValueError,
  1177. "embedded null character in %s");
  1178. goto error_exit;
  1179. }
  1180. path->wide = wide;
  1181. path->narrow = NULL;
  1182. Py_DECREF(bytes);
  1183. wide = NULL;
  1184. }
  1185. else {
  1186. path->wide = NULL;
  1187. path->narrow = narrow;
  1188. if (bytes == o) {
  1189. /* Still a reference owned by path->object, don't have to
  1190. worry about path->narrow is used after free. */
  1191. Py_DECREF(bytes);
  1192. }
  1193. else {
  1194. path->cleanup = bytes;
  1195. }
  1196. }
  1197. path->fd = -1;
  1198. success_exit:
  1199. path->value_error = 0;
  1200. path->length = length;
  1201. path->object = o;
  1202. return Py_CLEANUP_SUPPORTED;
  1203. error_exit:
  1204. Py_XDECREF(o);
  1205. Py_XDECREF(bytes);
  1206. PyMem_Free(wide);
  1207. if (!path->suppress_value_error ||
  1208. !PyErr_ExceptionMatches(PyExc_ValueError))
  1209. {
  1210. return 0;
  1211. }
  1212. PyErr_Clear();
  1213. path->wide = NULL;
  1214. path->narrow = NULL;
  1215. path->fd = -1;
  1216. path->value_error = 1;
  1217. path->length = 0;
  1218. path->object = NULL;
  1219. return Py_CLEANUP_SUPPORTED;
  1220. }
  1221. static void
  1222. argument_unavailable_error(const char *function_name, const char *argument_name)
  1223. {
  1224. PyErr_Format(PyExc_NotImplementedError,
  1225. "%s%s%s unavailable on this platform",
  1226. (function_name != NULL) ? function_name : "",
  1227. (function_name != NULL) ? ": ": "",
  1228. argument_name);
  1229. }
  1230. static int
  1231. dir_fd_unavailable(PyObject *o, void *p)
  1232. {
  1233. int dir_fd;
  1234. if (!dir_fd_converter(o, &dir_fd))
  1235. return 0;
  1236. if (dir_fd != DEFAULT_DIR_FD) {
  1237. argument_unavailable_error(NULL, "dir_fd");
  1238. return 0;
  1239. }
  1240. *(int *)p = dir_fd;
  1241. return 1;
  1242. }
  1243. static int
  1244. fd_specified(const char *function_name, int fd)
  1245. {
  1246. if (fd == -1)
  1247. return 0;
  1248. argument_unavailable_error(function_name, "fd");
  1249. return 1;
  1250. }
  1251. static int
  1252. follow_symlinks_specified(const char *function_name, int follow_symlinks)
  1253. {
  1254. if (follow_symlinks)
  1255. return 0;
  1256. argument_unavailable_error(function_name, "follow_symlinks");
  1257. return 1;
  1258. }
  1259. static int
  1260. path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
  1261. {
  1262. if (!path->wide && (dir_fd != DEFAULT_DIR_FD) && !path->narrow) {
  1263. PyErr_Format(PyExc_ValueError,
  1264. "%s: can't specify dir_fd without matching path",
  1265. function_name);
  1266. return 1;
  1267. }
  1268. return 0;
  1269. }
  1270. static int
  1271. dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
  1272. {
  1273. if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
  1274. PyErr_Format(PyExc_ValueError,
  1275. "%s: can't specify both dir_fd and fd",
  1276. function_name);
  1277. return 1;
  1278. }
  1279. return 0;
  1280. }
  1281. static int
  1282. fd_and_follow_symlinks_invalid(const char *function_name, int fd,
  1283. int follow_symlinks)
  1284. {
  1285. if ((fd > 0) && (!follow_symlinks)) {
  1286. PyErr_Format(PyExc_ValueError,
  1287. "%s: cannot use fd and follow_symlinks together",
  1288. function_name);
  1289. return 1;
  1290. }
  1291. return 0;
  1292. }
  1293. static int
  1294. dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
  1295. int follow_symlinks)
  1296. {
  1297. if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
  1298. PyErr_Format(PyExc_ValueError,
  1299. "%s: cannot use dir_fd and follow_symlinks together",
  1300. function_name);
  1301. return 1;
  1302. }
  1303. return 0;
  1304. }
  1305. #ifdef MS_WINDOWS
  1306. typedef long long Py_off_t;
  1307. #else
  1308. typedef off_t Py_off_t;
  1309. #endif
  1310. static int
  1311. Py_off_t_converter(PyObject *arg, void *addr)
  1312. {
  1313. #ifdef HAVE_LARGEFILE_SUPPORT
  1314. *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
  1315. #else
  1316. *((Py_off_t *)addr) = PyLong_AsLong(arg);
  1317. #endif
  1318. if (PyErr_Occurred())
  1319. return 0;
  1320. return 1;
  1321. }
  1322. static PyObject *
  1323. PyLong_FromPy_off_t(Py_off_t offset)
  1324. {
  1325. #ifdef HAVE_LARGEFILE_SUPPORT
  1326. return PyLong_FromLongLong(offset);
  1327. #else
  1328. return PyLong_FromLong(offset);
  1329. #endif
  1330. }
  1331. #ifdef HAVE_SIGSET_T
  1332. /* Convert an iterable of integers to a sigset.
  1333. Return 1 on success, return 0 and raise an exception on error. */
  1334. int
  1335. _Py_Sigset_Converter(PyObject *obj, void *addr)
  1336. {
  1337. sigset_t *mask = (sigset_t *)addr;
  1338. PyObject *iterator, *item;
  1339. long signum;
  1340. int overflow;
  1341. // The extra parens suppress the unreachable-code warning with clang on MacOS
  1342. if (sigemptyset(mask) < (0)) {
  1343. /* Probably only if mask == NULL. */
  1344. PyErr_SetFromErrno(PyExc_OSError);
  1345. return 0;
  1346. }
  1347. iterator = PyObject_GetIter(obj);
  1348. if (iterator == NULL) {
  1349. return 0;
  1350. }
  1351. while ((item = PyIter_Next(iterator)) != NULL) {
  1352. signum = PyLong_AsLongAndOverflow(item, &overflow);
  1353. Py_DECREF(item);
  1354. if (signum <= 0 || signum >= Py_NSIG) {
  1355. if (overflow || signum != -1 || !PyErr_Occurred()) {
  1356. PyErr_Format(PyExc_ValueError,
  1357. "signal number %ld out of range [1; %i]",
  1358. signum, Py_NSIG - 1);
  1359. }
  1360. goto error;
  1361. }
  1362. if (sigaddset(mask, (int)signum)) {
  1363. if (errno != EINVAL) {
  1364. /* Probably impossible */
  1365. PyErr_SetFromErrno(PyExc_OSError);
  1366. goto error;
  1367. }
  1368. /* For backwards compatibility, allow idioms such as
  1369. * `range(1, NSIG)` but warn about invalid signal numbers
  1370. */
  1371. const char msg[] =
  1372. "invalid signal number %ld, please use valid_signals()";
  1373. if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
  1374. goto error;
  1375. }
  1376. }
  1377. }
  1378. if (!PyErr_Occurred()) {
  1379. Py_DECREF(iterator);
  1380. return 1;
  1381. }
  1382. error:
  1383. Py_DECREF(iterator);
  1384. return 0;
  1385. }
  1386. #endif /* HAVE_SIGSET_T */
  1387. /* Return a dictionary corresponding to the POSIX environment table */
  1388. #if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
  1389. /* On Darwin/MacOSX a shared library or framework has no access to
  1390. ** environ directly, we must obtain it with _NSGetEnviron(). See also
  1391. ** man environ(7).
  1392. */
  1393. #include <crt_externs.h>
  1394. #elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
  1395. extern char **environ;
  1396. #endif /* !_MSC_VER */
  1397. static PyObject *
  1398. convertenviron(void)
  1399. {
  1400. PyObject *d;
  1401. #ifdef MS_WINDOWS
  1402. wchar_t **e;
  1403. #else
  1404. char **e;
  1405. #endif
  1406. d = PyDict_New();
  1407. if (d == NULL)
  1408. return NULL;
  1409. #ifdef MS_WINDOWS
  1410. /* _wenviron must be initialized in this way if the program is started
  1411. through main() instead of wmain(). */
  1412. (void)_wgetenv(L"");
  1413. e = _wenviron;
  1414. #elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
  1415. /* environ is not accessible as an extern in a shared object on OSX; use
  1416. _NSGetEnviron to resolve it. The value changes if you add environment
  1417. variables between calls to Py_Initialize, so don't cache the value. */
  1418. e = *_NSGetEnviron();
  1419. #else
  1420. e = environ;
  1421. #endif
  1422. if (e == NULL)
  1423. return d;
  1424. for (; *e != NULL; e++) {
  1425. PyObject *k;
  1426. PyObject *v;
  1427. #ifdef MS_WINDOWS
  1428. const wchar_t *p = wcschr(*e, L'=');
  1429. #else
  1430. const char *p = strchr(*e, '=');
  1431. #endif
  1432. if (p == NULL)
  1433. continue;
  1434. #ifdef MS_WINDOWS
  1435. k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
  1436. #else
  1437. k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
  1438. #endif
  1439. if (k == NULL) {
  1440. Py_DECREF(d);
  1441. return NULL;
  1442. }
  1443. #ifdef MS_WINDOWS
  1444. v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
  1445. #else
  1446. v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
  1447. #endif
  1448. if (v == NULL) {
  1449. Py_DECREF(k);
  1450. Py_DECREF(d);
  1451. return NULL;
  1452. }
  1453. if (PyDict_SetDefault(d, k, v) == NULL) {
  1454. Py_DECREF(v);
  1455. Py_DECREF(k);
  1456. Py_DECREF(d);
  1457. return NULL;
  1458. }
  1459. Py_DECREF(k);
  1460. Py_DECREF(v);
  1461. }
  1462. return d;
  1463. }
  1464. /* Set a POSIX-specific error from errno, and return NULL */
  1465. static PyObject *
  1466. posix_error(void)
  1467. {
  1468. return PyErr_SetFromErrno(PyExc_OSError);
  1469. }
  1470. #ifdef MS_WINDOWS
  1471. static PyObject *
  1472. win32_error(const char* function, const char* filename)
  1473. {
  1474. /* XXX We should pass the function name along in the future.
  1475. (winreg.c also wants to pass the function name.)
  1476. This would however require an additional param to the
  1477. Windows error object, which is non-trivial.
  1478. */
  1479. errno = GetLastError();
  1480. if (filename)
  1481. return PyErr_SetFromWindowsErrWithFilename(errno, filename);
  1482. else
  1483. return PyErr_SetFromWindowsErr(errno);
  1484. }
  1485. static PyObject *
  1486. win32_error_object_err(const char* function, PyObject* filename, DWORD err)
  1487. {
  1488. /* XXX - see win32_error for comments on 'function' */
  1489. if (filename)
  1490. return PyErr_SetExcFromWindowsErrWithFilenameObject(
  1491. PyExc_OSError,
  1492. err,
  1493. filename);
  1494. else
  1495. return PyErr_SetFromWindowsErr(err);
  1496. }
  1497. static PyObject *
  1498. win32_error_object(const char* function, PyObject* filename)
  1499. {
  1500. errno = GetLastError();
  1501. return win32_error_object_err(function, filename, errno);
  1502. }
  1503. #endif /* MS_WINDOWS */
  1504. static PyObject *
  1505. posix_path_object_error(PyObject *path)
  1506. {
  1507. return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
  1508. }
  1509. static PyObject *
  1510. path_object_error(PyObject *path)
  1511. {
  1512. #ifdef MS_WINDOWS
  1513. return PyErr_SetExcFromWindowsErrWithFilenameObject(
  1514. PyExc_OSError, 0, path);
  1515. #else
  1516. return posix_path_object_error(path);
  1517. #endif
  1518. }
  1519. static PyObject *
  1520. path_object_error2(PyObject *path, PyObject *path2)
  1521. {
  1522. #ifdef MS_WINDOWS
  1523. return PyErr_SetExcFromWindowsErrWithFilenameObjects(
  1524. PyExc_OSError, 0, path, path2);
  1525. #else
  1526. return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
  1527. #endif
  1528. }
  1529. static PyObject *
  1530. path_error(path_t *path)
  1531. {
  1532. return path_object_error(path->object);
  1533. }
  1534. static PyObject *
  1535. posix_path_error(path_t *path)
  1536. {
  1537. return posix_path_object_error(path->object);
  1538. }
  1539. static PyObject *
  1540. path_error2(path_t *path, path_t *path2)
  1541. {
  1542. return path_object_error2(path->object, path2->object);
  1543. }
  1544. /* POSIX generic methods */
  1545. static PyObject *
  1546. posix_fildes_fd(int fd, int (*func)(int))
  1547. {
  1548. int res;
  1549. int async_err = 0;
  1550. do {
  1551. Py_BEGIN_ALLOW_THREADS
  1552. _Py_BEGIN_SUPPRESS_IPH
  1553. res = (*func)(fd);
  1554. _Py_END_SUPPRESS_IPH
  1555. Py_END_ALLOW_THREADS
  1556. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1557. if (res != 0)
  1558. return (!async_err) ? posix_error() : NULL;
  1559. Py_RETURN_NONE;
  1560. }
  1561. #ifdef MS_WINDOWS
  1562. /* This is a reimplementation of the C library's chdir function,
  1563. but one that produces Win32 errors instead of DOS error codes.
  1564. chdir is essentially a wrapper around SetCurrentDirectory; however,
  1565. it also needs to set "magic" environment variables indicating
  1566. the per-drive current directory, which are of the form =<drive>: */
  1567. static BOOL __stdcall
  1568. win32_wchdir(LPCWSTR path)
  1569. {
  1570. wchar_t path_buf[MAX_PATH], *new_path = path_buf;
  1571. int result;
  1572. wchar_t env[4] = L"=x:";
  1573. if(!SetCurrentDirectoryW(path))
  1574. return FALSE;
  1575. result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
  1576. if (!result)
  1577. return FALSE;
  1578. if (result > Py_ARRAY_LENGTH(path_buf)) {
  1579. new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
  1580. if (!new_path) {
  1581. SetLastError(ERROR_OUTOFMEMORY);
  1582. return FALSE;
  1583. }
  1584. result = GetCurrentDirectoryW(result, new_path);
  1585. if (!result) {
  1586. PyMem_RawFree(new_path);
  1587. return FALSE;
  1588. }
  1589. }
  1590. int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
  1591. wcsncmp(new_path, L"//", 2) == 0);
  1592. if (!is_unc_like_path) {
  1593. env[1] = new_path[0];
  1594. result = SetEnvironmentVariableW(env, new_path);
  1595. }
  1596. if (new_path != path_buf)
  1597. PyMem_RawFree(new_path);
  1598. return result ? TRUE : FALSE;
  1599. }
  1600. #endif
  1601. #ifdef MS_WINDOWS
  1602. /* The CRT of Windows has a number of flaws wrt. its stat() implementation:
  1603. - time stamps are restricted to second resolution
  1604. - file modification times suffer from forth-and-back conversions between
  1605. UTC and local time
  1606. Therefore, we implement our own stat, based on the Win32 API directly.
  1607. */
  1608. #define HAVE_STAT_NSEC 1
  1609. #define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
  1610. #define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
  1611. static void
  1612. find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
  1613. BY_HANDLE_FILE_INFORMATION *info,
  1614. ULONG *reparse_tag)
  1615. {
  1616. memset(info, 0, sizeof(*info));
  1617. info->dwFileAttributes = pFileData->dwFileAttributes;
  1618. info->ftCreationTime = pFileData->ftCreationTime;
  1619. info->ftLastAccessTime = pFileData->ftLastAccessTime;
  1620. info->ftLastWriteTime = pFileData->ftLastWriteTime;
  1621. info->nFileSizeHigh = pFileData->nFileSizeHigh;
  1622. info->nFileSizeLow = pFileData->nFileSizeLow;
  1623. /* info->nNumberOfLinks = 1; */
  1624. if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
  1625. *reparse_tag = pFileData->dwReserved0;
  1626. else
  1627. *reparse_tag = 0;
  1628. }
  1629. static BOOL
  1630. attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
  1631. {
  1632. HANDLE hFindFile;
  1633. WIN32_FIND_DATAW FileData;
  1634. LPCWSTR filename = pszFile;
  1635. size_t n = wcslen(pszFile);
  1636. if (n && (pszFile[n - 1] == L'\\' || pszFile[n - 1] == L'/')) {
  1637. // cannot use PyMem_Malloc here because we do not hold the GIL
  1638. filename = (LPCWSTR)malloc((n + 1) * sizeof(filename[0]));
  1639. if(!filename) {
  1640. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1641. return FALSE;
  1642. }
  1643. wcsncpy_s((LPWSTR)filename, n + 1, pszFile, n);
  1644. while (--n > 0 && (filename[n] == L'\\' || filename[n] == L'/')) {
  1645. ((LPWSTR)filename)[n] = L'\0';
  1646. }
  1647. if (!n || (n == 1 && filename[1] == L':')) {
  1648. // Nothing left to query
  1649. free((void *)filename);
  1650. return FALSE;
  1651. }
  1652. }
  1653. hFindFile = FindFirstFileW(filename, &FileData);
  1654. if (pszFile != filename) {
  1655. free((void *)filename);
  1656. }
  1657. if (hFindFile == INVALID_HANDLE_VALUE) {
  1658. return FALSE;
  1659. }
  1660. FindClose(hFindFile);
  1661. find_data_to_file_info(&FileData, info, reparse_tag);
  1662. return TRUE;
  1663. }
  1664. static void
  1665. update_st_mode_from_path(const wchar_t *path, DWORD attr,
  1666. struct _Py_stat_struct *result)
  1667. {
  1668. if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) {
  1669. /* Fix the file execute permissions. This hack sets S_IEXEC if
  1670. the filename has an extension that is commonly used by files
  1671. that CreateProcessW can execute. A real implementation calls
  1672. GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
  1673. AccessCheck to check for generic read, write, and execute
  1674. access. */
  1675. const wchar_t *fileExtension = wcsrchr(path, '.');
  1676. if (fileExtension) {
  1677. if (_wcsicmp(fileExtension, L".exe") == 0 ||
  1678. _wcsicmp(fileExtension, L".bat") == 0 ||
  1679. _wcsicmp(fileExtension, L".cmd") == 0 ||
  1680. _wcsicmp(fileExtension, L".com") == 0) {
  1681. result->st_mode |= 0111;
  1682. }
  1683. }
  1684. }
  1685. }
  1686. static int
  1687. win32_xstat_slow_impl(const wchar_t *path, struct _Py_stat_struct *result,
  1688. BOOL traverse)
  1689. {
  1690. HANDLE hFile;
  1691. BY_HANDLE_FILE_INFORMATION fileInfo;
  1692. FILE_BASIC_INFO basicInfo;
  1693. FILE_BASIC_INFO *pBasicInfo = NULL;
  1694. FILE_ID_INFO idInfo;
  1695. FILE_ID_INFO *pIdInfo = NULL;
  1696. FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
  1697. DWORD fileType, error;
  1698. BOOL isUnhandledTag = FALSE;
  1699. int retval = 0;
  1700. DWORD access = FILE_READ_ATTRIBUTES;
  1701. DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
  1702. if (!traverse) {
  1703. flags |= FILE_FLAG_OPEN_REPARSE_POINT;
  1704. }
  1705. hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
  1706. if (hFile == INVALID_HANDLE_VALUE) {
  1707. /* Either the path doesn't exist, or the caller lacks access. */
  1708. error = GetLastError();
  1709. switch (error) {
  1710. case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
  1711. case ERROR_SHARING_VIOLATION: /* It's a paging file. */
  1712. /* Try reading the parent directory. */
  1713. if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
  1714. /* Cannot read the parent directory. */
  1715. switch (GetLastError()) {
  1716. case ERROR_FILE_NOT_FOUND: /* File cannot be found */
  1717. case ERROR_PATH_NOT_FOUND: /* File parent directory cannot be found */
  1718. case ERROR_NOT_READY: /* Drive exists but unavailable */
  1719. case ERROR_BAD_NET_NAME: /* Remote drive unavailable */
  1720. break;
  1721. /* Restore the error from CreateFileW(). */
  1722. default:
  1723. SetLastError(error);
  1724. }
  1725. return -1;
  1726. }
  1727. if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
  1728. if (traverse ||
  1729. !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
  1730. /* The stat call has to traverse but cannot, so fail. */
  1731. SetLastError(error);
  1732. return -1;
  1733. }
  1734. }
  1735. break;
  1736. case ERROR_INVALID_PARAMETER:
  1737. /* \\.\con requires read or write access. */
  1738. hFile = CreateFileW(path, access | GENERIC_READ,
  1739. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
  1740. OPEN_EXISTING, flags, NULL);
  1741. if (hFile == INVALID_HANDLE_VALUE) {
  1742. SetLastError(error);
  1743. return -1;
  1744. }
  1745. break;
  1746. case ERROR_CANT_ACCESS_FILE:
  1747. /* bpo37834: open unhandled reparse points if traverse fails. */
  1748. if (traverse) {
  1749. traverse = FALSE;
  1750. isUnhandledTag = TRUE;
  1751. hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
  1752. flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
  1753. }
  1754. if (hFile == INVALID_HANDLE_VALUE) {
  1755. SetLastError(error);
  1756. return -1;
  1757. }
  1758. break;
  1759. default:
  1760. return -1;
  1761. }
  1762. }
  1763. if (hFile != INVALID_HANDLE_VALUE) {
  1764. /* Handle types other than files on disk. */
  1765. fileType = GetFileType(hFile);
  1766. if (fileType != FILE_TYPE_DISK) {
  1767. if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
  1768. retval = -1;
  1769. goto cleanup;
  1770. }
  1771. DWORD fileAttributes = GetFileAttributesW(path);
  1772. memset(result, 0, sizeof(*result));
  1773. if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
  1774. fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  1775. /* \\.\pipe\ or \\.\mailslot\ */
  1776. result->st_mode = _S_IFDIR;
  1777. } else if (fileType == FILE_TYPE_CHAR) {
  1778. /* \\.\nul */
  1779. result->st_mode = _S_IFCHR;
  1780. } else if (fileType == FILE_TYPE_PIPE) {
  1781. /* \\.\pipe\spam */
  1782. result->st_mode = _S_IFIFO;
  1783. }
  1784. /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
  1785. goto cleanup;
  1786. }
  1787. /* Query the reparse tag, and traverse a non-link. */
  1788. if (!traverse) {
  1789. if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
  1790. &tagInfo, sizeof(tagInfo))) {
  1791. /* Allow devices that do not support FileAttributeTagInfo. */
  1792. switch (GetLastError()) {
  1793. case ERROR_INVALID_PARAMETER:
  1794. case ERROR_INVALID_FUNCTION:
  1795. case ERROR_NOT_SUPPORTED:
  1796. tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
  1797. tagInfo.ReparseTag = 0;
  1798. break;
  1799. default:
  1800. retval = -1;
  1801. goto cleanup;
  1802. }
  1803. } else if (tagInfo.FileAttributes &
  1804. FILE_ATTRIBUTE_REPARSE_POINT) {
  1805. if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
  1806. if (isUnhandledTag) {
  1807. /* Traversing previously failed for either this link
  1808. or its target. */
  1809. SetLastError(ERROR_CANT_ACCESS_FILE);
  1810. retval = -1;
  1811. goto cleanup;
  1812. }
  1813. /* Traverse a non-link, but not if traversing already failed
  1814. for an unhandled tag. */
  1815. } else if (!isUnhandledTag) {
  1816. CloseHandle(hFile);
  1817. return win32_xstat_slow_impl(path, result, TRUE);
  1818. }
  1819. }
  1820. }
  1821. if (!GetFileInformationByHandle(hFile, &fileInfo) ||
  1822. !GetFileInformationByHandleEx(hFile, FileBasicInfo,
  1823. &basicInfo, sizeof(basicInfo))) {
  1824. switch (GetLastError()) {
  1825. case ERROR_INVALID_PARAMETER:
  1826. case ERROR_INVALID_FUNCTION:
  1827. case ERROR_NOT_SUPPORTED:
  1828. /* Volumes and physical disks are block devices, e.g.
  1829. \\.\C: and \\.\PhysicalDrive0. */
  1830. memset(result, 0, sizeof(*result));
  1831. result->st_mode = 0x6000; /* S_IFBLK */
  1832. goto cleanup;
  1833. }
  1834. retval = -1;
  1835. goto cleanup;
  1836. }
  1837. /* Successfully got FileBasicInfo, so we'll pass it along */
  1838. pBasicInfo = &basicInfo;
  1839. if (GetFileInformationByHandleEx(hFile, FileIdInfo, &idInfo, sizeof(idInfo))) {
  1840. /* Successfully got FileIdInfo, so pass it along */
  1841. pIdInfo = &idInfo;
  1842. }
  1843. }
  1844. _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, pBasicInfo, pIdInfo, result);
  1845. update_st_mode_from_path(path, fileInfo.dwFileAttributes, result);
  1846. cleanup:
  1847. if (hFile != INVALID_HANDLE_VALUE) {
  1848. /* Preserve last error if we are failing */
  1849. error = retval ? GetLastError() : 0;
  1850. if (!CloseHandle(hFile)) {
  1851. retval = -1;
  1852. } else if (retval) {
  1853. /* Restore last error */
  1854. SetLastError(error);
  1855. }
  1856. }
  1857. return retval;
  1858. }
  1859. static int
  1860. win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
  1861. BOOL traverse)
  1862. {
  1863. FILE_STAT_BASIC_INFORMATION statInfo;
  1864. if (_Py_GetFileInformationByName(path, FileStatBasicByNameInfo,
  1865. &statInfo, sizeof(statInfo))) {
  1866. if (// Cannot use fast path for reparse points ...
  1867. !(statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
  1868. // ... unless it's a name surrogate (symlink) and we're not following
  1869. || (!traverse && IsReparseTagNameSurrogate(statInfo.ReparseTag))
  1870. ) {
  1871. _Py_stat_basic_info_to_stat(&statInfo, result);
  1872. update_st_mode_from_path(path, statInfo.FileAttributes, result);
  1873. return 0;
  1874. }
  1875. } else {
  1876. switch(GetLastError()) {
  1877. case ERROR_FILE_NOT_FOUND:
  1878. case ERROR_PATH_NOT_FOUND:
  1879. case ERROR_NOT_READY:
  1880. case ERROR_BAD_NET_NAME:
  1881. /* These errors aren't worth retrying with the slow path */
  1882. return -1;
  1883. case ERROR_NOT_SUPPORTED:
  1884. /* indicates the API couldn't be loaded */
  1885. break;
  1886. }
  1887. }
  1888. return win32_xstat_slow_impl(path, result, traverse);
  1889. }
  1890. static int
  1891. win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
  1892. {
  1893. /* Protocol violation: we explicitly clear errno, instead of
  1894. setting it to a POSIX error. Callers should use GetLastError. */
  1895. int code = win32_xstat_impl(path, result, traverse);
  1896. errno = 0;
  1897. /* ctime is only deprecated from 3.12, so we copy birthtime across */
  1898. result->st_ctime = result->st_birthtime;
  1899. result->st_ctime_nsec = result->st_birthtime_nsec;
  1900. return code;
  1901. }
  1902. /* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
  1903. In Posix, stat automatically traverses symlinks and returns the stat
  1904. structure for the target. In Windows, the equivalent GetFileAttributes by
  1905. default does not traverse symlinks and instead returns attributes for
  1906. the symlink.
  1907. Instead, we will open the file (which *does* traverse symlinks by default)
  1908. and GetFileInformationByHandle(). */
  1909. static int
  1910. win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
  1911. {
  1912. return win32_xstat(path, result, FALSE);
  1913. }
  1914. static int
  1915. win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
  1916. {
  1917. return win32_xstat(path, result, TRUE);
  1918. }
  1919. #endif /* MS_WINDOWS */
  1920. PyDoc_STRVAR(stat_result__doc__,
  1921. "stat_result: Result from stat, fstat, or lstat.\n\n\
  1922. This object may be accessed either as a tuple of\n\
  1923. (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
  1924. or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
  1925. \n\
  1926. Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
  1927. or st_flags, they are available as attributes only.\n\
  1928. \n\
  1929. See os.stat for more information.");
  1930. static PyStructSequence_Field stat_result_fields[] = {
  1931. {"st_mode", "protection bits"},
  1932. {"st_ino", "inode"},
  1933. {"st_dev", "device"},
  1934. {"st_nlink", "number of hard links"},
  1935. {"st_uid", "user ID of owner"},
  1936. {"st_gid", "group ID of owner"},
  1937. {"st_size", "total size, in bytes"},
  1938. /* The NULL is replaced with PyStructSequence_UnnamedField later. */
  1939. {NULL, "integer time of last access"},
  1940. {NULL, "integer time of last modification"},
  1941. {NULL, "integer time of last change"},
  1942. {"st_atime", "time of last access"},
  1943. {"st_mtime", "time of last modification"},
  1944. {"st_ctime", "time of last change"},
  1945. {"st_atime_ns", "time of last access in nanoseconds"},
  1946. {"st_mtime_ns", "time of last modification in nanoseconds"},
  1947. {"st_ctime_ns", "time of last change in nanoseconds"},
  1948. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1949. {"st_blksize", "blocksize for filesystem I/O"},
  1950. #endif
  1951. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1952. {"st_blocks", "number of blocks allocated"},
  1953. #endif
  1954. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1955. {"st_rdev", "device type (if inode device)"},
  1956. #endif
  1957. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1958. {"st_flags", "user defined flags for file"},
  1959. #endif
  1960. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1961. {"st_gen", "generation number"},
  1962. #endif
  1963. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) || defined(MS_WINDOWS)
  1964. {"st_birthtime", "time of creation"},
  1965. #endif
  1966. #ifdef MS_WINDOWS
  1967. {"st_birthtime_ns", "time of creation in nanoseconds"},
  1968. #endif
  1969. #ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
  1970. {"st_file_attributes", "Windows file attribute bits"},
  1971. #endif
  1972. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  1973. {"st_fstype", "Type of filesystem"},
  1974. #endif
  1975. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  1976. {"st_reparse_tag", "Windows reparse tag"},
  1977. #endif
  1978. {0}
  1979. };
  1980. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1981. #define ST_BLKSIZE_IDX 16
  1982. #else
  1983. #define ST_BLKSIZE_IDX 15
  1984. #endif
  1985. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1986. #define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
  1987. #else
  1988. #define ST_BLOCKS_IDX ST_BLKSIZE_IDX
  1989. #endif
  1990. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1991. #define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
  1992. #else
  1993. #define ST_RDEV_IDX ST_BLOCKS_IDX
  1994. #endif
  1995. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1996. #define ST_FLAGS_IDX (ST_RDEV_IDX+1)
  1997. #else
  1998. #define ST_FLAGS_IDX ST_RDEV_IDX
  1999. #endif
  2000. #ifdef HAVE_STRUCT_STAT_ST_GEN
  2001. #define ST_GEN_IDX (ST_FLAGS_IDX+1)
  2002. #else
  2003. #define ST_GEN_IDX ST_FLAGS_IDX
  2004. #endif
  2005. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) || defined(MS_WINDOWS)
  2006. #define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
  2007. #else
  2008. #define ST_BIRTHTIME_IDX ST_GEN_IDX
  2009. #endif
  2010. #ifdef MS_WINDOWS
  2011. #define ST_BIRTHTIME_NS_IDX (ST_BIRTHTIME_IDX+1)
  2012. #else
  2013. #define ST_BIRTHTIME_NS_IDX ST_BIRTHTIME_IDX
  2014. #endif
  2015. #if defined(HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES) || defined(MS_WINDOWS)
  2016. #define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_NS_IDX+1)
  2017. #else
  2018. #define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_NS_IDX
  2019. #endif
  2020. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  2021. #define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
  2022. #else
  2023. #define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
  2024. #endif
  2025. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  2026. #define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
  2027. #else
  2028. #define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
  2029. #endif
  2030. static PyStructSequence_Desc stat_result_desc = {
  2031. "stat_result", /* name */
  2032. stat_result__doc__, /* doc */
  2033. stat_result_fields,
  2034. 10
  2035. };
  2036. PyDoc_STRVAR(statvfs_result__doc__,
  2037. "statvfs_result: Result from statvfs or fstatvfs.\n\n\
  2038. This object may be accessed either as a tuple of\n\
  2039. (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
  2040. or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
  2041. \n\
  2042. See os.statvfs for more information.");
  2043. static PyStructSequence_Field statvfs_result_fields[] = {
  2044. {"f_bsize", },
  2045. {"f_frsize", },
  2046. {"f_blocks", },
  2047. {"f_bfree", },
  2048. {"f_bavail", },
  2049. {"f_files", },
  2050. {"f_ffree", },
  2051. {"f_favail", },
  2052. {"f_flag", },
  2053. {"f_namemax",},
  2054. {"f_fsid", },
  2055. {0}
  2056. };
  2057. static PyStructSequence_Desc statvfs_result_desc = {
  2058. "statvfs_result", /* name */
  2059. statvfs_result__doc__, /* doc */
  2060. statvfs_result_fields,
  2061. 10
  2062. };
  2063. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2064. PyDoc_STRVAR(waitid_result__doc__,
  2065. "waitid_result: Result from waitid.\n\n\
  2066. This object may be accessed either as a tuple of\n\
  2067. (si_pid, si_uid, si_signo, si_status, si_code),\n\
  2068. or via the attributes si_pid, si_uid, and so on.\n\
  2069. \n\
  2070. See os.waitid for more information.");
  2071. static PyStructSequence_Field waitid_result_fields[] = {
  2072. {"si_pid", },
  2073. {"si_uid", },
  2074. {"si_signo", },
  2075. {"si_status", },
  2076. {"si_code", },
  2077. {0}
  2078. };
  2079. static PyStructSequence_Desc waitid_result_desc = {
  2080. "waitid_result", /* name */
  2081. waitid_result__doc__, /* doc */
  2082. waitid_result_fields,
  2083. 5
  2084. };
  2085. #endif
  2086. static PyObject *
  2087. statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2088. {
  2089. PyStructSequence *result;
  2090. int i;
  2091. // ht_module doesn't get set in PyStructSequence_NewType(),
  2092. // so we can't use PyType_GetModule().
  2093. PyObject *mod = PyImport_GetModule(MODNAME_OBJ);
  2094. if (mod == NULL) {
  2095. return NULL;
  2096. }
  2097. _posixstate *state = get_posix_state(mod);
  2098. Py_DECREF(mod);
  2099. if (state == NULL) {
  2100. return NULL;
  2101. }
  2102. #define structseq_new state->statresult_new_orig
  2103. result = (PyStructSequence*)structseq_new(type, args, kwds);
  2104. if (!result)
  2105. return NULL;
  2106. /* If we have been initialized from a tuple,
  2107. st_?time might be set to None. Initialize it
  2108. from the int slots. */
  2109. for (i = 7; i <= 9; i++) {
  2110. if (result->ob_item[i+3] == Py_None) {
  2111. Py_DECREF(Py_None);
  2112. result->ob_item[i+3] = Py_NewRef(result->ob_item[i]);
  2113. }
  2114. }
  2115. return (PyObject*)result;
  2116. }
  2117. static int
  2118. _posix_clear(PyObject *module)
  2119. {
  2120. _posixstate *state = get_posix_state(module);
  2121. Py_CLEAR(state->billion);
  2122. Py_CLEAR(state->DirEntryType);
  2123. Py_CLEAR(state->ScandirIteratorType);
  2124. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  2125. Py_CLEAR(state->SchedParamType);
  2126. #endif
  2127. Py_CLEAR(state->StatResultType);
  2128. Py_CLEAR(state->StatVFSResultType);
  2129. Py_CLEAR(state->TerminalSizeType);
  2130. Py_CLEAR(state->TimesResultType);
  2131. Py_CLEAR(state->UnameResultType);
  2132. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2133. Py_CLEAR(state->WaitidResultType);
  2134. #endif
  2135. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  2136. Py_CLEAR(state->struct_rusage);
  2137. #endif
  2138. Py_CLEAR(state->st_mode);
  2139. return 0;
  2140. }
  2141. static int
  2142. _posix_traverse(PyObject *module, visitproc visit, void *arg)
  2143. {
  2144. _posixstate *state = get_posix_state(module);
  2145. Py_VISIT(state->billion);
  2146. Py_VISIT(state->DirEntryType);
  2147. Py_VISIT(state->ScandirIteratorType);
  2148. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  2149. Py_VISIT(state->SchedParamType);
  2150. #endif
  2151. Py_VISIT(state->StatResultType);
  2152. Py_VISIT(state->StatVFSResultType);
  2153. Py_VISIT(state->TerminalSizeType);
  2154. Py_VISIT(state->TimesResultType);
  2155. Py_VISIT(state->UnameResultType);
  2156. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2157. Py_VISIT(state->WaitidResultType);
  2158. #endif
  2159. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  2160. Py_VISIT(state->struct_rusage);
  2161. #endif
  2162. Py_VISIT(state->st_mode);
  2163. return 0;
  2164. }
  2165. static void
  2166. _posix_free(void *module)
  2167. {
  2168. _posix_clear((PyObject *)module);
  2169. }
  2170. static int
  2171. fill_time(PyObject *module, PyObject *v, int s_index, int f_index, int ns_index, time_t sec, unsigned long nsec)
  2172. {
  2173. assert(!PyErr_Occurred());
  2174. int res = -1;
  2175. PyObject *s_in_ns = NULL;
  2176. PyObject *ns_total = NULL;
  2177. PyObject *float_s = NULL;
  2178. PyObject *s = _PyLong_FromTime_t(sec);
  2179. PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
  2180. if (!(s && ns_fractional)) {
  2181. goto exit;
  2182. }
  2183. s_in_ns = PyNumber_Multiply(s, get_posix_state(module)->billion);
  2184. if (!s_in_ns) {
  2185. goto exit;
  2186. }
  2187. ns_total = PyNumber_Add(s_in_ns, ns_fractional);
  2188. if (!ns_total)
  2189. goto exit;
  2190. float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
  2191. if (!float_s) {
  2192. goto exit;
  2193. }
  2194. if (s_index >= 0) {
  2195. PyStructSequence_SET_ITEM(v, s_index, s);
  2196. s = NULL;
  2197. }
  2198. if (f_index >= 0) {
  2199. PyStructSequence_SET_ITEM(v, f_index, float_s);
  2200. float_s = NULL;
  2201. }
  2202. if (ns_index >= 0) {
  2203. PyStructSequence_SET_ITEM(v, ns_index, ns_total);
  2204. ns_total = NULL;
  2205. }
  2206. assert(!PyErr_Occurred());
  2207. res = 0;
  2208. exit:
  2209. Py_XDECREF(s);
  2210. Py_XDECREF(ns_fractional);
  2211. Py_XDECREF(s_in_ns);
  2212. Py_XDECREF(ns_total);
  2213. Py_XDECREF(float_s);
  2214. return res;
  2215. }
  2216. #ifdef MS_WINDOWS
  2217. static PyObject*
  2218. _pystat_l128_from_l64_l64(uint64_t low, uint64_t high)
  2219. {
  2220. PyObject *o_low = PyLong_FromUnsignedLongLong(low);
  2221. if (!o_low || !high) {
  2222. return o_low;
  2223. }
  2224. PyObject *o_high = PyLong_FromUnsignedLongLong(high);
  2225. PyObject *l64 = o_high ? PyLong_FromLong(64) : NULL;
  2226. if (!l64) {
  2227. Py_XDECREF(o_high);
  2228. Py_DECREF(o_low);
  2229. return NULL;
  2230. }
  2231. Py_SETREF(o_high, PyNumber_Lshift(o_high, l64));
  2232. Py_DECREF(l64);
  2233. if (!o_high) {
  2234. Py_DECREF(o_low);
  2235. return NULL;
  2236. }
  2237. Py_SETREF(o_low, PyNumber_Add(o_low, o_high));
  2238. Py_DECREF(o_high);
  2239. return o_low;
  2240. }
  2241. #endif
  2242. /* pack a system stat C structure into the Python stat tuple
  2243. (used by posix_stat() and posix_fstat()) */
  2244. static PyObject*
  2245. _pystat_fromstructstat(PyObject *module, STRUCT_STAT *st)
  2246. {
  2247. assert(!PyErr_Occurred());
  2248. PyObject *StatResultType = get_posix_state(module)->StatResultType;
  2249. PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
  2250. if (v == NULL) {
  2251. return NULL;
  2252. }
  2253. #define SET_ITEM(pos, expr) \
  2254. do { \
  2255. PyObject *obj = (expr); \
  2256. if (obj == NULL) { \
  2257. goto error; \
  2258. } \
  2259. PyStructSequence_SET_ITEM(v, (pos), obj); \
  2260. } while (0)
  2261. SET_ITEM(0, PyLong_FromLong((long)st->st_mode));
  2262. #ifdef MS_WINDOWS
  2263. SET_ITEM(1, _pystat_l128_from_l64_l64(st->st_ino, st->st_ino_high));
  2264. SET_ITEM(2, PyLong_FromUnsignedLongLong(st->st_dev));
  2265. #else
  2266. static_assert(sizeof(unsigned long long) >= sizeof(st->st_ino),
  2267. "stat.st_ino is larger than unsigned long long");
  2268. SET_ITEM(1, PyLong_FromUnsignedLongLong(st->st_ino));
  2269. SET_ITEM(2, _PyLong_FromDev(st->st_dev));
  2270. #endif
  2271. SET_ITEM(3, PyLong_FromLong((long)st->st_nlink));
  2272. #if defined(MS_WINDOWS)
  2273. SET_ITEM(4, PyLong_FromLong(0));
  2274. SET_ITEM(5, PyLong_FromLong(0));
  2275. #else
  2276. SET_ITEM(4, _PyLong_FromUid(st->st_uid));
  2277. SET_ITEM(5, _PyLong_FromGid(st->st_gid));
  2278. #endif
  2279. static_assert(sizeof(long long) >= sizeof(st->st_size),
  2280. "stat.st_size is larger than long long");
  2281. SET_ITEM(6, PyLong_FromLongLong(st->st_size));
  2282. // Set st_atime, st_mtime and st_ctime
  2283. unsigned long ansec, mnsec, cnsec;
  2284. #if defined(HAVE_STAT_TV_NSEC)
  2285. ansec = st->st_atim.tv_nsec;
  2286. mnsec = st->st_mtim.tv_nsec;
  2287. cnsec = st->st_ctim.tv_nsec;
  2288. #elif defined(HAVE_STAT_TV_NSEC2)
  2289. ansec = st->st_atimespec.tv_nsec;
  2290. mnsec = st->st_mtimespec.tv_nsec;
  2291. cnsec = st->st_ctimespec.tv_nsec;
  2292. #elif defined(HAVE_STAT_NSEC)
  2293. ansec = st->st_atime_nsec;
  2294. mnsec = st->st_mtime_nsec;
  2295. cnsec = st->st_ctime_nsec;
  2296. #else
  2297. ansec = mnsec = cnsec = 0;
  2298. #endif
  2299. if (fill_time(module, v, 7, 10, 13, st->st_atime, ansec) < 0) {
  2300. goto error;
  2301. }
  2302. if (fill_time(module, v, 8, 11, 14, st->st_mtime, mnsec) < 0) {
  2303. goto error;
  2304. }
  2305. if (fill_time(module, v, 9, 12, 15, st->st_ctime, cnsec) < 0) {
  2306. goto error;
  2307. }
  2308. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  2309. SET_ITEM(ST_BLKSIZE_IDX, PyLong_FromLong((long)st->st_blksize));
  2310. #endif
  2311. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  2312. SET_ITEM(ST_BLOCKS_IDX, PyLong_FromLong((long)st->st_blocks));
  2313. #endif
  2314. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  2315. SET_ITEM(ST_RDEV_IDX, PyLong_FromLong((long)st->st_rdev));
  2316. #endif
  2317. #ifdef HAVE_STRUCT_STAT_ST_GEN
  2318. SET_ITEM(ST_GEN_IDX, PyLong_FromLong((long)st->st_gen));
  2319. #endif
  2320. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME)
  2321. {
  2322. unsigned long bsec, bnsec;
  2323. bsec = (long)st->st_birthtime;
  2324. #ifdef HAVE_STAT_TV_NSEC2
  2325. bnsec = st->st_birthtimespec.tv_nsec;
  2326. #else
  2327. bnsec = 0;
  2328. #endif
  2329. SET_ITEM(ST_BIRTHTIME_IDX, PyFloat_FromDouble(bsec + bnsec * 1e-9));
  2330. }
  2331. #elif defined(MS_WINDOWS)
  2332. if (fill_time(module, v, -1, ST_BIRTHTIME_IDX, ST_BIRTHTIME_NS_IDX,
  2333. st->st_birthtime, st->st_birthtime_nsec) < 0) {
  2334. goto error;
  2335. }
  2336. #endif
  2337. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  2338. SET_ITEM(ST_FLAGS_IDX, PyLong_FromLong((long)st->st_flags));
  2339. #endif
  2340. #ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
  2341. SET_ITEM(ST_FILE_ATTRIBUTES_IDX,
  2342. PyLong_FromUnsignedLong(st->st_file_attributes));
  2343. #endif
  2344. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  2345. SET_ITEM(ST_FSTYPE_IDX, PyUnicode_FromString(st->st_fstype));
  2346. #endif
  2347. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  2348. SET_ITEM(ST_REPARSE_TAG_IDX, PyLong_FromUnsignedLong(st->st_reparse_tag));
  2349. #endif
  2350. assert(!PyErr_Occurred());
  2351. return v;
  2352. error:
  2353. Py_DECREF(v);
  2354. return NULL;
  2355. #undef SET_ITEM
  2356. }
  2357. /* POSIX methods */
  2358. static PyObject *
  2359. posix_do_stat(PyObject *module, const char *function_name, path_t *path,
  2360. int dir_fd, int follow_symlinks)
  2361. {
  2362. STRUCT_STAT st;
  2363. int result;
  2364. #ifdef HAVE_FSTATAT
  2365. int fstatat_unavailable = 0;
  2366. #endif
  2367. #if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
  2368. if (follow_symlinks_specified(function_name, follow_symlinks))
  2369. return NULL;
  2370. #endif
  2371. if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
  2372. dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
  2373. fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
  2374. return NULL;
  2375. Py_BEGIN_ALLOW_THREADS
  2376. if (path->fd != -1)
  2377. result = FSTAT(path->fd, &st);
  2378. #ifdef MS_WINDOWS
  2379. else if (follow_symlinks)
  2380. result = win32_stat(path->wide, &st);
  2381. else
  2382. result = win32_lstat(path->wide, &st);
  2383. #else
  2384. else
  2385. #if defined(HAVE_LSTAT)
  2386. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  2387. result = LSTAT(path->narrow, &st);
  2388. else
  2389. #endif /* HAVE_LSTAT */
  2390. #ifdef HAVE_FSTATAT
  2391. if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
  2392. if (HAVE_FSTATAT_RUNTIME) {
  2393. result = fstatat(dir_fd, path->narrow, &st,
  2394. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  2395. } else {
  2396. fstatat_unavailable = 1;
  2397. }
  2398. } else
  2399. #endif /* HAVE_FSTATAT */
  2400. result = STAT(path->narrow, &st);
  2401. #endif /* MS_WINDOWS */
  2402. Py_END_ALLOW_THREADS
  2403. #ifdef HAVE_FSTATAT
  2404. if (fstatat_unavailable) {
  2405. argument_unavailable_error("stat", "dir_fd");
  2406. return NULL;
  2407. }
  2408. #endif
  2409. if (result != 0) {
  2410. return path_error(path);
  2411. }
  2412. return _pystat_fromstructstat(module, &st);
  2413. }
  2414. /*[python input]
  2415. for s in """
  2416. FACCESSAT
  2417. FCHMODAT
  2418. FCHOWNAT
  2419. FSTATAT
  2420. LINKAT
  2421. MKDIRAT
  2422. MKFIFOAT
  2423. MKNODAT
  2424. OPENAT
  2425. READLINKAT
  2426. SYMLINKAT
  2427. UNLINKAT
  2428. """.strip().split():
  2429. s = s.strip()
  2430. print("""
  2431. #ifdef HAVE_{s}
  2432. #define {s}_DIR_FD_CONVERTER dir_fd_converter
  2433. #else
  2434. #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
  2435. #endif
  2436. """.rstrip().format(s=s))
  2437. for s in """
  2438. FCHDIR
  2439. FCHMOD
  2440. FCHOWN
  2441. FDOPENDIR
  2442. FEXECVE
  2443. FPATHCONF
  2444. FSTATVFS
  2445. FTRUNCATE
  2446. """.strip().split():
  2447. s = s.strip()
  2448. print("""
  2449. #ifdef HAVE_{s}
  2450. #define PATH_HAVE_{s} 1
  2451. #else
  2452. #define PATH_HAVE_{s} 0
  2453. #endif
  2454. """.rstrip().format(s=s))
  2455. [python start generated code]*/
  2456. #ifdef HAVE_FACCESSAT
  2457. #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
  2458. #else
  2459. #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
  2460. #endif
  2461. #ifdef HAVE_FCHMODAT
  2462. #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
  2463. #else
  2464. #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
  2465. #endif
  2466. #ifdef HAVE_FCHOWNAT
  2467. #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
  2468. #else
  2469. #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
  2470. #endif
  2471. #ifdef HAVE_FSTATAT
  2472. #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
  2473. #else
  2474. #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
  2475. #endif
  2476. #ifdef HAVE_LINKAT
  2477. #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
  2478. #else
  2479. #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2480. #endif
  2481. #ifdef HAVE_MKDIRAT
  2482. #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
  2483. #else
  2484. #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
  2485. #endif
  2486. #ifdef HAVE_MKFIFOAT
  2487. #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
  2488. #else
  2489. #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
  2490. #endif
  2491. #ifdef HAVE_MKNODAT
  2492. #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
  2493. #else
  2494. #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
  2495. #endif
  2496. #ifdef HAVE_OPENAT
  2497. #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
  2498. #else
  2499. #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
  2500. #endif
  2501. #ifdef HAVE_READLINKAT
  2502. #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2503. #else
  2504. #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2505. #endif
  2506. #ifdef HAVE_SYMLINKAT
  2507. #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2508. #else
  2509. #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2510. #endif
  2511. #ifdef HAVE_UNLINKAT
  2512. #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2513. #else
  2514. #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2515. #endif
  2516. #ifdef HAVE_FCHDIR
  2517. #define PATH_HAVE_FCHDIR 1
  2518. #else
  2519. #define PATH_HAVE_FCHDIR 0
  2520. #endif
  2521. #ifdef HAVE_FCHMOD
  2522. #define PATH_HAVE_FCHMOD 1
  2523. #else
  2524. #define PATH_HAVE_FCHMOD 0
  2525. #endif
  2526. #ifdef HAVE_FCHOWN
  2527. #define PATH_HAVE_FCHOWN 1
  2528. #else
  2529. #define PATH_HAVE_FCHOWN 0
  2530. #endif
  2531. #ifdef HAVE_FDOPENDIR
  2532. #define PATH_HAVE_FDOPENDIR 1
  2533. #else
  2534. #define PATH_HAVE_FDOPENDIR 0
  2535. #endif
  2536. #ifdef HAVE_FEXECVE
  2537. #define PATH_HAVE_FEXECVE 1
  2538. #else
  2539. #define PATH_HAVE_FEXECVE 0
  2540. #endif
  2541. #ifdef HAVE_FPATHCONF
  2542. #define PATH_HAVE_FPATHCONF 1
  2543. #else
  2544. #define PATH_HAVE_FPATHCONF 0
  2545. #endif
  2546. #ifdef HAVE_FSTATVFS
  2547. #define PATH_HAVE_FSTATVFS 1
  2548. #else
  2549. #define PATH_HAVE_FSTATVFS 0
  2550. #endif
  2551. #ifdef HAVE_FTRUNCATE
  2552. #define PATH_HAVE_FTRUNCATE 1
  2553. #else
  2554. #define PATH_HAVE_FTRUNCATE 0
  2555. #endif
  2556. /*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
  2557. #ifdef MS_WINDOWS
  2558. #undef PATH_HAVE_FTRUNCATE
  2559. #define PATH_HAVE_FTRUNCATE 1
  2560. #endif
  2561. /*[python input]
  2562. class path_t_converter(CConverter):
  2563. type = "path_t"
  2564. impl_by_reference = True
  2565. parse_by_reference = True
  2566. converter = 'path_converter'
  2567. def converter_init(self, *, allow_fd=False, make_wide=None,
  2568. nonstrict=False, nullable=False,
  2569. suppress_value_error=False):
  2570. # right now path_t doesn't support default values.
  2571. # to support a default value, you'll need to override initialize().
  2572. if self.default not in (unspecified, None):
  2573. fail("Can't specify a default to the path_t converter!")
  2574. if self.c_default not in (None, 'Py_None'):
  2575. raise RuntimeError("Can't specify a c_default to the path_t converter!")
  2576. self.nullable = nullable
  2577. self.nonstrict = nonstrict
  2578. self.make_wide = make_wide
  2579. self.suppress_value_error = suppress_value_error
  2580. self.allow_fd = allow_fd
  2581. def pre_render(self):
  2582. def strify(value):
  2583. if isinstance(value, str):
  2584. return value
  2585. return str(int(bool(value)))
  2586. # add self.py_name here when merging with posixmodule conversion
  2587. if self.make_wide is None:
  2588. self.c_default = 'PATH_T_INITIALIZE_P("{}", "{}", {}, {}, {}, {})'.format(
  2589. self.function.name,
  2590. self.name,
  2591. strify(self.nullable),
  2592. strify(self.nonstrict),
  2593. strify(self.suppress_value_error),
  2594. strify(self.allow_fd),
  2595. )
  2596. else:
  2597. self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {}, {}, {}, {})'.format(
  2598. self.function.name,
  2599. self.name,
  2600. strify(self.nullable),
  2601. strify(self.nonstrict),
  2602. strify(self.make_wide),
  2603. strify(self.suppress_value_error),
  2604. strify(self.allow_fd),
  2605. )
  2606. def cleanup(self):
  2607. return "path_cleanup(&" + self.name + ");\n"
  2608. class dir_fd_converter(CConverter):
  2609. type = 'int'
  2610. def converter_init(self, requires=None):
  2611. if self.default in (unspecified, None):
  2612. self.c_default = 'DEFAULT_DIR_FD'
  2613. if isinstance(requires, str):
  2614. self.converter = requires.upper() + '_DIR_FD_CONVERTER'
  2615. else:
  2616. self.converter = 'dir_fd_converter'
  2617. class uid_t_converter(CConverter):
  2618. type = "uid_t"
  2619. converter = '_Py_Uid_Converter'
  2620. class gid_t_converter(CConverter):
  2621. type = "gid_t"
  2622. converter = '_Py_Gid_Converter'
  2623. class dev_t_converter(CConverter):
  2624. type = 'dev_t'
  2625. converter = '_Py_Dev_Converter'
  2626. class dev_t_return_converter(unsigned_long_return_converter):
  2627. type = 'dev_t'
  2628. conversion_fn = '_PyLong_FromDev'
  2629. unsigned_cast = '(dev_t)'
  2630. class FSConverter_converter(CConverter):
  2631. type = 'PyObject *'
  2632. converter = 'PyUnicode_FSConverter'
  2633. def converter_init(self):
  2634. if self.default is not unspecified:
  2635. fail("FSConverter_converter does not support default values")
  2636. self.c_default = 'NULL'
  2637. def cleanup(self):
  2638. return "Py_XDECREF(" + self.name + ");\n"
  2639. class pid_t_converter(CConverter):
  2640. type = 'pid_t'
  2641. format_unit = '" _Py_PARSE_PID "'
  2642. class idtype_t_converter(int_converter):
  2643. type = 'idtype_t'
  2644. class id_t_converter(CConverter):
  2645. type = 'id_t'
  2646. format_unit = '" _Py_PARSE_PID "'
  2647. class intptr_t_converter(CConverter):
  2648. type = 'intptr_t'
  2649. format_unit = '" _Py_PARSE_INTPTR "'
  2650. class Py_off_t_converter(CConverter):
  2651. type = 'Py_off_t'
  2652. converter = 'Py_off_t_converter'
  2653. class Py_off_t_return_converter(long_return_converter):
  2654. type = 'Py_off_t'
  2655. conversion_fn = 'PyLong_FromPy_off_t'
  2656. class path_confname_converter(CConverter):
  2657. type="int"
  2658. converter="conv_path_confname"
  2659. class confstr_confname_converter(path_confname_converter):
  2660. converter='conv_confstr_confname'
  2661. class sysconf_confname_converter(path_confname_converter):
  2662. converter="conv_sysconf_confname"
  2663. [python start generated code]*/
  2664. /*[python end generated code: output=da39a3ee5e6b4b0d input=577cb476e5d64960]*/
  2665. /*[clinic input]
  2666. os.stat
  2667. path : path_t(allow_fd=True)
  2668. Path to be examined; can be string, bytes, a path-like object or
  2669. open-file-descriptor int.
  2670. *
  2671. dir_fd : dir_fd(requires='fstatat') = None
  2672. If not None, it should be a file descriptor open to a directory,
  2673. and path should be a relative string; path will then be relative to
  2674. that directory.
  2675. follow_symlinks: bool = True
  2676. If False, and the last element of the path is a symbolic link,
  2677. stat will examine the symbolic link itself instead of the file
  2678. the link points to.
  2679. Perform a stat system call on the given path.
  2680. dir_fd and follow_symlinks may not be implemented
  2681. on your platform. If they are unavailable, using them will raise a
  2682. NotImplementedError.
  2683. It's an error to use dir_fd or follow_symlinks when specifying path as
  2684. an open file descriptor.
  2685. [clinic start generated code]*/
  2686. static PyObject *
  2687. os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
  2688. /*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
  2689. {
  2690. return posix_do_stat(module, "stat", path, dir_fd, follow_symlinks);
  2691. }
  2692. /*[clinic input]
  2693. os.lstat
  2694. path : path_t
  2695. *
  2696. dir_fd : dir_fd(requires='fstatat') = None
  2697. Perform a stat system call on the given path, without following symbolic links.
  2698. Like stat(), but do not follow symbolic links.
  2699. Equivalent to stat(path, follow_symlinks=False).
  2700. [clinic start generated code]*/
  2701. static PyObject *
  2702. os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
  2703. /*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
  2704. {
  2705. int follow_symlinks = 0;
  2706. return posix_do_stat(module, "lstat", path, dir_fd, follow_symlinks);
  2707. }
  2708. /*[clinic input]
  2709. os.access -> bool
  2710. path: path_t
  2711. Path to be tested; can be string, bytes, or a path-like object.
  2712. mode: int
  2713. Operating-system mode bitfield. Can be F_OK to test existence,
  2714. or the inclusive-OR of R_OK, W_OK, and X_OK.
  2715. *
  2716. dir_fd : dir_fd(requires='faccessat') = None
  2717. If not None, it should be a file descriptor open to a directory,
  2718. and path should be relative; path will then be relative to that
  2719. directory.
  2720. effective_ids: bool = False
  2721. If True, access will use the effective uid/gid instead of
  2722. the real uid/gid.
  2723. follow_symlinks: bool = True
  2724. If False, and the last element of the path is a symbolic link,
  2725. access will examine the symbolic link itself instead of the file
  2726. the link points to.
  2727. Use the real uid/gid to test for access to a path.
  2728. {parameters}
  2729. dir_fd, effective_ids, and follow_symlinks may not be implemented
  2730. on your platform. If they are unavailable, using them will raise a
  2731. NotImplementedError.
  2732. Note that most operations will use the effective uid/gid, therefore this
  2733. routine can be used in a suid/sgid environment to test if the invoking user
  2734. has the specified access to the path.
  2735. [clinic start generated code]*/
  2736. static int
  2737. os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
  2738. int effective_ids, int follow_symlinks)
  2739. /*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
  2740. {
  2741. int return_value;
  2742. #ifdef MS_WINDOWS
  2743. DWORD attr;
  2744. #else
  2745. int result;
  2746. #endif
  2747. #ifdef HAVE_FACCESSAT
  2748. int faccessat_unavailable = 0;
  2749. #endif
  2750. #ifndef HAVE_FACCESSAT
  2751. if (follow_symlinks_specified("access", follow_symlinks))
  2752. return -1;
  2753. if (effective_ids) {
  2754. argument_unavailable_error("access", "effective_ids");
  2755. return -1;
  2756. }
  2757. #endif
  2758. #ifdef MS_WINDOWS
  2759. Py_BEGIN_ALLOW_THREADS
  2760. attr = GetFileAttributesW(path->wide);
  2761. Py_END_ALLOW_THREADS
  2762. /*
  2763. * Access is possible if
  2764. * * we didn't get a -1, and
  2765. * * write access wasn't requested,
  2766. * * or the file isn't read-only,
  2767. * * or it's a directory.
  2768. * (Directories cannot be read-only on Windows.)
  2769. */
  2770. return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
  2771. (!(mode & 2) ||
  2772. !(attr & FILE_ATTRIBUTE_READONLY) ||
  2773. (attr & FILE_ATTRIBUTE_DIRECTORY));
  2774. #else
  2775. Py_BEGIN_ALLOW_THREADS
  2776. #ifdef HAVE_FACCESSAT
  2777. if ((dir_fd != DEFAULT_DIR_FD) ||
  2778. effective_ids ||
  2779. !follow_symlinks) {
  2780. if (HAVE_FACCESSAT_RUNTIME) {
  2781. int flags = 0;
  2782. if (!follow_symlinks)
  2783. flags |= AT_SYMLINK_NOFOLLOW;
  2784. if (effective_ids)
  2785. flags |= AT_EACCESS;
  2786. result = faccessat(dir_fd, path->narrow, mode, flags);
  2787. } else {
  2788. faccessat_unavailable = 1;
  2789. }
  2790. }
  2791. else
  2792. #endif
  2793. result = access(path->narrow, mode);
  2794. Py_END_ALLOW_THREADS
  2795. #ifdef HAVE_FACCESSAT
  2796. if (faccessat_unavailable) {
  2797. if (dir_fd != DEFAULT_DIR_FD) {
  2798. argument_unavailable_error("access", "dir_fd");
  2799. return -1;
  2800. }
  2801. if (follow_symlinks_specified("access", follow_symlinks))
  2802. return -1;
  2803. if (effective_ids) {
  2804. argument_unavailable_error("access", "effective_ids");
  2805. return -1;
  2806. }
  2807. /* should be unreachable */
  2808. return -1;
  2809. }
  2810. #endif
  2811. return_value = !result;
  2812. #endif
  2813. return return_value;
  2814. }
  2815. #ifndef F_OK
  2816. #define F_OK 0
  2817. #endif
  2818. #ifndef R_OK
  2819. #define R_OK 4
  2820. #endif
  2821. #ifndef W_OK
  2822. #define W_OK 2
  2823. #endif
  2824. #ifndef X_OK
  2825. #define X_OK 1
  2826. #endif
  2827. #ifdef HAVE_TTYNAME
  2828. /*[clinic input]
  2829. os.ttyname
  2830. fd: int
  2831. Integer file descriptor handle.
  2832. /
  2833. Return the name of the terminal device connected to 'fd'.
  2834. [clinic start generated code]*/
  2835. static PyObject *
  2836. os_ttyname_impl(PyObject *module, int fd)
  2837. /*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
  2838. {
  2839. long size = sysconf(_SC_TTY_NAME_MAX);
  2840. if (size == -1) {
  2841. return posix_error();
  2842. }
  2843. char *buffer = (char *)PyMem_RawMalloc(size);
  2844. if (buffer == NULL) {
  2845. return PyErr_NoMemory();
  2846. }
  2847. int ret = ttyname_r(fd, buffer, size);
  2848. if (ret != 0) {
  2849. PyMem_RawFree(buffer);
  2850. errno = ret;
  2851. return posix_error();
  2852. }
  2853. PyObject *res = PyUnicode_DecodeFSDefault(buffer);
  2854. PyMem_RawFree(buffer);
  2855. return res;
  2856. }
  2857. #endif
  2858. #ifdef HAVE_CTERMID
  2859. /*[clinic input]
  2860. os.ctermid
  2861. Return the name of the controlling terminal for this process.
  2862. [clinic start generated code]*/
  2863. static PyObject *
  2864. os_ctermid_impl(PyObject *module)
  2865. /*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
  2866. {
  2867. char *ret;
  2868. char buffer[L_ctermid];
  2869. #ifdef USE_CTERMID_R
  2870. ret = ctermid_r(buffer);
  2871. #else
  2872. ret = ctermid(buffer);
  2873. #endif
  2874. if (ret == NULL)
  2875. return posix_error();
  2876. return PyUnicode_DecodeFSDefault(buffer);
  2877. }
  2878. #endif /* HAVE_CTERMID */
  2879. /*[clinic input]
  2880. os.chdir
  2881. path: path_t(allow_fd='PATH_HAVE_FCHDIR')
  2882. Change the current working directory to the specified path.
  2883. path may always be specified as a string.
  2884. On some platforms, path may also be specified as an open file descriptor.
  2885. If this functionality is unavailable, using it raises an exception.
  2886. [clinic start generated code]*/
  2887. static PyObject *
  2888. os_chdir_impl(PyObject *module, path_t *path)
  2889. /*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
  2890. {
  2891. int result;
  2892. if (PySys_Audit("os.chdir", "(O)", path->object) < 0) {
  2893. return NULL;
  2894. }
  2895. Py_BEGIN_ALLOW_THREADS
  2896. #ifdef MS_WINDOWS
  2897. /* on unix, success = 0, on windows, success = !0 */
  2898. result = !win32_wchdir(path->wide);
  2899. #else
  2900. #ifdef HAVE_FCHDIR
  2901. if (path->fd != -1)
  2902. result = fchdir(path->fd);
  2903. else
  2904. #endif
  2905. result = chdir(path->narrow);
  2906. #endif
  2907. Py_END_ALLOW_THREADS
  2908. if (result) {
  2909. return path_error(path);
  2910. }
  2911. Py_RETURN_NONE;
  2912. }
  2913. #ifdef HAVE_FCHDIR
  2914. /*[clinic input]
  2915. os.fchdir
  2916. fd: fildes
  2917. Change to the directory of the given file descriptor.
  2918. fd must be opened on a directory, not a file.
  2919. Equivalent to os.chdir(fd).
  2920. [clinic start generated code]*/
  2921. static PyObject *
  2922. os_fchdir_impl(PyObject *module, int fd)
  2923. /*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
  2924. {
  2925. if (PySys_Audit("os.chdir", "(i)", fd) < 0) {
  2926. return NULL;
  2927. }
  2928. return posix_fildes_fd(fd, fchdir);
  2929. }
  2930. #endif /* HAVE_FCHDIR */
  2931. /*[clinic input]
  2932. os.chmod
  2933. path: path_t(allow_fd='PATH_HAVE_FCHMOD')
  2934. Path to be modified. May always be specified as a str, bytes, or a path-like object.
  2935. On some platforms, path may also be specified as an open file descriptor.
  2936. If this functionality is unavailable, using it raises an exception.
  2937. mode: int
  2938. Operating-system mode bitfield.
  2939. Be careful when using number literals for *mode*. The conventional UNIX notation for
  2940. numeric modes uses an octal base, which needs to be indicated with a ``0o`` prefix in
  2941. Python.
  2942. *
  2943. dir_fd : dir_fd(requires='fchmodat') = None
  2944. If not None, it should be a file descriptor open to a directory,
  2945. and path should be relative; path will then be relative to that
  2946. directory.
  2947. follow_symlinks: bool = True
  2948. If False, and the last element of the path is a symbolic link,
  2949. chmod will modify the symbolic link itself instead of the file
  2950. the link points to.
  2951. Change the access permissions of a file.
  2952. It is an error to use dir_fd or follow_symlinks when specifying path as
  2953. an open file descriptor.
  2954. dir_fd and follow_symlinks may not be implemented on your platform.
  2955. If they are unavailable, using them will raise a NotImplementedError.
  2956. [clinic start generated code]*/
  2957. static PyObject *
  2958. os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
  2959. int follow_symlinks)
  2960. /*[clinic end generated code: output=5cf6a94915cc7bff input=674a14bc998de09d]*/
  2961. {
  2962. int result;
  2963. #ifdef MS_WINDOWS
  2964. DWORD attr;
  2965. #endif
  2966. #ifdef HAVE_FCHMODAT
  2967. int fchmodat_nofollow_unsupported = 0;
  2968. int fchmodat_unsupported = 0;
  2969. #endif
  2970. #if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
  2971. if (follow_symlinks_specified("chmod", follow_symlinks))
  2972. return NULL;
  2973. #endif
  2974. if (PySys_Audit("os.chmod", "Oii", path->object, mode,
  2975. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  2976. return NULL;
  2977. }
  2978. #ifdef MS_WINDOWS
  2979. Py_BEGIN_ALLOW_THREADS
  2980. attr = GetFileAttributesW(path->wide);
  2981. if (attr == INVALID_FILE_ATTRIBUTES)
  2982. result = 0;
  2983. else {
  2984. if (mode & _S_IWRITE)
  2985. attr &= ~FILE_ATTRIBUTE_READONLY;
  2986. else
  2987. attr |= FILE_ATTRIBUTE_READONLY;
  2988. result = SetFileAttributesW(path->wide, attr);
  2989. }
  2990. Py_END_ALLOW_THREADS
  2991. if (!result) {
  2992. return path_error(path);
  2993. }
  2994. #else /* MS_WINDOWS */
  2995. Py_BEGIN_ALLOW_THREADS
  2996. #ifdef HAVE_FCHMOD
  2997. if (path->fd != -1)
  2998. result = fchmod(path->fd, mode);
  2999. else
  3000. #endif /* HAVE_CHMOD */
  3001. #ifdef HAVE_LCHMOD
  3002. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  3003. result = lchmod(path->narrow, mode);
  3004. else
  3005. #endif /* HAVE_LCHMOD */
  3006. #ifdef HAVE_FCHMODAT
  3007. if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
  3008. if (HAVE_FCHMODAT_RUNTIME) {
  3009. /*
  3010. * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
  3011. * The documentation specifically shows how to use it,
  3012. * and then says it isn't implemented yet.
  3013. * (true on linux with glibc 2.15, and openindiana 3.x)
  3014. *
  3015. * Once it is supported, os.chmod will automatically
  3016. * support dir_fd and follow_symlinks=False. (Hopefully.)
  3017. * Until then, we need to be careful what exception we raise.
  3018. */
  3019. result = fchmodat(dir_fd, path->narrow, mode,
  3020. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  3021. /*
  3022. * But wait! We can't throw the exception without allowing threads,
  3023. * and we can't do that in this nested scope. (Macro trickery, sigh.)
  3024. */
  3025. fchmodat_nofollow_unsupported =
  3026. result &&
  3027. ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
  3028. !follow_symlinks;
  3029. } else {
  3030. fchmodat_unsupported = 1;
  3031. fchmodat_nofollow_unsupported = 1;
  3032. result = -1;
  3033. }
  3034. }
  3035. else
  3036. #endif /* HAVE_FHCMODAT */
  3037. {
  3038. #ifdef HAVE_CHMOD
  3039. result = chmod(path->narrow, mode);
  3040. #elif defined(__wasi__)
  3041. // WASI SDK 15.0 does not support chmod.
  3042. // Ignore missing syscall for now.
  3043. result = 0;
  3044. #else
  3045. result = -1;
  3046. errno = ENOSYS;
  3047. #endif
  3048. }
  3049. Py_END_ALLOW_THREADS
  3050. if (result) {
  3051. #ifdef HAVE_FCHMODAT
  3052. if (fchmodat_unsupported) {
  3053. if (dir_fd != DEFAULT_DIR_FD) {
  3054. argument_unavailable_error("chmod", "dir_fd");
  3055. return NULL;
  3056. }
  3057. }
  3058. if (fchmodat_nofollow_unsupported) {
  3059. if (dir_fd != DEFAULT_DIR_FD)
  3060. dir_fd_and_follow_symlinks_invalid("chmod",
  3061. dir_fd, follow_symlinks);
  3062. else
  3063. follow_symlinks_specified("chmod", follow_symlinks);
  3064. return NULL;
  3065. }
  3066. else
  3067. #endif /* HAVE_FCHMODAT */
  3068. return path_error(path);
  3069. }
  3070. #endif /* MS_WINDOWS */
  3071. Py_RETURN_NONE;
  3072. }
  3073. #ifdef HAVE_FCHMOD
  3074. /*[clinic input]
  3075. os.fchmod
  3076. fd: int
  3077. The file descriptor of the file to be modified.
  3078. mode: int
  3079. Operating-system mode bitfield.
  3080. Be careful when using number literals for *mode*. The conventional UNIX notation for
  3081. numeric modes uses an octal base, which needs to be indicated with a ``0o`` prefix in
  3082. Python.
  3083. Change the access permissions of the file given by file descriptor fd.
  3084. Equivalent to os.chmod(fd, mode).
  3085. [clinic start generated code]*/
  3086. static PyObject *
  3087. os_fchmod_impl(PyObject *module, int fd, int mode)
  3088. /*[clinic end generated code: output=afd9bc05b4e426b3 input=b5594618bbbc22df]*/
  3089. {
  3090. int res;
  3091. int async_err = 0;
  3092. if (PySys_Audit("os.chmod", "iii", fd, mode, -1) < 0) {
  3093. return NULL;
  3094. }
  3095. do {
  3096. Py_BEGIN_ALLOW_THREADS
  3097. res = fchmod(fd, mode);
  3098. Py_END_ALLOW_THREADS
  3099. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  3100. if (res != 0)
  3101. return (!async_err) ? posix_error() : NULL;
  3102. Py_RETURN_NONE;
  3103. }
  3104. #endif /* HAVE_FCHMOD */
  3105. #ifdef HAVE_LCHMOD
  3106. /*[clinic input]
  3107. os.lchmod
  3108. path: path_t
  3109. mode: int
  3110. Change the access permissions of a file, without following symbolic links.
  3111. If path is a symlink, this affects the link itself rather than the target.
  3112. Equivalent to chmod(path, mode, follow_symlinks=False)."
  3113. [clinic start generated code]*/
  3114. static PyObject *
  3115. os_lchmod_impl(PyObject *module, path_t *path, int mode)
  3116. /*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
  3117. {
  3118. int res;
  3119. if (PySys_Audit("os.chmod", "Oii", path->object, mode, -1) < 0) {
  3120. return NULL;
  3121. }
  3122. Py_BEGIN_ALLOW_THREADS
  3123. res = lchmod(path->narrow, mode);
  3124. Py_END_ALLOW_THREADS
  3125. if (res < 0) {
  3126. path_error(path);
  3127. return NULL;
  3128. }
  3129. Py_RETURN_NONE;
  3130. }
  3131. #endif /* HAVE_LCHMOD */
  3132. #ifdef HAVE_CHFLAGS
  3133. /*[clinic input]
  3134. os.chflags
  3135. path: path_t
  3136. flags: unsigned_long(bitwise=True)
  3137. follow_symlinks: bool=True
  3138. Set file flags.
  3139. If follow_symlinks is False, and the last element of the path is a symbolic
  3140. link, chflags will change flags on the symbolic link itself instead of the
  3141. file the link points to.
  3142. follow_symlinks may not be implemented on your platform. If it is
  3143. unavailable, using it will raise a NotImplementedError.
  3144. [clinic start generated code]*/
  3145. static PyObject *
  3146. os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
  3147. int follow_symlinks)
  3148. /*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
  3149. {
  3150. int result;
  3151. #ifndef HAVE_LCHFLAGS
  3152. if (follow_symlinks_specified("chflags", follow_symlinks))
  3153. return NULL;
  3154. #endif
  3155. if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
  3156. return NULL;
  3157. }
  3158. Py_BEGIN_ALLOW_THREADS
  3159. #ifdef HAVE_LCHFLAGS
  3160. if (!follow_symlinks)
  3161. result = lchflags(path->narrow, flags);
  3162. else
  3163. #endif
  3164. result = chflags(path->narrow, flags);
  3165. Py_END_ALLOW_THREADS
  3166. if (result)
  3167. return path_error(path);
  3168. Py_RETURN_NONE;
  3169. }
  3170. #endif /* HAVE_CHFLAGS */
  3171. #ifdef HAVE_LCHFLAGS
  3172. /*[clinic input]
  3173. os.lchflags
  3174. path: path_t
  3175. flags: unsigned_long(bitwise=True)
  3176. Set file flags.
  3177. This function will not follow symbolic links.
  3178. Equivalent to chflags(path, flags, follow_symlinks=False).
  3179. [clinic start generated code]*/
  3180. static PyObject *
  3181. os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
  3182. /*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
  3183. {
  3184. int res;
  3185. if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
  3186. return NULL;
  3187. }
  3188. Py_BEGIN_ALLOW_THREADS
  3189. res = lchflags(path->narrow, flags);
  3190. Py_END_ALLOW_THREADS
  3191. if (res < 0) {
  3192. return path_error(path);
  3193. }
  3194. Py_RETURN_NONE;
  3195. }
  3196. #endif /* HAVE_LCHFLAGS */
  3197. #ifdef HAVE_CHROOT
  3198. /*[clinic input]
  3199. os.chroot
  3200. path: path_t
  3201. Change root directory to path.
  3202. [clinic start generated code]*/
  3203. static PyObject *
  3204. os_chroot_impl(PyObject *module, path_t *path)
  3205. /*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
  3206. {
  3207. int res;
  3208. Py_BEGIN_ALLOW_THREADS
  3209. res = chroot(path->narrow);
  3210. Py_END_ALLOW_THREADS
  3211. if (res < 0)
  3212. return path_error(path);
  3213. Py_RETURN_NONE;
  3214. }
  3215. #endif /* HAVE_CHROOT */
  3216. #ifdef HAVE_FSYNC
  3217. /*[clinic input]
  3218. os.fsync
  3219. fd: fildes
  3220. Force write of fd to disk.
  3221. [clinic start generated code]*/
  3222. static PyObject *
  3223. os_fsync_impl(PyObject *module, int fd)
  3224. /*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
  3225. {
  3226. return posix_fildes_fd(fd, fsync);
  3227. }
  3228. #endif /* HAVE_FSYNC */
  3229. #ifdef HAVE_SYNC
  3230. /*[clinic input]
  3231. os.sync
  3232. Force write of everything to disk.
  3233. [clinic start generated code]*/
  3234. static PyObject *
  3235. os_sync_impl(PyObject *module)
  3236. /*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
  3237. {
  3238. Py_BEGIN_ALLOW_THREADS
  3239. sync();
  3240. Py_END_ALLOW_THREADS
  3241. Py_RETURN_NONE;
  3242. }
  3243. #endif /* HAVE_SYNC */
  3244. #ifdef HAVE_FDATASYNC
  3245. #ifdef __hpux
  3246. extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
  3247. #endif
  3248. /*[clinic input]
  3249. os.fdatasync
  3250. fd: fildes
  3251. Force write of fd to disk without forcing update of metadata.
  3252. [clinic start generated code]*/
  3253. static PyObject *
  3254. os_fdatasync_impl(PyObject *module, int fd)
  3255. /*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
  3256. {
  3257. return posix_fildes_fd(fd, fdatasync);
  3258. }
  3259. #endif /* HAVE_FDATASYNC */
  3260. #ifdef HAVE_CHOWN
  3261. /*[clinic input]
  3262. os.chown
  3263. path : path_t(allow_fd='PATH_HAVE_FCHOWN')
  3264. Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
  3265. uid: uid_t
  3266. gid: gid_t
  3267. *
  3268. dir_fd : dir_fd(requires='fchownat') = None
  3269. If not None, it should be a file descriptor open to a directory,
  3270. and path should be relative; path will then be relative to that
  3271. directory.
  3272. follow_symlinks: bool = True
  3273. If False, and the last element of the path is a symbolic link,
  3274. stat will examine the symbolic link itself instead of the file
  3275. the link points to.
  3276. Change the owner and group id of path to the numeric uid and gid.\
  3277. path may always be specified as a string.
  3278. On some platforms, path may also be specified as an open file descriptor.
  3279. If this functionality is unavailable, using it raises an exception.
  3280. If dir_fd is not None, it should be a file descriptor open to a directory,
  3281. and path should be relative; path will then be relative to that directory.
  3282. If follow_symlinks is False, and the last element of the path is a symbolic
  3283. link, chown will modify the symbolic link itself instead of the file the
  3284. link points to.
  3285. It is an error to use dir_fd or follow_symlinks when specifying path as
  3286. an open file descriptor.
  3287. dir_fd and follow_symlinks may not be implemented on your platform.
  3288. If they are unavailable, using them will raise a NotImplementedError.
  3289. [clinic start generated code]*/
  3290. static PyObject *
  3291. os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
  3292. int dir_fd, int follow_symlinks)
  3293. /*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
  3294. {
  3295. int result;
  3296. #if defined(HAVE_FCHOWNAT)
  3297. int fchownat_unsupported = 0;
  3298. #endif
  3299. #if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
  3300. if (follow_symlinks_specified("chown", follow_symlinks))
  3301. return NULL;
  3302. #endif
  3303. if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
  3304. fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
  3305. return NULL;
  3306. if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid,
  3307. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  3308. return NULL;
  3309. }
  3310. Py_BEGIN_ALLOW_THREADS
  3311. #ifdef HAVE_FCHOWN
  3312. if (path->fd != -1)
  3313. result = fchown(path->fd, uid, gid);
  3314. else
  3315. #endif
  3316. #ifdef HAVE_LCHOWN
  3317. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  3318. result = lchown(path->narrow, uid, gid);
  3319. else
  3320. #endif
  3321. #ifdef HAVE_FCHOWNAT
  3322. if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks)) {
  3323. if (HAVE_FCHOWNAT_RUNTIME) {
  3324. result = fchownat(dir_fd, path->narrow, uid, gid,
  3325. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  3326. } else {
  3327. fchownat_unsupported = 1;
  3328. }
  3329. } else
  3330. #endif
  3331. result = chown(path->narrow, uid, gid);
  3332. Py_END_ALLOW_THREADS
  3333. #ifdef HAVE_FCHOWNAT
  3334. if (fchownat_unsupported) {
  3335. /* This would be incorrect if the current platform
  3336. * doesn't support lchown.
  3337. */
  3338. argument_unavailable_error(NULL, "dir_fd");
  3339. return NULL;
  3340. }
  3341. #endif
  3342. if (result)
  3343. return path_error(path);
  3344. Py_RETURN_NONE;
  3345. }
  3346. #endif /* HAVE_CHOWN */
  3347. #ifdef HAVE_FCHOWN
  3348. /*[clinic input]
  3349. os.fchown
  3350. fd: int
  3351. uid: uid_t
  3352. gid: gid_t
  3353. Change the owner and group id of the file specified by file descriptor.
  3354. Equivalent to os.chown(fd, uid, gid).
  3355. [clinic start generated code]*/
  3356. static PyObject *
  3357. os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
  3358. /*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
  3359. {
  3360. int res;
  3361. int async_err = 0;
  3362. if (PySys_Audit("os.chown", "iIIi", fd, uid, gid, -1) < 0) {
  3363. return NULL;
  3364. }
  3365. do {
  3366. Py_BEGIN_ALLOW_THREADS
  3367. res = fchown(fd, uid, gid);
  3368. Py_END_ALLOW_THREADS
  3369. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  3370. if (res != 0)
  3371. return (!async_err) ? posix_error() : NULL;
  3372. Py_RETURN_NONE;
  3373. }
  3374. #endif /* HAVE_FCHOWN */
  3375. #ifdef HAVE_LCHOWN
  3376. /*[clinic input]
  3377. os.lchown
  3378. path : path_t
  3379. uid: uid_t
  3380. gid: gid_t
  3381. Change the owner and group id of path to the numeric uid and gid.
  3382. This function will not follow symbolic links.
  3383. Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
  3384. [clinic start generated code]*/
  3385. static PyObject *
  3386. os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
  3387. /*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
  3388. {
  3389. int res;
  3390. if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid, -1) < 0) {
  3391. return NULL;
  3392. }
  3393. Py_BEGIN_ALLOW_THREADS
  3394. res = lchown(path->narrow, uid, gid);
  3395. Py_END_ALLOW_THREADS
  3396. if (res < 0) {
  3397. return path_error(path);
  3398. }
  3399. Py_RETURN_NONE;
  3400. }
  3401. #endif /* HAVE_LCHOWN */
  3402. static PyObject *
  3403. posix_getcwd(int use_bytes)
  3404. {
  3405. #ifdef MS_WINDOWS
  3406. wchar_t wbuf[MAXPATHLEN];
  3407. wchar_t *wbuf2 = wbuf;
  3408. DWORD len;
  3409. Py_BEGIN_ALLOW_THREADS
  3410. len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
  3411. /* If the buffer is large enough, len does not include the
  3412. terminating \0. If the buffer is too small, len includes
  3413. the space needed for the terminator. */
  3414. if (len >= Py_ARRAY_LENGTH(wbuf)) {
  3415. if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  3416. wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
  3417. }
  3418. else {
  3419. wbuf2 = NULL;
  3420. }
  3421. if (wbuf2) {
  3422. len = GetCurrentDirectoryW(len, wbuf2);
  3423. }
  3424. }
  3425. Py_END_ALLOW_THREADS
  3426. if (!wbuf2) {
  3427. PyErr_NoMemory();
  3428. return NULL;
  3429. }
  3430. if (!len) {
  3431. PyErr_SetFromWindowsErr(0);
  3432. if (wbuf2 != wbuf)
  3433. PyMem_RawFree(wbuf2);
  3434. return NULL;
  3435. }
  3436. PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
  3437. if (wbuf2 != wbuf) {
  3438. PyMem_RawFree(wbuf2);
  3439. }
  3440. if (use_bytes) {
  3441. if (resobj == NULL) {
  3442. return NULL;
  3443. }
  3444. Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
  3445. }
  3446. return resobj;
  3447. #else
  3448. const size_t chunk = 1024;
  3449. char *buf = NULL;
  3450. char *cwd = NULL;
  3451. size_t buflen = 0;
  3452. Py_BEGIN_ALLOW_THREADS
  3453. do {
  3454. char *newbuf;
  3455. if (buflen <= PY_SSIZE_T_MAX - chunk) {
  3456. buflen += chunk;
  3457. newbuf = PyMem_RawRealloc(buf, buflen);
  3458. }
  3459. else {
  3460. newbuf = NULL;
  3461. }
  3462. if (newbuf == NULL) {
  3463. PyMem_RawFree(buf);
  3464. buf = NULL;
  3465. break;
  3466. }
  3467. buf = newbuf;
  3468. cwd = getcwd(buf, buflen);
  3469. } while (cwd == NULL && errno == ERANGE);
  3470. Py_END_ALLOW_THREADS
  3471. if (buf == NULL) {
  3472. return PyErr_NoMemory();
  3473. }
  3474. if (cwd == NULL) {
  3475. posix_error();
  3476. PyMem_RawFree(buf);
  3477. return NULL;
  3478. }
  3479. PyObject *obj;
  3480. if (use_bytes) {
  3481. obj = PyBytes_FromStringAndSize(buf, strlen(buf));
  3482. }
  3483. else {
  3484. obj = PyUnicode_DecodeFSDefault(buf);
  3485. }
  3486. PyMem_RawFree(buf);
  3487. return obj;
  3488. #endif /* !MS_WINDOWS */
  3489. }
  3490. /*[clinic input]
  3491. os.getcwd
  3492. Return a unicode string representing the current working directory.
  3493. [clinic start generated code]*/
  3494. static PyObject *
  3495. os_getcwd_impl(PyObject *module)
  3496. /*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
  3497. {
  3498. return posix_getcwd(0);
  3499. }
  3500. /*[clinic input]
  3501. os.getcwdb
  3502. Return a bytes string representing the current working directory.
  3503. [clinic start generated code]*/
  3504. static PyObject *
  3505. os_getcwdb_impl(PyObject *module)
  3506. /*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
  3507. {
  3508. return posix_getcwd(1);
  3509. }
  3510. #if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
  3511. #define HAVE_LINK 1
  3512. #endif
  3513. #ifdef HAVE_LINK
  3514. /*[clinic input]
  3515. os.link
  3516. src : path_t
  3517. dst : path_t
  3518. *
  3519. src_dir_fd : dir_fd = None
  3520. dst_dir_fd : dir_fd = None
  3521. follow_symlinks: bool = True
  3522. Create a hard link to a file.
  3523. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  3524. descriptor open to a directory, and the respective path string (src or dst)
  3525. should be relative; the path will then be relative to that directory.
  3526. If follow_symlinks is False, and the last element of src is a symbolic
  3527. link, link will create a link to the symbolic link itself instead of the
  3528. file the link points to.
  3529. src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
  3530. platform. If they are unavailable, using them will raise a
  3531. NotImplementedError.
  3532. [clinic start generated code]*/
  3533. static PyObject *
  3534. os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  3535. int dst_dir_fd, int follow_symlinks)
  3536. /*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
  3537. {
  3538. #ifdef MS_WINDOWS
  3539. BOOL result = FALSE;
  3540. #else
  3541. int result;
  3542. #endif
  3543. #if defined(HAVE_LINKAT)
  3544. int linkat_unavailable = 0;
  3545. #endif
  3546. #ifndef HAVE_LINKAT
  3547. if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
  3548. argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
  3549. return NULL;
  3550. }
  3551. #endif
  3552. #ifndef MS_WINDOWS
  3553. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  3554. PyErr_SetString(PyExc_NotImplementedError,
  3555. "link: src and dst must be the same type");
  3556. return NULL;
  3557. }
  3558. #endif
  3559. if (PySys_Audit("os.link", "OOii", src->object, dst->object,
  3560. src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
  3561. dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
  3562. return NULL;
  3563. }
  3564. #ifdef MS_WINDOWS
  3565. Py_BEGIN_ALLOW_THREADS
  3566. result = CreateHardLinkW(dst->wide, src->wide, NULL);
  3567. Py_END_ALLOW_THREADS
  3568. if (!result)
  3569. return path_error2(src, dst);
  3570. #else
  3571. Py_BEGIN_ALLOW_THREADS
  3572. #ifdef HAVE_LINKAT
  3573. if ((src_dir_fd != DEFAULT_DIR_FD) ||
  3574. (dst_dir_fd != DEFAULT_DIR_FD) ||
  3575. (!follow_symlinks)) {
  3576. if (HAVE_LINKAT_RUNTIME) {
  3577. result = linkat(src_dir_fd, src->narrow,
  3578. dst_dir_fd, dst->narrow,
  3579. follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
  3580. }
  3581. #ifdef __APPLE__
  3582. else {
  3583. if (src_dir_fd == DEFAULT_DIR_FD && dst_dir_fd == DEFAULT_DIR_FD) {
  3584. /* See issue 41355: This matches the behaviour of !HAVE_LINKAT */
  3585. result = link(src->narrow, dst->narrow);
  3586. } else {
  3587. linkat_unavailable = 1;
  3588. }
  3589. }
  3590. #endif
  3591. }
  3592. else
  3593. #endif /* HAVE_LINKAT */
  3594. result = link(src->narrow, dst->narrow);
  3595. Py_END_ALLOW_THREADS
  3596. #ifdef HAVE_LINKAT
  3597. if (linkat_unavailable) {
  3598. /* Either or both dir_fd arguments were specified */
  3599. if (src_dir_fd != DEFAULT_DIR_FD) {
  3600. argument_unavailable_error("link", "src_dir_fd");
  3601. } else {
  3602. argument_unavailable_error("link", "dst_dir_fd");
  3603. }
  3604. return NULL;
  3605. }
  3606. #endif
  3607. if (result)
  3608. return path_error2(src, dst);
  3609. #endif /* MS_WINDOWS */
  3610. Py_RETURN_NONE;
  3611. }
  3612. #endif
  3613. #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
  3614. static PyObject *
  3615. _listdir_windows_no_opendir(path_t *path, PyObject *list)
  3616. {
  3617. PyObject *v;
  3618. HANDLE hFindFile = INVALID_HANDLE_VALUE;
  3619. BOOL result, return_bytes;
  3620. wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
  3621. /* only claim to have space for MAX_PATH */
  3622. Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
  3623. wchar_t *wnamebuf = NULL;
  3624. WIN32_FIND_DATAW wFileData;
  3625. const wchar_t *po_wchars;
  3626. if (!path->wide) { /* Default arg: "." */
  3627. po_wchars = L".";
  3628. len = 1;
  3629. return_bytes = 0;
  3630. } else {
  3631. po_wchars = path->wide;
  3632. len = wcslen(path->wide);
  3633. return_bytes = PyBytes_Check(path->object);
  3634. }
  3635. /* The +5 is so we can append "\\*.*\0" */
  3636. wnamebuf = PyMem_New(wchar_t, len + 5);
  3637. if (!wnamebuf) {
  3638. PyErr_NoMemory();
  3639. goto exit;
  3640. }
  3641. wcscpy(wnamebuf, po_wchars);
  3642. if (len > 0) {
  3643. wchar_t wch = wnamebuf[len-1];
  3644. if (wch != SEP && wch != ALTSEP && wch != L':')
  3645. wnamebuf[len++] = SEP;
  3646. wcscpy(wnamebuf + len, L"*.*");
  3647. }
  3648. if ((list = PyList_New(0)) == NULL) {
  3649. goto exit;
  3650. }
  3651. Py_BEGIN_ALLOW_THREADS
  3652. hFindFile = FindFirstFileW(wnamebuf, &wFileData);
  3653. Py_END_ALLOW_THREADS
  3654. if (hFindFile == INVALID_HANDLE_VALUE) {
  3655. int error = GetLastError();
  3656. if (error == ERROR_FILE_NOT_FOUND)
  3657. goto exit;
  3658. path_error(path);
  3659. Py_CLEAR(list);
  3660. goto exit;
  3661. }
  3662. do {
  3663. /* Skip over . and .. */
  3664. if (wcscmp(wFileData.cFileName, L".") != 0 &&
  3665. wcscmp(wFileData.cFileName, L"..") != 0) {
  3666. v = PyUnicode_FromWideChar(wFileData.cFileName,
  3667. wcslen(wFileData.cFileName));
  3668. if (return_bytes && v) {
  3669. Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
  3670. }
  3671. if (v == NULL) {
  3672. Py_CLEAR(list);
  3673. break;
  3674. }
  3675. if (PyList_Append(list, v) != 0) {
  3676. Py_DECREF(v);
  3677. Py_CLEAR(list);
  3678. break;
  3679. }
  3680. Py_DECREF(v);
  3681. }
  3682. Py_BEGIN_ALLOW_THREADS
  3683. result = FindNextFileW(hFindFile, &wFileData);
  3684. Py_END_ALLOW_THREADS
  3685. /* FindNextFile sets error to ERROR_NO_MORE_FILES if
  3686. it got to the end of the directory. */
  3687. if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
  3688. path_error(path);
  3689. Py_CLEAR(list);
  3690. goto exit;
  3691. }
  3692. } while (result == TRUE);
  3693. exit:
  3694. if (hFindFile != INVALID_HANDLE_VALUE) {
  3695. if (FindClose(hFindFile) == FALSE) {
  3696. if (list != NULL) {
  3697. path_error(path);
  3698. Py_CLEAR(list);
  3699. }
  3700. }
  3701. }
  3702. PyMem_Free(wnamebuf);
  3703. return list;
  3704. } /* end of _listdir_windows_no_opendir */
  3705. #else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
  3706. static PyObject *
  3707. _posix_listdir(path_t *path, PyObject *list)
  3708. {
  3709. PyObject *v;
  3710. DIR *dirp = NULL;
  3711. struct dirent *ep;
  3712. int return_str; /* if false, return bytes */
  3713. #ifdef HAVE_FDOPENDIR
  3714. int fd = -1;
  3715. #endif
  3716. errno = 0;
  3717. #ifdef HAVE_FDOPENDIR
  3718. if (path->fd != -1) {
  3719. if (HAVE_FDOPENDIR_RUNTIME) {
  3720. /* closedir() closes the FD, so we duplicate it */
  3721. fd = _Py_dup(path->fd);
  3722. if (fd == -1)
  3723. return NULL;
  3724. return_str = 1;
  3725. Py_BEGIN_ALLOW_THREADS
  3726. dirp = fdopendir(fd);
  3727. Py_END_ALLOW_THREADS
  3728. } else {
  3729. PyErr_SetString(PyExc_TypeError,
  3730. "listdir: path should be string, bytes, os.PathLike or None, not int");
  3731. return NULL;
  3732. }
  3733. }
  3734. else
  3735. #endif
  3736. {
  3737. const char *name;
  3738. if (path->narrow) {
  3739. name = path->narrow;
  3740. /* only return bytes if they specified a bytes object */
  3741. return_str = !PyBytes_Check(path->object);
  3742. }
  3743. else {
  3744. name = ".";
  3745. return_str = 1;
  3746. }
  3747. Py_BEGIN_ALLOW_THREADS
  3748. dirp = opendir(name);
  3749. Py_END_ALLOW_THREADS
  3750. }
  3751. if (dirp == NULL) {
  3752. path_error(path);
  3753. list = NULL;
  3754. #ifdef HAVE_FDOPENDIR
  3755. if (fd != -1) {
  3756. Py_BEGIN_ALLOW_THREADS
  3757. close(fd);
  3758. Py_END_ALLOW_THREADS
  3759. }
  3760. #endif
  3761. goto exit;
  3762. }
  3763. if ((list = PyList_New(0)) == NULL) {
  3764. goto exit;
  3765. }
  3766. for (;;) {
  3767. errno = 0;
  3768. Py_BEGIN_ALLOW_THREADS
  3769. ep = readdir(dirp);
  3770. Py_END_ALLOW_THREADS
  3771. if (ep == NULL) {
  3772. if (errno == 0) {
  3773. break;
  3774. } else {
  3775. path_error(path);
  3776. Py_CLEAR(list);
  3777. goto exit;
  3778. }
  3779. }
  3780. if (ep->d_name[0] == '.' &&
  3781. (NAMLEN(ep) == 1 ||
  3782. (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
  3783. continue;
  3784. if (return_str)
  3785. v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
  3786. else
  3787. v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
  3788. if (v == NULL) {
  3789. Py_CLEAR(list);
  3790. break;
  3791. }
  3792. if (PyList_Append(list, v) != 0) {
  3793. Py_DECREF(v);
  3794. Py_CLEAR(list);
  3795. break;
  3796. }
  3797. Py_DECREF(v);
  3798. }
  3799. exit:
  3800. if (dirp != NULL) {
  3801. Py_BEGIN_ALLOW_THREADS
  3802. #ifdef HAVE_FDOPENDIR
  3803. if (fd > -1)
  3804. rewinddir(dirp);
  3805. #endif
  3806. closedir(dirp);
  3807. Py_END_ALLOW_THREADS
  3808. }
  3809. return list;
  3810. } /* end of _posix_listdir */
  3811. #endif /* which OS */
  3812. /*[clinic input]
  3813. os.listdir
  3814. path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
  3815. Return a list containing the names of the files in the directory.
  3816. path can be specified as either str, bytes, or a path-like object. If path is bytes,
  3817. the filenames returned will also be bytes; in all other circumstances
  3818. the filenames returned will be str.
  3819. If path is None, uses the path='.'.
  3820. On some platforms, path may also be specified as an open file descriptor;\
  3821. the file descriptor must refer to a directory.
  3822. If this functionality is unavailable, using it raises NotImplementedError.
  3823. The list is in arbitrary order. It does not include the special
  3824. entries '.' and '..' even if they are present in the directory.
  3825. [clinic start generated code]*/
  3826. static PyObject *
  3827. os_listdir_impl(PyObject *module, path_t *path)
  3828. /*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
  3829. {
  3830. if (PySys_Audit("os.listdir", "O",
  3831. path->object ? path->object : Py_None) < 0) {
  3832. return NULL;
  3833. }
  3834. #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
  3835. return _listdir_windows_no_opendir(path, NULL);
  3836. #else
  3837. return _posix_listdir(path, NULL);
  3838. #endif
  3839. }
  3840. #ifdef MS_WINDOWS
  3841. /*[clinic input]
  3842. os.listdrives
  3843. Return a list containing the names of drives in the system.
  3844. A drive name typically looks like 'C:\\'.
  3845. [clinic start generated code]*/
  3846. static PyObject *
  3847. os_listdrives_impl(PyObject *module)
  3848. /*[clinic end generated code: output=aaece9dacdf682b5 input=1af9ccc9e583798e]*/
  3849. {
  3850. /* Number of possible drives is limited, so 256 should always be enough.
  3851. On the day when it is not, listmounts() will have to be used. */
  3852. wchar_t buffer[256];
  3853. DWORD buflen = Py_ARRAY_LENGTH(buffer);
  3854. PyObject *result = NULL;
  3855. if (PySys_Audit("os.listdrives", NULL) < 0) {
  3856. return NULL;
  3857. }
  3858. Py_BEGIN_ALLOW_THREADS;
  3859. buflen = GetLogicalDriveStringsW(buflen, buffer);
  3860. Py_END_ALLOW_THREADS;
  3861. if (!buflen) {
  3862. PyErr_SetFromWindowsErr(0);
  3863. return NULL;
  3864. } else if (buflen >= Py_ARRAY_LENGTH(buffer)) {
  3865. PyErr_SetFromWindowsErr(ERROR_MORE_DATA);
  3866. return NULL;
  3867. }
  3868. /* buflen includes a null terminator, so remove it */
  3869. PyObject *str = PyUnicode_FromWideChar(buffer, buflen - 1);
  3870. if (str) {
  3871. PyObject *nullchar = PyUnicode_FromStringAndSize("\0", 1);
  3872. if (nullchar) {
  3873. result = PyUnicode_Split(str, nullchar, -1);
  3874. Py_DECREF(nullchar);
  3875. }
  3876. Py_DECREF(str);
  3877. }
  3878. return result;
  3879. }
  3880. /*[clinic input]
  3881. os.listvolumes
  3882. Return a list containing the volumes in the system.
  3883. Volumes are typically represented as a GUID path.
  3884. [clinic start generated code]*/
  3885. static PyObject *
  3886. os_listvolumes_impl(PyObject *module)
  3887. /*[clinic end generated code: output=534e10ea2bf9d386 input=f6e4e70371f11e99]*/
  3888. {
  3889. PyObject *result = PyList_New(0);
  3890. HANDLE find = INVALID_HANDLE_VALUE;
  3891. wchar_t buffer[MAX_PATH + 1];
  3892. if (!result) {
  3893. return NULL;
  3894. }
  3895. if (PySys_Audit("os.listvolumes", NULL) < 0) {
  3896. Py_DECREF(result);
  3897. return NULL;
  3898. }
  3899. int err = 0;
  3900. Py_BEGIN_ALLOW_THREADS;
  3901. find = FindFirstVolumeW(buffer, Py_ARRAY_LENGTH(buffer));
  3902. if (find == INVALID_HANDLE_VALUE) {
  3903. err = GetLastError();
  3904. }
  3905. Py_END_ALLOW_THREADS;
  3906. while (!err) {
  3907. PyObject *s = PyUnicode_FromWideChar(buffer, -1);
  3908. if (!s || PyList_Append(result, s) < 0) {
  3909. Py_XDECREF(s);
  3910. Py_CLEAR(result);
  3911. break;
  3912. }
  3913. Py_DECREF(s);
  3914. Py_BEGIN_ALLOW_THREADS;
  3915. if (!FindNextVolumeW(find, buffer, Py_ARRAY_LENGTH(buffer))) {
  3916. err = GetLastError();
  3917. }
  3918. Py_END_ALLOW_THREADS;
  3919. }
  3920. if (find != INVALID_HANDLE_VALUE) {
  3921. Py_BEGIN_ALLOW_THREADS;
  3922. FindVolumeClose(find);
  3923. Py_END_ALLOW_THREADS;
  3924. }
  3925. if (err && err != ERROR_NO_MORE_FILES) {
  3926. PyErr_SetFromWindowsErr(err);
  3927. Py_XDECREF(result);
  3928. result = NULL;
  3929. }
  3930. return result;
  3931. }
  3932. /*[clinic input]
  3933. os.listmounts
  3934. volume: path_t
  3935. Return a list containing mount points for a particular volume.
  3936. 'volume' should be a GUID path as returned from os.listvolumes.
  3937. [clinic start generated code]*/
  3938. static PyObject *
  3939. os_listmounts_impl(PyObject *module, path_t *volume)
  3940. /*[clinic end generated code: output=06da49679de4512e input=a8a27178e3f67845]*/
  3941. {
  3942. wchar_t default_buffer[MAX_PATH + 1];
  3943. DWORD buflen = Py_ARRAY_LENGTH(default_buffer);
  3944. LPWSTR buffer = default_buffer;
  3945. DWORD attributes;
  3946. PyObject *str = NULL;
  3947. PyObject *nullchar = NULL;
  3948. PyObject *result = NULL;
  3949. /* Ensure we have a valid volume path before continuing */
  3950. Py_BEGIN_ALLOW_THREADS
  3951. attributes = GetFileAttributesW(volume->wide);
  3952. Py_END_ALLOW_THREADS
  3953. if (attributes == INVALID_FILE_ATTRIBUTES &&
  3954. GetLastError() == ERROR_UNRECOGNIZED_VOLUME)
  3955. {
  3956. return PyErr_SetFromWindowsErr(ERROR_UNRECOGNIZED_VOLUME);
  3957. }
  3958. if (PySys_Audit("os.listmounts", "O", volume->object) < 0) {
  3959. return NULL;
  3960. }
  3961. while (1) {
  3962. BOOL success;
  3963. Py_BEGIN_ALLOW_THREADS
  3964. success = GetVolumePathNamesForVolumeNameW(volume->wide, buffer,
  3965. buflen, &buflen);
  3966. Py_END_ALLOW_THREADS
  3967. if (success) {
  3968. break;
  3969. }
  3970. if (GetLastError() != ERROR_MORE_DATA) {
  3971. PyErr_SetFromWindowsErr(0);
  3972. goto exit;
  3973. }
  3974. if (buffer != default_buffer) {
  3975. PyMem_Free((void *)buffer);
  3976. }
  3977. buffer = (wchar_t*)PyMem_Malloc(sizeof(wchar_t) * buflen);
  3978. if (!buffer) {
  3979. PyErr_NoMemory();
  3980. goto exit;
  3981. }
  3982. }
  3983. if (buflen < 2) {
  3984. result = PyList_New(0);
  3985. goto exit;
  3986. }
  3987. // buflen includes two null terminators, one for the last string
  3988. // and one for the array of strings.
  3989. str = PyUnicode_FromWideChar(buffer, buflen - 2);
  3990. nullchar = PyUnicode_FromStringAndSize("\0", 1);
  3991. if (str && nullchar) {
  3992. result = PyUnicode_Split(str, nullchar, -1);
  3993. }
  3994. exit:
  3995. if (buffer != default_buffer) {
  3996. PyMem_Free(buffer);
  3997. }
  3998. Py_XDECREF(nullchar);
  3999. Py_XDECREF(str);
  4000. return result;
  4001. }
  4002. /*[clinic input]
  4003. os._path_isdevdrive
  4004. path: path_t
  4005. Determines whether the specified path is on a Windows Dev Drive.
  4006. [clinic start generated code]*/
  4007. static PyObject *
  4008. os__path_isdevdrive_impl(PyObject *module, path_t *path)
  4009. /*[clinic end generated code: output=1f437ea6677433a2 input=ee83e4996a48e23d]*/
  4010. {
  4011. #ifndef PERSISTENT_VOLUME_STATE_DEV_VOLUME
  4012. /* This flag will be documented at
  4013. https://learn.microsoft.com/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_fs_persistent_volume_information
  4014. after release, and will be available in the latest WinSDK.
  4015. We include the flag to avoid a specific version dependency
  4016. on the latest WinSDK. */
  4017. const int PERSISTENT_VOLUME_STATE_DEV_VOLUME = 0x00002000;
  4018. #endif
  4019. int err = 0;
  4020. PyObject *r = NULL;
  4021. wchar_t volume[MAX_PATH];
  4022. Py_BEGIN_ALLOW_THREADS
  4023. if (!GetVolumePathNameW(path->wide, volume, MAX_PATH)) {
  4024. /* invalid path of some kind */
  4025. /* Note that this also includes the case where a volume is mounted
  4026. in a path longer than 260 characters. This is likely to be rare
  4027. and problematic for other reasons, so a (soft) failure in this
  4028. check seems okay. */
  4029. err = GetLastError();
  4030. } else if (GetDriveTypeW(volume) != DRIVE_FIXED) {
  4031. /* only care about local dev drives */
  4032. r = Py_False;
  4033. } else {
  4034. HANDLE hVolume = CreateFileW(
  4035. volume,
  4036. FILE_READ_ATTRIBUTES,
  4037. FILE_SHARE_READ | FILE_SHARE_WRITE,
  4038. NULL,
  4039. OPEN_EXISTING,
  4040. FILE_FLAG_BACKUP_SEMANTICS,
  4041. NULL
  4042. );
  4043. if (hVolume == INVALID_HANDLE_VALUE) {
  4044. err = GetLastError();
  4045. } else {
  4046. FILE_FS_PERSISTENT_VOLUME_INFORMATION volumeState = {0};
  4047. volumeState.Version = 1;
  4048. volumeState.FlagMask = PERSISTENT_VOLUME_STATE_DEV_VOLUME;
  4049. if (!DeviceIoControl(
  4050. hVolume,
  4051. FSCTL_QUERY_PERSISTENT_VOLUME_STATE,
  4052. &volumeState,
  4053. sizeof(volumeState),
  4054. &volumeState,
  4055. sizeof(volumeState),
  4056. NULL,
  4057. NULL
  4058. )) {
  4059. err = GetLastError();
  4060. }
  4061. CloseHandle(hVolume);
  4062. if (err == ERROR_INVALID_PARAMETER) {
  4063. /* not supported on this platform */
  4064. r = Py_False;
  4065. } else if (!err) {
  4066. r = (volumeState.VolumeFlags & PERSISTENT_VOLUME_STATE_DEV_VOLUME)
  4067. ? Py_True : Py_False;
  4068. }
  4069. }
  4070. }
  4071. Py_END_ALLOW_THREADS
  4072. if (err) {
  4073. PyErr_SetFromWindowsErr(err);
  4074. return NULL;
  4075. }
  4076. if (r) {
  4077. return Py_NewRef(r);
  4078. }
  4079. return NULL;
  4080. }
  4081. int
  4082. _PyOS_getfullpathname(const wchar_t *path, wchar_t **abspath_p)
  4083. {
  4084. wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
  4085. DWORD result;
  4086. result = GetFullPathNameW(path,
  4087. Py_ARRAY_LENGTH(woutbuf), woutbuf,
  4088. NULL);
  4089. if (!result) {
  4090. return -1;
  4091. }
  4092. if (result >= Py_ARRAY_LENGTH(woutbuf)) {
  4093. if ((size_t)result <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  4094. woutbufp = PyMem_RawMalloc((size_t)result * sizeof(wchar_t));
  4095. }
  4096. else {
  4097. woutbufp = NULL;
  4098. }
  4099. if (!woutbufp) {
  4100. *abspath_p = NULL;
  4101. return 0;
  4102. }
  4103. result = GetFullPathNameW(path, result, woutbufp, NULL);
  4104. if (!result) {
  4105. PyMem_RawFree(woutbufp);
  4106. return -1;
  4107. }
  4108. }
  4109. if (woutbufp != woutbuf) {
  4110. *abspath_p = woutbufp;
  4111. return 0;
  4112. }
  4113. *abspath_p = _PyMem_RawWcsdup(woutbufp);
  4114. return 0;
  4115. }
  4116. /* A helper function for abspath on win32 */
  4117. /*[clinic input]
  4118. os._getfullpathname
  4119. path: path_t
  4120. /
  4121. [clinic start generated code]*/
  4122. static PyObject *
  4123. os__getfullpathname_impl(PyObject *module, path_t *path)
  4124. /*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
  4125. {
  4126. wchar_t *abspath;
  4127. if (_PyOS_getfullpathname(path->wide, &abspath) < 0) {
  4128. return win32_error_object("GetFullPathNameW", path->object);
  4129. }
  4130. if (abspath == NULL) {
  4131. return PyErr_NoMemory();
  4132. }
  4133. PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
  4134. PyMem_RawFree(abspath);
  4135. if (str == NULL) {
  4136. return NULL;
  4137. }
  4138. if (PyBytes_Check(path->object)) {
  4139. Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
  4140. }
  4141. return str;
  4142. }
  4143. /*[clinic input]
  4144. os._getfinalpathname
  4145. path: path_t
  4146. /
  4147. A helper function for samepath on windows.
  4148. [clinic start generated code]*/
  4149. static PyObject *
  4150. os__getfinalpathname_impl(PyObject *module, path_t *path)
  4151. /*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
  4152. {
  4153. HANDLE hFile;
  4154. wchar_t buf[MAXPATHLEN], *target_path = buf;
  4155. int buf_size = Py_ARRAY_LENGTH(buf);
  4156. int result_length;
  4157. PyObject *result;
  4158. Py_BEGIN_ALLOW_THREADS
  4159. hFile = CreateFileW(
  4160. path->wide,
  4161. 0, /* desired access */
  4162. 0, /* share mode */
  4163. NULL, /* security attributes */
  4164. OPEN_EXISTING,
  4165. /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
  4166. FILE_FLAG_BACKUP_SEMANTICS,
  4167. NULL);
  4168. Py_END_ALLOW_THREADS
  4169. if (hFile == INVALID_HANDLE_VALUE) {
  4170. return win32_error_object("CreateFileW", path->object);
  4171. }
  4172. /* We have a good handle to the target, use it to determine the
  4173. target path name. */
  4174. while (1) {
  4175. Py_BEGIN_ALLOW_THREADS
  4176. result_length = GetFinalPathNameByHandleW(hFile, target_path,
  4177. buf_size, VOLUME_NAME_DOS);
  4178. Py_END_ALLOW_THREADS
  4179. if (!result_length) {
  4180. result = win32_error_object("GetFinalPathNameByHandleW",
  4181. path->object);
  4182. goto cleanup;
  4183. }
  4184. if (result_length < buf_size) {
  4185. break;
  4186. }
  4187. wchar_t *tmp;
  4188. tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
  4189. result_length * sizeof(*tmp));
  4190. if (!tmp) {
  4191. result = PyErr_NoMemory();
  4192. goto cleanup;
  4193. }
  4194. buf_size = result_length;
  4195. target_path = tmp;
  4196. }
  4197. result = PyUnicode_FromWideChar(target_path, result_length);
  4198. if (result && PyBytes_Check(path->object)) {
  4199. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  4200. }
  4201. cleanup:
  4202. if (target_path != buf) {
  4203. PyMem_Free(target_path);
  4204. }
  4205. CloseHandle(hFile);
  4206. return result;
  4207. }
  4208. /*[clinic input]
  4209. os._getvolumepathname
  4210. path: path_t
  4211. A helper function for ismount on Win32.
  4212. [clinic start generated code]*/
  4213. static PyObject *
  4214. os__getvolumepathname_impl(PyObject *module, path_t *path)
  4215. /*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
  4216. {
  4217. PyObject *result;
  4218. wchar_t *mountpath=NULL;
  4219. size_t buflen;
  4220. BOOL ret;
  4221. /* Volume path should be shorter than entire path */
  4222. buflen = Py_MAX(path->length, MAX_PATH);
  4223. if (buflen > PY_DWORD_MAX) {
  4224. PyErr_SetString(PyExc_OverflowError, "path too long");
  4225. return NULL;
  4226. }
  4227. mountpath = PyMem_New(wchar_t, buflen);
  4228. if (mountpath == NULL)
  4229. return PyErr_NoMemory();
  4230. Py_BEGIN_ALLOW_THREADS
  4231. ret = GetVolumePathNameW(path->wide, mountpath,
  4232. Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
  4233. Py_END_ALLOW_THREADS
  4234. if (!ret) {
  4235. result = win32_error_object("_getvolumepathname", path->object);
  4236. goto exit;
  4237. }
  4238. result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
  4239. if (PyBytes_Check(path->object))
  4240. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  4241. exit:
  4242. PyMem_Free(mountpath);
  4243. return result;
  4244. }
  4245. /*[clinic input]
  4246. os._path_splitroot
  4247. path: path_t
  4248. Removes everything after the root on Win32.
  4249. [clinic start generated code]*/
  4250. static PyObject *
  4251. os__path_splitroot_impl(PyObject *module, path_t *path)
  4252. /*[clinic end generated code: output=ab7f1a88b654581c input=dc93b1d3984cffb6]*/
  4253. {
  4254. wchar_t *buffer;
  4255. wchar_t *end;
  4256. PyObject *result = NULL;
  4257. HRESULT ret;
  4258. buffer = (wchar_t*)PyMem_Malloc(sizeof(wchar_t) * (wcslen(path->wide) + 1));
  4259. if (!buffer) {
  4260. return NULL;
  4261. }
  4262. wcscpy(buffer, path->wide);
  4263. for (wchar_t *p = wcschr(buffer, L'/'); p; p = wcschr(p, L'/')) {
  4264. *p = L'\\';
  4265. }
  4266. Py_BEGIN_ALLOW_THREADS
  4267. ret = PathCchSkipRoot(buffer, &end);
  4268. Py_END_ALLOW_THREADS
  4269. if (FAILED(ret)) {
  4270. result = Py_BuildValue("sO", "", path->object);
  4271. } else if (end != buffer) {
  4272. size_t rootLen = (size_t)(end - buffer);
  4273. result = Py_BuildValue("NN",
  4274. PyUnicode_FromWideChar(path->wide, rootLen),
  4275. PyUnicode_FromWideChar(path->wide + rootLen, -1)
  4276. );
  4277. } else {
  4278. result = Py_BuildValue("Os", path->object, "");
  4279. }
  4280. PyMem_Free(buffer);
  4281. return result;
  4282. }
  4283. #define PY_IFREG 1 // Regular file
  4284. #define PY_IFDIR 2 // Directory
  4285. #define PY_IFLNK 4 // Symlink
  4286. #define PY_IFMNT 8 // Mount Point (junction)
  4287. #define PY_IFLRP 16 // Link Reparse Point (name-surrogate, symlink, junction)
  4288. #define PY_IFRRP 32 // Regular Reparse Point
  4289. static inline BOOL
  4290. _testInfo(DWORD attributes, DWORD reparseTag, BOOL diskDevice, int testedType)
  4291. {
  4292. switch (testedType) {
  4293. case PY_IFREG:
  4294. return diskDevice && attributes &&
  4295. !(attributes & FILE_ATTRIBUTE_DIRECTORY);
  4296. case PY_IFDIR:
  4297. return attributes & FILE_ATTRIBUTE_DIRECTORY;
  4298. case PY_IFLNK:
  4299. return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
  4300. reparseTag == IO_REPARSE_TAG_SYMLINK;
  4301. case PY_IFMNT:
  4302. return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
  4303. reparseTag == IO_REPARSE_TAG_MOUNT_POINT;
  4304. case PY_IFLRP:
  4305. return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
  4306. IsReparseTagNameSurrogate(reparseTag);
  4307. case PY_IFRRP:
  4308. return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
  4309. reparseTag && !IsReparseTagNameSurrogate(reparseTag);
  4310. }
  4311. return FALSE;
  4312. }
  4313. static BOOL
  4314. _testFileTypeByHandle(HANDLE hfile, int testedType, BOOL diskOnly)
  4315. {
  4316. assert(testedType == PY_IFREG || testedType == PY_IFDIR ||
  4317. testedType == PY_IFLNK || testedType == PY_IFMNT ||
  4318. testedType == PY_IFLRP || testedType == PY_IFRRP);
  4319. BOOL diskDevice = GetFileType(hfile) == FILE_TYPE_DISK;
  4320. if (diskOnly && !diskDevice) {
  4321. return FALSE;
  4322. }
  4323. if (testedType != PY_IFREG && testedType != PY_IFDIR) {
  4324. FILE_ATTRIBUTE_TAG_INFO info;
  4325. return GetFileInformationByHandleEx(hfile, FileAttributeTagInfo, &info,
  4326. sizeof(info)) &&
  4327. _testInfo(info.FileAttributes, info.ReparseTag, diskDevice,
  4328. testedType);
  4329. }
  4330. FILE_BASIC_INFO info;
  4331. return GetFileInformationByHandleEx(hfile, FileBasicInfo, &info,
  4332. sizeof(info)) &&
  4333. _testInfo(info.FileAttributes, 0, diskDevice, testedType);
  4334. }
  4335. static BOOL
  4336. _testFileTypeByName(LPCWSTR path, int testedType)
  4337. {
  4338. assert(testedType == PY_IFREG || testedType == PY_IFDIR ||
  4339. testedType == PY_IFLNK || testedType == PY_IFMNT ||
  4340. testedType == PY_IFLRP || testedType == PY_IFRRP);
  4341. FILE_STAT_BASIC_INFORMATION info;
  4342. if (_Py_GetFileInformationByName(path, FileStatBasicByNameInfo, &info,
  4343. sizeof(info)))
  4344. {
  4345. BOOL diskDevice = info.DeviceType == FILE_DEVICE_DISK ||
  4346. info.DeviceType == FILE_DEVICE_VIRTUAL_DISK ||
  4347. info.DeviceType == FILE_DEVICE_CD_ROM;
  4348. BOOL result = _testInfo(info.FileAttributes, info.ReparseTag,
  4349. diskDevice, testedType);
  4350. if (!result || (testedType != PY_IFREG && testedType != PY_IFDIR) ||
  4351. !(info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
  4352. {
  4353. return result;
  4354. }
  4355. }
  4356. else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(
  4357. GetLastError()))
  4358. {
  4359. return FALSE;
  4360. }
  4361. DWORD flags = FILE_FLAG_BACKUP_SEMANTICS;
  4362. if (testedType != PY_IFREG && testedType != PY_IFDIR) {
  4363. flags |= FILE_FLAG_OPEN_REPARSE_POINT;
  4364. }
  4365. HANDLE hfile = CreateFileW(path, FILE_READ_ATTRIBUTES, 0, NULL,
  4366. OPEN_EXISTING, flags, NULL);
  4367. if (hfile != INVALID_HANDLE_VALUE) {
  4368. BOOL result = _testFileTypeByHandle(hfile, testedType, FALSE);
  4369. CloseHandle(hfile);
  4370. return result;
  4371. }
  4372. switch (GetLastError()) {
  4373. case ERROR_ACCESS_DENIED:
  4374. case ERROR_SHARING_VIOLATION:
  4375. case ERROR_CANT_ACCESS_FILE:
  4376. case ERROR_INVALID_PARAMETER:
  4377. int rc;
  4378. STRUCT_STAT st;
  4379. if (testedType == PY_IFREG || testedType == PY_IFDIR) {
  4380. rc = STAT(path, &st);
  4381. }
  4382. else {
  4383. // PY_IFRRP is not generally supported in this case, except for
  4384. // unhandled reparse points such as IO_REPARSE_TAG_APPEXECLINK.
  4385. rc = LSTAT(path, &st);
  4386. }
  4387. if (!rc) {
  4388. return _testInfo(st.st_file_attributes, st.st_reparse_tag,
  4389. st.st_mode & S_IFREG, testedType);
  4390. }
  4391. }
  4392. return FALSE;
  4393. }
  4394. static BOOL
  4395. _testFileExistsByName(LPCWSTR path, BOOL followLinks)
  4396. {
  4397. FILE_STAT_BASIC_INFORMATION info;
  4398. if (_Py_GetFileInformationByName(path, FileStatBasicByNameInfo, &info,
  4399. sizeof(info)))
  4400. {
  4401. if (!(info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ||
  4402. !followLinks && IsReparseTagNameSurrogate(info.ReparseTag))
  4403. {
  4404. return TRUE;
  4405. }
  4406. }
  4407. else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(
  4408. GetLastError()))
  4409. {
  4410. return FALSE;
  4411. }
  4412. DWORD flags = FILE_FLAG_BACKUP_SEMANTICS;
  4413. if (!followLinks) {
  4414. flags |= FILE_FLAG_OPEN_REPARSE_POINT;
  4415. }
  4416. HANDLE hfile = CreateFileW(path, FILE_READ_ATTRIBUTES, 0, NULL,
  4417. OPEN_EXISTING, flags, NULL);
  4418. if (hfile != INVALID_HANDLE_VALUE) {
  4419. if (followLinks) {
  4420. CloseHandle(hfile);
  4421. return TRUE;
  4422. }
  4423. // Regular Reparse Points (PY_IFRRP) have to be traversed.
  4424. BOOL result = _testFileTypeByHandle(hfile, PY_IFRRP, FALSE);
  4425. CloseHandle(hfile);
  4426. if (!result) {
  4427. return TRUE;
  4428. }
  4429. hfile = CreateFileW(path, FILE_READ_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
  4430. FILE_FLAG_BACKUP_SEMANTICS, NULL);
  4431. if (hfile != INVALID_HANDLE_VALUE) {
  4432. CloseHandle(hfile);
  4433. return TRUE;
  4434. }
  4435. }
  4436. switch (GetLastError()) {
  4437. case ERROR_ACCESS_DENIED:
  4438. case ERROR_SHARING_VIOLATION:
  4439. case ERROR_CANT_ACCESS_FILE:
  4440. case ERROR_INVALID_PARAMETER:
  4441. STRUCT_STAT _st;
  4442. return followLinks ? !STAT(path, &_st): !LSTAT(path, &_st);
  4443. }
  4444. return FALSE;
  4445. }
  4446. static BOOL
  4447. _testFileExists(path_t *path, BOOL followLinks)
  4448. {
  4449. BOOL result = FALSE;
  4450. if (path->value_error) {
  4451. return FALSE;
  4452. }
  4453. Py_BEGIN_ALLOW_THREADS
  4454. if (path->fd != -1) {
  4455. HANDLE hfile = _Py_get_osfhandle_noraise(path->fd);
  4456. if (hfile != INVALID_HANDLE_VALUE) {
  4457. if (GetFileType(hfile) != FILE_TYPE_UNKNOWN || !GetLastError()) {
  4458. result = TRUE;
  4459. }
  4460. }
  4461. }
  4462. else if (path->wide) {
  4463. result = _testFileExistsByName(path->wide, followLinks);
  4464. }
  4465. Py_END_ALLOW_THREADS
  4466. return result;
  4467. }
  4468. static BOOL
  4469. _testFileType(path_t *path, int testedType)
  4470. {
  4471. BOOL result = FALSE;
  4472. if (path->value_error) {
  4473. return FALSE;
  4474. }
  4475. Py_BEGIN_ALLOW_THREADS
  4476. if (path->fd != -1) {
  4477. HANDLE hfile = _Py_get_osfhandle_noraise(path->fd);
  4478. if (hfile != INVALID_HANDLE_VALUE) {
  4479. result = _testFileTypeByHandle(hfile, testedType, TRUE);
  4480. }
  4481. }
  4482. else if (path->wide) {
  4483. result = _testFileTypeByName(path->wide, testedType);
  4484. }
  4485. Py_END_ALLOW_THREADS
  4486. return result;
  4487. }
  4488. /*[clinic input]
  4489. os._path_exists -> bool
  4490. path: path_t(allow_fd=True, suppress_value_error=True)
  4491. /
  4492. Test whether a path exists. Returns False for broken symbolic links.
  4493. [clinic start generated code]*/
  4494. static int
  4495. os__path_exists_impl(PyObject *module, path_t *path)
  4496. /*[clinic end generated code: output=8da13acf666e16ba input=29198507a6082a57]*/
  4497. {
  4498. return _testFileExists(path, TRUE);
  4499. }
  4500. /*[clinic input]
  4501. os._path_isdir -> bool
  4502. s as path: path_t(allow_fd=True, suppress_value_error=True)
  4503. Return true if the pathname refers to an existing directory.
  4504. [clinic start generated code]*/
  4505. static int
  4506. os__path_isdir_impl(PyObject *module, path_t *path)
  4507. /*[clinic end generated code: output=d5786196f9e2fa7a input=132a3b5301aecf79]*/
  4508. {
  4509. return _testFileType(path, PY_IFDIR);
  4510. }
  4511. /*[clinic input]
  4512. os._path_isfile -> bool
  4513. path: path_t(allow_fd=True, suppress_value_error=True)
  4514. Test whether a path is a regular file
  4515. [clinic start generated code]*/
  4516. static int
  4517. os__path_isfile_impl(PyObject *module, path_t *path)
  4518. /*[clinic end generated code: output=5c3073bc212b9863 input=4ac1fd350b30a39e]*/
  4519. {
  4520. return _testFileType(path, PY_IFREG);
  4521. }
  4522. /*[clinic input]
  4523. os._path_islink -> bool
  4524. path: path_t(allow_fd=True, suppress_value_error=True)
  4525. Test whether a path is a symbolic link
  4526. [clinic start generated code]*/
  4527. static int
  4528. os__path_islink_impl(PyObject *module, path_t *path)
  4529. /*[clinic end generated code: output=30da7bda8296adcc input=7510ce05b547debb]*/
  4530. {
  4531. return _testFileType(path, PY_IFLNK);
  4532. }
  4533. #undef PY_IFREG
  4534. #undef PY_IFDIR
  4535. #undef PY_IFLNK
  4536. #undef PY_IFMNT
  4537. #undef PY_IFLRP
  4538. #undef PY_IFRRP
  4539. #endif /* MS_WINDOWS */
  4540. /*[clinic input]
  4541. os._path_normpath
  4542. path: path_t(make_wide=True, nonstrict=True)
  4543. Normalize path, eliminating double slashes, etc.
  4544. [clinic start generated code]*/
  4545. static PyObject *
  4546. os__path_normpath_impl(PyObject *module, path_t *path)
  4547. /*[clinic end generated code: output=d353e7ed9410c044 input=3d4ac23b06332dcb]*/
  4548. {
  4549. PyObject *result;
  4550. Py_ssize_t norm_len;
  4551. wchar_t *norm_path = _Py_normpath_and_size((wchar_t *)path->wide,
  4552. path->length, &norm_len);
  4553. if (!norm_len) {
  4554. result = PyUnicode_FromOrdinal('.');
  4555. }
  4556. else {
  4557. result = PyUnicode_FromWideChar(norm_path, norm_len);
  4558. }
  4559. if (PyBytes_Check(path->object)) {
  4560. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  4561. }
  4562. return result;
  4563. }
  4564. /*[clinic input]
  4565. os.mkdir
  4566. path : path_t
  4567. mode: int = 0o777
  4568. *
  4569. dir_fd : dir_fd(requires='mkdirat') = None
  4570. # "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
  4571. Create a directory.
  4572. If dir_fd is not None, it should be a file descriptor open to a directory,
  4573. and path should be relative; path will then be relative to that directory.
  4574. dir_fd may not be implemented on your platform.
  4575. If it is unavailable, using it will raise a NotImplementedError.
  4576. The mode argument is ignored on Windows. Where it is used, the current umask
  4577. value is first masked out.
  4578. [clinic start generated code]*/
  4579. static PyObject *
  4580. os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
  4581. /*[clinic end generated code: output=a70446903abe821f input=a61722e1576fab03]*/
  4582. {
  4583. int result;
  4584. #ifdef MS_WINDOWS
  4585. int error = 0;
  4586. int pathError = 0;
  4587. SECURITY_ATTRIBUTES secAttr = { sizeof(secAttr) };
  4588. SECURITY_ATTRIBUTES *pSecAttr = NULL;
  4589. #endif
  4590. #ifdef HAVE_MKDIRAT
  4591. int mkdirat_unavailable = 0;
  4592. #endif
  4593. if (PySys_Audit("os.mkdir", "Oii", path->object, mode,
  4594. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4595. return NULL;
  4596. }
  4597. #ifdef MS_WINDOWS
  4598. Py_BEGIN_ALLOW_THREADS
  4599. if (mode == 0700 /* 0o700 */) {
  4600. ULONG sdSize;
  4601. pSecAttr = &secAttr;
  4602. // Set a discretionary ACL (D) that is protected (P) and includes
  4603. // inheritable (OICI) entries that allow (A) full control (FA) to
  4604. // SYSTEM (SY), Administrators (BA), and the owner (OW).
  4605. if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
  4606. L"D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;OW)",
  4607. SDDL_REVISION_1,
  4608. &secAttr.lpSecurityDescriptor,
  4609. &sdSize
  4610. )) {
  4611. error = GetLastError();
  4612. }
  4613. }
  4614. if (!error) {
  4615. result = CreateDirectoryW(path->wide, pSecAttr);
  4616. if (secAttr.lpSecurityDescriptor &&
  4617. // uncommonly, LocalFree returns non-zero on error, but still uses
  4618. // GetLastError() to see what the error code is
  4619. LocalFree(secAttr.lpSecurityDescriptor)) {
  4620. error = GetLastError();
  4621. }
  4622. }
  4623. Py_END_ALLOW_THREADS
  4624. if (error) {
  4625. return PyErr_SetFromWindowsErr(error);
  4626. }
  4627. if (!result) {
  4628. return path_error(path);
  4629. }
  4630. #else
  4631. Py_BEGIN_ALLOW_THREADS
  4632. #if HAVE_MKDIRAT
  4633. if (dir_fd != DEFAULT_DIR_FD) {
  4634. if (HAVE_MKDIRAT_RUNTIME) {
  4635. result = mkdirat(dir_fd, path->narrow, mode);
  4636. } else {
  4637. mkdirat_unavailable = 1;
  4638. }
  4639. } else
  4640. #endif
  4641. #if defined(__WATCOMC__) && !defined(__QNX__)
  4642. result = mkdir(path->narrow);
  4643. #else
  4644. result = mkdir(path->narrow, mode);
  4645. #endif
  4646. Py_END_ALLOW_THREADS
  4647. #if HAVE_MKDIRAT
  4648. if (mkdirat_unavailable) {
  4649. argument_unavailable_error(NULL, "dir_fd");
  4650. return NULL;
  4651. }
  4652. #endif
  4653. if (result < 0)
  4654. return path_error(path);
  4655. #endif /* MS_WINDOWS */
  4656. Py_RETURN_NONE;
  4657. }
  4658. /* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
  4659. #if defined(HAVE_SYS_RESOURCE_H)
  4660. #include <sys/resource.h>
  4661. #endif
  4662. #ifdef HAVE_NICE
  4663. /*[clinic input]
  4664. os.nice
  4665. increment: int
  4666. /
  4667. Add increment to the priority of process and return the new priority.
  4668. [clinic start generated code]*/
  4669. static PyObject *
  4670. os_nice_impl(PyObject *module, int increment)
  4671. /*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
  4672. {
  4673. int value;
  4674. /* There are two flavours of 'nice': one that returns the new
  4675. priority (as required by almost all standards out there) and the
  4676. Linux/FreeBSD one, which returns '0' on success and advices
  4677. the use of getpriority() to get the new priority.
  4678. If we are of the nice family that returns the new priority, we
  4679. need to clear errno before the call, and check if errno is filled
  4680. before calling posix_error() on a returnvalue of -1, because the
  4681. -1 may be the actual new priority! */
  4682. errno = 0;
  4683. value = nice(increment);
  4684. #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
  4685. if (value == 0)
  4686. value = getpriority(PRIO_PROCESS, 0);
  4687. #endif
  4688. if (value == -1 && errno != 0)
  4689. /* either nice() or getpriority() returned an error */
  4690. return posix_error();
  4691. return PyLong_FromLong((long) value);
  4692. }
  4693. #endif /* HAVE_NICE */
  4694. #ifdef HAVE_GETPRIORITY
  4695. /*[clinic input]
  4696. os.getpriority
  4697. which: int
  4698. who: int
  4699. Return program scheduling priority.
  4700. [clinic start generated code]*/
  4701. static PyObject *
  4702. os_getpriority_impl(PyObject *module, int which, int who)
  4703. /*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
  4704. {
  4705. int retval;
  4706. errno = 0;
  4707. retval = getpriority(which, who);
  4708. if (errno != 0)
  4709. return posix_error();
  4710. return PyLong_FromLong((long)retval);
  4711. }
  4712. #endif /* HAVE_GETPRIORITY */
  4713. #ifdef HAVE_SETPRIORITY
  4714. /*[clinic input]
  4715. os.setpriority
  4716. which: int
  4717. who: int
  4718. priority: int
  4719. Set program scheduling priority.
  4720. [clinic start generated code]*/
  4721. static PyObject *
  4722. os_setpriority_impl(PyObject *module, int which, int who, int priority)
  4723. /*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
  4724. {
  4725. int retval;
  4726. retval = setpriority(which, who, priority);
  4727. if (retval == -1)
  4728. return posix_error();
  4729. Py_RETURN_NONE;
  4730. }
  4731. #endif /* HAVE_SETPRIORITY */
  4732. static PyObject *
  4733. internal_rename(path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int is_replace)
  4734. {
  4735. const char *function_name = is_replace ? "replace" : "rename";
  4736. int dir_fd_specified;
  4737. #ifdef HAVE_RENAMEAT
  4738. int renameat_unavailable = 0;
  4739. #endif
  4740. #ifdef MS_WINDOWS
  4741. BOOL result;
  4742. int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
  4743. #else
  4744. int result;
  4745. #endif
  4746. dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
  4747. (dst_dir_fd != DEFAULT_DIR_FD);
  4748. #ifndef HAVE_RENAMEAT
  4749. if (dir_fd_specified) {
  4750. argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
  4751. return NULL;
  4752. }
  4753. #endif
  4754. if (PySys_Audit("os.rename", "OOii", src->object, dst->object,
  4755. src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
  4756. dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
  4757. return NULL;
  4758. }
  4759. #ifdef MS_WINDOWS
  4760. Py_BEGIN_ALLOW_THREADS
  4761. result = MoveFileExW(src->wide, dst->wide, flags);
  4762. Py_END_ALLOW_THREADS
  4763. if (!result)
  4764. return path_error2(src, dst);
  4765. #else
  4766. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  4767. PyErr_Format(PyExc_ValueError,
  4768. "%s: src and dst must be the same type", function_name);
  4769. return NULL;
  4770. }
  4771. Py_BEGIN_ALLOW_THREADS
  4772. #ifdef HAVE_RENAMEAT
  4773. if (dir_fd_specified) {
  4774. if (HAVE_RENAMEAT_RUNTIME) {
  4775. result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
  4776. } else {
  4777. renameat_unavailable = 1;
  4778. }
  4779. } else
  4780. #endif
  4781. result = rename(src->narrow, dst->narrow);
  4782. Py_END_ALLOW_THREADS
  4783. #ifdef HAVE_RENAMEAT
  4784. if (renameat_unavailable) {
  4785. argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
  4786. return NULL;
  4787. }
  4788. #endif
  4789. if (result)
  4790. return path_error2(src, dst);
  4791. #endif
  4792. Py_RETURN_NONE;
  4793. }
  4794. /*[clinic input]
  4795. os.rename
  4796. src : path_t
  4797. dst : path_t
  4798. *
  4799. src_dir_fd : dir_fd = None
  4800. dst_dir_fd : dir_fd = None
  4801. Rename a file or directory.
  4802. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  4803. descriptor open to a directory, and the respective path string (src or dst)
  4804. should be relative; the path will then be relative to that directory.
  4805. src_dir_fd and dst_dir_fd, may not be implemented on your platform.
  4806. If they are unavailable, using them will raise a NotImplementedError.
  4807. [clinic start generated code]*/
  4808. static PyObject *
  4809. os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  4810. int dst_dir_fd)
  4811. /*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
  4812. {
  4813. return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
  4814. }
  4815. /*[clinic input]
  4816. os.replace = os.rename
  4817. Rename a file or directory, overwriting the destination.
  4818. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  4819. descriptor open to a directory, and the respective path string (src or dst)
  4820. should be relative; the path will then be relative to that directory.
  4821. src_dir_fd and dst_dir_fd, may not be implemented on your platform.
  4822. If they are unavailable, using them will raise a NotImplementedError.
  4823. [clinic start generated code]*/
  4824. static PyObject *
  4825. os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  4826. int dst_dir_fd)
  4827. /*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
  4828. {
  4829. return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
  4830. }
  4831. /*[clinic input]
  4832. os.rmdir
  4833. path: path_t
  4834. *
  4835. dir_fd: dir_fd(requires='unlinkat') = None
  4836. Remove a directory.
  4837. If dir_fd is not None, it should be a file descriptor open to a directory,
  4838. and path should be relative; path will then be relative to that directory.
  4839. dir_fd may not be implemented on your platform.
  4840. If it is unavailable, using it will raise a NotImplementedError.
  4841. [clinic start generated code]*/
  4842. static PyObject *
  4843. os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
  4844. /*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
  4845. {
  4846. int result;
  4847. #ifdef HAVE_UNLINKAT
  4848. int unlinkat_unavailable = 0;
  4849. #endif
  4850. if (PySys_Audit("os.rmdir", "Oi", path->object,
  4851. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4852. return NULL;
  4853. }
  4854. Py_BEGIN_ALLOW_THREADS
  4855. #ifdef MS_WINDOWS
  4856. /* Windows, success=1, UNIX, success=0 */
  4857. result = !RemoveDirectoryW(path->wide);
  4858. #else
  4859. #ifdef HAVE_UNLINKAT
  4860. if (dir_fd != DEFAULT_DIR_FD) {
  4861. if (HAVE_UNLINKAT_RUNTIME) {
  4862. result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
  4863. } else {
  4864. unlinkat_unavailable = 1;
  4865. result = -1;
  4866. }
  4867. } else
  4868. #endif
  4869. result = rmdir(path->narrow);
  4870. #endif
  4871. Py_END_ALLOW_THREADS
  4872. #ifdef HAVE_UNLINKAT
  4873. if (unlinkat_unavailable) {
  4874. argument_unavailable_error("rmdir", "dir_fd");
  4875. return NULL;
  4876. }
  4877. #endif
  4878. if (result)
  4879. return path_error(path);
  4880. Py_RETURN_NONE;
  4881. }
  4882. #ifdef HAVE_SYSTEM
  4883. #ifdef MS_WINDOWS
  4884. /*[clinic input]
  4885. os.system -> long
  4886. command: Py_UNICODE
  4887. Execute the command in a subshell.
  4888. [clinic start generated code]*/
  4889. static long
  4890. os_system_impl(PyObject *module, const Py_UNICODE *command)
  4891. /*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
  4892. {
  4893. long result;
  4894. if (PySys_Audit("os.system", "(u)", command) < 0) {
  4895. return -1;
  4896. }
  4897. Py_BEGIN_ALLOW_THREADS
  4898. _Py_BEGIN_SUPPRESS_IPH
  4899. result = _wsystem(command);
  4900. _Py_END_SUPPRESS_IPH
  4901. Py_END_ALLOW_THREADS
  4902. return result;
  4903. }
  4904. #else /* MS_WINDOWS */
  4905. /*[clinic input]
  4906. os.system -> long
  4907. command: FSConverter
  4908. Execute the command in a subshell.
  4909. [clinic start generated code]*/
  4910. static long
  4911. os_system_impl(PyObject *module, PyObject *command)
  4912. /*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
  4913. {
  4914. long result;
  4915. const char *bytes = PyBytes_AsString(command);
  4916. if (PySys_Audit("os.system", "(O)", command) < 0) {
  4917. return -1;
  4918. }
  4919. Py_BEGIN_ALLOW_THREADS
  4920. result = system(bytes);
  4921. Py_END_ALLOW_THREADS
  4922. return result;
  4923. }
  4924. #endif
  4925. #endif /* HAVE_SYSTEM */
  4926. #ifdef HAVE_UMASK
  4927. /*[clinic input]
  4928. os.umask
  4929. mask: int
  4930. /
  4931. Set the current numeric umask and return the previous umask.
  4932. [clinic start generated code]*/
  4933. static PyObject *
  4934. os_umask_impl(PyObject *module, int mask)
  4935. /*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
  4936. {
  4937. int i = (int)umask(mask);
  4938. if (i < 0)
  4939. return posix_error();
  4940. return PyLong_FromLong((long)i);
  4941. }
  4942. #endif
  4943. #ifdef MS_WINDOWS
  4944. /* override the default DeleteFileW behavior so that directory
  4945. symlinks can be removed with this function, the same as with
  4946. Unix symlinks */
  4947. BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
  4948. {
  4949. WIN32_FILE_ATTRIBUTE_DATA info;
  4950. WIN32_FIND_DATAW find_data;
  4951. HANDLE find_data_handle;
  4952. int is_directory = 0;
  4953. int is_link = 0;
  4954. if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
  4955. is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4956. /* Get WIN32_FIND_DATA structure for the path to determine if
  4957. it is a symlink */
  4958. if(is_directory &&
  4959. info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
  4960. find_data_handle = FindFirstFileW(lpFileName, &find_data);
  4961. if(find_data_handle != INVALID_HANDLE_VALUE) {
  4962. /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
  4963. IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
  4964. is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
  4965. find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
  4966. FindClose(find_data_handle);
  4967. }
  4968. }
  4969. }
  4970. if (is_directory && is_link)
  4971. return RemoveDirectoryW(lpFileName);
  4972. return DeleteFileW(lpFileName);
  4973. }
  4974. #endif /* MS_WINDOWS */
  4975. /*[clinic input]
  4976. os.unlink
  4977. path: path_t
  4978. *
  4979. dir_fd: dir_fd(requires='unlinkat')=None
  4980. Remove a file (same as remove()).
  4981. If dir_fd is not None, it should be a file descriptor open to a directory,
  4982. and path should be relative; path will then be relative to that directory.
  4983. dir_fd may not be implemented on your platform.
  4984. If it is unavailable, using it will raise a NotImplementedError.
  4985. [clinic start generated code]*/
  4986. static PyObject *
  4987. os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
  4988. /*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
  4989. {
  4990. int result;
  4991. #ifdef HAVE_UNLINKAT
  4992. int unlinkat_unavailable = 0;
  4993. #endif
  4994. if (PySys_Audit("os.remove", "Oi", path->object,
  4995. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4996. return NULL;
  4997. }
  4998. Py_BEGIN_ALLOW_THREADS
  4999. _Py_BEGIN_SUPPRESS_IPH
  5000. #ifdef MS_WINDOWS
  5001. /* Windows, success=1, UNIX, success=0 */
  5002. result = !Py_DeleteFileW(path->wide);
  5003. #else
  5004. #ifdef HAVE_UNLINKAT
  5005. if (dir_fd != DEFAULT_DIR_FD) {
  5006. if (HAVE_UNLINKAT_RUNTIME) {
  5007. result = unlinkat(dir_fd, path->narrow, 0);
  5008. } else {
  5009. unlinkat_unavailable = 1;
  5010. }
  5011. } else
  5012. #endif /* HAVE_UNLINKAT */
  5013. result = unlink(path->narrow);
  5014. #endif
  5015. _Py_END_SUPPRESS_IPH
  5016. Py_END_ALLOW_THREADS
  5017. #ifdef HAVE_UNLINKAT
  5018. if (unlinkat_unavailable) {
  5019. argument_unavailable_error(NULL, "dir_fd");
  5020. return NULL;
  5021. }
  5022. #endif
  5023. if (result)
  5024. return path_error(path);
  5025. Py_RETURN_NONE;
  5026. }
  5027. /*[clinic input]
  5028. os.remove = os.unlink
  5029. Remove a file (same as unlink()).
  5030. If dir_fd is not None, it should be a file descriptor open to a directory,
  5031. and path should be relative; path will then be relative to that directory.
  5032. dir_fd may not be implemented on your platform.
  5033. If it is unavailable, using it will raise a NotImplementedError.
  5034. [clinic start generated code]*/
  5035. static PyObject *
  5036. os_remove_impl(PyObject *module, path_t *path, int dir_fd)
  5037. /*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
  5038. {
  5039. return os_unlink_impl(module, path, dir_fd);
  5040. }
  5041. static PyStructSequence_Field uname_result_fields[] = {
  5042. {"sysname", "operating system name"},
  5043. {"nodename", "name of machine on network (implementation-defined)"},
  5044. {"release", "operating system release"},
  5045. {"version", "operating system version"},
  5046. {"machine", "hardware identifier"},
  5047. {NULL}
  5048. };
  5049. PyDoc_STRVAR(uname_result__doc__,
  5050. "uname_result: Result from os.uname().\n\n\
  5051. This object may be accessed either as a tuple of\n\
  5052. (sysname, nodename, release, version, machine),\n\
  5053. or via the attributes sysname, nodename, release, version, and machine.\n\
  5054. \n\
  5055. See os.uname for more information.");
  5056. static PyStructSequence_Desc uname_result_desc = {
  5057. MODNAME ".uname_result", /* name */
  5058. uname_result__doc__, /* doc */
  5059. uname_result_fields,
  5060. 5
  5061. };
  5062. #ifdef HAVE_UNAME
  5063. /*[clinic input]
  5064. os.uname
  5065. Return an object identifying the current operating system.
  5066. The object behaves like a named tuple with the following fields:
  5067. (sysname, nodename, release, version, machine)
  5068. [clinic start generated code]*/
  5069. static PyObject *
  5070. os_uname_impl(PyObject *module)
  5071. /*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
  5072. {
  5073. struct utsname u;
  5074. int res;
  5075. PyObject *value;
  5076. Py_BEGIN_ALLOW_THREADS
  5077. res = uname(&u);
  5078. Py_END_ALLOW_THREADS
  5079. if (res < 0)
  5080. return posix_error();
  5081. PyObject *UnameResultType = get_posix_state(module)->UnameResultType;
  5082. value = PyStructSequence_New((PyTypeObject *)UnameResultType);
  5083. if (value == NULL)
  5084. return NULL;
  5085. #define SET(i, field) \
  5086. { \
  5087. PyObject *o = PyUnicode_DecodeFSDefault(field); \
  5088. if (!o) { \
  5089. Py_DECREF(value); \
  5090. return NULL; \
  5091. } \
  5092. PyStructSequence_SET_ITEM(value, i, o); \
  5093. } \
  5094. SET(0, u.sysname);
  5095. SET(1, u.nodename);
  5096. SET(2, u.release);
  5097. SET(3, u.version);
  5098. SET(4, u.machine);
  5099. #undef SET
  5100. return value;
  5101. }
  5102. #endif /* HAVE_UNAME */
  5103. typedef struct {
  5104. int now;
  5105. time_t atime_s;
  5106. long atime_ns;
  5107. time_t mtime_s;
  5108. long mtime_ns;
  5109. } utime_t;
  5110. /*
  5111. * these macros assume that "ut" is a pointer to a utime_t
  5112. * they also intentionally leak the declaration of a pointer named "time"
  5113. */
  5114. #define UTIME_TO_TIMESPEC \
  5115. struct timespec ts[2]; \
  5116. struct timespec *time; \
  5117. if (ut->now) \
  5118. time = NULL; \
  5119. else { \
  5120. ts[0].tv_sec = ut->atime_s; \
  5121. ts[0].tv_nsec = ut->atime_ns; \
  5122. ts[1].tv_sec = ut->mtime_s; \
  5123. ts[1].tv_nsec = ut->mtime_ns; \
  5124. time = ts; \
  5125. } \
  5126. #define UTIME_TO_TIMEVAL \
  5127. struct timeval tv[2]; \
  5128. struct timeval *time; \
  5129. if (ut->now) \
  5130. time = NULL; \
  5131. else { \
  5132. tv[0].tv_sec = ut->atime_s; \
  5133. tv[0].tv_usec = ut->atime_ns / 1000; \
  5134. tv[1].tv_sec = ut->mtime_s; \
  5135. tv[1].tv_usec = ut->mtime_ns / 1000; \
  5136. time = tv; \
  5137. } \
  5138. #define UTIME_TO_UTIMBUF \
  5139. struct utimbuf u; \
  5140. struct utimbuf *time; \
  5141. if (ut->now) \
  5142. time = NULL; \
  5143. else { \
  5144. u.actime = ut->atime_s; \
  5145. u.modtime = ut->mtime_s; \
  5146. time = &u; \
  5147. }
  5148. #define UTIME_TO_TIME_T \
  5149. time_t timet[2]; \
  5150. time_t *time; \
  5151. if (ut->now) \
  5152. time = NULL; \
  5153. else { \
  5154. timet[0] = ut->atime_s; \
  5155. timet[1] = ut->mtime_s; \
  5156. time = timet; \
  5157. } \
  5158. #if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
  5159. static int
  5160. utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
  5161. {
  5162. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5163. if (HAVE_UTIMENSAT_RUNTIME) {
  5164. int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
  5165. UTIME_TO_TIMESPEC;
  5166. return utimensat(dir_fd, path, time, flags);
  5167. } else {
  5168. errno = ENOSYS;
  5169. return -1;
  5170. }
  5171. #elif defined(HAVE_UTIMENSAT)
  5172. int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
  5173. UTIME_TO_TIMESPEC;
  5174. return utimensat(dir_fd, path, time, flags);
  5175. #elif defined(HAVE_FUTIMESAT)
  5176. UTIME_TO_TIMEVAL;
  5177. /*
  5178. * follow_symlinks will never be false here;
  5179. * we only allow !follow_symlinks and dir_fd together
  5180. * if we have utimensat()
  5181. */
  5182. assert(follow_symlinks);
  5183. return futimesat(dir_fd, path, time);
  5184. #endif
  5185. }
  5186. #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
  5187. #else
  5188. #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
  5189. #endif
  5190. #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
  5191. static int
  5192. utime_fd(utime_t *ut, int fd)
  5193. {
  5194. #ifdef HAVE_FUTIMENS
  5195. if (HAVE_FUTIMENS_RUNTIME) {
  5196. UTIME_TO_TIMESPEC;
  5197. return futimens(fd, time);
  5198. } else
  5199. #ifndef HAVE_FUTIMES
  5200. {
  5201. /* Not sure if this can happen */
  5202. PyErr_SetString(
  5203. PyExc_RuntimeError,
  5204. "neither futimens nor futimes are supported"
  5205. " on this system");
  5206. return -1;
  5207. }
  5208. #endif
  5209. #endif
  5210. #ifdef HAVE_FUTIMES
  5211. {
  5212. UTIME_TO_TIMEVAL;
  5213. return futimes(fd, time);
  5214. }
  5215. #endif
  5216. }
  5217. #define PATH_UTIME_HAVE_FD 1
  5218. #else
  5219. #define PATH_UTIME_HAVE_FD 0
  5220. #endif
  5221. #if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
  5222. # define UTIME_HAVE_NOFOLLOW_SYMLINKS
  5223. #endif
  5224. #ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
  5225. static int
  5226. utime_nofollow_symlinks(utime_t *ut, const char *path)
  5227. {
  5228. #ifdef HAVE_UTIMENSAT
  5229. if (HAVE_UTIMENSAT_RUNTIME) {
  5230. UTIME_TO_TIMESPEC;
  5231. return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
  5232. } else
  5233. #ifndef HAVE_LUTIMES
  5234. {
  5235. /* Not sure if this can happen */
  5236. PyErr_SetString(
  5237. PyExc_RuntimeError,
  5238. "neither utimensat nor lutimes are supported"
  5239. " on this system");
  5240. return -1;
  5241. }
  5242. #endif
  5243. #endif
  5244. #ifdef HAVE_LUTIMES
  5245. {
  5246. UTIME_TO_TIMEVAL;
  5247. return lutimes(path, time);
  5248. }
  5249. #endif
  5250. }
  5251. #endif
  5252. #ifndef MS_WINDOWS
  5253. static int
  5254. utime_default(utime_t *ut, const char *path)
  5255. {
  5256. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5257. if (HAVE_UTIMENSAT_RUNTIME) {
  5258. UTIME_TO_TIMESPEC;
  5259. return utimensat(DEFAULT_DIR_FD, path, time, 0);
  5260. } else {
  5261. UTIME_TO_TIMEVAL;
  5262. return utimes(path, time);
  5263. }
  5264. #elif defined(HAVE_UTIMENSAT)
  5265. UTIME_TO_TIMESPEC;
  5266. return utimensat(DEFAULT_DIR_FD, path, time, 0);
  5267. #elif defined(HAVE_UTIMES)
  5268. UTIME_TO_TIMEVAL;
  5269. return utimes(path, time);
  5270. #elif defined(HAVE_UTIME_H)
  5271. UTIME_TO_UTIMBUF;
  5272. return utime(path, time);
  5273. #else
  5274. UTIME_TO_TIME_T;
  5275. return utime(path, time);
  5276. #endif
  5277. }
  5278. #endif
  5279. static int
  5280. split_py_long_to_s_and_ns(PyObject *module, PyObject *py_long, time_t *s, long *ns)
  5281. {
  5282. int result = 0;
  5283. PyObject *divmod;
  5284. divmod = PyNumber_Divmod(py_long, get_posix_state(module)->billion);
  5285. if (!divmod)
  5286. goto exit;
  5287. if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
  5288. PyErr_Format(PyExc_TypeError,
  5289. "%.200s.__divmod__() must return a 2-tuple, not %.200s",
  5290. _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
  5291. goto exit;
  5292. }
  5293. *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
  5294. if ((*s == -1) && PyErr_Occurred())
  5295. goto exit;
  5296. *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
  5297. if ((*ns == -1) && PyErr_Occurred())
  5298. goto exit;
  5299. result = 1;
  5300. exit:
  5301. Py_XDECREF(divmod);
  5302. return result;
  5303. }
  5304. /*[clinic input]
  5305. os.utime
  5306. path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
  5307. times: object = None
  5308. *
  5309. ns: object = NULL
  5310. dir_fd: dir_fd(requires='futimensat') = None
  5311. follow_symlinks: bool=True
  5312. # "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
  5313. Set the access and modified time of path.
  5314. path may always be specified as a string.
  5315. On some platforms, path may also be specified as an open file descriptor.
  5316. If this functionality is unavailable, using it raises an exception.
  5317. If times is not None, it must be a tuple (atime, mtime);
  5318. atime and mtime should be expressed as float seconds since the epoch.
  5319. If ns is specified, it must be a tuple (atime_ns, mtime_ns);
  5320. atime_ns and mtime_ns should be expressed as integer nanoseconds
  5321. since the epoch.
  5322. If times is None and ns is unspecified, utime uses the current time.
  5323. Specifying tuples for both times and ns is an error.
  5324. If dir_fd is not None, it should be a file descriptor open to a directory,
  5325. and path should be relative; path will then be relative to that directory.
  5326. If follow_symlinks is False, and the last element of the path is a symbolic
  5327. link, utime will modify the symbolic link itself instead of the file the
  5328. link points to.
  5329. It is an error to use dir_fd or follow_symlinks when specifying path
  5330. as an open file descriptor.
  5331. dir_fd and follow_symlinks may not be available on your platform.
  5332. If they are unavailable, using them will raise a NotImplementedError.
  5333. [clinic start generated code]*/
  5334. static PyObject *
  5335. os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
  5336. int dir_fd, int follow_symlinks)
  5337. /*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
  5338. {
  5339. #ifdef MS_WINDOWS
  5340. HANDLE hFile;
  5341. FILETIME atime, mtime;
  5342. #else
  5343. int result;
  5344. #endif
  5345. utime_t utime;
  5346. memset(&utime, 0, sizeof(utime_t));
  5347. if (times != Py_None && ns) {
  5348. PyErr_SetString(PyExc_ValueError,
  5349. "utime: you may specify either 'times'"
  5350. " or 'ns' but not both");
  5351. return NULL;
  5352. }
  5353. if (times != Py_None) {
  5354. time_t a_sec, m_sec;
  5355. long a_nsec, m_nsec;
  5356. if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
  5357. PyErr_SetString(PyExc_TypeError,
  5358. "utime: 'times' must be either"
  5359. " a tuple of two ints or None");
  5360. return NULL;
  5361. }
  5362. utime.now = 0;
  5363. if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
  5364. &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
  5365. _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
  5366. &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
  5367. return NULL;
  5368. }
  5369. utime.atime_s = a_sec;
  5370. utime.atime_ns = a_nsec;
  5371. utime.mtime_s = m_sec;
  5372. utime.mtime_ns = m_nsec;
  5373. }
  5374. else if (ns) {
  5375. if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
  5376. PyErr_SetString(PyExc_TypeError,
  5377. "utime: 'ns' must be a tuple of two ints");
  5378. return NULL;
  5379. }
  5380. utime.now = 0;
  5381. if (!split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 0),
  5382. &utime.atime_s, &utime.atime_ns) ||
  5383. !split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 1),
  5384. &utime.mtime_s, &utime.mtime_ns)) {
  5385. return NULL;
  5386. }
  5387. }
  5388. else {
  5389. /* times and ns are both None/unspecified. use "now". */
  5390. utime.now = 1;
  5391. }
  5392. #if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
  5393. if (follow_symlinks_specified("utime", follow_symlinks))
  5394. return NULL;
  5395. #endif
  5396. if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
  5397. dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
  5398. fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
  5399. return NULL;
  5400. #if !defined(HAVE_UTIMENSAT)
  5401. if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
  5402. PyErr_SetString(PyExc_ValueError,
  5403. "utime: cannot use dir_fd and follow_symlinks "
  5404. "together on this platform");
  5405. return NULL;
  5406. }
  5407. #endif
  5408. if (PySys_Audit("os.utime", "OOOi", path->object, times, ns ? ns : Py_None,
  5409. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  5410. return NULL;
  5411. }
  5412. #ifdef MS_WINDOWS
  5413. Py_BEGIN_ALLOW_THREADS
  5414. hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
  5415. NULL, OPEN_EXISTING,
  5416. FILE_FLAG_BACKUP_SEMANTICS, NULL);
  5417. Py_END_ALLOW_THREADS
  5418. if (hFile == INVALID_HANDLE_VALUE) {
  5419. path_error(path);
  5420. return NULL;
  5421. }
  5422. if (utime.now) {
  5423. GetSystemTimeAsFileTime(&mtime);
  5424. atime = mtime;
  5425. }
  5426. else {
  5427. _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
  5428. _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
  5429. }
  5430. if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
  5431. /* Avoid putting the file name into the error here,
  5432. as that may confuse the user into believing that
  5433. something is wrong with the file, when it also
  5434. could be the time stamp that gives a problem. */
  5435. PyErr_SetFromWindowsErr(0);
  5436. CloseHandle(hFile);
  5437. return NULL;
  5438. }
  5439. CloseHandle(hFile);
  5440. #else /* MS_WINDOWS */
  5441. Py_BEGIN_ALLOW_THREADS
  5442. #ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
  5443. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  5444. result = utime_nofollow_symlinks(&utime, path->narrow);
  5445. else
  5446. #endif
  5447. #if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
  5448. if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks)) {
  5449. result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
  5450. } else
  5451. #endif
  5452. #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
  5453. if (path->fd != -1)
  5454. result = utime_fd(&utime, path->fd);
  5455. else
  5456. #endif
  5457. result = utime_default(&utime, path->narrow);
  5458. Py_END_ALLOW_THREADS
  5459. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5460. /* See utime_dir_fd implementation */
  5461. if (result == -1 && errno == ENOSYS) {
  5462. argument_unavailable_error(NULL, "dir_fd");
  5463. return NULL;
  5464. }
  5465. #endif
  5466. if (result < 0) {
  5467. /* see previous comment about not putting filename in error here */
  5468. posix_error();
  5469. return NULL;
  5470. }
  5471. #endif /* MS_WINDOWS */
  5472. Py_RETURN_NONE;
  5473. }
  5474. /* Process operations */
  5475. /*[clinic input]
  5476. os._exit
  5477. status: int
  5478. Exit to the system with specified status, without normal exit processing.
  5479. [clinic start generated code]*/
  5480. static PyObject *
  5481. os__exit_impl(PyObject *module, int status)
  5482. /*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
  5483. {
  5484. _exit(status);
  5485. return NULL; /* Make gcc -Wall happy */
  5486. }
  5487. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5488. #define EXECV_CHAR wchar_t
  5489. #else
  5490. #define EXECV_CHAR char
  5491. #endif
  5492. #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
  5493. static void
  5494. free_string_array(EXECV_CHAR **array, Py_ssize_t count)
  5495. {
  5496. Py_ssize_t i;
  5497. for (i = 0; i < count; i++)
  5498. PyMem_Free(array[i]);
  5499. PyMem_Free(array);
  5500. }
  5501. static int
  5502. fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
  5503. {
  5504. Py_ssize_t size;
  5505. PyObject *ub;
  5506. int result = 0;
  5507. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5508. if (!PyUnicode_FSDecoder(o, &ub))
  5509. return 0;
  5510. *out = PyUnicode_AsWideCharString(ub, &size);
  5511. if (*out)
  5512. result = 1;
  5513. #else
  5514. if (!PyUnicode_FSConverter(o, &ub))
  5515. return 0;
  5516. size = PyBytes_GET_SIZE(ub);
  5517. *out = PyMem_Malloc(size + 1);
  5518. if (*out) {
  5519. memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
  5520. result = 1;
  5521. } else
  5522. PyErr_NoMemory();
  5523. #endif
  5524. Py_DECREF(ub);
  5525. return result;
  5526. }
  5527. #endif
  5528. #if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
  5529. static EXECV_CHAR**
  5530. parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
  5531. {
  5532. Py_ssize_t i, pos, envc;
  5533. PyObject *keys=NULL, *vals=NULL;
  5534. PyObject *key2, *val2, *keyval;
  5535. EXECV_CHAR **envlist;
  5536. i = PyMapping_Size(env);
  5537. if (i < 0)
  5538. return NULL;
  5539. envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
  5540. if (envlist == NULL) {
  5541. PyErr_NoMemory();
  5542. return NULL;
  5543. }
  5544. envc = 0;
  5545. keys = PyMapping_Keys(env);
  5546. if (!keys)
  5547. goto error;
  5548. vals = PyMapping_Values(env);
  5549. if (!vals)
  5550. goto error;
  5551. if (!PyList_Check(keys) || !PyList_Check(vals)) {
  5552. PyErr_Format(PyExc_TypeError,
  5553. "env.keys() or env.values() is not a list");
  5554. goto error;
  5555. }
  5556. for (pos = 0; pos < i; pos++) {
  5557. PyObject *key = PyList_GetItem(keys, pos); // Borrowed ref.
  5558. if (key == NULL) {
  5559. goto error;
  5560. }
  5561. PyObject *val = PyList_GetItem(vals, pos); // Borrowed ref.
  5562. if (val == NULL) {
  5563. goto error;
  5564. }
  5565. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5566. if (!PyUnicode_FSDecoder(key, &key2))
  5567. goto error;
  5568. if (!PyUnicode_FSDecoder(val, &val2)) {
  5569. Py_DECREF(key2);
  5570. goto error;
  5571. }
  5572. /* Search from index 1 because on Windows starting '=' is allowed for
  5573. defining hidden environment variables. */
  5574. if (PyUnicode_GET_LENGTH(key2) == 0 ||
  5575. PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
  5576. {
  5577. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  5578. Py_DECREF(key2);
  5579. Py_DECREF(val2);
  5580. goto error;
  5581. }
  5582. keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
  5583. #else
  5584. if (!PyUnicode_FSConverter(key, &key2))
  5585. goto error;
  5586. if (!PyUnicode_FSConverter(val, &val2)) {
  5587. Py_DECREF(key2);
  5588. goto error;
  5589. }
  5590. if (PyBytes_GET_SIZE(key2) == 0 ||
  5591. strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
  5592. {
  5593. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  5594. Py_DECREF(key2);
  5595. Py_DECREF(val2);
  5596. goto error;
  5597. }
  5598. keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
  5599. PyBytes_AS_STRING(val2));
  5600. #endif
  5601. Py_DECREF(key2);
  5602. Py_DECREF(val2);
  5603. if (!keyval)
  5604. goto error;
  5605. if (!fsconvert_strdup(keyval, &envlist[envc++])) {
  5606. Py_DECREF(keyval);
  5607. goto error;
  5608. }
  5609. Py_DECREF(keyval);
  5610. }
  5611. Py_DECREF(vals);
  5612. Py_DECREF(keys);
  5613. envlist[envc] = 0;
  5614. *envc_ptr = envc;
  5615. return envlist;
  5616. error:
  5617. Py_XDECREF(keys);
  5618. Py_XDECREF(vals);
  5619. free_string_array(envlist, envc);
  5620. return NULL;
  5621. }
  5622. static EXECV_CHAR**
  5623. parse_arglist(PyObject* argv, Py_ssize_t *argc)
  5624. {
  5625. int i;
  5626. EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
  5627. if (argvlist == NULL) {
  5628. PyErr_NoMemory();
  5629. return NULL;
  5630. }
  5631. for (i = 0; i < *argc; i++) {
  5632. PyObject* item = PySequence_ITEM(argv, i);
  5633. if (item == NULL)
  5634. goto fail;
  5635. if (!fsconvert_strdup(item, &argvlist[i])) {
  5636. Py_DECREF(item);
  5637. goto fail;
  5638. }
  5639. Py_DECREF(item);
  5640. }
  5641. argvlist[*argc] = NULL;
  5642. return argvlist;
  5643. fail:
  5644. *argc = i;
  5645. free_string_array(argvlist, *argc);
  5646. return NULL;
  5647. }
  5648. #endif
  5649. #ifdef HAVE_EXECV
  5650. /*[clinic input]
  5651. os.execv
  5652. path: path_t
  5653. Path of executable file.
  5654. argv: object
  5655. Tuple or list of strings.
  5656. /
  5657. Execute an executable path with arguments, replacing current process.
  5658. [clinic start generated code]*/
  5659. static PyObject *
  5660. os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
  5661. /*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
  5662. {
  5663. EXECV_CHAR **argvlist;
  5664. Py_ssize_t argc;
  5665. PyInterpreterState *interp = _PyInterpreterState_GET();
  5666. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_EXEC)) {
  5667. PyErr_SetString(PyExc_RuntimeError,
  5668. "exec not supported for isolated subinterpreters");
  5669. return NULL;
  5670. }
  5671. /* execv has two arguments: (path, argv), where
  5672. argv is a list or tuple of strings. */
  5673. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  5674. PyErr_SetString(PyExc_TypeError,
  5675. "execv() arg 2 must be a tuple or list");
  5676. return NULL;
  5677. }
  5678. argc = PySequence_Size(argv);
  5679. if (argc < 1) {
  5680. PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
  5681. return NULL;
  5682. }
  5683. argvlist = parse_arglist(argv, &argc);
  5684. if (argvlist == NULL) {
  5685. return NULL;
  5686. }
  5687. if (!argvlist[0][0]) {
  5688. PyErr_SetString(PyExc_ValueError,
  5689. "execv() arg 2 first element cannot be empty");
  5690. free_string_array(argvlist, argc);
  5691. return NULL;
  5692. }
  5693. if (PySys_Audit("os.exec", "OOO", path->object, argv, Py_None) < 0) {
  5694. free_string_array(argvlist, argc);
  5695. return NULL;
  5696. }
  5697. _Py_BEGIN_SUPPRESS_IPH
  5698. #ifdef HAVE_WEXECV
  5699. _wexecv(path->wide, argvlist);
  5700. #else
  5701. execv(path->narrow, argvlist);
  5702. #endif
  5703. _Py_END_SUPPRESS_IPH
  5704. /* If we get here it's definitely an error */
  5705. posix_error();
  5706. free_string_array(argvlist, argc);
  5707. return NULL;
  5708. }
  5709. /*[clinic input]
  5710. os.execve
  5711. path: path_t(allow_fd='PATH_HAVE_FEXECVE')
  5712. Path of executable file.
  5713. argv: object
  5714. Tuple or list of strings.
  5715. env: object
  5716. Dictionary of strings mapping to strings.
  5717. Execute an executable path with arguments, replacing current process.
  5718. [clinic start generated code]*/
  5719. static PyObject *
  5720. os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
  5721. /*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
  5722. {
  5723. EXECV_CHAR **argvlist = NULL;
  5724. EXECV_CHAR **envlist;
  5725. Py_ssize_t argc, envc;
  5726. PyInterpreterState *interp = _PyInterpreterState_GET();
  5727. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_EXEC)) {
  5728. PyErr_SetString(PyExc_RuntimeError,
  5729. "exec not supported for isolated subinterpreters");
  5730. return NULL;
  5731. }
  5732. /* execve has three arguments: (path, argv, env), where
  5733. argv is a list or tuple of strings and env is a dictionary
  5734. like posix.environ. */
  5735. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  5736. PyErr_SetString(PyExc_TypeError,
  5737. "execve: argv must be a tuple or list");
  5738. goto fail_0;
  5739. }
  5740. argc = PySequence_Size(argv);
  5741. if (argc < 1) {
  5742. PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
  5743. return NULL;
  5744. }
  5745. if (!PyMapping_Check(env)) {
  5746. PyErr_SetString(PyExc_TypeError,
  5747. "execve: environment must be a mapping object");
  5748. goto fail_0;
  5749. }
  5750. argvlist = parse_arglist(argv, &argc);
  5751. if (argvlist == NULL) {
  5752. goto fail_0;
  5753. }
  5754. if (!argvlist[0][0]) {
  5755. PyErr_SetString(PyExc_ValueError,
  5756. "execve: argv first element cannot be empty");
  5757. goto fail_0;
  5758. }
  5759. envlist = parse_envlist(env, &envc);
  5760. if (envlist == NULL)
  5761. goto fail_0;
  5762. if (PySys_Audit("os.exec", "OOO", path->object, argv, env) < 0) {
  5763. goto fail_1;
  5764. }
  5765. _Py_BEGIN_SUPPRESS_IPH
  5766. #ifdef HAVE_FEXECVE
  5767. if (path->fd > -1)
  5768. fexecve(path->fd, argvlist, envlist);
  5769. else
  5770. #endif
  5771. #ifdef HAVE_WEXECV
  5772. _wexecve(path->wide, argvlist, envlist);
  5773. #else
  5774. execve(path->narrow, argvlist, envlist);
  5775. #endif
  5776. _Py_END_SUPPRESS_IPH
  5777. /* If we get here it's definitely an error */
  5778. posix_path_error(path);
  5779. fail_1:
  5780. free_string_array(envlist, envc);
  5781. fail_0:
  5782. if (argvlist)
  5783. free_string_array(argvlist, argc);
  5784. return NULL;
  5785. }
  5786. #endif /* HAVE_EXECV */
  5787. #ifdef HAVE_POSIX_SPAWN
  5788. enum posix_spawn_file_actions_identifier {
  5789. POSIX_SPAWN_OPEN,
  5790. POSIX_SPAWN_CLOSE,
  5791. POSIX_SPAWN_DUP2
  5792. };
  5793. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  5794. static int
  5795. convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res);
  5796. #endif
  5797. static int
  5798. parse_posix_spawn_flags(PyObject *module, const char *func_name, PyObject *setpgroup,
  5799. int resetids, int setsid, PyObject *setsigmask,
  5800. PyObject *setsigdef, PyObject *scheduler,
  5801. posix_spawnattr_t *attrp)
  5802. {
  5803. long all_flags = 0;
  5804. errno = posix_spawnattr_init(attrp);
  5805. if (errno) {
  5806. posix_error();
  5807. return -1;
  5808. }
  5809. if (setpgroup) {
  5810. pid_t pgid = PyLong_AsPid(setpgroup);
  5811. if (pgid == (pid_t)-1 && PyErr_Occurred()) {
  5812. goto fail;
  5813. }
  5814. errno = posix_spawnattr_setpgroup(attrp, pgid);
  5815. if (errno) {
  5816. posix_error();
  5817. goto fail;
  5818. }
  5819. all_flags |= POSIX_SPAWN_SETPGROUP;
  5820. }
  5821. if (resetids) {
  5822. all_flags |= POSIX_SPAWN_RESETIDS;
  5823. }
  5824. if (setsid) {
  5825. #ifdef HAVE_POSIX_SPAWN_SETSID_RUNTIME
  5826. if (HAVE_POSIX_SPAWN_SETSID_RUNTIME) {
  5827. #endif
  5828. #ifdef POSIX_SPAWN_SETSID
  5829. all_flags |= POSIX_SPAWN_SETSID;
  5830. #elif defined(POSIX_SPAWN_SETSID_NP)
  5831. all_flags |= POSIX_SPAWN_SETSID_NP;
  5832. #else
  5833. argument_unavailable_error(func_name, "setsid");
  5834. return -1;
  5835. #endif
  5836. #ifdef HAVE_POSIX_SPAWN_SETSID_RUNTIME
  5837. } else {
  5838. argument_unavailable_error(func_name, "setsid");
  5839. return -1;
  5840. }
  5841. #endif /* HAVE_POSIX_SPAWN_SETSID_RUNTIME */
  5842. }
  5843. #ifdef HAVE_SIGSET_T
  5844. if (setsigmask) {
  5845. sigset_t set;
  5846. if (!_Py_Sigset_Converter(setsigmask, &set)) {
  5847. goto fail;
  5848. }
  5849. errno = posix_spawnattr_setsigmask(attrp, &set);
  5850. if (errno) {
  5851. posix_error();
  5852. goto fail;
  5853. }
  5854. all_flags |= POSIX_SPAWN_SETSIGMASK;
  5855. }
  5856. if (setsigdef) {
  5857. sigset_t set;
  5858. if (!_Py_Sigset_Converter(setsigdef, &set)) {
  5859. goto fail;
  5860. }
  5861. errno = posix_spawnattr_setsigdefault(attrp, &set);
  5862. if (errno) {
  5863. posix_error();
  5864. goto fail;
  5865. }
  5866. all_flags |= POSIX_SPAWN_SETSIGDEF;
  5867. }
  5868. #else
  5869. if (setsigmask || setsigdef) {
  5870. PyErr_SetString(PyExc_NotImplementedError,
  5871. "sigset is not supported on this platform");
  5872. goto fail;
  5873. }
  5874. #endif
  5875. if (scheduler) {
  5876. #ifdef POSIX_SPAWN_SETSCHEDULER
  5877. PyObject *py_schedpolicy;
  5878. PyObject *schedparam_obj;
  5879. struct sched_param schedparam;
  5880. if (!PyArg_ParseTuple(scheduler, "OO"
  5881. ";A scheduler tuple must have two elements",
  5882. &py_schedpolicy, &schedparam_obj)) {
  5883. goto fail;
  5884. }
  5885. if (!convert_sched_param(module, schedparam_obj, &schedparam)) {
  5886. goto fail;
  5887. }
  5888. if (py_schedpolicy != Py_None) {
  5889. int schedpolicy = _PyLong_AsInt(py_schedpolicy);
  5890. if (schedpolicy == -1 && PyErr_Occurred()) {
  5891. goto fail;
  5892. }
  5893. errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
  5894. if (errno) {
  5895. posix_error();
  5896. goto fail;
  5897. }
  5898. all_flags |= POSIX_SPAWN_SETSCHEDULER;
  5899. }
  5900. errno = posix_spawnattr_setschedparam(attrp, &schedparam);
  5901. if (errno) {
  5902. posix_error();
  5903. goto fail;
  5904. }
  5905. all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
  5906. #else
  5907. PyErr_SetString(PyExc_NotImplementedError,
  5908. "The scheduler option is not supported in this system.");
  5909. goto fail;
  5910. #endif
  5911. }
  5912. errno = posix_spawnattr_setflags(attrp, all_flags);
  5913. if (errno) {
  5914. posix_error();
  5915. goto fail;
  5916. }
  5917. return 0;
  5918. fail:
  5919. (void)posix_spawnattr_destroy(attrp);
  5920. return -1;
  5921. }
  5922. static int
  5923. parse_file_actions(PyObject *file_actions,
  5924. posix_spawn_file_actions_t *file_actionsp,
  5925. PyObject *temp_buffer)
  5926. {
  5927. PyObject *seq;
  5928. PyObject *file_action = NULL;
  5929. PyObject *tag_obj;
  5930. seq = PySequence_Fast(file_actions,
  5931. "file_actions must be a sequence or None");
  5932. if (seq == NULL) {
  5933. return -1;
  5934. }
  5935. errno = posix_spawn_file_actions_init(file_actionsp);
  5936. if (errno) {
  5937. posix_error();
  5938. Py_DECREF(seq);
  5939. return -1;
  5940. }
  5941. for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
  5942. file_action = PySequence_Fast_GET_ITEM(seq, i);
  5943. Py_INCREF(file_action);
  5944. if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
  5945. PyErr_SetString(PyExc_TypeError,
  5946. "Each file_actions element must be a non-empty tuple");
  5947. goto fail;
  5948. }
  5949. long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
  5950. if (tag == -1 && PyErr_Occurred()) {
  5951. goto fail;
  5952. }
  5953. /* Populate the file_actions object */
  5954. switch (tag) {
  5955. case POSIX_SPAWN_OPEN: {
  5956. int fd, oflag;
  5957. PyObject *path;
  5958. unsigned long mode;
  5959. if (!PyArg_ParseTuple(file_action, "OiO&ik"
  5960. ";A open file_action tuple must have 5 elements",
  5961. &tag_obj, &fd, PyUnicode_FSConverter, &path,
  5962. &oflag, &mode))
  5963. {
  5964. goto fail;
  5965. }
  5966. if (PyList_Append(temp_buffer, path)) {
  5967. Py_DECREF(path);
  5968. goto fail;
  5969. }
  5970. errno = posix_spawn_file_actions_addopen(file_actionsp,
  5971. fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
  5972. if (errno) {
  5973. posix_error();
  5974. Py_DECREF(path);
  5975. goto fail;
  5976. }
  5977. Py_DECREF(path);
  5978. break;
  5979. }
  5980. case POSIX_SPAWN_CLOSE: {
  5981. int fd;
  5982. if (!PyArg_ParseTuple(file_action, "Oi"
  5983. ";A close file_action tuple must have 2 elements",
  5984. &tag_obj, &fd))
  5985. {
  5986. goto fail;
  5987. }
  5988. errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
  5989. if (errno) {
  5990. posix_error();
  5991. goto fail;
  5992. }
  5993. break;
  5994. }
  5995. case POSIX_SPAWN_DUP2: {
  5996. int fd1, fd2;
  5997. if (!PyArg_ParseTuple(file_action, "Oii"
  5998. ";A dup2 file_action tuple must have 3 elements",
  5999. &tag_obj, &fd1, &fd2))
  6000. {
  6001. goto fail;
  6002. }
  6003. errno = posix_spawn_file_actions_adddup2(file_actionsp,
  6004. fd1, fd2);
  6005. if (errno) {
  6006. posix_error();
  6007. goto fail;
  6008. }
  6009. break;
  6010. }
  6011. default: {
  6012. PyErr_SetString(PyExc_TypeError,
  6013. "Unknown file_actions identifier");
  6014. goto fail;
  6015. }
  6016. }
  6017. Py_DECREF(file_action);
  6018. }
  6019. Py_DECREF(seq);
  6020. return 0;
  6021. fail:
  6022. Py_DECREF(seq);
  6023. Py_DECREF(file_action);
  6024. (void)posix_spawn_file_actions_destroy(file_actionsp);
  6025. return -1;
  6026. }
  6027. static PyObject *
  6028. py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
  6029. PyObject *env, PyObject *file_actions,
  6030. PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
  6031. PyObject *setsigdef, PyObject *scheduler)
  6032. {
  6033. const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
  6034. EXECV_CHAR **argvlist = NULL;
  6035. EXECV_CHAR **envlist = NULL;
  6036. posix_spawn_file_actions_t file_actions_buf;
  6037. posix_spawn_file_actions_t *file_actionsp = NULL;
  6038. posix_spawnattr_t attr;
  6039. posix_spawnattr_t *attrp = NULL;
  6040. Py_ssize_t argc, envc;
  6041. PyObject *result = NULL;
  6042. PyObject *temp_buffer = NULL;
  6043. pid_t pid;
  6044. int err_code;
  6045. /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
  6046. argv is a list or tuple of strings and env is a dictionary
  6047. like posix.environ. */
  6048. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  6049. PyErr_Format(PyExc_TypeError,
  6050. "%s: argv must be a tuple or list", func_name);
  6051. goto exit;
  6052. }
  6053. argc = PySequence_Size(argv);
  6054. if (argc < 1) {
  6055. PyErr_Format(PyExc_ValueError,
  6056. "%s: argv must not be empty", func_name);
  6057. return NULL;
  6058. }
  6059. if (!PyMapping_Check(env)) {
  6060. PyErr_Format(PyExc_TypeError,
  6061. "%s: environment must be a mapping object", func_name);
  6062. goto exit;
  6063. }
  6064. argvlist = parse_arglist(argv, &argc);
  6065. if (argvlist == NULL) {
  6066. goto exit;
  6067. }
  6068. if (!argvlist[0][0]) {
  6069. PyErr_Format(PyExc_ValueError,
  6070. "%s: argv first element cannot be empty", func_name);
  6071. goto exit;
  6072. }
  6073. envlist = parse_envlist(env, &envc);
  6074. if (envlist == NULL) {
  6075. goto exit;
  6076. }
  6077. if (file_actions != NULL && file_actions != Py_None) {
  6078. /* There is a bug in old versions of glibc that makes some of the
  6079. * helper functions for manipulating file actions not copy the provided
  6080. * buffers. The problem is that posix_spawn_file_actions_addopen does not
  6081. * copy the value of path for some old versions of glibc (<2.20).
  6082. * The use of temp_buffer here is a workaround that keeps the
  6083. * python objects that own the buffers alive until posix_spawn gets called.
  6084. * Check https://bugs.python.org/issue33630 and
  6085. * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
  6086. temp_buffer = PyList_New(0);
  6087. if (!temp_buffer) {
  6088. goto exit;
  6089. }
  6090. if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
  6091. goto exit;
  6092. }
  6093. file_actionsp = &file_actions_buf;
  6094. }
  6095. if (parse_posix_spawn_flags(module, func_name, setpgroup, resetids, setsid,
  6096. setsigmask, setsigdef, scheduler, &attr)) {
  6097. goto exit;
  6098. }
  6099. attrp = &attr;
  6100. if (PySys_Audit("os.posix_spawn", "OOO", path->object, argv, env) < 0) {
  6101. goto exit;
  6102. }
  6103. _Py_BEGIN_SUPPRESS_IPH
  6104. #ifdef HAVE_POSIX_SPAWNP
  6105. if (use_posix_spawnp) {
  6106. err_code = posix_spawnp(&pid, path->narrow,
  6107. file_actionsp, attrp, argvlist, envlist);
  6108. }
  6109. else
  6110. #endif /* HAVE_POSIX_SPAWNP */
  6111. {
  6112. err_code = posix_spawn(&pid, path->narrow,
  6113. file_actionsp, attrp, argvlist, envlist);
  6114. }
  6115. _Py_END_SUPPRESS_IPH
  6116. if (err_code) {
  6117. errno = err_code;
  6118. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
  6119. goto exit;
  6120. }
  6121. #ifdef _Py_MEMORY_SANITIZER
  6122. __msan_unpoison(&pid, sizeof(pid));
  6123. #endif
  6124. result = PyLong_FromPid(pid);
  6125. exit:
  6126. if (file_actionsp) {
  6127. (void)posix_spawn_file_actions_destroy(file_actionsp);
  6128. }
  6129. if (attrp) {
  6130. (void)posix_spawnattr_destroy(attrp);
  6131. }
  6132. if (envlist) {
  6133. free_string_array(envlist, envc);
  6134. }
  6135. if (argvlist) {
  6136. free_string_array(argvlist, argc);
  6137. }
  6138. Py_XDECREF(temp_buffer);
  6139. return result;
  6140. }
  6141. /*[clinic input]
  6142. os.posix_spawn
  6143. path: path_t
  6144. Path of executable file.
  6145. argv: object
  6146. Tuple or list of strings.
  6147. env: object
  6148. Dictionary of strings mapping to strings.
  6149. /
  6150. *
  6151. file_actions: object(c_default='NULL') = ()
  6152. A sequence of file action tuples.
  6153. setpgroup: object = NULL
  6154. The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
  6155. resetids: bool = False
  6156. If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
  6157. setsid: bool = False
  6158. If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
  6159. setsigmask: object(c_default='NULL') = ()
  6160. The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
  6161. setsigdef: object(c_default='NULL') = ()
  6162. The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
  6163. scheduler: object = NULL
  6164. A tuple with the scheduler policy (optional) and parameters.
  6165. Execute the program specified by path in a new process.
  6166. [clinic start generated code]*/
  6167. static PyObject *
  6168. os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
  6169. PyObject *env, PyObject *file_actions,
  6170. PyObject *setpgroup, int resetids, int setsid,
  6171. PyObject *setsigmask, PyObject *setsigdef,
  6172. PyObject *scheduler)
  6173. /*[clinic end generated code: output=14a1098c566bc675 input=808aed1090d84e33]*/
  6174. {
  6175. return py_posix_spawn(0, module, path, argv, env, file_actions,
  6176. setpgroup, resetids, setsid, setsigmask, setsigdef,
  6177. scheduler);
  6178. }
  6179. #endif /* HAVE_POSIX_SPAWN */
  6180. #ifdef HAVE_POSIX_SPAWNP
  6181. /*[clinic input]
  6182. os.posix_spawnp
  6183. path: path_t
  6184. Path of executable file.
  6185. argv: object
  6186. Tuple or list of strings.
  6187. env: object
  6188. Dictionary of strings mapping to strings.
  6189. /
  6190. *
  6191. file_actions: object(c_default='NULL') = ()
  6192. A sequence of file action tuples.
  6193. setpgroup: object = NULL
  6194. The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
  6195. resetids: bool = False
  6196. If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
  6197. setsid: bool = False
  6198. If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
  6199. setsigmask: object(c_default='NULL') = ()
  6200. The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
  6201. setsigdef: object(c_default='NULL') = ()
  6202. The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
  6203. scheduler: object = NULL
  6204. A tuple with the scheduler policy (optional) and parameters.
  6205. Execute the program specified by path in a new process.
  6206. [clinic start generated code]*/
  6207. static PyObject *
  6208. os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
  6209. PyObject *env, PyObject *file_actions,
  6210. PyObject *setpgroup, int resetids, int setsid,
  6211. PyObject *setsigmask, PyObject *setsigdef,
  6212. PyObject *scheduler)
  6213. /*[clinic end generated code: output=7b9aaefe3031238d input=9e89e616116752a1]*/
  6214. {
  6215. return py_posix_spawn(1, module, path, argv, env, file_actions,
  6216. setpgroup, resetids, setsid, setsigmask, setsigdef,
  6217. scheduler);
  6218. }
  6219. #endif /* HAVE_POSIX_SPAWNP */
  6220. #ifdef HAVE_RTPSPAWN
  6221. static intptr_t
  6222. _rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
  6223. const char *envp[])
  6224. {
  6225. RTP_ID rtpid;
  6226. int status;
  6227. pid_t res;
  6228. int async_err = 0;
  6229. /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
  6230. uStackSize=0 cannot be used, the default stack size is too small for
  6231. Python. */
  6232. if (envp) {
  6233. rtpid = rtpSpawn(rtpFileName, argv, envp,
  6234. 100, 0x1000000, 0, VX_FP_TASK);
  6235. }
  6236. else {
  6237. rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
  6238. 100, 0x1000000, 0, VX_FP_TASK);
  6239. }
  6240. if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
  6241. do {
  6242. res = waitpid((pid_t)rtpid, &status, 0);
  6243. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  6244. if (res < 0)
  6245. return RTP_ID_ERROR;
  6246. return ((intptr_t)status);
  6247. }
  6248. return ((intptr_t)rtpid);
  6249. }
  6250. #endif
  6251. #if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
  6252. /*[clinic input]
  6253. os.spawnv
  6254. mode: int
  6255. Mode of process creation.
  6256. path: path_t
  6257. Path of executable file.
  6258. argv: object
  6259. Tuple or list of strings.
  6260. /
  6261. Execute the program specified by path in a new process.
  6262. [clinic start generated code]*/
  6263. static PyObject *
  6264. os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
  6265. /*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
  6266. {
  6267. EXECV_CHAR **argvlist;
  6268. int i;
  6269. Py_ssize_t argc;
  6270. intptr_t spawnval;
  6271. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  6272. /* spawnv has three arguments: (mode, path, argv), where
  6273. argv is a list or tuple of strings. */
  6274. if (PyList_Check(argv)) {
  6275. argc = PyList_Size(argv);
  6276. getitem = PyList_GetItem;
  6277. }
  6278. else if (PyTuple_Check(argv)) {
  6279. argc = PyTuple_Size(argv);
  6280. getitem = PyTuple_GetItem;
  6281. }
  6282. else {
  6283. PyErr_SetString(PyExc_TypeError,
  6284. "spawnv() arg 2 must be a tuple or list");
  6285. return NULL;
  6286. }
  6287. if (argc == 0) {
  6288. PyErr_SetString(PyExc_ValueError,
  6289. "spawnv() arg 2 cannot be empty");
  6290. return NULL;
  6291. }
  6292. argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
  6293. if (argvlist == NULL) {
  6294. return PyErr_NoMemory();
  6295. }
  6296. for (i = 0; i < argc; i++) {
  6297. if (!fsconvert_strdup((*getitem)(argv, i),
  6298. &argvlist[i])) {
  6299. free_string_array(argvlist, i);
  6300. PyErr_SetString(
  6301. PyExc_TypeError,
  6302. "spawnv() arg 2 must contain only strings");
  6303. return NULL;
  6304. }
  6305. if (i == 0 && !argvlist[0][0]) {
  6306. free_string_array(argvlist, i + 1);
  6307. PyErr_SetString(
  6308. PyExc_ValueError,
  6309. "spawnv() arg 2 first element cannot be empty");
  6310. return NULL;
  6311. }
  6312. }
  6313. argvlist[argc] = NULL;
  6314. #if !defined(HAVE_RTPSPAWN)
  6315. if (mode == _OLD_P_OVERLAY)
  6316. mode = _P_OVERLAY;
  6317. #endif
  6318. if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv,
  6319. Py_None) < 0) {
  6320. free_string_array(argvlist, argc);
  6321. return NULL;
  6322. }
  6323. Py_BEGIN_ALLOW_THREADS
  6324. _Py_BEGIN_SUPPRESS_IPH
  6325. #ifdef HAVE_WSPAWNV
  6326. spawnval = _wspawnv(mode, path->wide, argvlist);
  6327. #elif defined(HAVE_RTPSPAWN)
  6328. spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
  6329. #else
  6330. spawnval = _spawnv(mode, path->narrow, argvlist);
  6331. #endif
  6332. _Py_END_SUPPRESS_IPH
  6333. Py_END_ALLOW_THREADS
  6334. int saved_errno = errno;
  6335. free_string_array(argvlist, argc);
  6336. if (spawnval == -1) {
  6337. errno = saved_errno;
  6338. posix_error();
  6339. return NULL;
  6340. }
  6341. return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
  6342. }
  6343. /*[clinic input]
  6344. os.spawnve
  6345. mode: int
  6346. Mode of process creation.
  6347. path: path_t
  6348. Path of executable file.
  6349. argv: object
  6350. Tuple or list of strings.
  6351. env: object
  6352. Dictionary of strings mapping to strings.
  6353. /
  6354. Execute the program specified by path in a new process.
  6355. [clinic start generated code]*/
  6356. static PyObject *
  6357. os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
  6358. PyObject *env)
  6359. /*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
  6360. {
  6361. EXECV_CHAR **argvlist;
  6362. EXECV_CHAR **envlist;
  6363. PyObject *res = NULL;
  6364. Py_ssize_t argc, i, envc;
  6365. intptr_t spawnval;
  6366. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  6367. Py_ssize_t lastarg = 0;
  6368. /* spawnve has four arguments: (mode, path, argv, env), where
  6369. argv is a list or tuple of strings and env is a dictionary
  6370. like posix.environ. */
  6371. if (PyList_Check(argv)) {
  6372. argc = PyList_Size(argv);
  6373. getitem = PyList_GetItem;
  6374. }
  6375. else if (PyTuple_Check(argv)) {
  6376. argc = PyTuple_Size(argv);
  6377. getitem = PyTuple_GetItem;
  6378. }
  6379. else {
  6380. PyErr_SetString(PyExc_TypeError,
  6381. "spawnve() arg 2 must be a tuple or list");
  6382. goto fail_0;
  6383. }
  6384. if (argc == 0) {
  6385. PyErr_SetString(PyExc_ValueError,
  6386. "spawnve() arg 2 cannot be empty");
  6387. goto fail_0;
  6388. }
  6389. if (!PyMapping_Check(env)) {
  6390. PyErr_SetString(PyExc_TypeError,
  6391. "spawnve() arg 3 must be a mapping object");
  6392. goto fail_0;
  6393. }
  6394. argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
  6395. if (argvlist == NULL) {
  6396. PyErr_NoMemory();
  6397. goto fail_0;
  6398. }
  6399. for (i = 0; i < argc; i++) {
  6400. if (!fsconvert_strdup((*getitem)(argv, i),
  6401. &argvlist[i]))
  6402. {
  6403. lastarg = i;
  6404. goto fail_1;
  6405. }
  6406. if (i == 0 && !argvlist[0][0]) {
  6407. lastarg = i + 1;
  6408. PyErr_SetString(
  6409. PyExc_ValueError,
  6410. "spawnv() arg 2 first element cannot be empty");
  6411. goto fail_1;
  6412. }
  6413. }
  6414. lastarg = argc;
  6415. argvlist[argc] = NULL;
  6416. envlist = parse_envlist(env, &envc);
  6417. if (envlist == NULL)
  6418. goto fail_1;
  6419. #if !defined(HAVE_RTPSPAWN)
  6420. if (mode == _OLD_P_OVERLAY)
  6421. mode = _P_OVERLAY;
  6422. #endif
  6423. if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv, env) < 0) {
  6424. goto fail_2;
  6425. }
  6426. Py_BEGIN_ALLOW_THREADS
  6427. _Py_BEGIN_SUPPRESS_IPH
  6428. #ifdef HAVE_WSPAWNV
  6429. spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
  6430. #elif defined(HAVE_RTPSPAWN)
  6431. spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
  6432. (const char **)envlist);
  6433. #else
  6434. spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
  6435. #endif
  6436. _Py_END_SUPPRESS_IPH
  6437. Py_END_ALLOW_THREADS
  6438. if (spawnval == -1)
  6439. (void) posix_error();
  6440. else
  6441. res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
  6442. fail_2:
  6443. while (--envc >= 0) {
  6444. PyMem_Free(envlist[envc]);
  6445. }
  6446. PyMem_Free(envlist);
  6447. fail_1:
  6448. free_string_array(argvlist, lastarg);
  6449. fail_0:
  6450. return res;
  6451. }
  6452. #endif /* HAVE_SPAWNV */
  6453. #ifdef HAVE_FORK
  6454. /* Helper function to validate arguments.
  6455. Returns 0 on success. non-zero on failure with a TypeError raised.
  6456. If obj is non-NULL it must be callable. */
  6457. static int
  6458. check_null_or_callable(PyObject *obj, const char* obj_name)
  6459. {
  6460. if (obj && !PyCallable_Check(obj)) {
  6461. PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
  6462. obj_name, _PyType_Name(Py_TYPE(obj)));
  6463. return -1;
  6464. }
  6465. return 0;
  6466. }
  6467. /*[clinic input]
  6468. os.register_at_fork
  6469. *
  6470. before: object=NULL
  6471. A callable to be called in the parent before the fork() syscall.
  6472. after_in_child: object=NULL
  6473. A callable to be called in the child after fork().
  6474. after_in_parent: object=NULL
  6475. A callable to be called in the parent after fork().
  6476. Register callables to be called when forking a new process.
  6477. 'before' callbacks are called in reverse order.
  6478. 'after_in_child' and 'after_in_parent' callbacks are called in order.
  6479. [clinic start generated code]*/
  6480. static PyObject *
  6481. os_register_at_fork_impl(PyObject *module, PyObject *before,
  6482. PyObject *after_in_child, PyObject *after_in_parent)
  6483. /*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
  6484. {
  6485. PyInterpreterState *interp;
  6486. if (!before && !after_in_child && !after_in_parent) {
  6487. PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
  6488. return NULL;
  6489. }
  6490. if (check_null_or_callable(before, "before") ||
  6491. check_null_or_callable(after_in_child, "after_in_child") ||
  6492. check_null_or_callable(after_in_parent, "after_in_parent")) {
  6493. return NULL;
  6494. }
  6495. interp = _PyInterpreterState_GET();
  6496. if (register_at_forker(&interp->before_forkers, before)) {
  6497. return NULL;
  6498. }
  6499. if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
  6500. return NULL;
  6501. }
  6502. if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
  6503. return NULL;
  6504. }
  6505. Py_RETURN_NONE;
  6506. }
  6507. #endif /* HAVE_FORK */
  6508. #if defined(HAVE_FORK1) || defined(HAVE_FORKPTY) || defined(HAVE_FORK)
  6509. // Common code to raise a warning if we detect there is more than one thread
  6510. // running in the process. Best effort, silent if unable to count threads.
  6511. // Constraint: Quick. Never overcounts. Never leaves an error set.
  6512. //
  6513. // This code might do an import, thus acquiring the import lock, which
  6514. // PyOS_BeforeFork() also does. As this should only be called from
  6515. // the parent process, it is in the same thread so that works.
  6516. static void warn_about_fork_with_threads(const char* name) {
  6517. // TODO: Consider making an `os` module API to return the current number
  6518. // of threads in the process. That'd presumably use this platform code but
  6519. // raise an error rather than using the inaccurate fallback.
  6520. Py_ssize_t num_python_threads = 0;
  6521. #if defined(__APPLE__) && defined(HAVE_GETPID)
  6522. mach_port_t macos_self = mach_task_self();
  6523. mach_port_t macos_task;
  6524. if (task_for_pid(macos_self, getpid(), &macos_task) == KERN_SUCCESS) {
  6525. thread_array_t macos_threads;
  6526. mach_msg_type_number_t macos_n_threads;
  6527. if (task_threads(macos_task, &macos_threads,
  6528. &macos_n_threads) == KERN_SUCCESS) {
  6529. num_python_threads = macos_n_threads;
  6530. }
  6531. }
  6532. #elif defined(__linux__)
  6533. // Linux /proc/self/stat 20th field is the number of threads.
  6534. FILE* proc_stat = fopen("/proc/self/stat", "r");
  6535. if (proc_stat) {
  6536. size_t n;
  6537. // Size chosen arbitrarily. ~60% more bytes than a 20th column index
  6538. // observed on the author's workstation.
  6539. char stat_line[160];
  6540. n = fread(&stat_line, 1, 159, proc_stat);
  6541. stat_line[n] = '\0';
  6542. fclose(proc_stat);
  6543. char *saveptr = NULL;
  6544. char *field = strtok_r(stat_line, " ", &saveptr);
  6545. unsigned int idx;
  6546. for (idx = 19; idx && field; --idx) {
  6547. field = strtok_r(NULL, " ", &saveptr);
  6548. }
  6549. if (idx == 0 && field) { // found the 20th field
  6550. num_python_threads = atoi(field); // 0 on error
  6551. }
  6552. }
  6553. #endif
  6554. if (num_python_threads <= 0) {
  6555. // Fall back to just the number our threading module knows about.
  6556. // An incomplete view of the world, but better than nothing.
  6557. PyObject *threading = PyImport_GetModule(&_Py_ID(threading));
  6558. if (!threading) {
  6559. PyErr_Clear();
  6560. return;
  6561. }
  6562. PyObject *threading_active =
  6563. PyObject_GetAttr(threading, &_Py_ID(_active));
  6564. if (!threading_active) {
  6565. PyErr_Clear();
  6566. Py_DECREF(threading);
  6567. return;
  6568. }
  6569. PyObject *threading_limbo =
  6570. PyObject_GetAttr(threading, &_Py_ID(_limbo));
  6571. if (!threading_limbo) {
  6572. PyErr_Clear();
  6573. Py_DECREF(threading);
  6574. Py_DECREF(threading_active);
  6575. return;
  6576. }
  6577. Py_DECREF(threading);
  6578. // Duplicating what threading.active_count() does but without holding
  6579. // threading._active_limbo_lock so our count could be inaccurate if
  6580. // these dicts are mid-update from another thread. Not a big deal.
  6581. // Worst case if someone replaced threading._active or threading._limbo
  6582. // with non-dicts, we get -1 from *Length() below and undercount.
  6583. // Nobody should, but we're best effort so we clear errors and move on.
  6584. num_python_threads = (PyMapping_Length(threading_active)
  6585. + PyMapping_Length(threading_limbo));
  6586. PyErr_Clear();
  6587. Py_DECREF(threading_active);
  6588. Py_DECREF(threading_limbo);
  6589. }
  6590. if (num_python_threads > 1) {
  6591. PyErr_WarnFormat(
  6592. PyExc_DeprecationWarning, 1,
  6593. #ifdef HAVE_GETPID
  6594. "This process (pid=%d) is multi-threaded, "
  6595. #else
  6596. "This process is multi-threaded, "
  6597. #endif
  6598. "use of %s() may lead to deadlocks in the child.",
  6599. #ifdef HAVE_GETPID
  6600. getpid(),
  6601. #endif
  6602. name);
  6603. PyErr_Clear();
  6604. }
  6605. }
  6606. #endif // HAVE_FORK1 || HAVE_FORKPTY || HAVE_FORK
  6607. #ifdef HAVE_FORK1
  6608. /*[clinic input]
  6609. os.fork1
  6610. Fork a child process with a single multiplexed (i.e., not bound) thread.
  6611. Return 0 to child process and PID of child to parent process.
  6612. [clinic start generated code]*/
  6613. static PyObject *
  6614. os_fork1_impl(PyObject *module)
  6615. /*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
  6616. {
  6617. pid_t pid;
  6618. PyInterpreterState *interp = _PyInterpreterState_GET();
  6619. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  6620. PyErr_SetString(PyExc_RuntimeError,
  6621. "can't fork at interpreter shutdown");
  6622. return NULL;
  6623. }
  6624. if (!_Py_IsMainInterpreter(interp)) {
  6625. PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
  6626. return NULL;
  6627. }
  6628. PyOS_BeforeFork();
  6629. pid = fork1();
  6630. int saved_errno = errno;
  6631. if (pid == 0) {
  6632. /* child: this clobbers and resets the import lock. */
  6633. PyOS_AfterFork_Child();
  6634. } else {
  6635. warn_about_fork_with_threads("fork1");
  6636. /* parent: release the import lock. */
  6637. PyOS_AfterFork_Parent();
  6638. }
  6639. if (pid == -1) {
  6640. errno = saved_errno;
  6641. return posix_error();
  6642. }
  6643. return PyLong_FromPid(pid);
  6644. }
  6645. #endif /* HAVE_FORK1 */
  6646. #ifdef HAVE_FORK
  6647. /*[clinic input]
  6648. os.fork
  6649. Fork a child process.
  6650. Return 0 to child process and PID of child to parent process.
  6651. [clinic start generated code]*/
  6652. static PyObject *
  6653. os_fork_impl(PyObject *module)
  6654. /*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
  6655. {
  6656. pid_t pid;
  6657. PyInterpreterState *interp = _PyInterpreterState_GET();
  6658. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  6659. PyErr_SetString(PyExc_RuntimeError,
  6660. "can't fork at interpreter shutdown");
  6661. return NULL;
  6662. }
  6663. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_FORK)) {
  6664. PyErr_SetString(PyExc_RuntimeError,
  6665. "fork not supported for isolated subinterpreters");
  6666. return NULL;
  6667. }
  6668. if (PySys_Audit("os.fork", NULL) < 0) {
  6669. return NULL;
  6670. }
  6671. PyOS_BeforeFork();
  6672. pid = fork();
  6673. int saved_errno = errno;
  6674. if (pid == 0) {
  6675. /* child: this clobbers and resets the import lock. */
  6676. PyOS_AfterFork_Child();
  6677. } else {
  6678. warn_about_fork_with_threads("fork");
  6679. /* parent: release the import lock. */
  6680. PyOS_AfterFork_Parent();
  6681. }
  6682. if (pid == -1) {
  6683. errno = saved_errno;
  6684. return posix_error();
  6685. }
  6686. return PyLong_FromPid(pid);
  6687. }
  6688. #endif /* HAVE_FORK */
  6689. #ifdef HAVE_SCHED_H
  6690. #ifdef HAVE_SCHED_GET_PRIORITY_MAX
  6691. /*[clinic input]
  6692. os.sched_get_priority_max
  6693. policy: int
  6694. Get the maximum scheduling priority for policy.
  6695. [clinic start generated code]*/
  6696. static PyObject *
  6697. os_sched_get_priority_max_impl(PyObject *module, int policy)
  6698. /*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
  6699. {
  6700. int max;
  6701. max = sched_get_priority_max(policy);
  6702. if (max < 0)
  6703. return posix_error();
  6704. return PyLong_FromLong(max);
  6705. }
  6706. /*[clinic input]
  6707. os.sched_get_priority_min
  6708. policy: int
  6709. Get the minimum scheduling priority for policy.
  6710. [clinic start generated code]*/
  6711. static PyObject *
  6712. os_sched_get_priority_min_impl(PyObject *module, int policy)
  6713. /*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
  6714. {
  6715. int min = sched_get_priority_min(policy);
  6716. if (min < 0)
  6717. return posix_error();
  6718. return PyLong_FromLong(min);
  6719. }
  6720. #endif /* HAVE_SCHED_GET_PRIORITY_MAX */
  6721. #ifdef HAVE_SCHED_SETSCHEDULER
  6722. /*[clinic input]
  6723. os.sched_getscheduler
  6724. pid: pid_t
  6725. /
  6726. Get the scheduling policy for the process identified by pid.
  6727. Passing 0 for pid returns the scheduling policy for the calling process.
  6728. [clinic start generated code]*/
  6729. static PyObject *
  6730. os_sched_getscheduler_impl(PyObject *module, pid_t pid)
  6731. /*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
  6732. {
  6733. int policy;
  6734. policy = sched_getscheduler(pid);
  6735. if (policy < 0)
  6736. return posix_error();
  6737. return PyLong_FromLong(policy);
  6738. }
  6739. #endif /* HAVE_SCHED_SETSCHEDULER */
  6740. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  6741. /*[clinic input]
  6742. class os.sched_param "PyObject *" "SchedParamType"
  6743. @classmethod
  6744. os.sched_param.__new__
  6745. sched_priority: object
  6746. A scheduling parameter.
  6747. Currently has only one field: sched_priority
  6748. [clinic start generated code]*/
  6749. static PyObject *
  6750. os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
  6751. /*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
  6752. {
  6753. PyObject *res;
  6754. res = PyStructSequence_New(type);
  6755. if (!res)
  6756. return NULL;
  6757. PyStructSequence_SET_ITEM(res, 0, Py_NewRef(sched_priority));
  6758. return res;
  6759. }
  6760. PyDoc_VAR(os_sched_param__doc__);
  6761. static PyStructSequence_Field sched_param_fields[] = {
  6762. {"sched_priority", "the scheduling priority"},
  6763. {0}
  6764. };
  6765. static PyStructSequence_Desc sched_param_desc = {
  6766. "sched_param", /* name */
  6767. os_sched_param__doc__, /* doc */
  6768. sched_param_fields,
  6769. 1
  6770. };
  6771. static int
  6772. convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res)
  6773. {
  6774. long priority;
  6775. if (!Py_IS_TYPE(param, (PyTypeObject *)get_posix_state(module)->SchedParamType)) {
  6776. PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
  6777. return 0;
  6778. }
  6779. priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
  6780. if (priority == -1 && PyErr_Occurred())
  6781. return 0;
  6782. if (priority > INT_MAX || priority < INT_MIN) {
  6783. PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
  6784. return 0;
  6785. }
  6786. res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
  6787. return 1;
  6788. }
  6789. #endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
  6790. #ifdef HAVE_SCHED_SETSCHEDULER
  6791. /*[clinic input]
  6792. os.sched_setscheduler
  6793. pid: pid_t
  6794. policy: int
  6795. param as param_obj: object
  6796. /
  6797. Set the scheduling policy for the process identified by pid.
  6798. If pid is 0, the calling process is changed.
  6799. param is an instance of sched_param.
  6800. [clinic start generated code]*/
  6801. static PyObject *
  6802. os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
  6803. PyObject *param_obj)
  6804. /*[clinic end generated code: output=cde27faa55dc993e input=73013d731bd8fbe9]*/
  6805. {
  6806. struct sched_param param;
  6807. if (!convert_sched_param(module, param_obj, &param)) {
  6808. return NULL;
  6809. }
  6810. /*
  6811. ** sched_setscheduler() returns 0 in Linux, but the previous
  6812. ** scheduling policy under Solaris/Illumos, and others.
  6813. ** On error, -1 is returned in all Operating Systems.
  6814. */
  6815. if (sched_setscheduler(pid, policy, &param) == -1)
  6816. return posix_error();
  6817. Py_RETURN_NONE;
  6818. }
  6819. #endif /* HAVE_SCHED_SETSCHEDULER*/
  6820. #ifdef HAVE_SCHED_SETPARAM
  6821. /*[clinic input]
  6822. os.sched_getparam
  6823. pid: pid_t
  6824. /
  6825. Returns scheduling parameters for the process identified by pid.
  6826. If pid is 0, returns parameters for the calling process.
  6827. Return value is an instance of sched_param.
  6828. [clinic start generated code]*/
  6829. static PyObject *
  6830. os_sched_getparam_impl(PyObject *module, pid_t pid)
  6831. /*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
  6832. {
  6833. struct sched_param param;
  6834. PyObject *result;
  6835. PyObject *priority;
  6836. if (sched_getparam(pid, &param))
  6837. return posix_error();
  6838. PyObject *SchedParamType = get_posix_state(module)->SchedParamType;
  6839. result = PyStructSequence_New((PyTypeObject *)SchedParamType);
  6840. if (!result)
  6841. return NULL;
  6842. priority = PyLong_FromLong(param.sched_priority);
  6843. if (!priority) {
  6844. Py_DECREF(result);
  6845. return NULL;
  6846. }
  6847. PyStructSequence_SET_ITEM(result, 0, priority);
  6848. return result;
  6849. }
  6850. /*[clinic input]
  6851. os.sched_setparam
  6852. pid: pid_t
  6853. param as param_obj: object
  6854. /
  6855. Set scheduling parameters for the process identified by pid.
  6856. If pid is 0, sets parameters for the calling process.
  6857. param should be an instance of sched_param.
  6858. [clinic start generated code]*/
  6859. static PyObject *
  6860. os_sched_setparam_impl(PyObject *module, pid_t pid, PyObject *param_obj)
  6861. /*[clinic end generated code: output=f19fe020a53741c1 input=27b98337c8b2dcc7]*/
  6862. {
  6863. struct sched_param param;
  6864. if (!convert_sched_param(module, param_obj, &param)) {
  6865. return NULL;
  6866. }
  6867. if (sched_setparam(pid, &param))
  6868. return posix_error();
  6869. Py_RETURN_NONE;
  6870. }
  6871. #endif /* HAVE_SCHED_SETPARAM */
  6872. #ifdef HAVE_SCHED_RR_GET_INTERVAL
  6873. /*[clinic input]
  6874. os.sched_rr_get_interval -> double
  6875. pid: pid_t
  6876. /
  6877. Return the round-robin quantum for the process identified by pid, in seconds.
  6878. Value returned is a float.
  6879. [clinic start generated code]*/
  6880. static double
  6881. os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
  6882. /*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
  6883. {
  6884. struct timespec interval;
  6885. if (sched_rr_get_interval(pid, &interval)) {
  6886. posix_error();
  6887. return -1.0;
  6888. }
  6889. #ifdef _Py_MEMORY_SANITIZER
  6890. __msan_unpoison(&interval, sizeof(interval));
  6891. #endif
  6892. return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
  6893. }
  6894. #endif /* HAVE_SCHED_RR_GET_INTERVAL */
  6895. /*[clinic input]
  6896. os.sched_yield
  6897. Voluntarily relinquish the CPU.
  6898. [clinic start generated code]*/
  6899. static PyObject *
  6900. os_sched_yield_impl(PyObject *module)
  6901. /*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
  6902. {
  6903. int result;
  6904. Py_BEGIN_ALLOW_THREADS
  6905. result = sched_yield();
  6906. Py_END_ALLOW_THREADS
  6907. if (result < 0) {
  6908. return posix_error();
  6909. }
  6910. Py_RETURN_NONE;
  6911. }
  6912. #ifdef HAVE_SCHED_SETAFFINITY
  6913. /* The minimum number of CPUs allocated in a cpu_set_t */
  6914. static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
  6915. /*[clinic input]
  6916. os.sched_setaffinity
  6917. pid: pid_t
  6918. mask : object
  6919. /
  6920. Set the CPU affinity of the process identified by pid to mask.
  6921. mask should be an iterable of integers identifying CPUs.
  6922. [clinic start generated code]*/
  6923. static PyObject *
  6924. os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
  6925. /*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
  6926. {
  6927. int ncpus;
  6928. size_t setsize;
  6929. cpu_set_t *cpu_set = NULL;
  6930. PyObject *iterator = NULL, *item;
  6931. iterator = PyObject_GetIter(mask);
  6932. if (iterator == NULL)
  6933. return NULL;
  6934. ncpus = NCPUS_START;
  6935. setsize = CPU_ALLOC_SIZE(ncpus);
  6936. cpu_set = CPU_ALLOC(ncpus);
  6937. if (cpu_set == NULL) {
  6938. PyErr_NoMemory();
  6939. goto error;
  6940. }
  6941. CPU_ZERO_S(setsize, cpu_set);
  6942. while ((item = PyIter_Next(iterator))) {
  6943. long cpu;
  6944. if (!PyLong_Check(item)) {
  6945. PyErr_Format(PyExc_TypeError,
  6946. "expected an iterator of ints, "
  6947. "but iterator yielded %R",
  6948. Py_TYPE(item));
  6949. Py_DECREF(item);
  6950. goto error;
  6951. }
  6952. cpu = PyLong_AsLong(item);
  6953. Py_DECREF(item);
  6954. if (cpu < 0) {
  6955. if (!PyErr_Occurred())
  6956. PyErr_SetString(PyExc_ValueError, "negative CPU number");
  6957. goto error;
  6958. }
  6959. if (cpu > INT_MAX - 1) {
  6960. PyErr_SetString(PyExc_OverflowError, "CPU number too large");
  6961. goto error;
  6962. }
  6963. if (cpu >= ncpus) {
  6964. /* Grow CPU mask to fit the CPU number */
  6965. int newncpus = ncpus;
  6966. cpu_set_t *newmask;
  6967. size_t newsetsize;
  6968. while (newncpus <= cpu) {
  6969. if (newncpus > INT_MAX / 2)
  6970. newncpus = cpu + 1;
  6971. else
  6972. newncpus = newncpus * 2;
  6973. }
  6974. newmask = CPU_ALLOC(newncpus);
  6975. if (newmask == NULL) {
  6976. PyErr_NoMemory();
  6977. goto error;
  6978. }
  6979. newsetsize = CPU_ALLOC_SIZE(newncpus);
  6980. CPU_ZERO_S(newsetsize, newmask);
  6981. memcpy(newmask, cpu_set, setsize);
  6982. CPU_FREE(cpu_set);
  6983. setsize = newsetsize;
  6984. cpu_set = newmask;
  6985. ncpus = newncpus;
  6986. }
  6987. CPU_SET_S(cpu, setsize, cpu_set);
  6988. }
  6989. if (PyErr_Occurred()) {
  6990. goto error;
  6991. }
  6992. Py_CLEAR(iterator);
  6993. if (sched_setaffinity(pid, setsize, cpu_set)) {
  6994. posix_error();
  6995. goto error;
  6996. }
  6997. CPU_FREE(cpu_set);
  6998. Py_RETURN_NONE;
  6999. error:
  7000. if (cpu_set)
  7001. CPU_FREE(cpu_set);
  7002. Py_XDECREF(iterator);
  7003. return NULL;
  7004. }
  7005. /*[clinic input]
  7006. os.sched_getaffinity
  7007. pid: pid_t
  7008. /
  7009. Return the affinity of the process identified by pid (or the current process if zero).
  7010. The affinity is returned as a set of CPU identifiers.
  7011. [clinic start generated code]*/
  7012. static PyObject *
  7013. os_sched_getaffinity_impl(PyObject *module, pid_t pid)
  7014. /*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
  7015. {
  7016. int cpu, ncpus, count;
  7017. size_t setsize;
  7018. cpu_set_t *mask = NULL;
  7019. PyObject *res = NULL;
  7020. ncpus = NCPUS_START;
  7021. while (1) {
  7022. setsize = CPU_ALLOC_SIZE(ncpus);
  7023. mask = CPU_ALLOC(ncpus);
  7024. if (mask == NULL)
  7025. return PyErr_NoMemory();
  7026. if (sched_getaffinity(pid, setsize, mask) == 0)
  7027. break;
  7028. CPU_FREE(mask);
  7029. if (errno != EINVAL)
  7030. return posix_error();
  7031. if (ncpus > INT_MAX / 2) {
  7032. PyErr_SetString(PyExc_OverflowError, "could not allocate "
  7033. "a large enough CPU set");
  7034. return NULL;
  7035. }
  7036. ncpus = ncpus * 2;
  7037. }
  7038. res = PySet_New(NULL);
  7039. if (res == NULL)
  7040. goto error;
  7041. for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
  7042. if (CPU_ISSET_S(cpu, setsize, mask)) {
  7043. PyObject *cpu_num = PyLong_FromLong(cpu);
  7044. --count;
  7045. if (cpu_num == NULL)
  7046. goto error;
  7047. if (PySet_Add(res, cpu_num)) {
  7048. Py_DECREF(cpu_num);
  7049. goto error;
  7050. }
  7051. Py_DECREF(cpu_num);
  7052. }
  7053. }
  7054. CPU_FREE(mask);
  7055. return res;
  7056. error:
  7057. if (mask)
  7058. CPU_FREE(mask);
  7059. Py_XDECREF(res);
  7060. return NULL;
  7061. }
  7062. #endif /* HAVE_SCHED_SETAFFINITY */
  7063. #endif /* HAVE_SCHED_H */
  7064. /* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
  7065. #if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
  7066. # define DEV_PTY_FILE "/dev/ptc"
  7067. # define HAVE_DEV_PTMX
  7068. #else
  7069. # define DEV_PTY_FILE "/dev/ptmx"
  7070. #endif
  7071. #if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX)
  7072. #ifdef HAVE_PTY_H
  7073. #include <pty.h>
  7074. #ifdef HAVE_UTMP_H
  7075. #include <utmp.h>
  7076. #endif /* HAVE_UTMP_H */
  7077. #elif defined(HAVE_LIBUTIL_H)
  7078. #include <libutil.h>
  7079. #elif defined(HAVE_UTIL_H)
  7080. #include <util.h>
  7081. #endif /* HAVE_PTY_H */
  7082. #ifdef HAVE_STROPTS_H
  7083. #include <stropts.h>
  7084. #else
  7085. #define __SID ('S' << 8)
  7086. #define I_PUSH (__SID | 2)
  7087. #endif
  7088. #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX) */
  7089. #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
  7090. /*[clinic input]
  7091. os.openpty
  7092. Open a pseudo-terminal.
  7093. Return a tuple of (master_fd, slave_fd) containing open file descriptors
  7094. for both the master and slave ends.
  7095. [clinic start generated code]*/
  7096. static PyObject *
  7097. os_openpty_impl(PyObject *module)
  7098. /*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
  7099. {
  7100. int master_fd = -1, slave_fd = -1;
  7101. #ifndef HAVE_OPENPTY
  7102. char * slave_name;
  7103. #endif
  7104. #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
  7105. PyOS_sighandler_t sig_saved;
  7106. #if defined(__sun) && defined(__SVR4)
  7107. extern char *ptsname(int fildes);
  7108. #endif
  7109. #endif
  7110. #ifdef HAVE_OPENPTY
  7111. if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
  7112. goto posix_error;
  7113. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7114. goto error;
  7115. if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
  7116. goto error;
  7117. #elif defined(HAVE__GETPTY)
  7118. slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
  7119. if (slave_name == NULL)
  7120. goto posix_error;
  7121. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7122. goto error;
  7123. slave_fd = _Py_open(slave_name, O_RDWR);
  7124. if (slave_fd < 0)
  7125. goto error;
  7126. #else
  7127. master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
  7128. if (master_fd < 0)
  7129. goto posix_error;
  7130. sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
  7131. /* change permission of slave */
  7132. if (grantpt(master_fd) < 0) {
  7133. int saved_errno = errno;
  7134. PyOS_setsig(SIGCHLD, sig_saved);
  7135. errno = saved_errno;
  7136. goto posix_error;
  7137. }
  7138. /* unlock slave */
  7139. if (unlockpt(master_fd) < 0) {
  7140. int saved_errno = errno;
  7141. PyOS_setsig(SIGCHLD, sig_saved);
  7142. errno = saved_errno;
  7143. goto posix_error;
  7144. }
  7145. PyOS_setsig(SIGCHLD, sig_saved);
  7146. slave_name = ptsname(master_fd); /* get name of slave */
  7147. if (slave_name == NULL)
  7148. goto posix_error;
  7149. slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
  7150. if (slave_fd == -1)
  7151. goto error;
  7152. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7153. goto posix_error;
  7154. #if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
  7155. ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
  7156. ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
  7157. #ifndef __hpux
  7158. ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
  7159. #endif /* __hpux */
  7160. #endif /* HAVE_CYGWIN */
  7161. #endif /* HAVE_OPENPTY */
  7162. return Py_BuildValue("(ii)", master_fd, slave_fd);
  7163. posix_error:
  7164. posix_error();
  7165. error:
  7166. if (master_fd != -1)
  7167. close(master_fd);
  7168. if (slave_fd != -1)
  7169. close(slave_fd);
  7170. return NULL;
  7171. }
  7172. #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
  7173. #if defined(HAVE_SETSID) && defined(TIOCSCTTY)
  7174. #define HAVE_FALLBACK_LOGIN_TTY 1
  7175. #endif /* defined(HAVE_SETSID) && defined(TIOCSCTTY) */
  7176. #if defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY)
  7177. /*[clinic input]
  7178. os.login_tty
  7179. fd: fildes
  7180. /
  7181. Prepare the tty of which fd is a file descriptor for a new login session.
  7182. Make the calling process a session leader; make the tty the
  7183. controlling tty, the stdin, the stdout, and the stderr of the
  7184. calling process; close fd.
  7185. [clinic start generated code]*/
  7186. static PyObject *
  7187. os_login_tty_impl(PyObject *module, int fd)
  7188. /*[clinic end generated code: output=495a79911b4cc1bc input=5f298565099903a2]*/
  7189. {
  7190. #ifdef HAVE_LOGIN_TTY
  7191. if (login_tty(fd) == -1) {
  7192. return posix_error();
  7193. }
  7194. #else /* defined(HAVE_FALLBACK_LOGIN_TTY) */
  7195. /* Establish a new session. */
  7196. if (setsid() == -1) {
  7197. return posix_error();
  7198. }
  7199. /* The tty becomes the controlling terminal. */
  7200. if (ioctl(fd, TIOCSCTTY, (char *)NULL) == -1) {
  7201. return posix_error();
  7202. }
  7203. /* The tty becomes stdin/stdout/stderr */
  7204. if (dup2(fd, 0) == -1 || dup2(fd, 1) == -1 || dup2(fd, 2) == -1) {
  7205. return posix_error();
  7206. }
  7207. if (fd > 2) {
  7208. close(fd);
  7209. }
  7210. #endif /* HAVE_LOGIN_TTY */
  7211. Py_RETURN_NONE;
  7212. }
  7213. #endif /* defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY) */
  7214. #ifdef HAVE_FORKPTY
  7215. /*[clinic input]
  7216. os.forkpty
  7217. Fork a new process with a new pseudo-terminal as controlling tty.
  7218. Returns a tuple of (pid, master_fd).
  7219. Like fork(), return pid of 0 to the child process,
  7220. and pid of child to the parent process.
  7221. To both, return fd of newly opened pseudo-terminal.
  7222. [clinic start generated code]*/
  7223. static PyObject *
  7224. os_forkpty_impl(PyObject *module)
  7225. /*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
  7226. {
  7227. int master_fd = -1;
  7228. pid_t pid;
  7229. PyInterpreterState *interp = _PyInterpreterState_GET();
  7230. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  7231. PyErr_SetString(PyExc_RuntimeError,
  7232. "can't fork at interpreter shutdown");
  7233. return NULL;
  7234. }
  7235. if (!_Py_IsMainInterpreter(interp)) {
  7236. PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
  7237. return NULL;
  7238. }
  7239. if (PySys_Audit("os.forkpty", NULL) < 0) {
  7240. return NULL;
  7241. }
  7242. PyOS_BeforeFork();
  7243. pid = forkpty(&master_fd, NULL, NULL, NULL);
  7244. if (pid == 0) {
  7245. /* child: this clobbers and resets the import lock. */
  7246. PyOS_AfterFork_Child();
  7247. } else {
  7248. warn_about_fork_with_threads("forkpty");
  7249. /* parent: release the import lock. */
  7250. PyOS_AfterFork_Parent();
  7251. }
  7252. if (pid == -1) {
  7253. return posix_error();
  7254. }
  7255. return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
  7256. }
  7257. #endif /* HAVE_FORKPTY */
  7258. #ifdef HAVE_GETEGID
  7259. /*[clinic input]
  7260. os.getegid
  7261. Return the current process's effective group id.
  7262. [clinic start generated code]*/
  7263. static PyObject *
  7264. os_getegid_impl(PyObject *module)
  7265. /*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
  7266. {
  7267. return _PyLong_FromGid(getegid());
  7268. }
  7269. #endif /* HAVE_GETEGID */
  7270. #ifdef HAVE_GETEUID
  7271. /*[clinic input]
  7272. os.geteuid
  7273. Return the current process's effective user id.
  7274. [clinic start generated code]*/
  7275. static PyObject *
  7276. os_geteuid_impl(PyObject *module)
  7277. /*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
  7278. {
  7279. return _PyLong_FromUid(geteuid());
  7280. }
  7281. #endif /* HAVE_GETEUID */
  7282. #ifdef HAVE_GETGID
  7283. /*[clinic input]
  7284. os.getgid
  7285. Return the current process's group id.
  7286. [clinic start generated code]*/
  7287. static PyObject *
  7288. os_getgid_impl(PyObject *module)
  7289. /*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
  7290. {
  7291. return _PyLong_FromGid(getgid());
  7292. }
  7293. #endif /* HAVE_GETGID */
  7294. #if defined(HAVE_GETPID)
  7295. /*[clinic input]
  7296. os.getpid
  7297. Return the current process id.
  7298. [clinic start generated code]*/
  7299. static PyObject *
  7300. os_getpid_impl(PyObject *module)
  7301. /*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
  7302. {
  7303. #if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  7304. return PyLong_FromPid(getpid());
  7305. #else
  7306. return PyLong_FromUnsignedLong(GetCurrentProcessId());
  7307. #endif
  7308. }
  7309. #endif /* defined(HAVE_GETPID) */
  7310. #ifdef NGROUPS_MAX
  7311. #define MAX_GROUPS NGROUPS_MAX
  7312. #else
  7313. /* defined to be 16 on Solaris7, so this should be a small number */
  7314. #define MAX_GROUPS 64
  7315. #endif
  7316. #ifdef HAVE_GETGROUPLIST
  7317. #ifdef __APPLE__
  7318. /*[clinic input]
  7319. os.getgrouplist
  7320. user: str
  7321. username to lookup
  7322. group as basegid: int
  7323. base group id of the user
  7324. /
  7325. Returns a list of groups to which a user belongs.
  7326. [clinic start generated code]*/
  7327. static PyObject *
  7328. os_getgrouplist_impl(PyObject *module, const char *user, int basegid)
  7329. /*[clinic end generated code: output=6e734697b8c26de0 input=f8d870374b09a490]*/
  7330. #else
  7331. /*[clinic input]
  7332. os.getgrouplist
  7333. user: str
  7334. username to lookup
  7335. group as basegid: gid_t
  7336. base group id of the user
  7337. /
  7338. Returns a list of groups to which a user belongs.
  7339. [clinic start generated code]*/
  7340. static PyObject *
  7341. os_getgrouplist_impl(PyObject *module, const char *user, gid_t basegid)
  7342. /*[clinic end generated code: output=0ebd7fb70115575b input=cc61d5c20b08958d]*/
  7343. #endif
  7344. {
  7345. int i, ngroups;
  7346. PyObject *list;
  7347. #ifdef __APPLE__
  7348. int *groups;
  7349. #else
  7350. gid_t *groups;
  7351. #endif
  7352. /*
  7353. * NGROUPS_MAX is defined by POSIX.1 as the maximum
  7354. * number of supplimental groups a users can belong to.
  7355. * We have to increment it by one because
  7356. * getgrouplist() returns both the supplemental groups
  7357. * and the primary group, i.e. all of the groups the
  7358. * user belongs to.
  7359. */
  7360. ngroups = 1 + MAX_GROUPS;
  7361. while (1) {
  7362. #ifdef __APPLE__
  7363. groups = PyMem_New(int, ngroups);
  7364. #else
  7365. groups = PyMem_New(gid_t, ngroups);
  7366. #endif
  7367. if (groups == NULL) {
  7368. return PyErr_NoMemory();
  7369. }
  7370. int old_ngroups = ngroups;
  7371. if (getgrouplist(user, basegid, groups, &ngroups) != -1) {
  7372. /* Success */
  7373. break;
  7374. }
  7375. /* getgrouplist() fails if the group list is too small */
  7376. PyMem_Free(groups);
  7377. if (ngroups > old_ngroups) {
  7378. /* If the group list is too small, the glibc implementation of
  7379. getgrouplist() sets ngroups to the total number of groups and
  7380. returns -1. */
  7381. }
  7382. else {
  7383. /* Double the group list size */
  7384. if (ngroups > INT_MAX / 2) {
  7385. return PyErr_NoMemory();
  7386. }
  7387. ngroups *= 2;
  7388. }
  7389. /* Retry getgrouplist() with a larger group list */
  7390. }
  7391. #ifdef _Py_MEMORY_SANITIZER
  7392. /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
  7393. __msan_unpoison(&ngroups, sizeof(ngroups));
  7394. __msan_unpoison(groups, ngroups*sizeof(*groups));
  7395. #endif
  7396. list = PyList_New(ngroups);
  7397. if (list == NULL) {
  7398. PyMem_Free(groups);
  7399. return NULL;
  7400. }
  7401. for (i = 0; i < ngroups; i++) {
  7402. #ifdef __APPLE__
  7403. PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
  7404. #else
  7405. PyObject *o = _PyLong_FromGid(groups[i]);
  7406. #endif
  7407. if (o == NULL) {
  7408. Py_DECREF(list);
  7409. PyMem_Free(groups);
  7410. return NULL;
  7411. }
  7412. PyList_SET_ITEM(list, i, o);
  7413. }
  7414. PyMem_Free(groups);
  7415. return list;
  7416. }
  7417. #endif /* HAVE_GETGROUPLIST */
  7418. #ifdef HAVE_GETGROUPS
  7419. /*[clinic input]
  7420. os.getgroups
  7421. Return list of supplemental group IDs for the process.
  7422. [clinic start generated code]*/
  7423. static PyObject *
  7424. os_getgroups_impl(PyObject *module)
  7425. /*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
  7426. {
  7427. // Call getgroups with length 0 to get the actual number of groups
  7428. int n = getgroups(0, NULL);
  7429. if (n < 0) {
  7430. return posix_error();
  7431. }
  7432. if (n == 0) {
  7433. return PyList_New(0);
  7434. }
  7435. gid_t *grouplist = PyMem_New(gid_t, n);
  7436. if (grouplist == NULL) {
  7437. return PyErr_NoMemory();
  7438. }
  7439. n = getgroups(n, grouplist);
  7440. if (n == -1) {
  7441. posix_error();
  7442. PyMem_Free(grouplist);
  7443. return NULL;
  7444. }
  7445. PyObject *result = PyList_New(n);
  7446. if (result == NULL) {
  7447. goto error;
  7448. }
  7449. for (int i = 0; i < n; ++i) {
  7450. PyObject *group = _PyLong_FromGid(grouplist[i]);
  7451. if (group == NULL) {
  7452. goto error;
  7453. }
  7454. PyList_SET_ITEM(result, i, group);
  7455. }
  7456. PyMem_Free(grouplist);
  7457. return result;
  7458. error:
  7459. PyMem_Free(grouplist);
  7460. Py_XDECREF(result);
  7461. return NULL;
  7462. }
  7463. #endif /* HAVE_GETGROUPS */
  7464. #ifdef HAVE_INITGROUPS
  7465. #ifdef __APPLE__
  7466. /*[clinic input]
  7467. os.initgroups
  7468. username as oname: FSConverter
  7469. gid: int
  7470. /
  7471. Initialize the group access list.
  7472. Call the system initgroups() to initialize the group access list with all of
  7473. the groups of which the specified username is a member, plus the specified
  7474. group id.
  7475. [clinic start generated code]*/
  7476. static PyObject *
  7477. os_initgroups_impl(PyObject *module, PyObject *oname, int gid)
  7478. /*[clinic end generated code: output=7f074d30a425fd3a input=df3d54331b0af204]*/
  7479. #else
  7480. /*[clinic input]
  7481. os.initgroups
  7482. username as oname: FSConverter
  7483. gid: gid_t
  7484. /
  7485. Initialize the group access list.
  7486. Call the system initgroups() to initialize the group access list with all of
  7487. the groups of which the specified username is a member, plus the specified
  7488. group id.
  7489. [clinic start generated code]*/
  7490. static PyObject *
  7491. os_initgroups_impl(PyObject *module, PyObject *oname, gid_t gid)
  7492. /*[clinic end generated code: output=59341244521a9e3f input=0cb91bdc59a4c564]*/
  7493. #endif
  7494. {
  7495. const char *username = PyBytes_AS_STRING(oname);
  7496. if (initgroups(username, gid) == -1)
  7497. return PyErr_SetFromErrno(PyExc_OSError);
  7498. Py_RETURN_NONE;
  7499. }
  7500. #endif /* HAVE_INITGROUPS */
  7501. #ifdef HAVE_GETPGID
  7502. /*[clinic input]
  7503. os.getpgid
  7504. pid: pid_t
  7505. Call the system call getpgid(), and return the result.
  7506. [clinic start generated code]*/
  7507. static PyObject *
  7508. os_getpgid_impl(PyObject *module, pid_t pid)
  7509. /*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
  7510. {
  7511. pid_t pgid = getpgid(pid);
  7512. if (pgid < 0)
  7513. return posix_error();
  7514. return PyLong_FromPid(pgid);
  7515. }
  7516. #endif /* HAVE_GETPGID */
  7517. #ifdef HAVE_GETPGRP
  7518. /*[clinic input]
  7519. os.getpgrp
  7520. Return the current process group id.
  7521. [clinic start generated code]*/
  7522. static PyObject *
  7523. os_getpgrp_impl(PyObject *module)
  7524. /*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
  7525. {
  7526. #ifdef GETPGRP_HAVE_ARG
  7527. return PyLong_FromPid(getpgrp(0));
  7528. #else /* GETPGRP_HAVE_ARG */
  7529. return PyLong_FromPid(getpgrp());
  7530. #endif /* GETPGRP_HAVE_ARG */
  7531. }
  7532. #endif /* HAVE_GETPGRP */
  7533. #ifdef HAVE_SETPGRP
  7534. /*[clinic input]
  7535. os.setpgrp
  7536. Make the current process the leader of its process group.
  7537. [clinic start generated code]*/
  7538. static PyObject *
  7539. os_setpgrp_impl(PyObject *module)
  7540. /*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
  7541. {
  7542. #ifdef SETPGRP_HAVE_ARG
  7543. if (setpgrp(0, 0) < 0)
  7544. #else /* SETPGRP_HAVE_ARG */
  7545. if (setpgrp() < 0)
  7546. #endif /* SETPGRP_HAVE_ARG */
  7547. return posix_error();
  7548. Py_RETURN_NONE;
  7549. }
  7550. #endif /* HAVE_SETPGRP */
  7551. #ifdef HAVE_GETPPID
  7552. #ifdef MS_WINDOWS
  7553. #include <processsnapshot.h>
  7554. static PyObject*
  7555. win32_getppid(void)
  7556. {
  7557. DWORD error;
  7558. PyObject* result = NULL;
  7559. HANDLE process = GetCurrentProcess();
  7560. HPSS snapshot = NULL;
  7561. error = PssCaptureSnapshot(process, PSS_CAPTURE_NONE, 0, &snapshot);
  7562. if (error != ERROR_SUCCESS) {
  7563. return PyErr_SetFromWindowsErr(error);
  7564. }
  7565. PSS_PROCESS_INFORMATION info;
  7566. error = PssQuerySnapshot(snapshot, PSS_QUERY_PROCESS_INFORMATION, &info,
  7567. sizeof(info));
  7568. if (error == ERROR_SUCCESS) {
  7569. result = PyLong_FromUnsignedLong(info.ParentProcessId);
  7570. }
  7571. else {
  7572. result = PyErr_SetFromWindowsErr(error);
  7573. }
  7574. PssFreeSnapshot(process, snapshot);
  7575. return result;
  7576. }
  7577. #endif /*MS_WINDOWS*/
  7578. /*[clinic input]
  7579. os.getppid
  7580. Return the parent's process id.
  7581. If the parent process has already exited, Windows machines will still
  7582. return its id; others systems will return the id of the 'init' process (1).
  7583. [clinic start generated code]*/
  7584. static PyObject *
  7585. os_getppid_impl(PyObject *module)
  7586. /*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
  7587. {
  7588. #ifdef MS_WINDOWS
  7589. return win32_getppid();
  7590. #else
  7591. return PyLong_FromPid(getppid());
  7592. #endif
  7593. }
  7594. #endif /* HAVE_GETPPID */
  7595. #ifdef HAVE_GETLOGIN
  7596. /*[clinic input]
  7597. os.getlogin
  7598. Return the actual login name.
  7599. [clinic start generated code]*/
  7600. static PyObject *
  7601. os_getlogin_impl(PyObject *module)
  7602. /*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
  7603. {
  7604. PyObject *result = NULL;
  7605. #ifdef MS_WINDOWS
  7606. wchar_t user_name[UNLEN + 1];
  7607. DWORD num_chars = Py_ARRAY_LENGTH(user_name);
  7608. if (GetUserNameW(user_name, &num_chars)) {
  7609. /* num_chars is the number of unicode chars plus null terminator */
  7610. result = PyUnicode_FromWideChar(user_name, num_chars - 1);
  7611. }
  7612. else
  7613. result = PyErr_SetFromWindowsErr(GetLastError());
  7614. #else
  7615. char *name;
  7616. int old_errno = errno;
  7617. errno = 0;
  7618. name = getlogin();
  7619. if (name == NULL) {
  7620. if (errno)
  7621. posix_error();
  7622. else
  7623. PyErr_SetString(PyExc_OSError, "unable to determine login name");
  7624. }
  7625. else
  7626. result = PyUnicode_DecodeFSDefault(name);
  7627. errno = old_errno;
  7628. #endif
  7629. return result;
  7630. }
  7631. #endif /* HAVE_GETLOGIN */
  7632. #ifdef HAVE_GETUID
  7633. /*[clinic input]
  7634. os.getuid
  7635. Return the current process's user id.
  7636. [clinic start generated code]*/
  7637. static PyObject *
  7638. os_getuid_impl(PyObject *module)
  7639. /*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
  7640. {
  7641. return _PyLong_FromUid(getuid());
  7642. }
  7643. #endif /* HAVE_GETUID */
  7644. #ifdef MS_WINDOWS
  7645. #define HAVE_KILL
  7646. #endif /* MS_WINDOWS */
  7647. #ifdef HAVE_KILL
  7648. /*[clinic input]
  7649. os.kill
  7650. pid: pid_t
  7651. signal: Py_ssize_t
  7652. /
  7653. Kill a process with a signal.
  7654. [clinic start generated code]*/
  7655. static PyObject *
  7656. os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
  7657. /*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
  7658. {
  7659. if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
  7660. return NULL;
  7661. }
  7662. #ifndef MS_WINDOWS
  7663. if (kill(pid, (int)signal) == -1) {
  7664. return posix_error();
  7665. }
  7666. // Check immediately if the signal was sent to the current process.
  7667. // Don't micro-optimize pid == getpid(), since PyErr_SetString() check
  7668. // is cheap.
  7669. if (PyErr_CheckSignals()) {
  7670. return NULL;
  7671. }
  7672. Py_RETURN_NONE;
  7673. #else /* !MS_WINDOWS */
  7674. PyObject *result;
  7675. DWORD sig = (DWORD)signal;
  7676. DWORD err;
  7677. HANDLE handle;
  7678. #ifdef HAVE_WINDOWS_CONSOLE_IO
  7679. /* Console processes which share a common console can be sent CTRL+C or
  7680. CTRL+BREAK events, provided they handle said events. */
  7681. if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
  7682. if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
  7683. err = GetLastError();
  7684. PyErr_SetFromWindowsErr(err);
  7685. }
  7686. else {
  7687. Py_RETURN_NONE;
  7688. }
  7689. }
  7690. #endif /* HAVE_WINDOWS_CONSOLE_IO */
  7691. /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
  7692. attempt to open and terminate the process. */
  7693. handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
  7694. if (handle == NULL) {
  7695. err = GetLastError();
  7696. return PyErr_SetFromWindowsErr(err);
  7697. }
  7698. if (TerminateProcess(handle, sig) == 0) {
  7699. err = GetLastError();
  7700. result = PyErr_SetFromWindowsErr(err);
  7701. } else {
  7702. result = Py_NewRef(Py_None);
  7703. }
  7704. CloseHandle(handle);
  7705. return result;
  7706. #endif /* !MS_WINDOWS */
  7707. }
  7708. #endif /* HAVE_KILL */
  7709. #ifdef HAVE_KILLPG
  7710. /*[clinic input]
  7711. os.killpg
  7712. pgid: pid_t
  7713. signal: int
  7714. /
  7715. Kill a process group with a signal.
  7716. [clinic start generated code]*/
  7717. static PyObject *
  7718. os_killpg_impl(PyObject *module, pid_t pgid, int signal)
  7719. /*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
  7720. {
  7721. if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
  7722. return NULL;
  7723. }
  7724. /* XXX some man pages make the `pgid` parameter an int, others
  7725. a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
  7726. take the same type. Moreover, pid_t is always at least as wide as
  7727. int (else compilation of this module fails), which is safe. */
  7728. if (killpg(pgid, signal) == -1)
  7729. return posix_error();
  7730. Py_RETURN_NONE;
  7731. }
  7732. #endif /* HAVE_KILLPG */
  7733. #ifdef HAVE_PLOCK
  7734. #ifdef HAVE_SYS_LOCK_H
  7735. #include <sys/lock.h>
  7736. #endif
  7737. /*[clinic input]
  7738. os.plock
  7739. op: int
  7740. /
  7741. Lock program segments into memory.");
  7742. [clinic start generated code]*/
  7743. static PyObject *
  7744. os_plock_impl(PyObject *module, int op)
  7745. /*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
  7746. {
  7747. if (plock(op) == -1)
  7748. return posix_error();
  7749. Py_RETURN_NONE;
  7750. }
  7751. #endif /* HAVE_PLOCK */
  7752. #ifdef HAVE_SETUID
  7753. /*[clinic input]
  7754. os.setuid
  7755. uid: uid_t
  7756. /
  7757. Set the current process's user id.
  7758. [clinic start generated code]*/
  7759. static PyObject *
  7760. os_setuid_impl(PyObject *module, uid_t uid)
  7761. /*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
  7762. {
  7763. if (setuid(uid) < 0)
  7764. return posix_error();
  7765. Py_RETURN_NONE;
  7766. }
  7767. #endif /* HAVE_SETUID */
  7768. #ifdef HAVE_SETEUID
  7769. /*[clinic input]
  7770. os.seteuid
  7771. euid: uid_t
  7772. /
  7773. Set the current process's effective user id.
  7774. [clinic start generated code]*/
  7775. static PyObject *
  7776. os_seteuid_impl(PyObject *module, uid_t euid)
  7777. /*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
  7778. {
  7779. if (seteuid(euid) < 0)
  7780. return posix_error();
  7781. Py_RETURN_NONE;
  7782. }
  7783. #endif /* HAVE_SETEUID */
  7784. #ifdef HAVE_SETEGID
  7785. /*[clinic input]
  7786. os.setegid
  7787. egid: gid_t
  7788. /
  7789. Set the current process's effective group id.
  7790. [clinic start generated code]*/
  7791. static PyObject *
  7792. os_setegid_impl(PyObject *module, gid_t egid)
  7793. /*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
  7794. {
  7795. if (setegid(egid) < 0)
  7796. return posix_error();
  7797. Py_RETURN_NONE;
  7798. }
  7799. #endif /* HAVE_SETEGID */
  7800. #ifdef HAVE_SETREUID
  7801. /*[clinic input]
  7802. os.setreuid
  7803. ruid: uid_t
  7804. euid: uid_t
  7805. /
  7806. Set the current process's real and effective user ids.
  7807. [clinic start generated code]*/
  7808. static PyObject *
  7809. os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
  7810. /*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
  7811. {
  7812. if (setreuid(ruid, euid) < 0) {
  7813. return posix_error();
  7814. } else {
  7815. Py_RETURN_NONE;
  7816. }
  7817. }
  7818. #endif /* HAVE_SETREUID */
  7819. #ifdef HAVE_SETREGID
  7820. /*[clinic input]
  7821. os.setregid
  7822. rgid: gid_t
  7823. egid: gid_t
  7824. /
  7825. Set the current process's real and effective group ids.
  7826. [clinic start generated code]*/
  7827. static PyObject *
  7828. os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
  7829. /*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
  7830. {
  7831. if (setregid(rgid, egid) < 0)
  7832. return posix_error();
  7833. Py_RETURN_NONE;
  7834. }
  7835. #endif /* HAVE_SETREGID */
  7836. #ifdef HAVE_SETGID
  7837. /*[clinic input]
  7838. os.setgid
  7839. gid: gid_t
  7840. /
  7841. Set the current process's group id.
  7842. [clinic start generated code]*/
  7843. static PyObject *
  7844. os_setgid_impl(PyObject *module, gid_t gid)
  7845. /*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
  7846. {
  7847. if (setgid(gid) < 0)
  7848. return posix_error();
  7849. Py_RETURN_NONE;
  7850. }
  7851. #endif /* HAVE_SETGID */
  7852. #ifdef HAVE_SETGROUPS
  7853. /*[clinic input]
  7854. os.setgroups
  7855. groups: object
  7856. /
  7857. Set the groups of the current process to list.
  7858. [clinic start generated code]*/
  7859. static PyObject *
  7860. os_setgroups(PyObject *module, PyObject *groups)
  7861. /*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
  7862. {
  7863. if (!PySequence_Check(groups)) {
  7864. PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
  7865. return NULL;
  7866. }
  7867. Py_ssize_t len = PySequence_Size(groups);
  7868. if (len < 0) {
  7869. return NULL;
  7870. }
  7871. if (len > MAX_GROUPS) {
  7872. PyErr_SetString(PyExc_ValueError, "too many groups");
  7873. return NULL;
  7874. }
  7875. gid_t *grouplist = PyMem_New(gid_t, len);
  7876. for (Py_ssize_t i = 0; i < len; i++) {
  7877. PyObject *elem;
  7878. elem = PySequence_GetItem(groups, i);
  7879. if (!elem) {
  7880. PyMem_Free(grouplist);
  7881. return NULL;
  7882. }
  7883. if (!PyLong_Check(elem)) {
  7884. PyErr_SetString(PyExc_TypeError,
  7885. "groups must be integers");
  7886. Py_DECREF(elem);
  7887. PyMem_Free(grouplist);
  7888. return NULL;
  7889. } else {
  7890. if (!_Py_Gid_Converter(elem, &grouplist[i])) {
  7891. Py_DECREF(elem);
  7892. PyMem_Free(grouplist);
  7893. return NULL;
  7894. }
  7895. }
  7896. Py_DECREF(elem);
  7897. }
  7898. if (setgroups(len, grouplist) < 0) {
  7899. posix_error();
  7900. PyMem_Free(grouplist);
  7901. return NULL;
  7902. }
  7903. PyMem_Free(grouplist);
  7904. Py_RETURN_NONE;
  7905. }
  7906. #endif /* HAVE_SETGROUPS */
  7907. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  7908. static PyObject *
  7909. wait_helper(PyObject *module, pid_t pid, int status, struct rusage *ru)
  7910. {
  7911. PyObject *result;
  7912. PyObject *struct_rusage;
  7913. if (pid == -1)
  7914. return posix_error();
  7915. // If wait succeeded but no child was ready to report status, ru will not
  7916. // have been populated.
  7917. if (pid == 0) {
  7918. memset(ru, 0, sizeof(*ru));
  7919. }
  7920. struct_rusage = _PyImport_GetModuleAttrString("resource", "struct_rusage");
  7921. if (struct_rusage == NULL)
  7922. return NULL;
  7923. /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
  7924. result = PyStructSequence_New((PyTypeObject*) struct_rusage);
  7925. Py_DECREF(struct_rusage);
  7926. if (!result)
  7927. return NULL;
  7928. int pos = 0;
  7929. #ifndef doubletime
  7930. #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
  7931. #endif
  7932. #define SET_RESULT(CALL) \
  7933. do { \
  7934. PyObject *item = (CALL); \
  7935. if (item == NULL) { \
  7936. Py_DECREF(result); \
  7937. return NULL; \
  7938. } \
  7939. PyStructSequence_SET_ITEM(result, pos++, item); \
  7940. } while(0)
  7941. SET_RESULT(PyFloat_FromDouble(doubletime(ru->ru_utime)));
  7942. SET_RESULT(PyFloat_FromDouble(doubletime(ru->ru_stime)));
  7943. SET_RESULT(PyLong_FromLong(ru->ru_maxrss));
  7944. SET_RESULT(PyLong_FromLong(ru->ru_ixrss));
  7945. SET_RESULT(PyLong_FromLong(ru->ru_idrss));
  7946. SET_RESULT(PyLong_FromLong(ru->ru_isrss));
  7947. SET_RESULT(PyLong_FromLong(ru->ru_minflt));
  7948. SET_RESULT(PyLong_FromLong(ru->ru_majflt));
  7949. SET_RESULT(PyLong_FromLong(ru->ru_nswap));
  7950. SET_RESULT(PyLong_FromLong(ru->ru_inblock));
  7951. SET_RESULT(PyLong_FromLong(ru->ru_oublock));
  7952. SET_RESULT(PyLong_FromLong(ru->ru_msgsnd));
  7953. SET_RESULT(PyLong_FromLong(ru->ru_msgrcv));
  7954. SET_RESULT(PyLong_FromLong(ru->ru_nsignals));
  7955. SET_RESULT(PyLong_FromLong(ru->ru_nvcsw));
  7956. SET_RESULT(PyLong_FromLong(ru->ru_nivcsw));
  7957. #undef SET_RESULT
  7958. return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
  7959. }
  7960. #endif /* HAVE_WAIT3 || HAVE_WAIT4 */
  7961. #ifdef HAVE_WAIT3
  7962. /*[clinic input]
  7963. os.wait3
  7964. options: int
  7965. Wait for completion of a child process.
  7966. Returns a tuple of information about the child process:
  7967. (pid, status, rusage)
  7968. [clinic start generated code]*/
  7969. static PyObject *
  7970. os_wait3_impl(PyObject *module, int options)
  7971. /*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
  7972. {
  7973. pid_t pid;
  7974. struct rusage ru;
  7975. int async_err = 0;
  7976. WAIT_TYPE status;
  7977. WAIT_STATUS_INT(status) = 0;
  7978. do {
  7979. Py_BEGIN_ALLOW_THREADS
  7980. pid = wait3(&status, options, &ru);
  7981. Py_END_ALLOW_THREADS
  7982. } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  7983. if (pid < 0)
  7984. return (!async_err) ? posix_error() : NULL;
  7985. return wait_helper(module, pid, WAIT_STATUS_INT(status), &ru);
  7986. }
  7987. #endif /* HAVE_WAIT3 */
  7988. #ifdef HAVE_WAIT4
  7989. /*[clinic input]
  7990. os.wait4
  7991. pid: pid_t
  7992. options: int
  7993. Wait for completion of a specific child process.
  7994. Returns a tuple of information about the child process:
  7995. (pid, status, rusage)
  7996. [clinic start generated code]*/
  7997. static PyObject *
  7998. os_wait4_impl(PyObject *module, pid_t pid, int options)
  7999. /*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
  8000. {
  8001. pid_t res;
  8002. struct rusage ru;
  8003. int async_err = 0;
  8004. WAIT_TYPE status;
  8005. WAIT_STATUS_INT(status) = 0;
  8006. do {
  8007. Py_BEGIN_ALLOW_THREADS
  8008. res = wait4(pid, &status, options, &ru);
  8009. Py_END_ALLOW_THREADS
  8010. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8011. if (res < 0)
  8012. return (!async_err) ? posix_error() : NULL;
  8013. return wait_helper(module, res, WAIT_STATUS_INT(status), &ru);
  8014. }
  8015. #endif /* HAVE_WAIT4 */
  8016. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  8017. /*[clinic input]
  8018. os.waitid
  8019. idtype: idtype_t
  8020. Must be one of be P_PID, P_PGID or P_ALL.
  8021. id: id_t
  8022. The id to wait on.
  8023. options: int
  8024. Constructed from the ORing of one or more of WEXITED, WSTOPPED
  8025. or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
  8026. /
  8027. Returns the result of waiting for a process or processes.
  8028. Returns either waitid_result or None if WNOHANG is specified and there are
  8029. no children in a waitable state.
  8030. [clinic start generated code]*/
  8031. static PyObject *
  8032. os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
  8033. /*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
  8034. {
  8035. PyObject *result;
  8036. int res;
  8037. int async_err = 0;
  8038. siginfo_t si;
  8039. si.si_pid = 0;
  8040. do {
  8041. Py_BEGIN_ALLOW_THREADS
  8042. res = waitid(idtype, id, &si, options);
  8043. Py_END_ALLOW_THREADS
  8044. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8045. if (res < 0)
  8046. return (!async_err) ? posix_error() : NULL;
  8047. if (si.si_pid == 0)
  8048. Py_RETURN_NONE;
  8049. PyObject *WaitidResultType = get_posix_state(module)->WaitidResultType;
  8050. result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
  8051. if (!result)
  8052. return NULL;
  8053. int pos = 0;
  8054. #define SET_RESULT(CALL) \
  8055. do { \
  8056. PyObject *item = (CALL); \
  8057. if (item == NULL) { \
  8058. Py_DECREF(result); \
  8059. return NULL; \
  8060. } \
  8061. PyStructSequence_SET_ITEM(result, pos++, item); \
  8062. } while(0)
  8063. SET_RESULT(PyLong_FromPid(si.si_pid));
  8064. SET_RESULT(_PyLong_FromUid(si.si_uid));
  8065. SET_RESULT(PyLong_FromLong((long)(si.si_signo)));
  8066. SET_RESULT(PyLong_FromLong((long)(si.si_status)));
  8067. SET_RESULT(PyLong_FromLong((long)(si.si_code)));
  8068. #undef SET_RESULT
  8069. return result;
  8070. }
  8071. #endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
  8072. #if defined(HAVE_WAITPID)
  8073. /*[clinic input]
  8074. os.waitpid
  8075. pid: pid_t
  8076. options: int
  8077. /
  8078. Wait for completion of a given child process.
  8079. Returns a tuple of information regarding the child process:
  8080. (pid, status)
  8081. The options argument is ignored on Windows.
  8082. [clinic start generated code]*/
  8083. static PyObject *
  8084. os_waitpid_impl(PyObject *module, pid_t pid, int options)
  8085. /*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
  8086. {
  8087. pid_t res;
  8088. int async_err = 0;
  8089. WAIT_TYPE status;
  8090. WAIT_STATUS_INT(status) = 0;
  8091. do {
  8092. Py_BEGIN_ALLOW_THREADS
  8093. res = waitpid(pid, &status, options);
  8094. Py_END_ALLOW_THREADS
  8095. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8096. if (res < 0)
  8097. return (!async_err) ? posix_error() : NULL;
  8098. return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
  8099. }
  8100. #elif defined(HAVE_CWAIT)
  8101. /* MS C has a variant of waitpid() that's usable for most purposes. */
  8102. /*[clinic input]
  8103. os.waitpid
  8104. pid: intptr_t
  8105. options: int
  8106. /
  8107. Wait for completion of a given process.
  8108. Returns a tuple of information regarding the process:
  8109. (pid, status << 8)
  8110. The options argument is ignored on Windows.
  8111. [clinic start generated code]*/
  8112. static PyObject *
  8113. os_waitpid_impl(PyObject *module, intptr_t pid, int options)
  8114. /*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
  8115. {
  8116. int status;
  8117. intptr_t res;
  8118. int async_err = 0;
  8119. do {
  8120. Py_BEGIN_ALLOW_THREADS
  8121. _Py_BEGIN_SUPPRESS_IPH
  8122. res = _cwait(&status, pid, options);
  8123. _Py_END_SUPPRESS_IPH
  8124. Py_END_ALLOW_THREADS
  8125. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8126. if (res < 0)
  8127. return (!async_err) ? posix_error() : NULL;
  8128. unsigned long long ustatus = (unsigned int)status;
  8129. /* shift the status left a byte so this is more like the POSIX waitpid */
  8130. return Py_BuildValue(_Py_PARSE_INTPTR "K", res, ustatus << 8);
  8131. }
  8132. #endif
  8133. #ifdef HAVE_WAIT
  8134. /*[clinic input]
  8135. os.wait
  8136. Wait for completion of a child process.
  8137. Returns a tuple of information about the child process:
  8138. (pid, status)
  8139. [clinic start generated code]*/
  8140. static PyObject *
  8141. os_wait_impl(PyObject *module)
  8142. /*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
  8143. {
  8144. pid_t pid;
  8145. int async_err = 0;
  8146. WAIT_TYPE status;
  8147. WAIT_STATUS_INT(status) = 0;
  8148. do {
  8149. Py_BEGIN_ALLOW_THREADS
  8150. pid = wait(&status);
  8151. Py_END_ALLOW_THREADS
  8152. } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8153. if (pid < 0)
  8154. return (!async_err) ? posix_error() : NULL;
  8155. return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
  8156. }
  8157. #endif /* HAVE_WAIT */
  8158. #if defined(__linux__) && defined(__NR_pidfd_open)
  8159. /*[clinic input]
  8160. os.pidfd_open
  8161. pid: pid_t
  8162. flags: unsigned_int = 0
  8163. Return a file descriptor referring to the process *pid*.
  8164. The descriptor can be used to perform process management without races and
  8165. signals.
  8166. [clinic start generated code]*/
  8167. static PyObject *
  8168. os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
  8169. /*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
  8170. {
  8171. int fd = syscall(__NR_pidfd_open, pid, flags);
  8172. if (fd < 0) {
  8173. return posix_error();
  8174. }
  8175. return PyLong_FromLong(fd);
  8176. }
  8177. #endif
  8178. #ifdef HAVE_SETNS
  8179. /*[clinic input]
  8180. os.setns
  8181. fd: fildes
  8182. A file descriptor to a namespace.
  8183. nstype: int = 0
  8184. Type of namespace.
  8185. Move the calling thread into different namespaces.
  8186. [clinic start generated code]*/
  8187. static PyObject *
  8188. os_setns_impl(PyObject *module, int fd, int nstype)
  8189. /*[clinic end generated code: output=5dbd055bfb66ecd0 input=42787871226bf3ee]*/
  8190. {
  8191. int res;
  8192. Py_BEGIN_ALLOW_THREADS
  8193. res = setns(fd, nstype);
  8194. Py_END_ALLOW_THREADS
  8195. if (res != 0) {
  8196. return posix_error();
  8197. }
  8198. Py_RETURN_NONE;
  8199. }
  8200. #endif
  8201. #ifdef HAVE_UNSHARE
  8202. /*[clinic input]
  8203. os.unshare
  8204. flags: int
  8205. Namespaces to be unshared.
  8206. Disassociate parts of a process (or thread) execution context.
  8207. [clinic start generated code]*/
  8208. static PyObject *
  8209. os_unshare_impl(PyObject *module, int flags)
  8210. /*[clinic end generated code: output=1b3177906dd237ee input=9e065db3232b8b1b]*/
  8211. {
  8212. int res;
  8213. Py_BEGIN_ALLOW_THREADS
  8214. res = unshare(flags);
  8215. Py_END_ALLOW_THREADS
  8216. if (res != 0) {
  8217. return posix_error();
  8218. }
  8219. Py_RETURN_NONE;
  8220. }
  8221. #endif
  8222. #if defined(HAVE_READLINK) || defined(MS_WINDOWS)
  8223. /*[clinic input]
  8224. os.readlink
  8225. path: path_t
  8226. *
  8227. dir_fd: dir_fd(requires='readlinkat') = None
  8228. Return a string representing the path to which the symbolic link points.
  8229. If dir_fd is not None, it should be a file descriptor open to a directory,
  8230. and path should be relative; path will then be relative to that directory.
  8231. dir_fd may not be implemented on your platform. If it is unavailable,
  8232. using it will raise a NotImplementedError.
  8233. [clinic start generated code]*/
  8234. static PyObject *
  8235. os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
  8236. /*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
  8237. {
  8238. #if defined(HAVE_READLINK)
  8239. char buffer[MAXPATHLEN+1];
  8240. ssize_t length;
  8241. #ifdef HAVE_READLINKAT
  8242. int readlinkat_unavailable = 0;
  8243. #endif
  8244. Py_BEGIN_ALLOW_THREADS
  8245. #ifdef HAVE_READLINKAT
  8246. if (dir_fd != DEFAULT_DIR_FD) {
  8247. if (HAVE_READLINKAT_RUNTIME) {
  8248. length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
  8249. } else {
  8250. readlinkat_unavailable = 1;
  8251. }
  8252. } else
  8253. #endif
  8254. length = readlink(path->narrow, buffer, MAXPATHLEN);
  8255. Py_END_ALLOW_THREADS
  8256. #ifdef HAVE_READLINKAT
  8257. if (readlinkat_unavailable) {
  8258. argument_unavailable_error(NULL, "dir_fd");
  8259. return NULL;
  8260. }
  8261. #endif
  8262. if (length < 0) {
  8263. return path_error(path);
  8264. }
  8265. buffer[length] = '\0';
  8266. if (PyUnicode_Check(path->object))
  8267. return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
  8268. else
  8269. return PyBytes_FromStringAndSize(buffer, length);
  8270. #elif defined(MS_WINDOWS)
  8271. DWORD n_bytes_returned;
  8272. DWORD io_result = 0;
  8273. HANDLE reparse_point_handle;
  8274. char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
  8275. _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
  8276. PyObject *result = NULL;
  8277. /* First get a handle to the reparse point */
  8278. Py_BEGIN_ALLOW_THREADS
  8279. reparse_point_handle = CreateFileW(
  8280. path->wide,
  8281. 0,
  8282. 0,
  8283. 0,
  8284. OPEN_EXISTING,
  8285. FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
  8286. 0);
  8287. if (reparse_point_handle != INVALID_HANDLE_VALUE) {
  8288. /* New call DeviceIoControl to read the reparse point */
  8289. io_result = DeviceIoControl(
  8290. reparse_point_handle,
  8291. FSCTL_GET_REPARSE_POINT,
  8292. 0, 0, /* in buffer */
  8293. target_buffer, sizeof(target_buffer),
  8294. &n_bytes_returned,
  8295. 0 /* we're not using OVERLAPPED_IO */
  8296. );
  8297. CloseHandle(reparse_point_handle);
  8298. }
  8299. Py_END_ALLOW_THREADS
  8300. if (io_result == 0) {
  8301. return path_error(path);
  8302. }
  8303. wchar_t *name = NULL;
  8304. Py_ssize_t nameLen = 0;
  8305. if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
  8306. {
  8307. name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
  8308. rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
  8309. nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
  8310. }
  8311. else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
  8312. {
  8313. name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
  8314. rdb->MountPointReparseBuffer.SubstituteNameOffset);
  8315. nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
  8316. }
  8317. else
  8318. {
  8319. PyErr_SetString(PyExc_ValueError, "not a symbolic link");
  8320. }
  8321. if (name) {
  8322. if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
  8323. /* Our buffer is mutable, so this is okay */
  8324. name[1] = L'\\';
  8325. }
  8326. result = PyUnicode_FromWideChar(name, nameLen);
  8327. if (result && PyBytes_Check(path->object)) {
  8328. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  8329. }
  8330. }
  8331. return result;
  8332. #endif
  8333. }
  8334. #endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
  8335. #if defined(MS_WINDOWS)
  8336. /* Remove the last portion of the path - return 0 on success */
  8337. static int
  8338. _dirnameW(WCHAR *path)
  8339. {
  8340. WCHAR *ptr;
  8341. size_t length = wcsnlen_s(path, MAX_PATH);
  8342. if (length == MAX_PATH) {
  8343. return -1;
  8344. }
  8345. /* walk the path from the end until a backslash is encountered */
  8346. for(ptr = path + length; ptr != path; ptr--) {
  8347. if (*ptr == L'\\' || *ptr == L'/') {
  8348. break;
  8349. }
  8350. }
  8351. *ptr = 0;
  8352. return 0;
  8353. }
  8354. #endif
  8355. #ifdef HAVE_SYMLINK
  8356. #if defined(MS_WINDOWS)
  8357. /* Is this path absolute? */
  8358. static int
  8359. _is_absW(const WCHAR *path)
  8360. {
  8361. return path[0] == L'\\' || path[0] == L'/' ||
  8362. (path[0] && path[1] == L':');
  8363. }
  8364. /* join root and rest with a backslash - return 0 on success */
  8365. static int
  8366. _joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
  8367. {
  8368. if (_is_absW(rest)) {
  8369. return wcscpy_s(dest_path, MAX_PATH, rest);
  8370. }
  8371. if (wcscpy_s(dest_path, MAX_PATH, root)) {
  8372. return -1;
  8373. }
  8374. if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
  8375. return -1;
  8376. }
  8377. return wcscat_s(dest_path, MAX_PATH, rest);
  8378. }
  8379. /* Return True if the path at src relative to dest is a directory */
  8380. static int
  8381. _check_dirW(LPCWSTR src, LPCWSTR dest)
  8382. {
  8383. WIN32_FILE_ATTRIBUTE_DATA src_info;
  8384. WCHAR dest_parent[MAX_PATH];
  8385. WCHAR src_resolved[MAX_PATH] = L"";
  8386. /* dest_parent = os.path.dirname(dest) */
  8387. if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
  8388. _dirnameW(dest_parent)) {
  8389. return 0;
  8390. }
  8391. /* src_resolved = os.path.join(dest_parent, src) */
  8392. if (_joinW(src_resolved, dest_parent, src)) {
  8393. return 0;
  8394. }
  8395. return (
  8396. GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
  8397. && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
  8398. );
  8399. }
  8400. #endif
  8401. /*[clinic input]
  8402. os.symlink
  8403. src: path_t
  8404. dst: path_t
  8405. target_is_directory: bool = False
  8406. *
  8407. dir_fd: dir_fd(requires='symlinkat')=None
  8408. # "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
  8409. Create a symbolic link pointing to src named dst.
  8410. target_is_directory is required on Windows if the target is to be
  8411. interpreted as a directory. (On Windows, symlink requires
  8412. Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
  8413. target_is_directory is ignored on non-Windows platforms.
  8414. If dir_fd is not None, it should be a file descriptor open to a directory,
  8415. and path should be relative; path will then be relative to that directory.
  8416. dir_fd may not be implemented on your platform.
  8417. If it is unavailable, using it will raise a NotImplementedError.
  8418. [clinic start generated code]*/
  8419. static PyObject *
  8420. os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
  8421. int target_is_directory, int dir_fd)
  8422. /*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
  8423. {
  8424. #ifdef MS_WINDOWS
  8425. DWORD result;
  8426. DWORD flags = 0;
  8427. /* Assumed true, set to false if detected to not be available. */
  8428. static int windows_has_symlink_unprivileged_flag = TRUE;
  8429. #else
  8430. int result;
  8431. #ifdef HAVE_SYMLINKAT
  8432. int symlinkat_unavailable = 0;
  8433. #endif
  8434. #endif
  8435. if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
  8436. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  8437. return NULL;
  8438. }
  8439. #ifdef MS_WINDOWS
  8440. if (windows_has_symlink_unprivileged_flag) {
  8441. /* Allow non-admin symlinks if system allows it. */
  8442. flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
  8443. }
  8444. Py_BEGIN_ALLOW_THREADS
  8445. _Py_BEGIN_SUPPRESS_IPH
  8446. /* if src is a directory, ensure flags==1 (target_is_directory bit) */
  8447. if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
  8448. flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
  8449. }
  8450. result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
  8451. _Py_END_SUPPRESS_IPH
  8452. Py_END_ALLOW_THREADS
  8453. if (windows_has_symlink_unprivileged_flag && !result &&
  8454. ERROR_INVALID_PARAMETER == GetLastError()) {
  8455. Py_BEGIN_ALLOW_THREADS
  8456. _Py_BEGIN_SUPPRESS_IPH
  8457. /* This error might be caused by
  8458. SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
  8459. Try again, and update windows_has_symlink_unprivileged_flag if we
  8460. are successful this time.
  8461. NOTE: There is a risk of a race condition here if there are other
  8462. conditions than the flag causing ERROR_INVALID_PARAMETER, and
  8463. another process (or thread) changes that condition in between our
  8464. calls to CreateSymbolicLink.
  8465. */
  8466. flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
  8467. result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
  8468. _Py_END_SUPPRESS_IPH
  8469. Py_END_ALLOW_THREADS
  8470. if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
  8471. windows_has_symlink_unprivileged_flag = FALSE;
  8472. }
  8473. }
  8474. if (!result)
  8475. return path_error2(src, dst);
  8476. #else
  8477. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  8478. PyErr_SetString(PyExc_ValueError,
  8479. "symlink: src and dst must be the same type");
  8480. return NULL;
  8481. }
  8482. Py_BEGIN_ALLOW_THREADS
  8483. #ifdef HAVE_SYMLINKAT
  8484. if (dir_fd != DEFAULT_DIR_FD) {
  8485. if (HAVE_SYMLINKAT_RUNTIME) {
  8486. result = symlinkat(src->narrow, dir_fd, dst->narrow);
  8487. } else {
  8488. symlinkat_unavailable = 1;
  8489. }
  8490. } else
  8491. #endif
  8492. result = symlink(src->narrow, dst->narrow);
  8493. Py_END_ALLOW_THREADS
  8494. #ifdef HAVE_SYMLINKAT
  8495. if (symlinkat_unavailable) {
  8496. argument_unavailable_error(NULL, "dir_fd");
  8497. return NULL;
  8498. }
  8499. #endif
  8500. if (result)
  8501. return path_error2(src, dst);
  8502. #endif
  8503. Py_RETURN_NONE;
  8504. }
  8505. #endif /* HAVE_SYMLINK */
  8506. static PyStructSequence_Field times_result_fields[] = {
  8507. {"user", "user time"},
  8508. {"system", "system time"},
  8509. {"children_user", "user time of children"},
  8510. {"children_system", "system time of children"},
  8511. {"elapsed", "elapsed time since an arbitrary point in the past"},
  8512. {NULL}
  8513. };
  8514. PyDoc_STRVAR(times_result__doc__,
  8515. "times_result: Result from os.times().\n\n\
  8516. This object may be accessed either as a tuple of\n\
  8517. (user, system, children_user, children_system, elapsed),\n\
  8518. or via the attributes user, system, children_user, children_system,\n\
  8519. and elapsed.\n\
  8520. \n\
  8521. See os.times for more information.");
  8522. static PyStructSequence_Desc times_result_desc = {
  8523. "times_result", /* name */
  8524. times_result__doc__, /* doc */
  8525. times_result_fields,
  8526. 5
  8527. };
  8528. #ifdef MS_WINDOWS
  8529. #define HAVE_TIMES /* mandatory, for the method table */
  8530. #endif
  8531. #ifdef HAVE_TIMES
  8532. static PyObject *
  8533. build_times_result(PyObject *module, double user, double system,
  8534. double children_user, double children_system,
  8535. double elapsed)
  8536. {
  8537. PyObject *TimesResultType = get_posix_state(module)->TimesResultType;
  8538. PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
  8539. if (value == NULL)
  8540. return NULL;
  8541. #define SET(i, field) \
  8542. { \
  8543. PyObject *o = PyFloat_FromDouble(field); \
  8544. if (!o) { \
  8545. Py_DECREF(value); \
  8546. return NULL; \
  8547. } \
  8548. PyStructSequence_SET_ITEM(value, i, o); \
  8549. } \
  8550. SET(0, user);
  8551. SET(1, system);
  8552. SET(2, children_user);
  8553. SET(3, children_system);
  8554. SET(4, elapsed);
  8555. #undef SET
  8556. return value;
  8557. }
  8558. /*[clinic input]
  8559. os.times
  8560. Return a collection containing process timing information.
  8561. The object returned behaves like a named tuple with these fields:
  8562. (utime, stime, cutime, cstime, elapsed_time)
  8563. All fields are floating-point numbers.
  8564. [clinic start generated code]*/
  8565. static PyObject *
  8566. os_times_impl(PyObject *module)
  8567. /*[clinic end generated code: output=35f640503557d32a input=8dbfe33a2dcc3df3]*/
  8568. #ifdef MS_WINDOWS
  8569. {
  8570. FILETIME create, exit, kernel, user;
  8571. HANDLE hProc;
  8572. hProc = GetCurrentProcess();
  8573. GetProcessTimes(hProc, &create, &exit, &kernel, &user);
  8574. /* The fields of a FILETIME structure are the hi and lo part
  8575. of a 64-bit value expressed in 100 nanosecond units.
  8576. 1e7 is one second in such units; 1e-7 the inverse.
  8577. 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
  8578. */
  8579. return build_times_result(module,
  8580. (double)(user.dwHighDateTime*429.4967296 +
  8581. user.dwLowDateTime*1e-7),
  8582. (double)(kernel.dwHighDateTime*429.4967296 +
  8583. kernel.dwLowDateTime*1e-7),
  8584. (double)0,
  8585. (double)0,
  8586. (double)0);
  8587. }
  8588. #else /* MS_WINDOWS */
  8589. {
  8590. struct tms t;
  8591. clock_t c;
  8592. errno = 0;
  8593. c = times(&t);
  8594. if (c == (clock_t) -1) {
  8595. return posix_error();
  8596. }
  8597. assert(_PyRuntime.time.ticks_per_second_initialized);
  8598. #define ticks_per_second _PyRuntime.time.ticks_per_second
  8599. return build_times_result(module,
  8600. (double)t.tms_utime / ticks_per_second,
  8601. (double)t.tms_stime / ticks_per_second,
  8602. (double)t.tms_cutime / ticks_per_second,
  8603. (double)t.tms_cstime / ticks_per_second,
  8604. (double)c / ticks_per_second);
  8605. #undef ticks_per_second
  8606. }
  8607. #endif /* MS_WINDOWS */
  8608. #endif /* HAVE_TIMES */
  8609. #ifdef HAVE_GETSID
  8610. /*[clinic input]
  8611. os.getsid
  8612. pid: pid_t
  8613. /
  8614. Call the system call getsid(pid) and return the result.
  8615. [clinic start generated code]*/
  8616. static PyObject *
  8617. os_getsid_impl(PyObject *module, pid_t pid)
  8618. /*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
  8619. {
  8620. int sid;
  8621. sid = getsid(pid);
  8622. if (sid < 0)
  8623. return posix_error();
  8624. return PyLong_FromLong((long)sid);
  8625. }
  8626. #endif /* HAVE_GETSID */
  8627. #ifdef HAVE_SETSID
  8628. /*[clinic input]
  8629. os.setsid
  8630. Call the system call setsid().
  8631. [clinic start generated code]*/
  8632. static PyObject *
  8633. os_setsid_impl(PyObject *module)
  8634. /*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
  8635. {
  8636. if (setsid() < 0)
  8637. return posix_error();
  8638. Py_RETURN_NONE;
  8639. }
  8640. #endif /* HAVE_SETSID */
  8641. #ifdef HAVE_SETPGID
  8642. /*[clinic input]
  8643. os.setpgid
  8644. pid: pid_t
  8645. pgrp: pid_t
  8646. /
  8647. Call the system call setpgid(pid, pgrp).
  8648. [clinic start generated code]*/
  8649. static PyObject *
  8650. os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
  8651. /*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
  8652. {
  8653. if (setpgid(pid, pgrp) < 0)
  8654. return posix_error();
  8655. Py_RETURN_NONE;
  8656. }
  8657. #endif /* HAVE_SETPGID */
  8658. #ifdef HAVE_TCGETPGRP
  8659. /*[clinic input]
  8660. os.tcgetpgrp
  8661. fd: int
  8662. /
  8663. Return the process group associated with the terminal specified by fd.
  8664. [clinic start generated code]*/
  8665. static PyObject *
  8666. os_tcgetpgrp_impl(PyObject *module, int fd)
  8667. /*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
  8668. {
  8669. pid_t pgid = tcgetpgrp(fd);
  8670. if (pgid < 0)
  8671. return posix_error();
  8672. return PyLong_FromPid(pgid);
  8673. }
  8674. #endif /* HAVE_TCGETPGRP */
  8675. #ifdef HAVE_TCSETPGRP
  8676. /*[clinic input]
  8677. os.tcsetpgrp
  8678. fd: int
  8679. pgid: pid_t
  8680. /
  8681. Set the process group associated with the terminal specified by fd.
  8682. [clinic start generated code]*/
  8683. static PyObject *
  8684. os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
  8685. /*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
  8686. {
  8687. if (tcsetpgrp(fd, pgid) < 0)
  8688. return posix_error();
  8689. Py_RETURN_NONE;
  8690. }
  8691. #endif /* HAVE_TCSETPGRP */
  8692. /* Functions acting on file descriptors */
  8693. #ifdef O_CLOEXEC
  8694. extern int _Py_open_cloexec_works;
  8695. #endif
  8696. /*[clinic input]
  8697. os.open -> int
  8698. path: path_t
  8699. flags: int
  8700. mode: int = 0o777
  8701. *
  8702. dir_fd: dir_fd(requires='openat') = None
  8703. # "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
  8704. Open a file for low level IO. Returns a file descriptor (integer).
  8705. If dir_fd is not None, it should be a file descriptor open to a directory,
  8706. and path should be relative; path will then be relative to that directory.
  8707. dir_fd may not be implemented on your platform.
  8708. If it is unavailable, using it will raise a NotImplementedError.
  8709. [clinic start generated code]*/
  8710. static int
  8711. os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
  8712. /*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
  8713. {
  8714. int fd;
  8715. int async_err = 0;
  8716. #ifdef HAVE_OPENAT
  8717. int openat_unavailable = 0;
  8718. #endif
  8719. #ifdef O_CLOEXEC
  8720. int *atomic_flag_works = &_Py_open_cloexec_works;
  8721. #elif !defined(MS_WINDOWS)
  8722. int *atomic_flag_works = NULL;
  8723. #endif
  8724. #ifdef MS_WINDOWS
  8725. flags |= O_NOINHERIT;
  8726. #elif defined(O_CLOEXEC)
  8727. flags |= O_CLOEXEC;
  8728. #endif
  8729. if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
  8730. return -1;
  8731. }
  8732. _Py_BEGIN_SUPPRESS_IPH
  8733. do {
  8734. Py_BEGIN_ALLOW_THREADS
  8735. #ifdef MS_WINDOWS
  8736. fd = _wopen(path->wide, flags, mode);
  8737. #else
  8738. #ifdef HAVE_OPENAT
  8739. if (dir_fd != DEFAULT_DIR_FD) {
  8740. if (HAVE_OPENAT_RUNTIME) {
  8741. fd = openat(dir_fd, path->narrow, flags, mode);
  8742. } else {
  8743. openat_unavailable = 1;
  8744. fd = -1;
  8745. }
  8746. } else
  8747. #endif /* HAVE_OPENAT */
  8748. fd = open(path->narrow, flags, mode);
  8749. #endif /* !MS_WINDOWS */
  8750. Py_END_ALLOW_THREADS
  8751. } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8752. _Py_END_SUPPRESS_IPH
  8753. #ifdef HAVE_OPENAT
  8754. if (openat_unavailable) {
  8755. argument_unavailable_error(NULL, "dir_fd");
  8756. return -1;
  8757. }
  8758. #endif
  8759. if (fd < 0) {
  8760. if (!async_err)
  8761. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
  8762. return -1;
  8763. }
  8764. #ifndef MS_WINDOWS
  8765. if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
  8766. close(fd);
  8767. return -1;
  8768. }
  8769. #endif
  8770. return fd;
  8771. }
  8772. /*[clinic input]
  8773. os.close
  8774. fd: int
  8775. Close a file descriptor.
  8776. [clinic start generated code]*/
  8777. static PyObject *
  8778. os_close_impl(PyObject *module, int fd)
  8779. /*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
  8780. {
  8781. int res;
  8782. /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
  8783. * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
  8784. * for more details.
  8785. */
  8786. Py_BEGIN_ALLOW_THREADS
  8787. _Py_BEGIN_SUPPRESS_IPH
  8788. res = close(fd);
  8789. _Py_END_SUPPRESS_IPH
  8790. Py_END_ALLOW_THREADS
  8791. if (res < 0)
  8792. return posix_error();
  8793. Py_RETURN_NONE;
  8794. }
  8795. /*[clinic input]
  8796. os.closerange
  8797. fd_low: int
  8798. fd_high: int
  8799. /
  8800. Closes all file descriptors in [fd_low, fd_high), ignoring errors.
  8801. [clinic start generated code]*/
  8802. static PyObject *
  8803. os_closerange_impl(PyObject *module, int fd_low, int fd_high)
  8804. /*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
  8805. {
  8806. Py_BEGIN_ALLOW_THREADS
  8807. _Py_closerange(fd_low, fd_high - 1);
  8808. Py_END_ALLOW_THREADS
  8809. Py_RETURN_NONE;
  8810. }
  8811. /*[clinic input]
  8812. os.dup -> int
  8813. fd: int
  8814. /
  8815. Return a duplicate of a file descriptor.
  8816. [clinic start generated code]*/
  8817. static int
  8818. os_dup_impl(PyObject *module, int fd)
  8819. /*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
  8820. {
  8821. return _Py_dup(fd);
  8822. }
  8823. // dup2() is either provided by libc or dup2.c with AC_REPLACE_FUNCS().
  8824. // dup2.c provides working dup2() if and only if F_DUPFD is available.
  8825. #if (defined(HAVE_DUP3) || defined(F_DUPFD) || defined(MS_WINDOWS))
  8826. /*[clinic input]
  8827. os.dup2 -> int
  8828. fd: int
  8829. fd2: int
  8830. inheritable: bool=True
  8831. Duplicate file descriptor.
  8832. [clinic start generated code]*/
  8833. static int
  8834. os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
  8835. /*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
  8836. {
  8837. int res = 0;
  8838. #if defined(HAVE_DUP3) && \
  8839. !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
  8840. /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
  8841. static int dup3_works = -1;
  8842. #endif
  8843. /* dup2() can fail with EINTR if the target FD is already open, because it
  8844. * then has to be closed. See os_close_impl() for why we don't handle EINTR
  8845. * upon close(), and therefore below.
  8846. */
  8847. #ifdef MS_WINDOWS
  8848. Py_BEGIN_ALLOW_THREADS
  8849. _Py_BEGIN_SUPPRESS_IPH
  8850. res = dup2(fd, fd2);
  8851. _Py_END_SUPPRESS_IPH
  8852. Py_END_ALLOW_THREADS
  8853. if (res < 0) {
  8854. posix_error();
  8855. return -1;
  8856. }
  8857. res = fd2; // msvcrt dup2 returns 0 on success.
  8858. /* Character files like console cannot be make non-inheritable */
  8859. if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
  8860. close(fd2);
  8861. return -1;
  8862. }
  8863. #elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
  8864. Py_BEGIN_ALLOW_THREADS
  8865. if (!inheritable)
  8866. res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
  8867. else
  8868. res = dup2(fd, fd2);
  8869. Py_END_ALLOW_THREADS
  8870. if (res < 0) {
  8871. posix_error();
  8872. return -1;
  8873. }
  8874. #else
  8875. #ifdef HAVE_DUP3
  8876. if (!inheritable && dup3_works != 0) {
  8877. Py_BEGIN_ALLOW_THREADS
  8878. res = dup3(fd, fd2, O_CLOEXEC);
  8879. Py_END_ALLOW_THREADS
  8880. if (res < 0) {
  8881. if (dup3_works == -1)
  8882. dup3_works = (errno != ENOSYS);
  8883. if (dup3_works) {
  8884. posix_error();
  8885. return -1;
  8886. }
  8887. }
  8888. }
  8889. if (inheritable || dup3_works == 0)
  8890. {
  8891. #endif
  8892. Py_BEGIN_ALLOW_THREADS
  8893. res = dup2(fd, fd2);
  8894. Py_END_ALLOW_THREADS
  8895. if (res < 0) {
  8896. posix_error();
  8897. return -1;
  8898. }
  8899. if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
  8900. close(fd2);
  8901. return -1;
  8902. }
  8903. #ifdef HAVE_DUP3
  8904. }
  8905. #endif
  8906. #endif
  8907. return res;
  8908. }
  8909. #endif
  8910. #ifdef HAVE_LOCKF
  8911. /*[clinic input]
  8912. os.lockf
  8913. fd: int
  8914. An open file descriptor.
  8915. command: int
  8916. One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
  8917. length: Py_off_t
  8918. The number of bytes to lock, starting at the current position.
  8919. /
  8920. Apply, test or remove a POSIX lock on an open file descriptor.
  8921. [clinic start generated code]*/
  8922. static PyObject *
  8923. os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
  8924. /*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
  8925. {
  8926. int res;
  8927. if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
  8928. return NULL;
  8929. }
  8930. Py_BEGIN_ALLOW_THREADS
  8931. res = lockf(fd, command, length);
  8932. Py_END_ALLOW_THREADS
  8933. if (res < 0)
  8934. return posix_error();
  8935. Py_RETURN_NONE;
  8936. }
  8937. #endif /* HAVE_LOCKF */
  8938. /*[clinic input]
  8939. os.lseek -> Py_off_t
  8940. fd: int
  8941. An open file descriptor, as returned by os.open().
  8942. position: Py_off_t
  8943. Position, interpreted relative to 'whence'.
  8944. whence as how: int
  8945. The relative position to seek from. Valid values are:
  8946. - SEEK_SET: seek from the start of the file.
  8947. - SEEK_CUR: seek from the current file position.
  8948. - SEEK_END: seek from the end of the file.
  8949. /
  8950. Set the position of a file descriptor. Return the new position.
  8951. The return value is the number of bytes relative to the beginning of the file.
  8952. [clinic start generated code]*/
  8953. static Py_off_t
  8954. os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
  8955. /*[clinic end generated code: output=971e1efb6b30bd2f input=f096e754c5367504]*/
  8956. {
  8957. Py_off_t result;
  8958. #ifdef SEEK_SET
  8959. /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
  8960. switch (how) {
  8961. case 0: how = SEEK_SET; break;
  8962. case 1: how = SEEK_CUR; break;
  8963. case 2: how = SEEK_END; break;
  8964. }
  8965. #endif /* SEEK_END */
  8966. Py_BEGIN_ALLOW_THREADS
  8967. _Py_BEGIN_SUPPRESS_IPH
  8968. #ifdef MS_WINDOWS
  8969. result = _lseeki64(fd, position, how);
  8970. #else
  8971. result = lseek(fd, position, how);
  8972. #endif
  8973. _Py_END_SUPPRESS_IPH
  8974. Py_END_ALLOW_THREADS
  8975. if (result < 0)
  8976. posix_error();
  8977. return result;
  8978. }
  8979. /*[clinic input]
  8980. os.read
  8981. fd: int
  8982. length: Py_ssize_t
  8983. /
  8984. Read from a file descriptor. Returns a bytes object.
  8985. [clinic start generated code]*/
  8986. static PyObject *
  8987. os_read_impl(PyObject *module, int fd, Py_ssize_t length)
  8988. /*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
  8989. {
  8990. Py_ssize_t n;
  8991. PyObject *buffer;
  8992. if (length < 0) {
  8993. errno = EINVAL;
  8994. return posix_error();
  8995. }
  8996. length = Py_MIN(length, _PY_READ_MAX);
  8997. buffer = PyBytes_FromStringAndSize((char *)NULL, length);
  8998. if (buffer == NULL)
  8999. return NULL;
  9000. n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
  9001. if (n == -1) {
  9002. Py_DECREF(buffer);
  9003. return NULL;
  9004. }
  9005. if (n != length)
  9006. _PyBytes_Resize(&buffer, n);
  9007. return buffer;
  9008. }
  9009. #if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
  9010. || defined(__APPLE__))) \
  9011. || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
  9012. || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
  9013. static int
  9014. iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
  9015. {
  9016. Py_ssize_t i, j;
  9017. *iov = PyMem_New(struct iovec, cnt);
  9018. if (*iov == NULL) {
  9019. PyErr_NoMemory();
  9020. return -1;
  9021. }
  9022. *buf = PyMem_New(Py_buffer, cnt);
  9023. if (*buf == NULL) {
  9024. PyMem_Free(*iov);
  9025. PyErr_NoMemory();
  9026. return -1;
  9027. }
  9028. for (i = 0; i < cnt; i++) {
  9029. PyObject *item = PySequence_GetItem(seq, i);
  9030. if (item == NULL)
  9031. goto fail;
  9032. if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
  9033. Py_DECREF(item);
  9034. goto fail;
  9035. }
  9036. Py_DECREF(item);
  9037. (*iov)[i].iov_base = (*buf)[i].buf;
  9038. (*iov)[i].iov_len = (*buf)[i].len;
  9039. }
  9040. return 0;
  9041. fail:
  9042. PyMem_Free(*iov);
  9043. for (j = 0; j < i; j++) {
  9044. PyBuffer_Release(&(*buf)[j]);
  9045. }
  9046. PyMem_Free(*buf);
  9047. return -1;
  9048. }
  9049. static void
  9050. iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
  9051. {
  9052. int i;
  9053. PyMem_Free(iov);
  9054. for (i = 0; i < cnt; i++) {
  9055. PyBuffer_Release(&buf[i]);
  9056. }
  9057. PyMem_Free(buf);
  9058. }
  9059. #endif
  9060. #ifdef HAVE_READV
  9061. /*[clinic input]
  9062. os.readv -> Py_ssize_t
  9063. fd: int
  9064. buffers: object
  9065. /
  9066. Read from a file descriptor fd into an iterable of buffers.
  9067. The buffers should be mutable buffers accepting bytes.
  9068. readv will transfer data into each buffer until it is full
  9069. and then move on to the next buffer in the sequence to hold
  9070. the rest of the data.
  9071. readv returns the total number of bytes read,
  9072. which may be less than the total capacity of all the buffers.
  9073. [clinic start generated code]*/
  9074. static Py_ssize_t
  9075. os_readv_impl(PyObject *module, int fd, PyObject *buffers)
  9076. /*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
  9077. {
  9078. Py_ssize_t cnt, n;
  9079. int async_err = 0;
  9080. struct iovec *iov;
  9081. Py_buffer *buf;
  9082. if (!PySequence_Check(buffers)) {
  9083. PyErr_SetString(PyExc_TypeError,
  9084. "readv() arg 2 must be a sequence");
  9085. return -1;
  9086. }
  9087. cnt = PySequence_Size(buffers);
  9088. if (cnt < 0)
  9089. return -1;
  9090. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
  9091. return -1;
  9092. do {
  9093. Py_BEGIN_ALLOW_THREADS
  9094. n = readv(fd, iov, cnt);
  9095. Py_END_ALLOW_THREADS
  9096. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9097. int saved_errno = errno;
  9098. iov_cleanup(iov, buf, cnt);
  9099. if (n < 0) {
  9100. if (!async_err) {
  9101. errno = saved_errno;
  9102. posix_error();
  9103. }
  9104. return -1;
  9105. }
  9106. return n;
  9107. }
  9108. #endif /* HAVE_READV */
  9109. #ifdef HAVE_PREAD
  9110. /*[clinic input]
  9111. os.pread
  9112. fd: int
  9113. length: Py_ssize_t
  9114. offset: Py_off_t
  9115. /
  9116. Read a number of bytes from a file descriptor starting at a particular offset.
  9117. Read length bytes from file descriptor fd, starting at offset bytes from
  9118. the beginning of the file. The file offset remains unchanged.
  9119. [clinic start generated code]*/
  9120. static PyObject *
  9121. os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
  9122. /*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
  9123. {
  9124. Py_ssize_t n;
  9125. int async_err = 0;
  9126. PyObject *buffer;
  9127. if (length < 0) {
  9128. errno = EINVAL;
  9129. return posix_error();
  9130. }
  9131. buffer = PyBytes_FromStringAndSize((char *)NULL, length);
  9132. if (buffer == NULL)
  9133. return NULL;
  9134. do {
  9135. Py_BEGIN_ALLOW_THREADS
  9136. _Py_BEGIN_SUPPRESS_IPH
  9137. n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
  9138. _Py_END_SUPPRESS_IPH
  9139. Py_END_ALLOW_THREADS
  9140. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9141. if (n < 0) {
  9142. if (!async_err) {
  9143. posix_error();
  9144. }
  9145. Py_DECREF(buffer);
  9146. return NULL;
  9147. }
  9148. if (n != length)
  9149. _PyBytes_Resize(&buffer, n);
  9150. return buffer;
  9151. }
  9152. #endif /* HAVE_PREAD */
  9153. #if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
  9154. /*[clinic input]
  9155. os.preadv -> Py_ssize_t
  9156. fd: int
  9157. buffers: object
  9158. offset: Py_off_t
  9159. flags: int = 0
  9160. /
  9161. Reads from a file descriptor into a number of mutable bytes-like objects.
  9162. Combines the functionality of readv() and pread(). As readv(), it will
  9163. transfer data into each buffer until it is full and then move on to the next
  9164. buffer in the sequence to hold the rest of the data. Its fourth argument,
  9165. specifies the file offset at which the input operation is to be performed. It
  9166. will return the total number of bytes read (which can be less than the total
  9167. capacity of all the objects).
  9168. The flags argument contains a bitwise OR of zero or more of the following flags:
  9169. - RWF_HIPRI
  9170. - RWF_NOWAIT
  9171. Using non-zero flags requires Linux 4.6 or newer.
  9172. [clinic start generated code]*/
  9173. static Py_ssize_t
  9174. os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
  9175. int flags)
  9176. /*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
  9177. {
  9178. Py_ssize_t cnt, n;
  9179. int async_err = 0;
  9180. struct iovec *iov;
  9181. Py_buffer *buf;
  9182. if (!PySequence_Check(buffers)) {
  9183. PyErr_SetString(PyExc_TypeError,
  9184. "preadv2() arg 2 must be a sequence");
  9185. return -1;
  9186. }
  9187. cnt = PySequence_Size(buffers);
  9188. if (cnt < 0) {
  9189. return -1;
  9190. }
  9191. #ifndef HAVE_PREADV2
  9192. if(flags != 0) {
  9193. argument_unavailable_error("preadv2", "flags");
  9194. return -1;
  9195. }
  9196. #endif
  9197. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
  9198. return -1;
  9199. }
  9200. #ifdef HAVE_PREADV2
  9201. do {
  9202. Py_BEGIN_ALLOW_THREADS
  9203. _Py_BEGIN_SUPPRESS_IPH
  9204. n = preadv2(fd, iov, cnt, offset, flags);
  9205. _Py_END_SUPPRESS_IPH
  9206. Py_END_ALLOW_THREADS
  9207. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9208. #else
  9209. do {
  9210. #if defined(__APPLE__) && defined(__clang__)
  9211. /* This entire function will be removed from the module dict when the API
  9212. * is not available.
  9213. */
  9214. #pragma clang diagnostic push
  9215. #pragma clang diagnostic ignored "-Wunguarded-availability"
  9216. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  9217. #endif
  9218. Py_BEGIN_ALLOW_THREADS
  9219. _Py_BEGIN_SUPPRESS_IPH
  9220. n = preadv(fd, iov, cnt, offset);
  9221. _Py_END_SUPPRESS_IPH
  9222. Py_END_ALLOW_THREADS
  9223. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9224. #if defined(__APPLE__) && defined(__clang__)
  9225. #pragma clang diagnostic pop
  9226. #endif
  9227. #endif
  9228. int saved_errno = errno;
  9229. iov_cleanup(iov, buf, cnt);
  9230. if (n < 0) {
  9231. if (!async_err) {
  9232. errno = saved_errno;
  9233. posix_error();
  9234. }
  9235. return -1;
  9236. }
  9237. return n;
  9238. }
  9239. #endif /* HAVE_PREADV */
  9240. /*[clinic input]
  9241. os.write -> Py_ssize_t
  9242. fd: int
  9243. data: Py_buffer
  9244. /
  9245. Write a bytes object to a file descriptor.
  9246. [clinic start generated code]*/
  9247. static Py_ssize_t
  9248. os_write_impl(PyObject *module, int fd, Py_buffer *data)
  9249. /*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
  9250. {
  9251. return _Py_write(fd, data->buf, data->len);
  9252. }
  9253. #ifdef HAVE_SENDFILE
  9254. #ifdef __APPLE__
  9255. /*[clinic input]
  9256. os.sendfile
  9257. out_fd: int
  9258. in_fd: int
  9259. offset: Py_off_t
  9260. count as sbytes: Py_off_t
  9261. headers: object(c_default="NULL") = ()
  9262. trailers: object(c_default="NULL") = ()
  9263. flags: int = 0
  9264. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9265. [clinic start generated code]*/
  9266. static PyObject *
  9267. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
  9268. Py_off_t sbytes, PyObject *headers, PyObject *trailers,
  9269. int flags)
  9270. /*[clinic end generated code: output=81c4bcd143f5c82b input=b0d72579d4c69afa]*/
  9271. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  9272. /*[clinic input]
  9273. os.sendfile
  9274. out_fd: int
  9275. in_fd: int
  9276. offset: Py_off_t
  9277. count: Py_ssize_t
  9278. headers: object(c_default="NULL") = ()
  9279. trailers: object(c_default="NULL") = ()
  9280. flags: int = 0
  9281. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9282. [clinic start generated code]*/
  9283. static PyObject *
  9284. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
  9285. Py_ssize_t count, PyObject *headers, PyObject *trailers,
  9286. int flags)
  9287. /*[clinic end generated code: output=329ea009bdd55afc input=338adb8ff84ae8cd]*/
  9288. #else
  9289. /*[clinic input]
  9290. os.sendfile
  9291. out_fd: int
  9292. in_fd: int
  9293. offset as offobj: object
  9294. count: Py_ssize_t
  9295. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9296. [clinic start generated code]*/
  9297. static PyObject *
  9298. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, PyObject *offobj,
  9299. Py_ssize_t count)
  9300. /*[clinic end generated code: output=ae81216e40f167d8 input=76d64058c74477ba]*/
  9301. #endif
  9302. {
  9303. Py_ssize_t ret;
  9304. int async_err = 0;
  9305. #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
  9306. #ifndef __APPLE__
  9307. off_t sbytes;
  9308. #endif
  9309. Py_buffer *hbuf, *tbuf;
  9310. struct sf_hdtr sf;
  9311. sf.headers = NULL;
  9312. sf.trailers = NULL;
  9313. if (headers != NULL) {
  9314. if (!PySequence_Check(headers)) {
  9315. PyErr_SetString(PyExc_TypeError,
  9316. "sendfile() headers must be a sequence");
  9317. return NULL;
  9318. } else {
  9319. Py_ssize_t i = PySequence_Size(headers);
  9320. if (i < 0)
  9321. return NULL;
  9322. if (i > INT_MAX) {
  9323. PyErr_SetString(PyExc_OverflowError,
  9324. "sendfile() header is too large");
  9325. return NULL;
  9326. }
  9327. if (i > 0) {
  9328. sf.hdr_cnt = (int)i;
  9329. if (iov_setup(&(sf.headers), &hbuf,
  9330. headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
  9331. return NULL;
  9332. #ifdef __APPLE__
  9333. for (i = 0; i < sf.hdr_cnt; i++) {
  9334. Py_ssize_t blen = sf.headers[i].iov_len;
  9335. # define OFF_T_MAX 0x7fffffffffffffff
  9336. if (sbytes >= OFF_T_MAX - blen) {
  9337. PyErr_SetString(PyExc_OverflowError,
  9338. "sendfile() header is too large");
  9339. return NULL;
  9340. }
  9341. sbytes += blen;
  9342. }
  9343. #endif
  9344. }
  9345. }
  9346. }
  9347. if (trailers != NULL) {
  9348. if (!PySequence_Check(trailers)) {
  9349. PyErr_SetString(PyExc_TypeError,
  9350. "sendfile() trailers must be a sequence");
  9351. return NULL;
  9352. } else {
  9353. Py_ssize_t i = PySequence_Size(trailers);
  9354. if (i < 0)
  9355. return NULL;
  9356. if (i > INT_MAX) {
  9357. PyErr_SetString(PyExc_OverflowError,
  9358. "sendfile() trailer is too large");
  9359. return NULL;
  9360. }
  9361. if (i > 0) {
  9362. sf.trl_cnt = (int)i;
  9363. if (iov_setup(&(sf.trailers), &tbuf,
  9364. trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
  9365. return NULL;
  9366. }
  9367. }
  9368. }
  9369. _Py_BEGIN_SUPPRESS_IPH
  9370. do {
  9371. Py_BEGIN_ALLOW_THREADS
  9372. #ifdef __APPLE__
  9373. ret = sendfile(in_fd, out_fd, offset, &sbytes, &sf, flags);
  9374. #else
  9375. ret = sendfile(in_fd, out_fd, offset, count, &sf, &sbytes, flags);
  9376. #endif
  9377. Py_END_ALLOW_THREADS
  9378. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9379. _Py_END_SUPPRESS_IPH
  9380. int saved_errno = errno;
  9381. if (sf.headers != NULL)
  9382. iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
  9383. if (sf.trailers != NULL)
  9384. iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
  9385. if (ret < 0) {
  9386. if ((saved_errno == EAGAIN) || (saved_errno == EBUSY)) {
  9387. if (sbytes != 0) {
  9388. // some data has been sent
  9389. goto done;
  9390. }
  9391. // no data has been sent; upper application is supposed
  9392. // to retry on EAGAIN or EBUSY
  9393. }
  9394. if (!async_err) {
  9395. errno = saved_errno;
  9396. posix_error();
  9397. }
  9398. return NULL;
  9399. }
  9400. goto done;
  9401. done:
  9402. #if !defined(HAVE_LARGEFILE_SUPPORT)
  9403. return Py_BuildValue("l", sbytes);
  9404. #else
  9405. return Py_BuildValue("L", sbytes);
  9406. #endif
  9407. #else
  9408. #ifdef __linux__
  9409. if (offobj == Py_None) {
  9410. do {
  9411. Py_BEGIN_ALLOW_THREADS
  9412. ret = sendfile(out_fd, in_fd, NULL, count);
  9413. Py_END_ALLOW_THREADS
  9414. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9415. if (ret < 0)
  9416. return (!async_err) ? posix_error() : NULL;
  9417. return Py_BuildValue("n", ret);
  9418. }
  9419. #endif
  9420. off_t offset;
  9421. if (!Py_off_t_converter(offobj, &offset))
  9422. return NULL;
  9423. #if defined(__sun) && defined(__SVR4)
  9424. // On Solaris, sendfile raises EINVAL rather than returning 0
  9425. // when the offset is equal or bigger than the in_fd size.
  9426. struct stat st;
  9427. do {
  9428. Py_BEGIN_ALLOW_THREADS
  9429. ret = fstat(in_fd, &st);
  9430. Py_END_ALLOW_THREADS
  9431. } while (ret != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9432. if (ret < 0)
  9433. return (!async_err) ? posix_error() : NULL;
  9434. if (offset >= st.st_size) {
  9435. return Py_BuildValue("i", 0);
  9436. }
  9437. // On illumos specifically sendfile() may perform a partial write but
  9438. // return -1/an error (in one confirmed case the destination socket
  9439. // had a 5 second timeout set and errno was EAGAIN) and it's on the client
  9440. // code to check if the offset parameter was modified by sendfile().
  9441. //
  9442. // We need this variable to track said change.
  9443. off_t original_offset = offset;
  9444. #endif
  9445. do {
  9446. Py_BEGIN_ALLOW_THREADS
  9447. ret = sendfile(out_fd, in_fd, &offset, count);
  9448. #if defined(__sun) && defined(__SVR4)
  9449. // This handles illumos-specific sendfile() partial write behavior,
  9450. // see a comment above for more details.
  9451. if (ret < 0 && offset != original_offset) {
  9452. ret = offset - original_offset;
  9453. }
  9454. #endif
  9455. Py_END_ALLOW_THREADS
  9456. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9457. if (ret < 0)
  9458. return (!async_err) ? posix_error() : NULL;
  9459. return Py_BuildValue("n", ret);
  9460. #endif
  9461. }
  9462. #endif /* HAVE_SENDFILE */
  9463. #if defined(__APPLE__)
  9464. /*[clinic input]
  9465. os._fcopyfile
  9466. in_fd: int
  9467. out_fd: int
  9468. flags: int
  9469. /
  9470. Efficiently copy content or metadata of 2 regular file descriptors (macOS).
  9471. [clinic start generated code]*/
  9472. static PyObject *
  9473. os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
  9474. /*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
  9475. {
  9476. int ret;
  9477. Py_BEGIN_ALLOW_THREADS
  9478. ret = fcopyfile(in_fd, out_fd, NULL, flags);
  9479. Py_END_ALLOW_THREADS
  9480. if (ret < 0)
  9481. return posix_error();
  9482. Py_RETURN_NONE;
  9483. }
  9484. #endif
  9485. /*[clinic input]
  9486. os.fstat
  9487. fd : int
  9488. Perform a stat system call on the given file descriptor.
  9489. Like stat(), but for an open file descriptor.
  9490. Equivalent to os.stat(fd).
  9491. [clinic start generated code]*/
  9492. static PyObject *
  9493. os_fstat_impl(PyObject *module, int fd)
  9494. /*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
  9495. {
  9496. STRUCT_STAT st;
  9497. int res;
  9498. int async_err = 0;
  9499. do {
  9500. Py_BEGIN_ALLOW_THREADS
  9501. res = FSTAT(fd, &st);
  9502. Py_END_ALLOW_THREADS
  9503. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9504. if (res != 0) {
  9505. #ifdef MS_WINDOWS
  9506. return PyErr_SetFromWindowsErr(0);
  9507. #else
  9508. return (!async_err) ? posix_error() : NULL;
  9509. #endif
  9510. }
  9511. return _pystat_fromstructstat(module, &st);
  9512. }
  9513. /*[clinic input]
  9514. os.isatty -> bool
  9515. fd: int
  9516. /
  9517. Return True if the fd is connected to a terminal.
  9518. Return True if the file descriptor is an open file descriptor
  9519. connected to the slave end of a terminal.
  9520. [clinic start generated code]*/
  9521. static int
  9522. os_isatty_impl(PyObject *module, int fd)
  9523. /*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
  9524. {
  9525. int return_value;
  9526. Py_BEGIN_ALLOW_THREADS
  9527. _Py_BEGIN_SUPPRESS_IPH
  9528. return_value = isatty(fd);
  9529. _Py_END_SUPPRESS_IPH
  9530. Py_END_ALLOW_THREADS
  9531. return return_value;
  9532. }
  9533. #ifdef HAVE_PIPE
  9534. /*[clinic input]
  9535. os.pipe
  9536. Create a pipe.
  9537. Returns a tuple of two file descriptors:
  9538. (read_fd, write_fd)
  9539. [clinic start generated code]*/
  9540. static PyObject *
  9541. os_pipe_impl(PyObject *module)
  9542. /*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
  9543. {
  9544. int fds[2];
  9545. #ifdef MS_WINDOWS
  9546. HANDLE read, write;
  9547. SECURITY_ATTRIBUTES attr;
  9548. BOOL ok;
  9549. #else
  9550. int res;
  9551. #endif
  9552. #ifdef MS_WINDOWS
  9553. attr.nLength = sizeof(attr);
  9554. attr.lpSecurityDescriptor = NULL;
  9555. attr.bInheritHandle = FALSE;
  9556. Py_BEGIN_ALLOW_THREADS
  9557. ok = CreatePipe(&read, &write, &attr, 0);
  9558. if (ok) {
  9559. fds[0] = _Py_open_osfhandle_noraise(read, _O_RDONLY);
  9560. fds[1] = _Py_open_osfhandle_noraise(write, _O_WRONLY);
  9561. if (fds[0] == -1 || fds[1] == -1) {
  9562. CloseHandle(read);
  9563. CloseHandle(write);
  9564. ok = 0;
  9565. }
  9566. }
  9567. Py_END_ALLOW_THREADS
  9568. if (!ok)
  9569. return PyErr_SetFromWindowsErr(0);
  9570. #else
  9571. #ifdef HAVE_PIPE2
  9572. Py_BEGIN_ALLOW_THREADS
  9573. res = pipe2(fds, O_CLOEXEC);
  9574. Py_END_ALLOW_THREADS
  9575. if (res != 0 && errno == ENOSYS)
  9576. {
  9577. #endif
  9578. Py_BEGIN_ALLOW_THREADS
  9579. res = pipe(fds);
  9580. Py_END_ALLOW_THREADS
  9581. if (res == 0) {
  9582. if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
  9583. close(fds[0]);
  9584. close(fds[1]);
  9585. return NULL;
  9586. }
  9587. if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
  9588. close(fds[0]);
  9589. close(fds[1]);
  9590. return NULL;
  9591. }
  9592. }
  9593. #ifdef HAVE_PIPE2
  9594. }
  9595. #endif
  9596. if (res != 0)
  9597. return PyErr_SetFromErrno(PyExc_OSError);
  9598. #endif /* !MS_WINDOWS */
  9599. return Py_BuildValue("(ii)", fds[0], fds[1]);
  9600. }
  9601. #endif /* HAVE_PIPE */
  9602. #ifdef HAVE_PIPE2
  9603. /*[clinic input]
  9604. os.pipe2
  9605. flags: int
  9606. /
  9607. Create a pipe with flags set atomically.
  9608. Returns a tuple of two file descriptors:
  9609. (read_fd, write_fd)
  9610. flags can be constructed by ORing together one or more of these values:
  9611. O_NONBLOCK, O_CLOEXEC.
  9612. [clinic start generated code]*/
  9613. static PyObject *
  9614. os_pipe2_impl(PyObject *module, int flags)
  9615. /*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
  9616. {
  9617. int fds[2];
  9618. int res;
  9619. res = pipe2(fds, flags);
  9620. if (res != 0)
  9621. return posix_error();
  9622. return Py_BuildValue("(ii)", fds[0], fds[1]);
  9623. }
  9624. #endif /* HAVE_PIPE2 */
  9625. #ifdef HAVE_WRITEV
  9626. /*[clinic input]
  9627. os.writev -> Py_ssize_t
  9628. fd: int
  9629. buffers: object
  9630. /
  9631. Iterate over buffers, and write the contents of each to a file descriptor.
  9632. Returns the total number of bytes written.
  9633. buffers must be a sequence of bytes-like objects.
  9634. [clinic start generated code]*/
  9635. static Py_ssize_t
  9636. os_writev_impl(PyObject *module, int fd, PyObject *buffers)
  9637. /*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
  9638. {
  9639. Py_ssize_t cnt;
  9640. Py_ssize_t result;
  9641. int async_err = 0;
  9642. struct iovec *iov;
  9643. Py_buffer *buf;
  9644. if (!PySequence_Check(buffers)) {
  9645. PyErr_SetString(PyExc_TypeError,
  9646. "writev() arg 2 must be a sequence");
  9647. return -1;
  9648. }
  9649. cnt = PySequence_Size(buffers);
  9650. if (cnt < 0)
  9651. return -1;
  9652. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
  9653. return -1;
  9654. }
  9655. do {
  9656. Py_BEGIN_ALLOW_THREADS
  9657. result = writev(fd, iov, cnt);
  9658. Py_END_ALLOW_THREADS
  9659. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9660. if (result < 0 && !async_err)
  9661. posix_error();
  9662. iov_cleanup(iov, buf, cnt);
  9663. return result;
  9664. }
  9665. #endif /* HAVE_WRITEV */
  9666. #ifdef HAVE_PWRITE
  9667. /*[clinic input]
  9668. os.pwrite -> Py_ssize_t
  9669. fd: int
  9670. buffer: Py_buffer
  9671. offset: Py_off_t
  9672. /
  9673. Write bytes to a file descriptor starting at a particular offset.
  9674. Write buffer to fd, starting at offset bytes from the beginning of
  9675. the file. Returns the number of bytes writte. Does not change the
  9676. current file offset.
  9677. [clinic start generated code]*/
  9678. static Py_ssize_t
  9679. os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
  9680. /*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
  9681. {
  9682. Py_ssize_t size;
  9683. int async_err = 0;
  9684. do {
  9685. Py_BEGIN_ALLOW_THREADS
  9686. _Py_BEGIN_SUPPRESS_IPH
  9687. size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
  9688. _Py_END_SUPPRESS_IPH
  9689. Py_END_ALLOW_THREADS
  9690. } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9691. if (size < 0 && !async_err)
  9692. posix_error();
  9693. return size;
  9694. }
  9695. #endif /* HAVE_PWRITE */
  9696. #if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
  9697. /*[clinic input]
  9698. os.pwritev -> Py_ssize_t
  9699. fd: int
  9700. buffers: object
  9701. offset: Py_off_t
  9702. flags: int = 0
  9703. /
  9704. Writes the contents of bytes-like objects to a file descriptor at a given offset.
  9705. Combines the functionality of writev() and pwrite(). All buffers must be a sequence
  9706. of bytes-like objects. Buffers are processed in array order. Entire contents of first
  9707. buffer is written before proceeding to second, and so on. The operating system may
  9708. set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
  9709. This function writes the contents of each object to the file descriptor and returns
  9710. the total number of bytes written.
  9711. The flags argument contains a bitwise OR of zero or more of the following flags:
  9712. - RWF_DSYNC
  9713. - RWF_SYNC
  9714. - RWF_APPEND
  9715. Using non-zero flags requires Linux 4.7 or newer.
  9716. [clinic start generated code]*/
  9717. static Py_ssize_t
  9718. os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
  9719. int flags)
  9720. /*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=35358c327e1a2a8e]*/
  9721. {
  9722. Py_ssize_t cnt;
  9723. Py_ssize_t result;
  9724. int async_err = 0;
  9725. struct iovec *iov;
  9726. Py_buffer *buf;
  9727. if (!PySequence_Check(buffers)) {
  9728. PyErr_SetString(PyExc_TypeError,
  9729. "pwritev() arg 2 must be a sequence");
  9730. return -1;
  9731. }
  9732. cnt = PySequence_Size(buffers);
  9733. if (cnt < 0) {
  9734. return -1;
  9735. }
  9736. #ifndef HAVE_PWRITEV2
  9737. if(flags != 0) {
  9738. argument_unavailable_error("pwritev2", "flags");
  9739. return -1;
  9740. }
  9741. #endif
  9742. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
  9743. return -1;
  9744. }
  9745. #ifdef HAVE_PWRITEV2
  9746. do {
  9747. Py_BEGIN_ALLOW_THREADS
  9748. _Py_BEGIN_SUPPRESS_IPH
  9749. result = pwritev2(fd, iov, cnt, offset, flags);
  9750. _Py_END_SUPPRESS_IPH
  9751. Py_END_ALLOW_THREADS
  9752. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9753. #else
  9754. #if defined(__APPLE__) && defined(__clang__)
  9755. /* This entire function will be removed from the module dict when the API
  9756. * is not available.
  9757. */
  9758. #pragma clang diagnostic push
  9759. #pragma clang diagnostic ignored "-Wunguarded-availability"
  9760. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  9761. #endif
  9762. do {
  9763. Py_BEGIN_ALLOW_THREADS
  9764. _Py_BEGIN_SUPPRESS_IPH
  9765. result = pwritev(fd, iov, cnt, offset);
  9766. _Py_END_SUPPRESS_IPH
  9767. Py_END_ALLOW_THREADS
  9768. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9769. #if defined(__APPLE__) && defined(__clang__)
  9770. #pragma clang diagnostic pop
  9771. #endif
  9772. #endif
  9773. if (result < 0) {
  9774. if (!async_err) {
  9775. posix_error();
  9776. }
  9777. result = -1;
  9778. }
  9779. iov_cleanup(iov, buf, cnt);
  9780. return result;
  9781. }
  9782. #endif /* HAVE_PWRITEV */
  9783. #ifdef HAVE_COPY_FILE_RANGE
  9784. /*[clinic input]
  9785. os.copy_file_range
  9786. src: int
  9787. Source file descriptor.
  9788. dst: int
  9789. Destination file descriptor.
  9790. count: Py_ssize_t
  9791. Number of bytes to copy.
  9792. offset_src: object = None
  9793. Starting offset in src.
  9794. offset_dst: object = None
  9795. Starting offset in dst.
  9796. Copy count bytes from one file descriptor to another.
  9797. If offset_src is None, then src is read from the current position;
  9798. respectively for offset_dst.
  9799. [clinic start generated code]*/
  9800. static PyObject *
  9801. os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
  9802. PyObject *offset_src, PyObject *offset_dst)
  9803. /*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
  9804. {
  9805. off_t offset_src_val, offset_dst_val;
  9806. off_t *p_offset_src = NULL;
  9807. off_t *p_offset_dst = NULL;
  9808. Py_ssize_t ret;
  9809. int async_err = 0;
  9810. /* The flags argument is provided to allow
  9811. * for future extensions and currently must be to 0. */
  9812. int flags = 0;
  9813. if (count < 0) {
  9814. PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
  9815. return NULL;
  9816. }
  9817. if (offset_src != Py_None) {
  9818. if (!Py_off_t_converter(offset_src, &offset_src_val)) {
  9819. return NULL;
  9820. }
  9821. p_offset_src = &offset_src_val;
  9822. }
  9823. if (offset_dst != Py_None) {
  9824. if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
  9825. return NULL;
  9826. }
  9827. p_offset_dst = &offset_dst_val;
  9828. }
  9829. do {
  9830. Py_BEGIN_ALLOW_THREADS
  9831. ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
  9832. Py_END_ALLOW_THREADS
  9833. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9834. if (ret < 0) {
  9835. return (!async_err) ? posix_error() : NULL;
  9836. }
  9837. return PyLong_FromSsize_t(ret);
  9838. }
  9839. #endif /* HAVE_COPY_FILE_RANGE*/
  9840. #if (defined(HAVE_SPLICE) && !defined(_AIX))
  9841. /*[clinic input]
  9842. os.splice
  9843. src: int
  9844. Source file descriptor.
  9845. dst: int
  9846. Destination file descriptor.
  9847. count: Py_ssize_t
  9848. Number of bytes to copy.
  9849. offset_src: object = None
  9850. Starting offset in src.
  9851. offset_dst: object = None
  9852. Starting offset in dst.
  9853. flags: unsigned_int = 0
  9854. Flags to modify the semantics of the call.
  9855. Transfer count bytes from one pipe to a descriptor or vice versa.
  9856. If offset_src is None, then src is read from the current position;
  9857. respectively for offset_dst. The offset associated to the file
  9858. descriptor that refers to a pipe must be None.
  9859. [clinic start generated code]*/
  9860. static PyObject *
  9861. os_splice_impl(PyObject *module, int src, int dst, Py_ssize_t count,
  9862. PyObject *offset_src, PyObject *offset_dst,
  9863. unsigned int flags)
  9864. /*[clinic end generated code: output=d0386f25a8519dc5 input=047527c66c6d2e0a]*/
  9865. {
  9866. off_t offset_src_val, offset_dst_val;
  9867. off_t *p_offset_src = NULL;
  9868. off_t *p_offset_dst = NULL;
  9869. Py_ssize_t ret;
  9870. int async_err = 0;
  9871. if (count < 0) {
  9872. PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
  9873. return NULL;
  9874. }
  9875. if (offset_src != Py_None) {
  9876. if (!Py_off_t_converter(offset_src, &offset_src_val)) {
  9877. return NULL;
  9878. }
  9879. p_offset_src = &offset_src_val;
  9880. }
  9881. if (offset_dst != Py_None) {
  9882. if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
  9883. return NULL;
  9884. }
  9885. p_offset_dst = &offset_dst_val;
  9886. }
  9887. do {
  9888. Py_BEGIN_ALLOW_THREADS
  9889. ret = splice(src, p_offset_src, dst, p_offset_dst, count, flags);
  9890. Py_END_ALLOW_THREADS
  9891. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9892. if (ret < 0) {
  9893. return (!async_err) ? posix_error() : NULL;
  9894. }
  9895. return PyLong_FromSsize_t(ret);
  9896. }
  9897. #endif /* HAVE_SPLICE*/
  9898. #ifdef HAVE_MKFIFO
  9899. /*[clinic input]
  9900. os.mkfifo
  9901. path: path_t
  9902. mode: int=0o666
  9903. *
  9904. dir_fd: dir_fd(requires='mkfifoat')=None
  9905. Create a "fifo" (a POSIX named pipe).
  9906. If dir_fd is not None, it should be a file descriptor open to a directory,
  9907. and path should be relative; path will then be relative to that directory.
  9908. dir_fd may not be implemented on your platform.
  9909. If it is unavailable, using it will raise a NotImplementedError.
  9910. [clinic start generated code]*/
  9911. static PyObject *
  9912. os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
  9913. /*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
  9914. {
  9915. int result;
  9916. int async_err = 0;
  9917. #ifdef HAVE_MKFIFOAT
  9918. int mkfifoat_unavailable = 0;
  9919. #endif
  9920. do {
  9921. Py_BEGIN_ALLOW_THREADS
  9922. #ifdef HAVE_MKFIFOAT
  9923. if (dir_fd != DEFAULT_DIR_FD) {
  9924. if (HAVE_MKFIFOAT_RUNTIME) {
  9925. result = mkfifoat(dir_fd, path->narrow, mode);
  9926. } else {
  9927. mkfifoat_unavailable = 1;
  9928. result = 0;
  9929. }
  9930. } else
  9931. #endif
  9932. result = mkfifo(path->narrow, mode);
  9933. Py_END_ALLOW_THREADS
  9934. } while (result != 0 && errno == EINTR &&
  9935. !(async_err = PyErr_CheckSignals()));
  9936. #ifdef HAVE_MKFIFOAT
  9937. if (mkfifoat_unavailable) {
  9938. argument_unavailable_error(NULL, "dir_fd");
  9939. return NULL;
  9940. }
  9941. #endif
  9942. if (result != 0)
  9943. return (!async_err) ? posix_error() : NULL;
  9944. Py_RETURN_NONE;
  9945. }
  9946. #endif /* HAVE_MKFIFO */
  9947. #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
  9948. /*[clinic input]
  9949. os.mknod
  9950. path: path_t
  9951. mode: int=0o600
  9952. device: dev_t=0
  9953. *
  9954. dir_fd: dir_fd(requires='mknodat')=None
  9955. Create a node in the file system.
  9956. Create a node in the file system (file, device special file or named pipe)
  9957. at path. mode specifies both the permissions to use and the
  9958. type of node to be created, being combined (bitwise OR) with one of
  9959. S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
  9960. device defines the newly created device special file (probably using
  9961. os.makedev()). Otherwise device is ignored.
  9962. If dir_fd is not None, it should be a file descriptor open to a directory,
  9963. and path should be relative; path will then be relative to that directory.
  9964. dir_fd may not be implemented on your platform.
  9965. If it is unavailable, using it will raise a NotImplementedError.
  9966. [clinic start generated code]*/
  9967. static PyObject *
  9968. os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
  9969. int dir_fd)
  9970. /*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
  9971. {
  9972. int result;
  9973. int async_err = 0;
  9974. #ifdef HAVE_MKNODAT
  9975. int mknodat_unavailable = 0;
  9976. #endif
  9977. do {
  9978. Py_BEGIN_ALLOW_THREADS
  9979. #ifdef HAVE_MKNODAT
  9980. if (dir_fd != DEFAULT_DIR_FD) {
  9981. if (HAVE_MKNODAT_RUNTIME) {
  9982. result = mknodat(dir_fd, path->narrow, mode, device);
  9983. } else {
  9984. mknodat_unavailable = 1;
  9985. result = 0;
  9986. }
  9987. } else
  9988. #endif
  9989. result = mknod(path->narrow, mode, device);
  9990. Py_END_ALLOW_THREADS
  9991. } while (result != 0 && errno == EINTR &&
  9992. !(async_err = PyErr_CheckSignals()));
  9993. #ifdef HAVE_MKNODAT
  9994. if (mknodat_unavailable) {
  9995. argument_unavailable_error(NULL, "dir_fd");
  9996. return NULL;
  9997. }
  9998. #endif
  9999. if (result != 0)
  10000. return (!async_err) ? posix_error() : NULL;
  10001. Py_RETURN_NONE;
  10002. }
  10003. #endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
  10004. #ifdef HAVE_DEVICE_MACROS
  10005. static PyObject *
  10006. major_minor_conv(unsigned int value)
  10007. {
  10008. #ifdef NODEV
  10009. if (value == (unsigned int)NODEV) {
  10010. return PyLong_FromLong((int)NODEV);
  10011. }
  10012. #endif
  10013. return PyLong_FromUnsignedLong(value);
  10014. }
  10015. static int
  10016. major_minor_check(dev_t value)
  10017. {
  10018. #ifdef NODEV
  10019. if (value == NODEV) {
  10020. return 1;
  10021. }
  10022. #endif
  10023. return (dev_t)(unsigned int)value == value;
  10024. }
  10025. /*[clinic input]
  10026. os.major
  10027. device: dev_t
  10028. /
  10029. Extracts a device major number from a raw device number.
  10030. [clinic start generated code]*/
  10031. static PyObject *
  10032. os_major_impl(PyObject *module, dev_t device)
  10033. /*[clinic end generated code: output=4071ffee17647891 input=b1a0a14ec9448229]*/
  10034. {
  10035. return major_minor_conv(major(device));
  10036. }
  10037. /*[clinic input]
  10038. os.minor
  10039. device: dev_t
  10040. /
  10041. Extracts a device minor number from a raw device number.
  10042. [clinic start generated code]*/
  10043. static PyObject *
  10044. os_minor_impl(PyObject *module, dev_t device)
  10045. /*[clinic end generated code: output=306cb78e3bc5004f input=2f686e463682a9da]*/
  10046. {
  10047. return major_minor_conv(minor(device));
  10048. }
  10049. /*[clinic input]
  10050. os.makedev -> dev_t
  10051. major: dev_t
  10052. minor: dev_t
  10053. /
  10054. Composes a raw device number from the major and minor device numbers.
  10055. [clinic start generated code]*/
  10056. static dev_t
  10057. os_makedev_impl(PyObject *module, dev_t major, dev_t minor)
  10058. /*[clinic end generated code: output=cad6125c51f5af80 input=2146126ec02e55c1]*/
  10059. {
  10060. if (!major_minor_check(major) || !major_minor_check(minor)) {
  10061. PyErr_SetString(PyExc_OverflowError,
  10062. "Python int too large to convert to C unsigned int");
  10063. return (dev_t)-1;
  10064. }
  10065. return makedev(major, minor);
  10066. }
  10067. #endif /* HAVE_DEVICE_MACROS */
  10068. #if defined HAVE_FTRUNCATE || defined MS_WINDOWS
  10069. /*[clinic input]
  10070. os.ftruncate
  10071. fd: int
  10072. length: Py_off_t
  10073. /
  10074. Truncate a file, specified by file descriptor, to a specific length.
  10075. [clinic start generated code]*/
  10076. static PyObject *
  10077. os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
  10078. /*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
  10079. {
  10080. int result;
  10081. int async_err = 0;
  10082. if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
  10083. return NULL;
  10084. }
  10085. do {
  10086. Py_BEGIN_ALLOW_THREADS
  10087. _Py_BEGIN_SUPPRESS_IPH
  10088. #ifdef MS_WINDOWS
  10089. result = _chsize_s(fd, length);
  10090. #else
  10091. result = ftruncate(fd, length);
  10092. #endif
  10093. _Py_END_SUPPRESS_IPH
  10094. Py_END_ALLOW_THREADS
  10095. } while (result != 0 && errno == EINTR &&
  10096. !(async_err = PyErr_CheckSignals()));
  10097. if (result != 0)
  10098. return (!async_err) ? posix_error() : NULL;
  10099. Py_RETURN_NONE;
  10100. }
  10101. #endif /* HAVE_FTRUNCATE || MS_WINDOWS */
  10102. #if defined HAVE_TRUNCATE || defined MS_WINDOWS
  10103. /*[clinic input]
  10104. os.truncate
  10105. path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
  10106. length: Py_off_t
  10107. Truncate a file, specified by path, to a specific length.
  10108. On some platforms, path may also be specified as an open file descriptor.
  10109. If this functionality is unavailable, using it raises an exception.
  10110. [clinic start generated code]*/
  10111. static PyObject *
  10112. os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
  10113. /*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
  10114. {
  10115. int result;
  10116. #ifdef MS_WINDOWS
  10117. int fd;
  10118. #endif
  10119. if (path->fd != -1)
  10120. return os_ftruncate_impl(module, path->fd, length);
  10121. if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
  10122. return NULL;
  10123. }
  10124. Py_BEGIN_ALLOW_THREADS
  10125. _Py_BEGIN_SUPPRESS_IPH
  10126. #ifdef MS_WINDOWS
  10127. fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
  10128. if (fd < 0)
  10129. result = -1;
  10130. else {
  10131. result = _chsize_s(fd, length);
  10132. close(fd);
  10133. if (result < 0)
  10134. errno = result;
  10135. }
  10136. #else
  10137. result = truncate(path->narrow, length);
  10138. #endif
  10139. _Py_END_SUPPRESS_IPH
  10140. Py_END_ALLOW_THREADS
  10141. if (result < 0)
  10142. return posix_path_error(path);
  10143. Py_RETURN_NONE;
  10144. }
  10145. #endif /* HAVE_TRUNCATE || MS_WINDOWS */
  10146. /* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
  10147. and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
  10148. defined, which is the case in Python on AIX. AIX bug report:
  10149. http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
  10150. #if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
  10151. # define POSIX_FADVISE_AIX_BUG
  10152. #endif
  10153. /* GH-111804: Due to posix_fallocate() not having consistent semantics across
  10154. OSs, support was dropped in WASI preview2. */
  10155. #if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG) && \
  10156. !defined(__wasi__)
  10157. /*[clinic input]
  10158. os.posix_fallocate
  10159. fd: int
  10160. offset: Py_off_t
  10161. length: Py_off_t
  10162. /
  10163. Ensure a file has allocated at least a particular number of bytes on disk.
  10164. Ensure that the file specified by fd encompasses a range of bytes
  10165. starting at offset bytes from the beginning and continuing for length bytes.
  10166. [clinic start generated code]*/
  10167. static PyObject *
  10168. os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
  10169. Py_off_t length)
  10170. /*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
  10171. {
  10172. int result;
  10173. int async_err = 0;
  10174. do {
  10175. Py_BEGIN_ALLOW_THREADS
  10176. result = posix_fallocate(fd, offset, length);
  10177. Py_END_ALLOW_THREADS
  10178. } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
  10179. if (result == 0)
  10180. Py_RETURN_NONE;
  10181. if (async_err)
  10182. return NULL;
  10183. errno = result;
  10184. return posix_error();
  10185. }
  10186. #endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG && !defined(__wasi__) */
  10187. #if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
  10188. /*[clinic input]
  10189. os.posix_fadvise
  10190. fd: int
  10191. offset: Py_off_t
  10192. length: Py_off_t
  10193. advice: int
  10194. /
  10195. Announce an intention to access data in a specific pattern.
  10196. Announce an intention to access data in a specific pattern, thus allowing
  10197. the kernel to make optimizations.
  10198. The advice applies to the region of the file specified by fd starting at
  10199. offset and continuing for length bytes.
  10200. advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
  10201. POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
  10202. POSIX_FADV_DONTNEED.
  10203. [clinic start generated code]*/
  10204. static PyObject *
  10205. os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
  10206. Py_off_t length, int advice)
  10207. /*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
  10208. {
  10209. int result;
  10210. int async_err = 0;
  10211. do {
  10212. Py_BEGIN_ALLOW_THREADS
  10213. result = posix_fadvise(fd, offset, length, advice);
  10214. Py_END_ALLOW_THREADS
  10215. } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
  10216. if (result == 0)
  10217. Py_RETURN_NONE;
  10218. if (async_err)
  10219. return NULL;
  10220. errno = result;
  10221. return posix_error();
  10222. }
  10223. #endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
  10224. #ifdef MS_WINDOWS
  10225. static PyObject*
  10226. win32_putenv(PyObject *name, PyObject *value)
  10227. {
  10228. /* Search from index 1 because on Windows starting '=' is allowed for
  10229. defining hidden environment variables. */
  10230. if (PyUnicode_GET_LENGTH(name) == 0 ||
  10231. PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
  10232. {
  10233. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  10234. return NULL;
  10235. }
  10236. PyObject *unicode;
  10237. if (value != NULL) {
  10238. unicode = PyUnicode_FromFormat("%U=%U", name, value);
  10239. }
  10240. else {
  10241. unicode = PyUnicode_FromFormat("%U=", name);
  10242. }
  10243. if (unicode == NULL) {
  10244. return NULL;
  10245. }
  10246. Py_ssize_t size;
  10247. wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
  10248. Py_DECREF(unicode);
  10249. if (env == NULL) {
  10250. return NULL;
  10251. }
  10252. if (size > _MAX_ENV) {
  10253. PyErr_Format(PyExc_ValueError,
  10254. "the environment variable is longer than %u characters",
  10255. _MAX_ENV);
  10256. PyMem_Free(env);
  10257. return NULL;
  10258. }
  10259. if (wcslen(env) != (size_t)size) {
  10260. PyErr_SetString(PyExc_ValueError,
  10261. "embedded null character");
  10262. PyMem_Free(env);
  10263. return NULL;
  10264. }
  10265. /* _wputenv() and SetEnvironmentVariableW() update the environment in the
  10266. Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
  10267. and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
  10268. Prefer _wputenv() to be compatible with C libraries using CRT
  10269. variables and CRT functions using these variables (ex: getenv()). */
  10270. int err = _wputenv(env);
  10271. if (err) {
  10272. posix_error();
  10273. PyMem_Free(env);
  10274. return NULL;
  10275. }
  10276. PyMem_Free(env);
  10277. Py_RETURN_NONE;
  10278. }
  10279. #endif
  10280. #ifdef MS_WINDOWS
  10281. /*[clinic input]
  10282. os.putenv
  10283. name: unicode
  10284. value: unicode
  10285. /
  10286. Change or add an environment variable.
  10287. [clinic start generated code]*/
  10288. static PyObject *
  10289. os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
  10290. /*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
  10291. {
  10292. if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
  10293. return NULL;
  10294. }
  10295. return win32_putenv(name, value);
  10296. }
  10297. #else
  10298. /*[clinic input]
  10299. os.putenv
  10300. name: FSConverter
  10301. value: FSConverter
  10302. /
  10303. Change or add an environment variable.
  10304. [clinic start generated code]*/
  10305. static PyObject *
  10306. os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
  10307. /*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
  10308. {
  10309. const char *name_string = PyBytes_AS_STRING(name);
  10310. const char *value_string = PyBytes_AS_STRING(value);
  10311. if (strchr(name_string, '=') != NULL) {
  10312. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  10313. return NULL;
  10314. }
  10315. if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
  10316. return NULL;
  10317. }
  10318. if (setenv(name_string, value_string, 1)) {
  10319. return posix_error();
  10320. }
  10321. Py_RETURN_NONE;
  10322. }
  10323. #endif /* !defined(MS_WINDOWS) */
  10324. #ifdef MS_WINDOWS
  10325. /*[clinic input]
  10326. os.unsetenv
  10327. name: unicode
  10328. /
  10329. Delete an environment variable.
  10330. [clinic start generated code]*/
  10331. static PyObject *
  10332. os_unsetenv_impl(PyObject *module, PyObject *name)
  10333. /*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
  10334. {
  10335. if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
  10336. return NULL;
  10337. }
  10338. return win32_putenv(name, NULL);
  10339. }
  10340. #else
  10341. /*[clinic input]
  10342. os.unsetenv
  10343. name: FSConverter
  10344. /
  10345. Delete an environment variable.
  10346. [clinic start generated code]*/
  10347. static PyObject *
  10348. os_unsetenv_impl(PyObject *module, PyObject *name)
  10349. /*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
  10350. {
  10351. if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
  10352. return NULL;
  10353. }
  10354. #ifdef HAVE_BROKEN_UNSETENV
  10355. unsetenv(PyBytes_AS_STRING(name));
  10356. #else
  10357. int err = unsetenv(PyBytes_AS_STRING(name));
  10358. if (err) {
  10359. return posix_error();
  10360. }
  10361. #endif
  10362. Py_RETURN_NONE;
  10363. }
  10364. #endif /* !MS_WINDOWS */
  10365. /*[clinic input]
  10366. os.strerror
  10367. code: int
  10368. /
  10369. Translate an error code to a message string.
  10370. [clinic start generated code]*/
  10371. static PyObject *
  10372. os_strerror_impl(PyObject *module, int code)
  10373. /*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
  10374. {
  10375. char *message = strerror(code);
  10376. if (message == NULL) {
  10377. PyErr_SetString(PyExc_ValueError,
  10378. "strerror() argument out of range");
  10379. return NULL;
  10380. }
  10381. return PyUnicode_DecodeLocale(message, "surrogateescape");
  10382. }
  10383. #ifdef HAVE_SYS_WAIT_H
  10384. #ifdef WCOREDUMP
  10385. /*[clinic input]
  10386. os.WCOREDUMP -> bool
  10387. status: int
  10388. /
  10389. Return True if the process returning status was dumped to a core file.
  10390. [clinic start generated code]*/
  10391. static int
  10392. os_WCOREDUMP_impl(PyObject *module, int status)
  10393. /*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
  10394. {
  10395. WAIT_TYPE wait_status;
  10396. WAIT_STATUS_INT(wait_status) = status;
  10397. return WCOREDUMP(wait_status);
  10398. }
  10399. #endif /* WCOREDUMP */
  10400. #ifdef WIFCONTINUED
  10401. /*[clinic input]
  10402. os.WIFCONTINUED -> bool
  10403. status: int
  10404. Return True if a particular process was continued from a job control stop.
  10405. Return True if the process returning status was continued from a
  10406. job control stop.
  10407. [clinic start generated code]*/
  10408. static int
  10409. os_WIFCONTINUED_impl(PyObject *module, int status)
  10410. /*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
  10411. {
  10412. WAIT_TYPE wait_status;
  10413. WAIT_STATUS_INT(wait_status) = status;
  10414. return WIFCONTINUED(wait_status);
  10415. }
  10416. #endif /* WIFCONTINUED */
  10417. #ifdef WIFSTOPPED
  10418. /*[clinic input]
  10419. os.WIFSTOPPED -> bool
  10420. status: int
  10421. Return True if the process returning status was stopped.
  10422. [clinic start generated code]*/
  10423. static int
  10424. os_WIFSTOPPED_impl(PyObject *module, int status)
  10425. /*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
  10426. {
  10427. WAIT_TYPE wait_status;
  10428. WAIT_STATUS_INT(wait_status) = status;
  10429. return WIFSTOPPED(wait_status);
  10430. }
  10431. #endif /* WIFSTOPPED */
  10432. #ifdef WIFSIGNALED
  10433. /*[clinic input]
  10434. os.WIFSIGNALED -> bool
  10435. status: int
  10436. Return True if the process returning status was terminated by a signal.
  10437. [clinic start generated code]*/
  10438. static int
  10439. os_WIFSIGNALED_impl(PyObject *module, int status)
  10440. /*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
  10441. {
  10442. WAIT_TYPE wait_status;
  10443. WAIT_STATUS_INT(wait_status) = status;
  10444. return WIFSIGNALED(wait_status);
  10445. }
  10446. #endif /* WIFSIGNALED */
  10447. #ifdef WIFEXITED
  10448. /*[clinic input]
  10449. os.WIFEXITED -> bool
  10450. status: int
  10451. Return True if the process returning status exited via the exit() system call.
  10452. [clinic start generated code]*/
  10453. static int
  10454. os_WIFEXITED_impl(PyObject *module, int status)
  10455. /*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
  10456. {
  10457. WAIT_TYPE wait_status;
  10458. WAIT_STATUS_INT(wait_status) = status;
  10459. return WIFEXITED(wait_status);
  10460. }
  10461. #endif /* WIFEXITED */
  10462. #ifdef WEXITSTATUS
  10463. /*[clinic input]
  10464. os.WEXITSTATUS -> int
  10465. status: int
  10466. Return the process return code from status.
  10467. [clinic start generated code]*/
  10468. static int
  10469. os_WEXITSTATUS_impl(PyObject *module, int status)
  10470. /*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
  10471. {
  10472. WAIT_TYPE wait_status;
  10473. WAIT_STATUS_INT(wait_status) = status;
  10474. return WEXITSTATUS(wait_status);
  10475. }
  10476. #endif /* WEXITSTATUS */
  10477. #ifdef WTERMSIG
  10478. /*[clinic input]
  10479. os.WTERMSIG -> int
  10480. status: int
  10481. Return the signal that terminated the process that provided the status value.
  10482. [clinic start generated code]*/
  10483. static int
  10484. os_WTERMSIG_impl(PyObject *module, int status)
  10485. /*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
  10486. {
  10487. WAIT_TYPE wait_status;
  10488. WAIT_STATUS_INT(wait_status) = status;
  10489. return WTERMSIG(wait_status);
  10490. }
  10491. #endif /* WTERMSIG */
  10492. #ifdef WSTOPSIG
  10493. /*[clinic input]
  10494. os.WSTOPSIG -> int
  10495. status: int
  10496. Return the signal that stopped the process that provided the status value.
  10497. [clinic start generated code]*/
  10498. static int
  10499. os_WSTOPSIG_impl(PyObject *module, int status)
  10500. /*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
  10501. {
  10502. WAIT_TYPE wait_status;
  10503. WAIT_STATUS_INT(wait_status) = status;
  10504. return WSTOPSIG(wait_status);
  10505. }
  10506. #endif /* WSTOPSIG */
  10507. #endif /* HAVE_SYS_WAIT_H */
  10508. #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
  10509. #ifdef _SCO_DS
  10510. /* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
  10511. needed definitions in sys/statvfs.h */
  10512. #define _SVID3
  10513. #endif
  10514. #include <sys/statvfs.h>
  10515. static PyObject*
  10516. _pystatvfs_fromstructstatvfs(PyObject *module, struct statvfs st) {
  10517. PyObject *StatVFSResultType = get_posix_state(module)->StatVFSResultType;
  10518. PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
  10519. if (v == NULL)
  10520. return NULL;
  10521. int pos = 0;
  10522. #define SET_RESULT(CALL) \
  10523. do { \
  10524. PyObject *item = (CALL); \
  10525. if (item == NULL) { \
  10526. Py_DECREF(v); \
  10527. return NULL; \
  10528. } \
  10529. PyStructSequence_SET_ITEM(v, pos++, item); \
  10530. } while(0)
  10531. #if !defined(HAVE_LARGEFILE_SUPPORT)
  10532. SET_RESULT(PyLong_FromLong((long) st.f_bsize));
  10533. SET_RESULT(PyLong_FromLong((long) st.f_frsize));
  10534. SET_RESULT(PyLong_FromLong((long) st.f_blocks));
  10535. SET_RESULT(PyLong_FromLong((long) st.f_bfree));
  10536. SET_RESULT(PyLong_FromLong((long) st.f_bavail));
  10537. SET_RESULT(PyLong_FromLong((long) st.f_files));
  10538. SET_RESULT(PyLong_FromLong((long) st.f_ffree));
  10539. SET_RESULT(PyLong_FromLong((long) st.f_favail));
  10540. SET_RESULT(PyLong_FromLong((long) st.f_flag));
  10541. SET_RESULT(PyLong_FromLong((long) st.f_namemax));
  10542. #else
  10543. SET_RESULT(PyLong_FromLong((long) st.f_bsize));
  10544. SET_RESULT(PyLong_FromLong((long) st.f_frsize));
  10545. SET_RESULT(PyLong_FromLongLong((long long) st.f_blocks));
  10546. SET_RESULT(PyLong_FromLongLong((long long) st.f_bfree));
  10547. SET_RESULT(PyLong_FromLongLong((long long) st.f_bavail));
  10548. SET_RESULT(PyLong_FromLongLong((long long) st.f_files));
  10549. SET_RESULT(PyLong_FromLongLong((long long) st.f_ffree));
  10550. SET_RESULT(PyLong_FromLongLong((long long) st.f_favail));
  10551. SET_RESULT(PyLong_FromLong((long) st.f_flag));
  10552. SET_RESULT(PyLong_FromLong((long) st.f_namemax));
  10553. #endif
  10554. /* The _ALL_SOURCE feature test macro defines f_fsid as a structure
  10555. * (issue #32390). */
  10556. #if defined(_AIX) && defined(_ALL_SOURCE)
  10557. SET_RESULT(PyLong_FromUnsignedLong(st.f_fsid.val[0]));
  10558. #else
  10559. SET_RESULT(PyLong_FromUnsignedLong(st.f_fsid));
  10560. #endif
  10561. #undef SET_RESULT
  10562. return v;
  10563. }
  10564. /*[clinic input]
  10565. os.fstatvfs
  10566. fd: int
  10567. /
  10568. Perform an fstatvfs system call on the given fd.
  10569. Equivalent to statvfs(fd).
  10570. [clinic start generated code]*/
  10571. static PyObject *
  10572. os_fstatvfs_impl(PyObject *module, int fd)
  10573. /*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
  10574. {
  10575. int result;
  10576. int async_err = 0;
  10577. struct statvfs st;
  10578. do {
  10579. Py_BEGIN_ALLOW_THREADS
  10580. result = fstatvfs(fd, &st);
  10581. Py_END_ALLOW_THREADS
  10582. } while (result != 0 && errno == EINTR &&
  10583. !(async_err = PyErr_CheckSignals()));
  10584. if (result != 0)
  10585. return (!async_err) ? posix_error() : NULL;
  10586. return _pystatvfs_fromstructstatvfs(module, st);
  10587. }
  10588. #endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
  10589. #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
  10590. #include <sys/statvfs.h>
  10591. /*[clinic input]
  10592. os.statvfs
  10593. path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
  10594. Perform a statvfs system call on the given path.
  10595. path may always be specified as a string.
  10596. On some platforms, path may also be specified as an open file descriptor.
  10597. If this functionality is unavailable, using it raises an exception.
  10598. [clinic start generated code]*/
  10599. static PyObject *
  10600. os_statvfs_impl(PyObject *module, path_t *path)
  10601. /*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
  10602. {
  10603. int result;
  10604. struct statvfs st;
  10605. Py_BEGIN_ALLOW_THREADS
  10606. #ifdef HAVE_FSTATVFS
  10607. if (path->fd != -1) {
  10608. result = fstatvfs(path->fd, &st);
  10609. }
  10610. else
  10611. #endif
  10612. result = statvfs(path->narrow, &st);
  10613. Py_END_ALLOW_THREADS
  10614. if (result) {
  10615. return path_error(path);
  10616. }
  10617. return _pystatvfs_fromstructstatvfs(module, st);
  10618. }
  10619. #endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
  10620. #ifdef MS_WINDOWS
  10621. /*[clinic input]
  10622. os._getdiskusage
  10623. path: path_t
  10624. Return disk usage statistics about the given path as a (total, free) tuple.
  10625. [clinic start generated code]*/
  10626. static PyObject *
  10627. os__getdiskusage_impl(PyObject *module, path_t *path)
  10628. /*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
  10629. {
  10630. BOOL retval;
  10631. ULARGE_INTEGER _, total, free;
  10632. DWORD err = 0;
  10633. Py_BEGIN_ALLOW_THREADS
  10634. retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
  10635. Py_END_ALLOW_THREADS
  10636. if (retval == 0) {
  10637. if (GetLastError() == ERROR_DIRECTORY) {
  10638. wchar_t *dir_path = NULL;
  10639. dir_path = PyMem_New(wchar_t, path->length + 1);
  10640. if (dir_path == NULL) {
  10641. return PyErr_NoMemory();
  10642. }
  10643. wcscpy_s(dir_path, path->length + 1, path->wide);
  10644. if (_dirnameW(dir_path) != -1) {
  10645. Py_BEGIN_ALLOW_THREADS
  10646. retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
  10647. Py_END_ALLOW_THREADS
  10648. }
  10649. /* Record the last error in case it's modified by PyMem_Free. */
  10650. err = GetLastError();
  10651. PyMem_Free(dir_path);
  10652. if (retval) {
  10653. goto success;
  10654. }
  10655. }
  10656. return PyErr_SetFromWindowsErr(err);
  10657. }
  10658. success:
  10659. return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
  10660. }
  10661. #endif /* MS_WINDOWS */
  10662. /* This is used for fpathconf(), pathconf(), confstr() and sysconf().
  10663. * It maps strings representing configuration variable names to
  10664. * integer values, allowing those functions to be called with the
  10665. * magic names instead of polluting the module's namespace with tons of
  10666. * rarely-used constants. There are three separate tables that use
  10667. * these definitions.
  10668. *
  10669. * This code is always included, even if none of the interfaces that
  10670. * need it are included. The #if hackery needed to avoid it would be
  10671. * sufficiently pervasive that it's not worth the loss of readability.
  10672. */
  10673. struct constdef {
  10674. const char *name;
  10675. int value;
  10676. };
  10677. static int
  10678. conv_confname(PyObject *arg, int *valuep, struct constdef *table,
  10679. size_t tablesize)
  10680. {
  10681. if (PyLong_Check(arg)) {
  10682. int value = _PyLong_AsInt(arg);
  10683. if (value == -1 && PyErr_Occurred())
  10684. return 0;
  10685. *valuep = value;
  10686. return 1;
  10687. }
  10688. else {
  10689. /* look up the value in the table using a binary search */
  10690. size_t lo = 0;
  10691. size_t mid;
  10692. size_t hi = tablesize;
  10693. int cmp;
  10694. const char *confname;
  10695. if (!PyUnicode_Check(arg)) {
  10696. PyErr_SetString(PyExc_TypeError,
  10697. "configuration names must be strings or integers");
  10698. return 0;
  10699. }
  10700. confname = PyUnicode_AsUTF8(arg);
  10701. if (confname == NULL)
  10702. return 0;
  10703. while (lo < hi) {
  10704. mid = (lo + hi) / 2;
  10705. cmp = strcmp(confname, table[mid].name);
  10706. if (cmp < 0)
  10707. hi = mid;
  10708. else if (cmp > 0)
  10709. lo = mid + 1;
  10710. else {
  10711. *valuep = table[mid].value;
  10712. return 1;
  10713. }
  10714. }
  10715. PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
  10716. return 0;
  10717. }
  10718. }
  10719. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  10720. static struct constdef posix_constants_pathconf[] = {
  10721. #ifdef _PC_ABI_AIO_XFER_MAX
  10722. {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
  10723. #endif
  10724. #ifdef _PC_ABI_ASYNC_IO
  10725. {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
  10726. #endif
  10727. #ifdef _PC_ASYNC_IO
  10728. {"PC_ASYNC_IO", _PC_ASYNC_IO},
  10729. #endif
  10730. #ifdef _PC_CHOWN_RESTRICTED
  10731. {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
  10732. #endif
  10733. #ifdef _PC_FILESIZEBITS
  10734. {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
  10735. #endif
  10736. #ifdef _PC_LAST
  10737. {"PC_LAST", _PC_LAST},
  10738. #endif
  10739. #ifdef _PC_LINK_MAX
  10740. {"PC_LINK_MAX", _PC_LINK_MAX},
  10741. #endif
  10742. #ifdef _PC_MAX_CANON
  10743. {"PC_MAX_CANON", _PC_MAX_CANON},
  10744. #endif
  10745. #ifdef _PC_MAX_INPUT
  10746. {"PC_MAX_INPUT", _PC_MAX_INPUT},
  10747. #endif
  10748. #ifdef _PC_NAME_MAX
  10749. {"PC_NAME_MAX", _PC_NAME_MAX},
  10750. #endif
  10751. #ifdef _PC_NO_TRUNC
  10752. {"PC_NO_TRUNC", _PC_NO_TRUNC},
  10753. #endif
  10754. #ifdef _PC_PATH_MAX
  10755. {"PC_PATH_MAX", _PC_PATH_MAX},
  10756. #endif
  10757. #ifdef _PC_PIPE_BUF
  10758. {"PC_PIPE_BUF", _PC_PIPE_BUF},
  10759. #endif
  10760. #ifdef _PC_PRIO_IO
  10761. {"PC_PRIO_IO", _PC_PRIO_IO},
  10762. #endif
  10763. #ifdef _PC_SOCK_MAXBUF
  10764. {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
  10765. #endif
  10766. #ifdef _PC_SYNC_IO
  10767. {"PC_SYNC_IO", _PC_SYNC_IO},
  10768. #endif
  10769. #ifdef _PC_VDISABLE
  10770. {"PC_VDISABLE", _PC_VDISABLE},
  10771. #endif
  10772. #ifdef _PC_ACL_ENABLED
  10773. {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
  10774. #endif
  10775. #ifdef _PC_MIN_HOLE_SIZE
  10776. {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
  10777. #endif
  10778. #ifdef _PC_ALLOC_SIZE_MIN
  10779. {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
  10780. #endif
  10781. #ifdef _PC_REC_INCR_XFER_SIZE
  10782. {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
  10783. #endif
  10784. #ifdef _PC_REC_MAX_XFER_SIZE
  10785. {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
  10786. #endif
  10787. #ifdef _PC_REC_MIN_XFER_SIZE
  10788. {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
  10789. #endif
  10790. #ifdef _PC_REC_XFER_ALIGN
  10791. {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
  10792. #endif
  10793. #ifdef _PC_SYMLINK_MAX
  10794. {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
  10795. #endif
  10796. #ifdef _PC_XATTR_ENABLED
  10797. {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
  10798. #endif
  10799. #ifdef _PC_XATTR_EXISTS
  10800. {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
  10801. #endif
  10802. #ifdef _PC_TIMESTAMP_RESOLUTION
  10803. {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
  10804. #endif
  10805. };
  10806. static int
  10807. conv_path_confname(PyObject *arg, int *valuep)
  10808. {
  10809. return conv_confname(arg, valuep, posix_constants_pathconf,
  10810. sizeof(posix_constants_pathconf)
  10811. / sizeof(struct constdef));
  10812. }
  10813. #endif
  10814. #ifdef HAVE_FPATHCONF
  10815. /*[clinic input]
  10816. os.fpathconf -> long
  10817. fd: fildes
  10818. name: path_confname
  10819. /
  10820. Return the configuration limit name for the file descriptor fd.
  10821. If there is no limit, return -1.
  10822. [clinic start generated code]*/
  10823. static long
  10824. os_fpathconf_impl(PyObject *module, int fd, int name)
  10825. /*[clinic end generated code: output=d5b7042425fc3e21 input=5b8d2471cfaae186]*/
  10826. {
  10827. long limit;
  10828. errno = 0;
  10829. limit = fpathconf(fd, name);
  10830. if (limit == -1 && errno != 0)
  10831. posix_error();
  10832. return limit;
  10833. }
  10834. #endif /* HAVE_FPATHCONF */
  10835. #ifdef HAVE_PATHCONF
  10836. /*[clinic input]
  10837. os.pathconf -> long
  10838. path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
  10839. name: path_confname
  10840. Return the configuration limit name for the file or directory path.
  10841. If there is no limit, return -1.
  10842. On some platforms, path may also be specified as an open file descriptor.
  10843. If this functionality is unavailable, using it raises an exception.
  10844. [clinic start generated code]*/
  10845. static long
  10846. os_pathconf_impl(PyObject *module, path_t *path, int name)
  10847. /*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
  10848. {
  10849. long limit;
  10850. errno = 0;
  10851. #ifdef HAVE_FPATHCONF
  10852. if (path->fd != -1)
  10853. limit = fpathconf(path->fd, name);
  10854. else
  10855. #endif
  10856. limit = pathconf(path->narrow, name);
  10857. if (limit == -1 && errno != 0) {
  10858. if (errno == EINVAL)
  10859. /* could be a path or name problem */
  10860. posix_error();
  10861. else
  10862. path_error(path);
  10863. }
  10864. return limit;
  10865. }
  10866. #endif /* HAVE_PATHCONF */
  10867. #ifdef HAVE_CONFSTR
  10868. static struct constdef posix_constants_confstr[] = {
  10869. #ifdef _CS_ARCHITECTURE
  10870. {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
  10871. #endif
  10872. #ifdef _CS_GNU_LIBC_VERSION
  10873. {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
  10874. #endif
  10875. #ifdef _CS_GNU_LIBPTHREAD_VERSION
  10876. {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
  10877. #endif
  10878. #ifdef _CS_HOSTNAME
  10879. {"CS_HOSTNAME", _CS_HOSTNAME},
  10880. #endif
  10881. #ifdef _CS_HW_PROVIDER
  10882. {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
  10883. #endif
  10884. #ifdef _CS_HW_SERIAL
  10885. {"CS_HW_SERIAL", _CS_HW_SERIAL},
  10886. #endif
  10887. #ifdef _CS_INITTAB_NAME
  10888. {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
  10889. #endif
  10890. #ifdef _CS_LFS64_CFLAGS
  10891. {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
  10892. #endif
  10893. #ifdef _CS_LFS64_LDFLAGS
  10894. {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
  10895. #endif
  10896. #ifdef _CS_LFS64_LIBS
  10897. {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
  10898. #endif
  10899. #ifdef _CS_LFS64_LINTFLAGS
  10900. {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
  10901. #endif
  10902. #ifdef _CS_LFS_CFLAGS
  10903. {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
  10904. #endif
  10905. #ifdef _CS_LFS_LDFLAGS
  10906. {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
  10907. #endif
  10908. #ifdef _CS_LFS_LIBS
  10909. {"CS_LFS_LIBS", _CS_LFS_LIBS},
  10910. #endif
  10911. #ifdef _CS_LFS_LINTFLAGS
  10912. {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
  10913. #endif
  10914. #ifdef _CS_MACHINE
  10915. {"CS_MACHINE", _CS_MACHINE},
  10916. #endif
  10917. #ifdef _CS_PATH
  10918. {"CS_PATH", _CS_PATH},
  10919. #endif
  10920. #ifdef _CS_RELEASE
  10921. {"CS_RELEASE", _CS_RELEASE},
  10922. #endif
  10923. #ifdef _CS_SRPC_DOMAIN
  10924. {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
  10925. #endif
  10926. #ifdef _CS_SYSNAME
  10927. {"CS_SYSNAME", _CS_SYSNAME},
  10928. #endif
  10929. #ifdef _CS_VERSION
  10930. {"CS_VERSION", _CS_VERSION},
  10931. #endif
  10932. #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
  10933. {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
  10934. #endif
  10935. #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
  10936. {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
  10937. #endif
  10938. #ifdef _CS_XBS5_ILP32_OFF32_LIBS
  10939. {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
  10940. #endif
  10941. #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
  10942. {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
  10943. #endif
  10944. #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
  10945. {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
  10946. #endif
  10947. #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
  10948. {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
  10949. #endif
  10950. #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
  10951. {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
  10952. #endif
  10953. #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
  10954. {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
  10955. #endif
  10956. #ifdef _CS_XBS5_LP64_OFF64_CFLAGS
  10957. {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
  10958. #endif
  10959. #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
  10960. {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
  10961. #endif
  10962. #ifdef _CS_XBS5_LP64_OFF64_LIBS
  10963. {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
  10964. #endif
  10965. #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
  10966. {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
  10967. #endif
  10968. #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
  10969. {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
  10970. #endif
  10971. #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
  10972. {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
  10973. #endif
  10974. #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
  10975. {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
  10976. #endif
  10977. #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
  10978. {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
  10979. #endif
  10980. #ifdef _MIPS_CS_AVAIL_PROCESSORS
  10981. {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
  10982. #endif
  10983. #ifdef _MIPS_CS_BASE
  10984. {"MIPS_CS_BASE", _MIPS_CS_BASE},
  10985. #endif
  10986. #ifdef _MIPS_CS_HOSTID
  10987. {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
  10988. #endif
  10989. #ifdef _MIPS_CS_HW_NAME
  10990. {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
  10991. #endif
  10992. #ifdef _MIPS_CS_NUM_PROCESSORS
  10993. {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
  10994. #endif
  10995. #ifdef _MIPS_CS_OSREL_MAJ
  10996. {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
  10997. #endif
  10998. #ifdef _MIPS_CS_OSREL_MIN
  10999. {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
  11000. #endif
  11001. #ifdef _MIPS_CS_OSREL_PATCH
  11002. {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
  11003. #endif
  11004. #ifdef _MIPS_CS_OS_NAME
  11005. {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
  11006. #endif
  11007. #ifdef _MIPS_CS_OS_PROVIDER
  11008. {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
  11009. #endif
  11010. #ifdef _MIPS_CS_PROCESSORS
  11011. {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
  11012. #endif
  11013. #ifdef _MIPS_CS_SERIAL
  11014. {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
  11015. #endif
  11016. #ifdef _MIPS_CS_VENDOR
  11017. {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
  11018. #endif
  11019. };
  11020. static int
  11021. conv_confstr_confname(PyObject *arg, int *valuep)
  11022. {
  11023. return conv_confname(arg, valuep, posix_constants_confstr,
  11024. sizeof(posix_constants_confstr)
  11025. / sizeof(struct constdef));
  11026. }
  11027. /*[clinic input]
  11028. os.confstr
  11029. name: confstr_confname
  11030. /
  11031. Return a string-valued system configuration variable.
  11032. [clinic start generated code]*/
  11033. static PyObject *
  11034. os_confstr_impl(PyObject *module, int name)
  11035. /*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
  11036. {
  11037. PyObject *result = NULL;
  11038. char buffer[255];
  11039. size_t len;
  11040. errno = 0;
  11041. len = confstr(name, buffer, sizeof(buffer));
  11042. if (len == 0) {
  11043. if (errno) {
  11044. posix_error();
  11045. return NULL;
  11046. }
  11047. else {
  11048. Py_RETURN_NONE;
  11049. }
  11050. }
  11051. if (len >= sizeof(buffer)) {
  11052. size_t len2;
  11053. char *buf = PyMem_Malloc(len);
  11054. if (buf == NULL)
  11055. return PyErr_NoMemory();
  11056. len2 = confstr(name, buf, len);
  11057. assert(len == len2);
  11058. result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
  11059. PyMem_Free(buf);
  11060. }
  11061. else
  11062. result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
  11063. return result;
  11064. }
  11065. #endif /* HAVE_CONFSTR */
  11066. #ifdef HAVE_SYSCONF
  11067. static struct constdef posix_constants_sysconf[] = {
  11068. #ifdef _SC_2_CHAR_TERM
  11069. {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
  11070. #endif
  11071. #ifdef _SC_2_C_BIND
  11072. {"SC_2_C_BIND", _SC_2_C_BIND},
  11073. #endif
  11074. #ifdef _SC_2_C_DEV
  11075. {"SC_2_C_DEV", _SC_2_C_DEV},
  11076. #endif
  11077. #ifdef _SC_2_C_VERSION
  11078. {"SC_2_C_VERSION", _SC_2_C_VERSION},
  11079. #endif
  11080. #ifdef _SC_2_FORT_DEV
  11081. {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
  11082. #endif
  11083. #ifdef _SC_2_FORT_RUN
  11084. {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
  11085. #endif
  11086. #ifdef _SC_2_LOCALEDEF
  11087. {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
  11088. #endif
  11089. #ifdef _SC_2_SW_DEV
  11090. {"SC_2_SW_DEV", _SC_2_SW_DEV},
  11091. #endif
  11092. #ifdef _SC_2_UPE
  11093. {"SC_2_UPE", _SC_2_UPE},
  11094. #endif
  11095. #ifdef _SC_2_VERSION
  11096. {"SC_2_VERSION", _SC_2_VERSION},
  11097. #endif
  11098. #ifdef _SC_ABI_ASYNCHRONOUS_IO
  11099. {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
  11100. #endif
  11101. #ifdef _SC_ACL
  11102. {"SC_ACL", _SC_ACL},
  11103. #endif
  11104. #ifdef _SC_AIO_LISTIO_MAX
  11105. {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
  11106. #endif
  11107. #ifdef _SC_AIO_MAX
  11108. {"SC_AIO_MAX", _SC_AIO_MAX},
  11109. #endif
  11110. #ifdef _SC_AIO_PRIO_DELTA_MAX
  11111. {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
  11112. #endif
  11113. #ifdef _SC_ARG_MAX
  11114. {"SC_ARG_MAX", _SC_ARG_MAX},
  11115. #endif
  11116. #ifdef _SC_ASYNCHRONOUS_IO
  11117. {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
  11118. #endif
  11119. #ifdef _SC_ATEXIT_MAX
  11120. {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
  11121. #endif
  11122. #ifdef _SC_AUDIT
  11123. {"SC_AUDIT", _SC_AUDIT},
  11124. #endif
  11125. #ifdef _SC_AVPHYS_PAGES
  11126. {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
  11127. #endif
  11128. #ifdef _SC_BC_BASE_MAX
  11129. {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
  11130. #endif
  11131. #ifdef _SC_BC_DIM_MAX
  11132. {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
  11133. #endif
  11134. #ifdef _SC_BC_SCALE_MAX
  11135. {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
  11136. #endif
  11137. #ifdef _SC_BC_STRING_MAX
  11138. {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
  11139. #endif
  11140. #ifdef _SC_CAP
  11141. {"SC_CAP", _SC_CAP},
  11142. #endif
  11143. #ifdef _SC_CHARCLASS_NAME_MAX
  11144. {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
  11145. #endif
  11146. #ifdef _SC_CHAR_BIT
  11147. {"SC_CHAR_BIT", _SC_CHAR_BIT},
  11148. #endif
  11149. #ifdef _SC_CHAR_MAX
  11150. {"SC_CHAR_MAX", _SC_CHAR_MAX},
  11151. #endif
  11152. #ifdef _SC_CHAR_MIN
  11153. {"SC_CHAR_MIN", _SC_CHAR_MIN},
  11154. #endif
  11155. #ifdef _SC_CHILD_MAX
  11156. {"SC_CHILD_MAX", _SC_CHILD_MAX},
  11157. #endif
  11158. #ifdef _SC_CLK_TCK
  11159. {"SC_CLK_TCK", _SC_CLK_TCK},
  11160. #endif
  11161. #ifdef _SC_COHER_BLKSZ
  11162. {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
  11163. #endif
  11164. #ifdef _SC_COLL_WEIGHTS_MAX
  11165. {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
  11166. #endif
  11167. #ifdef _SC_DCACHE_ASSOC
  11168. {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
  11169. #endif
  11170. #ifdef _SC_DCACHE_BLKSZ
  11171. {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
  11172. #endif
  11173. #ifdef _SC_DCACHE_LINESZ
  11174. {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
  11175. #endif
  11176. #ifdef _SC_DCACHE_SZ
  11177. {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
  11178. #endif
  11179. #ifdef _SC_DCACHE_TBLKSZ
  11180. {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
  11181. #endif
  11182. #ifdef _SC_DELAYTIMER_MAX
  11183. {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
  11184. #endif
  11185. #ifdef _SC_EQUIV_CLASS_MAX
  11186. {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
  11187. #endif
  11188. #ifdef _SC_EXPR_NEST_MAX
  11189. {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
  11190. #endif
  11191. #ifdef _SC_FSYNC
  11192. {"SC_FSYNC", _SC_FSYNC},
  11193. #endif
  11194. #ifdef _SC_GETGR_R_SIZE_MAX
  11195. {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
  11196. #endif
  11197. #ifdef _SC_GETPW_R_SIZE_MAX
  11198. {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
  11199. #endif
  11200. #ifdef _SC_ICACHE_ASSOC
  11201. {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
  11202. #endif
  11203. #ifdef _SC_ICACHE_BLKSZ
  11204. {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
  11205. #endif
  11206. #ifdef _SC_ICACHE_LINESZ
  11207. {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
  11208. #endif
  11209. #ifdef _SC_ICACHE_SZ
  11210. {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
  11211. #endif
  11212. #ifdef _SC_INF
  11213. {"SC_INF", _SC_INF},
  11214. #endif
  11215. #ifdef _SC_INT_MAX
  11216. {"SC_INT_MAX", _SC_INT_MAX},
  11217. #endif
  11218. #ifdef _SC_INT_MIN
  11219. {"SC_INT_MIN", _SC_INT_MIN},
  11220. #endif
  11221. #ifdef _SC_IOV_MAX
  11222. {"SC_IOV_MAX", _SC_IOV_MAX},
  11223. #endif
  11224. #ifdef _SC_IP_SECOPTS
  11225. {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
  11226. #endif
  11227. #ifdef _SC_JOB_CONTROL
  11228. {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
  11229. #endif
  11230. #ifdef _SC_KERN_POINTERS
  11231. {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
  11232. #endif
  11233. #ifdef _SC_KERN_SIM
  11234. {"SC_KERN_SIM", _SC_KERN_SIM},
  11235. #endif
  11236. #ifdef _SC_LINE_MAX
  11237. {"SC_LINE_MAX", _SC_LINE_MAX},
  11238. #endif
  11239. #ifdef _SC_LOGIN_NAME_MAX
  11240. {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
  11241. #endif
  11242. #ifdef _SC_LOGNAME_MAX
  11243. {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
  11244. #endif
  11245. #ifdef _SC_LONG_BIT
  11246. {"SC_LONG_BIT", _SC_LONG_BIT},
  11247. #endif
  11248. #ifdef _SC_MAC
  11249. {"SC_MAC", _SC_MAC},
  11250. #endif
  11251. #ifdef _SC_MAPPED_FILES
  11252. {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
  11253. #endif
  11254. #ifdef _SC_MAXPID
  11255. {"SC_MAXPID", _SC_MAXPID},
  11256. #endif
  11257. #ifdef _SC_MB_LEN_MAX
  11258. {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
  11259. #endif
  11260. #ifdef _SC_MEMLOCK
  11261. {"SC_MEMLOCK", _SC_MEMLOCK},
  11262. #endif
  11263. #ifdef _SC_MEMLOCK_RANGE
  11264. {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
  11265. #endif
  11266. #ifdef _SC_MEMORY_PROTECTION
  11267. {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
  11268. #endif
  11269. #ifdef _SC_MESSAGE_PASSING
  11270. {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
  11271. #endif
  11272. #ifdef _SC_MMAP_FIXED_ALIGNMENT
  11273. {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
  11274. #endif
  11275. #ifdef _SC_MQ_OPEN_MAX
  11276. {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
  11277. #endif
  11278. #ifdef _SC_MQ_PRIO_MAX
  11279. {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
  11280. #endif
  11281. #ifdef _SC_NACLS_MAX
  11282. {"SC_NACLS_MAX", _SC_NACLS_MAX},
  11283. #endif
  11284. #ifdef _SC_NGROUPS_MAX
  11285. {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
  11286. #endif
  11287. #ifdef _SC_NL_ARGMAX
  11288. {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
  11289. #endif
  11290. #ifdef _SC_NL_LANGMAX
  11291. {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
  11292. #endif
  11293. #ifdef _SC_NL_MSGMAX
  11294. {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
  11295. #endif
  11296. #ifdef _SC_NL_NMAX
  11297. {"SC_NL_NMAX", _SC_NL_NMAX},
  11298. #endif
  11299. #ifdef _SC_NL_SETMAX
  11300. {"SC_NL_SETMAX", _SC_NL_SETMAX},
  11301. #endif
  11302. #ifdef _SC_NL_TEXTMAX
  11303. {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
  11304. #endif
  11305. #ifdef _SC_NPROCESSORS_CONF
  11306. {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
  11307. #endif
  11308. #ifdef _SC_NPROCESSORS_ONLN
  11309. {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
  11310. #endif
  11311. #ifdef _SC_NPROC_CONF
  11312. {"SC_NPROC_CONF", _SC_NPROC_CONF},
  11313. #endif
  11314. #ifdef _SC_NPROC_ONLN
  11315. {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
  11316. #endif
  11317. #ifdef _SC_NZERO
  11318. {"SC_NZERO", _SC_NZERO},
  11319. #endif
  11320. #ifdef _SC_OPEN_MAX
  11321. {"SC_OPEN_MAX", _SC_OPEN_MAX},
  11322. #endif
  11323. #ifdef _SC_PAGESIZE
  11324. {"SC_PAGESIZE", _SC_PAGESIZE},
  11325. #endif
  11326. #ifdef _SC_PAGE_SIZE
  11327. {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
  11328. #endif
  11329. #ifdef _SC_AIX_REALMEM
  11330. {"SC_AIX_REALMEM", _SC_AIX_REALMEM},
  11331. #endif
  11332. #ifdef _SC_PASS_MAX
  11333. {"SC_PASS_MAX", _SC_PASS_MAX},
  11334. #endif
  11335. #ifdef _SC_PHYS_PAGES
  11336. {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
  11337. #endif
  11338. #ifdef _SC_PII
  11339. {"SC_PII", _SC_PII},
  11340. #endif
  11341. #ifdef _SC_PII_INTERNET
  11342. {"SC_PII_INTERNET", _SC_PII_INTERNET},
  11343. #endif
  11344. #ifdef _SC_PII_INTERNET_DGRAM
  11345. {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
  11346. #endif
  11347. #ifdef _SC_PII_INTERNET_STREAM
  11348. {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
  11349. #endif
  11350. #ifdef _SC_PII_OSI
  11351. {"SC_PII_OSI", _SC_PII_OSI},
  11352. #endif
  11353. #ifdef _SC_PII_OSI_CLTS
  11354. {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
  11355. #endif
  11356. #ifdef _SC_PII_OSI_COTS
  11357. {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
  11358. #endif
  11359. #ifdef _SC_PII_OSI_M
  11360. {"SC_PII_OSI_M", _SC_PII_OSI_M},
  11361. #endif
  11362. #ifdef _SC_PII_SOCKET
  11363. {"SC_PII_SOCKET", _SC_PII_SOCKET},
  11364. #endif
  11365. #ifdef _SC_PII_XTI
  11366. {"SC_PII_XTI", _SC_PII_XTI},
  11367. #endif
  11368. #ifdef _SC_POLL
  11369. {"SC_POLL", _SC_POLL},
  11370. #endif
  11371. #ifdef _SC_PRIORITIZED_IO
  11372. {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
  11373. #endif
  11374. #ifdef _SC_PRIORITY_SCHEDULING
  11375. {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
  11376. #endif
  11377. #ifdef _SC_REALTIME_SIGNALS
  11378. {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
  11379. #endif
  11380. #ifdef _SC_RE_DUP_MAX
  11381. {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
  11382. #endif
  11383. #ifdef _SC_RTSIG_MAX
  11384. {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
  11385. #endif
  11386. #ifdef _SC_SAVED_IDS
  11387. {"SC_SAVED_IDS", _SC_SAVED_IDS},
  11388. #endif
  11389. #ifdef _SC_SCHAR_MAX
  11390. {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
  11391. #endif
  11392. #ifdef _SC_SCHAR_MIN
  11393. {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
  11394. #endif
  11395. #ifdef _SC_SELECT
  11396. {"SC_SELECT", _SC_SELECT},
  11397. #endif
  11398. #ifdef _SC_SEMAPHORES
  11399. {"SC_SEMAPHORES", _SC_SEMAPHORES},
  11400. #endif
  11401. #ifdef _SC_SEM_NSEMS_MAX
  11402. {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
  11403. #endif
  11404. #ifdef _SC_SEM_VALUE_MAX
  11405. {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
  11406. #endif
  11407. #ifdef _SC_SHARED_MEMORY_OBJECTS
  11408. {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
  11409. #endif
  11410. #ifdef _SC_SHRT_MAX
  11411. {"SC_SHRT_MAX", _SC_SHRT_MAX},
  11412. #endif
  11413. #ifdef _SC_SHRT_MIN
  11414. {"SC_SHRT_MIN", _SC_SHRT_MIN},
  11415. #endif
  11416. #ifdef _SC_SIGQUEUE_MAX
  11417. {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
  11418. #endif
  11419. #ifdef _SC_SIGRT_MAX
  11420. {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
  11421. #endif
  11422. #ifdef _SC_SIGRT_MIN
  11423. {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
  11424. #endif
  11425. #ifdef _SC_SOFTPOWER
  11426. {"SC_SOFTPOWER", _SC_SOFTPOWER},
  11427. #endif
  11428. #ifdef _SC_SPLIT_CACHE
  11429. {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
  11430. #endif
  11431. #ifdef _SC_SSIZE_MAX
  11432. {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
  11433. #endif
  11434. #ifdef _SC_STACK_PROT
  11435. {"SC_STACK_PROT", _SC_STACK_PROT},
  11436. #endif
  11437. #ifdef _SC_STREAM_MAX
  11438. {"SC_STREAM_MAX", _SC_STREAM_MAX},
  11439. #endif
  11440. #ifdef _SC_SYNCHRONIZED_IO
  11441. {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
  11442. #endif
  11443. #ifdef _SC_THREADS
  11444. {"SC_THREADS", _SC_THREADS},
  11445. #endif
  11446. #ifdef _SC_THREAD_ATTR_STACKADDR
  11447. {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
  11448. #endif
  11449. #ifdef _SC_THREAD_ATTR_STACKSIZE
  11450. {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
  11451. #endif
  11452. #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
  11453. {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
  11454. #endif
  11455. #ifdef _SC_THREAD_KEYS_MAX
  11456. {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
  11457. #endif
  11458. #ifdef _SC_THREAD_PRIORITY_SCHEDULING
  11459. {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
  11460. #endif
  11461. #ifdef _SC_THREAD_PRIO_INHERIT
  11462. {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
  11463. #endif
  11464. #ifdef _SC_THREAD_PRIO_PROTECT
  11465. {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
  11466. #endif
  11467. #ifdef _SC_THREAD_PROCESS_SHARED
  11468. {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
  11469. #endif
  11470. #ifdef _SC_THREAD_SAFE_FUNCTIONS
  11471. {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
  11472. #endif
  11473. #ifdef _SC_THREAD_STACK_MIN
  11474. {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
  11475. #endif
  11476. #ifdef _SC_THREAD_THREADS_MAX
  11477. {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
  11478. #endif
  11479. #ifdef _SC_TIMERS
  11480. {"SC_TIMERS", _SC_TIMERS},
  11481. #endif
  11482. #ifdef _SC_TIMER_MAX
  11483. {"SC_TIMER_MAX", _SC_TIMER_MAX},
  11484. #endif
  11485. #ifdef _SC_TTY_NAME_MAX
  11486. {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
  11487. #endif
  11488. #ifdef _SC_TZNAME_MAX
  11489. {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
  11490. #endif
  11491. #ifdef _SC_T_IOV_MAX
  11492. {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
  11493. #endif
  11494. #ifdef _SC_UCHAR_MAX
  11495. {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
  11496. #endif
  11497. #ifdef _SC_UINT_MAX
  11498. {"SC_UINT_MAX", _SC_UINT_MAX},
  11499. #endif
  11500. #ifdef _SC_UIO_MAXIOV
  11501. {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
  11502. #endif
  11503. #ifdef _SC_ULONG_MAX
  11504. {"SC_ULONG_MAX", _SC_ULONG_MAX},
  11505. #endif
  11506. #ifdef _SC_USHRT_MAX
  11507. {"SC_USHRT_MAX", _SC_USHRT_MAX},
  11508. #endif
  11509. #ifdef _SC_VERSION
  11510. {"SC_VERSION", _SC_VERSION},
  11511. #endif
  11512. #ifdef _SC_WORD_BIT
  11513. {"SC_WORD_BIT", _SC_WORD_BIT},
  11514. #endif
  11515. #ifdef _SC_XBS5_ILP32_OFF32
  11516. {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
  11517. #endif
  11518. #ifdef _SC_XBS5_ILP32_OFFBIG
  11519. {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
  11520. #endif
  11521. #ifdef _SC_XBS5_LP64_OFF64
  11522. {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
  11523. #endif
  11524. #ifdef _SC_XBS5_LPBIG_OFFBIG
  11525. {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
  11526. #endif
  11527. #ifdef _SC_XOPEN_CRYPT
  11528. {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
  11529. #endif
  11530. #ifdef _SC_XOPEN_ENH_I18N
  11531. {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
  11532. #endif
  11533. #ifdef _SC_XOPEN_LEGACY
  11534. {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
  11535. #endif
  11536. #ifdef _SC_XOPEN_REALTIME
  11537. {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
  11538. #endif
  11539. #ifdef _SC_XOPEN_REALTIME_THREADS
  11540. {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
  11541. #endif
  11542. #ifdef _SC_XOPEN_SHM
  11543. {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
  11544. #endif
  11545. #ifdef _SC_XOPEN_UNIX
  11546. {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
  11547. #endif
  11548. #ifdef _SC_XOPEN_VERSION
  11549. {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
  11550. #endif
  11551. #ifdef _SC_XOPEN_XCU_VERSION
  11552. {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
  11553. #endif
  11554. #ifdef _SC_XOPEN_XPG2
  11555. {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
  11556. #endif
  11557. #ifdef _SC_XOPEN_XPG3
  11558. {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
  11559. #endif
  11560. #ifdef _SC_XOPEN_XPG4
  11561. {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
  11562. #endif
  11563. #ifdef _SC_MINSIGSTKSZ
  11564. {"SC_MINSIGSTKSZ", _SC_MINSIGSTKSZ},
  11565. #endif
  11566. };
  11567. static int
  11568. conv_sysconf_confname(PyObject *arg, int *valuep)
  11569. {
  11570. return conv_confname(arg, valuep, posix_constants_sysconf,
  11571. sizeof(posix_constants_sysconf)
  11572. / sizeof(struct constdef));
  11573. }
  11574. /*[clinic input]
  11575. os.sysconf -> long
  11576. name: sysconf_confname
  11577. /
  11578. Return an integer-valued system configuration variable.
  11579. [clinic start generated code]*/
  11580. static long
  11581. os_sysconf_impl(PyObject *module, int name)
  11582. /*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
  11583. {
  11584. long value;
  11585. errno = 0;
  11586. value = sysconf(name);
  11587. if (value == -1 && errno != 0)
  11588. posix_error();
  11589. return value;
  11590. }
  11591. #endif /* HAVE_SYSCONF */
  11592. /* This code is used to ensure that the tables of configuration value names
  11593. * are in sorted order as required by conv_confname(), and also to build
  11594. * the exported dictionaries that are used to publish information about the
  11595. * names available on the host platform.
  11596. *
  11597. * Sorting the table at runtime ensures that the table is properly ordered
  11598. * when used, even for platforms we're not able to test on. It also makes
  11599. * it easier to add additional entries to the tables.
  11600. */
  11601. static int
  11602. cmp_constdefs(const void *v1, const void *v2)
  11603. {
  11604. const struct constdef *c1 =
  11605. (const struct constdef *) v1;
  11606. const struct constdef *c2 =
  11607. (const struct constdef *) v2;
  11608. return strcmp(c1->name, c2->name);
  11609. }
  11610. static int
  11611. setup_confname_table(struct constdef *table, size_t tablesize,
  11612. const char *tablename, PyObject *module)
  11613. {
  11614. PyObject *d = NULL;
  11615. size_t i;
  11616. qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
  11617. d = PyDict_New();
  11618. if (d == NULL)
  11619. return -1;
  11620. for (i=0; i < tablesize; ++i) {
  11621. PyObject *o = PyLong_FromLong(table[i].value);
  11622. if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
  11623. Py_XDECREF(o);
  11624. Py_DECREF(d);
  11625. return -1;
  11626. }
  11627. Py_DECREF(o);
  11628. }
  11629. return _PyModule_Add(module, tablename, d);
  11630. }
  11631. /* Return -1 on failure, 0 on success. */
  11632. static int
  11633. setup_confname_tables(PyObject *module)
  11634. {
  11635. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  11636. if (setup_confname_table(posix_constants_pathconf,
  11637. sizeof(posix_constants_pathconf)
  11638. / sizeof(struct constdef),
  11639. "pathconf_names", module))
  11640. return -1;
  11641. #endif
  11642. #ifdef HAVE_CONFSTR
  11643. if (setup_confname_table(posix_constants_confstr,
  11644. sizeof(posix_constants_confstr)
  11645. / sizeof(struct constdef),
  11646. "confstr_names", module))
  11647. return -1;
  11648. #endif
  11649. #ifdef HAVE_SYSCONF
  11650. if (setup_confname_table(posix_constants_sysconf,
  11651. sizeof(posix_constants_sysconf)
  11652. / sizeof(struct constdef),
  11653. "sysconf_names", module))
  11654. return -1;
  11655. #endif
  11656. return 0;
  11657. }
  11658. /*[clinic input]
  11659. os.abort
  11660. Abort the interpreter immediately.
  11661. This function 'dumps core' or otherwise fails in the hardest way possible
  11662. on the hosting operating system. This function never returns.
  11663. [clinic start generated code]*/
  11664. static PyObject *
  11665. os_abort_impl(PyObject *module)
  11666. /*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
  11667. {
  11668. abort();
  11669. /*NOTREACHED*/
  11670. #ifndef __clang__
  11671. /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
  11672. GCC emits a warning without "return NULL;" (compiler bug?), but Clang
  11673. is smarter and emits a warning on the return. */
  11674. Py_FatalError("abort() called from Python code didn't abort!");
  11675. return NULL;
  11676. #endif
  11677. }
  11678. #ifdef MS_WINDOWS
  11679. /* Grab ShellExecute dynamically from shell32 */
  11680. static int has_ShellExecute = -1;
  11681. static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
  11682. LPCWSTR, INT);
  11683. static int
  11684. check_ShellExecute(void)
  11685. {
  11686. HINSTANCE hShell32;
  11687. /* only recheck */
  11688. if (-1 == has_ShellExecute) {
  11689. Py_BEGIN_ALLOW_THREADS
  11690. /* Security note: this call is not vulnerable to "DLL hijacking".
  11691. SHELL32 is part of "KnownDLLs" and so Windows always load
  11692. the system SHELL32.DLL, even if there is another SHELL32.DLL
  11693. in the DLL search path. */
  11694. hShell32 = LoadLibraryW(L"SHELL32");
  11695. if (hShell32) {
  11696. *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
  11697. "ShellExecuteW");
  11698. has_ShellExecute = Py_ShellExecuteW != NULL;
  11699. } else {
  11700. has_ShellExecute = 0;
  11701. }
  11702. Py_END_ALLOW_THREADS
  11703. }
  11704. return has_ShellExecute;
  11705. }
  11706. /*[clinic input]
  11707. os.startfile
  11708. filepath: path_t
  11709. operation: Py_UNICODE = NULL
  11710. arguments: Py_UNICODE = NULL
  11711. cwd: path_t(nullable=True) = None
  11712. show_cmd: int = 1
  11713. Start a file with its associated application.
  11714. When "operation" is not specified or "open", this acts like
  11715. double-clicking the file in Explorer, or giving the file name as an
  11716. argument to the DOS "start" command: the file is opened with whatever
  11717. application (if any) its extension is associated.
  11718. When another "operation" is given, it specifies what should be done with
  11719. the file. A typical operation is "print".
  11720. "arguments" is passed to the application, but should be omitted if the
  11721. file is a document.
  11722. "cwd" is the working directory for the operation. If "filepath" is
  11723. relative, it will be resolved against this directory. This argument
  11724. should usually be an absolute path.
  11725. "show_cmd" can be used to override the recommended visibility option.
  11726. See the Windows ShellExecute documentation for values.
  11727. startfile returns as soon as the associated application is launched.
  11728. There is no option to wait for the application to close, and no way
  11729. to retrieve the application's exit status.
  11730. The filepath is relative to the current directory. If you want to use
  11731. an absolute path, make sure the first character is not a slash ("/");
  11732. the underlying Win32 ShellExecute function doesn't work if it is.
  11733. [clinic start generated code]*/
  11734. static PyObject *
  11735. os_startfile_impl(PyObject *module, path_t *filepath,
  11736. const Py_UNICODE *operation, const Py_UNICODE *arguments,
  11737. path_t *cwd, int show_cmd)
  11738. /*[clinic end generated code: output=3baa4f9795841880 input=8248997b80669622]*/
  11739. {
  11740. HINSTANCE rc;
  11741. if(!check_ShellExecute()) {
  11742. /* If the OS doesn't have ShellExecute, return a
  11743. NotImplementedError. */
  11744. return PyErr_Format(PyExc_NotImplementedError,
  11745. "startfile not available on this platform");
  11746. }
  11747. if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
  11748. return NULL;
  11749. }
  11750. if (PySys_Audit("os.startfile/2", "OuuOi", filepath->object, operation,
  11751. arguments, cwd->object ? cwd->object : Py_None,
  11752. show_cmd) < 0) {
  11753. return NULL;
  11754. }
  11755. Py_BEGIN_ALLOW_THREADS
  11756. rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
  11757. arguments, cwd->wide, show_cmd);
  11758. Py_END_ALLOW_THREADS
  11759. if (rc <= (HINSTANCE)32) {
  11760. win32_error_object("startfile", filepath->object);
  11761. return NULL;
  11762. }
  11763. Py_RETURN_NONE;
  11764. }
  11765. #endif /* MS_WINDOWS */
  11766. #ifdef HAVE_GETLOADAVG
  11767. /*[clinic input]
  11768. os.getloadavg
  11769. Return average recent system load information.
  11770. Return the number of processes in the system run queue averaged over
  11771. the last 1, 5, and 15 minutes as a tuple of three floats.
  11772. Raises OSError if the load average was unobtainable.
  11773. [clinic start generated code]*/
  11774. static PyObject *
  11775. os_getloadavg_impl(PyObject *module)
  11776. /*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
  11777. {
  11778. double loadavg[3];
  11779. if (getloadavg(loadavg, 3)!=3) {
  11780. PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
  11781. return NULL;
  11782. } else
  11783. return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
  11784. }
  11785. #endif /* HAVE_GETLOADAVG */
  11786. /*[clinic input]
  11787. os.device_encoding
  11788. fd: int
  11789. Return a string describing the encoding of a terminal's file descriptor.
  11790. The file descriptor must be attached to a terminal.
  11791. If the device is not a terminal, return None.
  11792. [clinic start generated code]*/
  11793. static PyObject *
  11794. os_device_encoding_impl(PyObject *module, int fd)
  11795. /*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
  11796. {
  11797. return _Py_device_encoding(fd);
  11798. }
  11799. #ifdef HAVE_SETRESUID
  11800. /*[clinic input]
  11801. os.setresuid
  11802. ruid: uid_t
  11803. euid: uid_t
  11804. suid: uid_t
  11805. /
  11806. Set the current process's real, effective, and saved user ids.
  11807. [clinic start generated code]*/
  11808. static PyObject *
  11809. os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
  11810. /*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
  11811. {
  11812. if (setresuid(ruid, euid, suid) < 0)
  11813. return posix_error();
  11814. Py_RETURN_NONE;
  11815. }
  11816. #endif /* HAVE_SETRESUID */
  11817. #ifdef HAVE_SETRESGID
  11818. /*[clinic input]
  11819. os.setresgid
  11820. rgid: gid_t
  11821. egid: gid_t
  11822. sgid: gid_t
  11823. /
  11824. Set the current process's real, effective, and saved group ids.
  11825. [clinic start generated code]*/
  11826. static PyObject *
  11827. os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
  11828. /*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
  11829. {
  11830. if (setresgid(rgid, egid, sgid) < 0)
  11831. return posix_error();
  11832. Py_RETURN_NONE;
  11833. }
  11834. #endif /* HAVE_SETRESGID */
  11835. #ifdef HAVE_GETRESUID
  11836. /*[clinic input]
  11837. os.getresuid
  11838. Return a tuple of the current process's real, effective, and saved user ids.
  11839. [clinic start generated code]*/
  11840. static PyObject *
  11841. os_getresuid_impl(PyObject *module)
  11842. /*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
  11843. {
  11844. uid_t ruid, euid, suid;
  11845. if (getresuid(&ruid, &euid, &suid) < 0)
  11846. return posix_error();
  11847. return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
  11848. _PyLong_FromUid(euid),
  11849. _PyLong_FromUid(suid));
  11850. }
  11851. #endif /* HAVE_GETRESUID */
  11852. #ifdef HAVE_GETRESGID
  11853. /*[clinic input]
  11854. os.getresgid
  11855. Return a tuple of the current process's real, effective, and saved group ids.
  11856. [clinic start generated code]*/
  11857. static PyObject *
  11858. os_getresgid_impl(PyObject *module)
  11859. /*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
  11860. {
  11861. gid_t rgid, egid, sgid;
  11862. if (getresgid(&rgid, &egid, &sgid) < 0)
  11863. return posix_error();
  11864. return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
  11865. _PyLong_FromGid(egid),
  11866. _PyLong_FromGid(sgid));
  11867. }
  11868. #endif /* HAVE_GETRESGID */
  11869. #ifdef USE_XATTRS
  11870. /*[clinic input]
  11871. os.getxattr
  11872. path: path_t(allow_fd=True)
  11873. attribute: path_t
  11874. *
  11875. follow_symlinks: bool = True
  11876. Return the value of extended attribute attribute on path.
  11877. path may be either a string, a path-like object, or an open file descriptor.
  11878. If follow_symlinks is False, and the last element of the path is a symbolic
  11879. link, getxattr will examine the symbolic link itself instead of the file
  11880. the link points to.
  11881. [clinic start generated code]*/
  11882. static PyObject *
  11883. os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11884. int follow_symlinks)
  11885. /*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
  11886. {
  11887. Py_ssize_t i;
  11888. PyObject *buffer = NULL;
  11889. if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
  11890. return NULL;
  11891. if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
  11892. return NULL;
  11893. }
  11894. for (i = 0; ; i++) {
  11895. void *ptr;
  11896. ssize_t result;
  11897. static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
  11898. Py_ssize_t buffer_size = buffer_sizes[i];
  11899. if (!buffer_size) {
  11900. path_error(path);
  11901. return NULL;
  11902. }
  11903. buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
  11904. if (!buffer)
  11905. return NULL;
  11906. ptr = PyBytes_AS_STRING(buffer);
  11907. Py_BEGIN_ALLOW_THREADS;
  11908. if (path->fd >= 0)
  11909. result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
  11910. else if (follow_symlinks)
  11911. result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
  11912. else
  11913. result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
  11914. Py_END_ALLOW_THREADS;
  11915. if (result < 0) {
  11916. if (errno == ERANGE) {
  11917. Py_DECREF(buffer);
  11918. continue;
  11919. }
  11920. path_error(path);
  11921. Py_DECREF(buffer);
  11922. return NULL;
  11923. }
  11924. if (result != buffer_size) {
  11925. /* Can only shrink. */
  11926. _PyBytes_Resize(&buffer, result);
  11927. }
  11928. break;
  11929. }
  11930. return buffer;
  11931. }
  11932. /*[clinic input]
  11933. os.setxattr
  11934. path: path_t(allow_fd=True)
  11935. attribute: path_t
  11936. value: Py_buffer
  11937. flags: int = 0
  11938. *
  11939. follow_symlinks: bool = True
  11940. Set extended attribute attribute on path to value.
  11941. path may be either a string, a path-like object, or an open file descriptor.
  11942. If follow_symlinks is False, and the last element of the path is a symbolic
  11943. link, setxattr will modify the symbolic link itself instead of the file
  11944. the link points to.
  11945. [clinic start generated code]*/
  11946. static PyObject *
  11947. os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11948. Py_buffer *value, int flags, int follow_symlinks)
  11949. /*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
  11950. {
  11951. ssize_t result;
  11952. if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
  11953. return NULL;
  11954. if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
  11955. value->buf, value->len, flags) < 0) {
  11956. return NULL;
  11957. }
  11958. Py_BEGIN_ALLOW_THREADS;
  11959. if (path->fd > -1)
  11960. result = fsetxattr(path->fd, attribute->narrow,
  11961. value->buf, value->len, flags);
  11962. else if (follow_symlinks)
  11963. result = setxattr(path->narrow, attribute->narrow,
  11964. value->buf, value->len, flags);
  11965. else
  11966. result = lsetxattr(path->narrow, attribute->narrow,
  11967. value->buf, value->len, flags);
  11968. Py_END_ALLOW_THREADS;
  11969. if (result) {
  11970. path_error(path);
  11971. return NULL;
  11972. }
  11973. Py_RETURN_NONE;
  11974. }
  11975. /*[clinic input]
  11976. os.removexattr
  11977. path: path_t(allow_fd=True)
  11978. attribute: path_t
  11979. *
  11980. follow_symlinks: bool = True
  11981. Remove extended attribute attribute on path.
  11982. path may be either a string, a path-like object, or an open file descriptor.
  11983. If follow_symlinks is False, and the last element of the path is a symbolic
  11984. link, removexattr will modify the symbolic link itself instead of the file
  11985. the link points to.
  11986. [clinic start generated code]*/
  11987. static PyObject *
  11988. os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11989. int follow_symlinks)
  11990. /*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
  11991. {
  11992. ssize_t result;
  11993. if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
  11994. return NULL;
  11995. if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
  11996. return NULL;
  11997. }
  11998. Py_BEGIN_ALLOW_THREADS;
  11999. if (path->fd > -1)
  12000. result = fremovexattr(path->fd, attribute->narrow);
  12001. else if (follow_symlinks)
  12002. result = removexattr(path->narrow, attribute->narrow);
  12003. else
  12004. result = lremovexattr(path->narrow, attribute->narrow);
  12005. Py_END_ALLOW_THREADS;
  12006. if (result) {
  12007. return path_error(path);
  12008. }
  12009. Py_RETURN_NONE;
  12010. }
  12011. /*[clinic input]
  12012. os.listxattr
  12013. path: path_t(allow_fd=True, nullable=True) = None
  12014. *
  12015. follow_symlinks: bool = True
  12016. Return a list of extended attributes on path.
  12017. path may be either None, a string, a path-like object, or an open file descriptor.
  12018. if path is None, listxattr will examine the current directory.
  12019. If follow_symlinks is False, and the last element of the path is a symbolic
  12020. link, listxattr will examine the symbolic link itself instead of the file
  12021. the link points to.
  12022. [clinic start generated code]*/
  12023. static PyObject *
  12024. os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
  12025. /*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
  12026. {
  12027. Py_ssize_t i;
  12028. PyObject *result = NULL;
  12029. const char *name;
  12030. char *buffer = NULL;
  12031. if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
  12032. goto exit;
  12033. if (PySys_Audit("os.listxattr", "(O)",
  12034. path->object ? path->object : Py_None) < 0) {
  12035. return NULL;
  12036. }
  12037. name = path->narrow ? path->narrow : ".";
  12038. for (i = 0; ; i++) {
  12039. const char *start, *trace, *end;
  12040. ssize_t length;
  12041. static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
  12042. Py_ssize_t buffer_size = buffer_sizes[i];
  12043. if (!buffer_size) {
  12044. /* ERANGE */
  12045. path_error(path);
  12046. break;
  12047. }
  12048. buffer = PyMem_Malloc(buffer_size);
  12049. if (!buffer) {
  12050. PyErr_NoMemory();
  12051. break;
  12052. }
  12053. Py_BEGIN_ALLOW_THREADS;
  12054. if (path->fd > -1)
  12055. length = flistxattr(path->fd, buffer, buffer_size);
  12056. else if (follow_symlinks)
  12057. length = listxattr(name, buffer, buffer_size);
  12058. else
  12059. length = llistxattr(name, buffer, buffer_size);
  12060. Py_END_ALLOW_THREADS;
  12061. if (length < 0) {
  12062. if (errno == ERANGE) {
  12063. PyMem_Free(buffer);
  12064. buffer = NULL;
  12065. continue;
  12066. }
  12067. path_error(path);
  12068. break;
  12069. }
  12070. result = PyList_New(0);
  12071. if (!result) {
  12072. goto exit;
  12073. }
  12074. end = buffer + length;
  12075. for (trace = start = buffer; trace != end; trace++) {
  12076. if (!*trace) {
  12077. int error;
  12078. PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
  12079. trace - start);
  12080. if (!attribute) {
  12081. Py_SETREF(result, NULL);
  12082. goto exit;
  12083. }
  12084. error = PyList_Append(result, attribute);
  12085. Py_DECREF(attribute);
  12086. if (error) {
  12087. Py_SETREF(result, NULL);
  12088. goto exit;
  12089. }
  12090. start = trace + 1;
  12091. }
  12092. }
  12093. break;
  12094. }
  12095. exit:
  12096. if (buffer)
  12097. PyMem_Free(buffer);
  12098. return result;
  12099. }
  12100. #endif /* USE_XATTRS */
  12101. /*[clinic input]
  12102. os.urandom
  12103. size: Py_ssize_t
  12104. /
  12105. Return a bytes object containing random bytes suitable for cryptographic use.
  12106. [clinic start generated code]*/
  12107. static PyObject *
  12108. os_urandom_impl(PyObject *module, Py_ssize_t size)
  12109. /*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
  12110. {
  12111. PyObject *bytes;
  12112. int result;
  12113. if (size < 0)
  12114. return PyErr_Format(PyExc_ValueError,
  12115. "negative argument not allowed");
  12116. bytes = PyBytes_FromStringAndSize(NULL, size);
  12117. if (bytes == NULL)
  12118. return NULL;
  12119. result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
  12120. if (result == -1) {
  12121. Py_DECREF(bytes);
  12122. return NULL;
  12123. }
  12124. return bytes;
  12125. }
  12126. #ifdef HAVE_MEMFD_CREATE
  12127. /*[clinic input]
  12128. os.memfd_create
  12129. name: FSConverter
  12130. flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
  12131. [clinic start generated code]*/
  12132. static PyObject *
  12133. os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
  12134. /*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
  12135. {
  12136. int fd;
  12137. const char *bytes = PyBytes_AS_STRING(name);
  12138. Py_BEGIN_ALLOW_THREADS
  12139. fd = memfd_create(bytes, flags);
  12140. Py_END_ALLOW_THREADS
  12141. if (fd == -1) {
  12142. return PyErr_SetFromErrno(PyExc_OSError);
  12143. }
  12144. return PyLong_FromLong(fd);
  12145. }
  12146. #endif
  12147. #if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
  12148. /*[clinic input]
  12149. os.eventfd
  12150. initval: unsigned_int
  12151. flags: int(c_default="EFD_CLOEXEC") = EFD_CLOEXEC
  12152. Creates and returns an event notification file descriptor.
  12153. [clinic start generated code]*/
  12154. static PyObject *
  12155. os_eventfd_impl(PyObject *module, unsigned int initval, int flags)
  12156. /*[clinic end generated code: output=ce9c9bbd1446f2de input=66203e3c50c4028b]*/
  12157. {
  12158. /* initval is limited to uint32_t, internal counter is uint64_t */
  12159. int fd;
  12160. Py_BEGIN_ALLOW_THREADS
  12161. fd = eventfd(initval, flags);
  12162. Py_END_ALLOW_THREADS
  12163. if (fd == -1) {
  12164. return PyErr_SetFromErrno(PyExc_OSError);
  12165. }
  12166. return PyLong_FromLong(fd);
  12167. }
  12168. /*[clinic input]
  12169. os.eventfd_read
  12170. fd: fildes
  12171. Read eventfd value
  12172. [clinic start generated code]*/
  12173. static PyObject *
  12174. os_eventfd_read_impl(PyObject *module, int fd)
  12175. /*[clinic end generated code: output=8f2c7b59a3521fd1 input=110f8b57fa596afe]*/
  12176. {
  12177. eventfd_t value;
  12178. int result;
  12179. Py_BEGIN_ALLOW_THREADS
  12180. result = eventfd_read(fd, &value);
  12181. Py_END_ALLOW_THREADS
  12182. if (result == -1) {
  12183. return PyErr_SetFromErrno(PyExc_OSError);
  12184. }
  12185. return PyLong_FromUnsignedLongLong(value);
  12186. }
  12187. /*[clinic input]
  12188. os.eventfd_write
  12189. fd: fildes
  12190. value: unsigned_long_long
  12191. Write eventfd value.
  12192. [clinic start generated code]*/
  12193. static PyObject *
  12194. os_eventfd_write_impl(PyObject *module, int fd, unsigned long long value)
  12195. /*[clinic end generated code: output=bebd9040bbf987f5 input=156de8555be5a949]*/
  12196. {
  12197. int result;
  12198. Py_BEGIN_ALLOW_THREADS
  12199. result = eventfd_write(fd, value);
  12200. Py_END_ALLOW_THREADS
  12201. if (result == -1) {
  12202. return PyErr_SetFromErrno(PyExc_OSError);
  12203. }
  12204. Py_RETURN_NONE;
  12205. }
  12206. #endif /* HAVE_EVENTFD && EFD_CLOEXEC */
  12207. /* Terminal size querying */
  12208. PyDoc_STRVAR(TerminalSize_docstring,
  12209. "A tuple of (columns, lines) for holding terminal window size");
  12210. static PyStructSequence_Field TerminalSize_fields[] = {
  12211. {"columns", "width of the terminal window in characters"},
  12212. {"lines", "height of the terminal window in characters"},
  12213. {NULL, NULL}
  12214. };
  12215. static PyStructSequence_Desc TerminalSize_desc = {
  12216. "os.terminal_size",
  12217. TerminalSize_docstring,
  12218. TerminalSize_fields,
  12219. 2,
  12220. };
  12221. #if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
  12222. /*[clinic input]
  12223. os.get_terminal_size
  12224. fd: int(c_default="fileno(stdout)", py_default="<unrepresentable>") = -1
  12225. /
  12226. Return the size of the terminal window as (columns, lines).
  12227. The optional argument fd (default standard output) specifies
  12228. which file descriptor should be queried.
  12229. If the file descriptor is not connected to a terminal, an OSError
  12230. is thrown.
  12231. This function will only be defined if an implementation is
  12232. available for this system.
  12233. shutil.get_terminal_size is the high-level function which should
  12234. normally be used, os.get_terminal_size is the low-level implementation.
  12235. [clinic start generated code]*/
  12236. static PyObject *
  12237. os_get_terminal_size_impl(PyObject *module, int fd)
  12238. /*[clinic end generated code: output=fbab93acef980508 input=ead5679b82ddb920]*/
  12239. {
  12240. int columns, lines;
  12241. PyObject *termsize;
  12242. /* Under some conditions stdout may not be connected and
  12243. * fileno(stdout) may point to an invalid file descriptor. For example
  12244. * GUI apps don't have valid standard streams by default.
  12245. *
  12246. * If this happens, and the optional fd argument is not present,
  12247. * the ioctl below will fail returning EBADF. This is what we want.
  12248. */
  12249. #ifdef TERMSIZE_USE_IOCTL
  12250. {
  12251. struct winsize w;
  12252. if (ioctl(fd, TIOCGWINSZ, &w))
  12253. return PyErr_SetFromErrno(PyExc_OSError);
  12254. columns = w.ws_col;
  12255. lines = w.ws_row;
  12256. }
  12257. #endif /* TERMSIZE_USE_IOCTL */
  12258. #ifdef TERMSIZE_USE_CONIO
  12259. {
  12260. HANDLE handle;
  12261. CONSOLE_SCREEN_BUFFER_INFO csbi;
  12262. handle = _Py_get_osfhandle(fd);
  12263. if (handle == INVALID_HANDLE_VALUE)
  12264. return NULL;
  12265. if (!GetConsoleScreenBufferInfo(handle, &csbi))
  12266. return PyErr_SetFromWindowsErr(0);
  12267. columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
  12268. lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
  12269. }
  12270. #endif /* TERMSIZE_USE_CONIO */
  12271. PyObject *TerminalSizeType = get_posix_state(module)->TerminalSizeType;
  12272. termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
  12273. if (termsize == NULL)
  12274. return NULL;
  12275. int pos = 0;
  12276. #define SET_TERMSIZE(CALL) \
  12277. do { \
  12278. PyObject *item = (CALL); \
  12279. if (item == NULL) { \
  12280. Py_DECREF(termsize); \
  12281. return NULL; \
  12282. } \
  12283. PyStructSequence_SET_ITEM(termsize, pos++, item); \
  12284. } while(0)
  12285. SET_TERMSIZE(PyLong_FromLong(columns));
  12286. SET_TERMSIZE(PyLong_FromLong(lines));
  12287. #undef SET_TERMSIZE
  12288. return termsize;
  12289. }
  12290. #endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
  12291. /*[clinic input]
  12292. os.cpu_count
  12293. Return the number of CPUs in the system; return None if indeterminable.
  12294. This number is not equivalent to the number of CPUs the current process can
  12295. use. The number of usable CPUs can be obtained with
  12296. ``len(os.sched_getaffinity(0))``
  12297. [clinic start generated code]*/
  12298. static PyObject *
  12299. os_cpu_count_impl(PyObject *module)
  12300. /*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
  12301. {
  12302. int ncpu = 0;
  12303. #ifdef MS_WINDOWS
  12304. #ifdef MS_WINDOWS_DESKTOP
  12305. ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
  12306. #endif
  12307. #elif defined(__hpux)
  12308. ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
  12309. #elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
  12310. ncpu = sysconf(_SC_NPROCESSORS_ONLN);
  12311. #elif defined(__VXWORKS__)
  12312. ncpu = _Py_popcount32(vxCpuEnabledGet());
  12313. #elif defined(__DragonFly__) || \
  12314. defined(__OpenBSD__) || \
  12315. defined(__FreeBSD__) || \
  12316. defined(__NetBSD__) || \
  12317. defined(__APPLE__)
  12318. int mib[2];
  12319. size_t len = sizeof(ncpu);
  12320. mib[0] = CTL_HW;
  12321. mib[1] = HW_NCPU;
  12322. if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
  12323. ncpu = 0;
  12324. #endif
  12325. if (ncpu >= 1)
  12326. return PyLong_FromLong(ncpu);
  12327. else
  12328. Py_RETURN_NONE;
  12329. }
  12330. /*[clinic input]
  12331. os.get_inheritable -> bool
  12332. fd: int
  12333. /
  12334. Get the close-on-exe flag of the specified file descriptor.
  12335. [clinic start generated code]*/
  12336. static int
  12337. os_get_inheritable_impl(PyObject *module, int fd)
  12338. /*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
  12339. {
  12340. int return_value;
  12341. _Py_BEGIN_SUPPRESS_IPH
  12342. return_value = _Py_get_inheritable(fd);
  12343. _Py_END_SUPPRESS_IPH
  12344. return return_value;
  12345. }
  12346. /*[clinic input]
  12347. os.set_inheritable
  12348. fd: int
  12349. inheritable: int
  12350. /
  12351. Set the inheritable flag of the specified file descriptor.
  12352. [clinic start generated code]*/
  12353. static PyObject *
  12354. os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
  12355. /*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
  12356. {
  12357. int result;
  12358. _Py_BEGIN_SUPPRESS_IPH
  12359. result = _Py_set_inheritable(fd, inheritable, NULL);
  12360. _Py_END_SUPPRESS_IPH
  12361. if (result < 0)
  12362. return NULL;
  12363. Py_RETURN_NONE;
  12364. }
  12365. #ifdef MS_WINDOWS
  12366. #ifndef HANDLE_FLAG_INHERIT
  12367. #define HANDLE_FLAG_INHERIT 0x00000001
  12368. #endif
  12369. /*[clinic input]
  12370. os.get_handle_inheritable -> bool
  12371. handle: intptr_t
  12372. /
  12373. Get the close-on-exe flag of the specified file descriptor.
  12374. [clinic start generated code]*/
  12375. static int
  12376. os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
  12377. /*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
  12378. {
  12379. DWORD flags;
  12380. if (!GetHandleInformation((HANDLE)handle, &flags)) {
  12381. PyErr_SetFromWindowsErr(0);
  12382. return -1;
  12383. }
  12384. return flags & HANDLE_FLAG_INHERIT;
  12385. }
  12386. /*[clinic input]
  12387. os.set_handle_inheritable
  12388. handle: intptr_t
  12389. inheritable: bool
  12390. /
  12391. Set the inheritable flag of the specified handle.
  12392. [clinic start generated code]*/
  12393. static PyObject *
  12394. os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
  12395. int inheritable)
  12396. /*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
  12397. {
  12398. DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
  12399. if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
  12400. PyErr_SetFromWindowsErr(0);
  12401. return NULL;
  12402. }
  12403. Py_RETURN_NONE;
  12404. }
  12405. #endif /* MS_WINDOWS */
  12406. /*[clinic input]
  12407. os.get_blocking -> bool
  12408. fd: int
  12409. /
  12410. Get the blocking mode of the file descriptor.
  12411. Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
  12412. [clinic start generated code]*/
  12413. static int
  12414. os_get_blocking_impl(PyObject *module, int fd)
  12415. /*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
  12416. {
  12417. int blocking;
  12418. _Py_BEGIN_SUPPRESS_IPH
  12419. blocking = _Py_get_blocking(fd);
  12420. _Py_END_SUPPRESS_IPH
  12421. return blocking;
  12422. }
  12423. /*[clinic input]
  12424. os.set_blocking
  12425. fd: int
  12426. blocking: bool
  12427. /
  12428. Set the blocking mode of the specified file descriptor.
  12429. Set the O_NONBLOCK flag if blocking is False,
  12430. clear the O_NONBLOCK flag otherwise.
  12431. [clinic start generated code]*/
  12432. static PyObject *
  12433. os_set_blocking_impl(PyObject *module, int fd, int blocking)
  12434. /*[clinic end generated code: output=384eb43aa0762a9d input=7e9dfc9b14804dd4]*/
  12435. {
  12436. int result;
  12437. _Py_BEGIN_SUPPRESS_IPH
  12438. result = _Py_set_blocking(fd, blocking);
  12439. _Py_END_SUPPRESS_IPH
  12440. if (result < 0)
  12441. return NULL;
  12442. Py_RETURN_NONE;
  12443. }
  12444. /*[clinic input]
  12445. class os.DirEntry "DirEntry *" "DirEntryType"
  12446. [clinic start generated code]*/
  12447. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
  12448. typedef struct {
  12449. PyObject_HEAD
  12450. PyObject *name;
  12451. PyObject *path;
  12452. PyObject *stat;
  12453. PyObject *lstat;
  12454. #ifdef MS_WINDOWS
  12455. struct _Py_stat_struct win32_lstat;
  12456. uint64_t win32_file_index;
  12457. uint64_t win32_file_index_high;
  12458. int got_file_index;
  12459. #else /* POSIX */
  12460. #ifdef HAVE_DIRENT_D_TYPE
  12461. unsigned char d_type;
  12462. #endif
  12463. ino_t d_ino;
  12464. int dir_fd;
  12465. #endif
  12466. } DirEntry;
  12467. static void
  12468. DirEntry_dealloc(DirEntry *entry)
  12469. {
  12470. PyTypeObject *tp = Py_TYPE(entry);
  12471. Py_XDECREF(entry->name);
  12472. Py_XDECREF(entry->path);
  12473. Py_XDECREF(entry->stat);
  12474. Py_XDECREF(entry->lstat);
  12475. freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
  12476. free_func(entry);
  12477. Py_DECREF(tp);
  12478. }
  12479. /* Forward reference */
  12480. static int
  12481. DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
  12482. int follow_symlinks, unsigned short mode_bits);
  12483. /*[clinic input]
  12484. os.DirEntry.is_symlink -> bool
  12485. defining_class: defining_class
  12486. /
  12487. Return True if the entry is a symbolic link; cached per entry.
  12488. [clinic start generated code]*/
  12489. static int
  12490. os_DirEntry_is_symlink_impl(DirEntry *self, PyTypeObject *defining_class)
  12491. /*[clinic end generated code: output=293096d589b6d47c input=e9acc5ee4d511113]*/
  12492. {
  12493. #ifdef MS_WINDOWS
  12494. return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
  12495. #elif defined(HAVE_DIRENT_D_TYPE)
  12496. /* POSIX */
  12497. if (self->d_type != DT_UNKNOWN)
  12498. return self->d_type == DT_LNK;
  12499. else
  12500. return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
  12501. #else
  12502. /* POSIX without d_type */
  12503. return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
  12504. #endif
  12505. }
  12506. /*[clinic input]
  12507. os.DirEntry.is_junction -> bool
  12508. defining_class: defining_class
  12509. /
  12510. Return True if the entry is a junction; cached per entry.
  12511. [clinic start generated code]*/
  12512. static int
  12513. os_DirEntry_is_junction_impl(DirEntry *self, PyTypeObject *defining_class)
  12514. /*[clinic end generated code: output=7061a07b0ef2cd1f input=475cd36fb7d4723f]*/
  12515. {
  12516. #ifdef MS_WINDOWS
  12517. return self->win32_lstat.st_reparse_tag == IO_REPARSE_TAG_MOUNT_POINT;
  12518. #else
  12519. return 0;
  12520. #endif
  12521. }
  12522. static PyObject *
  12523. DirEntry_fetch_stat(PyObject *module, DirEntry *self, int follow_symlinks)
  12524. {
  12525. int result;
  12526. STRUCT_STAT st;
  12527. PyObject *ub;
  12528. #ifdef MS_WINDOWS
  12529. if (!PyUnicode_FSDecoder(self->path, &ub))
  12530. return NULL;
  12531. wchar_t *path = PyUnicode_AsWideCharString(ub, NULL);
  12532. Py_DECREF(ub);
  12533. #else /* POSIX */
  12534. if (!PyUnicode_FSConverter(self->path, &ub))
  12535. return NULL;
  12536. const char *path = PyBytes_AS_STRING(ub);
  12537. if (self->dir_fd != DEFAULT_DIR_FD) {
  12538. #ifdef HAVE_FSTATAT
  12539. if (HAVE_FSTATAT_RUNTIME) {
  12540. Py_BEGIN_ALLOW_THREADS
  12541. result = fstatat(self->dir_fd, path, &st,
  12542. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  12543. Py_END_ALLOW_THREADS
  12544. } else
  12545. #endif /* HAVE_FSTATAT */
  12546. {
  12547. Py_DECREF(ub);
  12548. PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
  12549. return NULL;
  12550. }
  12551. }
  12552. else
  12553. #endif
  12554. {
  12555. Py_BEGIN_ALLOW_THREADS
  12556. if (follow_symlinks) {
  12557. result = STAT(path, &st);
  12558. }
  12559. else {
  12560. result = LSTAT(path, &st);
  12561. }
  12562. Py_END_ALLOW_THREADS
  12563. }
  12564. int saved_errno = errno;
  12565. #if defined(MS_WINDOWS)
  12566. PyMem_Free(path);
  12567. #else
  12568. Py_DECREF(ub);
  12569. #endif
  12570. if (result != 0) {
  12571. errno = saved_errno;
  12572. path_object_error(self->path);
  12573. return NULL;
  12574. }
  12575. return _pystat_fromstructstat(module, &st);
  12576. }
  12577. static PyObject *
  12578. DirEntry_get_lstat(PyTypeObject *defining_class, DirEntry *self)
  12579. {
  12580. if (!self->lstat) {
  12581. PyObject *module = PyType_GetModule(defining_class);
  12582. #ifdef MS_WINDOWS
  12583. self->lstat = _pystat_fromstructstat(module, &self->win32_lstat);
  12584. #else /* POSIX */
  12585. self->lstat = DirEntry_fetch_stat(module, self, 0);
  12586. #endif
  12587. }
  12588. return Py_XNewRef(self->lstat);
  12589. }
  12590. /*[clinic input]
  12591. os.DirEntry.stat
  12592. defining_class: defining_class
  12593. /
  12594. *
  12595. follow_symlinks: bool = True
  12596. Return stat_result object for the entry; cached per entry.
  12597. [clinic start generated code]*/
  12598. static PyObject *
  12599. os_DirEntry_stat_impl(DirEntry *self, PyTypeObject *defining_class,
  12600. int follow_symlinks)
  12601. /*[clinic end generated code: output=23f803e19c3e780e input=e816273c4e67ee98]*/
  12602. {
  12603. if (!follow_symlinks) {
  12604. return DirEntry_get_lstat(defining_class, self);
  12605. }
  12606. if (!self->stat) {
  12607. int result = os_DirEntry_is_symlink_impl(self, defining_class);
  12608. if (result == -1) {
  12609. return NULL;
  12610. }
  12611. if (result) {
  12612. PyObject *module = PyType_GetModule(defining_class);
  12613. self->stat = DirEntry_fetch_stat(module, self, 1);
  12614. }
  12615. else {
  12616. self->stat = DirEntry_get_lstat(defining_class, self);
  12617. }
  12618. }
  12619. return Py_XNewRef(self->stat);
  12620. }
  12621. /* Set exception and return -1 on error, 0 for False, 1 for True */
  12622. static int
  12623. DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
  12624. int follow_symlinks, unsigned short mode_bits)
  12625. {
  12626. PyObject *stat = NULL;
  12627. PyObject *st_mode = NULL;
  12628. long mode;
  12629. int result;
  12630. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12631. int is_symlink;
  12632. int need_stat;
  12633. #endif
  12634. #ifdef MS_WINDOWS
  12635. unsigned long dir_bits;
  12636. #endif
  12637. #ifdef MS_WINDOWS
  12638. is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
  12639. need_stat = follow_symlinks && is_symlink;
  12640. #elif defined(HAVE_DIRENT_D_TYPE)
  12641. is_symlink = self->d_type == DT_LNK;
  12642. need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
  12643. #endif
  12644. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12645. if (need_stat) {
  12646. #endif
  12647. stat = os_DirEntry_stat_impl(self, defining_class, follow_symlinks);
  12648. if (!stat) {
  12649. if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
  12650. /* If file doesn't exist (anymore), then return False
  12651. (i.e., say it's not a file/directory) */
  12652. PyErr_Clear();
  12653. return 0;
  12654. }
  12655. goto error;
  12656. }
  12657. _posixstate* state = get_posix_state(PyType_GetModule(defining_class));
  12658. st_mode = PyObject_GetAttr(stat, state->st_mode);
  12659. if (!st_mode)
  12660. goto error;
  12661. mode = PyLong_AsLong(st_mode);
  12662. if (mode == -1 && PyErr_Occurred())
  12663. goto error;
  12664. Py_CLEAR(st_mode);
  12665. Py_CLEAR(stat);
  12666. result = (mode & S_IFMT) == mode_bits;
  12667. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12668. }
  12669. else if (is_symlink) {
  12670. assert(mode_bits != S_IFLNK);
  12671. result = 0;
  12672. }
  12673. else {
  12674. assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
  12675. #ifdef MS_WINDOWS
  12676. dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
  12677. if (mode_bits == S_IFDIR)
  12678. result = dir_bits != 0;
  12679. else
  12680. result = dir_bits == 0;
  12681. #else /* POSIX */
  12682. if (mode_bits == S_IFDIR)
  12683. result = self->d_type == DT_DIR;
  12684. else
  12685. result = self->d_type == DT_REG;
  12686. #endif
  12687. }
  12688. #endif
  12689. return result;
  12690. error:
  12691. Py_XDECREF(st_mode);
  12692. Py_XDECREF(stat);
  12693. return -1;
  12694. }
  12695. /*[clinic input]
  12696. os.DirEntry.is_dir -> bool
  12697. defining_class: defining_class
  12698. /
  12699. *
  12700. follow_symlinks: bool = True
  12701. Return True if the entry is a directory; cached per entry.
  12702. [clinic start generated code]*/
  12703. static int
  12704. os_DirEntry_is_dir_impl(DirEntry *self, PyTypeObject *defining_class,
  12705. int follow_symlinks)
  12706. /*[clinic end generated code: output=0cd453b9c0987fdf input=1a4ffd6dec9920cb]*/
  12707. {
  12708. return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFDIR);
  12709. }
  12710. /*[clinic input]
  12711. os.DirEntry.is_file -> bool
  12712. defining_class: defining_class
  12713. /
  12714. *
  12715. follow_symlinks: bool = True
  12716. Return True if the entry is a file; cached per entry.
  12717. [clinic start generated code]*/
  12718. static int
  12719. os_DirEntry_is_file_impl(DirEntry *self, PyTypeObject *defining_class,
  12720. int follow_symlinks)
  12721. /*[clinic end generated code: output=f7c277ab5ba80908 input=0a64c5a12e802e3b]*/
  12722. {
  12723. return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFREG);
  12724. }
  12725. /*[clinic input]
  12726. os.DirEntry.inode
  12727. Return inode of the entry; cached per entry.
  12728. [clinic start generated code]*/
  12729. static PyObject *
  12730. os_DirEntry_inode_impl(DirEntry *self)
  12731. /*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
  12732. {
  12733. #ifdef MS_WINDOWS
  12734. if (!self->got_file_index) {
  12735. PyObject *unicode;
  12736. STRUCT_STAT stat;
  12737. int result;
  12738. if (!PyUnicode_FSDecoder(self->path, &unicode))
  12739. return NULL;
  12740. wchar_t *path = PyUnicode_AsWideCharString(unicode, NULL);
  12741. Py_DECREF(unicode);
  12742. result = LSTAT(path, &stat);
  12743. int saved_errno = errno;
  12744. PyMem_Free(path);
  12745. if (result != 0) {
  12746. errno = saved_errno;
  12747. return path_object_error(self->path);
  12748. }
  12749. self->win32_file_index = stat.st_ino;
  12750. self->win32_file_index_high = stat.st_ino_high;
  12751. self->got_file_index = 1;
  12752. }
  12753. return _pystat_l128_from_l64_l64(self->win32_file_index, self->win32_file_index_high);
  12754. #else /* POSIX */
  12755. static_assert(sizeof(unsigned long long) >= sizeof(self->d_ino),
  12756. "DirEntry.d_ino is larger than unsigned long long");
  12757. return PyLong_FromUnsignedLongLong(self->d_ino);
  12758. #endif
  12759. }
  12760. static PyObject *
  12761. DirEntry_repr(DirEntry *self)
  12762. {
  12763. return PyUnicode_FromFormat("<DirEntry %R>", self->name);
  12764. }
  12765. /*[clinic input]
  12766. os.DirEntry.__fspath__
  12767. Returns the path for the entry.
  12768. [clinic start generated code]*/
  12769. static PyObject *
  12770. os_DirEntry___fspath___impl(DirEntry *self)
  12771. /*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
  12772. {
  12773. return Py_NewRef(self->path);
  12774. }
  12775. static PyMemberDef DirEntry_members[] = {
  12776. {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
  12777. "the entry's base filename, relative to scandir() \"path\" argument"},
  12778. {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
  12779. "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
  12780. {NULL}
  12781. };
  12782. #include "clinic/posixmodule.c.h"
  12783. static PyMethodDef DirEntry_methods[] = {
  12784. OS_DIRENTRY_IS_DIR_METHODDEF
  12785. OS_DIRENTRY_IS_FILE_METHODDEF
  12786. OS_DIRENTRY_IS_SYMLINK_METHODDEF
  12787. OS_DIRENTRY_IS_JUNCTION_METHODDEF
  12788. OS_DIRENTRY_STAT_METHODDEF
  12789. OS_DIRENTRY_INODE_METHODDEF
  12790. OS_DIRENTRY___FSPATH___METHODDEF
  12791. {"__class_getitem__", Py_GenericAlias,
  12792. METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  12793. {NULL}
  12794. };
  12795. static PyType_Slot DirEntryType_slots[] = {
  12796. {Py_tp_dealloc, DirEntry_dealloc},
  12797. {Py_tp_repr, DirEntry_repr},
  12798. {Py_tp_methods, DirEntry_methods},
  12799. {Py_tp_members, DirEntry_members},
  12800. {0, 0},
  12801. };
  12802. static PyType_Spec DirEntryType_spec = {
  12803. MODNAME ".DirEntry",
  12804. sizeof(DirEntry),
  12805. 0,
  12806. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
  12807. DirEntryType_slots
  12808. };
  12809. #ifdef MS_WINDOWS
  12810. static wchar_t *
  12811. join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
  12812. {
  12813. Py_ssize_t path_len;
  12814. Py_ssize_t size;
  12815. wchar_t *result;
  12816. wchar_t ch;
  12817. if (!path_wide) { /* Default arg: "." */
  12818. path_wide = L".";
  12819. path_len = 1;
  12820. }
  12821. else {
  12822. path_len = wcslen(path_wide);
  12823. }
  12824. /* The +1's are for the path separator and the NUL */
  12825. size = path_len + 1 + wcslen(filename) + 1;
  12826. result = PyMem_New(wchar_t, size);
  12827. if (!result) {
  12828. PyErr_NoMemory();
  12829. return NULL;
  12830. }
  12831. wcscpy(result, path_wide);
  12832. if (path_len > 0) {
  12833. ch = result[path_len - 1];
  12834. if (ch != SEP && ch != ALTSEP && ch != L':')
  12835. result[path_len++] = SEP;
  12836. wcscpy(result + path_len, filename);
  12837. }
  12838. return result;
  12839. }
  12840. static PyObject *
  12841. DirEntry_from_find_data(PyObject *module, path_t *path, WIN32_FIND_DATAW *dataW)
  12842. {
  12843. DirEntry *entry;
  12844. BY_HANDLE_FILE_INFORMATION file_info;
  12845. ULONG reparse_tag;
  12846. wchar_t *joined_path;
  12847. PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
  12848. entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
  12849. if (!entry)
  12850. return NULL;
  12851. entry->name = NULL;
  12852. entry->path = NULL;
  12853. entry->stat = NULL;
  12854. entry->lstat = NULL;
  12855. entry->got_file_index = 0;
  12856. entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
  12857. if (!entry->name)
  12858. goto error;
  12859. int return_bytes = path->wide && PyBytes_Check(path->object);
  12860. if (return_bytes) {
  12861. Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
  12862. if (!entry->name)
  12863. goto error;
  12864. }
  12865. joined_path = join_path_filenameW(path->wide, dataW->cFileName);
  12866. if (!joined_path)
  12867. goto error;
  12868. entry->path = PyUnicode_FromWideChar(joined_path, -1);
  12869. PyMem_Free(joined_path);
  12870. if (!entry->path)
  12871. goto error;
  12872. if (return_bytes) {
  12873. Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
  12874. if (!entry->path)
  12875. goto error;
  12876. }
  12877. find_data_to_file_info(dataW, &file_info, &reparse_tag);
  12878. _Py_attribute_data_to_stat(&file_info, reparse_tag, NULL, NULL, &entry->win32_lstat);
  12879. /* ctime is only deprecated from 3.12, so we copy birthtime across */
  12880. entry->win32_lstat.st_ctime = entry->win32_lstat.st_birthtime;
  12881. entry->win32_lstat.st_ctime_nsec = entry->win32_lstat.st_birthtime_nsec;
  12882. return (PyObject *)entry;
  12883. error:
  12884. Py_DECREF(entry);
  12885. return NULL;
  12886. }
  12887. #else /* POSIX */
  12888. static char *
  12889. join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
  12890. {
  12891. Py_ssize_t path_len;
  12892. Py_ssize_t size;
  12893. char *result;
  12894. if (!path_narrow) { /* Default arg: "." */
  12895. path_narrow = ".";
  12896. path_len = 1;
  12897. }
  12898. else {
  12899. path_len = strlen(path_narrow);
  12900. }
  12901. if (filename_len == -1)
  12902. filename_len = strlen(filename);
  12903. /* The +1's are for the path separator and the NUL */
  12904. size = path_len + 1 + filename_len + 1;
  12905. result = PyMem_New(char, size);
  12906. if (!result) {
  12907. PyErr_NoMemory();
  12908. return NULL;
  12909. }
  12910. strcpy(result, path_narrow);
  12911. if (path_len > 0 && result[path_len - 1] != '/')
  12912. result[path_len++] = '/';
  12913. strcpy(result + path_len, filename);
  12914. return result;
  12915. }
  12916. static PyObject *
  12917. DirEntry_from_posix_info(PyObject *module, path_t *path, const char *name,
  12918. Py_ssize_t name_len, ino_t d_ino
  12919. #ifdef HAVE_DIRENT_D_TYPE
  12920. , unsigned char d_type
  12921. #endif
  12922. )
  12923. {
  12924. DirEntry *entry;
  12925. char *joined_path;
  12926. PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
  12927. entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
  12928. if (!entry)
  12929. return NULL;
  12930. entry->name = NULL;
  12931. entry->path = NULL;
  12932. entry->stat = NULL;
  12933. entry->lstat = NULL;
  12934. if (path->fd != -1) {
  12935. entry->dir_fd = path->fd;
  12936. joined_path = NULL;
  12937. }
  12938. else {
  12939. entry->dir_fd = DEFAULT_DIR_FD;
  12940. joined_path = join_path_filename(path->narrow, name, name_len);
  12941. if (!joined_path)
  12942. goto error;
  12943. }
  12944. if (!path->narrow || !PyBytes_Check(path->object)) {
  12945. entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
  12946. if (joined_path)
  12947. entry->path = PyUnicode_DecodeFSDefault(joined_path);
  12948. }
  12949. else {
  12950. entry->name = PyBytes_FromStringAndSize(name, name_len);
  12951. if (joined_path)
  12952. entry->path = PyBytes_FromString(joined_path);
  12953. }
  12954. PyMem_Free(joined_path);
  12955. if (!entry->name)
  12956. goto error;
  12957. if (path->fd != -1) {
  12958. entry->path = Py_NewRef(entry->name);
  12959. }
  12960. else if (!entry->path)
  12961. goto error;
  12962. #ifdef HAVE_DIRENT_D_TYPE
  12963. entry->d_type = d_type;
  12964. #endif
  12965. entry->d_ino = d_ino;
  12966. return (PyObject *)entry;
  12967. error:
  12968. Py_XDECREF(entry);
  12969. return NULL;
  12970. }
  12971. #endif
  12972. typedef struct {
  12973. PyObject_HEAD
  12974. path_t path;
  12975. #ifdef MS_WINDOWS
  12976. HANDLE handle;
  12977. WIN32_FIND_DATAW file_data;
  12978. int first_time;
  12979. #else /* POSIX */
  12980. DIR *dirp;
  12981. #endif
  12982. #ifdef HAVE_FDOPENDIR
  12983. int fd;
  12984. #endif
  12985. } ScandirIterator;
  12986. #ifdef MS_WINDOWS
  12987. static int
  12988. ScandirIterator_is_closed(ScandirIterator *iterator)
  12989. {
  12990. return iterator->handle == INVALID_HANDLE_VALUE;
  12991. }
  12992. static void
  12993. ScandirIterator_closedir(ScandirIterator *iterator)
  12994. {
  12995. HANDLE handle = iterator->handle;
  12996. if (handle == INVALID_HANDLE_VALUE)
  12997. return;
  12998. iterator->handle = INVALID_HANDLE_VALUE;
  12999. Py_BEGIN_ALLOW_THREADS
  13000. FindClose(handle);
  13001. Py_END_ALLOW_THREADS
  13002. }
  13003. static PyObject *
  13004. ScandirIterator_iternext(ScandirIterator *iterator)
  13005. {
  13006. WIN32_FIND_DATAW *file_data = &iterator->file_data;
  13007. BOOL success;
  13008. PyObject *entry;
  13009. /* Happens if the iterator is iterated twice, or closed explicitly */
  13010. if (iterator->handle == INVALID_HANDLE_VALUE)
  13011. return NULL;
  13012. while (1) {
  13013. if (!iterator->first_time) {
  13014. Py_BEGIN_ALLOW_THREADS
  13015. success = FindNextFileW(iterator->handle, file_data);
  13016. Py_END_ALLOW_THREADS
  13017. if (!success) {
  13018. /* Error or no more files */
  13019. if (GetLastError() != ERROR_NO_MORE_FILES)
  13020. path_error(&iterator->path);
  13021. break;
  13022. }
  13023. }
  13024. iterator->first_time = 0;
  13025. /* Skip over . and .. */
  13026. if (wcscmp(file_data->cFileName, L".") != 0 &&
  13027. wcscmp(file_data->cFileName, L"..") != 0)
  13028. {
  13029. PyObject *module = PyType_GetModule(Py_TYPE(iterator));
  13030. entry = DirEntry_from_find_data(module, &iterator->path, file_data);
  13031. if (!entry)
  13032. break;
  13033. return entry;
  13034. }
  13035. /* Loop till we get a non-dot directory or finish iterating */
  13036. }
  13037. /* Error or no more files */
  13038. ScandirIterator_closedir(iterator);
  13039. return NULL;
  13040. }
  13041. #else /* POSIX */
  13042. static int
  13043. ScandirIterator_is_closed(ScandirIterator *iterator)
  13044. {
  13045. return !iterator->dirp;
  13046. }
  13047. static void
  13048. ScandirIterator_closedir(ScandirIterator *iterator)
  13049. {
  13050. DIR *dirp = iterator->dirp;
  13051. if (!dirp)
  13052. return;
  13053. iterator->dirp = NULL;
  13054. Py_BEGIN_ALLOW_THREADS
  13055. #ifdef HAVE_FDOPENDIR
  13056. if (iterator->path.fd != -1)
  13057. rewinddir(dirp);
  13058. #endif
  13059. closedir(dirp);
  13060. Py_END_ALLOW_THREADS
  13061. return;
  13062. }
  13063. static PyObject *
  13064. ScandirIterator_iternext(ScandirIterator *iterator)
  13065. {
  13066. struct dirent *direntp;
  13067. Py_ssize_t name_len;
  13068. int is_dot;
  13069. PyObject *entry;
  13070. /* Happens if the iterator is iterated twice, or closed explicitly */
  13071. if (!iterator->dirp)
  13072. return NULL;
  13073. while (1) {
  13074. errno = 0;
  13075. Py_BEGIN_ALLOW_THREADS
  13076. direntp = readdir(iterator->dirp);
  13077. Py_END_ALLOW_THREADS
  13078. if (!direntp) {
  13079. /* Error or no more files */
  13080. if (errno != 0)
  13081. path_error(&iterator->path);
  13082. break;
  13083. }
  13084. /* Skip over . and .. */
  13085. name_len = NAMLEN(direntp);
  13086. is_dot = direntp->d_name[0] == '.' &&
  13087. (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
  13088. if (!is_dot) {
  13089. PyObject *module = PyType_GetModule(Py_TYPE(iterator));
  13090. entry = DirEntry_from_posix_info(module,
  13091. &iterator->path, direntp->d_name,
  13092. name_len, direntp->d_ino
  13093. #ifdef HAVE_DIRENT_D_TYPE
  13094. , direntp->d_type
  13095. #endif
  13096. );
  13097. if (!entry)
  13098. break;
  13099. return entry;
  13100. }
  13101. /* Loop till we get a non-dot directory or finish iterating */
  13102. }
  13103. /* Error or no more files */
  13104. ScandirIterator_closedir(iterator);
  13105. return NULL;
  13106. }
  13107. #endif
  13108. static PyObject *
  13109. ScandirIterator_close(ScandirIterator *self, PyObject *args)
  13110. {
  13111. ScandirIterator_closedir(self);
  13112. Py_RETURN_NONE;
  13113. }
  13114. static PyObject *
  13115. ScandirIterator_enter(PyObject *self, PyObject *args)
  13116. {
  13117. return Py_NewRef(self);
  13118. }
  13119. static PyObject *
  13120. ScandirIterator_exit(ScandirIterator *self, PyObject *args)
  13121. {
  13122. ScandirIterator_closedir(self);
  13123. Py_RETURN_NONE;
  13124. }
  13125. static void
  13126. ScandirIterator_finalize(ScandirIterator *iterator)
  13127. {
  13128. /* Save the current exception, if any. */
  13129. PyObject *exc = PyErr_GetRaisedException();
  13130. if (!ScandirIterator_is_closed(iterator)) {
  13131. ScandirIterator_closedir(iterator);
  13132. if (PyErr_ResourceWarning((PyObject *)iterator, 1,
  13133. "unclosed scandir iterator %R", iterator)) {
  13134. /* Spurious errors can appear at shutdown */
  13135. if (PyErr_ExceptionMatches(PyExc_Warning)) {
  13136. PyErr_WriteUnraisable((PyObject *) iterator);
  13137. }
  13138. }
  13139. }
  13140. path_cleanup(&iterator->path);
  13141. /* Restore the saved exception. */
  13142. PyErr_SetRaisedException(exc);
  13143. }
  13144. static void
  13145. ScandirIterator_dealloc(ScandirIterator *iterator)
  13146. {
  13147. PyTypeObject *tp = Py_TYPE(iterator);
  13148. if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
  13149. return;
  13150. freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
  13151. free_func(iterator);
  13152. Py_DECREF(tp);
  13153. }
  13154. static PyMethodDef ScandirIterator_methods[] = {
  13155. {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
  13156. {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
  13157. {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
  13158. {NULL}
  13159. };
  13160. static PyType_Slot ScandirIteratorType_slots[] = {
  13161. {Py_tp_dealloc, ScandirIterator_dealloc},
  13162. {Py_tp_finalize, ScandirIterator_finalize},
  13163. {Py_tp_iter, PyObject_SelfIter},
  13164. {Py_tp_iternext, ScandirIterator_iternext},
  13165. {Py_tp_methods, ScandirIterator_methods},
  13166. {0, 0},
  13167. };
  13168. static PyType_Spec ScandirIteratorType_spec = {
  13169. MODNAME ".ScandirIterator",
  13170. sizeof(ScandirIterator),
  13171. 0,
  13172. // bpo-40549: Py_TPFLAGS_BASETYPE should not be used, since
  13173. // PyType_GetModule(Py_TYPE(self)) doesn't work on a subclass instance.
  13174. (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE
  13175. | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  13176. ScandirIteratorType_slots
  13177. };
  13178. /*[clinic input]
  13179. os.scandir
  13180. path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
  13181. Return an iterator of DirEntry objects for given path.
  13182. path can be specified as either str, bytes, or a path-like object. If path
  13183. is bytes, the names of yielded DirEntry objects will also be bytes; in
  13184. all other circumstances they will be str.
  13185. If path is None, uses the path='.'.
  13186. [clinic start generated code]*/
  13187. static PyObject *
  13188. os_scandir_impl(PyObject *module, path_t *path)
  13189. /*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
  13190. {
  13191. ScandirIterator *iterator;
  13192. #ifdef MS_WINDOWS
  13193. wchar_t *path_strW;
  13194. #else
  13195. const char *path_str;
  13196. #ifdef HAVE_FDOPENDIR
  13197. int fd = -1;
  13198. #endif
  13199. #endif
  13200. if (PySys_Audit("os.scandir", "O",
  13201. path->object ? path->object : Py_None) < 0) {
  13202. return NULL;
  13203. }
  13204. PyObject *ScandirIteratorType = get_posix_state(module)->ScandirIteratorType;
  13205. iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
  13206. if (!iterator)
  13207. return NULL;
  13208. #ifdef MS_WINDOWS
  13209. iterator->handle = INVALID_HANDLE_VALUE;
  13210. #else
  13211. iterator->dirp = NULL;
  13212. #endif
  13213. /* Move the ownership to iterator->path */
  13214. memcpy(&iterator->path, path, sizeof(path_t));
  13215. memset(path, 0, sizeof(path_t));
  13216. #ifdef MS_WINDOWS
  13217. iterator->first_time = 1;
  13218. path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
  13219. if (!path_strW)
  13220. goto error;
  13221. Py_BEGIN_ALLOW_THREADS
  13222. iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
  13223. Py_END_ALLOW_THREADS
  13224. if (iterator->handle == INVALID_HANDLE_VALUE) {
  13225. path_error(&iterator->path);
  13226. PyMem_Free(path_strW);
  13227. goto error;
  13228. }
  13229. PyMem_Free(path_strW);
  13230. #else /* POSIX */
  13231. errno = 0;
  13232. #ifdef HAVE_FDOPENDIR
  13233. if (iterator->path.fd != -1) {
  13234. if (HAVE_FDOPENDIR_RUNTIME) {
  13235. /* closedir() closes the FD, so we duplicate it */
  13236. fd = _Py_dup(iterator->path.fd);
  13237. if (fd == -1)
  13238. goto error;
  13239. Py_BEGIN_ALLOW_THREADS
  13240. iterator->dirp = fdopendir(fd);
  13241. Py_END_ALLOW_THREADS
  13242. } else {
  13243. PyErr_SetString(PyExc_TypeError,
  13244. "scandir: path should be string, bytes, os.PathLike or None, not int");
  13245. return NULL;
  13246. }
  13247. }
  13248. else
  13249. #endif
  13250. {
  13251. if (iterator->path.narrow)
  13252. path_str = iterator->path.narrow;
  13253. else
  13254. path_str = ".";
  13255. Py_BEGIN_ALLOW_THREADS
  13256. iterator->dirp = opendir(path_str);
  13257. Py_END_ALLOW_THREADS
  13258. }
  13259. if (!iterator->dirp) {
  13260. path_error(&iterator->path);
  13261. #ifdef HAVE_FDOPENDIR
  13262. if (fd != -1) {
  13263. Py_BEGIN_ALLOW_THREADS
  13264. close(fd);
  13265. Py_END_ALLOW_THREADS
  13266. }
  13267. #endif
  13268. goto error;
  13269. }
  13270. #endif
  13271. return (PyObject *)iterator;
  13272. error:
  13273. Py_DECREF(iterator);
  13274. return NULL;
  13275. }
  13276. /*
  13277. Return the file system path representation of the object.
  13278. If the object is str or bytes, then allow it to pass through with
  13279. an incremented refcount. If the object defines __fspath__(), then
  13280. return the result of that method. All other types raise a TypeError.
  13281. */
  13282. PyObject *
  13283. PyOS_FSPath(PyObject *path)
  13284. {
  13285. /* For error message reasons, this function is manually inlined in
  13286. path_converter(). */
  13287. PyObject *func = NULL;
  13288. PyObject *path_repr = NULL;
  13289. if (PyUnicode_Check(path) || PyBytes_Check(path)) {
  13290. return Py_NewRef(path);
  13291. }
  13292. func = _PyObject_LookupSpecial(path, &_Py_ID(__fspath__));
  13293. if (NULL == func) {
  13294. return PyErr_Format(PyExc_TypeError,
  13295. "expected str, bytes or os.PathLike object, "
  13296. "not %.200s",
  13297. _PyType_Name(Py_TYPE(path)));
  13298. }
  13299. path_repr = _PyObject_CallNoArgs(func);
  13300. Py_DECREF(func);
  13301. if (NULL == path_repr) {
  13302. return NULL;
  13303. }
  13304. if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
  13305. PyErr_Format(PyExc_TypeError,
  13306. "expected %.200s.__fspath__() to return str or bytes, "
  13307. "not %.200s", _PyType_Name(Py_TYPE(path)),
  13308. _PyType_Name(Py_TYPE(path_repr)));
  13309. Py_DECREF(path_repr);
  13310. return NULL;
  13311. }
  13312. return path_repr;
  13313. }
  13314. /*[clinic input]
  13315. os.fspath
  13316. path: object
  13317. Return the file system path representation of the object.
  13318. If the object is str or bytes, then allow it to pass through as-is. If the
  13319. object defines __fspath__(), then return the result of that method. All other
  13320. types raise a TypeError.
  13321. [clinic start generated code]*/
  13322. static PyObject *
  13323. os_fspath_impl(PyObject *module, PyObject *path)
  13324. /*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
  13325. {
  13326. return PyOS_FSPath(path);
  13327. }
  13328. #ifdef HAVE_GETRANDOM_SYSCALL
  13329. /*[clinic input]
  13330. os.getrandom
  13331. size: Py_ssize_t
  13332. flags: int=0
  13333. Obtain a series of random bytes.
  13334. [clinic start generated code]*/
  13335. static PyObject *
  13336. os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
  13337. /*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
  13338. {
  13339. PyObject *bytes;
  13340. Py_ssize_t n;
  13341. if (size < 0) {
  13342. errno = EINVAL;
  13343. return posix_error();
  13344. }
  13345. bytes = PyBytes_FromStringAndSize(NULL, size);
  13346. if (bytes == NULL) {
  13347. PyErr_NoMemory();
  13348. return NULL;
  13349. }
  13350. while (1) {
  13351. n = syscall(SYS_getrandom,
  13352. PyBytes_AS_STRING(bytes),
  13353. PyBytes_GET_SIZE(bytes),
  13354. flags);
  13355. if (n < 0 && errno == EINTR) {
  13356. if (PyErr_CheckSignals() < 0) {
  13357. goto error;
  13358. }
  13359. /* getrandom() was interrupted by a signal: retry */
  13360. continue;
  13361. }
  13362. break;
  13363. }
  13364. if (n < 0) {
  13365. PyErr_SetFromErrno(PyExc_OSError);
  13366. goto error;
  13367. }
  13368. if (n != size) {
  13369. _PyBytes_Resize(&bytes, n);
  13370. }
  13371. return bytes;
  13372. error:
  13373. Py_DECREF(bytes);
  13374. return NULL;
  13375. }
  13376. #endif /* HAVE_GETRANDOM_SYSCALL */
  13377. #if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
  13378. /* bpo-36085: Helper functions for managing DLL search directories
  13379. * on win32
  13380. */
  13381. /*[clinic input]
  13382. os._add_dll_directory
  13383. path: path_t
  13384. Add a path to the DLL search path.
  13385. This search path is used when resolving dependencies for imported
  13386. extension modules (the module itself is resolved through sys.path),
  13387. and also by ctypes.
  13388. Returns an opaque value that may be passed to os.remove_dll_directory
  13389. to remove this directory from the search path.
  13390. [clinic start generated code]*/
  13391. static PyObject *
  13392. os__add_dll_directory_impl(PyObject *module, path_t *path)
  13393. /*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
  13394. {
  13395. DLL_DIRECTORY_COOKIE cookie = 0;
  13396. DWORD err = 0;
  13397. if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
  13398. return NULL;
  13399. }
  13400. Py_BEGIN_ALLOW_THREADS
  13401. if (!(cookie = AddDllDirectory(path->wide))) {
  13402. err = GetLastError();
  13403. }
  13404. Py_END_ALLOW_THREADS
  13405. if (err) {
  13406. return win32_error_object_err("add_dll_directory",
  13407. path->object, err);
  13408. }
  13409. return PyCapsule_New(cookie, "DLL directory cookie", NULL);
  13410. }
  13411. /*[clinic input]
  13412. os._remove_dll_directory
  13413. cookie: object
  13414. Removes a path from the DLL search path.
  13415. The parameter is an opaque value that was returned from
  13416. os.add_dll_directory. You can only remove directories that you added
  13417. yourself.
  13418. [clinic start generated code]*/
  13419. static PyObject *
  13420. os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
  13421. /*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
  13422. {
  13423. DLL_DIRECTORY_COOKIE cookieValue;
  13424. DWORD err = 0;
  13425. if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
  13426. PyErr_SetString(PyExc_TypeError,
  13427. "Provided cookie was not returned from os.add_dll_directory");
  13428. return NULL;
  13429. }
  13430. cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
  13431. cookie, "DLL directory cookie");
  13432. Py_BEGIN_ALLOW_THREADS
  13433. if (!RemoveDllDirectory(cookieValue)) {
  13434. err = GetLastError();
  13435. }
  13436. Py_END_ALLOW_THREADS
  13437. if (err) {
  13438. return win32_error_object_err("remove_dll_directory",
  13439. NULL, err);
  13440. }
  13441. if (PyCapsule_SetName(cookie, NULL)) {
  13442. return NULL;
  13443. }
  13444. Py_RETURN_NONE;
  13445. }
  13446. #endif /* MS_WINDOWS_APP || MS_WINDOWS_SYSTEM */
  13447. /* Only check if WIFEXITED is available: expect that it comes
  13448. with WEXITSTATUS, WIFSIGNALED, etc.
  13449. os.waitstatus_to_exitcode() is implemented in C and not in Python, so
  13450. subprocess can safely call it during late Python finalization without
  13451. risking that used os attributes were set to None by finalize_modules(). */
  13452. #if defined(WIFEXITED) || defined(MS_WINDOWS)
  13453. /*[clinic input]
  13454. os.waitstatus_to_exitcode
  13455. status as status_obj: object
  13456. Convert a wait status to an exit code.
  13457. On Unix:
  13458. * If WIFEXITED(status) is true, return WEXITSTATUS(status).
  13459. * If WIFSIGNALED(status) is true, return -WTERMSIG(status).
  13460. * Otherwise, raise a ValueError.
  13461. On Windows, return status shifted right by 8 bits.
  13462. On Unix, if the process is being traced or if waitpid() was called with
  13463. WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true.
  13464. This function must not be called if WIFSTOPPED(status) is true.
  13465. [clinic start generated code]*/
  13466. static PyObject *
  13467. os_waitstatus_to_exitcode_impl(PyObject *module, PyObject *status_obj)
  13468. /*[clinic end generated code: output=db50b1b0ba3c7153 input=7fe2d7fdaea3db42]*/
  13469. {
  13470. #ifndef MS_WINDOWS
  13471. int status = _PyLong_AsInt(status_obj);
  13472. if (status == -1 && PyErr_Occurred()) {
  13473. return NULL;
  13474. }
  13475. WAIT_TYPE wait_status;
  13476. WAIT_STATUS_INT(wait_status) = status;
  13477. int exitcode;
  13478. if (WIFEXITED(wait_status)) {
  13479. exitcode = WEXITSTATUS(wait_status);
  13480. /* Sanity check to provide warranty on the function behavior.
  13481. It should not occur in practice */
  13482. if (exitcode < 0) {
  13483. PyErr_Format(PyExc_ValueError, "invalid WEXITSTATUS: %i", exitcode);
  13484. return NULL;
  13485. }
  13486. }
  13487. else if (WIFSIGNALED(wait_status)) {
  13488. int signum = WTERMSIG(wait_status);
  13489. /* Sanity check to provide warranty on the function behavior.
  13490. It should not occurs in practice */
  13491. if (signum <= 0) {
  13492. PyErr_Format(PyExc_ValueError, "invalid WTERMSIG: %i", signum);
  13493. return NULL;
  13494. }
  13495. exitcode = -signum;
  13496. } else if (WIFSTOPPED(wait_status)) {
  13497. /* Status only received if the process is being traced
  13498. or if waitpid() was called with WUNTRACED option. */
  13499. int signum = WSTOPSIG(wait_status);
  13500. PyErr_Format(PyExc_ValueError,
  13501. "process stopped by delivery of signal %i",
  13502. signum);
  13503. return NULL;
  13504. }
  13505. else {
  13506. PyErr_Format(PyExc_ValueError, "invalid wait status: %i", status);
  13507. return NULL;
  13508. }
  13509. return PyLong_FromLong(exitcode);
  13510. #else
  13511. /* Windows implementation: see os.waitpid() implementation
  13512. which uses _cwait(). */
  13513. unsigned long long status = PyLong_AsUnsignedLongLong(status_obj);
  13514. if (status == (unsigned long long)-1 && PyErr_Occurred()) {
  13515. return NULL;
  13516. }
  13517. unsigned long long exitcode = (status >> 8);
  13518. /* ExitProcess() accepts an UINT type:
  13519. reject exit code which doesn't fit in an UINT */
  13520. if (exitcode > UINT_MAX) {
  13521. PyErr_Format(PyExc_ValueError, "invalid exit code: %llu", exitcode);
  13522. return NULL;
  13523. }
  13524. return PyLong_FromUnsignedLong((unsigned long)exitcode);
  13525. #endif
  13526. }
  13527. #endif
  13528. static PyMethodDef posix_methods[] = {
  13529. OS_STAT_METHODDEF
  13530. OS_ACCESS_METHODDEF
  13531. OS_TTYNAME_METHODDEF
  13532. OS_CHDIR_METHODDEF
  13533. OS_CHFLAGS_METHODDEF
  13534. OS_CHMOD_METHODDEF
  13535. OS_FCHMOD_METHODDEF
  13536. OS_LCHMOD_METHODDEF
  13537. OS_CHOWN_METHODDEF
  13538. OS_FCHOWN_METHODDEF
  13539. OS_LCHOWN_METHODDEF
  13540. OS_LCHFLAGS_METHODDEF
  13541. OS_CHROOT_METHODDEF
  13542. OS_CTERMID_METHODDEF
  13543. OS_GETCWD_METHODDEF
  13544. OS_GETCWDB_METHODDEF
  13545. OS_LINK_METHODDEF
  13546. OS_LISTDIR_METHODDEF
  13547. OS_LISTDRIVES_METHODDEF
  13548. OS_LISTMOUNTS_METHODDEF
  13549. OS_LISTVOLUMES_METHODDEF
  13550. OS_LSTAT_METHODDEF
  13551. OS_MKDIR_METHODDEF
  13552. OS_NICE_METHODDEF
  13553. OS_GETPRIORITY_METHODDEF
  13554. OS_SETPRIORITY_METHODDEF
  13555. OS_POSIX_SPAWN_METHODDEF
  13556. OS_POSIX_SPAWNP_METHODDEF
  13557. OS_READLINK_METHODDEF
  13558. OS_COPY_FILE_RANGE_METHODDEF
  13559. OS_SPLICE_METHODDEF
  13560. OS_RENAME_METHODDEF
  13561. OS_REPLACE_METHODDEF
  13562. OS_RMDIR_METHODDEF
  13563. OS_SYMLINK_METHODDEF
  13564. OS_SYSTEM_METHODDEF
  13565. OS_UMASK_METHODDEF
  13566. OS_UNAME_METHODDEF
  13567. OS_UNLINK_METHODDEF
  13568. OS_REMOVE_METHODDEF
  13569. OS_UTIME_METHODDEF
  13570. OS_TIMES_METHODDEF
  13571. OS__EXIT_METHODDEF
  13572. OS__FCOPYFILE_METHODDEF
  13573. OS_EXECV_METHODDEF
  13574. OS_EXECVE_METHODDEF
  13575. OS_SPAWNV_METHODDEF
  13576. OS_SPAWNVE_METHODDEF
  13577. OS_FORK1_METHODDEF
  13578. OS_FORK_METHODDEF
  13579. OS_REGISTER_AT_FORK_METHODDEF
  13580. OS_SCHED_GET_PRIORITY_MAX_METHODDEF
  13581. OS_SCHED_GET_PRIORITY_MIN_METHODDEF
  13582. OS_SCHED_GETPARAM_METHODDEF
  13583. OS_SCHED_GETSCHEDULER_METHODDEF
  13584. OS_SCHED_RR_GET_INTERVAL_METHODDEF
  13585. OS_SCHED_SETPARAM_METHODDEF
  13586. OS_SCHED_SETSCHEDULER_METHODDEF
  13587. OS_SCHED_YIELD_METHODDEF
  13588. OS_SCHED_SETAFFINITY_METHODDEF
  13589. OS_SCHED_GETAFFINITY_METHODDEF
  13590. OS_OPENPTY_METHODDEF
  13591. OS_LOGIN_TTY_METHODDEF
  13592. OS_FORKPTY_METHODDEF
  13593. OS_GETEGID_METHODDEF
  13594. OS_GETEUID_METHODDEF
  13595. OS_GETGID_METHODDEF
  13596. OS_GETGROUPLIST_METHODDEF
  13597. OS_GETGROUPS_METHODDEF
  13598. OS_GETPID_METHODDEF
  13599. OS_GETPGRP_METHODDEF
  13600. OS_GETPPID_METHODDEF
  13601. OS_GETUID_METHODDEF
  13602. OS_GETLOGIN_METHODDEF
  13603. OS_KILL_METHODDEF
  13604. OS_KILLPG_METHODDEF
  13605. OS_PLOCK_METHODDEF
  13606. OS_STARTFILE_METHODDEF
  13607. OS_SETUID_METHODDEF
  13608. OS_SETEUID_METHODDEF
  13609. OS_SETREUID_METHODDEF
  13610. OS_SETGID_METHODDEF
  13611. OS_SETEGID_METHODDEF
  13612. OS_SETREGID_METHODDEF
  13613. OS_SETGROUPS_METHODDEF
  13614. OS_INITGROUPS_METHODDEF
  13615. OS_GETPGID_METHODDEF
  13616. OS_SETPGRP_METHODDEF
  13617. OS_WAIT_METHODDEF
  13618. OS_WAIT3_METHODDEF
  13619. OS_WAIT4_METHODDEF
  13620. OS_WAITID_METHODDEF
  13621. OS_WAITPID_METHODDEF
  13622. OS_PIDFD_OPEN_METHODDEF
  13623. OS_GETSID_METHODDEF
  13624. OS_SETSID_METHODDEF
  13625. OS_SETPGID_METHODDEF
  13626. OS_TCGETPGRP_METHODDEF
  13627. OS_TCSETPGRP_METHODDEF
  13628. OS_OPEN_METHODDEF
  13629. OS_CLOSE_METHODDEF
  13630. OS_CLOSERANGE_METHODDEF
  13631. OS_DEVICE_ENCODING_METHODDEF
  13632. OS_DUP_METHODDEF
  13633. OS_DUP2_METHODDEF
  13634. OS_LOCKF_METHODDEF
  13635. OS_LSEEK_METHODDEF
  13636. OS_READ_METHODDEF
  13637. OS_READV_METHODDEF
  13638. OS_PREAD_METHODDEF
  13639. OS_PREADV_METHODDEF
  13640. OS_WRITE_METHODDEF
  13641. OS_WRITEV_METHODDEF
  13642. OS_PWRITE_METHODDEF
  13643. OS_PWRITEV_METHODDEF
  13644. OS_SENDFILE_METHODDEF
  13645. OS_FSTAT_METHODDEF
  13646. OS_ISATTY_METHODDEF
  13647. OS_PIPE_METHODDEF
  13648. OS_PIPE2_METHODDEF
  13649. OS_MKFIFO_METHODDEF
  13650. OS_MKNOD_METHODDEF
  13651. OS_MAJOR_METHODDEF
  13652. OS_MINOR_METHODDEF
  13653. OS_MAKEDEV_METHODDEF
  13654. OS_FTRUNCATE_METHODDEF
  13655. OS_TRUNCATE_METHODDEF
  13656. OS_POSIX_FALLOCATE_METHODDEF
  13657. OS_POSIX_FADVISE_METHODDEF
  13658. OS_PUTENV_METHODDEF
  13659. OS_UNSETENV_METHODDEF
  13660. OS_STRERROR_METHODDEF
  13661. OS_FCHDIR_METHODDEF
  13662. OS_FSYNC_METHODDEF
  13663. OS_SYNC_METHODDEF
  13664. OS_FDATASYNC_METHODDEF
  13665. OS_WCOREDUMP_METHODDEF
  13666. OS_WIFCONTINUED_METHODDEF
  13667. OS_WIFSTOPPED_METHODDEF
  13668. OS_WIFSIGNALED_METHODDEF
  13669. OS_WIFEXITED_METHODDEF
  13670. OS_WEXITSTATUS_METHODDEF
  13671. OS_WTERMSIG_METHODDEF
  13672. OS_WSTOPSIG_METHODDEF
  13673. OS_FSTATVFS_METHODDEF
  13674. OS_STATVFS_METHODDEF
  13675. OS_CONFSTR_METHODDEF
  13676. OS_SYSCONF_METHODDEF
  13677. OS_FPATHCONF_METHODDEF
  13678. OS_PATHCONF_METHODDEF
  13679. OS_ABORT_METHODDEF
  13680. OS__GETFULLPATHNAME_METHODDEF
  13681. OS__GETDISKUSAGE_METHODDEF
  13682. OS__GETFINALPATHNAME_METHODDEF
  13683. OS__GETVOLUMEPATHNAME_METHODDEF
  13684. OS__PATH_SPLITROOT_METHODDEF
  13685. OS__PATH_NORMPATH_METHODDEF
  13686. OS_GETLOADAVG_METHODDEF
  13687. OS_URANDOM_METHODDEF
  13688. OS_SETRESUID_METHODDEF
  13689. OS_SETRESGID_METHODDEF
  13690. OS_GETRESUID_METHODDEF
  13691. OS_GETRESGID_METHODDEF
  13692. OS_GETXATTR_METHODDEF
  13693. OS_SETXATTR_METHODDEF
  13694. OS_REMOVEXATTR_METHODDEF
  13695. OS_LISTXATTR_METHODDEF
  13696. OS_GET_TERMINAL_SIZE_METHODDEF
  13697. OS_CPU_COUNT_METHODDEF
  13698. OS_GET_INHERITABLE_METHODDEF
  13699. OS_SET_INHERITABLE_METHODDEF
  13700. OS_GET_HANDLE_INHERITABLE_METHODDEF
  13701. OS_SET_HANDLE_INHERITABLE_METHODDEF
  13702. OS_GET_BLOCKING_METHODDEF
  13703. OS_SET_BLOCKING_METHODDEF
  13704. OS_SCANDIR_METHODDEF
  13705. OS_FSPATH_METHODDEF
  13706. OS_GETRANDOM_METHODDEF
  13707. OS_MEMFD_CREATE_METHODDEF
  13708. OS_EVENTFD_METHODDEF
  13709. OS_EVENTFD_READ_METHODDEF
  13710. OS_EVENTFD_WRITE_METHODDEF
  13711. OS__ADD_DLL_DIRECTORY_METHODDEF
  13712. OS__REMOVE_DLL_DIRECTORY_METHODDEF
  13713. OS_WAITSTATUS_TO_EXITCODE_METHODDEF
  13714. OS_SETNS_METHODDEF
  13715. OS_UNSHARE_METHODDEF
  13716. OS__PATH_ISDEVDRIVE_METHODDEF
  13717. OS__PATH_ISDIR_METHODDEF
  13718. OS__PATH_ISFILE_METHODDEF
  13719. OS__PATH_ISLINK_METHODDEF
  13720. OS__PATH_EXISTS_METHODDEF
  13721. {NULL, NULL} /* Sentinel */
  13722. };
  13723. static int
  13724. all_ins(PyObject *m)
  13725. {
  13726. #ifdef F_OK
  13727. if (PyModule_AddIntMacro(m, F_OK)) return -1;
  13728. #endif
  13729. #ifdef R_OK
  13730. if (PyModule_AddIntMacro(m, R_OK)) return -1;
  13731. #endif
  13732. #ifdef W_OK
  13733. if (PyModule_AddIntMacro(m, W_OK)) return -1;
  13734. #endif
  13735. #ifdef X_OK
  13736. if (PyModule_AddIntMacro(m, X_OK)) return -1;
  13737. #endif
  13738. #ifdef NGROUPS_MAX
  13739. if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
  13740. #endif
  13741. #ifdef TMP_MAX
  13742. if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
  13743. #endif
  13744. #ifdef WCONTINUED
  13745. if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
  13746. #endif
  13747. #ifdef WNOHANG
  13748. if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
  13749. #endif
  13750. #ifdef WUNTRACED
  13751. if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
  13752. #endif
  13753. #ifdef O_RDONLY
  13754. if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
  13755. #endif
  13756. #ifdef O_WRONLY
  13757. if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
  13758. #endif
  13759. #ifdef O_RDWR
  13760. if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
  13761. #endif
  13762. #ifdef O_NDELAY
  13763. if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
  13764. #endif
  13765. #ifdef O_NONBLOCK
  13766. if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
  13767. #endif
  13768. #ifdef O_APPEND
  13769. if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
  13770. #endif
  13771. #ifdef O_DSYNC
  13772. if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
  13773. #endif
  13774. #ifdef O_RSYNC
  13775. if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
  13776. #endif
  13777. #ifdef O_SYNC
  13778. if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
  13779. #endif
  13780. #ifdef O_NOCTTY
  13781. if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
  13782. #endif
  13783. #ifdef O_CREAT
  13784. if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
  13785. #endif
  13786. #ifdef O_EXCL
  13787. if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
  13788. #endif
  13789. #ifdef O_TRUNC
  13790. if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
  13791. #endif
  13792. #ifdef O_BINARY
  13793. if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
  13794. #endif
  13795. #ifdef O_TEXT
  13796. if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
  13797. #endif
  13798. #ifdef O_XATTR
  13799. if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
  13800. #endif
  13801. #ifdef O_LARGEFILE
  13802. if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
  13803. #endif
  13804. #ifndef __GNU__
  13805. #ifdef O_SHLOCK
  13806. if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
  13807. #endif
  13808. #ifdef O_EXLOCK
  13809. if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
  13810. #endif
  13811. #endif
  13812. #ifdef O_EXEC
  13813. if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
  13814. #endif
  13815. #ifdef O_SEARCH
  13816. if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
  13817. #endif
  13818. #ifdef O_PATH
  13819. if (PyModule_AddIntMacro(m, O_PATH)) return -1;
  13820. #endif
  13821. #ifdef O_TTY_INIT
  13822. if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
  13823. #endif
  13824. #ifdef O_TMPFILE
  13825. if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
  13826. #endif
  13827. #ifdef PRIO_PROCESS
  13828. if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
  13829. #endif
  13830. #ifdef PRIO_PGRP
  13831. if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
  13832. #endif
  13833. #ifdef PRIO_USER
  13834. if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
  13835. #endif
  13836. #ifdef PRIO_DARWIN_THREAD
  13837. if (PyModule_AddIntMacro(m, PRIO_DARWIN_THREAD)) return -1;
  13838. #endif
  13839. #ifdef PRIO_DARWIN_PROCESS
  13840. if (PyModule_AddIntMacro(m, PRIO_DARWIN_PROCESS)) return -1;
  13841. #endif
  13842. #ifdef PRIO_DARWIN_BG
  13843. if (PyModule_AddIntMacro(m, PRIO_DARWIN_BG)) return -1;
  13844. #endif
  13845. #ifdef PRIO_DARWIN_NONUI
  13846. if (PyModule_AddIntMacro(m, PRIO_DARWIN_NONUI)) return -1;
  13847. #endif
  13848. #ifdef O_CLOEXEC
  13849. if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
  13850. #endif
  13851. #ifdef O_ACCMODE
  13852. if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
  13853. #endif
  13854. #ifdef O_EVTONLY
  13855. if (PyModule_AddIntMacro(m, O_EVTONLY)) return -1;
  13856. #endif
  13857. #ifdef O_FSYNC
  13858. if (PyModule_AddIntMacro(m, O_FSYNC)) return -1;
  13859. #endif
  13860. #ifdef O_SYMLINK
  13861. if (PyModule_AddIntMacro(m, O_SYMLINK)) return -1;
  13862. #endif
  13863. #ifdef SEEK_HOLE
  13864. if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
  13865. #endif
  13866. #ifdef SEEK_DATA
  13867. if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
  13868. #endif
  13869. /* MS Windows */
  13870. #ifdef O_NOINHERIT
  13871. /* Don't inherit in child processes. */
  13872. if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
  13873. #endif
  13874. #ifdef _O_SHORT_LIVED
  13875. /* Optimize for short life (keep in memory). */
  13876. /* MS forgot to define this one with a non-underscore form too. */
  13877. if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
  13878. #endif
  13879. #ifdef O_TEMPORARY
  13880. /* Automatically delete when last handle is closed. */
  13881. if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
  13882. #endif
  13883. #ifdef O_RANDOM
  13884. /* Optimize for random access. */
  13885. if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
  13886. #endif
  13887. #ifdef O_SEQUENTIAL
  13888. /* Optimize for sequential access. */
  13889. if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
  13890. #endif
  13891. /* GNU extensions. */
  13892. #ifdef O_ASYNC
  13893. /* Send a SIGIO signal whenever input or output
  13894. becomes available on file descriptor */
  13895. if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
  13896. #endif
  13897. #ifdef O_DIRECT
  13898. /* Direct disk access. */
  13899. if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
  13900. #endif
  13901. #ifdef O_DIRECTORY
  13902. /* Must be a directory. */
  13903. if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
  13904. #endif
  13905. #ifdef O_NOFOLLOW
  13906. /* Do not follow links. */
  13907. if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
  13908. #endif
  13909. #ifdef O_NOFOLLOW_ANY
  13910. if (PyModule_AddIntMacro(m, O_NOFOLLOW_ANY)) return -1;
  13911. #endif
  13912. #ifdef O_NOLINKS
  13913. /* Fails if link count of the named file is greater than 1 */
  13914. if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
  13915. #endif
  13916. #ifdef O_NOATIME
  13917. /* Do not update the access time. */
  13918. if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
  13919. #endif
  13920. /* These come from sysexits.h */
  13921. #ifdef EX_OK
  13922. if (PyModule_AddIntMacro(m, EX_OK)) return -1;
  13923. #endif /* EX_OK */
  13924. #ifdef EX_USAGE
  13925. if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
  13926. #endif /* EX_USAGE */
  13927. #ifdef EX_DATAERR
  13928. if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
  13929. #endif /* EX_DATAERR */
  13930. #ifdef EX_NOINPUT
  13931. if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
  13932. #endif /* EX_NOINPUT */
  13933. #ifdef EX_NOUSER
  13934. if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
  13935. #endif /* EX_NOUSER */
  13936. #ifdef EX_NOHOST
  13937. if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
  13938. #endif /* EX_NOHOST */
  13939. #ifdef EX_UNAVAILABLE
  13940. if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
  13941. #endif /* EX_UNAVAILABLE */
  13942. #ifdef EX_SOFTWARE
  13943. if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
  13944. #endif /* EX_SOFTWARE */
  13945. #ifdef EX_OSERR
  13946. if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
  13947. #endif /* EX_OSERR */
  13948. #ifdef EX_OSFILE
  13949. if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
  13950. #endif /* EX_OSFILE */
  13951. #ifdef EX_CANTCREAT
  13952. if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
  13953. #endif /* EX_CANTCREAT */
  13954. #ifdef EX_IOERR
  13955. if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
  13956. #endif /* EX_IOERR */
  13957. #ifdef EX_TEMPFAIL
  13958. if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
  13959. #endif /* EX_TEMPFAIL */
  13960. #ifdef EX_PROTOCOL
  13961. if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
  13962. #endif /* EX_PROTOCOL */
  13963. #ifdef EX_NOPERM
  13964. if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
  13965. #endif /* EX_NOPERM */
  13966. #ifdef EX_CONFIG
  13967. if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
  13968. #endif /* EX_CONFIG */
  13969. #ifdef EX_NOTFOUND
  13970. if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
  13971. #endif /* EX_NOTFOUND */
  13972. /* statvfs */
  13973. #ifdef ST_RDONLY
  13974. if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
  13975. #endif /* ST_RDONLY */
  13976. #ifdef ST_NOSUID
  13977. if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
  13978. #endif /* ST_NOSUID */
  13979. /* GNU extensions */
  13980. #ifdef ST_NODEV
  13981. if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
  13982. #endif /* ST_NODEV */
  13983. #ifdef ST_NOEXEC
  13984. if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
  13985. #endif /* ST_NOEXEC */
  13986. #ifdef ST_SYNCHRONOUS
  13987. if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
  13988. #endif /* ST_SYNCHRONOUS */
  13989. #ifdef ST_MANDLOCK
  13990. if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
  13991. #endif /* ST_MANDLOCK */
  13992. #ifdef ST_WRITE
  13993. if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
  13994. #endif /* ST_WRITE */
  13995. #ifdef ST_APPEND
  13996. if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
  13997. #endif /* ST_APPEND */
  13998. #ifdef ST_NOATIME
  13999. if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
  14000. #endif /* ST_NOATIME */
  14001. #ifdef ST_NODIRATIME
  14002. if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
  14003. #endif /* ST_NODIRATIME */
  14004. #ifdef ST_RELATIME
  14005. if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
  14006. #endif /* ST_RELATIME */
  14007. /* FreeBSD sendfile() constants */
  14008. #ifdef SF_NODISKIO
  14009. if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
  14010. #endif
  14011. /* is obsolete since the 11.x release */
  14012. #ifdef SF_MNOWAIT
  14013. if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
  14014. #endif
  14015. #ifdef SF_SYNC
  14016. if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
  14017. #endif
  14018. #ifdef SF_NOCACHE
  14019. if (PyModule_AddIntMacro(m, SF_NOCACHE)) return -1;
  14020. #endif
  14021. /* constants for posix_fadvise */
  14022. #ifdef POSIX_FADV_NORMAL
  14023. if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
  14024. #endif
  14025. #ifdef POSIX_FADV_SEQUENTIAL
  14026. if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
  14027. #endif
  14028. #ifdef POSIX_FADV_RANDOM
  14029. if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
  14030. #endif
  14031. #ifdef POSIX_FADV_NOREUSE
  14032. if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
  14033. #endif
  14034. #ifdef POSIX_FADV_WILLNEED
  14035. if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
  14036. #endif
  14037. #ifdef POSIX_FADV_DONTNEED
  14038. if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
  14039. #endif
  14040. /* constants for waitid */
  14041. #if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
  14042. if (PyModule_AddIntMacro(m, P_PID)) return -1;
  14043. if (PyModule_AddIntMacro(m, P_PGID)) return -1;
  14044. if (PyModule_AddIntMacro(m, P_ALL)) return -1;
  14045. #ifdef P_PIDFD
  14046. if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
  14047. #endif
  14048. #ifdef PIDFD_NONBLOCK
  14049. if (PyModule_AddIntMacro(m, PIDFD_NONBLOCK)) return -1;
  14050. #endif
  14051. #endif
  14052. #ifdef WEXITED
  14053. if (PyModule_AddIntMacro(m, WEXITED)) return -1;
  14054. #endif
  14055. #ifdef WNOWAIT
  14056. if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
  14057. #endif
  14058. #ifdef WSTOPPED
  14059. if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
  14060. #endif
  14061. #ifdef CLD_EXITED
  14062. if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
  14063. #endif
  14064. #ifdef CLD_KILLED
  14065. if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
  14066. #endif
  14067. #ifdef CLD_DUMPED
  14068. if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
  14069. #endif
  14070. #ifdef CLD_TRAPPED
  14071. if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
  14072. #endif
  14073. #ifdef CLD_STOPPED
  14074. if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
  14075. #endif
  14076. #ifdef CLD_CONTINUED
  14077. if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
  14078. #endif
  14079. /* constants for lockf */
  14080. #ifdef F_LOCK
  14081. if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
  14082. #endif
  14083. #ifdef F_TLOCK
  14084. if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
  14085. #endif
  14086. #ifdef F_ULOCK
  14087. if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
  14088. #endif
  14089. #ifdef F_TEST
  14090. if (PyModule_AddIntMacro(m, F_TEST)) return -1;
  14091. #endif
  14092. #ifdef RWF_DSYNC
  14093. if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
  14094. #endif
  14095. #ifdef RWF_HIPRI
  14096. if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
  14097. #endif
  14098. #ifdef RWF_SYNC
  14099. if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
  14100. #endif
  14101. #ifdef RWF_NOWAIT
  14102. if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
  14103. #endif
  14104. #ifdef RWF_APPEND
  14105. if (PyModule_AddIntConstant(m, "RWF_APPEND", RWF_APPEND)) return -1;
  14106. #endif
  14107. /* constants for splice */
  14108. #if defined(HAVE_SPLICE) && defined(__linux__)
  14109. if (PyModule_AddIntConstant(m, "SPLICE_F_MOVE", SPLICE_F_MOVE)) return -1;
  14110. if (PyModule_AddIntConstant(m, "SPLICE_F_NONBLOCK", SPLICE_F_NONBLOCK)) return -1;
  14111. if (PyModule_AddIntConstant(m, "SPLICE_F_MORE", SPLICE_F_MORE)) return -1;
  14112. #endif
  14113. /* constants for posix_spawn */
  14114. #ifdef HAVE_POSIX_SPAWN
  14115. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
  14116. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
  14117. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
  14118. #endif
  14119. #if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
  14120. if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
  14121. if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
  14122. if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
  14123. #endif
  14124. #ifdef HAVE_SPAWNV
  14125. if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
  14126. if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
  14127. #endif
  14128. #ifdef HAVE_SCHED_H
  14129. #ifdef SCHED_OTHER
  14130. if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
  14131. #endif
  14132. #ifdef SCHED_FIFO
  14133. if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
  14134. #endif
  14135. #ifdef SCHED_RR
  14136. if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
  14137. #endif
  14138. #ifdef SCHED_SPORADIC
  14139. if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
  14140. #endif
  14141. #ifdef SCHED_BATCH
  14142. if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
  14143. #endif
  14144. #ifdef SCHED_IDLE
  14145. if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
  14146. #endif
  14147. #ifdef SCHED_RESET_ON_FORK
  14148. if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
  14149. #endif
  14150. #ifdef SCHED_SYS
  14151. if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
  14152. #endif
  14153. #ifdef SCHED_IA
  14154. if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
  14155. #endif
  14156. #ifdef SCHED_FSS
  14157. if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
  14158. #endif
  14159. #ifdef SCHED_FX
  14160. if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
  14161. #endif
  14162. /* constants for namespaces */
  14163. #if defined(HAVE_SETNS) || defined(HAVE_UNSHARE)
  14164. #ifdef CLONE_FS
  14165. if (PyModule_AddIntMacro(m, CLONE_FS)) return -1;
  14166. #endif
  14167. #ifdef CLONE_FILES
  14168. if (PyModule_AddIntMacro(m, CLONE_FILES)) return -1;
  14169. #endif
  14170. #ifdef CLONE_NEWNS
  14171. if (PyModule_AddIntMacro(m, CLONE_NEWNS)) return -1;
  14172. #endif
  14173. #ifdef CLONE_NEWCGROUP
  14174. if (PyModule_AddIntMacro(m, CLONE_NEWCGROUP)) return -1;
  14175. #endif
  14176. #ifdef CLONE_NEWUTS
  14177. if (PyModule_AddIntMacro(m, CLONE_NEWUTS)) return -1;
  14178. #endif
  14179. #ifdef CLONE_NEWIPC
  14180. if (PyModule_AddIntMacro(m, CLONE_NEWIPC)) return -1;
  14181. #endif
  14182. #ifdef CLONE_NEWUSER
  14183. if (PyModule_AddIntMacro(m, CLONE_NEWUSER)) return -1;
  14184. #endif
  14185. #ifdef CLONE_NEWPID
  14186. if (PyModule_AddIntMacro(m, CLONE_NEWPID)) return -1;
  14187. #endif
  14188. #ifdef CLONE_NEWNET
  14189. if (PyModule_AddIntMacro(m, CLONE_NEWNET)) return -1;
  14190. #endif
  14191. #ifdef CLONE_NEWTIME
  14192. if (PyModule_AddIntMacro(m, CLONE_NEWTIME)) return -1;
  14193. #endif
  14194. #ifdef CLONE_SYSVSEM
  14195. if (PyModule_AddIntMacro(m, CLONE_SYSVSEM)) return -1;
  14196. #endif
  14197. #ifdef CLONE_THREAD
  14198. if (PyModule_AddIntMacro(m, CLONE_THREAD)) return -1;
  14199. #endif
  14200. #ifdef CLONE_SIGHAND
  14201. if (PyModule_AddIntMacro(m, CLONE_SIGHAND)) return -1;
  14202. #endif
  14203. #ifdef CLONE_VM
  14204. if (PyModule_AddIntMacro(m, CLONE_VM)) return -1;
  14205. #endif
  14206. #endif
  14207. #endif
  14208. #ifdef USE_XATTRS
  14209. if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
  14210. if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
  14211. if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
  14212. #endif
  14213. #if HAVE_DECL_RTLD_LAZY
  14214. if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
  14215. #endif
  14216. #if HAVE_DECL_RTLD_NOW
  14217. if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
  14218. #endif
  14219. #if HAVE_DECL_RTLD_GLOBAL
  14220. if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
  14221. #endif
  14222. #if HAVE_DECL_RTLD_LOCAL
  14223. if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
  14224. #endif
  14225. #if HAVE_DECL_RTLD_NODELETE
  14226. if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
  14227. #endif
  14228. #if HAVE_DECL_RTLD_NOLOAD
  14229. if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
  14230. #endif
  14231. #if HAVE_DECL_RTLD_DEEPBIND
  14232. if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
  14233. #endif
  14234. #if HAVE_DECL_RTLD_MEMBER
  14235. if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
  14236. #endif
  14237. #ifdef HAVE_GETRANDOM_SYSCALL
  14238. if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
  14239. if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
  14240. #endif
  14241. #ifdef HAVE_MEMFD_CREATE
  14242. if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
  14243. if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
  14244. #ifdef MFD_HUGETLB
  14245. if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
  14246. #endif
  14247. #ifdef MFD_HUGE_SHIFT
  14248. if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
  14249. #endif
  14250. #ifdef MFD_HUGE_MASK
  14251. if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
  14252. #endif
  14253. #ifdef MFD_HUGE_64KB
  14254. if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
  14255. #endif
  14256. #ifdef MFD_HUGE_512KB
  14257. if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
  14258. #endif
  14259. #ifdef MFD_HUGE_1MB
  14260. if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
  14261. #endif
  14262. #ifdef MFD_HUGE_2MB
  14263. if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
  14264. #endif
  14265. #ifdef MFD_HUGE_8MB
  14266. if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
  14267. #endif
  14268. #ifdef MFD_HUGE_16MB
  14269. if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
  14270. #endif
  14271. #ifdef MFD_HUGE_32MB
  14272. if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
  14273. #endif
  14274. #ifdef MFD_HUGE_256MB
  14275. if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
  14276. #endif
  14277. #ifdef MFD_HUGE_512MB
  14278. if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
  14279. #endif
  14280. #ifdef MFD_HUGE_1GB
  14281. if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
  14282. #endif
  14283. #ifdef MFD_HUGE_2GB
  14284. if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
  14285. #endif
  14286. #ifdef MFD_HUGE_16GB
  14287. if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
  14288. #endif
  14289. #endif /* HAVE_MEMFD_CREATE */
  14290. #if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
  14291. if (PyModule_AddIntMacro(m, EFD_CLOEXEC)) return -1;
  14292. #ifdef EFD_NONBLOCK
  14293. if (PyModule_AddIntMacro(m, EFD_NONBLOCK)) return -1;
  14294. #endif
  14295. #ifdef EFD_SEMAPHORE
  14296. if (PyModule_AddIntMacro(m, EFD_SEMAPHORE)) return -1;
  14297. #endif
  14298. #endif /* HAVE_EVENTFD && EFD_CLOEXEC */
  14299. #if defined(__APPLE__)
  14300. if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
  14301. if (PyModule_AddIntConstant(m, "_COPYFILE_STAT", COPYFILE_STAT)) return -1;
  14302. if (PyModule_AddIntConstant(m, "_COPYFILE_ACL", COPYFILE_ACL)) return -1;
  14303. if (PyModule_AddIntConstant(m, "_COPYFILE_XATTR", COPYFILE_XATTR)) return -1;
  14304. #endif
  14305. #ifdef MS_WINDOWS
  14306. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
  14307. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
  14308. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
  14309. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
  14310. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
  14311. #endif
  14312. return 0;
  14313. }
  14314. #define PROBE(name, test) \
  14315. static int name(void) \
  14316. { \
  14317. if (test) { \
  14318. return 1; \
  14319. } else { \
  14320. return 0; \
  14321. } \
  14322. }
  14323. #ifdef HAVE_FSTATAT
  14324. PROBE(probe_fstatat, HAVE_FSTATAT_RUNTIME)
  14325. #endif
  14326. #ifdef HAVE_FACCESSAT
  14327. PROBE(probe_faccessat, HAVE_FACCESSAT_RUNTIME)
  14328. #endif
  14329. #ifdef HAVE_FCHMODAT
  14330. PROBE(probe_fchmodat, HAVE_FCHMODAT_RUNTIME)
  14331. #endif
  14332. #ifdef HAVE_FCHOWNAT
  14333. PROBE(probe_fchownat, HAVE_FCHOWNAT_RUNTIME)
  14334. #endif
  14335. #ifdef HAVE_LINKAT
  14336. PROBE(probe_linkat, HAVE_LINKAT_RUNTIME)
  14337. #endif
  14338. #ifdef HAVE_FDOPENDIR
  14339. PROBE(probe_fdopendir, HAVE_FDOPENDIR_RUNTIME)
  14340. #endif
  14341. #ifdef HAVE_MKDIRAT
  14342. PROBE(probe_mkdirat, HAVE_MKDIRAT_RUNTIME)
  14343. #endif
  14344. #ifdef HAVE_MKFIFOAT
  14345. PROBE(probe_mkfifoat, HAVE_MKFIFOAT_RUNTIME)
  14346. #endif
  14347. #ifdef HAVE_MKNODAT
  14348. PROBE(probe_mknodat, HAVE_MKNODAT_RUNTIME)
  14349. #endif
  14350. #ifdef HAVE_RENAMEAT
  14351. PROBE(probe_renameat, HAVE_RENAMEAT_RUNTIME)
  14352. #endif
  14353. #ifdef HAVE_UNLINKAT
  14354. PROBE(probe_unlinkat, HAVE_UNLINKAT_RUNTIME)
  14355. #endif
  14356. #ifdef HAVE_OPENAT
  14357. PROBE(probe_openat, HAVE_OPENAT_RUNTIME)
  14358. #endif
  14359. #ifdef HAVE_READLINKAT
  14360. PROBE(probe_readlinkat, HAVE_READLINKAT_RUNTIME)
  14361. #endif
  14362. #ifdef HAVE_SYMLINKAT
  14363. PROBE(probe_symlinkat, HAVE_SYMLINKAT_RUNTIME)
  14364. #endif
  14365. #ifdef HAVE_FUTIMENS
  14366. PROBE(probe_futimens, HAVE_FUTIMENS_RUNTIME)
  14367. #endif
  14368. #ifdef HAVE_UTIMENSAT
  14369. PROBE(probe_utimensat, HAVE_UTIMENSAT_RUNTIME)
  14370. #endif
  14371. static const struct have_function {
  14372. const char * const label;
  14373. int (*probe)(void);
  14374. } have_functions[] = {
  14375. #ifdef HAVE_EVENTFD
  14376. {"HAVE_EVENTFD", NULL},
  14377. #endif
  14378. #ifdef HAVE_FACCESSAT
  14379. { "HAVE_FACCESSAT", probe_faccessat },
  14380. #endif
  14381. #ifdef HAVE_FCHDIR
  14382. { "HAVE_FCHDIR", NULL },
  14383. #endif
  14384. #ifdef HAVE_FCHMOD
  14385. { "HAVE_FCHMOD", NULL },
  14386. #endif
  14387. #ifdef HAVE_FCHMODAT
  14388. { "HAVE_FCHMODAT", probe_fchmodat },
  14389. #endif
  14390. #ifdef HAVE_FCHOWN
  14391. { "HAVE_FCHOWN", NULL },
  14392. #endif
  14393. #ifdef HAVE_FCHOWNAT
  14394. { "HAVE_FCHOWNAT", probe_fchownat },
  14395. #endif
  14396. #ifdef HAVE_FEXECVE
  14397. { "HAVE_FEXECVE", NULL },
  14398. #endif
  14399. #ifdef HAVE_FDOPENDIR
  14400. { "HAVE_FDOPENDIR", probe_fdopendir },
  14401. #endif
  14402. #ifdef HAVE_FPATHCONF
  14403. { "HAVE_FPATHCONF", NULL },
  14404. #endif
  14405. #ifdef HAVE_FSTATAT
  14406. { "HAVE_FSTATAT", probe_fstatat },
  14407. #endif
  14408. #ifdef HAVE_FSTATVFS
  14409. { "HAVE_FSTATVFS", NULL },
  14410. #endif
  14411. #if defined HAVE_FTRUNCATE || defined MS_WINDOWS
  14412. { "HAVE_FTRUNCATE", NULL },
  14413. #endif
  14414. #ifdef HAVE_FUTIMENS
  14415. { "HAVE_FUTIMENS", probe_futimens },
  14416. #endif
  14417. #ifdef HAVE_FUTIMES
  14418. { "HAVE_FUTIMES", NULL },
  14419. #endif
  14420. #ifdef HAVE_FUTIMESAT
  14421. { "HAVE_FUTIMESAT", NULL },
  14422. #endif
  14423. #ifdef HAVE_LINKAT
  14424. { "HAVE_LINKAT", probe_linkat },
  14425. #endif
  14426. #ifdef HAVE_LCHFLAGS
  14427. { "HAVE_LCHFLAGS", NULL },
  14428. #endif
  14429. #ifdef HAVE_LCHMOD
  14430. { "HAVE_LCHMOD", NULL },
  14431. #endif
  14432. #ifdef HAVE_LCHOWN
  14433. { "HAVE_LCHOWN", NULL },
  14434. #endif
  14435. #ifdef HAVE_LSTAT
  14436. { "HAVE_LSTAT", NULL },
  14437. #endif
  14438. #ifdef HAVE_LUTIMES
  14439. { "HAVE_LUTIMES", NULL },
  14440. #endif
  14441. #ifdef HAVE_MEMFD_CREATE
  14442. { "HAVE_MEMFD_CREATE", NULL },
  14443. #endif
  14444. #ifdef HAVE_MKDIRAT
  14445. { "HAVE_MKDIRAT", probe_mkdirat },
  14446. #endif
  14447. #ifdef HAVE_MKFIFOAT
  14448. { "HAVE_MKFIFOAT", probe_mkfifoat },
  14449. #endif
  14450. #ifdef HAVE_MKNODAT
  14451. { "HAVE_MKNODAT", probe_mknodat },
  14452. #endif
  14453. #ifdef HAVE_OPENAT
  14454. { "HAVE_OPENAT", probe_openat },
  14455. #endif
  14456. #ifdef HAVE_READLINKAT
  14457. { "HAVE_READLINKAT", probe_readlinkat },
  14458. #endif
  14459. #ifdef HAVE_RENAMEAT
  14460. { "HAVE_RENAMEAT", probe_renameat },
  14461. #endif
  14462. #ifdef HAVE_SYMLINKAT
  14463. { "HAVE_SYMLINKAT", probe_symlinkat },
  14464. #endif
  14465. #ifdef HAVE_UNLINKAT
  14466. { "HAVE_UNLINKAT", probe_unlinkat },
  14467. #endif
  14468. #ifdef HAVE_UTIMENSAT
  14469. { "HAVE_UTIMENSAT", probe_utimensat },
  14470. #endif
  14471. #ifdef MS_WINDOWS
  14472. { "MS_WINDOWS", NULL },
  14473. #endif
  14474. { NULL, NULL }
  14475. };
  14476. static int
  14477. posixmodule_exec(PyObject *m)
  14478. {
  14479. _posixstate *state = get_posix_state(m);
  14480. #if defined(HAVE_PWRITEV)
  14481. if (HAVE_PWRITEV_RUNTIME) {} else {
  14482. PyObject* dct = PyModule_GetDict(m);
  14483. if (dct == NULL) {
  14484. return -1;
  14485. }
  14486. if (PyDict_DelItemString(dct, "pwritev") == -1) {
  14487. PyErr_Clear();
  14488. }
  14489. if (PyDict_DelItemString(dct, "preadv") == -1) {
  14490. PyErr_Clear();
  14491. }
  14492. }
  14493. #endif
  14494. /* Initialize environ dictionary */
  14495. if (_PyModule_Add(m, "environ", convertenviron()) != 0) {
  14496. return -1;
  14497. }
  14498. if (all_ins(m))
  14499. return -1;
  14500. if (setup_confname_tables(m))
  14501. return -1;
  14502. if (PyModule_AddObjectRef(m, "error", PyExc_OSError) < 0) {
  14503. return -1;
  14504. }
  14505. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  14506. waitid_result_desc.name = MODNAME ".waitid_result";
  14507. state->WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
  14508. if (PyModule_AddObjectRef(m, "waitid_result", state->WaitidResultType) < 0) {
  14509. return -1;
  14510. }
  14511. #endif
  14512. stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
  14513. stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
  14514. stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
  14515. stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
  14516. state->StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
  14517. if (PyModule_AddObjectRef(m, "stat_result", state->StatResultType) < 0) {
  14518. return -1;
  14519. }
  14520. state->statresult_new_orig = ((PyTypeObject *)state->StatResultType)->tp_new;
  14521. ((PyTypeObject *)state->StatResultType)->tp_new = statresult_new;
  14522. statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
  14523. state->StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
  14524. if (PyModule_AddObjectRef(m, "statvfs_result", state->StatVFSResultType) < 0) {
  14525. return -1;
  14526. }
  14527. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  14528. sched_param_desc.name = MODNAME ".sched_param";
  14529. state->SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
  14530. if (PyModule_AddObjectRef(m, "sched_param", state->SchedParamType) < 0) {
  14531. return -1;
  14532. }
  14533. ((PyTypeObject *)state->SchedParamType)->tp_new = os_sched_param;
  14534. #endif
  14535. /* initialize TerminalSize_info */
  14536. state->TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
  14537. if (PyModule_AddObjectRef(m, "terminal_size", state->TerminalSizeType) < 0) {
  14538. return -1;
  14539. }
  14540. /* initialize scandir types */
  14541. PyObject *ScandirIteratorType = PyType_FromModuleAndSpec(m, &ScandirIteratorType_spec, NULL);
  14542. if (ScandirIteratorType == NULL) {
  14543. return -1;
  14544. }
  14545. state->ScandirIteratorType = ScandirIteratorType;
  14546. state->DirEntryType = PyType_FromModuleAndSpec(m, &DirEntryType_spec, NULL);
  14547. if (PyModule_AddObjectRef(m, "DirEntry", state->DirEntryType) < 0) {
  14548. return -1;
  14549. }
  14550. times_result_desc.name = MODNAME ".times_result";
  14551. state->TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
  14552. if (PyModule_AddObjectRef(m, "times_result", state->TimesResultType) < 0) {
  14553. return -1;
  14554. }
  14555. state->UnameResultType = (PyObject *)PyStructSequence_NewType(&uname_result_desc);
  14556. if (PyModule_AddObjectRef(m, "uname_result", state->UnameResultType) < 0) {
  14557. return -1;
  14558. }
  14559. if ((state->billion = PyLong_FromLong(1000000000)) == NULL)
  14560. return -1;
  14561. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  14562. state->struct_rusage = PyUnicode_InternFromString("struct_rusage");
  14563. if (state->struct_rusage == NULL)
  14564. return -1;
  14565. #endif
  14566. state->st_mode = PyUnicode_InternFromString("st_mode");
  14567. if (state->st_mode == NULL)
  14568. return -1;
  14569. /* suppress "function not used" warnings */
  14570. {
  14571. int ignored;
  14572. fd_specified("", -1);
  14573. follow_symlinks_specified("", 1);
  14574. dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
  14575. dir_fd_converter(Py_None, &ignored);
  14576. dir_fd_unavailable(Py_None, &ignored);
  14577. }
  14578. /*
  14579. * provide list of locally available functions
  14580. * so os.py can populate support_* lists
  14581. */
  14582. PyObject *list = PyList_New(0);
  14583. if (!list) {
  14584. return -1;
  14585. }
  14586. for (const struct have_function *trace = have_functions; trace->label; trace++) {
  14587. PyObject *unicode;
  14588. if (trace->probe && !trace->probe()) continue;
  14589. unicode = PyUnicode_DecodeASCII(trace->label, strlen(trace->label), NULL);
  14590. if (!unicode)
  14591. return -1;
  14592. if (PyList_Append(list, unicode))
  14593. return -1;
  14594. Py_DECREF(unicode);
  14595. }
  14596. return _PyModule_Add(m, "_have_functions", list);
  14597. }
  14598. static PyModuleDef_Slot posixmodile_slots[] = {
  14599. {Py_mod_exec, posixmodule_exec},
  14600. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  14601. {0, NULL}
  14602. };
  14603. static struct PyModuleDef posixmodule = {
  14604. PyModuleDef_HEAD_INIT,
  14605. .m_name = MODNAME,
  14606. .m_doc = posix__doc__,
  14607. .m_size = sizeof(_posixstate),
  14608. .m_methods = posix_methods,
  14609. .m_slots = posixmodile_slots,
  14610. .m_traverse = _posix_traverse,
  14611. .m_clear = _posix_clear,
  14612. .m_free = _posix_free,
  14613. };
  14614. PyMODINIT_FUNC
  14615. INITFUNC(void)
  14616. {
  14617. return PyModuleDef_Init(&posixmodule);
  14618. }
  14619. #ifdef __cplusplus
  14620. }
  14621. #endif