posixmodule.c 450 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108
  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. # 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. // Common code to raise a warning if we detect there is more than one thread
  6509. // running in the process. Best effort, silent if unable to count threads.
  6510. // Constraint: Quick. Never overcounts. Never leaves an error set.
  6511. //
  6512. // This code might do an import, thus acquiring the import lock, which
  6513. // PyOS_BeforeFork() also does. As this should only be called from
  6514. // the parent process, it is in the same thread so that works.
  6515. static void warn_about_fork_with_threads(const char* name) {
  6516. // TODO: Consider making an `os` module API to return the current number
  6517. // of threads in the process. That'd presumably use this platform code but
  6518. // raise an error rather than using the inaccurate fallback.
  6519. Py_ssize_t num_python_threads = 0;
  6520. #if defined(__APPLE__) && defined(HAVE_GETPID)
  6521. mach_port_t macos_self = mach_task_self();
  6522. mach_port_t macos_task;
  6523. if (task_for_pid(macos_self, getpid(), &macos_task) == KERN_SUCCESS) {
  6524. thread_array_t macos_threads;
  6525. mach_msg_type_number_t macos_n_threads;
  6526. if (task_threads(macos_task, &macos_threads,
  6527. &macos_n_threads) == KERN_SUCCESS) {
  6528. num_python_threads = macos_n_threads;
  6529. }
  6530. }
  6531. #elif defined(__linux__)
  6532. // Linux /proc/self/stat 20th field is the number of threads.
  6533. FILE* proc_stat = fopen("/proc/self/stat", "r");
  6534. if (proc_stat) {
  6535. size_t n;
  6536. // Size chosen arbitrarily. ~60% more bytes than a 20th column index
  6537. // observed on the author's workstation.
  6538. char stat_line[160];
  6539. n = fread(&stat_line, 1, 159, proc_stat);
  6540. stat_line[n] = '\0';
  6541. fclose(proc_stat);
  6542. char *saveptr = NULL;
  6543. char *field = strtok_r(stat_line, " ", &saveptr);
  6544. unsigned int idx;
  6545. for (idx = 19; idx && field; --idx) {
  6546. field = strtok_r(NULL, " ", &saveptr);
  6547. }
  6548. if (idx == 0 && field) { // found the 20th field
  6549. num_python_threads = atoi(field); // 0 on error
  6550. }
  6551. }
  6552. #endif
  6553. if (num_python_threads <= 0) {
  6554. // Fall back to just the number our threading module knows about.
  6555. // An incomplete view of the world, but better than nothing.
  6556. PyObject *threading = PyImport_GetModule(&_Py_ID(threading));
  6557. if (!threading) {
  6558. PyErr_Clear();
  6559. return;
  6560. }
  6561. PyObject *threading_active =
  6562. PyObject_GetAttr(threading, &_Py_ID(_active));
  6563. if (!threading_active) {
  6564. PyErr_Clear();
  6565. Py_DECREF(threading);
  6566. return;
  6567. }
  6568. PyObject *threading_limbo =
  6569. PyObject_GetAttr(threading, &_Py_ID(_limbo));
  6570. if (!threading_limbo) {
  6571. PyErr_Clear();
  6572. Py_DECREF(threading);
  6573. Py_DECREF(threading_active);
  6574. return;
  6575. }
  6576. Py_DECREF(threading);
  6577. // Duplicating what threading.active_count() does but without holding
  6578. // threading._active_limbo_lock so our count could be inaccurate if
  6579. // these dicts are mid-update from another thread. Not a big deal.
  6580. // Worst case if someone replaced threading._active or threading._limbo
  6581. // with non-dicts, we get -1 from *Length() below and undercount.
  6582. // Nobody should, but we're best effort so we clear errors and move on.
  6583. num_python_threads = (PyMapping_Length(threading_active)
  6584. + PyMapping_Length(threading_limbo));
  6585. PyErr_Clear();
  6586. Py_DECREF(threading_active);
  6587. Py_DECREF(threading_limbo);
  6588. }
  6589. if (num_python_threads > 1) {
  6590. PyErr_WarnFormat(
  6591. PyExc_DeprecationWarning, 1,
  6592. #ifdef HAVE_GETPID
  6593. "This process (pid=%d) is multi-threaded, "
  6594. #else
  6595. "This process is multi-threaded, "
  6596. #endif
  6597. "use of %s() may lead to deadlocks in the child.",
  6598. #ifdef HAVE_GETPID
  6599. getpid(),
  6600. #endif
  6601. name);
  6602. PyErr_Clear();
  6603. }
  6604. }
  6605. #ifdef HAVE_FORK1
  6606. /*[clinic input]
  6607. os.fork1
  6608. Fork a child process with a single multiplexed (i.e., not bound) thread.
  6609. Return 0 to child process and PID of child to parent process.
  6610. [clinic start generated code]*/
  6611. static PyObject *
  6612. os_fork1_impl(PyObject *module)
  6613. /*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
  6614. {
  6615. pid_t pid;
  6616. PyInterpreterState *interp = _PyInterpreterState_GET();
  6617. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  6618. PyErr_SetString(PyExc_RuntimeError,
  6619. "can't fork at interpreter shutdown");
  6620. return NULL;
  6621. }
  6622. if (!_Py_IsMainInterpreter(interp)) {
  6623. PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
  6624. return NULL;
  6625. }
  6626. PyOS_BeforeFork();
  6627. pid = fork1();
  6628. int saved_errno = errno;
  6629. if (pid == 0) {
  6630. /* child: this clobbers and resets the import lock. */
  6631. PyOS_AfterFork_Child();
  6632. } else {
  6633. warn_about_fork_with_threads("fork1");
  6634. /* parent: release the import lock. */
  6635. PyOS_AfterFork_Parent();
  6636. }
  6637. if (pid == -1) {
  6638. errno = saved_errno;
  6639. return posix_error();
  6640. }
  6641. return PyLong_FromPid(pid);
  6642. }
  6643. #endif /* HAVE_FORK1 */
  6644. #ifdef HAVE_FORK
  6645. /*[clinic input]
  6646. os.fork
  6647. Fork a child process.
  6648. Return 0 to child process and PID of child to parent process.
  6649. [clinic start generated code]*/
  6650. static PyObject *
  6651. os_fork_impl(PyObject *module)
  6652. /*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
  6653. {
  6654. pid_t pid;
  6655. PyInterpreterState *interp = _PyInterpreterState_GET();
  6656. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  6657. PyErr_SetString(PyExc_RuntimeError,
  6658. "can't fork at interpreter shutdown");
  6659. return NULL;
  6660. }
  6661. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_FORK)) {
  6662. PyErr_SetString(PyExc_RuntimeError,
  6663. "fork not supported for isolated subinterpreters");
  6664. return NULL;
  6665. }
  6666. if (PySys_Audit("os.fork", NULL) < 0) {
  6667. return NULL;
  6668. }
  6669. PyOS_BeforeFork();
  6670. pid = fork();
  6671. int saved_errno = errno;
  6672. if (pid == 0) {
  6673. /* child: this clobbers and resets the import lock. */
  6674. PyOS_AfterFork_Child();
  6675. } else {
  6676. warn_about_fork_with_threads("fork");
  6677. /* parent: release the import lock. */
  6678. PyOS_AfterFork_Parent();
  6679. }
  6680. if (pid == -1) {
  6681. errno = saved_errno;
  6682. return posix_error();
  6683. }
  6684. return PyLong_FromPid(pid);
  6685. }
  6686. #endif /* HAVE_FORK */
  6687. #ifdef HAVE_SCHED_H
  6688. #ifdef HAVE_SCHED_GET_PRIORITY_MAX
  6689. /*[clinic input]
  6690. os.sched_get_priority_max
  6691. policy: int
  6692. Get the maximum scheduling priority for policy.
  6693. [clinic start generated code]*/
  6694. static PyObject *
  6695. os_sched_get_priority_max_impl(PyObject *module, int policy)
  6696. /*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
  6697. {
  6698. int max;
  6699. max = sched_get_priority_max(policy);
  6700. if (max < 0)
  6701. return posix_error();
  6702. return PyLong_FromLong(max);
  6703. }
  6704. /*[clinic input]
  6705. os.sched_get_priority_min
  6706. policy: int
  6707. Get the minimum scheduling priority for policy.
  6708. [clinic start generated code]*/
  6709. static PyObject *
  6710. os_sched_get_priority_min_impl(PyObject *module, int policy)
  6711. /*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
  6712. {
  6713. int min = sched_get_priority_min(policy);
  6714. if (min < 0)
  6715. return posix_error();
  6716. return PyLong_FromLong(min);
  6717. }
  6718. #endif /* HAVE_SCHED_GET_PRIORITY_MAX */
  6719. #ifdef HAVE_SCHED_SETSCHEDULER
  6720. /*[clinic input]
  6721. os.sched_getscheduler
  6722. pid: pid_t
  6723. /
  6724. Get the scheduling policy for the process identified by pid.
  6725. Passing 0 for pid returns the scheduling policy for the calling process.
  6726. [clinic start generated code]*/
  6727. static PyObject *
  6728. os_sched_getscheduler_impl(PyObject *module, pid_t pid)
  6729. /*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
  6730. {
  6731. int policy;
  6732. policy = sched_getscheduler(pid);
  6733. if (policy < 0)
  6734. return posix_error();
  6735. return PyLong_FromLong(policy);
  6736. }
  6737. #endif /* HAVE_SCHED_SETSCHEDULER */
  6738. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  6739. /*[clinic input]
  6740. class os.sched_param "PyObject *" "SchedParamType"
  6741. @classmethod
  6742. os.sched_param.__new__
  6743. sched_priority: object
  6744. A scheduling parameter.
  6745. Currently has only one field: sched_priority
  6746. [clinic start generated code]*/
  6747. static PyObject *
  6748. os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
  6749. /*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
  6750. {
  6751. PyObject *res;
  6752. res = PyStructSequence_New(type);
  6753. if (!res)
  6754. return NULL;
  6755. PyStructSequence_SET_ITEM(res, 0, Py_NewRef(sched_priority));
  6756. return res;
  6757. }
  6758. PyDoc_VAR(os_sched_param__doc__);
  6759. static PyStructSequence_Field sched_param_fields[] = {
  6760. {"sched_priority", "the scheduling priority"},
  6761. {0}
  6762. };
  6763. static PyStructSequence_Desc sched_param_desc = {
  6764. "sched_param", /* name */
  6765. os_sched_param__doc__, /* doc */
  6766. sched_param_fields,
  6767. 1
  6768. };
  6769. static int
  6770. convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res)
  6771. {
  6772. long priority;
  6773. if (!Py_IS_TYPE(param, (PyTypeObject *)get_posix_state(module)->SchedParamType)) {
  6774. PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
  6775. return 0;
  6776. }
  6777. priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
  6778. if (priority == -1 && PyErr_Occurred())
  6779. return 0;
  6780. if (priority > INT_MAX || priority < INT_MIN) {
  6781. PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
  6782. return 0;
  6783. }
  6784. res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
  6785. return 1;
  6786. }
  6787. #endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
  6788. #ifdef HAVE_SCHED_SETSCHEDULER
  6789. /*[clinic input]
  6790. os.sched_setscheduler
  6791. pid: pid_t
  6792. policy: int
  6793. param as param_obj: object
  6794. /
  6795. Set the scheduling policy for the process identified by pid.
  6796. If pid is 0, the calling process is changed.
  6797. param is an instance of sched_param.
  6798. [clinic start generated code]*/
  6799. static PyObject *
  6800. os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
  6801. PyObject *param_obj)
  6802. /*[clinic end generated code: output=cde27faa55dc993e input=73013d731bd8fbe9]*/
  6803. {
  6804. struct sched_param param;
  6805. if (!convert_sched_param(module, param_obj, &param)) {
  6806. return NULL;
  6807. }
  6808. /*
  6809. ** sched_setscheduler() returns 0 in Linux, but the previous
  6810. ** scheduling policy under Solaris/Illumos, and others.
  6811. ** On error, -1 is returned in all Operating Systems.
  6812. */
  6813. if (sched_setscheduler(pid, policy, &param) == -1)
  6814. return posix_error();
  6815. Py_RETURN_NONE;
  6816. }
  6817. #endif /* HAVE_SCHED_SETSCHEDULER*/
  6818. #ifdef HAVE_SCHED_SETPARAM
  6819. /*[clinic input]
  6820. os.sched_getparam
  6821. pid: pid_t
  6822. /
  6823. Returns scheduling parameters for the process identified by pid.
  6824. If pid is 0, returns parameters for the calling process.
  6825. Return value is an instance of sched_param.
  6826. [clinic start generated code]*/
  6827. static PyObject *
  6828. os_sched_getparam_impl(PyObject *module, pid_t pid)
  6829. /*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
  6830. {
  6831. struct sched_param param;
  6832. PyObject *result;
  6833. PyObject *priority;
  6834. if (sched_getparam(pid, &param))
  6835. return posix_error();
  6836. PyObject *SchedParamType = get_posix_state(module)->SchedParamType;
  6837. result = PyStructSequence_New((PyTypeObject *)SchedParamType);
  6838. if (!result)
  6839. return NULL;
  6840. priority = PyLong_FromLong(param.sched_priority);
  6841. if (!priority) {
  6842. Py_DECREF(result);
  6843. return NULL;
  6844. }
  6845. PyStructSequence_SET_ITEM(result, 0, priority);
  6846. return result;
  6847. }
  6848. /*[clinic input]
  6849. os.sched_setparam
  6850. pid: pid_t
  6851. param as param_obj: object
  6852. /
  6853. Set scheduling parameters for the process identified by pid.
  6854. If pid is 0, sets parameters for the calling process.
  6855. param should be an instance of sched_param.
  6856. [clinic start generated code]*/
  6857. static PyObject *
  6858. os_sched_setparam_impl(PyObject *module, pid_t pid, PyObject *param_obj)
  6859. /*[clinic end generated code: output=f19fe020a53741c1 input=27b98337c8b2dcc7]*/
  6860. {
  6861. struct sched_param param;
  6862. if (!convert_sched_param(module, param_obj, &param)) {
  6863. return NULL;
  6864. }
  6865. if (sched_setparam(pid, &param))
  6866. return posix_error();
  6867. Py_RETURN_NONE;
  6868. }
  6869. #endif /* HAVE_SCHED_SETPARAM */
  6870. #ifdef HAVE_SCHED_RR_GET_INTERVAL
  6871. /*[clinic input]
  6872. os.sched_rr_get_interval -> double
  6873. pid: pid_t
  6874. /
  6875. Return the round-robin quantum for the process identified by pid, in seconds.
  6876. Value returned is a float.
  6877. [clinic start generated code]*/
  6878. static double
  6879. os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
  6880. /*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
  6881. {
  6882. struct timespec interval;
  6883. if (sched_rr_get_interval(pid, &interval)) {
  6884. posix_error();
  6885. return -1.0;
  6886. }
  6887. #ifdef _Py_MEMORY_SANITIZER
  6888. __msan_unpoison(&interval, sizeof(interval));
  6889. #endif
  6890. return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
  6891. }
  6892. #endif /* HAVE_SCHED_RR_GET_INTERVAL */
  6893. /*[clinic input]
  6894. os.sched_yield
  6895. Voluntarily relinquish the CPU.
  6896. [clinic start generated code]*/
  6897. static PyObject *
  6898. os_sched_yield_impl(PyObject *module)
  6899. /*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
  6900. {
  6901. int result;
  6902. Py_BEGIN_ALLOW_THREADS
  6903. result = sched_yield();
  6904. Py_END_ALLOW_THREADS
  6905. if (result < 0) {
  6906. return posix_error();
  6907. }
  6908. Py_RETURN_NONE;
  6909. }
  6910. #ifdef HAVE_SCHED_SETAFFINITY
  6911. /* The minimum number of CPUs allocated in a cpu_set_t */
  6912. static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
  6913. /*[clinic input]
  6914. os.sched_setaffinity
  6915. pid: pid_t
  6916. mask : object
  6917. /
  6918. Set the CPU affinity of the process identified by pid to mask.
  6919. mask should be an iterable of integers identifying CPUs.
  6920. [clinic start generated code]*/
  6921. static PyObject *
  6922. os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
  6923. /*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
  6924. {
  6925. int ncpus;
  6926. size_t setsize;
  6927. cpu_set_t *cpu_set = NULL;
  6928. PyObject *iterator = NULL, *item;
  6929. iterator = PyObject_GetIter(mask);
  6930. if (iterator == NULL)
  6931. return NULL;
  6932. ncpus = NCPUS_START;
  6933. setsize = CPU_ALLOC_SIZE(ncpus);
  6934. cpu_set = CPU_ALLOC(ncpus);
  6935. if (cpu_set == NULL) {
  6936. PyErr_NoMemory();
  6937. goto error;
  6938. }
  6939. CPU_ZERO_S(setsize, cpu_set);
  6940. while ((item = PyIter_Next(iterator))) {
  6941. long cpu;
  6942. if (!PyLong_Check(item)) {
  6943. PyErr_Format(PyExc_TypeError,
  6944. "expected an iterator of ints, "
  6945. "but iterator yielded %R",
  6946. Py_TYPE(item));
  6947. Py_DECREF(item);
  6948. goto error;
  6949. }
  6950. cpu = PyLong_AsLong(item);
  6951. Py_DECREF(item);
  6952. if (cpu < 0) {
  6953. if (!PyErr_Occurred())
  6954. PyErr_SetString(PyExc_ValueError, "negative CPU number");
  6955. goto error;
  6956. }
  6957. if (cpu > INT_MAX - 1) {
  6958. PyErr_SetString(PyExc_OverflowError, "CPU number too large");
  6959. goto error;
  6960. }
  6961. if (cpu >= ncpus) {
  6962. /* Grow CPU mask to fit the CPU number */
  6963. int newncpus = ncpus;
  6964. cpu_set_t *newmask;
  6965. size_t newsetsize;
  6966. while (newncpus <= cpu) {
  6967. if (newncpus > INT_MAX / 2)
  6968. newncpus = cpu + 1;
  6969. else
  6970. newncpus = newncpus * 2;
  6971. }
  6972. newmask = CPU_ALLOC(newncpus);
  6973. if (newmask == NULL) {
  6974. PyErr_NoMemory();
  6975. goto error;
  6976. }
  6977. newsetsize = CPU_ALLOC_SIZE(newncpus);
  6978. CPU_ZERO_S(newsetsize, newmask);
  6979. memcpy(newmask, cpu_set, setsize);
  6980. CPU_FREE(cpu_set);
  6981. setsize = newsetsize;
  6982. cpu_set = newmask;
  6983. ncpus = newncpus;
  6984. }
  6985. CPU_SET_S(cpu, setsize, cpu_set);
  6986. }
  6987. if (PyErr_Occurred()) {
  6988. goto error;
  6989. }
  6990. Py_CLEAR(iterator);
  6991. if (sched_setaffinity(pid, setsize, cpu_set)) {
  6992. posix_error();
  6993. goto error;
  6994. }
  6995. CPU_FREE(cpu_set);
  6996. Py_RETURN_NONE;
  6997. error:
  6998. if (cpu_set)
  6999. CPU_FREE(cpu_set);
  7000. Py_XDECREF(iterator);
  7001. return NULL;
  7002. }
  7003. /*[clinic input]
  7004. os.sched_getaffinity
  7005. pid: pid_t
  7006. /
  7007. Return the affinity of the process identified by pid (or the current process if zero).
  7008. The affinity is returned as a set of CPU identifiers.
  7009. [clinic start generated code]*/
  7010. static PyObject *
  7011. os_sched_getaffinity_impl(PyObject *module, pid_t pid)
  7012. /*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
  7013. {
  7014. int cpu, ncpus, count;
  7015. size_t setsize;
  7016. cpu_set_t *mask = NULL;
  7017. PyObject *res = NULL;
  7018. ncpus = NCPUS_START;
  7019. while (1) {
  7020. setsize = CPU_ALLOC_SIZE(ncpus);
  7021. mask = CPU_ALLOC(ncpus);
  7022. if (mask == NULL)
  7023. return PyErr_NoMemory();
  7024. if (sched_getaffinity(pid, setsize, mask) == 0)
  7025. break;
  7026. CPU_FREE(mask);
  7027. if (errno != EINVAL)
  7028. return posix_error();
  7029. if (ncpus > INT_MAX / 2) {
  7030. PyErr_SetString(PyExc_OverflowError, "could not allocate "
  7031. "a large enough CPU set");
  7032. return NULL;
  7033. }
  7034. ncpus = ncpus * 2;
  7035. }
  7036. res = PySet_New(NULL);
  7037. if (res == NULL)
  7038. goto error;
  7039. for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
  7040. if (CPU_ISSET_S(cpu, setsize, mask)) {
  7041. PyObject *cpu_num = PyLong_FromLong(cpu);
  7042. --count;
  7043. if (cpu_num == NULL)
  7044. goto error;
  7045. if (PySet_Add(res, cpu_num)) {
  7046. Py_DECREF(cpu_num);
  7047. goto error;
  7048. }
  7049. Py_DECREF(cpu_num);
  7050. }
  7051. }
  7052. CPU_FREE(mask);
  7053. return res;
  7054. error:
  7055. if (mask)
  7056. CPU_FREE(mask);
  7057. Py_XDECREF(res);
  7058. return NULL;
  7059. }
  7060. #endif /* HAVE_SCHED_SETAFFINITY */
  7061. #endif /* HAVE_SCHED_H */
  7062. /* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
  7063. #if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
  7064. # define DEV_PTY_FILE "/dev/ptc"
  7065. # define HAVE_DEV_PTMX
  7066. #else
  7067. # define DEV_PTY_FILE "/dev/ptmx"
  7068. #endif
  7069. #if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX)
  7070. #ifdef HAVE_PTY_H
  7071. #include <pty.h>
  7072. #ifdef HAVE_UTMP_H
  7073. #include <utmp.h>
  7074. #endif /* HAVE_UTMP_H */
  7075. #elif defined(HAVE_LIBUTIL_H)
  7076. #include <libutil.h>
  7077. #elif defined(HAVE_UTIL_H)
  7078. #include <util.h>
  7079. #endif /* HAVE_PTY_H */
  7080. #ifdef HAVE_STROPTS_H
  7081. #include <stropts.h>
  7082. #else
  7083. #define __SID ('S' << 8)
  7084. #define I_PUSH (__SID | 2)
  7085. #endif
  7086. #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX) */
  7087. #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
  7088. /*[clinic input]
  7089. os.openpty
  7090. Open a pseudo-terminal.
  7091. Return a tuple of (master_fd, slave_fd) containing open file descriptors
  7092. for both the master and slave ends.
  7093. [clinic start generated code]*/
  7094. static PyObject *
  7095. os_openpty_impl(PyObject *module)
  7096. /*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
  7097. {
  7098. int master_fd = -1, slave_fd = -1;
  7099. #ifndef HAVE_OPENPTY
  7100. char * slave_name;
  7101. #endif
  7102. #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
  7103. PyOS_sighandler_t sig_saved;
  7104. #if defined(__sun) && defined(__SVR4)
  7105. extern char *ptsname(int fildes);
  7106. #endif
  7107. #endif
  7108. #ifdef HAVE_OPENPTY
  7109. if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
  7110. goto posix_error;
  7111. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7112. goto error;
  7113. if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
  7114. goto error;
  7115. #elif defined(HAVE__GETPTY)
  7116. slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
  7117. if (slave_name == NULL)
  7118. goto posix_error;
  7119. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7120. goto error;
  7121. slave_fd = _Py_open(slave_name, O_RDWR);
  7122. if (slave_fd < 0)
  7123. goto error;
  7124. #else
  7125. master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
  7126. if (master_fd < 0)
  7127. goto posix_error;
  7128. sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
  7129. /* change permission of slave */
  7130. if (grantpt(master_fd) < 0) {
  7131. int saved_errno = errno;
  7132. PyOS_setsig(SIGCHLD, sig_saved);
  7133. errno = saved_errno;
  7134. goto posix_error;
  7135. }
  7136. /* unlock slave */
  7137. if (unlockpt(master_fd) < 0) {
  7138. int saved_errno = errno;
  7139. PyOS_setsig(SIGCHLD, sig_saved);
  7140. errno = saved_errno;
  7141. goto posix_error;
  7142. }
  7143. PyOS_setsig(SIGCHLD, sig_saved);
  7144. slave_name = ptsname(master_fd); /* get name of slave */
  7145. if (slave_name == NULL)
  7146. goto posix_error;
  7147. slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
  7148. if (slave_fd == -1)
  7149. goto error;
  7150. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7151. goto posix_error;
  7152. #if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
  7153. ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
  7154. ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
  7155. #ifndef __hpux
  7156. ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
  7157. #endif /* __hpux */
  7158. #endif /* HAVE_CYGWIN */
  7159. #endif /* HAVE_OPENPTY */
  7160. return Py_BuildValue("(ii)", master_fd, slave_fd);
  7161. posix_error:
  7162. posix_error();
  7163. error:
  7164. if (master_fd != -1)
  7165. close(master_fd);
  7166. if (slave_fd != -1)
  7167. close(slave_fd);
  7168. return NULL;
  7169. }
  7170. #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
  7171. #if defined(HAVE_SETSID) && defined(TIOCSCTTY)
  7172. #define HAVE_FALLBACK_LOGIN_TTY 1
  7173. #endif /* defined(HAVE_SETSID) && defined(TIOCSCTTY) */
  7174. #if defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY)
  7175. /*[clinic input]
  7176. os.login_tty
  7177. fd: fildes
  7178. /
  7179. Prepare the tty of which fd is a file descriptor for a new login session.
  7180. Make the calling process a session leader; make the tty the
  7181. controlling tty, the stdin, the stdout, and the stderr of the
  7182. calling process; close fd.
  7183. [clinic start generated code]*/
  7184. static PyObject *
  7185. os_login_tty_impl(PyObject *module, int fd)
  7186. /*[clinic end generated code: output=495a79911b4cc1bc input=5f298565099903a2]*/
  7187. {
  7188. #ifdef HAVE_LOGIN_TTY
  7189. if (login_tty(fd) == -1) {
  7190. return posix_error();
  7191. }
  7192. #else /* defined(HAVE_FALLBACK_LOGIN_TTY) */
  7193. /* Establish a new session. */
  7194. if (setsid() == -1) {
  7195. return posix_error();
  7196. }
  7197. /* The tty becomes the controlling terminal. */
  7198. if (ioctl(fd, TIOCSCTTY, (char *)NULL) == -1) {
  7199. return posix_error();
  7200. }
  7201. /* The tty becomes stdin/stdout/stderr */
  7202. if (dup2(fd, 0) == -1 || dup2(fd, 1) == -1 || dup2(fd, 2) == -1) {
  7203. return posix_error();
  7204. }
  7205. if (fd > 2) {
  7206. close(fd);
  7207. }
  7208. #endif /* HAVE_LOGIN_TTY */
  7209. Py_RETURN_NONE;
  7210. }
  7211. #endif /* defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY) */
  7212. #ifdef HAVE_FORKPTY
  7213. /*[clinic input]
  7214. os.forkpty
  7215. Fork a new process with a new pseudo-terminal as controlling tty.
  7216. Returns a tuple of (pid, master_fd).
  7217. Like fork(), return pid of 0 to the child process,
  7218. and pid of child to the parent process.
  7219. To both, return fd of newly opened pseudo-terminal.
  7220. [clinic start generated code]*/
  7221. static PyObject *
  7222. os_forkpty_impl(PyObject *module)
  7223. /*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
  7224. {
  7225. int master_fd = -1;
  7226. pid_t pid;
  7227. PyInterpreterState *interp = _PyInterpreterState_GET();
  7228. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  7229. PyErr_SetString(PyExc_RuntimeError,
  7230. "can't fork at interpreter shutdown");
  7231. return NULL;
  7232. }
  7233. if (!_Py_IsMainInterpreter(interp)) {
  7234. PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
  7235. return NULL;
  7236. }
  7237. if (PySys_Audit("os.forkpty", NULL) < 0) {
  7238. return NULL;
  7239. }
  7240. PyOS_BeforeFork();
  7241. pid = forkpty(&master_fd, NULL, NULL, NULL);
  7242. if (pid == 0) {
  7243. /* child: this clobbers and resets the import lock. */
  7244. PyOS_AfterFork_Child();
  7245. } else {
  7246. warn_about_fork_with_threads("forkpty");
  7247. /* parent: release the import lock. */
  7248. PyOS_AfterFork_Parent();
  7249. }
  7250. if (pid == -1) {
  7251. return posix_error();
  7252. }
  7253. return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
  7254. }
  7255. #endif /* HAVE_FORKPTY */
  7256. #ifdef HAVE_GETEGID
  7257. /*[clinic input]
  7258. os.getegid
  7259. Return the current process's effective group id.
  7260. [clinic start generated code]*/
  7261. static PyObject *
  7262. os_getegid_impl(PyObject *module)
  7263. /*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
  7264. {
  7265. return _PyLong_FromGid(getegid());
  7266. }
  7267. #endif /* HAVE_GETEGID */
  7268. #ifdef HAVE_GETEUID
  7269. /*[clinic input]
  7270. os.geteuid
  7271. Return the current process's effective user id.
  7272. [clinic start generated code]*/
  7273. static PyObject *
  7274. os_geteuid_impl(PyObject *module)
  7275. /*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
  7276. {
  7277. return _PyLong_FromUid(geteuid());
  7278. }
  7279. #endif /* HAVE_GETEUID */
  7280. #ifdef HAVE_GETGID
  7281. /*[clinic input]
  7282. os.getgid
  7283. Return the current process's group id.
  7284. [clinic start generated code]*/
  7285. static PyObject *
  7286. os_getgid_impl(PyObject *module)
  7287. /*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
  7288. {
  7289. return _PyLong_FromGid(getgid());
  7290. }
  7291. #endif /* HAVE_GETGID */
  7292. #if defined(HAVE_GETPID)
  7293. /*[clinic input]
  7294. os.getpid
  7295. Return the current process id.
  7296. [clinic start generated code]*/
  7297. static PyObject *
  7298. os_getpid_impl(PyObject *module)
  7299. /*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
  7300. {
  7301. #if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  7302. return PyLong_FromPid(getpid());
  7303. #else
  7304. return PyLong_FromUnsignedLong(GetCurrentProcessId());
  7305. #endif
  7306. }
  7307. #endif /* defined(HAVE_GETPID) */
  7308. #ifdef NGROUPS_MAX
  7309. #define MAX_GROUPS NGROUPS_MAX
  7310. #else
  7311. /* defined to be 16 on Solaris7, so this should be a small number */
  7312. #define MAX_GROUPS 64
  7313. #endif
  7314. #ifdef HAVE_GETGROUPLIST
  7315. #ifdef __APPLE__
  7316. /*[clinic input]
  7317. os.getgrouplist
  7318. user: str
  7319. username to lookup
  7320. group as basegid: int
  7321. base group id of the user
  7322. /
  7323. Returns a list of groups to which a user belongs.
  7324. [clinic start generated code]*/
  7325. static PyObject *
  7326. os_getgrouplist_impl(PyObject *module, const char *user, int basegid)
  7327. /*[clinic end generated code: output=6e734697b8c26de0 input=f8d870374b09a490]*/
  7328. #else
  7329. /*[clinic input]
  7330. os.getgrouplist
  7331. user: str
  7332. username to lookup
  7333. group as basegid: gid_t
  7334. base group id of the user
  7335. /
  7336. Returns a list of groups to which a user belongs.
  7337. [clinic start generated code]*/
  7338. static PyObject *
  7339. os_getgrouplist_impl(PyObject *module, const char *user, gid_t basegid)
  7340. /*[clinic end generated code: output=0ebd7fb70115575b input=cc61d5c20b08958d]*/
  7341. #endif
  7342. {
  7343. int i, ngroups;
  7344. PyObject *list;
  7345. #ifdef __APPLE__
  7346. int *groups;
  7347. #else
  7348. gid_t *groups;
  7349. #endif
  7350. /*
  7351. * NGROUPS_MAX is defined by POSIX.1 as the maximum
  7352. * number of supplimental groups a users can belong to.
  7353. * We have to increment it by one because
  7354. * getgrouplist() returns both the supplemental groups
  7355. * and the primary group, i.e. all of the groups the
  7356. * user belongs to.
  7357. */
  7358. ngroups = 1 + MAX_GROUPS;
  7359. while (1) {
  7360. #ifdef __APPLE__
  7361. groups = PyMem_New(int, ngroups);
  7362. #else
  7363. groups = PyMem_New(gid_t, ngroups);
  7364. #endif
  7365. if (groups == NULL) {
  7366. return PyErr_NoMemory();
  7367. }
  7368. int old_ngroups = ngroups;
  7369. if (getgrouplist(user, basegid, groups, &ngroups) != -1) {
  7370. /* Success */
  7371. break;
  7372. }
  7373. /* getgrouplist() fails if the group list is too small */
  7374. PyMem_Free(groups);
  7375. if (ngroups > old_ngroups) {
  7376. /* If the group list is too small, the glibc implementation of
  7377. getgrouplist() sets ngroups to the total number of groups and
  7378. returns -1. */
  7379. }
  7380. else {
  7381. /* Double the group list size */
  7382. if (ngroups > INT_MAX / 2) {
  7383. return PyErr_NoMemory();
  7384. }
  7385. ngroups *= 2;
  7386. }
  7387. /* Retry getgrouplist() with a larger group list */
  7388. }
  7389. #ifdef _Py_MEMORY_SANITIZER
  7390. /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
  7391. __msan_unpoison(&ngroups, sizeof(ngroups));
  7392. __msan_unpoison(groups, ngroups*sizeof(*groups));
  7393. #endif
  7394. list = PyList_New(ngroups);
  7395. if (list == NULL) {
  7396. PyMem_Free(groups);
  7397. return NULL;
  7398. }
  7399. for (i = 0; i < ngroups; i++) {
  7400. #ifdef __APPLE__
  7401. PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
  7402. #else
  7403. PyObject *o = _PyLong_FromGid(groups[i]);
  7404. #endif
  7405. if (o == NULL) {
  7406. Py_DECREF(list);
  7407. PyMem_Free(groups);
  7408. return NULL;
  7409. }
  7410. PyList_SET_ITEM(list, i, o);
  7411. }
  7412. PyMem_Free(groups);
  7413. return list;
  7414. }
  7415. #endif /* HAVE_GETGROUPLIST */
  7416. #ifdef HAVE_GETGROUPS
  7417. /*[clinic input]
  7418. os.getgroups
  7419. Return list of supplemental group IDs for the process.
  7420. [clinic start generated code]*/
  7421. static PyObject *
  7422. os_getgroups_impl(PyObject *module)
  7423. /*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
  7424. {
  7425. // Call getgroups with length 0 to get the actual number of groups
  7426. int n = getgroups(0, NULL);
  7427. if (n < 0) {
  7428. return posix_error();
  7429. }
  7430. if (n == 0) {
  7431. return PyList_New(0);
  7432. }
  7433. gid_t *grouplist = PyMem_New(gid_t, n);
  7434. if (grouplist == NULL) {
  7435. return PyErr_NoMemory();
  7436. }
  7437. n = getgroups(n, grouplist);
  7438. if (n == -1) {
  7439. posix_error();
  7440. PyMem_Free(grouplist);
  7441. return NULL;
  7442. }
  7443. PyObject *result = PyList_New(n);
  7444. if (result == NULL) {
  7445. goto error;
  7446. }
  7447. for (int i = 0; i < n; ++i) {
  7448. PyObject *group = _PyLong_FromGid(grouplist[i]);
  7449. if (group == NULL) {
  7450. goto error;
  7451. }
  7452. PyList_SET_ITEM(result, i, group);
  7453. }
  7454. PyMem_Free(grouplist);
  7455. return result;
  7456. error:
  7457. PyMem_Free(grouplist);
  7458. Py_XDECREF(result);
  7459. return NULL;
  7460. }
  7461. #endif /* HAVE_GETGROUPS */
  7462. #ifdef HAVE_INITGROUPS
  7463. #ifdef __APPLE__
  7464. /*[clinic input]
  7465. os.initgroups
  7466. username as oname: FSConverter
  7467. gid: int
  7468. /
  7469. Initialize the group access list.
  7470. Call the system initgroups() to initialize the group access list with all of
  7471. the groups of which the specified username is a member, plus the specified
  7472. group id.
  7473. [clinic start generated code]*/
  7474. static PyObject *
  7475. os_initgroups_impl(PyObject *module, PyObject *oname, int gid)
  7476. /*[clinic end generated code: output=7f074d30a425fd3a input=df3d54331b0af204]*/
  7477. #else
  7478. /*[clinic input]
  7479. os.initgroups
  7480. username as oname: FSConverter
  7481. gid: gid_t
  7482. /
  7483. Initialize the group access list.
  7484. Call the system initgroups() to initialize the group access list with all of
  7485. the groups of which the specified username is a member, plus the specified
  7486. group id.
  7487. [clinic start generated code]*/
  7488. static PyObject *
  7489. os_initgroups_impl(PyObject *module, PyObject *oname, gid_t gid)
  7490. /*[clinic end generated code: output=59341244521a9e3f input=0cb91bdc59a4c564]*/
  7491. #endif
  7492. {
  7493. const char *username = PyBytes_AS_STRING(oname);
  7494. if (initgroups(username, gid) == -1)
  7495. return PyErr_SetFromErrno(PyExc_OSError);
  7496. Py_RETURN_NONE;
  7497. }
  7498. #endif /* HAVE_INITGROUPS */
  7499. #ifdef HAVE_GETPGID
  7500. /*[clinic input]
  7501. os.getpgid
  7502. pid: pid_t
  7503. Call the system call getpgid(), and return the result.
  7504. [clinic start generated code]*/
  7505. static PyObject *
  7506. os_getpgid_impl(PyObject *module, pid_t pid)
  7507. /*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
  7508. {
  7509. pid_t pgid = getpgid(pid);
  7510. if (pgid < 0)
  7511. return posix_error();
  7512. return PyLong_FromPid(pgid);
  7513. }
  7514. #endif /* HAVE_GETPGID */
  7515. #ifdef HAVE_GETPGRP
  7516. /*[clinic input]
  7517. os.getpgrp
  7518. Return the current process group id.
  7519. [clinic start generated code]*/
  7520. static PyObject *
  7521. os_getpgrp_impl(PyObject *module)
  7522. /*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
  7523. {
  7524. #ifdef GETPGRP_HAVE_ARG
  7525. return PyLong_FromPid(getpgrp(0));
  7526. #else /* GETPGRP_HAVE_ARG */
  7527. return PyLong_FromPid(getpgrp());
  7528. #endif /* GETPGRP_HAVE_ARG */
  7529. }
  7530. #endif /* HAVE_GETPGRP */
  7531. #ifdef HAVE_SETPGRP
  7532. /*[clinic input]
  7533. os.setpgrp
  7534. Make the current process the leader of its process group.
  7535. [clinic start generated code]*/
  7536. static PyObject *
  7537. os_setpgrp_impl(PyObject *module)
  7538. /*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
  7539. {
  7540. #ifdef SETPGRP_HAVE_ARG
  7541. if (setpgrp(0, 0) < 0)
  7542. #else /* SETPGRP_HAVE_ARG */
  7543. if (setpgrp() < 0)
  7544. #endif /* SETPGRP_HAVE_ARG */
  7545. return posix_error();
  7546. Py_RETURN_NONE;
  7547. }
  7548. #endif /* HAVE_SETPGRP */
  7549. #ifdef HAVE_GETPPID
  7550. #ifdef MS_WINDOWS
  7551. #include <processsnapshot.h>
  7552. static PyObject*
  7553. win32_getppid(void)
  7554. {
  7555. DWORD error;
  7556. PyObject* result = NULL;
  7557. HANDLE process = GetCurrentProcess();
  7558. HPSS snapshot = NULL;
  7559. error = PssCaptureSnapshot(process, PSS_CAPTURE_NONE, 0, &snapshot);
  7560. if (error != ERROR_SUCCESS) {
  7561. return PyErr_SetFromWindowsErr(error);
  7562. }
  7563. PSS_PROCESS_INFORMATION info;
  7564. error = PssQuerySnapshot(snapshot, PSS_QUERY_PROCESS_INFORMATION, &info,
  7565. sizeof(info));
  7566. if (error == ERROR_SUCCESS) {
  7567. result = PyLong_FromUnsignedLong(info.ParentProcessId);
  7568. }
  7569. else {
  7570. result = PyErr_SetFromWindowsErr(error);
  7571. }
  7572. PssFreeSnapshot(process, snapshot);
  7573. return result;
  7574. }
  7575. #endif /*MS_WINDOWS*/
  7576. /*[clinic input]
  7577. os.getppid
  7578. Return the parent's process id.
  7579. If the parent process has already exited, Windows machines will still
  7580. return its id; others systems will return the id of the 'init' process (1).
  7581. [clinic start generated code]*/
  7582. static PyObject *
  7583. os_getppid_impl(PyObject *module)
  7584. /*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
  7585. {
  7586. #ifdef MS_WINDOWS
  7587. return win32_getppid();
  7588. #else
  7589. return PyLong_FromPid(getppid());
  7590. #endif
  7591. }
  7592. #endif /* HAVE_GETPPID */
  7593. #ifdef HAVE_GETLOGIN
  7594. /*[clinic input]
  7595. os.getlogin
  7596. Return the actual login name.
  7597. [clinic start generated code]*/
  7598. static PyObject *
  7599. os_getlogin_impl(PyObject *module)
  7600. /*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
  7601. {
  7602. PyObject *result = NULL;
  7603. #ifdef MS_WINDOWS
  7604. wchar_t user_name[UNLEN + 1];
  7605. DWORD num_chars = Py_ARRAY_LENGTH(user_name);
  7606. if (GetUserNameW(user_name, &num_chars)) {
  7607. /* num_chars is the number of unicode chars plus null terminator */
  7608. result = PyUnicode_FromWideChar(user_name, num_chars - 1);
  7609. }
  7610. else
  7611. result = PyErr_SetFromWindowsErr(GetLastError());
  7612. #else
  7613. char *name;
  7614. int old_errno = errno;
  7615. errno = 0;
  7616. name = getlogin();
  7617. if (name == NULL) {
  7618. if (errno)
  7619. posix_error();
  7620. else
  7621. PyErr_SetString(PyExc_OSError, "unable to determine login name");
  7622. }
  7623. else
  7624. result = PyUnicode_DecodeFSDefault(name);
  7625. errno = old_errno;
  7626. #endif
  7627. return result;
  7628. }
  7629. #endif /* HAVE_GETLOGIN */
  7630. #ifdef HAVE_GETUID
  7631. /*[clinic input]
  7632. os.getuid
  7633. Return the current process's user id.
  7634. [clinic start generated code]*/
  7635. static PyObject *
  7636. os_getuid_impl(PyObject *module)
  7637. /*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
  7638. {
  7639. return _PyLong_FromUid(getuid());
  7640. }
  7641. #endif /* HAVE_GETUID */
  7642. #ifdef MS_WINDOWS
  7643. #define HAVE_KILL
  7644. #endif /* MS_WINDOWS */
  7645. #ifdef HAVE_KILL
  7646. /*[clinic input]
  7647. os.kill
  7648. pid: pid_t
  7649. signal: Py_ssize_t
  7650. /
  7651. Kill a process with a signal.
  7652. [clinic start generated code]*/
  7653. static PyObject *
  7654. os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
  7655. /*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
  7656. {
  7657. if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
  7658. return NULL;
  7659. }
  7660. #ifndef MS_WINDOWS
  7661. if (kill(pid, (int)signal) == -1) {
  7662. return posix_error();
  7663. }
  7664. // Check immediately if the signal was sent to the current process.
  7665. // Don't micro-optimize pid == getpid(), since PyErr_SetString() check
  7666. // is cheap.
  7667. if (PyErr_CheckSignals()) {
  7668. return NULL;
  7669. }
  7670. Py_RETURN_NONE;
  7671. #else /* !MS_WINDOWS */
  7672. PyObject *result;
  7673. DWORD sig = (DWORD)signal;
  7674. DWORD err;
  7675. HANDLE handle;
  7676. #ifdef HAVE_WINDOWS_CONSOLE_IO
  7677. /* Console processes which share a common console can be sent CTRL+C or
  7678. CTRL+BREAK events, provided they handle said events. */
  7679. if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
  7680. if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
  7681. err = GetLastError();
  7682. PyErr_SetFromWindowsErr(err);
  7683. }
  7684. else {
  7685. Py_RETURN_NONE;
  7686. }
  7687. }
  7688. #endif /* HAVE_WINDOWS_CONSOLE_IO */
  7689. /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
  7690. attempt to open and terminate the process. */
  7691. handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
  7692. if (handle == NULL) {
  7693. err = GetLastError();
  7694. return PyErr_SetFromWindowsErr(err);
  7695. }
  7696. if (TerminateProcess(handle, sig) == 0) {
  7697. err = GetLastError();
  7698. result = PyErr_SetFromWindowsErr(err);
  7699. } else {
  7700. result = Py_NewRef(Py_None);
  7701. }
  7702. CloseHandle(handle);
  7703. return result;
  7704. #endif /* !MS_WINDOWS */
  7705. }
  7706. #endif /* HAVE_KILL */
  7707. #ifdef HAVE_KILLPG
  7708. /*[clinic input]
  7709. os.killpg
  7710. pgid: pid_t
  7711. signal: int
  7712. /
  7713. Kill a process group with a signal.
  7714. [clinic start generated code]*/
  7715. static PyObject *
  7716. os_killpg_impl(PyObject *module, pid_t pgid, int signal)
  7717. /*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
  7718. {
  7719. if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
  7720. return NULL;
  7721. }
  7722. /* XXX some man pages make the `pgid` parameter an int, others
  7723. a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
  7724. take the same type. Moreover, pid_t is always at least as wide as
  7725. int (else compilation of this module fails), which is safe. */
  7726. if (killpg(pgid, signal) == -1)
  7727. return posix_error();
  7728. Py_RETURN_NONE;
  7729. }
  7730. #endif /* HAVE_KILLPG */
  7731. #ifdef HAVE_PLOCK
  7732. #ifdef HAVE_SYS_LOCK_H
  7733. #include <sys/lock.h>
  7734. #endif
  7735. /*[clinic input]
  7736. os.plock
  7737. op: int
  7738. /
  7739. Lock program segments into memory.");
  7740. [clinic start generated code]*/
  7741. static PyObject *
  7742. os_plock_impl(PyObject *module, int op)
  7743. /*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
  7744. {
  7745. if (plock(op) == -1)
  7746. return posix_error();
  7747. Py_RETURN_NONE;
  7748. }
  7749. #endif /* HAVE_PLOCK */
  7750. #ifdef HAVE_SETUID
  7751. /*[clinic input]
  7752. os.setuid
  7753. uid: uid_t
  7754. /
  7755. Set the current process's user id.
  7756. [clinic start generated code]*/
  7757. static PyObject *
  7758. os_setuid_impl(PyObject *module, uid_t uid)
  7759. /*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
  7760. {
  7761. if (setuid(uid) < 0)
  7762. return posix_error();
  7763. Py_RETURN_NONE;
  7764. }
  7765. #endif /* HAVE_SETUID */
  7766. #ifdef HAVE_SETEUID
  7767. /*[clinic input]
  7768. os.seteuid
  7769. euid: uid_t
  7770. /
  7771. Set the current process's effective user id.
  7772. [clinic start generated code]*/
  7773. static PyObject *
  7774. os_seteuid_impl(PyObject *module, uid_t euid)
  7775. /*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
  7776. {
  7777. if (seteuid(euid) < 0)
  7778. return posix_error();
  7779. Py_RETURN_NONE;
  7780. }
  7781. #endif /* HAVE_SETEUID */
  7782. #ifdef HAVE_SETEGID
  7783. /*[clinic input]
  7784. os.setegid
  7785. egid: gid_t
  7786. /
  7787. Set the current process's effective group id.
  7788. [clinic start generated code]*/
  7789. static PyObject *
  7790. os_setegid_impl(PyObject *module, gid_t egid)
  7791. /*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
  7792. {
  7793. if (setegid(egid) < 0)
  7794. return posix_error();
  7795. Py_RETURN_NONE;
  7796. }
  7797. #endif /* HAVE_SETEGID */
  7798. #ifdef HAVE_SETREUID
  7799. /*[clinic input]
  7800. os.setreuid
  7801. ruid: uid_t
  7802. euid: uid_t
  7803. /
  7804. Set the current process's real and effective user ids.
  7805. [clinic start generated code]*/
  7806. static PyObject *
  7807. os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
  7808. /*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
  7809. {
  7810. if (setreuid(ruid, euid) < 0) {
  7811. return posix_error();
  7812. } else {
  7813. Py_RETURN_NONE;
  7814. }
  7815. }
  7816. #endif /* HAVE_SETREUID */
  7817. #ifdef HAVE_SETREGID
  7818. /*[clinic input]
  7819. os.setregid
  7820. rgid: gid_t
  7821. egid: gid_t
  7822. /
  7823. Set the current process's real and effective group ids.
  7824. [clinic start generated code]*/
  7825. static PyObject *
  7826. os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
  7827. /*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
  7828. {
  7829. if (setregid(rgid, egid) < 0)
  7830. return posix_error();
  7831. Py_RETURN_NONE;
  7832. }
  7833. #endif /* HAVE_SETREGID */
  7834. #ifdef HAVE_SETGID
  7835. /*[clinic input]
  7836. os.setgid
  7837. gid: gid_t
  7838. /
  7839. Set the current process's group id.
  7840. [clinic start generated code]*/
  7841. static PyObject *
  7842. os_setgid_impl(PyObject *module, gid_t gid)
  7843. /*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
  7844. {
  7845. if (setgid(gid) < 0)
  7846. return posix_error();
  7847. Py_RETURN_NONE;
  7848. }
  7849. #endif /* HAVE_SETGID */
  7850. #ifdef HAVE_SETGROUPS
  7851. /*[clinic input]
  7852. os.setgroups
  7853. groups: object
  7854. /
  7855. Set the groups of the current process to list.
  7856. [clinic start generated code]*/
  7857. static PyObject *
  7858. os_setgroups(PyObject *module, PyObject *groups)
  7859. /*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
  7860. {
  7861. if (!PySequence_Check(groups)) {
  7862. PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
  7863. return NULL;
  7864. }
  7865. Py_ssize_t len = PySequence_Size(groups);
  7866. if (len < 0) {
  7867. return NULL;
  7868. }
  7869. if (len > MAX_GROUPS) {
  7870. PyErr_SetString(PyExc_ValueError, "too many groups");
  7871. return NULL;
  7872. }
  7873. gid_t *grouplist = PyMem_New(gid_t, len);
  7874. for (Py_ssize_t i = 0; i < len; i++) {
  7875. PyObject *elem;
  7876. elem = PySequence_GetItem(groups, i);
  7877. if (!elem) {
  7878. PyMem_Free(grouplist);
  7879. return NULL;
  7880. }
  7881. if (!PyLong_Check(elem)) {
  7882. PyErr_SetString(PyExc_TypeError,
  7883. "groups must be integers");
  7884. Py_DECREF(elem);
  7885. PyMem_Free(grouplist);
  7886. return NULL;
  7887. } else {
  7888. if (!_Py_Gid_Converter(elem, &grouplist[i])) {
  7889. Py_DECREF(elem);
  7890. PyMem_Free(grouplist);
  7891. return NULL;
  7892. }
  7893. }
  7894. Py_DECREF(elem);
  7895. }
  7896. if (setgroups(len, grouplist) < 0) {
  7897. posix_error();
  7898. PyMem_Free(grouplist);
  7899. return NULL;
  7900. }
  7901. PyMem_Free(grouplist);
  7902. Py_RETURN_NONE;
  7903. }
  7904. #endif /* HAVE_SETGROUPS */
  7905. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  7906. static PyObject *
  7907. wait_helper(PyObject *module, pid_t pid, int status, struct rusage *ru)
  7908. {
  7909. PyObject *result;
  7910. PyObject *struct_rusage;
  7911. if (pid == -1)
  7912. return posix_error();
  7913. // If wait succeeded but no child was ready to report status, ru will not
  7914. // have been populated.
  7915. if (pid == 0) {
  7916. memset(ru, 0, sizeof(*ru));
  7917. }
  7918. struct_rusage = _PyImport_GetModuleAttrString("resource", "struct_rusage");
  7919. if (struct_rusage == NULL)
  7920. return NULL;
  7921. /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
  7922. result = PyStructSequence_New((PyTypeObject*) struct_rusage);
  7923. Py_DECREF(struct_rusage);
  7924. if (!result)
  7925. return NULL;
  7926. int pos = 0;
  7927. #ifndef doubletime
  7928. #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
  7929. #endif
  7930. #define SET_RESULT(CALL) \
  7931. do { \
  7932. PyObject *item = (CALL); \
  7933. if (item == NULL) { \
  7934. Py_DECREF(result); \
  7935. return NULL; \
  7936. } \
  7937. PyStructSequence_SET_ITEM(result, pos++, item); \
  7938. } while(0)
  7939. SET_RESULT(PyFloat_FromDouble(doubletime(ru->ru_utime)));
  7940. SET_RESULT(PyFloat_FromDouble(doubletime(ru->ru_stime)));
  7941. SET_RESULT(PyLong_FromLong(ru->ru_maxrss));
  7942. SET_RESULT(PyLong_FromLong(ru->ru_ixrss));
  7943. SET_RESULT(PyLong_FromLong(ru->ru_idrss));
  7944. SET_RESULT(PyLong_FromLong(ru->ru_isrss));
  7945. SET_RESULT(PyLong_FromLong(ru->ru_minflt));
  7946. SET_RESULT(PyLong_FromLong(ru->ru_majflt));
  7947. SET_RESULT(PyLong_FromLong(ru->ru_nswap));
  7948. SET_RESULT(PyLong_FromLong(ru->ru_inblock));
  7949. SET_RESULT(PyLong_FromLong(ru->ru_oublock));
  7950. SET_RESULT(PyLong_FromLong(ru->ru_msgsnd));
  7951. SET_RESULT(PyLong_FromLong(ru->ru_msgrcv));
  7952. SET_RESULT(PyLong_FromLong(ru->ru_nsignals));
  7953. SET_RESULT(PyLong_FromLong(ru->ru_nvcsw));
  7954. SET_RESULT(PyLong_FromLong(ru->ru_nivcsw));
  7955. #undef SET_RESULT
  7956. return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
  7957. }
  7958. #endif /* HAVE_WAIT3 || HAVE_WAIT4 */
  7959. #ifdef HAVE_WAIT3
  7960. /*[clinic input]
  7961. os.wait3
  7962. options: int
  7963. Wait for completion of a child process.
  7964. Returns a tuple of information about the child process:
  7965. (pid, status, rusage)
  7966. [clinic start generated code]*/
  7967. static PyObject *
  7968. os_wait3_impl(PyObject *module, int options)
  7969. /*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
  7970. {
  7971. pid_t pid;
  7972. struct rusage ru;
  7973. int async_err = 0;
  7974. WAIT_TYPE status;
  7975. WAIT_STATUS_INT(status) = 0;
  7976. do {
  7977. Py_BEGIN_ALLOW_THREADS
  7978. pid = wait3(&status, options, &ru);
  7979. Py_END_ALLOW_THREADS
  7980. } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  7981. if (pid < 0)
  7982. return (!async_err) ? posix_error() : NULL;
  7983. return wait_helper(module, pid, WAIT_STATUS_INT(status), &ru);
  7984. }
  7985. #endif /* HAVE_WAIT3 */
  7986. #ifdef HAVE_WAIT4
  7987. /*[clinic input]
  7988. os.wait4
  7989. pid: pid_t
  7990. options: int
  7991. Wait for completion of a specific child process.
  7992. Returns a tuple of information about the child process:
  7993. (pid, status, rusage)
  7994. [clinic start generated code]*/
  7995. static PyObject *
  7996. os_wait4_impl(PyObject *module, pid_t pid, int options)
  7997. /*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
  7998. {
  7999. pid_t res;
  8000. struct rusage ru;
  8001. int async_err = 0;
  8002. WAIT_TYPE status;
  8003. WAIT_STATUS_INT(status) = 0;
  8004. do {
  8005. Py_BEGIN_ALLOW_THREADS
  8006. res = wait4(pid, &status, options, &ru);
  8007. Py_END_ALLOW_THREADS
  8008. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8009. if (res < 0)
  8010. return (!async_err) ? posix_error() : NULL;
  8011. return wait_helper(module, res, WAIT_STATUS_INT(status), &ru);
  8012. }
  8013. #endif /* HAVE_WAIT4 */
  8014. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  8015. /*[clinic input]
  8016. os.waitid
  8017. idtype: idtype_t
  8018. Must be one of be P_PID, P_PGID or P_ALL.
  8019. id: id_t
  8020. The id to wait on.
  8021. options: int
  8022. Constructed from the ORing of one or more of WEXITED, WSTOPPED
  8023. or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
  8024. /
  8025. Returns the result of waiting for a process or processes.
  8026. Returns either waitid_result or None if WNOHANG is specified and there are
  8027. no children in a waitable state.
  8028. [clinic start generated code]*/
  8029. static PyObject *
  8030. os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
  8031. /*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
  8032. {
  8033. PyObject *result;
  8034. int res;
  8035. int async_err = 0;
  8036. siginfo_t si;
  8037. si.si_pid = 0;
  8038. do {
  8039. Py_BEGIN_ALLOW_THREADS
  8040. res = waitid(idtype, id, &si, options);
  8041. Py_END_ALLOW_THREADS
  8042. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8043. if (res < 0)
  8044. return (!async_err) ? posix_error() : NULL;
  8045. if (si.si_pid == 0)
  8046. Py_RETURN_NONE;
  8047. PyObject *WaitidResultType = get_posix_state(module)->WaitidResultType;
  8048. result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
  8049. if (!result)
  8050. return NULL;
  8051. int pos = 0;
  8052. #define SET_RESULT(CALL) \
  8053. do { \
  8054. PyObject *item = (CALL); \
  8055. if (item == NULL) { \
  8056. Py_DECREF(result); \
  8057. return NULL; \
  8058. } \
  8059. PyStructSequence_SET_ITEM(result, pos++, item); \
  8060. } while(0)
  8061. SET_RESULT(PyLong_FromPid(si.si_pid));
  8062. SET_RESULT(_PyLong_FromUid(si.si_uid));
  8063. SET_RESULT(PyLong_FromLong((long)(si.si_signo)));
  8064. SET_RESULT(PyLong_FromLong((long)(si.si_status)));
  8065. SET_RESULT(PyLong_FromLong((long)(si.si_code)));
  8066. #undef SET_RESULT
  8067. return result;
  8068. }
  8069. #endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
  8070. #if defined(HAVE_WAITPID)
  8071. /*[clinic input]
  8072. os.waitpid
  8073. pid: pid_t
  8074. options: int
  8075. /
  8076. Wait for completion of a given child process.
  8077. Returns a tuple of information regarding the child process:
  8078. (pid, status)
  8079. The options argument is ignored on Windows.
  8080. [clinic start generated code]*/
  8081. static PyObject *
  8082. os_waitpid_impl(PyObject *module, pid_t pid, int options)
  8083. /*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
  8084. {
  8085. pid_t res;
  8086. int async_err = 0;
  8087. WAIT_TYPE status;
  8088. WAIT_STATUS_INT(status) = 0;
  8089. do {
  8090. Py_BEGIN_ALLOW_THREADS
  8091. res = waitpid(pid, &status, options);
  8092. Py_END_ALLOW_THREADS
  8093. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8094. if (res < 0)
  8095. return (!async_err) ? posix_error() : NULL;
  8096. return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
  8097. }
  8098. #elif defined(HAVE_CWAIT)
  8099. /* MS C has a variant of waitpid() that's usable for most purposes. */
  8100. /*[clinic input]
  8101. os.waitpid
  8102. pid: intptr_t
  8103. options: int
  8104. /
  8105. Wait for completion of a given process.
  8106. Returns a tuple of information regarding the process:
  8107. (pid, status << 8)
  8108. The options argument is ignored on Windows.
  8109. [clinic start generated code]*/
  8110. static PyObject *
  8111. os_waitpid_impl(PyObject *module, intptr_t pid, int options)
  8112. /*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
  8113. {
  8114. int status;
  8115. intptr_t res;
  8116. int async_err = 0;
  8117. do {
  8118. Py_BEGIN_ALLOW_THREADS
  8119. _Py_BEGIN_SUPPRESS_IPH
  8120. res = _cwait(&status, pid, options);
  8121. _Py_END_SUPPRESS_IPH
  8122. Py_END_ALLOW_THREADS
  8123. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8124. if (res < 0)
  8125. return (!async_err) ? posix_error() : NULL;
  8126. unsigned long long ustatus = (unsigned int)status;
  8127. /* shift the status left a byte so this is more like the POSIX waitpid */
  8128. return Py_BuildValue(_Py_PARSE_INTPTR "K", res, ustatus << 8);
  8129. }
  8130. #endif
  8131. #ifdef HAVE_WAIT
  8132. /*[clinic input]
  8133. os.wait
  8134. Wait for completion of a child process.
  8135. Returns a tuple of information about the child process:
  8136. (pid, status)
  8137. [clinic start generated code]*/
  8138. static PyObject *
  8139. os_wait_impl(PyObject *module)
  8140. /*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
  8141. {
  8142. pid_t pid;
  8143. int async_err = 0;
  8144. WAIT_TYPE status;
  8145. WAIT_STATUS_INT(status) = 0;
  8146. do {
  8147. Py_BEGIN_ALLOW_THREADS
  8148. pid = wait(&status);
  8149. Py_END_ALLOW_THREADS
  8150. } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8151. if (pid < 0)
  8152. return (!async_err) ? posix_error() : NULL;
  8153. return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
  8154. }
  8155. #endif /* HAVE_WAIT */
  8156. #if defined(__linux__) && defined(__NR_pidfd_open)
  8157. /*[clinic input]
  8158. os.pidfd_open
  8159. pid: pid_t
  8160. flags: unsigned_int = 0
  8161. Return a file descriptor referring to the process *pid*.
  8162. The descriptor can be used to perform process management without races and
  8163. signals.
  8164. [clinic start generated code]*/
  8165. static PyObject *
  8166. os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
  8167. /*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
  8168. {
  8169. int fd = syscall(__NR_pidfd_open, pid, flags);
  8170. if (fd < 0) {
  8171. return posix_error();
  8172. }
  8173. return PyLong_FromLong(fd);
  8174. }
  8175. #endif
  8176. #ifdef HAVE_SETNS
  8177. /*[clinic input]
  8178. os.setns
  8179. fd: fildes
  8180. A file descriptor to a namespace.
  8181. nstype: int = 0
  8182. Type of namespace.
  8183. Move the calling thread into different namespaces.
  8184. [clinic start generated code]*/
  8185. static PyObject *
  8186. os_setns_impl(PyObject *module, int fd, int nstype)
  8187. /*[clinic end generated code: output=5dbd055bfb66ecd0 input=42787871226bf3ee]*/
  8188. {
  8189. int res;
  8190. Py_BEGIN_ALLOW_THREADS
  8191. res = setns(fd, nstype);
  8192. Py_END_ALLOW_THREADS
  8193. if (res != 0) {
  8194. return posix_error();
  8195. }
  8196. Py_RETURN_NONE;
  8197. }
  8198. #endif
  8199. #ifdef HAVE_UNSHARE
  8200. /*[clinic input]
  8201. os.unshare
  8202. flags: int
  8203. Namespaces to be unshared.
  8204. Disassociate parts of a process (or thread) execution context.
  8205. [clinic start generated code]*/
  8206. static PyObject *
  8207. os_unshare_impl(PyObject *module, int flags)
  8208. /*[clinic end generated code: output=1b3177906dd237ee input=9e065db3232b8b1b]*/
  8209. {
  8210. int res;
  8211. Py_BEGIN_ALLOW_THREADS
  8212. res = unshare(flags);
  8213. Py_END_ALLOW_THREADS
  8214. if (res != 0) {
  8215. return posix_error();
  8216. }
  8217. Py_RETURN_NONE;
  8218. }
  8219. #endif
  8220. #if defined(HAVE_READLINK) || defined(MS_WINDOWS)
  8221. /*[clinic input]
  8222. os.readlink
  8223. path: path_t
  8224. *
  8225. dir_fd: dir_fd(requires='readlinkat') = None
  8226. Return a string representing the path to which the symbolic link points.
  8227. If dir_fd is not None, it should be a file descriptor open to a directory,
  8228. and path should be relative; path will then be relative to that directory.
  8229. dir_fd may not be implemented on your platform. If it is unavailable,
  8230. using it will raise a NotImplementedError.
  8231. [clinic start generated code]*/
  8232. static PyObject *
  8233. os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
  8234. /*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
  8235. {
  8236. #if defined(HAVE_READLINK)
  8237. char buffer[MAXPATHLEN+1];
  8238. ssize_t length;
  8239. #ifdef HAVE_READLINKAT
  8240. int readlinkat_unavailable = 0;
  8241. #endif
  8242. Py_BEGIN_ALLOW_THREADS
  8243. #ifdef HAVE_READLINKAT
  8244. if (dir_fd != DEFAULT_DIR_FD) {
  8245. if (HAVE_READLINKAT_RUNTIME) {
  8246. length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
  8247. } else {
  8248. readlinkat_unavailable = 1;
  8249. }
  8250. } else
  8251. #endif
  8252. length = readlink(path->narrow, buffer, MAXPATHLEN);
  8253. Py_END_ALLOW_THREADS
  8254. #ifdef HAVE_READLINKAT
  8255. if (readlinkat_unavailable) {
  8256. argument_unavailable_error(NULL, "dir_fd");
  8257. return NULL;
  8258. }
  8259. #endif
  8260. if (length < 0) {
  8261. return path_error(path);
  8262. }
  8263. buffer[length] = '\0';
  8264. if (PyUnicode_Check(path->object))
  8265. return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
  8266. else
  8267. return PyBytes_FromStringAndSize(buffer, length);
  8268. #elif defined(MS_WINDOWS)
  8269. DWORD n_bytes_returned;
  8270. DWORD io_result = 0;
  8271. HANDLE reparse_point_handle;
  8272. char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
  8273. _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
  8274. PyObject *result = NULL;
  8275. /* First get a handle to the reparse point */
  8276. Py_BEGIN_ALLOW_THREADS
  8277. reparse_point_handle = CreateFileW(
  8278. path->wide,
  8279. 0,
  8280. 0,
  8281. 0,
  8282. OPEN_EXISTING,
  8283. FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
  8284. 0);
  8285. if (reparse_point_handle != INVALID_HANDLE_VALUE) {
  8286. /* New call DeviceIoControl to read the reparse point */
  8287. io_result = DeviceIoControl(
  8288. reparse_point_handle,
  8289. FSCTL_GET_REPARSE_POINT,
  8290. 0, 0, /* in buffer */
  8291. target_buffer, sizeof(target_buffer),
  8292. &n_bytes_returned,
  8293. 0 /* we're not using OVERLAPPED_IO */
  8294. );
  8295. CloseHandle(reparse_point_handle);
  8296. }
  8297. Py_END_ALLOW_THREADS
  8298. if (io_result == 0) {
  8299. return path_error(path);
  8300. }
  8301. wchar_t *name = NULL;
  8302. Py_ssize_t nameLen = 0;
  8303. if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
  8304. {
  8305. name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
  8306. rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
  8307. nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
  8308. }
  8309. else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
  8310. {
  8311. name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
  8312. rdb->MountPointReparseBuffer.SubstituteNameOffset);
  8313. nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
  8314. }
  8315. else
  8316. {
  8317. PyErr_SetString(PyExc_ValueError, "not a symbolic link");
  8318. }
  8319. if (name) {
  8320. if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
  8321. /* Our buffer is mutable, so this is okay */
  8322. name[1] = L'\\';
  8323. }
  8324. result = PyUnicode_FromWideChar(name, nameLen);
  8325. if (result && PyBytes_Check(path->object)) {
  8326. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  8327. }
  8328. }
  8329. return result;
  8330. #endif
  8331. }
  8332. #endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
  8333. #if defined(MS_WINDOWS)
  8334. /* Remove the last portion of the path - return 0 on success */
  8335. static int
  8336. _dirnameW(WCHAR *path)
  8337. {
  8338. WCHAR *ptr;
  8339. size_t length = wcsnlen_s(path, MAX_PATH);
  8340. if (length == MAX_PATH) {
  8341. return -1;
  8342. }
  8343. /* walk the path from the end until a backslash is encountered */
  8344. for(ptr = path + length; ptr != path; ptr--) {
  8345. if (*ptr == L'\\' || *ptr == L'/') {
  8346. break;
  8347. }
  8348. }
  8349. *ptr = 0;
  8350. return 0;
  8351. }
  8352. #endif
  8353. #ifdef HAVE_SYMLINK
  8354. #if defined(MS_WINDOWS)
  8355. /* Is this path absolute? */
  8356. static int
  8357. _is_absW(const WCHAR *path)
  8358. {
  8359. return path[0] == L'\\' || path[0] == L'/' ||
  8360. (path[0] && path[1] == L':');
  8361. }
  8362. /* join root and rest with a backslash - return 0 on success */
  8363. static int
  8364. _joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
  8365. {
  8366. if (_is_absW(rest)) {
  8367. return wcscpy_s(dest_path, MAX_PATH, rest);
  8368. }
  8369. if (wcscpy_s(dest_path, MAX_PATH, root)) {
  8370. return -1;
  8371. }
  8372. if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
  8373. return -1;
  8374. }
  8375. return wcscat_s(dest_path, MAX_PATH, rest);
  8376. }
  8377. /* Return True if the path at src relative to dest is a directory */
  8378. static int
  8379. _check_dirW(LPCWSTR src, LPCWSTR dest)
  8380. {
  8381. WIN32_FILE_ATTRIBUTE_DATA src_info;
  8382. WCHAR dest_parent[MAX_PATH];
  8383. WCHAR src_resolved[MAX_PATH] = L"";
  8384. /* dest_parent = os.path.dirname(dest) */
  8385. if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
  8386. _dirnameW(dest_parent)) {
  8387. return 0;
  8388. }
  8389. /* src_resolved = os.path.join(dest_parent, src) */
  8390. if (_joinW(src_resolved, dest_parent, src)) {
  8391. return 0;
  8392. }
  8393. return (
  8394. GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
  8395. && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
  8396. );
  8397. }
  8398. #endif
  8399. /*[clinic input]
  8400. os.symlink
  8401. src: path_t
  8402. dst: path_t
  8403. target_is_directory: bool = False
  8404. *
  8405. dir_fd: dir_fd(requires='symlinkat')=None
  8406. # "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
  8407. Create a symbolic link pointing to src named dst.
  8408. target_is_directory is required on Windows if the target is to be
  8409. interpreted as a directory. (On Windows, symlink requires
  8410. Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
  8411. target_is_directory is ignored on non-Windows platforms.
  8412. If dir_fd is not None, it should be a file descriptor open to a directory,
  8413. and path should be relative; path will then be relative to that directory.
  8414. dir_fd may not be implemented on your platform.
  8415. If it is unavailable, using it will raise a NotImplementedError.
  8416. [clinic start generated code]*/
  8417. static PyObject *
  8418. os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
  8419. int target_is_directory, int dir_fd)
  8420. /*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
  8421. {
  8422. #ifdef MS_WINDOWS
  8423. DWORD result;
  8424. DWORD flags = 0;
  8425. /* Assumed true, set to false if detected to not be available. */
  8426. static int windows_has_symlink_unprivileged_flag = TRUE;
  8427. #else
  8428. int result;
  8429. #ifdef HAVE_SYMLINKAT
  8430. int symlinkat_unavailable = 0;
  8431. #endif
  8432. #endif
  8433. if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
  8434. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  8435. return NULL;
  8436. }
  8437. #ifdef MS_WINDOWS
  8438. if (windows_has_symlink_unprivileged_flag) {
  8439. /* Allow non-admin symlinks if system allows it. */
  8440. flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
  8441. }
  8442. Py_BEGIN_ALLOW_THREADS
  8443. _Py_BEGIN_SUPPRESS_IPH
  8444. /* if src is a directory, ensure flags==1 (target_is_directory bit) */
  8445. if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
  8446. flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
  8447. }
  8448. result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
  8449. _Py_END_SUPPRESS_IPH
  8450. Py_END_ALLOW_THREADS
  8451. if (windows_has_symlink_unprivileged_flag && !result &&
  8452. ERROR_INVALID_PARAMETER == GetLastError()) {
  8453. Py_BEGIN_ALLOW_THREADS
  8454. _Py_BEGIN_SUPPRESS_IPH
  8455. /* This error might be caused by
  8456. SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
  8457. Try again, and update windows_has_symlink_unprivileged_flag if we
  8458. are successful this time.
  8459. NOTE: There is a risk of a race condition here if there are other
  8460. conditions than the flag causing ERROR_INVALID_PARAMETER, and
  8461. another process (or thread) changes that condition in between our
  8462. calls to CreateSymbolicLink.
  8463. */
  8464. flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
  8465. result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
  8466. _Py_END_SUPPRESS_IPH
  8467. Py_END_ALLOW_THREADS
  8468. if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
  8469. windows_has_symlink_unprivileged_flag = FALSE;
  8470. }
  8471. }
  8472. if (!result)
  8473. return path_error2(src, dst);
  8474. #else
  8475. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  8476. PyErr_SetString(PyExc_ValueError,
  8477. "symlink: src and dst must be the same type");
  8478. return NULL;
  8479. }
  8480. Py_BEGIN_ALLOW_THREADS
  8481. #ifdef HAVE_SYMLINKAT
  8482. if (dir_fd != DEFAULT_DIR_FD) {
  8483. if (HAVE_SYMLINKAT_RUNTIME) {
  8484. result = symlinkat(src->narrow, dir_fd, dst->narrow);
  8485. } else {
  8486. symlinkat_unavailable = 1;
  8487. }
  8488. } else
  8489. #endif
  8490. result = symlink(src->narrow, dst->narrow);
  8491. Py_END_ALLOW_THREADS
  8492. #ifdef HAVE_SYMLINKAT
  8493. if (symlinkat_unavailable) {
  8494. argument_unavailable_error(NULL, "dir_fd");
  8495. return NULL;
  8496. }
  8497. #endif
  8498. if (result)
  8499. return path_error2(src, dst);
  8500. #endif
  8501. Py_RETURN_NONE;
  8502. }
  8503. #endif /* HAVE_SYMLINK */
  8504. static PyStructSequence_Field times_result_fields[] = {
  8505. {"user", "user time"},
  8506. {"system", "system time"},
  8507. {"children_user", "user time of children"},
  8508. {"children_system", "system time of children"},
  8509. {"elapsed", "elapsed time since an arbitrary point in the past"},
  8510. {NULL}
  8511. };
  8512. PyDoc_STRVAR(times_result__doc__,
  8513. "times_result: Result from os.times().\n\n\
  8514. This object may be accessed either as a tuple of\n\
  8515. (user, system, children_user, children_system, elapsed),\n\
  8516. or via the attributes user, system, children_user, children_system,\n\
  8517. and elapsed.\n\
  8518. \n\
  8519. See os.times for more information.");
  8520. static PyStructSequence_Desc times_result_desc = {
  8521. "times_result", /* name */
  8522. times_result__doc__, /* doc */
  8523. times_result_fields,
  8524. 5
  8525. };
  8526. #ifdef MS_WINDOWS
  8527. #define HAVE_TIMES /* mandatory, for the method table */
  8528. #endif
  8529. #ifdef HAVE_TIMES
  8530. static PyObject *
  8531. build_times_result(PyObject *module, double user, double system,
  8532. double children_user, double children_system,
  8533. double elapsed)
  8534. {
  8535. PyObject *TimesResultType = get_posix_state(module)->TimesResultType;
  8536. PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
  8537. if (value == NULL)
  8538. return NULL;
  8539. #define SET(i, field) \
  8540. { \
  8541. PyObject *o = PyFloat_FromDouble(field); \
  8542. if (!o) { \
  8543. Py_DECREF(value); \
  8544. return NULL; \
  8545. } \
  8546. PyStructSequence_SET_ITEM(value, i, o); \
  8547. } \
  8548. SET(0, user);
  8549. SET(1, system);
  8550. SET(2, children_user);
  8551. SET(3, children_system);
  8552. SET(4, elapsed);
  8553. #undef SET
  8554. return value;
  8555. }
  8556. /*[clinic input]
  8557. os.times
  8558. Return a collection containing process timing information.
  8559. The object returned behaves like a named tuple with these fields:
  8560. (utime, stime, cutime, cstime, elapsed_time)
  8561. All fields are floating point numbers.
  8562. [clinic start generated code]*/
  8563. static PyObject *
  8564. os_times_impl(PyObject *module)
  8565. /*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
  8566. #ifdef MS_WINDOWS
  8567. {
  8568. FILETIME create, exit, kernel, user;
  8569. HANDLE hProc;
  8570. hProc = GetCurrentProcess();
  8571. GetProcessTimes(hProc, &create, &exit, &kernel, &user);
  8572. /* The fields of a FILETIME structure are the hi and lo part
  8573. of a 64-bit value expressed in 100 nanosecond units.
  8574. 1e7 is one second in such units; 1e-7 the inverse.
  8575. 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
  8576. */
  8577. return build_times_result(module,
  8578. (double)(user.dwHighDateTime*429.4967296 +
  8579. user.dwLowDateTime*1e-7),
  8580. (double)(kernel.dwHighDateTime*429.4967296 +
  8581. kernel.dwLowDateTime*1e-7),
  8582. (double)0,
  8583. (double)0,
  8584. (double)0);
  8585. }
  8586. #else /* MS_WINDOWS */
  8587. {
  8588. struct tms t;
  8589. clock_t c;
  8590. errno = 0;
  8591. c = times(&t);
  8592. if (c == (clock_t) -1) {
  8593. return posix_error();
  8594. }
  8595. assert(_PyRuntime.time.ticks_per_second_initialized);
  8596. #define ticks_per_second _PyRuntime.time.ticks_per_second
  8597. return build_times_result(module,
  8598. (double)t.tms_utime / ticks_per_second,
  8599. (double)t.tms_stime / ticks_per_second,
  8600. (double)t.tms_cutime / ticks_per_second,
  8601. (double)t.tms_cstime / ticks_per_second,
  8602. (double)c / ticks_per_second);
  8603. #undef ticks_per_second
  8604. }
  8605. #endif /* MS_WINDOWS */
  8606. #endif /* HAVE_TIMES */
  8607. #ifdef HAVE_GETSID
  8608. /*[clinic input]
  8609. os.getsid
  8610. pid: pid_t
  8611. /
  8612. Call the system call getsid(pid) and return the result.
  8613. [clinic start generated code]*/
  8614. static PyObject *
  8615. os_getsid_impl(PyObject *module, pid_t pid)
  8616. /*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
  8617. {
  8618. int sid;
  8619. sid = getsid(pid);
  8620. if (sid < 0)
  8621. return posix_error();
  8622. return PyLong_FromLong((long)sid);
  8623. }
  8624. #endif /* HAVE_GETSID */
  8625. #ifdef HAVE_SETSID
  8626. /*[clinic input]
  8627. os.setsid
  8628. Call the system call setsid().
  8629. [clinic start generated code]*/
  8630. static PyObject *
  8631. os_setsid_impl(PyObject *module)
  8632. /*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
  8633. {
  8634. if (setsid() < 0)
  8635. return posix_error();
  8636. Py_RETURN_NONE;
  8637. }
  8638. #endif /* HAVE_SETSID */
  8639. #ifdef HAVE_SETPGID
  8640. /*[clinic input]
  8641. os.setpgid
  8642. pid: pid_t
  8643. pgrp: pid_t
  8644. /
  8645. Call the system call setpgid(pid, pgrp).
  8646. [clinic start generated code]*/
  8647. static PyObject *
  8648. os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
  8649. /*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
  8650. {
  8651. if (setpgid(pid, pgrp) < 0)
  8652. return posix_error();
  8653. Py_RETURN_NONE;
  8654. }
  8655. #endif /* HAVE_SETPGID */
  8656. #ifdef HAVE_TCGETPGRP
  8657. /*[clinic input]
  8658. os.tcgetpgrp
  8659. fd: int
  8660. /
  8661. Return the process group associated with the terminal specified by fd.
  8662. [clinic start generated code]*/
  8663. static PyObject *
  8664. os_tcgetpgrp_impl(PyObject *module, int fd)
  8665. /*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
  8666. {
  8667. pid_t pgid = tcgetpgrp(fd);
  8668. if (pgid < 0)
  8669. return posix_error();
  8670. return PyLong_FromPid(pgid);
  8671. }
  8672. #endif /* HAVE_TCGETPGRP */
  8673. #ifdef HAVE_TCSETPGRP
  8674. /*[clinic input]
  8675. os.tcsetpgrp
  8676. fd: int
  8677. pgid: pid_t
  8678. /
  8679. Set the process group associated with the terminal specified by fd.
  8680. [clinic start generated code]*/
  8681. static PyObject *
  8682. os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
  8683. /*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
  8684. {
  8685. if (tcsetpgrp(fd, pgid) < 0)
  8686. return posix_error();
  8687. Py_RETURN_NONE;
  8688. }
  8689. #endif /* HAVE_TCSETPGRP */
  8690. /* Functions acting on file descriptors */
  8691. #ifdef O_CLOEXEC
  8692. extern int _Py_open_cloexec_works;
  8693. #endif
  8694. /*[clinic input]
  8695. os.open -> int
  8696. path: path_t
  8697. flags: int
  8698. mode: int = 0o777
  8699. *
  8700. dir_fd: dir_fd(requires='openat') = None
  8701. # "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
  8702. Open a file for low level IO. Returns a file descriptor (integer).
  8703. If dir_fd is not None, it should be a file descriptor open to a directory,
  8704. and path should be relative; path will then be relative to that directory.
  8705. dir_fd may not be implemented on your platform.
  8706. If it is unavailable, using it will raise a NotImplementedError.
  8707. [clinic start generated code]*/
  8708. static int
  8709. os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
  8710. /*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
  8711. {
  8712. int fd;
  8713. int async_err = 0;
  8714. #ifdef HAVE_OPENAT
  8715. int openat_unavailable = 0;
  8716. #endif
  8717. #ifdef O_CLOEXEC
  8718. int *atomic_flag_works = &_Py_open_cloexec_works;
  8719. #elif !defined(MS_WINDOWS)
  8720. int *atomic_flag_works = NULL;
  8721. #endif
  8722. #ifdef MS_WINDOWS
  8723. flags |= O_NOINHERIT;
  8724. #elif defined(O_CLOEXEC)
  8725. flags |= O_CLOEXEC;
  8726. #endif
  8727. if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
  8728. return -1;
  8729. }
  8730. _Py_BEGIN_SUPPRESS_IPH
  8731. do {
  8732. Py_BEGIN_ALLOW_THREADS
  8733. #ifdef MS_WINDOWS
  8734. fd = _wopen(path->wide, flags, mode);
  8735. #else
  8736. #ifdef HAVE_OPENAT
  8737. if (dir_fd != DEFAULT_DIR_FD) {
  8738. if (HAVE_OPENAT_RUNTIME) {
  8739. fd = openat(dir_fd, path->narrow, flags, mode);
  8740. } else {
  8741. openat_unavailable = 1;
  8742. fd = -1;
  8743. }
  8744. } else
  8745. #endif /* HAVE_OPENAT */
  8746. fd = open(path->narrow, flags, mode);
  8747. #endif /* !MS_WINDOWS */
  8748. Py_END_ALLOW_THREADS
  8749. } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8750. _Py_END_SUPPRESS_IPH
  8751. #ifdef HAVE_OPENAT
  8752. if (openat_unavailable) {
  8753. argument_unavailable_error(NULL, "dir_fd");
  8754. return -1;
  8755. }
  8756. #endif
  8757. if (fd < 0) {
  8758. if (!async_err)
  8759. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
  8760. return -1;
  8761. }
  8762. #ifndef MS_WINDOWS
  8763. if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
  8764. close(fd);
  8765. return -1;
  8766. }
  8767. #endif
  8768. return fd;
  8769. }
  8770. /*[clinic input]
  8771. os.close
  8772. fd: int
  8773. Close a file descriptor.
  8774. [clinic start generated code]*/
  8775. static PyObject *
  8776. os_close_impl(PyObject *module, int fd)
  8777. /*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
  8778. {
  8779. int res;
  8780. /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
  8781. * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
  8782. * for more details.
  8783. */
  8784. Py_BEGIN_ALLOW_THREADS
  8785. _Py_BEGIN_SUPPRESS_IPH
  8786. res = close(fd);
  8787. _Py_END_SUPPRESS_IPH
  8788. Py_END_ALLOW_THREADS
  8789. if (res < 0)
  8790. return posix_error();
  8791. Py_RETURN_NONE;
  8792. }
  8793. /*[clinic input]
  8794. os.closerange
  8795. fd_low: int
  8796. fd_high: int
  8797. /
  8798. Closes all file descriptors in [fd_low, fd_high), ignoring errors.
  8799. [clinic start generated code]*/
  8800. static PyObject *
  8801. os_closerange_impl(PyObject *module, int fd_low, int fd_high)
  8802. /*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
  8803. {
  8804. Py_BEGIN_ALLOW_THREADS
  8805. _Py_closerange(fd_low, fd_high - 1);
  8806. Py_END_ALLOW_THREADS
  8807. Py_RETURN_NONE;
  8808. }
  8809. /*[clinic input]
  8810. os.dup -> int
  8811. fd: int
  8812. /
  8813. Return a duplicate of a file descriptor.
  8814. [clinic start generated code]*/
  8815. static int
  8816. os_dup_impl(PyObject *module, int fd)
  8817. /*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
  8818. {
  8819. return _Py_dup(fd);
  8820. }
  8821. // dup2() is either provided by libc or dup2.c with AC_REPLACE_FUNCS().
  8822. // dup2.c provides working dup2() if and only if F_DUPFD is available.
  8823. #if (defined(HAVE_DUP3) || defined(F_DUPFD) || defined(MS_WINDOWS))
  8824. /*[clinic input]
  8825. os.dup2 -> int
  8826. fd: int
  8827. fd2: int
  8828. inheritable: bool=True
  8829. Duplicate file descriptor.
  8830. [clinic start generated code]*/
  8831. static int
  8832. os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
  8833. /*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
  8834. {
  8835. int res = 0;
  8836. #if defined(HAVE_DUP3) && \
  8837. !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
  8838. /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
  8839. static int dup3_works = -1;
  8840. #endif
  8841. /* dup2() can fail with EINTR if the target FD is already open, because it
  8842. * then has to be closed. See os_close_impl() for why we don't handle EINTR
  8843. * upon close(), and therefore below.
  8844. */
  8845. #ifdef MS_WINDOWS
  8846. Py_BEGIN_ALLOW_THREADS
  8847. _Py_BEGIN_SUPPRESS_IPH
  8848. res = dup2(fd, fd2);
  8849. _Py_END_SUPPRESS_IPH
  8850. Py_END_ALLOW_THREADS
  8851. if (res < 0) {
  8852. posix_error();
  8853. return -1;
  8854. }
  8855. res = fd2; // msvcrt dup2 returns 0 on success.
  8856. /* Character files like console cannot be make non-inheritable */
  8857. if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
  8858. close(fd2);
  8859. return -1;
  8860. }
  8861. #elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
  8862. Py_BEGIN_ALLOW_THREADS
  8863. if (!inheritable)
  8864. res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
  8865. else
  8866. res = dup2(fd, fd2);
  8867. Py_END_ALLOW_THREADS
  8868. if (res < 0) {
  8869. posix_error();
  8870. return -1;
  8871. }
  8872. #else
  8873. #ifdef HAVE_DUP3
  8874. if (!inheritable && dup3_works != 0) {
  8875. Py_BEGIN_ALLOW_THREADS
  8876. res = dup3(fd, fd2, O_CLOEXEC);
  8877. Py_END_ALLOW_THREADS
  8878. if (res < 0) {
  8879. if (dup3_works == -1)
  8880. dup3_works = (errno != ENOSYS);
  8881. if (dup3_works) {
  8882. posix_error();
  8883. return -1;
  8884. }
  8885. }
  8886. }
  8887. if (inheritable || dup3_works == 0)
  8888. {
  8889. #endif
  8890. Py_BEGIN_ALLOW_THREADS
  8891. res = dup2(fd, fd2);
  8892. Py_END_ALLOW_THREADS
  8893. if (res < 0) {
  8894. posix_error();
  8895. return -1;
  8896. }
  8897. if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
  8898. close(fd2);
  8899. return -1;
  8900. }
  8901. #ifdef HAVE_DUP3
  8902. }
  8903. #endif
  8904. #endif
  8905. return res;
  8906. }
  8907. #endif
  8908. #ifdef HAVE_LOCKF
  8909. /*[clinic input]
  8910. os.lockf
  8911. fd: int
  8912. An open file descriptor.
  8913. command: int
  8914. One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
  8915. length: Py_off_t
  8916. The number of bytes to lock, starting at the current position.
  8917. /
  8918. Apply, test or remove a POSIX lock on an open file descriptor.
  8919. [clinic start generated code]*/
  8920. static PyObject *
  8921. os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
  8922. /*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
  8923. {
  8924. int res;
  8925. if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
  8926. return NULL;
  8927. }
  8928. Py_BEGIN_ALLOW_THREADS
  8929. res = lockf(fd, command, length);
  8930. Py_END_ALLOW_THREADS
  8931. if (res < 0)
  8932. return posix_error();
  8933. Py_RETURN_NONE;
  8934. }
  8935. #endif /* HAVE_LOCKF */
  8936. /*[clinic input]
  8937. os.lseek -> Py_off_t
  8938. fd: int
  8939. An open file descriptor, as returned by os.open().
  8940. position: Py_off_t
  8941. Position, interpreted relative to 'whence'.
  8942. whence as how: int
  8943. The relative position to seek from. Valid values are:
  8944. - SEEK_SET: seek from the start of the file.
  8945. - SEEK_CUR: seek from the current file position.
  8946. - SEEK_END: seek from the end of the file.
  8947. /
  8948. Set the position of a file descriptor. Return the new position.
  8949. The return value is the number of bytes relative to the beginning of the file.
  8950. [clinic start generated code]*/
  8951. static Py_off_t
  8952. os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
  8953. /*[clinic end generated code: output=971e1efb6b30bd2f input=f096e754c5367504]*/
  8954. {
  8955. Py_off_t result;
  8956. #ifdef SEEK_SET
  8957. /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
  8958. switch (how) {
  8959. case 0: how = SEEK_SET; break;
  8960. case 1: how = SEEK_CUR; break;
  8961. case 2: how = SEEK_END; break;
  8962. }
  8963. #endif /* SEEK_END */
  8964. Py_BEGIN_ALLOW_THREADS
  8965. _Py_BEGIN_SUPPRESS_IPH
  8966. #ifdef MS_WINDOWS
  8967. result = _lseeki64(fd, position, how);
  8968. #else
  8969. result = lseek(fd, position, how);
  8970. #endif
  8971. _Py_END_SUPPRESS_IPH
  8972. Py_END_ALLOW_THREADS
  8973. if (result < 0)
  8974. posix_error();
  8975. return result;
  8976. }
  8977. /*[clinic input]
  8978. os.read
  8979. fd: int
  8980. length: Py_ssize_t
  8981. /
  8982. Read from a file descriptor. Returns a bytes object.
  8983. [clinic start generated code]*/
  8984. static PyObject *
  8985. os_read_impl(PyObject *module, int fd, Py_ssize_t length)
  8986. /*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
  8987. {
  8988. Py_ssize_t n;
  8989. PyObject *buffer;
  8990. if (length < 0) {
  8991. errno = EINVAL;
  8992. return posix_error();
  8993. }
  8994. length = Py_MIN(length, _PY_READ_MAX);
  8995. buffer = PyBytes_FromStringAndSize((char *)NULL, length);
  8996. if (buffer == NULL)
  8997. return NULL;
  8998. n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
  8999. if (n == -1) {
  9000. Py_DECREF(buffer);
  9001. return NULL;
  9002. }
  9003. if (n != length)
  9004. _PyBytes_Resize(&buffer, n);
  9005. return buffer;
  9006. }
  9007. #if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
  9008. || defined(__APPLE__))) \
  9009. || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
  9010. || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
  9011. static int
  9012. iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
  9013. {
  9014. Py_ssize_t i, j;
  9015. *iov = PyMem_New(struct iovec, cnt);
  9016. if (*iov == NULL) {
  9017. PyErr_NoMemory();
  9018. return -1;
  9019. }
  9020. *buf = PyMem_New(Py_buffer, cnt);
  9021. if (*buf == NULL) {
  9022. PyMem_Free(*iov);
  9023. PyErr_NoMemory();
  9024. return -1;
  9025. }
  9026. for (i = 0; i < cnt; i++) {
  9027. PyObject *item = PySequence_GetItem(seq, i);
  9028. if (item == NULL)
  9029. goto fail;
  9030. if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
  9031. Py_DECREF(item);
  9032. goto fail;
  9033. }
  9034. Py_DECREF(item);
  9035. (*iov)[i].iov_base = (*buf)[i].buf;
  9036. (*iov)[i].iov_len = (*buf)[i].len;
  9037. }
  9038. return 0;
  9039. fail:
  9040. PyMem_Free(*iov);
  9041. for (j = 0; j < i; j++) {
  9042. PyBuffer_Release(&(*buf)[j]);
  9043. }
  9044. PyMem_Free(*buf);
  9045. return -1;
  9046. }
  9047. static void
  9048. iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
  9049. {
  9050. int i;
  9051. PyMem_Free(iov);
  9052. for (i = 0; i < cnt; i++) {
  9053. PyBuffer_Release(&buf[i]);
  9054. }
  9055. PyMem_Free(buf);
  9056. }
  9057. #endif
  9058. #ifdef HAVE_READV
  9059. /*[clinic input]
  9060. os.readv -> Py_ssize_t
  9061. fd: int
  9062. buffers: object
  9063. /
  9064. Read from a file descriptor fd into an iterable of buffers.
  9065. The buffers should be mutable buffers accepting bytes.
  9066. readv will transfer data into each buffer until it is full
  9067. and then move on to the next buffer in the sequence to hold
  9068. the rest of the data.
  9069. readv returns the total number of bytes read,
  9070. which may be less than the total capacity of all the buffers.
  9071. [clinic start generated code]*/
  9072. static Py_ssize_t
  9073. os_readv_impl(PyObject *module, int fd, PyObject *buffers)
  9074. /*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
  9075. {
  9076. Py_ssize_t cnt, n;
  9077. int async_err = 0;
  9078. struct iovec *iov;
  9079. Py_buffer *buf;
  9080. if (!PySequence_Check(buffers)) {
  9081. PyErr_SetString(PyExc_TypeError,
  9082. "readv() arg 2 must be a sequence");
  9083. return -1;
  9084. }
  9085. cnt = PySequence_Size(buffers);
  9086. if (cnt < 0)
  9087. return -1;
  9088. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
  9089. return -1;
  9090. do {
  9091. Py_BEGIN_ALLOW_THREADS
  9092. n = readv(fd, iov, cnt);
  9093. Py_END_ALLOW_THREADS
  9094. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9095. int saved_errno = errno;
  9096. iov_cleanup(iov, buf, cnt);
  9097. if (n < 0) {
  9098. if (!async_err) {
  9099. errno = saved_errno;
  9100. posix_error();
  9101. }
  9102. return -1;
  9103. }
  9104. return n;
  9105. }
  9106. #endif /* HAVE_READV */
  9107. #ifdef HAVE_PREAD
  9108. /*[clinic input]
  9109. os.pread
  9110. fd: int
  9111. length: Py_ssize_t
  9112. offset: Py_off_t
  9113. /
  9114. Read a number of bytes from a file descriptor starting at a particular offset.
  9115. Read length bytes from file descriptor fd, starting at offset bytes from
  9116. the beginning of the file. The file offset remains unchanged.
  9117. [clinic start generated code]*/
  9118. static PyObject *
  9119. os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
  9120. /*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
  9121. {
  9122. Py_ssize_t n;
  9123. int async_err = 0;
  9124. PyObject *buffer;
  9125. if (length < 0) {
  9126. errno = EINVAL;
  9127. return posix_error();
  9128. }
  9129. buffer = PyBytes_FromStringAndSize((char *)NULL, length);
  9130. if (buffer == NULL)
  9131. return NULL;
  9132. do {
  9133. Py_BEGIN_ALLOW_THREADS
  9134. _Py_BEGIN_SUPPRESS_IPH
  9135. n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
  9136. _Py_END_SUPPRESS_IPH
  9137. Py_END_ALLOW_THREADS
  9138. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9139. if (n < 0) {
  9140. if (!async_err) {
  9141. posix_error();
  9142. }
  9143. Py_DECREF(buffer);
  9144. return NULL;
  9145. }
  9146. if (n != length)
  9147. _PyBytes_Resize(&buffer, n);
  9148. return buffer;
  9149. }
  9150. #endif /* HAVE_PREAD */
  9151. #if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
  9152. /*[clinic input]
  9153. os.preadv -> Py_ssize_t
  9154. fd: int
  9155. buffers: object
  9156. offset: Py_off_t
  9157. flags: int = 0
  9158. /
  9159. Reads from a file descriptor into a number of mutable bytes-like objects.
  9160. Combines the functionality of readv() and pread(). As readv(), it will
  9161. transfer data into each buffer until it is full and then move on to the next
  9162. buffer in the sequence to hold the rest of the data. Its fourth argument,
  9163. specifies the file offset at which the input operation is to be performed. It
  9164. will return the total number of bytes read (which can be less than the total
  9165. capacity of all the objects).
  9166. The flags argument contains a bitwise OR of zero or more of the following flags:
  9167. - RWF_HIPRI
  9168. - RWF_NOWAIT
  9169. Using non-zero flags requires Linux 4.6 or newer.
  9170. [clinic start generated code]*/
  9171. static Py_ssize_t
  9172. os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
  9173. int flags)
  9174. /*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
  9175. {
  9176. Py_ssize_t cnt, n;
  9177. int async_err = 0;
  9178. struct iovec *iov;
  9179. Py_buffer *buf;
  9180. if (!PySequence_Check(buffers)) {
  9181. PyErr_SetString(PyExc_TypeError,
  9182. "preadv2() arg 2 must be a sequence");
  9183. return -1;
  9184. }
  9185. cnt = PySequence_Size(buffers);
  9186. if (cnt < 0) {
  9187. return -1;
  9188. }
  9189. #ifndef HAVE_PREADV2
  9190. if(flags != 0) {
  9191. argument_unavailable_error("preadv2", "flags");
  9192. return -1;
  9193. }
  9194. #endif
  9195. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
  9196. return -1;
  9197. }
  9198. #ifdef HAVE_PREADV2
  9199. do {
  9200. Py_BEGIN_ALLOW_THREADS
  9201. _Py_BEGIN_SUPPRESS_IPH
  9202. n = preadv2(fd, iov, cnt, offset, flags);
  9203. _Py_END_SUPPRESS_IPH
  9204. Py_END_ALLOW_THREADS
  9205. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9206. #else
  9207. do {
  9208. #if defined(__APPLE__) && defined(__clang__)
  9209. /* This entire function will be removed from the module dict when the API
  9210. * is not available.
  9211. */
  9212. #pragma clang diagnostic push
  9213. #pragma clang diagnostic ignored "-Wunguarded-availability"
  9214. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  9215. #endif
  9216. Py_BEGIN_ALLOW_THREADS
  9217. _Py_BEGIN_SUPPRESS_IPH
  9218. n = preadv(fd, iov, cnt, offset);
  9219. _Py_END_SUPPRESS_IPH
  9220. Py_END_ALLOW_THREADS
  9221. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9222. #if defined(__APPLE__) && defined(__clang__)
  9223. #pragma clang diagnostic pop
  9224. #endif
  9225. #endif
  9226. int saved_errno = errno;
  9227. iov_cleanup(iov, buf, cnt);
  9228. if (n < 0) {
  9229. if (!async_err) {
  9230. errno = saved_errno;
  9231. posix_error();
  9232. }
  9233. return -1;
  9234. }
  9235. return n;
  9236. }
  9237. #endif /* HAVE_PREADV */
  9238. /*[clinic input]
  9239. os.write -> Py_ssize_t
  9240. fd: int
  9241. data: Py_buffer
  9242. /
  9243. Write a bytes object to a file descriptor.
  9244. [clinic start generated code]*/
  9245. static Py_ssize_t
  9246. os_write_impl(PyObject *module, int fd, Py_buffer *data)
  9247. /*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
  9248. {
  9249. return _Py_write(fd, data->buf, data->len);
  9250. }
  9251. #ifdef HAVE_SENDFILE
  9252. #ifdef __APPLE__
  9253. /*[clinic input]
  9254. os.sendfile
  9255. out_fd: int
  9256. in_fd: int
  9257. offset: Py_off_t
  9258. count as sbytes: Py_off_t
  9259. headers: object(c_default="NULL") = ()
  9260. trailers: object(c_default="NULL") = ()
  9261. flags: int = 0
  9262. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9263. [clinic start generated code]*/
  9264. static PyObject *
  9265. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
  9266. Py_off_t sbytes, PyObject *headers, PyObject *trailers,
  9267. int flags)
  9268. /*[clinic end generated code: output=81c4bcd143f5c82b input=b0d72579d4c69afa]*/
  9269. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  9270. /*[clinic input]
  9271. os.sendfile
  9272. out_fd: int
  9273. in_fd: int
  9274. offset: Py_off_t
  9275. count: Py_ssize_t
  9276. headers: object(c_default="NULL") = ()
  9277. trailers: object(c_default="NULL") = ()
  9278. flags: int = 0
  9279. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9280. [clinic start generated code]*/
  9281. static PyObject *
  9282. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
  9283. Py_ssize_t count, PyObject *headers, PyObject *trailers,
  9284. int flags)
  9285. /*[clinic end generated code: output=329ea009bdd55afc input=338adb8ff84ae8cd]*/
  9286. #else
  9287. /*[clinic input]
  9288. os.sendfile
  9289. out_fd: int
  9290. in_fd: int
  9291. offset as offobj: object
  9292. count: Py_ssize_t
  9293. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9294. [clinic start generated code]*/
  9295. static PyObject *
  9296. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, PyObject *offobj,
  9297. Py_ssize_t count)
  9298. /*[clinic end generated code: output=ae81216e40f167d8 input=76d64058c74477ba]*/
  9299. #endif
  9300. {
  9301. Py_ssize_t ret;
  9302. int async_err = 0;
  9303. #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
  9304. #ifndef __APPLE__
  9305. off_t sbytes;
  9306. #endif
  9307. Py_buffer *hbuf, *tbuf;
  9308. struct sf_hdtr sf;
  9309. sf.headers = NULL;
  9310. sf.trailers = NULL;
  9311. if (headers != NULL) {
  9312. if (!PySequence_Check(headers)) {
  9313. PyErr_SetString(PyExc_TypeError,
  9314. "sendfile() headers must be a sequence");
  9315. return NULL;
  9316. } else {
  9317. Py_ssize_t i = PySequence_Size(headers);
  9318. if (i < 0)
  9319. return NULL;
  9320. if (i > INT_MAX) {
  9321. PyErr_SetString(PyExc_OverflowError,
  9322. "sendfile() header is too large");
  9323. return NULL;
  9324. }
  9325. if (i > 0) {
  9326. sf.hdr_cnt = (int)i;
  9327. if (iov_setup(&(sf.headers), &hbuf,
  9328. headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
  9329. return NULL;
  9330. #ifdef __APPLE__
  9331. for (i = 0; i < sf.hdr_cnt; i++) {
  9332. Py_ssize_t blen = sf.headers[i].iov_len;
  9333. # define OFF_T_MAX 0x7fffffffffffffff
  9334. if (sbytes >= OFF_T_MAX - blen) {
  9335. PyErr_SetString(PyExc_OverflowError,
  9336. "sendfile() header is too large");
  9337. return NULL;
  9338. }
  9339. sbytes += blen;
  9340. }
  9341. #endif
  9342. }
  9343. }
  9344. }
  9345. if (trailers != NULL) {
  9346. if (!PySequence_Check(trailers)) {
  9347. PyErr_SetString(PyExc_TypeError,
  9348. "sendfile() trailers must be a sequence");
  9349. return NULL;
  9350. } else {
  9351. Py_ssize_t i = PySequence_Size(trailers);
  9352. if (i < 0)
  9353. return NULL;
  9354. if (i > INT_MAX) {
  9355. PyErr_SetString(PyExc_OverflowError,
  9356. "sendfile() trailer is too large");
  9357. return NULL;
  9358. }
  9359. if (i > 0) {
  9360. sf.trl_cnt = (int)i;
  9361. if (iov_setup(&(sf.trailers), &tbuf,
  9362. trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
  9363. return NULL;
  9364. }
  9365. }
  9366. }
  9367. _Py_BEGIN_SUPPRESS_IPH
  9368. do {
  9369. Py_BEGIN_ALLOW_THREADS
  9370. #ifdef __APPLE__
  9371. ret = sendfile(in_fd, out_fd, offset, &sbytes, &sf, flags);
  9372. #else
  9373. ret = sendfile(in_fd, out_fd, offset, count, &sf, &sbytes, flags);
  9374. #endif
  9375. Py_END_ALLOW_THREADS
  9376. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9377. _Py_END_SUPPRESS_IPH
  9378. int saved_errno = errno;
  9379. if (sf.headers != NULL)
  9380. iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
  9381. if (sf.trailers != NULL)
  9382. iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
  9383. if (ret < 0) {
  9384. if ((saved_errno == EAGAIN) || (saved_errno == EBUSY)) {
  9385. if (sbytes != 0) {
  9386. // some data has been sent
  9387. goto done;
  9388. }
  9389. // no data has been sent; upper application is supposed
  9390. // to retry on EAGAIN or EBUSY
  9391. }
  9392. if (!async_err) {
  9393. errno = saved_errno;
  9394. posix_error();
  9395. }
  9396. return NULL;
  9397. }
  9398. goto done;
  9399. done:
  9400. #if !defined(HAVE_LARGEFILE_SUPPORT)
  9401. return Py_BuildValue("l", sbytes);
  9402. #else
  9403. return Py_BuildValue("L", sbytes);
  9404. #endif
  9405. #else
  9406. #ifdef __linux__
  9407. if (offobj == Py_None) {
  9408. do {
  9409. Py_BEGIN_ALLOW_THREADS
  9410. ret = sendfile(out_fd, in_fd, NULL, count);
  9411. Py_END_ALLOW_THREADS
  9412. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9413. if (ret < 0)
  9414. return (!async_err) ? posix_error() : NULL;
  9415. return Py_BuildValue("n", ret);
  9416. }
  9417. #endif
  9418. off_t offset;
  9419. if (!Py_off_t_converter(offobj, &offset))
  9420. return NULL;
  9421. #if defined(__sun) && defined(__SVR4)
  9422. // On Solaris, sendfile raises EINVAL rather than returning 0
  9423. // when the offset is equal or bigger than the in_fd size.
  9424. struct stat st;
  9425. do {
  9426. Py_BEGIN_ALLOW_THREADS
  9427. ret = fstat(in_fd, &st);
  9428. Py_END_ALLOW_THREADS
  9429. } while (ret != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9430. if (ret < 0)
  9431. return (!async_err) ? posix_error() : NULL;
  9432. if (offset >= st.st_size) {
  9433. return Py_BuildValue("i", 0);
  9434. }
  9435. // On illumos specifically sendfile() may perform a partial write but
  9436. // return -1/an error (in one confirmed case the destination socket
  9437. // had a 5 second timeout set and errno was EAGAIN) and it's on the client
  9438. // code to check if the offset parameter was modified by sendfile().
  9439. //
  9440. // We need this variable to track said change.
  9441. off_t original_offset = offset;
  9442. #endif
  9443. do {
  9444. Py_BEGIN_ALLOW_THREADS
  9445. ret = sendfile(out_fd, in_fd, &offset, count);
  9446. #if defined(__sun) && defined(__SVR4)
  9447. // This handles illumos-specific sendfile() partial write behavior,
  9448. // see a comment above for more details.
  9449. if (ret < 0 && offset != original_offset) {
  9450. ret = offset - original_offset;
  9451. }
  9452. #endif
  9453. Py_END_ALLOW_THREADS
  9454. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9455. if (ret < 0)
  9456. return (!async_err) ? posix_error() : NULL;
  9457. return Py_BuildValue("n", ret);
  9458. #endif
  9459. }
  9460. #endif /* HAVE_SENDFILE */
  9461. #if defined(__APPLE__)
  9462. /*[clinic input]
  9463. os._fcopyfile
  9464. in_fd: int
  9465. out_fd: int
  9466. flags: int
  9467. /
  9468. Efficiently copy content or metadata of 2 regular file descriptors (macOS).
  9469. [clinic start generated code]*/
  9470. static PyObject *
  9471. os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
  9472. /*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
  9473. {
  9474. int ret;
  9475. Py_BEGIN_ALLOW_THREADS
  9476. ret = fcopyfile(in_fd, out_fd, NULL, flags);
  9477. Py_END_ALLOW_THREADS
  9478. if (ret < 0)
  9479. return posix_error();
  9480. Py_RETURN_NONE;
  9481. }
  9482. #endif
  9483. /*[clinic input]
  9484. os.fstat
  9485. fd : int
  9486. Perform a stat system call on the given file descriptor.
  9487. Like stat(), but for an open file descriptor.
  9488. Equivalent to os.stat(fd).
  9489. [clinic start generated code]*/
  9490. static PyObject *
  9491. os_fstat_impl(PyObject *module, int fd)
  9492. /*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
  9493. {
  9494. STRUCT_STAT st;
  9495. int res;
  9496. int async_err = 0;
  9497. do {
  9498. Py_BEGIN_ALLOW_THREADS
  9499. res = FSTAT(fd, &st);
  9500. Py_END_ALLOW_THREADS
  9501. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9502. if (res != 0) {
  9503. #ifdef MS_WINDOWS
  9504. return PyErr_SetFromWindowsErr(0);
  9505. #else
  9506. return (!async_err) ? posix_error() : NULL;
  9507. #endif
  9508. }
  9509. return _pystat_fromstructstat(module, &st);
  9510. }
  9511. /*[clinic input]
  9512. os.isatty -> bool
  9513. fd: int
  9514. /
  9515. Return True if the fd is connected to a terminal.
  9516. Return True if the file descriptor is an open file descriptor
  9517. connected to the slave end of a terminal.
  9518. [clinic start generated code]*/
  9519. static int
  9520. os_isatty_impl(PyObject *module, int fd)
  9521. /*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
  9522. {
  9523. int return_value;
  9524. Py_BEGIN_ALLOW_THREADS
  9525. _Py_BEGIN_SUPPRESS_IPH
  9526. return_value = isatty(fd);
  9527. _Py_END_SUPPRESS_IPH
  9528. Py_END_ALLOW_THREADS
  9529. return return_value;
  9530. }
  9531. #ifdef HAVE_PIPE
  9532. /*[clinic input]
  9533. os.pipe
  9534. Create a pipe.
  9535. Returns a tuple of two file descriptors:
  9536. (read_fd, write_fd)
  9537. [clinic start generated code]*/
  9538. static PyObject *
  9539. os_pipe_impl(PyObject *module)
  9540. /*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
  9541. {
  9542. int fds[2];
  9543. #ifdef MS_WINDOWS
  9544. HANDLE read, write;
  9545. SECURITY_ATTRIBUTES attr;
  9546. BOOL ok;
  9547. #else
  9548. int res;
  9549. #endif
  9550. #ifdef MS_WINDOWS
  9551. attr.nLength = sizeof(attr);
  9552. attr.lpSecurityDescriptor = NULL;
  9553. attr.bInheritHandle = FALSE;
  9554. Py_BEGIN_ALLOW_THREADS
  9555. ok = CreatePipe(&read, &write, &attr, 0);
  9556. if (ok) {
  9557. fds[0] = _Py_open_osfhandle_noraise(read, _O_RDONLY);
  9558. fds[1] = _Py_open_osfhandle_noraise(write, _O_WRONLY);
  9559. if (fds[0] == -1 || fds[1] == -1) {
  9560. CloseHandle(read);
  9561. CloseHandle(write);
  9562. ok = 0;
  9563. }
  9564. }
  9565. Py_END_ALLOW_THREADS
  9566. if (!ok)
  9567. return PyErr_SetFromWindowsErr(0);
  9568. #else
  9569. #ifdef HAVE_PIPE2
  9570. Py_BEGIN_ALLOW_THREADS
  9571. res = pipe2(fds, O_CLOEXEC);
  9572. Py_END_ALLOW_THREADS
  9573. if (res != 0 && errno == ENOSYS)
  9574. {
  9575. #endif
  9576. Py_BEGIN_ALLOW_THREADS
  9577. res = pipe(fds);
  9578. Py_END_ALLOW_THREADS
  9579. if (res == 0) {
  9580. if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
  9581. close(fds[0]);
  9582. close(fds[1]);
  9583. return NULL;
  9584. }
  9585. if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
  9586. close(fds[0]);
  9587. close(fds[1]);
  9588. return NULL;
  9589. }
  9590. }
  9591. #ifdef HAVE_PIPE2
  9592. }
  9593. #endif
  9594. if (res != 0)
  9595. return PyErr_SetFromErrno(PyExc_OSError);
  9596. #endif /* !MS_WINDOWS */
  9597. return Py_BuildValue("(ii)", fds[0], fds[1]);
  9598. }
  9599. #endif /* HAVE_PIPE */
  9600. #ifdef HAVE_PIPE2
  9601. /*[clinic input]
  9602. os.pipe2
  9603. flags: int
  9604. /
  9605. Create a pipe with flags set atomically.
  9606. Returns a tuple of two file descriptors:
  9607. (read_fd, write_fd)
  9608. flags can be constructed by ORing together one or more of these values:
  9609. O_NONBLOCK, O_CLOEXEC.
  9610. [clinic start generated code]*/
  9611. static PyObject *
  9612. os_pipe2_impl(PyObject *module, int flags)
  9613. /*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
  9614. {
  9615. int fds[2];
  9616. int res;
  9617. res = pipe2(fds, flags);
  9618. if (res != 0)
  9619. return posix_error();
  9620. return Py_BuildValue("(ii)", fds[0], fds[1]);
  9621. }
  9622. #endif /* HAVE_PIPE2 */
  9623. #ifdef HAVE_WRITEV
  9624. /*[clinic input]
  9625. os.writev -> Py_ssize_t
  9626. fd: int
  9627. buffers: object
  9628. /
  9629. Iterate over buffers, and write the contents of each to a file descriptor.
  9630. Returns the total number of bytes written.
  9631. buffers must be a sequence of bytes-like objects.
  9632. [clinic start generated code]*/
  9633. static Py_ssize_t
  9634. os_writev_impl(PyObject *module, int fd, PyObject *buffers)
  9635. /*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
  9636. {
  9637. Py_ssize_t cnt;
  9638. Py_ssize_t result;
  9639. int async_err = 0;
  9640. struct iovec *iov;
  9641. Py_buffer *buf;
  9642. if (!PySequence_Check(buffers)) {
  9643. PyErr_SetString(PyExc_TypeError,
  9644. "writev() arg 2 must be a sequence");
  9645. return -1;
  9646. }
  9647. cnt = PySequence_Size(buffers);
  9648. if (cnt < 0)
  9649. return -1;
  9650. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
  9651. return -1;
  9652. }
  9653. do {
  9654. Py_BEGIN_ALLOW_THREADS
  9655. result = writev(fd, iov, cnt);
  9656. Py_END_ALLOW_THREADS
  9657. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9658. if (result < 0 && !async_err)
  9659. posix_error();
  9660. iov_cleanup(iov, buf, cnt);
  9661. return result;
  9662. }
  9663. #endif /* HAVE_WRITEV */
  9664. #ifdef HAVE_PWRITE
  9665. /*[clinic input]
  9666. os.pwrite -> Py_ssize_t
  9667. fd: int
  9668. buffer: Py_buffer
  9669. offset: Py_off_t
  9670. /
  9671. Write bytes to a file descriptor starting at a particular offset.
  9672. Write buffer to fd, starting at offset bytes from the beginning of
  9673. the file. Returns the number of bytes writte. Does not change the
  9674. current file offset.
  9675. [clinic start generated code]*/
  9676. static Py_ssize_t
  9677. os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
  9678. /*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
  9679. {
  9680. Py_ssize_t size;
  9681. int async_err = 0;
  9682. do {
  9683. Py_BEGIN_ALLOW_THREADS
  9684. _Py_BEGIN_SUPPRESS_IPH
  9685. size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
  9686. _Py_END_SUPPRESS_IPH
  9687. Py_END_ALLOW_THREADS
  9688. } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9689. if (size < 0 && !async_err)
  9690. posix_error();
  9691. return size;
  9692. }
  9693. #endif /* HAVE_PWRITE */
  9694. #if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
  9695. /*[clinic input]
  9696. os.pwritev -> Py_ssize_t
  9697. fd: int
  9698. buffers: object
  9699. offset: Py_off_t
  9700. flags: int = 0
  9701. /
  9702. Writes the contents of bytes-like objects to a file descriptor at a given offset.
  9703. Combines the functionality of writev() and pwrite(). All buffers must be a sequence
  9704. of bytes-like objects. Buffers are processed in array order. Entire contents of first
  9705. buffer is written before proceeding to second, and so on. The operating system may
  9706. set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
  9707. This function writes the contents of each object to the file descriptor and returns
  9708. the total number of bytes written.
  9709. The flags argument contains a bitwise OR of zero or more of the following flags:
  9710. - RWF_DSYNC
  9711. - RWF_SYNC
  9712. - RWF_APPEND
  9713. Using non-zero flags requires Linux 4.7 or newer.
  9714. [clinic start generated code]*/
  9715. static Py_ssize_t
  9716. os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
  9717. int flags)
  9718. /*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=35358c327e1a2a8e]*/
  9719. {
  9720. Py_ssize_t cnt;
  9721. Py_ssize_t result;
  9722. int async_err = 0;
  9723. struct iovec *iov;
  9724. Py_buffer *buf;
  9725. if (!PySequence_Check(buffers)) {
  9726. PyErr_SetString(PyExc_TypeError,
  9727. "pwritev() arg 2 must be a sequence");
  9728. return -1;
  9729. }
  9730. cnt = PySequence_Size(buffers);
  9731. if (cnt < 0) {
  9732. return -1;
  9733. }
  9734. #ifndef HAVE_PWRITEV2
  9735. if(flags != 0) {
  9736. argument_unavailable_error("pwritev2", "flags");
  9737. return -1;
  9738. }
  9739. #endif
  9740. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
  9741. return -1;
  9742. }
  9743. #ifdef HAVE_PWRITEV2
  9744. do {
  9745. Py_BEGIN_ALLOW_THREADS
  9746. _Py_BEGIN_SUPPRESS_IPH
  9747. result = pwritev2(fd, iov, cnt, offset, flags);
  9748. _Py_END_SUPPRESS_IPH
  9749. Py_END_ALLOW_THREADS
  9750. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9751. #else
  9752. #if defined(__APPLE__) && defined(__clang__)
  9753. /* This entire function will be removed from the module dict when the API
  9754. * is not available.
  9755. */
  9756. #pragma clang diagnostic push
  9757. #pragma clang diagnostic ignored "-Wunguarded-availability"
  9758. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  9759. #endif
  9760. do {
  9761. Py_BEGIN_ALLOW_THREADS
  9762. _Py_BEGIN_SUPPRESS_IPH
  9763. result = pwritev(fd, iov, cnt, offset);
  9764. _Py_END_SUPPRESS_IPH
  9765. Py_END_ALLOW_THREADS
  9766. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9767. #if defined(__APPLE__) && defined(__clang__)
  9768. #pragma clang diagnostic pop
  9769. #endif
  9770. #endif
  9771. if (result < 0) {
  9772. if (!async_err) {
  9773. posix_error();
  9774. }
  9775. result = -1;
  9776. }
  9777. iov_cleanup(iov, buf, cnt);
  9778. return result;
  9779. }
  9780. #endif /* HAVE_PWRITEV */
  9781. #ifdef HAVE_COPY_FILE_RANGE
  9782. /*[clinic input]
  9783. os.copy_file_range
  9784. src: int
  9785. Source file descriptor.
  9786. dst: int
  9787. Destination file descriptor.
  9788. count: Py_ssize_t
  9789. Number of bytes to copy.
  9790. offset_src: object = None
  9791. Starting offset in src.
  9792. offset_dst: object = None
  9793. Starting offset in dst.
  9794. Copy count bytes from one file descriptor to another.
  9795. If offset_src is None, then src is read from the current position;
  9796. respectively for offset_dst.
  9797. [clinic start generated code]*/
  9798. static PyObject *
  9799. os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
  9800. PyObject *offset_src, PyObject *offset_dst)
  9801. /*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
  9802. {
  9803. off_t offset_src_val, offset_dst_val;
  9804. off_t *p_offset_src = NULL;
  9805. off_t *p_offset_dst = NULL;
  9806. Py_ssize_t ret;
  9807. int async_err = 0;
  9808. /* The flags argument is provided to allow
  9809. * for future extensions and currently must be to 0. */
  9810. int flags = 0;
  9811. if (count < 0) {
  9812. PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
  9813. return NULL;
  9814. }
  9815. if (offset_src != Py_None) {
  9816. if (!Py_off_t_converter(offset_src, &offset_src_val)) {
  9817. return NULL;
  9818. }
  9819. p_offset_src = &offset_src_val;
  9820. }
  9821. if (offset_dst != Py_None) {
  9822. if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
  9823. return NULL;
  9824. }
  9825. p_offset_dst = &offset_dst_val;
  9826. }
  9827. do {
  9828. Py_BEGIN_ALLOW_THREADS
  9829. ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
  9830. Py_END_ALLOW_THREADS
  9831. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9832. if (ret < 0) {
  9833. return (!async_err) ? posix_error() : NULL;
  9834. }
  9835. return PyLong_FromSsize_t(ret);
  9836. }
  9837. #endif /* HAVE_COPY_FILE_RANGE*/
  9838. #if (defined(HAVE_SPLICE) && !defined(_AIX))
  9839. /*[clinic input]
  9840. os.splice
  9841. src: int
  9842. Source file descriptor.
  9843. dst: int
  9844. Destination file descriptor.
  9845. count: Py_ssize_t
  9846. Number of bytes to copy.
  9847. offset_src: object = None
  9848. Starting offset in src.
  9849. offset_dst: object = None
  9850. Starting offset in dst.
  9851. flags: unsigned_int = 0
  9852. Flags to modify the semantics of the call.
  9853. Transfer count bytes from one pipe to a descriptor or vice versa.
  9854. If offset_src is None, then src is read from the current position;
  9855. respectively for offset_dst. The offset associated to the file
  9856. descriptor that refers to a pipe must be None.
  9857. [clinic start generated code]*/
  9858. static PyObject *
  9859. os_splice_impl(PyObject *module, int src, int dst, Py_ssize_t count,
  9860. PyObject *offset_src, PyObject *offset_dst,
  9861. unsigned int flags)
  9862. /*[clinic end generated code: output=d0386f25a8519dc5 input=047527c66c6d2e0a]*/
  9863. {
  9864. off_t offset_src_val, offset_dst_val;
  9865. off_t *p_offset_src = NULL;
  9866. off_t *p_offset_dst = NULL;
  9867. Py_ssize_t ret;
  9868. int async_err = 0;
  9869. if (count < 0) {
  9870. PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
  9871. return NULL;
  9872. }
  9873. if (offset_src != Py_None) {
  9874. if (!Py_off_t_converter(offset_src, &offset_src_val)) {
  9875. return NULL;
  9876. }
  9877. p_offset_src = &offset_src_val;
  9878. }
  9879. if (offset_dst != Py_None) {
  9880. if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
  9881. return NULL;
  9882. }
  9883. p_offset_dst = &offset_dst_val;
  9884. }
  9885. do {
  9886. Py_BEGIN_ALLOW_THREADS
  9887. ret = splice(src, p_offset_src, dst, p_offset_dst, count, flags);
  9888. Py_END_ALLOW_THREADS
  9889. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9890. if (ret < 0) {
  9891. return (!async_err) ? posix_error() : NULL;
  9892. }
  9893. return PyLong_FromSsize_t(ret);
  9894. }
  9895. #endif /* HAVE_SPLICE*/
  9896. #ifdef HAVE_MKFIFO
  9897. /*[clinic input]
  9898. os.mkfifo
  9899. path: path_t
  9900. mode: int=0o666
  9901. *
  9902. dir_fd: dir_fd(requires='mkfifoat')=None
  9903. Create a "fifo" (a POSIX named pipe).
  9904. If dir_fd is not None, it should be a file descriptor open to a directory,
  9905. and path should be relative; path will then be relative to that directory.
  9906. dir_fd may not be implemented on your platform.
  9907. If it is unavailable, using it will raise a NotImplementedError.
  9908. [clinic start generated code]*/
  9909. static PyObject *
  9910. os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
  9911. /*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
  9912. {
  9913. int result;
  9914. int async_err = 0;
  9915. #ifdef HAVE_MKFIFOAT
  9916. int mkfifoat_unavailable = 0;
  9917. #endif
  9918. do {
  9919. Py_BEGIN_ALLOW_THREADS
  9920. #ifdef HAVE_MKFIFOAT
  9921. if (dir_fd != DEFAULT_DIR_FD) {
  9922. if (HAVE_MKFIFOAT_RUNTIME) {
  9923. result = mkfifoat(dir_fd, path->narrow, mode);
  9924. } else {
  9925. mkfifoat_unavailable = 1;
  9926. result = 0;
  9927. }
  9928. } else
  9929. #endif
  9930. result = mkfifo(path->narrow, mode);
  9931. Py_END_ALLOW_THREADS
  9932. } while (result != 0 && errno == EINTR &&
  9933. !(async_err = PyErr_CheckSignals()));
  9934. #ifdef HAVE_MKFIFOAT
  9935. if (mkfifoat_unavailable) {
  9936. argument_unavailable_error(NULL, "dir_fd");
  9937. return NULL;
  9938. }
  9939. #endif
  9940. if (result != 0)
  9941. return (!async_err) ? posix_error() : NULL;
  9942. Py_RETURN_NONE;
  9943. }
  9944. #endif /* HAVE_MKFIFO */
  9945. #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
  9946. /*[clinic input]
  9947. os.mknod
  9948. path: path_t
  9949. mode: int=0o600
  9950. device: dev_t=0
  9951. *
  9952. dir_fd: dir_fd(requires='mknodat')=None
  9953. Create a node in the file system.
  9954. Create a node in the file system (file, device special file or named pipe)
  9955. at path. mode specifies both the permissions to use and the
  9956. type of node to be created, being combined (bitwise OR) with one of
  9957. S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
  9958. device defines the newly created device special file (probably using
  9959. os.makedev()). Otherwise device is ignored.
  9960. If dir_fd is not None, it should be a file descriptor open to a directory,
  9961. and path should be relative; path will then be relative to that directory.
  9962. dir_fd may not be implemented on your platform.
  9963. If it is unavailable, using it will raise a NotImplementedError.
  9964. [clinic start generated code]*/
  9965. static PyObject *
  9966. os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
  9967. int dir_fd)
  9968. /*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
  9969. {
  9970. int result;
  9971. int async_err = 0;
  9972. #ifdef HAVE_MKNODAT
  9973. int mknodat_unavailable = 0;
  9974. #endif
  9975. do {
  9976. Py_BEGIN_ALLOW_THREADS
  9977. #ifdef HAVE_MKNODAT
  9978. if (dir_fd != DEFAULT_DIR_FD) {
  9979. if (HAVE_MKNODAT_RUNTIME) {
  9980. result = mknodat(dir_fd, path->narrow, mode, device);
  9981. } else {
  9982. mknodat_unavailable = 1;
  9983. result = 0;
  9984. }
  9985. } else
  9986. #endif
  9987. result = mknod(path->narrow, mode, device);
  9988. Py_END_ALLOW_THREADS
  9989. } while (result != 0 && errno == EINTR &&
  9990. !(async_err = PyErr_CheckSignals()));
  9991. #ifdef HAVE_MKNODAT
  9992. if (mknodat_unavailable) {
  9993. argument_unavailable_error(NULL, "dir_fd");
  9994. return NULL;
  9995. }
  9996. #endif
  9997. if (result != 0)
  9998. return (!async_err) ? posix_error() : NULL;
  9999. Py_RETURN_NONE;
  10000. }
  10001. #endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
  10002. static PyObject *
  10003. major_minor_conv(unsigned int value)
  10004. {
  10005. #ifdef NODEV
  10006. if (value == (unsigned int)NODEV) {
  10007. return PyLong_FromLong((int)NODEV);
  10008. }
  10009. #endif
  10010. return PyLong_FromUnsignedLong(value);
  10011. }
  10012. static int
  10013. major_minor_check(dev_t value)
  10014. {
  10015. #ifdef NODEV
  10016. if (value == NODEV) {
  10017. return 1;
  10018. }
  10019. #endif
  10020. return (dev_t)(unsigned int)value == value;
  10021. }
  10022. #ifdef HAVE_DEVICE_MACROS
  10023. /*[clinic input]
  10024. os.major
  10025. device: dev_t
  10026. /
  10027. Extracts a device major number from a raw device number.
  10028. [clinic start generated code]*/
  10029. static PyObject *
  10030. os_major_impl(PyObject *module, dev_t device)
  10031. /*[clinic end generated code: output=4071ffee17647891 input=b1a0a14ec9448229]*/
  10032. {
  10033. return major_minor_conv(major(device));
  10034. }
  10035. /*[clinic input]
  10036. os.minor
  10037. device: dev_t
  10038. /
  10039. Extracts a device minor number from a raw device number.
  10040. [clinic start generated code]*/
  10041. static PyObject *
  10042. os_minor_impl(PyObject *module, dev_t device)
  10043. /*[clinic end generated code: output=306cb78e3bc5004f input=2f686e463682a9da]*/
  10044. {
  10045. return major_minor_conv(minor(device));
  10046. }
  10047. /*[clinic input]
  10048. os.makedev -> dev_t
  10049. major: dev_t
  10050. minor: dev_t
  10051. /
  10052. Composes a raw device number from the major and minor device numbers.
  10053. [clinic start generated code]*/
  10054. static dev_t
  10055. os_makedev_impl(PyObject *module, dev_t major, dev_t minor)
  10056. /*[clinic end generated code: output=cad6125c51f5af80 input=2146126ec02e55c1]*/
  10057. {
  10058. if (!major_minor_check(major) || !major_minor_check(minor)) {
  10059. PyErr_SetString(PyExc_OverflowError,
  10060. "Python int too large to convert to C unsigned int");
  10061. return (dev_t)-1;
  10062. }
  10063. return makedev(major, minor);
  10064. }
  10065. #endif /* HAVE_DEVICE_MACROS */
  10066. #if defined HAVE_FTRUNCATE || defined MS_WINDOWS
  10067. /*[clinic input]
  10068. os.ftruncate
  10069. fd: int
  10070. length: Py_off_t
  10071. /
  10072. Truncate a file, specified by file descriptor, to a specific length.
  10073. [clinic start generated code]*/
  10074. static PyObject *
  10075. os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
  10076. /*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
  10077. {
  10078. int result;
  10079. int async_err = 0;
  10080. if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
  10081. return NULL;
  10082. }
  10083. do {
  10084. Py_BEGIN_ALLOW_THREADS
  10085. _Py_BEGIN_SUPPRESS_IPH
  10086. #ifdef MS_WINDOWS
  10087. result = _chsize_s(fd, length);
  10088. #else
  10089. result = ftruncate(fd, length);
  10090. #endif
  10091. _Py_END_SUPPRESS_IPH
  10092. Py_END_ALLOW_THREADS
  10093. } while (result != 0 && errno == EINTR &&
  10094. !(async_err = PyErr_CheckSignals()));
  10095. if (result != 0)
  10096. return (!async_err) ? posix_error() : NULL;
  10097. Py_RETURN_NONE;
  10098. }
  10099. #endif /* HAVE_FTRUNCATE || MS_WINDOWS */
  10100. #if defined HAVE_TRUNCATE || defined MS_WINDOWS
  10101. /*[clinic input]
  10102. os.truncate
  10103. path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
  10104. length: Py_off_t
  10105. Truncate a file, specified by path, to a specific length.
  10106. On some platforms, path may also be specified as an open file descriptor.
  10107. If this functionality is unavailable, using it raises an exception.
  10108. [clinic start generated code]*/
  10109. static PyObject *
  10110. os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
  10111. /*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
  10112. {
  10113. int result;
  10114. #ifdef MS_WINDOWS
  10115. int fd;
  10116. #endif
  10117. if (path->fd != -1)
  10118. return os_ftruncate_impl(module, path->fd, length);
  10119. if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
  10120. return NULL;
  10121. }
  10122. Py_BEGIN_ALLOW_THREADS
  10123. _Py_BEGIN_SUPPRESS_IPH
  10124. #ifdef MS_WINDOWS
  10125. fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
  10126. if (fd < 0)
  10127. result = -1;
  10128. else {
  10129. result = _chsize_s(fd, length);
  10130. close(fd);
  10131. if (result < 0)
  10132. errno = result;
  10133. }
  10134. #else
  10135. result = truncate(path->narrow, length);
  10136. #endif
  10137. _Py_END_SUPPRESS_IPH
  10138. Py_END_ALLOW_THREADS
  10139. if (result < 0)
  10140. return posix_path_error(path);
  10141. Py_RETURN_NONE;
  10142. }
  10143. #endif /* HAVE_TRUNCATE || MS_WINDOWS */
  10144. /* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
  10145. and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
  10146. defined, which is the case in Python on AIX. AIX bug report:
  10147. http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
  10148. #if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
  10149. # define POSIX_FADVISE_AIX_BUG
  10150. #endif
  10151. /* GH-111804: Due to posix_fallocate() not having consistent semantics across
  10152. OSs, support was dropped in WASI preview2. */
  10153. #if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG) && \
  10154. !defined(__wasi__)
  10155. /*[clinic input]
  10156. os.posix_fallocate
  10157. fd: int
  10158. offset: Py_off_t
  10159. length: Py_off_t
  10160. /
  10161. Ensure a file has allocated at least a particular number of bytes on disk.
  10162. Ensure that the file specified by fd encompasses a range of bytes
  10163. starting at offset bytes from the beginning and continuing for length bytes.
  10164. [clinic start generated code]*/
  10165. static PyObject *
  10166. os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
  10167. Py_off_t length)
  10168. /*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
  10169. {
  10170. int result;
  10171. int async_err = 0;
  10172. do {
  10173. Py_BEGIN_ALLOW_THREADS
  10174. result = posix_fallocate(fd, offset, length);
  10175. Py_END_ALLOW_THREADS
  10176. } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
  10177. if (result == 0)
  10178. Py_RETURN_NONE;
  10179. if (async_err)
  10180. return NULL;
  10181. errno = result;
  10182. return posix_error();
  10183. }
  10184. #endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG && !defined(__wasi__) */
  10185. #if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
  10186. /*[clinic input]
  10187. os.posix_fadvise
  10188. fd: int
  10189. offset: Py_off_t
  10190. length: Py_off_t
  10191. advice: int
  10192. /
  10193. Announce an intention to access data in a specific pattern.
  10194. Announce an intention to access data in a specific pattern, thus allowing
  10195. the kernel to make optimizations.
  10196. The advice applies to the region of the file specified by fd starting at
  10197. offset and continuing for length bytes.
  10198. advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
  10199. POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
  10200. POSIX_FADV_DONTNEED.
  10201. [clinic start generated code]*/
  10202. static PyObject *
  10203. os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
  10204. Py_off_t length, int advice)
  10205. /*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
  10206. {
  10207. int result;
  10208. int async_err = 0;
  10209. do {
  10210. Py_BEGIN_ALLOW_THREADS
  10211. result = posix_fadvise(fd, offset, length, advice);
  10212. Py_END_ALLOW_THREADS
  10213. } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
  10214. if (result == 0)
  10215. Py_RETURN_NONE;
  10216. if (async_err)
  10217. return NULL;
  10218. errno = result;
  10219. return posix_error();
  10220. }
  10221. #endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
  10222. #ifdef MS_WINDOWS
  10223. static PyObject*
  10224. win32_putenv(PyObject *name, PyObject *value)
  10225. {
  10226. /* Search from index 1 because on Windows starting '=' is allowed for
  10227. defining hidden environment variables. */
  10228. if (PyUnicode_GET_LENGTH(name) == 0 ||
  10229. PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
  10230. {
  10231. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  10232. return NULL;
  10233. }
  10234. PyObject *unicode;
  10235. if (value != NULL) {
  10236. unicode = PyUnicode_FromFormat("%U=%U", name, value);
  10237. }
  10238. else {
  10239. unicode = PyUnicode_FromFormat("%U=", name);
  10240. }
  10241. if (unicode == NULL) {
  10242. return NULL;
  10243. }
  10244. Py_ssize_t size;
  10245. wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
  10246. Py_DECREF(unicode);
  10247. if (env == NULL) {
  10248. return NULL;
  10249. }
  10250. if (size > _MAX_ENV) {
  10251. PyErr_Format(PyExc_ValueError,
  10252. "the environment variable is longer than %u characters",
  10253. _MAX_ENV);
  10254. PyMem_Free(env);
  10255. return NULL;
  10256. }
  10257. if (wcslen(env) != (size_t)size) {
  10258. PyErr_SetString(PyExc_ValueError,
  10259. "embedded null character");
  10260. PyMem_Free(env);
  10261. return NULL;
  10262. }
  10263. /* _wputenv() and SetEnvironmentVariableW() update the environment in the
  10264. Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
  10265. and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
  10266. Prefer _wputenv() to be compatible with C libraries using CRT
  10267. variables and CRT functions using these variables (ex: getenv()). */
  10268. int err = _wputenv(env);
  10269. if (err) {
  10270. posix_error();
  10271. PyMem_Free(env);
  10272. return NULL;
  10273. }
  10274. PyMem_Free(env);
  10275. Py_RETURN_NONE;
  10276. }
  10277. #endif
  10278. #ifdef MS_WINDOWS
  10279. /*[clinic input]
  10280. os.putenv
  10281. name: unicode
  10282. value: unicode
  10283. /
  10284. Change or add an environment variable.
  10285. [clinic start generated code]*/
  10286. static PyObject *
  10287. os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
  10288. /*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
  10289. {
  10290. if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
  10291. return NULL;
  10292. }
  10293. return win32_putenv(name, value);
  10294. }
  10295. #else
  10296. /*[clinic input]
  10297. os.putenv
  10298. name: FSConverter
  10299. value: FSConverter
  10300. /
  10301. Change or add an environment variable.
  10302. [clinic start generated code]*/
  10303. static PyObject *
  10304. os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
  10305. /*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
  10306. {
  10307. const char *name_string = PyBytes_AS_STRING(name);
  10308. const char *value_string = PyBytes_AS_STRING(value);
  10309. if (strchr(name_string, '=') != NULL) {
  10310. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  10311. return NULL;
  10312. }
  10313. if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
  10314. return NULL;
  10315. }
  10316. if (setenv(name_string, value_string, 1)) {
  10317. return posix_error();
  10318. }
  10319. Py_RETURN_NONE;
  10320. }
  10321. #endif /* !defined(MS_WINDOWS) */
  10322. #ifdef MS_WINDOWS
  10323. /*[clinic input]
  10324. os.unsetenv
  10325. name: unicode
  10326. /
  10327. Delete an environment variable.
  10328. [clinic start generated code]*/
  10329. static PyObject *
  10330. os_unsetenv_impl(PyObject *module, PyObject *name)
  10331. /*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
  10332. {
  10333. if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
  10334. return NULL;
  10335. }
  10336. return win32_putenv(name, NULL);
  10337. }
  10338. #else
  10339. /*[clinic input]
  10340. os.unsetenv
  10341. name: FSConverter
  10342. /
  10343. Delete an environment variable.
  10344. [clinic start generated code]*/
  10345. static PyObject *
  10346. os_unsetenv_impl(PyObject *module, PyObject *name)
  10347. /*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
  10348. {
  10349. if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
  10350. return NULL;
  10351. }
  10352. #ifdef HAVE_BROKEN_UNSETENV
  10353. unsetenv(PyBytes_AS_STRING(name));
  10354. #else
  10355. int err = unsetenv(PyBytes_AS_STRING(name));
  10356. if (err) {
  10357. return posix_error();
  10358. }
  10359. #endif
  10360. Py_RETURN_NONE;
  10361. }
  10362. #endif /* !MS_WINDOWS */
  10363. /*[clinic input]
  10364. os.strerror
  10365. code: int
  10366. /
  10367. Translate an error code to a message string.
  10368. [clinic start generated code]*/
  10369. static PyObject *
  10370. os_strerror_impl(PyObject *module, int code)
  10371. /*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
  10372. {
  10373. char *message = strerror(code);
  10374. if (message == NULL) {
  10375. PyErr_SetString(PyExc_ValueError,
  10376. "strerror() argument out of range");
  10377. return NULL;
  10378. }
  10379. return PyUnicode_DecodeLocale(message, "surrogateescape");
  10380. }
  10381. #ifdef HAVE_SYS_WAIT_H
  10382. #ifdef WCOREDUMP
  10383. /*[clinic input]
  10384. os.WCOREDUMP -> bool
  10385. status: int
  10386. /
  10387. Return True if the process returning status was dumped to a core file.
  10388. [clinic start generated code]*/
  10389. static int
  10390. os_WCOREDUMP_impl(PyObject *module, int status)
  10391. /*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
  10392. {
  10393. WAIT_TYPE wait_status;
  10394. WAIT_STATUS_INT(wait_status) = status;
  10395. return WCOREDUMP(wait_status);
  10396. }
  10397. #endif /* WCOREDUMP */
  10398. #ifdef WIFCONTINUED
  10399. /*[clinic input]
  10400. os.WIFCONTINUED -> bool
  10401. status: int
  10402. Return True if a particular process was continued from a job control stop.
  10403. Return True if the process returning status was continued from a
  10404. job control stop.
  10405. [clinic start generated code]*/
  10406. static int
  10407. os_WIFCONTINUED_impl(PyObject *module, int status)
  10408. /*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
  10409. {
  10410. WAIT_TYPE wait_status;
  10411. WAIT_STATUS_INT(wait_status) = status;
  10412. return WIFCONTINUED(wait_status);
  10413. }
  10414. #endif /* WIFCONTINUED */
  10415. #ifdef WIFSTOPPED
  10416. /*[clinic input]
  10417. os.WIFSTOPPED -> bool
  10418. status: int
  10419. Return True if the process returning status was stopped.
  10420. [clinic start generated code]*/
  10421. static int
  10422. os_WIFSTOPPED_impl(PyObject *module, int status)
  10423. /*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
  10424. {
  10425. WAIT_TYPE wait_status;
  10426. WAIT_STATUS_INT(wait_status) = status;
  10427. return WIFSTOPPED(wait_status);
  10428. }
  10429. #endif /* WIFSTOPPED */
  10430. #ifdef WIFSIGNALED
  10431. /*[clinic input]
  10432. os.WIFSIGNALED -> bool
  10433. status: int
  10434. Return True if the process returning status was terminated by a signal.
  10435. [clinic start generated code]*/
  10436. static int
  10437. os_WIFSIGNALED_impl(PyObject *module, int status)
  10438. /*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
  10439. {
  10440. WAIT_TYPE wait_status;
  10441. WAIT_STATUS_INT(wait_status) = status;
  10442. return WIFSIGNALED(wait_status);
  10443. }
  10444. #endif /* WIFSIGNALED */
  10445. #ifdef WIFEXITED
  10446. /*[clinic input]
  10447. os.WIFEXITED -> bool
  10448. status: int
  10449. Return True if the process returning status exited via the exit() system call.
  10450. [clinic start generated code]*/
  10451. static int
  10452. os_WIFEXITED_impl(PyObject *module, int status)
  10453. /*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
  10454. {
  10455. WAIT_TYPE wait_status;
  10456. WAIT_STATUS_INT(wait_status) = status;
  10457. return WIFEXITED(wait_status);
  10458. }
  10459. #endif /* WIFEXITED */
  10460. #ifdef WEXITSTATUS
  10461. /*[clinic input]
  10462. os.WEXITSTATUS -> int
  10463. status: int
  10464. Return the process return code from status.
  10465. [clinic start generated code]*/
  10466. static int
  10467. os_WEXITSTATUS_impl(PyObject *module, int status)
  10468. /*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
  10469. {
  10470. WAIT_TYPE wait_status;
  10471. WAIT_STATUS_INT(wait_status) = status;
  10472. return WEXITSTATUS(wait_status);
  10473. }
  10474. #endif /* WEXITSTATUS */
  10475. #ifdef WTERMSIG
  10476. /*[clinic input]
  10477. os.WTERMSIG -> int
  10478. status: int
  10479. Return the signal that terminated the process that provided the status value.
  10480. [clinic start generated code]*/
  10481. static int
  10482. os_WTERMSIG_impl(PyObject *module, int status)
  10483. /*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
  10484. {
  10485. WAIT_TYPE wait_status;
  10486. WAIT_STATUS_INT(wait_status) = status;
  10487. return WTERMSIG(wait_status);
  10488. }
  10489. #endif /* WTERMSIG */
  10490. #ifdef WSTOPSIG
  10491. /*[clinic input]
  10492. os.WSTOPSIG -> int
  10493. status: int
  10494. Return the signal that stopped the process that provided the status value.
  10495. [clinic start generated code]*/
  10496. static int
  10497. os_WSTOPSIG_impl(PyObject *module, int status)
  10498. /*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
  10499. {
  10500. WAIT_TYPE wait_status;
  10501. WAIT_STATUS_INT(wait_status) = status;
  10502. return WSTOPSIG(wait_status);
  10503. }
  10504. #endif /* WSTOPSIG */
  10505. #endif /* HAVE_SYS_WAIT_H */
  10506. #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
  10507. #ifdef _SCO_DS
  10508. /* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
  10509. needed definitions in sys/statvfs.h */
  10510. #define _SVID3
  10511. #endif
  10512. #include <sys/statvfs.h>
  10513. static PyObject*
  10514. _pystatvfs_fromstructstatvfs(PyObject *module, struct statvfs st) {
  10515. PyObject *StatVFSResultType = get_posix_state(module)->StatVFSResultType;
  10516. PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
  10517. if (v == NULL)
  10518. return NULL;
  10519. int pos = 0;
  10520. #define SET_RESULT(CALL) \
  10521. do { \
  10522. PyObject *item = (CALL); \
  10523. if (item == NULL) { \
  10524. Py_DECREF(v); \
  10525. return NULL; \
  10526. } \
  10527. PyStructSequence_SET_ITEM(v, pos++, item); \
  10528. } while(0)
  10529. #if !defined(HAVE_LARGEFILE_SUPPORT)
  10530. SET_RESULT(PyLong_FromLong((long) st.f_bsize));
  10531. SET_RESULT(PyLong_FromLong((long) st.f_frsize));
  10532. SET_RESULT(PyLong_FromLong((long) st.f_blocks));
  10533. SET_RESULT(PyLong_FromLong((long) st.f_bfree));
  10534. SET_RESULT(PyLong_FromLong((long) st.f_bavail));
  10535. SET_RESULT(PyLong_FromLong((long) st.f_files));
  10536. SET_RESULT(PyLong_FromLong((long) st.f_ffree));
  10537. SET_RESULT(PyLong_FromLong((long) st.f_favail));
  10538. SET_RESULT(PyLong_FromLong((long) st.f_flag));
  10539. SET_RESULT(PyLong_FromLong((long) st.f_namemax));
  10540. #else
  10541. SET_RESULT(PyLong_FromLong((long) st.f_bsize));
  10542. SET_RESULT(PyLong_FromLong((long) st.f_frsize));
  10543. SET_RESULT(PyLong_FromLongLong((long long) st.f_blocks));
  10544. SET_RESULT(PyLong_FromLongLong((long long) st.f_bfree));
  10545. SET_RESULT(PyLong_FromLongLong((long long) st.f_bavail));
  10546. SET_RESULT(PyLong_FromLongLong((long long) st.f_files));
  10547. SET_RESULT(PyLong_FromLongLong((long long) st.f_ffree));
  10548. SET_RESULT(PyLong_FromLongLong((long long) st.f_favail));
  10549. SET_RESULT(PyLong_FromLong((long) st.f_flag));
  10550. SET_RESULT(PyLong_FromLong((long) st.f_namemax));
  10551. #endif
  10552. /* The _ALL_SOURCE feature test macro defines f_fsid as a structure
  10553. * (issue #32390). */
  10554. #if defined(_AIX) && defined(_ALL_SOURCE)
  10555. SET_RESULT(PyLong_FromUnsignedLong(st.f_fsid.val[0]));
  10556. #else
  10557. SET_RESULT(PyLong_FromUnsignedLong(st.f_fsid));
  10558. #endif
  10559. #undef SET_RESULT
  10560. return v;
  10561. }
  10562. /*[clinic input]
  10563. os.fstatvfs
  10564. fd: int
  10565. /
  10566. Perform an fstatvfs system call on the given fd.
  10567. Equivalent to statvfs(fd).
  10568. [clinic start generated code]*/
  10569. static PyObject *
  10570. os_fstatvfs_impl(PyObject *module, int fd)
  10571. /*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
  10572. {
  10573. int result;
  10574. int async_err = 0;
  10575. struct statvfs st;
  10576. do {
  10577. Py_BEGIN_ALLOW_THREADS
  10578. result = fstatvfs(fd, &st);
  10579. Py_END_ALLOW_THREADS
  10580. } while (result != 0 && errno == EINTR &&
  10581. !(async_err = PyErr_CheckSignals()));
  10582. if (result != 0)
  10583. return (!async_err) ? posix_error() : NULL;
  10584. return _pystatvfs_fromstructstatvfs(module, st);
  10585. }
  10586. #endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
  10587. #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
  10588. #include <sys/statvfs.h>
  10589. /*[clinic input]
  10590. os.statvfs
  10591. path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
  10592. Perform a statvfs system call on the given path.
  10593. path may always be specified as a string.
  10594. On some platforms, path may also be specified as an open file descriptor.
  10595. If this functionality is unavailable, using it raises an exception.
  10596. [clinic start generated code]*/
  10597. static PyObject *
  10598. os_statvfs_impl(PyObject *module, path_t *path)
  10599. /*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
  10600. {
  10601. int result;
  10602. struct statvfs st;
  10603. Py_BEGIN_ALLOW_THREADS
  10604. #ifdef HAVE_FSTATVFS
  10605. if (path->fd != -1) {
  10606. result = fstatvfs(path->fd, &st);
  10607. }
  10608. else
  10609. #endif
  10610. result = statvfs(path->narrow, &st);
  10611. Py_END_ALLOW_THREADS
  10612. if (result) {
  10613. return path_error(path);
  10614. }
  10615. return _pystatvfs_fromstructstatvfs(module, st);
  10616. }
  10617. #endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
  10618. #ifdef MS_WINDOWS
  10619. /*[clinic input]
  10620. os._getdiskusage
  10621. path: path_t
  10622. Return disk usage statistics about the given path as a (total, free) tuple.
  10623. [clinic start generated code]*/
  10624. static PyObject *
  10625. os__getdiskusage_impl(PyObject *module, path_t *path)
  10626. /*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
  10627. {
  10628. BOOL retval;
  10629. ULARGE_INTEGER _, total, free;
  10630. DWORD err = 0;
  10631. Py_BEGIN_ALLOW_THREADS
  10632. retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
  10633. Py_END_ALLOW_THREADS
  10634. if (retval == 0) {
  10635. if (GetLastError() == ERROR_DIRECTORY) {
  10636. wchar_t *dir_path = NULL;
  10637. dir_path = PyMem_New(wchar_t, path->length + 1);
  10638. if (dir_path == NULL) {
  10639. return PyErr_NoMemory();
  10640. }
  10641. wcscpy_s(dir_path, path->length + 1, path->wide);
  10642. if (_dirnameW(dir_path) != -1) {
  10643. Py_BEGIN_ALLOW_THREADS
  10644. retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
  10645. Py_END_ALLOW_THREADS
  10646. }
  10647. /* Record the last error in case it's modified by PyMem_Free. */
  10648. err = GetLastError();
  10649. PyMem_Free(dir_path);
  10650. if (retval) {
  10651. goto success;
  10652. }
  10653. }
  10654. return PyErr_SetFromWindowsErr(err);
  10655. }
  10656. success:
  10657. return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
  10658. }
  10659. #endif /* MS_WINDOWS */
  10660. /* This is used for fpathconf(), pathconf(), confstr() and sysconf().
  10661. * It maps strings representing configuration variable names to
  10662. * integer values, allowing those functions to be called with the
  10663. * magic names instead of polluting the module's namespace with tons of
  10664. * rarely-used constants. There are three separate tables that use
  10665. * these definitions.
  10666. *
  10667. * This code is always included, even if none of the interfaces that
  10668. * need it are included. The #if hackery needed to avoid it would be
  10669. * sufficiently pervasive that it's not worth the loss of readability.
  10670. */
  10671. struct constdef {
  10672. const char *name;
  10673. int value;
  10674. };
  10675. static int
  10676. conv_confname(PyObject *arg, int *valuep, struct constdef *table,
  10677. size_t tablesize)
  10678. {
  10679. if (PyLong_Check(arg)) {
  10680. int value = _PyLong_AsInt(arg);
  10681. if (value == -1 && PyErr_Occurred())
  10682. return 0;
  10683. *valuep = value;
  10684. return 1;
  10685. }
  10686. else {
  10687. /* look up the value in the table using a binary search */
  10688. size_t lo = 0;
  10689. size_t mid;
  10690. size_t hi = tablesize;
  10691. int cmp;
  10692. const char *confname;
  10693. if (!PyUnicode_Check(arg)) {
  10694. PyErr_SetString(PyExc_TypeError,
  10695. "configuration names must be strings or integers");
  10696. return 0;
  10697. }
  10698. confname = PyUnicode_AsUTF8(arg);
  10699. if (confname == NULL)
  10700. return 0;
  10701. while (lo < hi) {
  10702. mid = (lo + hi) / 2;
  10703. cmp = strcmp(confname, table[mid].name);
  10704. if (cmp < 0)
  10705. hi = mid;
  10706. else if (cmp > 0)
  10707. lo = mid + 1;
  10708. else {
  10709. *valuep = table[mid].value;
  10710. return 1;
  10711. }
  10712. }
  10713. PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
  10714. return 0;
  10715. }
  10716. }
  10717. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  10718. static struct constdef posix_constants_pathconf[] = {
  10719. #ifdef _PC_ABI_AIO_XFER_MAX
  10720. {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
  10721. #endif
  10722. #ifdef _PC_ABI_ASYNC_IO
  10723. {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
  10724. #endif
  10725. #ifdef _PC_ASYNC_IO
  10726. {"PC_ASYNC_IO", _PC_ASYNC_IO},
  10727. #endif
  10728. #ifdef _PC_CHOWN_RESTRICTED
  10729. {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
  10730. #endif
  10731. #ifdef _PC_FILESIZEBITS
  10732. {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
  10733. #endif
  10734. #ifdef _PC_LAST
  10735. {"PC_LAST", _PC_LAST},
  10736. #endif
  10737. #ifdef _PC_LINK_MAX
  10738. {"PC_LINK_MAX", _PC_LINK_MAX},
  10739. #endif
  10740. #ifdef _PC_MAX_CANON
  10741. {"PC_MAX_CANON", _PC_MAX_CANON},
  10742. #endif
  10743. #ifdef _PC_MAX_INPUT
  10744. {"PC_MAX_INPUT", _PC_MAX_INPUT},
  10745. #endif
  10746. #ifdef _PC_NAME_MAX
  10747. {"PC_NAME_MAX", _PC_NAME_MAX},
  10748. #endif
  10749. #ifdef _PC_NO_TRUNC
  10750. {"PC_NO_TRUNC", _PC_NO_TRUNC},
  10751. #endif
  10752. #ifdef _PC_PATH_MAX
  10753. {"PC_PATH_MAX", _PC_PATH_MAX},
  10754. #endif
  10755. #ifdef _PC_PIPE_BUF
  10756. {"PC_PIPE_BUF", _PC_PIPE_BUF},
  10757. #endif
  10758. #ifdef _PC_PRIO_IO
  10759. {"PC_PRIO_IO", _PC_PRIO_IO},
  10760. #endif
  10761. #ifdef _PC_SOCK_MAXBUF
  10762. {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
  10763. #endif
  10764. #ifdef _PC_SYNC_IO
  10765. {"PC_SYNC_IO", _PC_SYNC_IO},
  10766. #endif
  10767. #ifdef _PC_VDISABLE
  10768. {"PC_VDISABLE", _PC_VDISABLE},
  10769. #endif
  10770. #ifdef _PC_ACL_ENABLED
  10771. {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
  10772. #endif
  10773. #ifdef _PC_MIN_HOLE_SIZE
  10774. {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
  10775. #endif
  10776. #ifdef _PC_ALLOC_SIZE_MIN
  10777. {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
  10778. #endif
  10779. #ifdef _PC_REC_INCR_XFER_SIZE
  10780. {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
  10781. #endif
  10782. #ifdef _PC_REC_MAX_XFER_SIZE
  10783. {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
  10784. #endif
  10785. #ifdef _PC_REC_MIN_XFER_SIZE
  10786. {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
  10787. #endif
  10788. #ifdef _PC_REC_XFER_ALIGN
  10789. {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
  10790. #endif
  10791. #ifdef _PC_SYMLINK_MAX
  10792. {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
  10793. #endif
  10794. #ifdef _PC_XATTR_ENABLED
  10795. {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
  10796. #endif
  10797. #ifdef _PC_XATTR_EXISTS
  10798. {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
  10799. #endif
  10800. #ifdef _PC_TIMESTAMP_RESOLUTION
  10801. {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
  10802. #endif
  10803. };
  10804. static int
  10805. conv_path_confname(PyObject *arg, int *valuep)
  10806. {
  10807. return conv_confname(arg, valuep, posix_constants_pathconf,
  10808. sizeof(posix_constants_pathconf)
  10809. / sizeof(struct constdef));
  10810. }
  10811. #endif
  10812. #ifdef HAVE_FPATHCONF
  10813. /*[clinic input]
  10814. os.fpathconf -> long
  10815. fd: fildes
  10816. name: path_confname
  10817. /
  10818. Return the configuration limit name for the file descriptor fd.
  10819. If there is no limit, return -1.
  10820. [clinic start generated code]*/
  10821. static long
  10822. os_fpathconf_impl(PyObject *module, int fd, int name)
  10823. /*[clinic end generated code: output=d5b7042425fc3e21 input=5b8d2471cfaae186]*/
  10824. {
  10825. long limit;
  10826. errno = 0;
  10827. limit = fpathconf(fd, name);
  10828. if (limit == -1 && errno != 0)
  10829. posix_error();
  10830. return limit;
  10831. }
  10832. #endif /* HAVE_FPATHCONF */
  10833. #ifdef HAVE_PATHCONF
  10834. /*[clinic input]
  10835. os.pathconf -> long
  10836. path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
  10837. name: path_confname
  10838. Return the configuration limit name for the file or directory path.
  10839. If there is no limit, return -1.
  10840. On some platforms, path may also be specified as an open file descriptor.
  10841. If this functionality is unavailable, using it raises an exception.
  10842. [clinic start generated code]*/
  10843. static long
  10844. os_pathconf_impl(PyObject *module, path_t *path, int name)
  10845. /*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
  10846. {
  10847. long limit;
  10848. errno = 0;
  10849. #ifdef HAVE_FPATHCONF
  10850. if (path->fd != -1)
  10851. limit = fpathconf(path->fd, name);
  10852. else
  10853. #endif
  10854. limit = pathconf(path->narrow, name);
  10855. if (limit == -1 && errno != 0) {
  10856. if (errno == EINVAL)
  10857. /* could be a path or name problem */
  10858. posix_error();
  10859. else
  10860. path_error(path);
  10861. }
  10862. return limit;
  10863. }
  10864. #endif /* HAVE_PATHCONF */
  10865. #ifdef HAVE_CONFSTR
  10866. static struct constdef posix_constants_confstr[] = {
  10867. #ifdef _CS_ARCHITECTURE
  10868. {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
  10869. #endif
  10870. #ifdef _CS_GNU_LIBC_VERSION
  10871. {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
  10872. #endif
  10873. #ifdef _CS_GNU_LIBPTHREAD_VERSION
  10874. {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
  10875. #endif
  10876. #ifdef _CS_HOSTNAME
  10877. {"CS_HOSTNAME", _CS_HOSTNAME},
  10878. #endif
  10879. #ifdef _CS_HW_PROVIDER
  10880. {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
  10881. #endif
  10882. #ifdef _CS_HW_SERIAL
  10883. {"CS_HW_SERIAL", _CS_HW_SERIAL},
  10884. #endif
  10885. #ifdef _CS_INITTAB_NAME
  10886. {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
  10887. #endif
  10888. #ifdef _CS_LFS64_CFLAGS
  10889. {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
  10890. #endif
  10891. #ifdef _CS_LFS64_LDFLAGS
  10892. {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
  10893. #endif
  10894. #ifdef _CS_LFS64_LIBS
  10895. {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
  10896. #endif
  10897. #ifdef _CS_LFS64_LINTFLAGS
  10898. {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
  10899. #endif
  10900. #ifdef _CS_LFS_CFLAGS
  10901. {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
  10902. #endif
  10903. #ifdef _CS_LFS_LDFLAGS
  10904. {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
  10905. #endif
  10906. #ifdef _CS_LFS_LIBS
  10907. {"CS_LFS_LIBS", _CS_LFS_LIBS},
  10908. #endif
  10909. #ifdef _CS_LFS_LINTFLAGS
  10910. {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
  10911. #endif
  10912. #ifdef _CS_MACHINE
  10913. {"CS_MACHINE", _CS_MACHINE},
  10914. #endif
  10915. #ifdef _CS_PATH
  10916. {"CS_PATH", _CS_PATH},
  10917. #endif
  10918. #ifdef _CS_RELEASE
  10919. {"CS_RELEASE", _CS_RELEASE},
  10920. #endif
  10921. #ifdef _CS_SRPC_DOMAIN
  10922. {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
  10923. #endif
  10924. #ifdef _CS_SYSNAME
  10925. {"CS_SYSNAME", _CS_SYSNAME},
  10926. #endif
  10927. #ifdef _CS_VERSION
  10928. {"CS_VERSION", _CS_VERSION},
  10929. #endif
  10930. #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
  10931. {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
  10932. #endif
  10933. #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
  10934. {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
  10935. #endif
  10936. #ifdef _CS_XBS5_ILP32_OFF32_LIBS
  10937. {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
  10938. #endif
  10939. #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
  10940. {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
  10941. #endif
  10942. #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
  10943. {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
  10944. #endif
  10945. #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
  10946. {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
  10947. #endif
  10948. #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
  10949. {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
  10950. #endif
  10951. #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
  10952. {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
  10953. #endif
  10954. #ifdef _CS_XBS5_LP64_OFF64_CFLAGS
  10955. {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
  10956. #endif
  10957. #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
  10958. {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
  10959. #endif
  10960. #ifdef _CS_XBS5_LP64_OFF64_LIBS
  10961. {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
  10962. #endif
  10963. #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
  10964. {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
  10965. #endif
  10966. #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
  10967. {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
  10968. #endif
  10969. #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
  10970. {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
  10971. #endif
  10972. #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
  10973. {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
  10974. #endif
  10975. #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
  10976. {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
  10977. #endif
  10978. #ifdef _MIPS_CS_AVAIL_PROCESSORS
  10979. {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
  10980. #endif
  10981. #ifdef _MIPS_CS_BASE
  10982. {"MIPS_CS_BASE", _MIPS_CS_BASE},
  10983. #endif
  10984. #ifdef _MIPS_CS_HOSTID
  10985. {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
  10986. #endif
  10987. #ifdef _MIPS_CS_HW_NAME
  10988. {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
  10989. #endif
  10990. #ifdef _MIPS_CS_NUM_PROCESSORS
  10991. {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
  10992. #endif
  10993. #ifdef _MIPS_CS_OSREL_MAJ
  10994. {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
  10995. #endif
  10996. #ifdef _MIPS_CS_OSREL_MIN
  10997. {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
  10998. #endif
  10999. #ifdef _MIPS_CS_OSREL_PATCH
  11000. {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
  11001. #endif
  11002. #ifdef _MIPS_CS_OS_NAME
  11003. {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
  11004. #endif
  11005. #ifdef _MIPS_CS_OS_PROVIDER
  11006. {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
  11007. #endif
  11008. #ifdef _MIPS_CS_PROCESSORS
  11009. {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
  11010. #endif
  11011. #ifdef _MIPS_CS_SERIAL
  11012. {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
  11013. #endif
  11014. #ifdef _MIPS_CS_VENDOR
  11015. {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
  11016. #endif
  11017. };
  11018. static int
  11019. conv_confstr_confname(PyObject *arg, int *valuep)
  11020. {
  11021. return conv_confname(arg, valuep, posix_constants_confstr,
  11022. sizeof(posix_constants_confstr)
  11023. / sizeof(struct constdef));
  11024. }
  11025. /*[clinic input]
  11026. os.confstr
  11027. name: confstr_confname
  11028. /
  11029. Return a string-valued system configuration variable.
  11030. [clinic start generated code]*/
  11031. static PyObject *
  11032. os_confstr_impl(PyObject *module, int name)
  11033. /*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
  11034. {
  11035. PyObject *result = NULL;
  11036. char buffer[255];
  11037. size_t len;
  11038. errno = 0;
  11039. len = confstr(name, buffer, sizeof(buffer));
  11040. if (len == 0) {
  11041. if (errno) {
  11042. posix_error();
  11043. return NULL;
  11044. }
  11045. else {
  11046. Py_RETURN_NONE;
  11047. }
  11048. }
  11049. if (len >= sizeof(buffer)) {
  11050. size_t len2;
  11051. char *buf = PyMem_Malloc(len);
  11052. if (buf == NULL)
  11053. return PyErr_NoMemory();
  11054. len2 = confstr(name, buf, len);
  11055. assert(len == len2);
  11056. result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
  11057. PyMem_Free(buf);
  11058. }
  11059. else
  11060. result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
  11061. return result;
  11062. }
  11063. #endif /* HAVE_CONFSTR */
  11064. #ifdef HAVE_SYSCONF
  11065. static struct constdef posix_constants_sysconf[] = {
  11066. #ifdef _SC_2_CHAR_TERM
  11067. {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
  11068. #endif
  11069. #ifdef _SC_2_C_BIND
  11070. {"SC_2_C_BIND", _SC_2_C_BIND},
  11071. #endif
  11072. #ifdef _SC_2_C_DEV
  11073. {"SC_2_C_DEV", _SC_2_C_DEV},
  11074. #endif
  11075. #ifdef _SC_2_C_VERSION
  11076. {"SC_2_C_VERSION", _SC_2_C_VERSION},
  11077. #endif
  11078. #ifdef _SC_2_FORT_DEV
  11079. {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
  11080. #endif
  11081. #ifdef _SC_2_FORT_RUN
  11082. {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
  11083. #endif
  11084. #ifdef _SC_2_LOCALEDEF
  11085. {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
  11086. #endif
  11087. #ifdef _SC_2_SW_DEV
  11088. {"SC_2_SW_DEV", _SC_2_SW_DEV},
  11089. #endif
  11090. #ifdef _SC_2_UPE
  11091. {"SC_2_UPE", _SC_2_UPE},
  11092. #endif
  11093. #ifdef _SC_2_VERSION
  11094. {"SC_2_VERSION", _SC_2_VERSION},
  11095. #endif
  11096. #ifdef _SC_ABI_ASYNCHRONOUS_IO
  11097. {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
  11098. #endif
  11099. #ifdef _SC_ACL
  11100. {"SC_ACL", _SC_ACL},
  11101. #endif
  11102. #ifdef _SC_AIO_LISTIO_MAX
  11103. {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
  11104. #endif
  11105. #ifdef _SC_AIO_MAX
  11106. {"SC_AIO_MAX", _SC_AIO_MAX},
  11107. #endif
  11108. #ifdef _SC_AIO_PRIO_DELTA_MAX
  11109. {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
  11110. #endif
  11111. #ifdef _SC_ARG_MAX
  11112. {"SC_ARG_MAX", _SC_ARG_MAX},
  11113. #endif
  11114. #ifdef _SC_ASYNCHRONOUS_IO
  11115. {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
  11116. #endif
  11117. #ifdef _SC_ATEXIT_MAX
  11118. {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
  11119. #endif
  11120. #ifdef _SC_AUDIT
  11121. {"SC_AUDIT", _SC_AUDIT},
  11122. #endif
  11123. #ifdef _SC_AVPHYS_PAGES
  11124. {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
  11125. #endif
  11126. #ifdef _SC_BC_BASE_MAX
  11127. {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
  11128. #endif
  11129. #ifdef _SC_BC_DIM_MAX
  11130. {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
  11131. #endif
  11132. #ifdef _SC_BC_SCALE_MAX
  11133. {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
  11134. #endif
  11135. #ifdef _SC_BC_STRING_MAX
  11136. {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
  11137. #endif
  11138. #ifdef _SC_CAP
  11139. {"SC_CAP", _SC_CAP},
  11140. #endif
  11141. #ifdef _SC_CHARCLASS_NAME_MAX
  11142. {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
  11143. #endif
  11144. #ifdef _SC_CHAR_BIT
  11145. {"SC_CHAR_BIT", _SC_CHAR_BIT},
  11146. #endif
  11147. #ifdef _SC_CHAR_MAX
  11148. {"SC_CHAR_MAX", _SC_CHAR_MAX},
  11149. #endif
  11150. #ifdef _SC_CHAR_MIN
  11151. {"SC_CHAR_MIN", _SC_CHAR_MIN},
  11152. #endif
  11153. #ifdef _SC_CHILD_MAX
  11154. {"SC_CHILD_MAX", _SC_CHILD_MAX},
  11155. #endif
  11156. #ifdef _SC_CLK_TCK
  11157. {"SC_CLK_TCK", _SC_CLK_TCK},
  11158. #endif
  11159. #ifdef _SC_COHER_BLKSZ
  11160. {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
  11161. #endif
  11162. #ifdef _SC_COLL_WEIGHTS_MAX
  11163. {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
  11164. #endif
  11165. #ifdef _SC_DCACHE_ASSOC
  11166. {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
  11167. #endif
  11168. #ifdef _SC_DCACHE_BLKSZ
  11169. {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
  11170. #endif
  11171. #ifdef _SC_DCACHE_LINESZ
  11172. {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
  11173. #endif
  11174. #ifdef _SC_DCACHE_SZ
  11175. {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
  11176. #endif
  11177. #ifdef _SC_DCACHE_TBLKSZ
  11178. {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
  11179. #endif
  11180. #ifdef _SC_DELAYTIMER_MAX
  11181. {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
  11182. #endif
  11183. #ifdef _SC_EQUIV_CLASS_MAX
  11184. {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
  11185. #endif
  11186. #ifdef _SC_EXPR_NEST_MAX
  11187. {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
  11188. #endif
  11189. #ifdef _SC_FSYNC
  11190. {"SC_FSYNC", _SC_FSYNC},
  11191. #endif
  11192. #ifdef _SC_GETGR_R_SIZE_MAX
  11193. {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
  11194. #endif
  11195. #ifdef _SC_GETPW_R_SIZE_MAX
  11196. {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
  11197. #endif
  11198. #ifdef _SC_ICACHE_ASSOC
  11199. {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
  11200. #endif
  11201. #ifdef _SC_ICACHE_BLKSZ
  11202. {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
  11203. #endif
  11204. #ifdef _SC_ICACHE_LINESZ
  11205. {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
  11206. #endif
  11207. #ifdef _SC_ICACHE_SZ
  11208. {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
  11209. #endif
  11210. #ifdef _SC_INF
  11211. {"SC_INF", _SC_INF},
  11212. #endif
  11213. #ifdef _SC_INT_MAX
  11214. {"SC_INT_MAX", _SC_INT_MAX},
  11215. #endif
  11216. #ifdef _SC_INT_MIN
  11217. {"SC_INT_MIN", _SC_INT_MIN},
  11218. #endif
  11219. #ifdef _SC_IOV_MAX
  11220. {"SC_IOV_MAX", _SC_IOV_MAX},
  11221. #endif
  11222. #ifdef _SC_IP_SECOPTS
  11223. {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
  11224. #endif
  11225. #ifdef _SC_JOB_CONTROL
  11226. {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
  11227. #endif
  11228. #ifdef _SC_KERN_POINTERS
  11229. {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
  11230. #endif
  11231. #ifdef _SC_KERN_SIM
  11232. {"SC_KERN_SIM", _SC_KERN_SIM},
  11233. #endif
  11234. #ifdef _SC_LINE_MAX
  11235. {"SC_LINE_MAX", _SC_LINE_MAX},
  11236. #endif
  11237. #ifdef _SC_LOGIN_NAME_MAX
  11238. {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
  11239. #endif
  11240. #ifdef _SC_LOGNAME_MAX
  11241. {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
  11242. #endif
  11243. #ifdef _SC_LONG_BIT
  11244. {"SC_LONG_BIT", _SC_LONG_BIT},
  11245. #endif
  11246. #ifdef _SC_MAC
  11247. {"SC_MAC", _SC_MAC},
  11248. #endif
  11249. #ifdef _SC_MAPPED_FILES
  11250. {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
  11251. #endif
  11252. #ifdef _SC_MAXPID
  11253. {"SC_MAXPID", _SC_MAXPID},
  11254. #endif
  11255. #ifdef _SC_MB_LEN_MAX
  11256. {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
  11257. #endif
  11258. #ifdef _SC_MEMLOCK
  11259. {"SC_MEMLOCK", _SC_MEMLOCK},
  11260. #endif
  11261. #ifdef _SC_MEMLOCK_RANGE
  11262. {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
  11263. #endif
  11264. #ifdef _SC_MEMORY_PROTECTION
  11265. {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
  11266. #endif
  11267. #ifdef _SC_MESSAGE_PASSING
  11268. {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
  11269. #endif
  11270. #ifdef _SC_MMAP_FIXED_ALIGNMENT
  11271. {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
  11272. #endif
  11273. #ifdef _SC_MQ_OPEN_MAX
  11274. {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
  11275. #endif
  11276. #ifdef _SC_MQ_PRIO_MAX
  11277. {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
  11278. #endif
  11279. #ifdef _SC_NACLS_MAX
  11280. {"SC_NACLS_MAX", _SC_NACLS_MAX},
  11281. #endif
  11282. #ifdef _SC_NGROUPS_MAX
  11283. {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
  11284. #endif
  11285. #ifdef _SC_NL_ARGMAX
  11286. {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
  11287. #endif
  11288. #ifdef _SC_NL_LANGMAX
  11289. {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
  11290. #endif
  11291. #ifdef _SC_NL_MSGMAX
  11292. {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
  11293. #endif
  11294. #ifdef _SC_NL_NMAX
  11295. {"SC_NL_NMAX", _SC_NL_NMAX},
  11296. #endif
  11297. #ifdef _SC_NL_SETMAX
  11298. {"SC_NL_SETMAX", _SC_NL_SETMAX},
  11299. #endif
  11300. #ifdef _SC_NL_TEXTMAX
  11301. {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
  11302. #endif
  11303. #ifdef _SC_NPROCESSORS_CONF
  11304. {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
  11305. #endif
  11306. #ifdef _SC_NPROCESSORS_ONLN
  11307. {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
  11308. #endif
  11309. #ifdef _SC_NPROC_CONF
  11310. {"SC_NPROC_CONF", _SC_NPROC_CONF},
  11311. #endif
  11312. #ifdef _SC_NPROC_ONLN
  11313. {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
  11314. #endif
  11315. #ifdef _SC_NZERO
  11316. {"SC_NZERO", _SC_NZERO},
  11317. #endif
  11318. #ifdef _SC_OPEN_MAX
  11319. {"SC_OPEN_MAX", _SC_OPEN_MAX},
  11320. #endif
  11321. #ifdef _SC_PAGESIZE
  11322. {"SC_PAGESIZE", _SC_PAGESIZE},
  11323. #endif
  11324. #ifdef _SC_PAGE_SIZE
  11325. {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
  11326. #endif
  11327. #ifdef _SC_AIX_REALMEM
  11328. {"SC_AIX_REALMEM", _SC_AIX_REALMEM},
  11329. #endif
  11330. #ifdef _SC_PASS_MAX
  11331. {"SC_PASS_MAX", _SC_PASS_MAX},
  11332. #endif
  11333. #ifdef _SC_PHYS_PAGES
  11334. {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
  11335. #endif
  11336. #ifdef _SC_PII
  11337. {"SC_PII", _SC_PII},
  11338. #endif
  11339. #ifdef _SC_PII_INTERNET
  11340. {"SC_PII_INTERNET", _SC_PII_INTERNET},
  11341. #endif
  11342. #ifdef _SC_PII_INTERNET_DGRAM
  11343. {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
  11344. #endif
  11345. #ifdef _SC_PII_INTERNET_STREAM
  11346. {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
  11347. #endif
  11348. #ifdef _SC_PII_OSI
  11349. {"SC_PII_OSI", _SC_PII_OSI},
  11350. #endif
  11351. #ifdef _SC_PII_OSI_CLTS
  11352. {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
  11353. #endif
  11354. #ifdef _SC_PII_OSI_COTS
  11355. {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
  11356. #endif
  11357. #ifdef _SC_PII_OSI_M
  11358. {"SC_PII_OSI_M", _SC_PII_OSI_M},
  11359. #endif
  11360. #ifdef _SC_PII_SOCKET
  11361. {"SC_PII_SOCKET", _SC_PII_SOCKET},
  11362. #endif
  11363. #ifdef _SC_PII_XTI
  11364. {"SC_PII_XTI", _SC_PII_XTI},
  11365. #endif
  11366. #ifdef _SC_POLL
  11367. {"SC_POLL", _SC_POLL},
  11368. #endif
  11369. #ifdef _SC_PRIORITIZED_IO
  11370. {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
  11371. #endif
  11372. #ifdef _SC_PRIORITY_SCHEDULING
  11373. {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
  11374. #endif
  11375. #ifdef _SC_REALTIME_SIGNALS
  11376. {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
  11377. #endif
  11378. #ifdef _SC_RE_DUP_MAX
  11379. {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
  11380. #endif
  11381. #ifdef _SC_RTSIG_MAX
  11382. {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
  11383. #endif
  11384. #ifdef _SC_SAVED_IDS
  11385. {"SC_SAVED_IDS", _SC_SAVED_IDS},
  11386. #endif
  11387. #ifdef _SC_SCHAR_MAX
  11388. {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
  11389. #endif
  11390. #ifdef _SC_SCHAR_MIN
  11391. {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
  11392. #endif
  11393. #ifdef _SC_SELECT
  11394. {"SC_SELECT", _SC_SELECT},
  11395. #endif
  11396. #ifdef _SC_SEMAPHORES
  11397. {"SC_SEMAPHORES", _SC_SEMAPHORES},
  11398. #endif
  11399. #ifdef _SC_SEM_NSEMS_MAX
  11400. {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
  11401. #endif
  11402. #ifdef _SC_SEM_VALUE_MAX
  11403. {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
  11404. #endif
  11405. #ifdef _SC_SHARED_MEMORY_OBJECTS
  11406. {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
  11407. #endif
  11408. #ifdef _SC_SHRT_MAX
  11409. {"SC_SHRT_MAX", _SC_SHRT_MAX},
  11410. #endif
  11411. #ifdef _SC_SHRT_MIN
  11412. {"SC_SHRT_MIN", _SC_SHRT_MIN},
  11413. #endif
  11414. #ifdef _SC_SIGQUEUE_MAX
  11415. {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
  11416. #endif
  11417. #ifdef _SC_SIGRT_MAX
  11418. {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
  11419. #endif
  11420. #ifdef _SC_SIGRT_MIN
  11421. {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
  11422. #endif
  11423. #ifdef _SC_SOFTPOWER
  11424. {"SC_SOFTPOWER", _SC_SOFTPOWER},
  11425. #endif
  11426. #ifdef _SC_SPLIT_CACHE
  11427. {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
  11428. #endif
  11429. #ifdef _SC_SSIZE_MAX
  11430. {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
  11431. #endif
  11432. #ifdef _SC_STACK_PROT
  11433. {"SC_STACK_PROT", _SC_STACK_PROT},
  11434. #endif
  11435. #ifdef _SC_STREAM_MAX
  11436. {"SC_STREAM_MAX", _SC_STREAM_MAX},
  11437. #endif
  11438. #ifdef _SC_SYNCHRONIZED_IO
  11439. {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
  11440. #endif
  11441. #ifdef _SC_THREADS
  11442. {"SC_THREADS", _SC_THREADS},
  11443. #endif
  11444. #ifdef _SC_THREAD_ATTR_STACKADDR
  11445. {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
  11446. #endif
  11447. #ifdef _SC_THREAD_ATTR_STACKSIZE
  11448. {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
  11449. #endif
  11450. #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
  11451. {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
  11452. #endif
  11453. #ifdef _SC_THREAD_KEYS_MAX
  11454. {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
  11455. #endif
  11456. #ifdef _SC_THREAD_PRIORITY_SCHEDULING
  11457. {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
  11458. #endif
  11459. #ifdef _SC_THREAD_PRIO_INHERIT
  11460. {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
  11461. #endif
  11462. #ifdef _SC_THREAD_PRIO_PROTECT
  11463. {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
  11464. #endif
  11465. #ifdef _SC_THREAD_PROCESS_SHARED
  11466. {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
  11467. #endif
  11468. #ifdef _SC_THREAD_SAFE_FUNCTIONS
  11469. {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
  11470. #endif
  11471. #ifdef _SC_THREAD_STACK_MIN
  11472. {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
  11473. #endif
  11474. #ifdef _SC_THREAD_THREADS_MAX
  11475. {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
  11476. #endif
  11477. #ifdef _SC_TIMERS
  11478. {"SC_TIMERS", _SC_TIMERS},
  11479. #endif
  11480. #ifdef _SC_TIMER_MAX
  11481. {"SC_TIMER_MAX", _SC_TIMER_MAX},
  11482. #endif
  11483. #ifdef _SC_TTY_NAME_MAX
  11484. {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
  11485. #endif
  11486. #ifdef _SC_TZNAME_MAX
  11487. {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
  11488. #endif
  11489. #ifdef _SC_T_IOV_MAX
  11490. {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
  11491. #endif
  11492. #ifdef _SC_UCHAR_MAX
  11493. {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
  11494. #endif
  11495. #ifdef _SC_UINT_MAX
  11496. {"SC_UINT_MAX", _SC_UINT_MAX},
  11497. #endif
  11498. #ifdef _SC_UIO_MAXIOV
  11499. {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
  11500. #endif
  11501. #ifdef _SC_ULONG_MAX
  11502. {"SC_ULONG_MAX", _SC_ULONG_MAX},
  11503. #endif
  11504. #ifdef _SC_USHRT_MAX
  11505. {"SC_USHRT_MAX", _SC_USHRT_MAX},
  11506. #endif
  11507. #ifdef _SC_VERSION
  11508. {"SC_VERSION", _SC_VERSION},
  11509. #endif
  11510. #ifdef _SC_WORD_BIT
  11511. {"SC_WORD_BIT", _SC_WORD_BIT},
  11512. #endif
  11513. #ifdef _SC_XBS5_ILP32_OFF32
  11514. {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
  11515. #endif
  11516. #ifdef _SC_XBS5_ILP32_OFFBIG
  11517. {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
  11518. #endif
  11519. #ifdef _SC_XBS5_LP64_OFF64
  11520. {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
  11521. #endif
  11522. #ifdef _SC_XBS5_LPBIG_OFFBIG
  11523. {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
  11524. #endif
  11525. #ifdef _SC_XOPEN_CRYPT
  11526. {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
  11527. #endif
  11528. #ifdef _SC_XOPEN_ENH_I18N
  11529. {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
  11530. #endif
  11531. #ifdef _SC_XOPEN_LEGACY
  11532. {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
  11533. #endif
  11534. #ifdef _SC_XOPEN_REALTIME
  11535. {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
  11536. #endif
  11537. #ifdef _SC_XOPEN_REALTIME_THREADS
  11538. {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
  11539. #endif
  11540. #ifdef _SC_XOPEN_SHM
  11541. {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
  11542. #endif
  11543. #ifdef _SC_XOPEN_UNIX
  11544. {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
  11545. #endif
  11546. #ifdef _SC_XOPEN_VERSION
  11547. {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
  11548. #endif
  11549. #ifdef _SC_XOPEN_XCU_VERSION
  11550. {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
  11551. #endif
  11552. #ifdef _SC_XOPEN_XPG2
  11553. {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
  11554. #endif
  11555. #ifdef _SC_XOPEN_XPG3
  11556. {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
  11557. #endif
  11558. #ifdef _SC_XOPEN_XPG4
  11559. {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
  11560. #endif
  11561. #ifdef _SC_MINSIGSTKSZ
  11562. {"SC_MINSIGSTKSZ", _SC_MINSIGSTKSZ},
  11563. #endif
  11564. };
  11565. static int
  11566. conv_sysconf_confname(PyObject *arg, int *valuep)
  11567. {
  11568. return conv_confname(arg, valuep, posix_constants_sysconf,
  11569. sizeof(posix_constants_sysconf)
  11570. / sizeof(struct constdef));
  11571. }
  11572. /*[clinic input]
  11573. os.sysconf -> long
  11574. name: sysconf_confname
  11575. /
  11576. Return an integer-valued system configuration variable.
  11577. [clinic start generated code]*/
  11578. static long
  11579. os_sysconf_impl(PyObject *module, int name)
  11580. /*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
  11581. {
  11582. long value;
  11583. errno = 0;
  11584. value = sysconf(name);
  11585. if (value == -1 && errno != 0)
  11586. posix_error();
  11587. return value;
  11588. }
  11589. #endif /* HAVE_SYSCONF */
  11590. /* This code is used to ensure that the tables of configuration value names
  11591. * are in sorted order as required by conv_confname(), and also to build
  11592. * the exported dictionaries that are used to publish information about the
  11593. * names available on the host platform.
  11594. *
  11595. * Sorting the table at runtime ensures that the table is properly ordered
  11596. * when used, even for platforms we're not able to test on. It also makes
  11597. * it easier to add additional entries to the tables.
  11598. */
  11599. static int
  11600. cmp_constdefs(const void *v1, const void *v2)
  11601. {
  11602. const struct constdef *c1 =
  11603. (const struct constdef *) v1;
  11604. const struct constdef *c2 =
  11605. (const struct constdef *) v2;
  11606. return strcmp(c1->name, c2->name);
  11607. }
  11608. static int
  11609. setup_confname_table(struct constdef *table, size_t tablesize,
  11610. const char *tablename, PyObject *module)
  11611. {
  11612. PyObject *d = NULL;
  11613. size_t i;
  11614. qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
  11615. d = PyDict_New();
  11616. if (d == NULL)
  11617. return -1;
  11618. for (i=0; i < tablesize; ++i) {
  11619. PyObject *o = PyLong_FromLong(table[i].value);
  11620. if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
  11621. Py_XDECREF(o);
  11622. Py_DECREF(d);
  11623. return -1;
  11624. }
  11625. Py_DECREF(o);
  11626. }
  11627. return _PyModule_Add(module, tablename, d);
  11628. }
  11629. /* Return -1 on failure, 0 on success. */
  11630. static int
  11631. setup_confname_tables(PyObject *module)
  11632. {
  11633. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  11634. if (setup_confname_table(posix_constants_pathconf,
  11635. sizeof(posix_constants_pathconf)
  11636. / sizeof(struct constdef),
  11637. "pathconf_names", module))
  11638. return -1;
  11639. #endif
  11640. #ifdef HAVE_CONFSTR
  11641. if (setup_confname_table(posix_constants_confstr,
  11642. sizeof(posix_constants_confstr)
  11643. / sizeof(struct constdef),
  11644. "confstr_names", module))
  11645. return -1;
  11646. #endif
  11647. #ifdef HAVE_SYSCONF
  11648. if (setup_confname_table(posix_constants_sysconf,
  11649. sizeof(posix_constants_sysconf)
  11650. / sizeof(struct constdef),
  11651. "sysconf_names", module))
  11652. return -1;
  11653. #endif
  11654. return 0;
  11655. }
  11656. /*[clinic input]
  11657. os.abort
  11658. Abort the interpreter immediately.
  11659. This function 'dumps core' or otherwise fails in the hardest way possible
  11660. on the hosting operating system. This function never returns.
  11661. [clinic start generated code]*/
  11662. static PyObject *
  11663. os_abort_impl(PyObject *module)
  11664. /*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
  11665. {
  11666. abort();
  11667. /*NOTREACHED*/
  11668. #ifndef __clang__
  11669. /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
  11670. GCC emits a warning without "return NULL;" (compiler bug?), but Clang
  11671. is smarter and emits a warning on the return. */
  11672. Py_FatalError("abort() called from Python code didn't abort!");
  11673. return NULL;
  11674. #endif
  11675. }
  11676. #ifdef MS_WINDOWS
  11677. /* Grab ShellExecute dynamically from shell32 */
  11678. static int has_ShellExecute = -1;
  11679. static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
  11680. LPCWSTR, INT);
  11681. static int
  11682. check_ShellExecute(void)
  11683. {
  11684. HINSTANCE hShell32;
  11685. /* only recheck */
  11686. if (-1 == has_ShellExecute) {
  11687. Py_BEGIN_ALLOW_THREADS
  11688. /* Security note: this call is not vulnerable to "DLL hijacking".
  11689. SHELL32 is part of "KnownDLLs" and so Windows always load
  11690. the system SHELL32.DLL, even if there is another SHELL32.DLL
  11691. in the DLL search path. */
  11692. hShell32 = LoadLibraryW(L"SHELL32");
  11693. if (hShell32) {
  11694. *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
  11695. "ShellExecuteW");
  11696. has_ShellExecute = Py_ShellExecuteW != NULL;
  11697. } else {
  11698. has_ShellExecute = 0;
  11699. }
  11700. Py_END_ALLOW_THREADS
  11701. }
  11702. return has_ShellExecute;
  11703. }
  11704. /*[clinic input]
  11705. os.startfile
  11706. filepath: path_t
  11707. operation: Py_UNICODE = NULL
  11708. arguments: Py_UNICODE = NULL
  11709. cwd: path_t(nullable=True) = None
  11710. show_cmd: int = 1
  11711. Start a file with its associated application.
  11712. When "operation" is not specified or "open", this acts like
  11713. double-clicking the file in Explorer, or giving the file name as an
  11714. argument to the DOS "start" command: the file is opened with whatever
  11715. application (if any) its extension is associated.
  11716. When another "operation" is given, it specifies what should be done with
  11717. the file. A typical operation is "print".
  11718. "arguments" is passed to the application, but should be omitted if the
  11719. file is a document.
  11720. "cwd" is the working directory for the operation. If "filepath" is
  11721. relative, it will be resolved against this directory. This argument
  11722. should usually be an absolute path.
  11723. "show_cmd" can be used to override the recommended visibility option.
  11724. See the Windows ShellExecute documentation for values.
  11725. startfile returns as soon as the associated application is launched.
  11726. There is no option to wait for the application to close, and no way
  11727. to retrieve the application's exit status.
  11728. The filepath is relative to the current directory. If you want to use
  11729. an absolute path, make sure the first character is not a slash ("/");
  11730. the underlying Win32 ShellExecute function doesn't work if it is.
  11731. [clinic start generated code]*/
  11732. static PyObject *
  11733. os_startfile_impl(PyObject *module, path_t *filepath,
  11734. const Py_UNICODE *operation, const Py_UNICODE *arguments,
  11735. path_t *cwd, int show_cmd)
  11736. /*[clinic end generated code: output=3baa4f9795841880 input=8248997b80669622]*/
  11737. {
  11738. HINSTANCE rc;
  11739. if(!check_ShellExecute()) {
  11740. /* If the OS doesn't have ShellExecute, return a
  11741. NotImplementedError. */
  11742. return PyErr_Format(PyExc_NotImplementedError,
  11743. "startfile not available on this platform");
  11744. }
  11745. if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
  11746. return NULL;
  11747. }
  11748. if (PySys_Audit("os.startfile/2", "OuuOi", filepath->object, operation,
  11749. arguments, cwd->object ? cwd->object : Py_None,
  11750. show_cmd) < 0) {
  11751. return NULL;
  11752. }
  11753. Py_BEGIN_ALLOW_THREADS
  11754. rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
  11755. arguments, cwd->wide, show_cmd);
  11756. Py_END_ALLOW_THREADS
  11757. if (rc <= (HINSTANCE)32) {
  11758. win32_error_object("startfile", filepath->object);
  11759. return NULL;
  11760. }
  11761. Py_RETURN_NONE;
  11762. }
  11763. #endif /* MS_WINDOWS */
  11764. #ifdef HAVE_GETLOADAVG
  11765. /*[clinic input]
  11766. os.getloadavg
  11767. Return average recent system load information.
  11768. Return the number of processes in the system run queue averaged over
  11769. the last 1, 5, and 15 minutes as a tuple of three floats.
  11770. Raises OSError if the load average was unobtainable.
  11771. [clinic start generated code]*/
  11772. static PyObject *
  11773. os_getloadavg_impl(PyObject *module)
  11774. /*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
  11775. {
  11776. double loadavg[3];
  11777. if (getloadavg(loadavg, 3)!=3) {
  11778. PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
  11779. return NULL;
  11780. } else
  11781. return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
  11782. }
  11783. #endif /* HAVE_GETLOADAVG */
  11784. /*[clinic input]
  11785. os.device_encoding
  11786. fd: int
  11787. Return a string describing the encoding of a terminal's file descriptor.
  11788. The file descriptor must be attached to a terminal.
  11789. If the device is not a terminal, return None.
  11790. [clinic start generated code]*/
  11791. static PyObject *
  11792. os_device_encoding_impl(PyObject *module, int fd)
  11793. /*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
  11794. {
  11795. return _Py_device_encoding(fd);
  11796. }
  11797. #ifdef HAVE_SETRESUID
  11798. /*[clinic input]
  11799. os.setresuid
  11800. ruid: uid_t
  11801. euid: uid_t
  11802. suid: uid_t
  11803. /
  11804. Set the current process's real, effective, and saved user ids.
  11805. [clinic start generated code]*/
  11806. static PyObject *
  11807. os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
  11808. /*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
  11809. {
  11810. if (setresuid(ruid, euid, suid) < 0)
  11811. return posix_error();
  11812. Py_RETURN_NONE;
  11813. }
  11814. #endif /* HAVE_SETRESUID */
  11815. #ifdef HAVE_SETRESGID
  11816. /*[clinic input]
  11817. os.setresgid
  11818. rgid: gid_t
  11819. egid: gid_t
  11820. sgid: gid_t
  11821. /
  11822. Set the current process's real, effective, and saved group ids.
  11823. [clinic start generated code]*/
  11824. static PyObject *
  11825. os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
  11826. /*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
  11827. {
  11828. if (setresgid(rgid, egid, sgid) < 0)
  11829. return posix_error();
  11830. Py_RETURN_NONE;
  11831. }
  11832. #endif /* HAVE_SETRESGID */
  11833. #ifdef HAVE_GETRESUID
  11834. /*[clinic input]
  11835. os.getresuid
  11836. Return a tuple of the current process's real, effective, and saved user ids.
  11837. [clinic start generated code]*/
  11838. static PyObject *
  11839. os_getresuid_impl(PyObject *module)
  11840. /*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
  11841. {
  11842. uid_t ruid, euid, suid;
  11843. if (getresuid(&ruid, &euid, &suid) < 0)
  11844. return posix_error();
  11845. return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
  11846. _PyLong_FromUid(euid),
  11847. _PyLong_FromUid(suid));
  11848. }
  11849. #endif /* HAVE_GETRESUID */
  11850. #ifdef HAVE_GETRESGID
  11851. /*[clinic input]
  11852. os.getresgid
  11853. Return a tuple of the current process's real, effective, and saved group ids.
  11854. [clinic start generated code]*/
  11855. static PyObject *
  11856. os_getresgid_impl(PyObject *module)
  11857. /*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
  11858. {
  11859. gid_t rgid, egid, sgid;
  11860. if (getresgid(&rgid, &egid, &sgid) < 0)
  11861. return posix_error();
  11862. return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
  11863. _PyLong_FromGid(egid),
  11864. _PyLong_FromGid(sgid));
  11865. }
  11866. #endif /* HAVE_GETRESGID */
  11867. #ifdef USE_XATTRS
  11868. /*[clinic input]
  11869. os.getxattr
  11870. path: path_t(allow_fd=True)
  11871. attribute: path_t
  11872. *
  11873. follow_symlinks: bool = True
  11874. Return the value of extended attribute attribute on path.
  11875. path may be either a string, a path-like object, or an open file descriptor.
  11876. If follow_symlinks is False, and the last element of the path is a symbolic
  11877. link, getxattr will examine the symbolic link itself instead of the file
  11878. the link points to.
  11879. [clinic start generated code]*/
  11880. static PyObject *
  11881. os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11882. int follow_symlinks)
  11883. /*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
  11884. {
  11885. Py_ssize_t i;
  11886. PyObject *buffer = NULL;
  11887. if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
  11888. return NULL;
  11889. if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
  11890. return NULL;
  11891. }
  11892. for (i = 0; ; i++) {
  11893. void *ptr;
  11894. ssize_t result;
  11895. static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
  11896. Py_ssize_t buffer_size = buffer_sizes[i];
  11897. if (!buffer_size) {
  11898. path_error(path);
  11899. return NULL;
  11900. }
  11901. buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
  11902. if (!buffer)
  11903. return NULL;
  11904. ptr = PyBytes_AS_STRING(buffer);
  11905. Py_BEGIN_ALLOW_THREADS;
  11906. if (path->fd >= 0)
  11907. result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
  11908. else if (follow_symlinks)
  11909. result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
  11910. else
  11911. result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
  11912. Py_END_ALLOW_THREADS;
  11913. if (result < 0) {
  11914. if (errno == ERANGE) {
  11915. Py_DECREF(buffer);
  11916. continue;
  11917. }
  11918. path_error(path);
  11919. Py_DECREF(buffer);
  11920. return NULL;
  11921. }
  11922. if (result != buffer_size) {
  11923. /* Can only shrink. */
  11924. _PyBytes_Resize(&buffer, result);
  11925. }
  11926. break;
  11927. }
  11928. return buffer;
  11929. }
  11930. /*[clinic input]
  11931. os.setxattr
  11932. path: path_t(allow_fd=True)
  11933. attribute: path_t
  11934. value: Py_buffer
  11935. flags: int = 0
  11936. *
  11937. follow_symlinks: bool = True
  11938. Set extended attribute attribute on path to value.
  11939. path may be either a string, a path-like object, or an open file descriptor.
  11940. If follow_symlinks is False, and the last element of the path is a symbolic
  11941. link, setxattr will modify the symbolic link itself instead of the file
  11942. the link points to.
  11943. [clinic start generated code]*/
  11944. static PyObject *
  11945. os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11946. Py_buffer *value, int flags, int follow_symlinks)
  11947. /*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
  11948. {
  11949. ssize_t result;
  11950. if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
  11951. return NULL;
  11952. if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
  11953. value->buf, value->len, flags) < 0) {
  11954. return NULL;
  11955. }
  11956. Py_BEGIN_ALLOW_THREADS;
  11957. if (path->fd > -1)
  11958. result = fsetxattr(path->fd, attribute->narrow,
  11959. value->buf, value->len, flags);
  11960. else if (follow_symlinks)
  11961. result = setxattr(path->narrow, attribute->narrow,
  11962. value->buf, value->len, flags);
  11963. else
  11964. result = lsetxattr(path->narrow, attribute->narrow,
  11965. value->buf, value->len, flags);
  11966. Py_END_ALLOW_THREADS;
  11967. if (result) {
  11968. path_error(path);
  11969. return NULL;
  11970. }
  11971. Py_RETURN_NONE;
  11972. }
  11973. /*[clinic input]
  11974. os.removexattr
  11975. path: path_t(allow_fd=True)
  11976. attribute: path_t
  11977. *
  11978. follow_symlinks: bool = True
  11979. Remove extended attribute attribute on path.
  11980. path may be either a string, a path-like object, or an open file descriptor.
  11981. If follow_symlinks is False, and the last element of the path is a symbolic
  11982. link, removexattr will modify the symbolic link itself instead of the file
  11983. the link points to.
  11984. [clinic start generated code]*/
  11985. static PyObject *
  11986. os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11987. int follow_symlinks)
  11988. /*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
  11989. {
  11990. ssize_t result;
  11991. if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
  11992. return NULL;
  11993. if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
  11994. return NULL;
  11995. }
  11996. Py_BEGIN_ALLOW_THREADS;
  11997. if (path->fd > -1)
  11998. result = fremovexattr(path->fd, attribute->narrow);
  11999. else if (follow_symlinks)
  12000. result = removexattr(path->narrow, attribute->narrow);
  12001. else
  12002. result = lremovexattr(path->narrow, attribute->narrow);
  12003. Py_END_ALLOW_THREADS;
  12004. if (result) {
  12005. return path_error(path);
  12006. }
  12007. Py_RETURN_NONE;
  12008. }
  12009. /*[clinic input]
  12010. os.listxattr
  12011. path: path_t(allow_fd=True, nullable=True) = None
  12012. *
  12013. follow_symlinks: bool = True
  12014. Return a list of extended attributes on path.
  12015. path may be either None, a string, a path-like object, or an open file descriptor.
  12016. if path is None, listxattr will examine the current directory.
  12017. If follow_symlinks is False, and the last element of the path is a symbolic
  12018. link, listxattr will examine the symbolic link itself instead of the file
  12019. the link points to.
  12020. [clinic start generated code]*/
  12021. static PyObject *
  12022. os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
  12023. /*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
  12024. {
  12025. Py_ssize_t i;
  12026. PyObject *result = NULL;
  12027. const char *name;
  12028. char *buffer = NULL;
  12029. if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
  12030. goto exit;
  12031. if (PySys_Audit("os.listxattr", "(O)",
  12032. path->object ? path->object : Py_None) < 0) {
  12033. return NULL;
  12034. }
  12035. name = path->narrow ? path->narrow : ".";
  12036. for (i = 0; ; i++) {
  12037. const char *start, *trace, *end;
  12038. ssize_t length;
  12039. static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
  12040. Py_ssize_t buffer_size = buffer_sizes[i];
  12041. if (!buffer_size) {
  12042. /* ERANGE */
  12043. path_error(path);
  12044. break;
  12045. }
  12046. buffer = PyMem_Malloc(buffer_size);
  12047. if (!buffer) {
  12048. PyErr_NoMemory();
  12049. break;
  12050. }
  12051. Py_BEGIN_ALLOW_THREADS;
  12052. if (path->fd > -1)
  12053. length = flistxattr(path->fd, buffer, buffer_size);
  12054. else if (follow_symlinks)
  12055. length = listxattr(name, buffer, buffer_size);
  12056. else
  12057. length = llistxattr(name, buffer, buffer_size);
  12058. Py_END_ALLOW_THREADS;
  12059. if (length < 0) {
  12060. if (errno == ERANGE) {
  12061. PyMem_Free(buffer);
  12062. buffer = NULL;
  12063. continue;
  12064. }
  12065. path_error(path);
  12066. break;
  12067. }
  12068. result = PyList_New(0);
  12069. if (!result) {
  12070. goto exit;
  12071. }
  12072. end = buffer + length;
  12073. for (trace = start = buffer; trace != end; trace++) {
  12074. if (!*trace) {
  12075. int error;
  12076. PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
  12077. trace - start);
  12078. if (!attribute) {
  12079. Py_SETREF(result, NULL);
  12080. goto exit;
  12081. }
  12082. error = PyList_Append(result, attribute);
  12083. Py_DECREF(attribute);
  12084. if (error) {
  12085. Py_SETREF(result, NULL);
  12086. goto exit;
  12087. }
  12088. start = trace + 1;
  12089. }
  12090. }
  12091. break;
  12092. }
  12093. exit:
  12094. if (buffer)
  12095. PyMem_Free(buffer);
  12096. return result;
  12097. }
  12098. #endif /* USE_XATTRS */
  12099. /*[clinic input]
  12100. os.urandom
  12101. size: Py_ssize_t
  12102. /
  12103. Return a bytes object containing random bytes suitable for cryptographic use.
  12104. [clinic start generated code]*/
  12105. static PyObject *
  12106. os_urandom_impl(PyObject *module, Py_ssize_t size)
  12107. /*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
  12108. {
  12109. PyObject *bytes;
  12110. int result;
  12111. if (size < 0)
  12112. return PyErr_Format(PyExc_ValueError,
  12113. "negative argument not allowed");
  12114. bytes = PyBytes_FromStringAndSize(NULL, size);
  12115. if (bytes == NULL)
  12116. return NULL;
  12117. result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
  12118. if (result == -1) {
  12119. Py_DECREF(bytes);
  12120. return NULL;
  12121. }
  12122. return bytes;
  12123. }
  12124. #ifdef HAVE_MEMFD_CREATE
  12125. /*[clinic input]
  12126. os.memfd_create
  12127. name: FSConverter
  12128. flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
  12129. [clinic start generated code]*/
  12130. static PyObject *
  12131. os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
  12132. /*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
  12133. {
  12134. int fd;
  12135. const char *bytes = PyBytes_AS_STRING(name);
  12136. Py_BEGIN_ALLOW_THREADS
  12137. fd = memfd_create(bytes, flags);
  12138. Py_END_ALLOW_THREADS
  12139. if (fd == -1) {
  12140. return PyErr_SetFromErrno(PyExc_OSError);
  12141. }
  12142. return PyLong_FromLong(fd);
  12143. }
  12144. #endif
  12145. #if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
  12146. /*[clinic input]
  12147. os.eventfd
  12148. initval: unsigned_int
  12149. flags: int(c_default="EFD_CLOEXEC") = EFD_CLOEXEC
  12150. Creates and returns an event notification file descriptor.
  12151. [clinic start generated code]*/
  12152. static PyObject *
  12153. os_eventfd_impl(PyObject *module, unsigned int initval, int flags)
  12154. /*[clinic end generated code: output=ce9c9bbd1446f2de input=66203e3c50c4028b]*/
  12155. {
  12156. /* initval is limited to uint32_t, internal counter is uint64_t */
  12157. int fd;
  12158. Py_BEGIN_ALLOW_THREADS
  12159. fd = eventfd(initval, flags);
  12160. Py_END_ALLOW_THREADS
  12161. if (fd == -1) {
  12162. return PyErr_SetFromErrno(PyExc_OSError);
  12163. }
  12164. return PyLong_FromLong(fd);
  12165. }
  12166. /*[clinic input]
  12167. os.eventfd_read
  12168. fd: fildes
  12169. Read eventfd value
  12170. [clinic start generated code]*/
  12171. static PyObject *
  12172. os_eventfd_read_impl(PyObject *module, int fd)
  12173. /*[clinic end generated code: output=8f2c7b59a3521fd1 input=110f8b57fa596afe]*/
  12174. {
  12175. eventfd_t value;
  12176. int result;
  12177. Py_BEGIN_ALLOW_THREADS
  12178. result = eventfd_read(fd, &value);
  12179. Py_END_ALLOW_THREADS
  12180. if (result == -1) {
  12181. return PyErr_SetFromErrno(PyExc_OSError);
  12182. }
  12183. return PyLong_FromUnsignedLongLong(value);
  12184. }
  12185. /*[clinic input]
  12186. os.eventfd_write
  12187. fd: fildes
  12188. value: unsigned_long_long
  12189. Write eventfd value.
  12190. [clinic start generated code]*/
  12191. static PyObject *
  12192. os_eventfd_write_impl(PyObject *module, int fd, unsigned long long value)
  12193. /*[clinic end generated code: output=bebd9040bbf987f5 input=156de8555be5a949]*/
  12194. {
  12195. int result;
  12196. Py_BEGIN_ALLOW_THREADS
  12197. result = eventfd_write(fd, value);
  12198. Py_END_ALLOW_THREADS
  12199. if (result == -1) {
  12200. return PyErr_SetFromErrno(PyExc_OSError);
  12201. }
  12202. Py_RETURN_NONE;
  12203. }
  12204. #endif /* HAVE_EVENTFD && EFD_CLOEXEC */
  12205. /* Terminal size querying */
  12206. PyDoc_STRVAR(TerminalSize_docstring,
  12207. "A tuple of (columns, lines) for holding terminal window size");
  12208. static PyStructSequence_Field TerminalSize_fields[] = {
  12209. {"columns", "width of the terminal window in characters"},
  12210. {"lines", "height of the terminal window in characters"},
  12211. {NULL, NULL}
  12212. };
  12213. static PyStructSequence_Desc TerminalSize_desc = {
  12214. "os.terminal_size",
  12215. TerminalSize_docstring,
  12216. TerminalSize_fields,
  12217. 2,
  12218. };
  12219. #if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
  12220. /*[clinic input]
  12221. os.get_terminal_size
  12222. fd: int(c_default="fileno(stdout)", py_default="<unrepresentable>") = -1
  12223. /
  12224. Return the size of the terminal window as (columns, lines).
  12225. The optional argument fd (default standard output) specifies
  12226. which file descriptor should be queried.
  12227. If the file descriptor is not connected to a terminal, an OSError
  12228. is thrown.
  12229. This function will only be defined if an implementation is
  12230. available for this system.
  12231. shutil.get_terminal_size is the high-level function which should
  12232. normally be used, os.get_terminal_size is the low-level implementation.
  12233. [clinic start generated code]*/
  12234. static PyObject *
  12235. os_get_terminal_size_impl(PyObject *module, int fd)
  12236. /*[clinic end generated code: output=fbab93acef980508 input=ead5679b82ddb920]*/
  12237. {
  12238. int columns, lines;
  12239. PyObject *termsize;
  12240. /* Under some conditions stdout may not be connected and
  12241. * fileno(stdout) may point to an invalid file descriptor. For example
  12242. * GUI apps don't have valid standard streams by default.
  12243. *
  12244. * If this happens, and the optional fd argument is not present,
  12245. * the ioctl below will fail returning EBADF. This is what we want.
  12246. */
  12247. #ifdef TERMSIZE_USE_IOCTL
  12248. {
  12249. struct winsize w;
  12250. if (ioctl(fd, TIOCGWINSZ, &w))
  12251. return PyErr_SetFromErrno(PyExc_OSError);
  12252. columns = w.ws_col;
  12253. lines = w.ws_row;
  12254. }
  12255. #endif /* TERMSIZE_USE_IOCTL */
  12256. #ifdef TERMSIZE_USE_CONIO
  12257. {
  12258. HANDLE handle;
  12259. CONSOLE_SCREEN_BUFFER_INFO csbi;
  12260. handle = _Py_get_osfhandle(fd);
  12261. if (handle == INVALID_HANDLE_VALUE)
  12262. return NULL;
  12263. if (!GetConsoleScreenBufferInfo(handle, &csbi))
  12264. return PyErr_SetFromWindowsErr(0);
  12265. columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
  12266. lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
  12267. }
  12268. #endif /* TERMSIZE_USE_CONIO */
  12269. PyObject *TerminalSizeType = get_posix_state(module)->TerminalSizeType;
  12270. termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
  12271. if (termsize == NULL)
  12272. return NULL;
  12273. int pos = 0;
  12274. #define SET_TERMSIZE(CALL) \
  12275. do { \
  12276. PyObject *item = (CALL); \
  12277. if (item == NULL) { \
  12278. Py_DECREF(termsize); \
  12279. return NULL; \
  12280. } \
  12281. PyStructSequence_SET_ITEM(termsize, pos++, item); \
  12282. } while(0)
  12283. SET_TERMSIZE(PyLong_FromLong(columns));
  12284. SET_TERMSIZE(PyLong_FromLong(lines));
  12285. #undef SET_TERMSIZE
  12286. return termsize;
  12287. }
  12288. #endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
  12289. /*[clinic input]
  12290. os.cpu_count
  12291. Return the number of CPUs in the system; return None if indeterminable.
  12292. This number is not equivalent to the number of CPUs the current process can
  12293. use. The number of usable CPUs can be obtained with
  12294. ``len(os.sched_getaffinity(0))``
  12295. [clinic start generated code]*/
  12296. static PyObject *
  12297. os_cpu_count_impl(PyObject *module)
  12298. /*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
  12299. {
  12300. int ncpu = 0;
  12301. #ifdef MS_WINDOWS
  12302. #ifdef MS_WINDOWS_DESKTOP
  12303. ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
  12304. #endif
  12305. #elif defined(__hpux)
  12306. ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
  12307. #elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
  12308. ncpu = sysconf(_SC_NPROCESSORS_ONLN);
  12309. #elif defined(__VXWORKS__)
  12310. ncpu = _Py_popcount32(vxCpuEnabledGet());
  12311. #elif defined(__DragonFly__) || \
  12312. defined(__OpenBSD__) || \
  12313. defined(__FreeBSD__) || \
  12314. defined(__NetBSD__) || \
  12315. defined(__APPLE__)
  12316. int mib[2];
  12317. size_t len = sizeof(ncpu);
  12318. mib[0] = CTL_HW;
  12319. mib[1] = HW_NCPU;
  12320. if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
  12321. ncpu = 0;
  12322. #endif
  12323. if (ncpu >= 1)
  12324. return PyLong_FromLong(ncpu);
  12325. else
  12326. Py_RETURN_NONE;
  12327. }
  12328. /*[clinic input]
  12329. os.get_inheritable -> bool
  12330. fd: int
  12331. /
  12332. Get the close-on-exe flag of the specified file descriptor.
  12333. [clinic start generated code]*/
  12334. static int
  12335. os_get_inheritable_impl(PyObject *module, int fd)
  12336. /*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
  12337. {
  12338. int return_value;
  12339. _Py_BEGIN_SUPPRESS_IPH
  12340. return_value = _Py_get_inheritable(fd);
  12341. _Py_END_SUPPRESS_IPH
  12342. return return_value;
  12343. }
  12344. /*[clinic input]
  12345. os.set_inheritable
  12346. fd: int
  12347. inheritable: int
  12348. /
  12349. Set the inheritable flag of the specified file descriptor.
  12350. [clinic start generated code]*/
  12351. static PyObject *
  12352. os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
  12353. /*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
  12354. {
  12355. int result;
  12356. _Py_BEGIN_SUPPRESS_IPH
  12357. result = _Py_set_inheritable(fd, inheritable, NULL);
  12358. _Py_END_SUPPRESS_IPH
  12359. if (result < 0)
  12360. return NULL;
  12361. Py_RETURN_NONE;
  12362. }
  12363. #ifdef MS_WINDOWS
  12364. #ifndef HANDLE_FLAG_INHERIT
  12365. #define HANDLE_FLAG_INHERIT 0x00000001
  12366. #endif
  12367. /*[clinic input]
  12368. os.get_handle_inheritable -> bool
  12369. handle: intptr_t
  12370. /
  12371. Get the close-on-exe flag of the specified file descriptor.
  12372. [clinic start generated code]*/
  12373. static int
  12374. os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
  12375. /*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
  12376. {
  12377. DWORD flags;
  12378. if (!GetHandleInformation((HANDLE)handle, &flags)) {
  12379. PyErr_SetFromWindowsErr(0);
  12380. return -1;
  12381. }
  12382. return flags & HANDLE_FLAG_INHERIT;
  12383. }
  12384. /*[clinic input]
  12385. os.set_handle_inheritable
  12386. handle: intptr_t
  12387. inheritable: bool
  12388. /
  12389. Set the inheritable flag of the specified handle.
  12390. [clinic start generated code]*/
  12391. static PyObject *
  12392. os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
  12393. int inheritable)
  12394. /*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
  12395. {
  12396. DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
  12397. if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
  12398. PyErr_SetFromWindowsErr(0);
  12399. return NULL;
  12400. }
  12401. Py_RETURN_NONE;
  12402. }
  12403. #endif /* MS_WINDOWS */
  12404. /*[clinic input]
  12405. os.get_blocking -> bool
  12406. fd: int
  12407. /
  12408. Get the blocking mode of the file descriptor.
  12409. Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
  12410. [clinic start generated code]*/
  12411. static int
  12412. os_get_blocking_impl(PyObject *module, int fd)
  12413. /*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
  12414. {
  12415. int blocking;
  12416. _Py_BEGIN_SUPPRESS_IPH
  12417. blocking = _Py_get_blocking(fd);
  12418. _Py_END_SUPPRESS_IPH
  12419. return blocking;
  12420. }
  12421. /*[clinic input]
  12422. os.set_blocking
  12423. fd: int
  12424. blocking: bool
  12425. /
  12426. Set the blocking mode of the specified file descriptor.
  12427. Set the O_NONBLOCK flag if blocking is False,
  12428. clear the O_NONBLOCK flag otherwise.
  12429. [clinic start generated code]*/
  12430. static PyObject *
  12431. os_set_blocking_impl(PyObject *module, int fd, int blocking)
  12432. /*[clinic end generated code: output=384eb43aa0762a9d input=7e9dfc9b14804dd4]*/
  12433. {
  12434. int result;
  12435. _Py_BEGIN_SUPPRESS_IPH
  12436. result = _Py_set_blocking(fd, blocking);
  12437. _Py_END_SUPPRESS_IPH
  12438. if (result < 0)
  12439. return NULL;
  12440. Py_RETURN_NONE;
  12441. }
  12442. /*[clinic input]
  12443. class os.DirEntry "DirEntry *" "DirEntryType"
  12444. [clinic start generated code]*/
  12445. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
  12446. typedef struct {
  12447. PyObject_HEAD
  12448. PyObject *name;
  12449. PyObject *path;
  12450. PyObject *stat;
  12451. PyObject *lstat;
  12452. #ifdef MS_WINDOWS
  12453. struct _Py_stat_struct win32_lstat;
  12454. uint64_t win32_file_index;
  12455. uint64_t win32_file_index_high;
  12456. int got_file_index;
  12457. #else /* POSIX */
  12458. #ifdef HAVE_DIRENT_D_TYPE
  12459. unsigned char d_type;
  12460. #endif
  12461. ino_t d_ino;
  12462. int dir_fd;
  12463. #endif
  12464. } DirEntry;
  12465. static void
  12466. DirEntry_dealloc(DirEntry *entry)
  12467. {
  12468. PyTypeObject *tp = Py_TYPE(entry);
  12469. Py_XDECREF(entry->name);
  12470. Py_XDECREF(entry->path);
  12471. Py_XDECREF(entry->stat);
  12472. Py_XDECREF(entry->lstat);
  12473. freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
  12474. free_func(entry);
  12475. Py_DECREF(tp);
  12476. }
  12477. /* Forward reference */
  12478. static int
  12479. DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
  12480. int follow_symlinks, unsigned short mode_bits);
  12481. /*[clinic input]
  12482. os.DirEntry.is_symlink -> bool
  12483. defining_class: defining_class
  12484. /
  12485. Return True if the entry is a symbolic link; cached per entry.
  12486. [clinic start generated code]*/
  12487. static int
  12488. os_DirEntry_is_symlink_impl(DirEntry *self, PyTypeObject *defining_class)
  12489. /*[clinic end generated code: output=293096d589b6d47c input=e9acc5ee4d511113]*/
  12490. {
  12491. #ifdef MS_WINDOWS
  12492. return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
  12493. #elif defined(HAVE_DIRENT_D_TYPE)
  12494. /* POSIX */
  12495. if (self->d_type != DT_UNKNOWN)
  12496. return self->d_type == DT_LNK;
  12497. else
  12498. return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
  12499. #else
  12500. /* POSIX without d_type */
  12501. return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
  12502. #endif
  12503. }
  12504. /*[clinic input]
  12505. os.DirEntry.is_junction -> bool
  12506. defining_class: defining_class
  12507. /
  12508. Return True if the entry is a junction; cached per entry.
  12509. [clinic start generated code]*/
  12510. static int
  12511. os_DirEntry_is_junction_impl(DirEntry *self, PyTypeObject *defining_class)
  12512. /*[clinic end generated code: output=7061a07b0ef2cd1f input=475cd36fb7d4723f]*/
  12513. {
  12514. #ifdef MS_WINDOWS
  12515. return self->win32_lstat.st_reparse_tag == IO_REPARSE_TAG_MOUNT_POINT;
  12516. #else
  12517. return 0;
  12518. #endif
  12519. }
  12520. static PyObject *
  12521. DirEntry_fetch_stat(PyObject *module, DirEntry *self, int follow_symlinks)
  12522. {
  12523. int result;
  12524. STRUCT_STAT st;
  12525. PyObject *ub;
  12526. #ifdef MS_WINDOWS
  12527. if (!PyUnicode_FSDecoder(self->path, &ub))
  12528. return NULL;
  12529. wchar_t *path = PyUnicode_AsWideCharString(ub, NULL);
  12530. Py_DECREF(ub);
  12531. #else /* POSIX */
  12532. if (!PyUnicode_FSConverter(self->path, &ub))
  12533. return NULL;
  12534. const char *path = PyBytes_AS_STRING(ub);
  12535. if (self->dir_fd != DEFAULT_DIR_FD) {
  12536. #ifdef HAVE_FSTATAT
  12537. if (HAVE_FSTATAT_RUNTIME) {
  12538. Py_BEGIN_ALLOW_THREADS
  12539. result = fstatat(self->dir_fd, path, &st,
  12540. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  12541. Py_END_ALLOW_THREADS
  12542. } else
  12543. #endif /* HAVE_FSTATAT */
  12544. {
  12545. Py_DECREF(ub);
  12546. PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
  12547. return NULL;
  12548. }
  12549. }
  12550. else
  12551. #endif
  12552. {
  12553. Py_BEGIN_ALLOW_THREADS
  12554. if (follow_symlinks) {
  12555. result = STAT(path, &st);
  12556. }
  12557. else {
  12558. result = LSTAT(path, &st);
  12559. }
  12560. Py_END_ALLOW_THREADS
  12561. }
  12562. int saved_errno = errno;
  12563. #if defined(MS_WINDOWS)
  12564. PyMem_Free(path);
  12565. #else
  12566. Py_DECREF(ub);
  12567. #endif
  12568. if (result != 0) {
  12569. errno = saved_errno;
  12570. path_object_error(self->path);
  12571. return NULL;
  12572. }
  12573. return _pystat_fromstructstat(module, &st);
  12574. }
  12575. static PyObject *
  12576. DirEntry_get_lstat(PyTypeObject *defining_class, DirEntry *self)
  12577. {
  12578. if (!self->lstat) {
  12579. PyObject *module = PyType_GetModule(defining_class);
  12580. #ifdef MS_WINDOWS
  12581. self->lstat = _pystat_fromstructstat(module, &self->win32_lstat);
  12582. #else /* POSIX */
  12583. self->lstat = DirEntry_fetch_stat(module, self, 0);
  12584. #endif
  12585. }
  12586. return Py_XNewRef(self->lstat);
  12587. }
  12588. /*[clinic input]
  12589. os.DirEntry.stat
  12590. defining_class: defining_class
  12591. /
  12592. *
  12593. follow_symlinks: bool = True
  12594. Return stat_result object for the entry; cached per entry.
  12595. [clinic start generated code]*/
  12596. static PyObject *
  12597. os_DirEntry_stat_impl(DirEntry *self, PyTypeObject *defining_class,
  12598. int follow_symlinks)
  12599. /*[clinic end generated code: output=23f803e19c3e780e input=e816273c4e67ee98]*/
  12600. {
  12601. if (!follow_symlinks) {
  12602. return DirEntry_get_lstat(defining_class, self);
  12603. }
  12604. if (!self->stat) {
  12605. int result = os_DirEntry_is_symlink_impl(self, defining_class);
  12606. if (result == -1) {
  12607. return NULL;
  12608. }
  12609. if (result) {
  12610. PyObject *module = PyType_GetModule(defining_class);
  12611. self->stat = DirEntry_fetch_stat(module, self, 1);
  12612. }
  12613. else {
  12614. self->stat = DirEntry_get_lstat(defining_class, self);
  12615. }
  12616. }
  12617. return Py_XNewRef(self->stat);
  12618. }
  12619. /* Set exception and return -1 on error, 0 for False, 1 for True */
  12620. static int
  12621. DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
  12622. int follow_symlinks, unsigned short mode_bits)
  12623. {
  12624. PyObject *stat = NULL;
  12625. PyObject *st_mode = NULL;
  12626. long mode;
  12627. int result;
  12628. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12629. int is_symlink;
  12630. int need_stat;
  12631. #endif
  12632. #ifdef MS_WINDOWS
  12633. unsigned long dir_bits;
  12634. #endif
  12635. #ifdef MS_WINDOWS
  12636. is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
  12637. need_stat = follow_symlinks && is_symlink;
  12638. #elif defined(HAVE_DIRENT_D_TYPE)
  12639. is_symlink = self->d_type == DT_LNK;
  12640. need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
  12641. #endif
  12642. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12643. if (need_stat) {
  12644. #endif
  12645. stat = os_DirEntry_stat_impl(self, defining_class, follow_symlinks);
  12646. if (!stat) {
  12647. if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
  12648. /* If file doesn't exist (anymore), then return False
  12649. (i.e., say it's not a file/directory) */
  12650. PyErr_Clear();
  12651. return 0;
  12652. }
  12653. goto error;
  12654. }
  12655. _posixstate* state = get_posix_state(PyType_GetModule(defining_class));
  12656. st_mode = PyObject_GetAttr(stat, state->st_mode);
  12657. if (!st_mode)
  12658. goto error;
  12659. mode = PyLong_AsLong(st_mode);
  12660. if (mode == -1 && PyErr_Occurred())
  12661. goto error;
  12662. Py_CLEAR(st_mode);
  12663. Py_CLEAR(stat);
  12664. result = (mode & S_IFMT) == mode_bits;
  12665. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12666. }
  12667. else if (is_symlink) {
  12668. assert(mode_bits != S_IFLNK);
  12669. result = 0;
  12670. }
  12671. else {
  12672. assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
  12673. #ifdef MS_WINDOWS
  12674. dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
  12675. if (mode_bits == S_IFDIR)
  12676. result = dir_bits != 0;
  12677. else
  12678. result = dir_bits == 0;
  12679. #else /* POSIX */
  12680. if (mode_bits == S_IFDIR)
  12681. result = self->d_type == DT_DIR;
  12682. else
  12683. result = self->d_type == DT_REG;
  12684. #endif
  12685. }
  12686. #endif
  12687. return result;
  12688. error:
  12689. Py_XDECREF(st_mode);
  12690. Py_XDECREF(stat);
  12691. return -1;
  12692. }
  12693. /*[clinic input]
  12694. os.DirEntry.is_dir -> bool
  12695. defining_class: defining_class
  12696. /
  12697. *
  12698. follow_symlinks: bool = True
  12699. Return True if the entry is a directory; cached per entry.
  12700. [clinic start generated code]*/
  12701. static int
  12702. os_DirEntry_is_dir_impl(DirEntry *self, PyTypeObject *defining_class,
  12703. int follow_symlinks)
  12704. /*[clinic end generated code: output=0cd453b9c0987fdf input=1a4ffd6dec9920cb]*/
  12705. {
  12706. return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFDIR);
  12707. }
  12708. /*[clinic input]
  12709. os.DirEntry.is_file -> bool
  12710. defining_class: defining_class
  12711. /
  12712. *
  12713. follow_symlinks: bool = True
  12714. Return True if the entry is a file; cached per entry.
  12715. [clinic start generated code]*/
  12716. static int
  12717. os_DirEntry_is_file_impl(DirEntry *self, PyTypeObject *defining_class,
  12718. int follow_symlinks)
  12719. /*[clinic end generated code: output=f7c277ab5ba80908 input=0a64c5a12e802e3b]*/
  12720. {
  12721. return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFREG);
  12722. }
  12723. /*[clinic input]
  12724. os.DirEntry.inode
  12725. Return inode of the entry; cached per entry.
  12726. [clinic start generated code]*/
  12727. static PyObject *
  12728. os_DirEntry_inode_impl(DirEntry *self)
  12729. /*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
  12730. {
  12731. #ifdef MS_WINDOWS
  12732. if (!self->got_file_index) {
  12733. PyObject *unicode;
  12734. STRUCT_STAT stat;
  12735. int result;
  12736. if (!PyUnicode_FSDecoder(self->path, &unicode))
  12737. return NULL;
  12738. wchar_t *path = PyUnicode_AsWideCharString(unicode, NULL);
  12739. Py_DECREF(unicode);
  12740. result = LSTAT(path, &stat);
  12741. int saved_errno = errno;
  12742. PyMem_Free(path);
  12743. if (result != 0) {
  12744. errno = saved_errno;
  12745. return path_object_error(self->path);
  12746. }
  12747. self->win32_file_index = stat.st_ino;
  12748. self->win32_file_index_high = stat.st_ino_high;
  12749. self->got_file_index = 1;
  12750. }
  12751. return _pystat_l128_from_l64_l64(self->win32_file_index, self->win32_file_index_high);
  12752. #else /* POSIX */
  12753. static_assert(sizeof(unsigned long long) >= sizeof(self->d_ino),
  12754. "DirEntry.d_ino is larger than unsigned long long");
  12755. return PyLong_FromUnsignedLongLong(self->d_ino);
  12756. #endif
  12757. }
  12758. static PyObject *
  12759. DirEntry_repr(DirEntry *self)
  12760. {
  12761. return PyUnicode_FromFormat("<DirEntry %R>", self->name);
  12762. }
  12763. /*[clinic input]
  12764. os.DirEntry.__fspath__
  12765. Returns the path for the entry.
  12766. [clinic start generated code]*/
  12767. static PyObject *
  12768. os_DirEntry___fspath___impl(DirEntry *self)
  12769. /*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
  12770. {
  12771. return Py_NewRef(self->path);
  12772. }
  12773. static PyMemberDef DirEntry_members[] = {
  12774. {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
  12775. "the entry's base filename, relative to scandir() \"path\" argument"},
  12776. {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
  12777. "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
  12778. {NULL}
  12779. };
  12780. #include "clinic/posixmodule.c.h"
  12781. static PyMethodDef DirEntry_methods[] = {
  12782. OS_DIRENTRY_IS_DIR_METHODDEF
  12783. OS_DIRENTRY_IS_FILE_METHODDEF
  12784. OS_DIRENTRY_IS_SYMLINK_METHODDEF
  12785. OS_DIRENTRY_IS_JUNCTION_METHODDEF
  12786. OS_DIRENTRY_STAT_METHODDEF
  12787. OS_DIRENTRY_INODE_METHODDEF
  12788. OS_DIRENTRY___FSPATH___METHODDEF
  12789. {"__class_getitem__", Py_GenericAlias,
  12790. METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  12791. {NULL}
  12792. };
  12793. static PyType_Slot DirEntryType_slots[] = {
  12794. {Py_tp_dealloc, DirEntry_dealloc},
  12795. {Py_tp_repr, DirEntry_repr},
  12796. {Py_tp_methods, DirEntry_methods},
  12797. {Py_tp_members, DirEntry_members},
  12798. {0, 0},
  12799. };
  12800. static PyType_Spec DirEntryType_spec = {
  12801. MODNAME ".DirEntry",
  12802. sizeof(DirEntry),
  12803. 0,
  12804. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
  12805. DirEntryType_slots
  12806. };
  12807. #ifdef MS_WINDOWS
  12808. static wchar_t *
  12809. join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
  12810. {
  12811. Py_ssize_t path_len;
  12812. Py_ssize_t size;
  12813. wchar_t *result;
  12814. wchar_t ch;
  12815. if (!path_wide) { /* Default arg: "." */
  12816. path_wide = L".";
  12817. path_len = 1;
  12818. }
  12819. else {
  12820. path_len = wcslen(path_wide);
  12821. }
  12822. /* The +1's are for the path separator and the NUL */
  12823. size = path_len + 1 + wcslen(filename) + 1;
  12824. result = PyMem_New(wchar_t, size);
  12825. if (!result) {
  12826. PyErr_NoMemory();
  12827. return NULL;
  12828. }
  12829. wcscpy(result, path_wide);
  12830. if (path_len > 0) {
  12831. ch = result[path_len - 1];
  12832. if (ch != SEP && ch != ALTSEP && ch != L':')
  12833. result[path_len++] = SEP;
  12834. wcscpy(result + path_len, filename);
  12835. }
  12836. return result;
  12837. }
  12838. static PyObject *
  12839. DirEntry_from_find_data(PyObject *module, path_t *path, WIN32_FIND_DATAW *dataW)
  12840. {
  12841. DirEntry *entry;
  12842. BY_HANDLE_FILE_INFORMATION file_info;
  12843. ULONG reparse_tag;
  12844. wchar_t *joined_path;
  12845. PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
  12846. entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
  12847. if (!entry)
  12848. return NULL;
  12849. entry->name = NULL;
  12850. entry->path = NULL;
  12851. entry->stat = NULL;
  12852. entry->lstat = NULL;
  12853. entry->got_file_index = 0;
  12854. entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
  12855. if (!entry->name)
  12856. goto error;
  12857. int return_bytes = path->wide && PyBytes_Check(path->object);
  12858. if (return_bytes) {
  12859. Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
  12860. if (!entry->name)
  12861. goto error;
  12862. }
  12863. joined_path = join_path_filenameW(path->wide, dataW->cFileName);
  12864. if (!joined_path)
  12865. goto error;
  12866. entry->path = PyUnicode_FromWideChar(joined_path, -1);
  12867. PyMem_Free(joined_path);
  12868. if (!entry->path)
  12869. goto error;
  12870. if (return_bytes) {
  12871. Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
  12872. if (!entry->path)
  12873. goto error;
  12874. }
  12875. find_data_to_file_info(dataW, &file_info, &reparse_tag);
  12876. _Py_attribute_data_to_stat(&file_info, reparse_tag, NULL, NULL, &entry->win32_lstat);
  12877. /* ctime is only deprecated from 3.12, so we copy birthtime across */
  12878. entry->win32_lstat.st_ctime = entry->win32_lstat.st_birthtime;
  12879. entry->win32_lstat.st_ctime_nsec = entry->win32_lstat.st_birthtime_nsec;
  12880. return (PyObject *)entry;
  12881. error:
  12882. Py_DECREF(entry);
  12883. return NULL;
  12884. }
  12885. #else /* POSIX */
  12886. static char *
  12887. join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
  12888. {
  12889. Py_ssize_t path_len;
  12890. Py_ssize_t size;
  12891. char *result;
  12892. if (!path_narrow) { /* Default arg: "." */
  12893. path_narrow = ".";
  12894. path_len = 1;
  12895. }
  12896. else {
  12897. path_len = strlen(path_narrow);
  12898. }
  12899. if (filename_len == -1)
  12900. filename_len = strlen(filename);
  12901. /* The +1's are for the path separator and the NUL */
  12902. size = path_len + 1 + filename_len + 1;
  12903. result = PyMem_New(char, size);
  12904. if (!result) {
  12905. PyErr_NoMemory();
  12906. return NULL;
  12907. }
  12908. strcpy(result, path_narrow);
  12909. if (path_len > 0 && result[path_len - 1] != '/')
  12910. result[path_len++] = '/';
  12911. strcpy(result + path_len, filename);
  12912. return result;
  12913. }
  12914. static PyObject *
  12915. DirEntry_from_posix_info(PyObject *module, path_t *path, const char *name,
  12916. Py_ssize_t name_len, ino_t d_ino
  12917. #ifdef HAVE_DIRENT_D_TYPE
  12918. , unsigned char d_type
  12919. #endif
  12920. )
  12921. {
  12922. DirEntry *entry;
  12923. char *joined_path;
  12924. PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
  12925. entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
  12926. if (!entry)
  12927. return NULL;
  12928. entry->name = NULL;
  12929. entry->path = NULL;
  12930. entry->stat = NULL;
  12931. entry->lstat = NULL;
  12932. if (path->fd != -1) {
  12933. entry->dir_fd = path->fd;
  12934. joined_path = NULL;
  12935. }
  12936. else {
  12937. entry->dir_fd = DEFAULT_DIR_FD;
  12938. joined_path = join_path_filename(path->narrow, name, name_len);
  12939. if (!joined_path)
  12940. goto error;
  12941. }
  12942. if (!path->narrow || !PyBytes_Check(path->object)) {
  12943. entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
  12944. if (joined_path)
  12945. entry->path = PyUnicode_DecodeFSDefault(joined_path);
  12946. }
  12947. else {
  12948. entry->name = PyBytes_FromStringAndSize(name, name_len);
  12949. if (joined_path)
  12950. entry->path = PyBytes_FromString(joined_path);
  12951. }
  12952. PyMem_Free(joined_path);
  12953. if (!entry->name)
  12954. goto error;
  12955. if (path->fd != -1) {
  12956. entry->path = Py_NewRef(entry->name);
  12957. }
  12958. else if (!entry->path)
  12959. goto error;
  12960. #ifdef HAVE_DIRENT_D_TYPE
  12961. entry->d_type = d_type;
  12962. #endif
  12963. entry->d_ino = d_ino;
  12964. return (PyObject *)entry;
  12965. error:
  12966. Py_XDECREF(entry);
  12967. return NULL;
  12968. }
  12969. #endif
  12970. typedef struct {
  12971. PyObject_HEAD
  12972. path_t path;
  12973. #ifdef MS_WINDOWS
  12974. HANDLE handle;
  12975. WIN32_FIND_DATAW file_data;
  12976. int first_time;
  12977. #else /* POSIX */
  12978. DIR *dirp;
  12979. #endif
  12980. #ifdef HAVE_FDOPENDIR
  12981. int fd;
  12982. #endif
  12983. } ScandirIterator;
  12984. #ifdef MS_WINDOWS
  12985. static int
  12986. ScandirIterator_is_closed(ScandirIterator *iterator)
  12987. {
  12988. return iterator->handle == INVALID_HANDLE_VALUE;
  12989. }
  12990. static void
  12991. ScandirIterator_closedir(ScandirIterator *iterator)
  12992. {
  12993. HANDLE handle = iterator->handle;
  12994. if (handle == INVALID_HANDLE_VALUE)
  12995. return;
  12996. iterator->handle = INVALID_HANDLE_VALUE;
  12997. Py_BEGIN_ALLOW_THREADS
  12998. FindClose(handle);
  12999. Py_END_ALLOW_THREADS
  13000. }
  13001. static PyObject *
  13002. ScandirIterator_iternext(ScandirIterator *iterator)
  13003. {
  13004. WIN32_FIND_DATAW *file_data = &iterator->file_data;
  13005. BOOL success;
  13006. PyObject *entry;
  13007. /* Happens if the iterator is iterated twice, or closed explicitly */
  13008. if (iterator->handle == INVALID_HANDLE_VALUE)
  13009. return NULL;
  13010. while (1) {
  13011. if (!iterator->first_time) {
  13012. Py_BEGIN_ALLOW_THREADS
  13013. success = FindNextFileW(iterator->handle, file_data);
  13014. Py_END_ALLOW_THREADS
  13015. if (!success) {
  13016. /* Error or no more files */
  13017. if (GetLastError() != ERROR_NO_MORE_FILES)
  13018. path_error(&iterator->path);
  13019. break;
  13020. }
  13021. }
  13022. iterator->first_time = 0;
  13023. /* Skip over . and .. */
  13024. if (wcscmp(file_data->cFileName, L".") != 0 &&
  13025. wcscmp(file_data->cFileName, L"..") != 0)
  13026. {
  13027. PyObject *module = PyType_GetModule(Py_TYPE(iterator));
  13028. entry = DirEntry_from_find_data(module, &iterator->path, file_data);
  13029. if (!entry)
  13030. break;
  13031. return entry;
  13032. }
  13033. /* Loop till we get a non-dot directory or finish iterating */
  13034. }
  13035. /* Error or no more files */
  13036. ScandirIterator_closedir(iterator);
  13037. return NULL;
  13038. }
  13039. #else /* POSIX */
  13040. static int
  13041. ScandirIterator_is_closed(ScandirIterator *iterator)
  13042. {
  13043. return !iterator->dirp;
  13044. }
  13045. static void
  13046. ScandirIterator_closedir(ScandirIterator *iterator)
  13047. {
  13048. DIR *dirp = iterator->dirp;
  13049. if (!dirp)
  13050. return;
  13051. iterator->dirp = NULL;
  13052. Py_BEGIN_ALLOW_THREADS
  13053. #ifdef HAVE_FDOPENDIR
  13054. if (iterator->path.fd != -1)
  13055. rewinddir(dirp);
  13056. #endif
  13057. closedir(dirp);
  13058. Py_END_ALLOW_THREADS
  13059. return;
  13060. }
  13061. static PyObject *
  13062. ScandirIterator_iternext(ScandirIterator *iterator)
  13063. {
  13064. struct dirent *direntp;
  13065. Py_ssize_t name_len;
  13066. int is_dot;
  13067. PyObject *entry;
  13068. /* Happens if the iterator is iterated twice, or closed explicitly */
  13069. if (!iterator->dirp)
  13070. return NULL;
  13071. while (1) {
  13072. errno = 0;
  13073. Py_BEGIN_ALLOW_THREADS
  13074. direntp = readdir(iterator->dirp);
  13075. Py_END_ALLOW_THREADS
  13076. if (!direntp) {
  13077. /* Error or no more files */
  13078. if (errno != 0)
  13079. path_error(&iterator->path);
  13080. break;
  13081. }
  13082. /* Skip over . and .. */
  13083. name_len = NAMLEN(direntp);
  13084. is_dot = direntp->d_name[0] == '.' &&
  13085. (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
  13086. if (!is_dot) {
  13087. PyObject *module = PyType_GetModule(Py_TYPE(iterator));
  13088. entry = DirEntry_from_posix_info(module,
  13089. &iterator->path, direntp->d_name,
  13090. name_len, direntp->d_ino
  13091. #ifdef HAVE_DIRENT_D_TYPE
  13092. , direntp->d_type
  13093. #endif
  13094. );
  13095. if (!entry)
  13096. break;
  13097. return entry;
  13098. }
  13099. /* Loop till we get a non-dot directory or finish iterating */
  13100. }
  13101. /* Error or no more files */
  13102. ScandirIterator_closedir(iterator);
  13103. return NULL;
  13104. }
  13105. #endif
  13106. static PyObject *
  13107. ScandirIterator_close(ScandirIterator *self, PyObject *args)
  13108. {
  13109. ScandirIterator_closedir(self);
  13110. Py_RETURN_NONE;
  13111. }
  13112. static PyObject *
  13113. ScandirIterator_enter(PyObject *self, PyObject *args)
  13114. {
  13115. return Py_NewRef(self);
  13116. }
  13117. static PyObject *
  13118. ScandirIterator_exit(ScandirIterator *self, PyObject *args)
  13119. {
  13120. ScandirIterator_closedir(self);
  13121. Py_RETURN_NONE;
  13122. }
  13123. static void
  13124. ScandirIterator_finalize(ScandirIterator *iterator)
  13125. {
  13126. /* Save the current exception, if any. */
  13127. PyObject *exc = PyErr_GetRaisedException();
  13128. if (!ScandirIterator_is_closed(iterator)) {
  13129. ScandirIterator_closedir(iterator);
  13130. if (PyErr_ResourceWarning((PyObject *)iterator, 1,
  13131. "unclosed scandir iterator %R", iterator)) {
  13132. /* Spurious errors can appear at shutdown */
  13133. if (PyErr_ExceptionMatches(PyExc_Warning)) {
  13134. PyErr_WriteUnraisable((PyObject *) iterator);
  13135. }
  13136. }
  13137. }
  13138. path_cleanup(&iterator->path);
  13139. /* Restore the saved exception. */
  13140. PyErr_SetRaisedException(exc);
  13141. }
  13142. static void
  13143. ScandirIterator_dealloc(ScandirIterator *iterator)
  13144. {
  13145. PyTypeObject *tp = Py_TYPE(iterator);
  13146. if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
  13147. return;
  13148. freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
  13149. free_func(iterator);
  13150. Py_DECREF(tp);
  13151. }
  13152. static PyMethodDef ScandirIterator_methods[] = {
  13153. {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
  13154. {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
  13155. {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
  13156. {NULL}
  13157. };
  13158. static PyType_Slot ScandirIteratorType_slots[] = {
  13159. {Py_tp_dealloc, ScandirIterator_dealloc},
  13160. {Py_tp_finalize, ScandirIterator_finalize},
  13161. {Py_tp_iter, PyObject_SelfIter},
  13162. {Py_tp_iternext, ScandirIterator_iternext},
  13163. {Py_tp_methods, ScandirIterator_methods},
  13164. {0, 0},
  13165. };
  13166. static PyType_Spec ScandirIteratorType_spec = {
  13167. MODNAME ".ScandirIterator",
  13168. sizeof(ScandirIterator),
  13169. 0,
  13170. // bpo-40549: Py_TPFLAGS_BASETYPE should not be used, since
  13171. // PyType_GetModule(Py_TYPE(self)) doesn't work on a subclass instance.
  13172. (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE
  13173. | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  13174. ScandirIteratorType_slots
  13175. };
  13176. /*[clinic input]
  13177. os.scandir
  13178. path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
  13179. Return an iterator of DirEntry objects for given path.
  13180. path can be specified as either str, bytes, or a path-like object. If path
  13181. is bytes, the names of yielded DirEntry objects will also be bytes; in
  13182. all other circumstances they will be str.
  13183. If path is None, uses the path='.'.
  13184. [clinic start generated code]*/
  13185. static PyObject *
  13186. os_scandir_impl(PyObject *module, path_t *path)
  13187. /*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
  13188. {
  13189. ScandirIterator *iterator;
  13190. #ifdef MS_WINDOWS
  13191. wchar_t *path_strW;
  13192. #else
  13193. const char *path_str;
  13194. #ifdef HAVE_FDOPENDIR
  13195. int fd = -1;
  13196. #endif
  13197. #endif
  13198. if (PySys_Audit("os.scandir", "O",
  13199. path->object ? path->object : Py_None) < 0) {
  13200. return NULL;
  13201. }
  13202. PyObject *ScandirIteratorType = get_posix_state(module)->ScandirIteratorType;
  13203. iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
  13204. if (!iterator)
  13205. return NULL;
  13206. #ifdef MS_WINDOWS
  13207. iterator->handle = INVALID_HANDLE_VALUE;
  13208. #else
  13209. iterator->dirp = NULL;
  13210. #endif
  13211. /* Move the ownership to iterator->path */
  13212. memcpy(&iterator->path, path, sizeof(path_t));
  13213. memset(path, 0, sizeof(path_t));
  13214. #ifdef MS_WINDOWS
  13215. iterator->first_time = 1;
  13216. path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
  13217. if (!path_strW)
  13218. goto error;
  13219. Py_BEGIN_ALLOW_THREADS
  13220. iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
  13221. Py_END_ALLOW_THREADS
  13222. if (iterator->handle == INVALID_HANDLE_VALUE) {
  13223. path_error(&iterator->path);
  13224. PyMem_Free(path_strW);
  13225. goto error;
  13226. }
  13227. PyMem_Free(path_strW);
  13228. #else /* POSIX */
  13229. errno = 0;
  13230. #ifdef HAVE_FDOPENDIR
  13231. if (iterator->path.fd != -1) {
  13232. if (HAVE_FDOPENDIR_RUNTIME) {
  13233. /* closedir() closes the FD, so we duplicate it */
  13234. fd = _Py_dup(iterator->path.fd);
  13235. if (fd == -1)
  13236. goto error;
  13237. Py_BEGIN_ALLOW_THREADS
  13238. iterator->dirp = fdopendir(fd);
  13239. Py_END_ALLOW_THREADS
  13240. } else {
  13241. PyErr_SetString(PyExc_TypeError,
  13242. "scandir: path should be string, bytes, os.PathLike or None, not int");
  13243. return NULL;
  13244. }
  13245. }
  13246. else
  13247. #endif
  13248. {
  13249. if (iterator->path.narrow)
  13250. path_str = iterator->path.narrow;
  13251. else
  13252. path_str = ".";
  13253. Py_BEGIN_ALLOW_THREADS
  13254. iterator->dirp = opendir(path_str);
  13255. Py_END_ALLOW_THREADS
  13256. }
  13257. if (!iterator->dirp) {
  13258. path_error(&iterator->path);
  13259. #ifdef HAVE_FDOPENDIR
  13260. if (fd != -1) {
  13261. Py_BEGIN_ALLOW_THREADS
  13262. close(fd);
  13263. Py_END_ALLOW_THREADS
  13264. }
  13265. #endif
  13266. goto error;
  13267. }
  13268. #endif
  13269. return (PyObject *)iterator;
  13270. error:
  13271. Py_DECREF(iterator);
  13272. return NULL;
  13273. }
  13274. /*
  13275. Return the file system path representation of the object.
  13276. If the object is str or bytes, then allow it to pass through with
  13277. an incremented refcount. If the object defines __fspath__(), then
  13278. return the result of that method. All other types raise a TypeError.
  13279. */
  13280. PyObject *
  13281. PyOS_FSPath(PyObject *path)
  13282. {
  13283. /* For error message reasons, this function is manually inlined in
  13284. path_converter(). */
  13285. PyObject *func = NULL;
  13286. PyObject *path_repr = NULL;
  13287. if (PyUnicode_Check(path) || PyBytes_Check(path)) {
  13288. return Py_NewRef(path);
  13289. }
  13290. func = _PyObject_LookupSpecial(path, &_Py_ID(__fspath__));
  13291. if (NULL == func) {
  13292. return PyErr_Format(PyExc_TypeError,
  13293. "expected str, bytes or os.PathLike object, "
  13294. "not %.200s",
  13295. _PyType_Name(Py_TYPE(path)));
  13296. }
  13297. path_repr = _PyObject_CallNoArgs(func);
  13298. Py_DECREF(func);
  13299. if (NULL == path_repr) {
  13300. return NULL;
  13301. }
  13302. if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
  13303. PyErr_Format(PyExc_TypeError,
  13304. "expected %.200s.__fspath__() to return str or bytes, "
  13305. "not %.200s", _PyType_Name(Py_TYPE(path)),
  13306. _PyType_Name(Py_TYPE(path_repr)));
  13307. Py_DECREF(path_repr);
  13308. return NULL;
  13309. }
  13310. return path_repr;
  13311. }
  13312. /*[clinic input]
  13313. os.fspath
  13314. path: object
  13315. Return the file system path representation of the object.
  13316. If the object is str or bytes, then allow it to pass through as-is. If the
  13317. object defines __fspath__(), then return the result of that method. All other
  13318. types raise a TypeError.
  13319. [clinic start generated code]*/
  13320. static PyObject *
  13321. os_fspath_impl(PyObject *module, PyObject *path)
  13322. /*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
  13323. {
  13324. return PyOS_FSPath(path);
  13325. }
  13326. #ifdef HAVE_GETRANDOM_SYSCALL
  13327. /*[clinic input]
  13328. os.getrandom
  13329. size: Py_ssize_t
  13330. flags: int=0
  13331. Obtain a series of random bytes.
  13332. [clinic start generated code]*/
  13333. static PyObject *
  13334. os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
  13335. /*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
  13336. {
  13337. PyObject *bytes;
  13338. Py_ssize_t n;
  13339. if (size < 0) {
  13340. errno = EINVAL;
  13341. return posix_error();
  13342. }
  13343. bytes = PyBytes_FromStringAndSize(NULL, size);
  13344. if (bytes == NULL) {
  13345. PyErr_NoMemory();
  13346. return NULL;
  13347. }
  13348. while (1) {
  13349. n = syscall(SYS_getrandom,
  13350. PyBytes_AS_STRING(bytes),
  13351. PyBytes_GET_SIZE(bytes),
  13352. flags);
  13353. if (n < 0 && errno == EINTR) {
  13354. if (PyErr_CheckSignals() < 0) {
  13355. goto error;
  13356. }
  13357. /* getrandom() was interrupted by a signal: retry */
  13358. continue;
  13359. }
  13360. break;
  13361. }
  13362. if (n < 0) {
  13363. PyErr_SetFromErrno(PyExc_OSError);
  13364. goto error;
  13365. }
  13366. if (n != size) {
  13367. _PyBytes_Resize(&bytes, n);
  13368. }
  13369. return bytes;
  13370. error:
  13371. Py_DECREF(bytes);
  13372. return NULL;
  13373. }
  13374. #endif /* HAVE_GETRANDOM_SYSCALL */
  13375. #if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
  13376. /* bpo-36085: Helper functions for managing DLL search directories
  13377. * on win32
  13378. */
  13379. /*[clinic input]
  13380. os._add_dll_directory
  13381. path: path_t
  13382. Add a path to the DLL search path.
  13383. This search path is used when resolving dependencies for imported
  13384. extension modules (the module itself is resolved through sys.path),
  13385. and also by ctypes.
  13386. Returns an opaque value that may be passed to os.remove_dll_directory
  13387. to remove this directory from the search path.
  13388. [clinic start generated code]*/
  13389. static PyObject *
  13390. os__add_dll_directory_impl(PyObject *module, path_t *path)
  13391. /*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
  13392. {
  13393. DLL_DIRECTORY_COOKIE cookie = 0;
  13394. DWORD err = 0;
  13395. if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
  13396. return NULL;
  13397. }
  13398. Py_BEGIN_ALLOW_THREADS
  13399. if (!(cookie = AddDllDirectory(path->wide))) {
  13400. err = GetLastError();
  13401. }
  13402. Py_END_ALLOW_THREADS
  13403. if (err) {
  13404. return win32_error_object_err("add_dll_directory",
  13405. path->object, err);
  13406. }
  13407. return PyCapsule_New(cookie, "DLL directory cookie", NULL);
  13408. }
  13409. /*[clinic input]
  13410. os._remove_dll_directory
  13411. cookie: object
  13412. Removes a path from the DLL search path.
  13413. The parameter is an opaque value that was returned from
  13414. os.add_dll_directory. You can only remove directories that you added
  13415. yourself.
  13416. [clinic start generated code]*/
  13417. static PyObject *
  13418. os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
  13419. /*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
  13420. {
  13421. DLL_DIRECTORY_COOKIE cookieValue;
  13422. DWORD err = 0;
  13423. if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
  13424. PyErr_SetString(PyExc_TypeError,
  13425. "Provided cookie was not returned from os.add_dll_directory");
  13426. return NULL;
  13427. }
  13428. cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
  13429. cookie, "DLL directory cookie");
  13430. Py_BEGIN_ALLOW_THREADS
  13431. if (!RemoveDllDirectory(cookieValue)) {
  13432. err = GetLastError();
  13433. }
  13434. Py_END_ALLOW_THREADS
  13435. if (err) {
  13436. return win32_error_object_err("remove_dll_directory",
  13437. NULL, err);
  13438. }
  13439. if (PyCapsule_SetName(cookie, NULL)) {
  13440. return NULL;
  13441. }
  13442. Py_RETURN_NONE;
  13443. }
  13444. #endif /* MS_WINDOWS_APP || MS_WINDOWS_SYSTEM */
  13445. /* Only check if WIFEXITED is available: expect that it comes
  13446. with WEXITSTATUS, WIFSIGNALED, etc.
  13447. os.waitstatus_to_exitcode() is implemented in C and not in Python, so
  13448. subprocess can safely call it during late Python finalization without
  13449. risking that used os attributes were set to None by finalize_modules(). */
  13450. #if defined(WIFEXITED) || defined(MS_WINDOWS)
  13451. /*[clinic input]
  13452. os.waitstatus_to_exitcode
  13453. status as status_obj: object
  13454. Convert a wait status to an exit code.
  13455. On Unix:
  13456. * If WIFEXITED(status) is true, return WEXITSTATUS(status).
  13457. * If WIFSIGNALED(status) is true, return -WTERMSIG(status).
  13458. * Otherwise, raise a ValueError.
  13459. On Windows, return status shifted right by 8 bits.
  13460. On Unix, if the process is being traced or if waitpid() was called with
  13461. WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true.
  13462. This function must not be called if WIFSTOPPED(status) is true.
  13463. [clinic start generated code]*/
  13464. static PyObject *
  13465. os_waitstatus_to_exitcode_impl(PyObject *module, PyObject *status_obj)
  13466. /*[clinic end generated code: output=db50b1b0ba3c7153 input=7fe2d7fdaea3db42]*/
  13467. {
  13468. #ifndef MS_WINDOWS
  13469. int status = _PyLong_AsInt(status_obj);
  13470. if (status == -1 && PyErr_Occurred()) {
  13471. return NULL;
  13472. }
  13473. WAIT_TYPE wait_status;
  13474. WAIT_STATUS_INT(wait_status) = status;
  13475. int exitcode;
  13476. if (WIFEXITED(wait_status)) {
  13477. exitcode = WEXITSTATUS(wait_status);
  13478. /* Sanity check to provide warranty on the function behavior.
  13479. It should not occur in practice */
  13480. if (exitcode < 0) {
  13481. PyErr_Format(PyExc_ValueError, "invalid WEXITSTATUS: %i", exitcode);
  13482. return NULL;
  13483. }
  13484. }
  13485. else if (WIFSIGNALED(wait_status)) {
  13486. int signum = WTERMSIG(wait_status);
  13487. /* Sanity check to provide warranty on the function behavior.
  13488. It should not occurs in practice */
  13489. if (signum <= 0) {
  13490. PyErr_Format(PyExc_ValueError, "invalid WTERMSIG: %i", signum);
  13491. return NULL;
  13492. }
  13493. exitcode = -signum;
  13494. } else if (WIFSTOPPED(wait_status)) {
  13495. /* Status only received if the process is being traced
  13496. or if waitpid() was called with WUNTRACED option. */
  13497. int signum = WSTOPSIG(wait_status);
  13498. PyErr_Format(PyExc_ValueError,
  13499. "process stopped by delivery of signal %i",
  13500. signum);
  13501. return NULL;
  13502. }
  13503. else {
  13504. PyErr_Format(PyExc_ValueError, "invalid wait status: %i", status);
  13505. return NULL;
  13506. }
  13507. return PyLong_FromLong(exitcode);
  13508. #else
  13509. /* Windows implementation: see os.waitpid() implementation
  13510. which uses _cwait(). */
  13511. unsigned long long status = PyLong_AsUnsignedLongLong(status_obj);
  13512. if (status == (unsigned long long)-1 && PyErr_Occurred()) {
  13513. return NULL;
  13514. }
  13515. unsigned long long exitcode = (status >> 8);
  13516. /* ExitProcess() accepts an UINT type:
  13517. reject exit code which doesn't fit in an UINT */
  13518. if (exitcode > UINT_MAX) {
  13519. PyErr_Format(PyExc_ValueError, "invalid exit code: %llu", exitcode);
  13520. return NULL;
  13521. }
  13522. return PyLong_FromUnsignedLong((unsigned long)exitcode);
  13523. #endif
  13524. }
  13525. #endif
  13526. static PyMethodDef posix_methods[] = {
  13527. OS_STAT_METHODDEF
  13528. OS_ACCESS_METHODDEF
  13529. OS_TTYNAME_METHODDEF
  13530. OS_CHDIR_METHODDEF
  13531. OS_CHFLAGS_METHODDEF
  13532. OS_CHMOD_METHODDEF
  13533. OS_FCHMOD_METHODDEF
  13534. OS_LCHMOD_METHODDEF
  13535. OS_CHOWN_METHODDEF
  13536. OS_FCHOWN_METHODDEF
  13537. OS_LCHOWN_METHODDEF
  13538. OS_LCHFLAGS_METHODDEF
  13539. OS_CHROOT_METHODDEF
  13540. OS_CTERMID_METHODDEF
  13541. OS_GETCWD_METHODDEF
  13542. OS_GETCWDB_METHODDEF
  13543. OS_LINK_METHODDEF
  13544. OS_LISTDIR_METHODDEF
  13545. OS_LISTDRIVES_METHODDEF
  13546. OS_LISTMOUNTS_METHODDEF
  13547. OS_LISTVOLUMES_METHODDEF
  13548. OS_LSTAT_METHODDEF
  13549. OS_MKDIR_METHODDEF
  13550. OS_NICE_METHODDEF
  13551. OS_GETPRIORITY_METHODDEF
  13552. OS_SETPRIORITY_METHODDEF
  13553. OS_POSIX_SPAWN_METHODDEF
  13554. OS_POSIX_SPAWNP_METHODDEF
  13555. OS_READLINK_METHODDEF
  13556. OS_COPY_FILE_RANGE_METHODDEF
  13557. OS_SPLICE_METHODDEF
  13558. OS_RENAME_METHODDEF
  13559. OS_REPLACE_METHODDEF
  13560. OS_RMDIR_METHODDEF
  13561. OS_SYMLINK_METHODDEF
  13562. OS_SYSTEM_METHODDEF
  13563. OS_UMASK_METHODDEF
  13564. OS_UNAME_METHODDEF
  13565. OS_UNLINK_METHODDEF
  13566. OS_REMOVE_METHODDEF
  13567. OS_UTIME_METHODDEF
  13568. OS_TIMES_METHODDEF
  13569. OS__EXIT_METHODDEF
  13570. OS__FCOPYFILE_METHODDEF
  13571. OS_EXECV_METHODDEF
  13572. OS_EXECVE_METHODDEF
  13573. OS_SPAWNV_METHODDEF
  13574. OS_SPAWNVE_METHODDEF
  13575. OS_FORK1_METHODDEF
  13576. OS_FORK_METHODDEF
  13577. OS_REGISTER_AT_FORK_METHODDEF
  13578. OS_SCHED_GET_PRIORITY_MAX_METHODDEF
  13579. OS_SCHED_GET_PRIORITY_MIN_METHODDEF
  13580. OS_SCHED_GETPARAM_METHODDEF
  13581. OS_SCHED_GETSCHEDULER_METHODDEF
  13582. OS_SCHED_RR_GET_INTERVAL_METHODDEF
  13583. OS_SCHED_SETPARAM_METHODDEF
  13584. OS_SCHED_SETSCHEDULER_METHODDEF
  13585. OS_SCHED_YIELD_METHODDEF
  13586. OS_SCHED_SETAFFINITY_METHODDEF
  13587. OS_SCHED_GETAFFINITY_METHODDEF
  13588. OS_OPENPTY_METHODDEF
  13589. OS_LOGIN_TTY_METHODDEF
  13590. OS_FORKPTY_METHODDEF
  13591. OS_GETEGID_METHODDEF
  13592. OS_GETEUID_METHODDEF
  13593. OS_GETGID_METHODDEF
  13594. OS_GETGROUPLIST_METHODDEF
  13595. OS_GETGROUPS_METHODDEF
  13596. OS_GETPID_METHODDEF
  13597. OS_GETPGRP_METHODDEF
  13598. OS_GETPPID_METHODDEF
  13599. OS_GETUID_METHODDEF
  13600. OS_GETLOGIN_METHODDEF
  13601. OS_KILL_METHODDEF
  13602. OS_KILLPG_METHODDEF
  13603. OS_PLOCK_METHODDEF
  13604. OS_STARTFILE_METHODDEF
  13605. OS_SETUID_METHODDEF
  13606. OS_SETEUID_METHODDEF
  13607. OS_SETREUID_METHODDEF
  13608. OS_SETGID_METHODDEF
  13609. OS_SETEGID_METHODDEF
  13610. OS_SETREGID_METHODDEF
  13611. OS_SETGROUPS_METHODDEF
  13612. OS_INITGROUPS_METHODDEF
  13613. OS_GETPGID_METHODDEF
  13614. OS_SETPGRP_METHODDEF
  13615. OS_WAIT_METHODDEF
  13616. OS_WAIT3_METHODDEF
  13617. OS_WAIT4_METHODDEF
  13618. OS_WAITID_METHODDEF
  13619. OS_WAITPID_METHODDEF
  13620. OS_PIDFD_OPEN_METHODDEF
  13621. OS_GETSID_METHODDEF
  13622. OS_SETSID_METHODDEF
  13623. OS_SETPGID_METHODDEF
  13624. OS_TCGETPGRP_METHODDEF
  13625. OS_TCSETPGRP_METHODDEF
  13626. OS_OPEN_METHODDEF
  13627. OS_CLOSE_METHODDEF
  13628. OS_CLOSERANGE_METHODDEF
  13629. OS_DEVICE_ENCODING_METHODDEF
  13630. OS_DUP_METHODDEF
  13631. OS_DUP2_METHODDEF
  13632. OS_LOCKF_METHODDEF
  13633. OS_LSEEK_METHODDEF
  13634. OS_READ_METHODDEF
  13635. OS_READV_METHODDEF
  13636. OS_PREAD_METHODDEF
  13637. OS_PREADV_METHODDEF
  13638. OS_WRITE_METHODDEF
  13639. OS_WRITEV_METHODDEF
  13640. OS_PWRITE_METHODDEF
  13641. OS_PWRITEV_METHODDEF
  13642. OS_SENDFILE_METHODDEF
  13643. OS_FSTAT_METHODDEF
  13644. OS_ISATTY_METHODDEF
  13645. OS_PIPE_METHODDEF
  13646. OS_PIPE2_METHODDEF
  13647. OS_MKFIFO_METHODDEF
  13648. OS_MKNOD_METHODDEF
  13649. OS_MAJOR_METHODDEF
  13650. OS_MINOR_METHODDEF
  13651. OS_MAKEDEV_METHODDEF
  13652. OS_FTRUNCATE_METHODDEF
  13653. OS_TRUNCATE_METHODDEF
  13654. OS_POSIX_FALLOCATE_METHODDEF
  13655. OS_POSIX_FADVISE_METHODDEF
  13656. OS_PUTENV_METHODDEF
  13657. OS_UNSETENV_METHODDEF
  13658. OS_STRERROR_METHODDEF
  13659. OS_FCHDIR_METHODDEF
  13660. OS_FSYNC_METHODDEF
  13661. OS_SYNC_METHODDEF
  13662. OS_FDATASYNC_METHODDEF
  13663. OS_WCOREDUMP_METHODDEF
  13664. OS_WIFCONTINUED_METHODDEF
  13665. OS_WIFSTOPPED_METHODDEF
  13666. OS_WIFSIGNALED_METHODDEF
  13667. OS_WIFEXITED_METHODDEF
  13668. OS_WEXITSTATUS_METHODDEF
  13669. OS_WTERMSIG_METHODDEF
  13670. OS_WSTOPSIG_METHODDEF
  13671. OS_FSTATVFS_METHODDEF
  13672. OS_STATVFS_METHODDEF
  13673. OS_CONFSTR_METHODDEF
  13674. OS_SYSCONF_METHODDEF
  13675. OS_FPATHCONF_METHODDEF
  13676. OS_PATHCONF_METHODDEF
  13677. OS_ABORT_METHODDEF
  13678. OS__GETFULLPATHNAME_METHODDEF
  13679. OS__GETDISKUSAGE_METHODDEF
  13680. OS__GETFINALPATHNAME_METHODDEF
  13681. OS__GETVOLUMEPATHNAME_METHODDEF
  13682. OS__PATH_SPLITROOT_METHODDEF
  13683. OS__PATH_NORMPATH_METHODDEF
  13684. OS_GETLOADAVG_METHODDEF
  13685. OS_URANDOM_METHODDEF
  13686. OS_SETRESUID_METHODDEF
  13687. OS_SETRESGID_METHODDEF
  13688. OS_GETRESUID_METHODDEF
  13689. OS_GETRESGID_METHODDEF
  13690. OS_GETXATTR_METHODDEF
  13691. OS_SETXATTR_METHODDEF
  13692. OS_REMOVEXATTR_METHODDEF
  13693. OS_LISTXATTR_METHODDEF
  13694. OS_GET_TERMINAL_SIZE_METHODDEF
  13695. OS_CPU_COUNT_METHODDEF
  13696. OS_GET_INHERITABLE_METHODDEF
  13697. OS_SET_INHERITABLE_METHODDEF
  13698. OS_GET_HANDLE_INHERITABLE_METHODDEF
  13699. OS_SET_HANDLE_INHERITABLE_METHODDEF
  13700. OS_GET_BLOCKING_METHODDEF
  13701. OS_SET_BLOCKING_METHODDEF
  13702. OS_SCANDIR_METHODDEF
  13703. OS_FSPATH_METHODDEF
  13704. OS_GETRANDOM_METHODDEF
  13705. OS_MEMFD_CREATE_METHODDEF
  13706. OS_EVENTFD_METHODDEF
  13707. OS_EVENTFD_READ_METHODDEF
  13708. OS_EVENTFD_WRITE_METHODDEF
  13709. OS__ADD_DLL_DIRECTORY_METHODDEF
  13710. OS__REMOVE_DLL_DIRECTORY_METHODDEF
  13711. OS_WAITSTATUS_TO_EXITCODE_METHODDEF
  13712. OS_SETNS_METHODDEF
  13713. OS_UNSHARE_METHODDEF
  13714. OS__PATH_ISDEVDRIVE_METHODDEF
  13715. OS__PATH_ISDIR_METHODDEF
  13716. OS__PATH_ISFILE_METHODDEF
  13717. OS__PATH_ISLINK_METHODDEF
  13718. OS__PATH_EXISTS_METHODDEF
  13719. {NULL, NULL} /* Sentinel */
  13720. };
  13721. static int
  13722. all_ins(PyObject *m)
  13723. {
  13724. #ifdef F_OK
  13725. if (PyModule_AddIntMacro(m, F_OK)) return -1;
  13726. #endif
  13727. #ifdef R_OK
  13728. if (PyModule_AddIntMacro(m, R_OK)) return -1;
  13729. #endif
  13730. #ifdef W_OK
  13731. if (PyModule_AddIntMacro(m, W_OK)) return -1;
  13732. #endif
  13733. #ifdef X_OK
  13734. if (PyModule_AddIntMacro(m, X_OK)) return -1;
  13735. #endif
  13736. #ifdef NGROUPS_MAX
  13737. if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
  13738. #endif
  13739. #ifdef TMP_MAX
  13740. if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
  13741. #endif
  13742. #ifdef WCONTINUED
  13743. if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
  13744. #endif
  13745. #ifdef WNOHANG
  13746. if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
  13747. #endif
  13748. #ifdef WUNTRACED
  13749. if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
  13750. #endif
  13751. #ifdef O_RDONLY
  13752. if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
  13753. #endif
  13754. #ifdef O_WRONLY
  13755. if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
  13756. #endif
  13757. #ifdef O_RDWR
  13758. if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
  13759. #endif
  13760. #ifdef O_NDELAY
  13761. if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
  13762. #endif
  13763. #ifdef O_NONBLOCK
  13764. if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
  13765. #endif
  13766. #ifdef O_APPEND
  13767. if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
  13768. #endif
  13769. #ifdef O_DSYNC
  13770. if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
  13771. #endif
  13772. #ifdef O_RSYNC
  13773. if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
  13774. #endif
  13775. #ifdef O_SYNC
  13776. if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
  13777. #endif
  13778. #ifdef O_NOCTTY
  13779. if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
  13780. #endif
  13781. #ifdef O_CREAT
  13782. if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
  13783. #endif
  13784. #ifdef O_EXCL
  13785. if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
  13786. #endif
  13787. #ifdef O_TRUNC
  13788. if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
  13789. #endif
  13790. #ifdef O_BINARY
  13791. if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
  13792. #endif
  13793. #ifdef O_TEXT
  13794. if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
  13795. #endif
  13796. #ifdef O_XATTR
  13797. if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
  13798. #endif
  13799. #ifdef O_LARGEFILE
  13800. if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
  13801. #endif
  13802. #ifndef __GNU__
  13803. #ifdef O_SHLOCK
  13804. if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
  13805. #endif
  13806. #ifdef O_EXLOCK
  13807. if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
  13808. #endif
  13809. #endif
  13810. #ifdef O_EXEC
  13811. if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
  13812. #endif
  13813. #ifdef O_SEARCH
  13814. if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
  13815. #endif
  13816. #ifdef O_PATH
  13817. if (PyModule_AddIntMacro(m, O_PATH)) return -1;
  13818. #endif
  13819. #ifdef O_TTY_INIT
  13820. if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
  13821. #endif
  13822. #ifdef O_TMPFILE
  13823. if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
  13824. #endif
  13825. #ifdef PRIO_PROCESS
  13826. if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
  13827. #endif
  13828. #ifdef PRIO_PGRP
  13829. if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
  13830. #endif
  13831. #ifdef PRIO_USER
  13832. if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
  13833. #endif
  13834. #ifdef PRIO_DARWIN_THREAD
  13835. if (PyModule_AddIntMacro(m, PRIO_DARWIN_THREAD)) return -1;
  13836. #endif
  13837. #ifdef PRIO_DARWIN_PROCESS
  13838. if (PyModule_AddIntMacro(m, PRIO_DARWIN_PROCESS)) return -1;
  13839. #endif
  13840. #ifdef PRIO_DARWIN_BG
  13841. if (PyModule_AddIntMacro(m, PRIO_DARWIN_BG)) return -1;
  13842. #endif
  13843. #ifdef PRIO_DARWIN_NONUI
  13844. if (PyModule_AddIntMacro(m, PRIO_DARWIN_NONUI)) return -1;
  13845. #endif
  13846. #ifdef O_CLOEXEC
  13847. if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
  13848. #endif
  13849. #ifdef O_ACCMODE
  13850. if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
  13851. #endif
  13852. #ifdef O_EVTONLY
  13853. if (PyModule_AddIntMacro(m, O_EVTONLY)) return -1;
  13854. #endif
  13855. #ifdef O_FSYNC
  13856. if (PyModule_AddIntMacro(m, O_FSYNC)) return -1;
  13857. #endif
  13858. #ifdef O_SYMLINK
  13859. if (PyModule_AddIntMacro(m, O_SYMLINK)) return -1;
  13860. #endif
  13861. #ifdef SEEK_HOLE
  13862. if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
  13863. #endif
  13864. #ifdef SEEK_DATA
  13865. if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
  13866. #endif
  13867. /* MS Windows */
  13868. #ifdef O_NOINHERIT
  13869. /* Don't inherit in child processes. */
  13870. if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
  13871. #endif
  13872. #ifdef _O_SHORT_LIVED
  13873. /* Optimize for short life (keep in memory). */
  13874. /* MS forgot to define this one with a non-underscore form too. */
  13875. if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
  13876. #endif
  13877. #ifdef O_TEMPORARY
  13878. /* Automatically delete when last handle is closed. */
  13879. if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
  13880. #endif
  13881. #ifdef O_RANDOM
  13882. /* Optimize for random access. */
  13883. if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
  13884. #endif
  13885. #ifdef O_SEQUENTIAL
  13886. /* Optimize for sequential access. */
  13887. if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
  13888. #endif
  13889. /* GNU extensions. */
  13890. #ifdef O_ASYNC
  13891. /* Send a SIGIO signal whenever input or output
  13892. becomes available on file descriptor */
  13893. if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
  13894. #endif
  13895. #ifdef O_DIRECT
  13896. /* Direct disk access. */
  13897. if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
  13898. #endif
  13899. #ifdef O_DIRECTORY
  13900. /* Must be a directory. */
  13901. if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
  13902. #endif
  13903. #ifdef O_NOFOLLOW
  13904. /* Do not follow links. */
  13905. if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
  13906. #endif
  13907. #ifdef O_NOFOLLOW_ANY
  13908. if (PyModule_AddIntMacro(m, O_NOFOLLOW_ANY)) return -1;
  13909. #endif
  13910. #ifdef O_NOLINKS
  13911. /* Fails if link count of the named file is greater than 1 */
  13912. if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
  13913. #endif
  13914. #ifdef O_NOATIME
  13915. /* Do not update the access time. */
  13916. if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
  13917. #endif
  13918. /* These come from sysexits.h */
  13919. #ifdef EX_OK
  13920. if (PyModule_AddIntMacro(m, EX_OK)) return -1;
  13921. #endif /* EX_OK */
  13922. #ifdef EX_USAGE
  13923. if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
  13924. #endif /* EX_USAGE */
  13925. #ifdef EX_DATAERR
  13926. if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
  13927. #endif /* EX_DATAERR */
  13928. #ifdef EX_NOINPUT
  13929. if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
  13930. #endif /* EX_NOINPUT */
  13931. #ifdef EX_NOUSER
  13932. if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
  13933. #endif /* EX_NOUSER */
  13934. #ifdef EX_NOHOST
  13935. if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
  13936. #endif /* EX_NOHOST */
  13937. #ifdef EX_UNAVAILABLE
  13938. if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
  13939. #endif /* EX_UNAVAILABLE */
  13940. #ifdef EX_SOFTWARE
  13941. if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
  13942. #endif /* EX_SOFTWARE */
  13943. #ifdef EX_OSERR
  13944. if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
  13945. #endif /* EX_OSERR */
  13946. #ifdef EX_OSFILE
  13947. if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
  13948. #endif /* EX_OSFILE */
  13949. #ifdef EX_CANTCREAT
  13950. if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
  13951. #endif /* EX_CANTCREAT */
  13952. #ifdef EX_IOERR
  13953. if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
  13954. #endif /* EX_IOERR */
  13955. #ifdef EX_TEMPFAIL
  13956. if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
  13957. #endif /* EX_TEMPFAIL */
  13958. #ifdef EX_PROTOCOL
  13959. if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
  13960. #endif /* EX_PROTOCOL */
  13961. #ifdef EX_NOPERM
  13962. if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
  13963. #endif /* EX_NOPERM */
  13964. #ifdef EX_CONFIG
  13965. if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
  13966. #endif /* EX_CONFIG */
  13967. #ifdef EX_NOTFOUND
  13968. if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
  13969. #endif /* EX_NOTFOUND */
  13970. /* statvfs */
  13971. #ifdef ST_RDONLY
  13972. if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
  13973. #endif /* ST_RDONLY */
  13974. #ifdef ST_NOSUID
  13975. if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
  13976. #endif /* ST_NOSUID */
  13977. /* GNU extensions */
  13978. #ifdef ST_NODEV
  13979. if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
  13980. #endif /* ST_NODEV */
  13981. #ifdef ST_NOEXEC
  13982. if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
  13983. #endif /* ST_NOEXEC */
  13984. #ifdef ST_SYNCHRONOUS
  13985. if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
  13986. #endif /* ST_SYNCHRONOUS */
  13987. #ifdef ST_MANDLOCK
  13988. if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
  13989. #endif /* ST_MANDLOCK */
  13990. #ifdef ST_WRITE
  13991. if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
  13992. #endif /* ST_WRITE */
  13993. #ifdef ST_APPEND
  13994. if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
  13995. #endif /* ST_APPEND */
  13996. #ifdef ST_NOATIME
  13997. if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
  13998. #endif /* ST_NOATIME */
  13999. #ifdef ST_NODIRATIME
  14000. if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
  14001. #endif /* ST_NODIRATIME */
  14002. #ifdef ST_RELATIME
  14003. if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
  14004. #endif /* ST_RELATIME */
  14005. /* FreeBSD sendfile() constants */
  14006. #ifdef SF_NODISKIO
  14007. if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
  14008. #endif
  14009. /* is obsolete since the 11.x release */
  14010. #ifdef SF_MNOWAIT
  14011. if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
  14012. #endif
  14013. #ifdef SF_SYNC
  14014. if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
  14015. #endif
  14016. #ifdef SF_NOCACHE
  14017. if (PyModule_AddIntMacro(m, SF_NOCACHE)) return -1;
  14018. #endif
  14019. /* constants for posix_fadvise */
  14020. #ifdef POSIX_FADV_NORMAL
  14021. if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
  14022. #endif
  14023. #ifdef POSIX_FADV_SEQUENTIAL
  14024. if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
  14025. #endif
  14026. #ifdef POSIX_FADV_RANDOM
  14027. if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
  14028. #endif
  14029. #ifdef POSIX_FADV_NOREUSE
  14030. if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
  14031. #endif
  14032. #ifdef POSIX_FADV_WILLNEED
  14033. if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
  14034. #endif
  14035. #ifdef POSIX_FADV_DONTNEED
  14036. if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
  14037. #endif
  14038. /* constants for waitid */
  14039. #if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
  14040. if (PyModule_AddIntMacro(m, P_PID)) return -1;
  14041. if (PyModule_AddIntMacro(m, P_PGID)) return -1;
  14042. if (PyModule_AddIntMacro(m, P_ALL)) return -1;
  14043. #ifdef P_PIDFD
  14044. if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
  14045. #endif
  14046. #ifdef PIDFD_NONBLOCK
  14047. if (PyModule_AddIntMacro(m, PIDFD_NONBLOCK)) return -1;
  14048. #endif
  14049. #endif
  14050. #ifdef WEXITED
  14051. if (PyModule_AddIntMacro(m, WEXITED)) return -1;
  14052. #endif
  14053. #ifdef WNOWAIT
  14054. if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
  14055. #endif
  14056. #ifdef WSTOPPED
  14057. if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
  14058. #endif
  14059. #ifdef CLD_EXITED
  14060. if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
  14061. #endif
  14062. #ifdef CLD_KILLED
  14063. if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
  14064. #endif
  14065. #ifdef CLD_DUMPED
  14066. if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
  14067. #endif
  14068. #ifdef CLD_TRAPPED
  14069. if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
  14070. #endif
  14071. #ifdef CLD_STOPPED
  14072. if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
  14073. #endif
  14074. #ifdef CLD_CONTINUED
  14075. if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
  14076. #endif
  14077. /* constants for lockf */
  14078. #ifdef F_LOCK
  14079. if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
  14080. #endif
  14081. #ifdef F_TLOCK
  14082. if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
  14083. #endif
  14084. #ifdef F_ULOCK
  14085. if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
  14086. #endif
  14087. #ifdef F_TEST
  14088. if (PyModule_AddIntMacro(m, F_TEST)) return -1;
  14089. #endif
  14090. #ifdef RWF_DSYNC
  14091. if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
  14092. #endif
  14093. #ifdef RWF_HIPRI
  14094. if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
  14095. #endif
  14096. #ifdef RWF_SYNC
  14097. if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
  14098. #endif
  14099. #ifdef RWF_NOWAIT
  14100. if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
  14101. #endif
  14102. #ifdef RWF_APPEND
  14103. if (PyModule_AddIntConstant(m, "RWF_APPEND", RWF_APPEND)) return -1;
  14104. #endif
  14105. /* constants for splice */
  14106. #if defined(HAVE_SPLICE) && defined(__linux__)
  14107. if (PyModule_AddIntConstant(m, "SPLICE_F_MOVE", SPLICE_F_MOVE)) return -1;
  14108. if (PyModule_AddIntConstant(m, "SPLICE_F_NONBLOCK", SPLICE_F_NONBLOCK)) return -1;
  14109. if (PyModule_AddIntConstant(m, "SPLICE_F_MORE", SPLICE_F_MORE)) return -1;
  14110. #endif
  14111. /* constants for posix_spawn */
  14112. #ifdef HAVE_POSIX_SPAWN
  14113. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
  14114. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
  14115. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
  14116. #endif
  14117. #if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
  14118. if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
  14119. if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
  14120. if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
  14121. #endif
  14122. #ifdef HAVE_SPAWNV
  14123. if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
  14124. if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
  14125. #endif
  14126. #ifdef HAVE_SCHED_H
  14127. #ifdef SCHED_OTHER
  14128. if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
  14129. #endif
  14130. #ifdef SCHED_FIFO
  14131. if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
  14132. #endif
  14133. #ifdef SCHED_RR
  14134. if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
  14135. #endif
  14136. #ifdef SCHED_SPORADIC
  14137. if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
  14138. #endif
  14139. #ifdef SCHED_BATCH
  14140. if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
  14141. #endif
  14142. #ifdef SCHED_IDLE
  14143. if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
  14144. #endif
  14145. #ifdef SCHED_RESET_ON_FORK
  14146. if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
  14147. #endif
  14148. #ifdef SCHED_SYS
  14149. if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
  14150. #endif
  14151. #ifdef SCHED_IA
  14152. if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
  14153. #endif
  14154. #ifdef SCHED_FSS
  14155. if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
  14156. #endif
  14157. #ifdef SCHED_FX
  14158. if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
  14159. #endif
  14160. /* constants for namespaces */
  14161. #if defined(HAVE_SETNS) || defined(HAVE_UNSHARE)
  14162. #ifdef CLONE_FS
  14163. if (PyModule_AddIntMacro(m, CLONE_FS)) return -1;
  14164. #endif
  14165. #ifdef CLONE_FILES
  14166. if (PyModule_AddIntMacro(m, CLONE_FILES)) return -1;
  14167. #endif
  14168. #ifdef CLONE_NEWNS
  14169. if (PyModule_AddIntMacro(m, CLONE_NEWNS)) return -1;
  14170. #endif
  14171. #ifdef CLONE_NEWCGROUP
  14172. if (PyModule_AddIntMacro(m, CLONE_NEWCGROUP)) return -1;
  14173. #endif
  14174. #ifdef CLONE_NEWUTS
  14175. if (PyModule_AddIntMacro(m, CLONE_NEWUTS)) return -1;
  14176. #endif
  14177. #ifdef CLONE_NEWIPC
  14178. if (PyModule_AddIntMacro(m, CLONE_NEWIPC)) return -1;
  14179. #endif
  14180. #ifdef CLONE_NEWUSER
  14181. if (PyModule_AddIntMacro(m, CLONE_NEWUSER)) return -1;
  14182. #endif
  14183. #ifdef CLONE_NEWPID
  14184. if (PyModule_AddIntMacro(m, CLONE_NEWPID)) return -1;
  14185. #endif
  14186. #ifdef CLONE_NEWNET
  14187. if (PyModule_AddIntMacro(m, CLONE_NEWNET)) return -1;
  14188. #endif
  14189. #ifdef CLONE_NEWTIME
  14190. if (PyModule_AddIntMacro(m, CLONE_NEWTIME)) return -1;
  14191. #endif
  14192. #ifdef CLONE_SYSVSEM
  14193. if (PyModule_AddIntMacro(m, CLONE_SYSVSEM)) return -1;
  14194. #endif
  14195. #ifdef CLONE_THREAD
  14196. if (PyModule_AddIntMacro(m, CLONE_THREAD)) return -1;
  14197. #endif
  14198. #ifdef CLONE_SIGHAND
  14199. if (PyModule_AddIntMacro(m, CLONE_SIGHAND)) return -1;
  14200. #endif
  14201. #ifdef CLONE_VM
  14202. if (PyModule_AddIntMacro(m, CLONE_VM)) return -1;
  14203. #endif
  14204. #endif
  14205. #endif
  14206. #ifdef USE_XATTRS
  14207. if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
  14208. if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
  14209. if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
  14210. #endif
  14211. #if HAVE_DECL_RTLD_LAZY
  14212. if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
  14213. #endif
  14214. #if HAVE_DECL_RTLD_NOW
  14215. if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
  14216. #endif
  14217. #if HAVE_DECL_RTLD_GLOBAL
  14218. if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
  14219. #endif
  14220. #if HAVE_DECL_RTLD_LOCAL
  14221. if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
  14222. #endif
  14223. #if HAVE_DECL_RTLD_NODELETE
  14224. if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
  14225. #endif
  14226. #if HAVE_DECL_RTLD_NOLOAD
  14227. if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
  14228. #endif
  14229. #if HAVE_DECL_RTLD_DEEPBIND
  14230. if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
  14231. #endif
  14232. #if HAVE_DECL_RTLD_MEMBER
  14233. if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
  14234. #endif
  14235. #ifdef HAVE_GETRANDOM_SYSCALL
  14236. if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
  14237. if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
  14238. #endif
  14239. #ifdef HAVE_MEMFD_CREATE
  14240. if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
  14241. if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
  14242. #ifdef MFD_HUGETLB
  14243. if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
  14244. #endif
  14245. #ifdef MFD_HUGE_SHIFT
  14246. if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
  14247. #endif
  14248. #ifdef MFD_HUGE_MASK
  14249. if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
  14250. #endif
  14251. #ifdef MFD_HUGE_64KB
  14252. if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
  14253. #endif
  14254. #ifdef MFD_HUGE_512KB
  14255. if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
  14256. #endif
  14257. #ifdef MFD_HUGE_1MB
  14258. if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
  14259. #endif
  14260. #ifdef MFD_HUGE_2MB
  14261. if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
  14262. #endif
  14263. #ifdef MFD_HUGE_8MB
  14264. if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
  14265. #endif
  14266. #ifdef MFD_HUGE_16MB
  14267. if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
  14268. #endif
  14269. #ifdef MFD_HUGE_32MB
  14270. if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
  14271. #endif
  14272. #ifdef MFD_HUGE_256MB
  14273. if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
  14274. #endif
  14275. #ifdef MFD_HUGE_512MB
  14276. if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
  14277. #endif
  14278. #ifdef MFD_HUGE_1GB
  14279. if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
  14280. #endif
  14281. #ifdef MFD_HUGE_2GB
  14282. if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
  14283. #endif
  14284. #ifdef MFD_HUGE_16GB
  14285. if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
  14286. #endif
  14287. #endif /* HAVE_MEMFD_CREATE */
  14288. #if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
  14289. if (PyModule_AddIntMacro(m, EFD_CLOEXEC)) return -1;
  14290. #ifdef EFD_NONBLOCK
  14291. if (PyModule_AddIntMacro(m, EFD_NONBLOCK)) return -1;
  14292. #endif
  14293. #ifdef EFD_SEMAPHORE
  14294. if (PyModule_AddIntMacro(m, EFD_SEMAPHORE)) return -1;
  14295. #endif
  14296. #endif /* HAVE_EVENTFD && EFD_CLOEXEC */
  14297. #if defined(__APPLE__)
  14298. if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
  14299. if (PyModule_AddIntConstant(m, "_COPYFILE_STAT", COPYFILE_STAT)) return -1;
  14300. if (PyModule_AddIntConstant(m, "_COPYFILE_ACL", COPYFILE_ACL)) return -1;
  14301. if (PyModule_AddIntConstant(m, "_COPYFILE_XATTR", COPYFILE_XATTR)) return -1;
  14302. #endif
  14303. #ifdef MS_WINDOWS
  14304. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
  14305. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
  14306. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
  14307. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
  14308. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
  14309. #endif
  14310. return 0;
  14311. }
  14312. #define PROBE(name, test) \
  14313. static int name(void) \
  14314. { \
  14315. if (test) { \
  14316. return 1; \
  14317. } else { \
  14318. return 0; \
  14319. } \
  14320. }
  14321. #ifdef HAVE_FSTATAT
  14322. PROBE(probe_fstatat, HAVE_FSTATAT_RUNTIME)
  14323. #endif
  14324. #ifdef HAVE_FACCESSAT
  14325. PROBE(probe_faccessat, HAVE_FACCESSAT_RUNTIME)
  14326. #endif
  14327. #ifdef HAVE_FCHMODAT
  14328. PROBE(probe_fchmodat, HAVE_FCHMODAT_RUNTIME)
  14329. #endif
  14330. #ifdef HAVE_FCHOWNAT
  14331. PROBE(probe_fchownat, HAVE_FCHOWNAT_RUNTIME)
  14332. #endif
  14333. #ifdef HAVE_LINKAT
  14334. PROBE(probe_linkat, HAVE_LINKAT_RUNTIME)
  14335. #endif
  14336. #ifdef HAVE_FDOPENDIR
  14337. PROBE(probe_fdopendir, HAVE_FDOPENDIR_RUNTIME)
  14338. #endif
  14339. #ifdef HAVE_MKDIRAT
  14340. PROBE(probe_mkdirat, HAVE_MKDIRAT_RUNTIME)
  14341. #endif
  14342. #ifdef HAVE_MKFIFOAT
  14343. PROBE(probe_mkfifoat, HAVE_MKFIFOAT_RUNTIME)
  14344. #endif
  14345. #ifdef HAVE_MKNODAT
  14346. PROBE(probe_mknodat, HAVE_MKNODAT_RUNTIME)
  14347. #endif
  14348. #ifdef HAVE_RENAMEAT
  14349. PROBE(probe_renameat, HAVE_RENAMEAT_RUNTIME)
  14350. #endif
  14351. #ifdef HAVE_UNLINKAT
  14352. PROBE(probe_unlinkat, HAVE_UNLINKAT_RUNTIME)
  14353. #endif
  14354. #ifdef HAVE_OPENAT
  14355. PROBE(probe_openat, HAVE_OPENAT_RUNTIME)
  14356. #endif
  14357. #ifdef HAVE_READLINKAT
  14358. PROBE(probe_readlinkat, HAVE_READLINKAT_RUNTIME)
  14359. #endif
  14360. #ifdef HAVE_SYMLINKAT
  14361. PROBE(probe_symlinkat, HAVE_SYMLINKAT_RUNTIME)
  14362. #endif
  14363. #ifdef HAVE_FUTIMENS
  14364. PROBE(probe_futimens, HAVE_FUTIMENS_RUNTIME)
  14365. #endif
  14366. #ifdef HAVE_UTIMENSAT
  14367. PROBE(probe_utimensat, HAVE_UTIMENSAT_RUNTIME)
  14368. #endif
  14369. static const struct have_function {
  14370. const char * const label;
  14371. int (*probe)(void);
  14372. } have_functions[] = {
  14373. #ifdef HAVE_EVENTFD
  14374. {"HAVE_EVENTFD", NULL},
  14375. #endif
  14376. #ifdef HAVE_FACCESSAT
  14377. { "HAVE_FACCESSAT", probe_faccessat },
  14378. #endif
  14379. #ifdef HAVE_FCHDIR
  14380. { "HAVE_FCHDIR", NULL },
  14381. #endif
  14382. #ifdef HAVE_FCHMOD
  14383. { "HAVE_FCHMOD", NULL },
  14384. #endif
  14385. #ifdef HAVE_FCHMODAT
  14386. { "HAVE_FCHMODAT", probe_fchmodat },
  14387. #endif
  14388. #ifdef HAVE_FCHOWN
  14389. { "HAVE_FCHOWN", NULL },
  14390. #endif
  14391. #ifdef HAVE_FCHOWNAT
  14392. { "HAVE_FCHOWNAT", probe_fchownat },
  14393. #endif
  14394. #ifdef HAVE_FEXECVE
  14395. { "HAVE_FEXECVE", NULL },
  14396. #endif
  14397. #ifdef HAVE_FDOPENDIR
  14398. { "HAVE_FDOPENDIR", probe_fdopendir },
  14399. #endif
  14400. #ifdef HAVE_FPATHCONF
  14401. { "HAVE_FPATHCONF", NULL },
  14402. #endif
  14403. #ifdef HAVE_FSTATAT
  14404. { "HAVE_FSTATAT", probe_fstatat },
  14405. #endif
  14406. #ifdef HAVE_FSTATVFS
  14407. { "HAVE_FSTATVFS", NULL },
  14408. #endif
  14409. #if defined HAVE_FTRUNCATE || defined MS_WINDOWS
  14410. { "HAVE_FTRUNCATE", NULL },
  14411. #endif
  14412. #ifdef HAVE_FUTIMENS
  14413. { "HAVE_FUTIMENS", probe_futimens },
  14414. #endif
  14415. #ifdef HAVE_FUTIMES
  14416. { "HAVE_FUTIMES", NULL },
  14417. #endif
  14418. #ifdef HAVE_FUTIMESAT
  14419. { "HAVE_FUTIMESAT", NULL },
  14420. #endif
  14421. #ifdef HAVE_LINKAT
  14422. { "HAVE_LINKAT", probe_linkat },
  14423. #endif
  14424. #ifdef HAVE_LCHFLAGS
  14425. { "HAVE_LCHFLAGS", NULL },
  14426. #endif
  14427. #ifdef HAVE_LCHMOD
  14428. { "HAVE_LCHMOD", NULL },
  14429. #endif
  14430. #ifdef HAVE_LCHOWN
  14431. { "HAVE_LCHOWN", NULL },
  14432. #endif
  14433. #ifdef HAVE_LSTAT
  14434. { "HAVE_LSTAT", NULL },
  14435. #endif
  14436. #ifdef HAVE_LUTIMES
  14437. { "HAVE_LUTIMES", NULL },
  14438. #endif
  14439. #ifdef HAVE_MEMFD_CREATE
  14440. { "HAVE_MEMFD_CREATE", NULL },
  14441. #endif
  14442. #ifdef HAVE_MKDIRAT
  14443. { "HAVE_MKDIRAT", probe_mkdirat },
  14444. #endif
  14445. #ifdef HAVE_MKFIFOAT
  14446. { "HAVE_MKFIFOAT", probe_mkfifoat },
  14447. #endif
  14448. #ifdef HAVE_MKNODAT
  14449. { "HAVE_MKNODAT", probe_mknodat },
  14450. #endif
  14451. #ifdef HAVE_OPENAT
  14452. { "HAVE_OPENAT", probe_openat },
  14453. #endif
  14454. #ifdef HAVE_READLINKAT
  14455. { "HAVE_READLINKAT", probe_readlinkat },
  14456. #endif
  14457. #ifdef HAVE_RENAMEAT
  14458. { "HAVE_RENAMEAT", probe_renameat },
  14459. #endif
  14460. #ifdef HAVE_SYMLINKAT
  14461. { "HAVE_SYMLINKAT", probe_symlinkat },
  14462. #endif
  14463. #ifdef HAVE_UNLINKAT
  14464. { "HAVE_UNLINKAT", probe_unlinkat },
  14465. #endif
  14466. #ifdef HAVE_UTIMENSAT
  14467. { "HAVE_UTIMENSAT", probe_utimensat },
  14468. #endif
  14469. #ifdef MS_WINDOWS
  14470. { "MS_WINDOWS", NULL },
  14471. #endif
  14472. { NULL, NULL }
  14473. };
  14474. static int
  14475. posixmodule_exec(PyObject *m)
  14476. {
  14477. _posixstate *state = get_posix_state(m);
  14478. #if defined(HAVE_PWRITEV)
  14479. if (HAVE_PWRITEV_RUNTIME) {} else {
  14480. PyObject* dct = PyModule_GetDict(m);
  14481. if (dct == NULL) {
  14482. return -1;
  14483. }
  14484. if (PyDict_DelItemString(dct, "pwritev") == -1) {
  14485. PyErr_Clear();
  14486. }
  14487. if (PyDict_DelItemString(dct, "preadv") == -1) {
  14488. PyErr_Clear();
  14489. }
  14490. }
  14491. #endif
  14492. /* Initialize environ dictionary */
  14493. if (_PyModule_Add(m, "environ", convertenviron()) != 0) {
  14494. return -1;
  14495. }
  14496. if (all_ins(m))
  14497. return -1;
  14498. if (setup_confname_tables(m))
  14499. return -1;
  14500. if (PyModule_AddObjectRef(m, "error", PyExc_OSError) < 0) {
  14501. return -1;
  14502. }
  14503. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  14504. waitid_result_desc.name = MODNAME ".waitid_result";
  14505. state->WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
  14506. if (PyModule_AddObjectRef(m, "waitid_result", state->WaitidResultType) < 0) {
  14507. return -1;
  14508. }
  14509. #endif
  14510. stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
  14511. stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
  14512. stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
  14513. stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
  14514. state->StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
  14515. if (PyModule_AddObjectRef(m, "stat_result", state->StatResultType) < 0) {
  14516. return -1;
  14517. }
  14518. state->statresult_new_orig = ((PyTypeObject *)state->StatResultType)->tp_new;
  14519. ((PyTypeObject *)state->StatResultType)->tp_new = statresult_new;
  14520. statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
  14521. state->StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
  14522. if (PyModule_AddObjectRef(m, "statvfs_result", state->StatVFSResultType) < 0) {
  14523. return -1;
  14524. }
  14525. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  14526. sched_param_desc.name = MODNAME ".sched_param";
  14527. state->SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
  14528. if (PyModule_AddObjectRef(m, "sched_param", state->SchedParamType) < 0) {
  14529. return -1;
  14530. }
  14531. ((PyTypeObject *)state->SchedParamType)->tp_new = os_sched_param;
  14532. #endif
  14533. /* initialize TerminalSize_info */
  14534. state->TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
  14535. if (PyModule_AddObjectRef(m, "terminal_size", state->TerminalSizeType) < 0) {
  14536. return -1;
  14537. }
  14538. /* initialize scandir types */
  14539. PyObject *ScandirIteratorType = PyType_FromModuleAndSpec(m, &ScandirIteratorType_spec, NULL);
  14540. if (ScandirIteratorType == NULL) {
  14541. return -1;
  14542. }
  14543. state->ScandirIteratorType = ScandirIteratorType;
  14544. state->DirEntryType = PyType_FromModuleAndSpec(m, &DirEntryType_spec, NULL);
  14545. if (PyModule_AddObjectRef(m, "DirEntry", state->DirEntryType) < 0) {
  14546. return -1;
  14547. }
  14548. times_result_desc.name = MODNAME ".times_result";
  14549. state->TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
  14550. if (PyModule_AddObjectRef(m, "times_result", state->TimesResultType) < 0) {
  14551. return -1;
  14552. }
  14553. state->UnameResultType = (PyObject *)PyStructSequence_NewType(&uname_result_desc);
  14554. if (PyModule_AddObjectRef(m, "uname_result", state->UnameResultType) < 0) {
  14555. return -1;
  14556. }
  14557. if ((state->billion = PyLong_FromLong(1000000000)) == NULL)
  14558. return -1;
  14559. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  14560. state->struct_rusage = PyUnicode_InternFromString("struct_rusage");
  14561. if (state->struct_rusage == NULL)
  14562. return -1;
  14563. #endif
  14564. state->st_mode = PyUnicode_InternFromString("st_mode");
  14565. if (state->st_mode == NULL)
  14566. return -1;
  14567. /* suppress "function not used" warnings */
  14568. {
  14569. int ignored;
  14570. fd_specified("", -1);
  14571. follow_symlinks_specified("", 1);
  14572. dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
  14573. dir_fd_converter(Py_None, &ignored);
  14574. dir_fd_unavailable(Py_None, &ignored);
  14575. }
  14576. /*
  14577. * provide list of locally available functions
  14578. * so os.py can populate support_* lists
  14579. */
  14580. PyObject *list = PyList_New(0);
  14581. if (!list) {
  14582. return -1;
  14583. }
  14584. for (const struct have_function *trace = have_functions; trace->label; trace++) {
  14585. PyObject *unicode;
  14586. if (trace->probe && !trace->probe()) continue;
  14587. unicode = PyUnicode_DecodeASCII(trace->label, strlen(trace->label), NULL);
  14588. if (!unicode)
  14589. return -1;
  14590. if (PyList_Append(list, unicode))
  14591. return -1;
  14592. Py_DECREF(unicode);
  14593. }
  14594. return _PyModule_Add(m, "_have_functions", list);
  14595. }
  14596. static PyModuleDef_Slot posixmodile_slots[] = {
  14597. {Py_mod_exec, posixmodule_exec},
  14598. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  14599. {0, NULL}
  14600. };
  14601. static struct PyModuleDef posixmodule = {
  14602. PyModuleDef_HEAD_INIT,
  14603. .m_name = MODNAME,
  14604. .m_doc = posix__doc__,
  14605. .m_size = sizeof(_posixstate),
  14606. .m_methods = posix_methods,
  14607. .m_slots = posixmodile_slots,
  14608. .m_traverse = _posix_traverse,
  14609. .m_clear = _posix_clear,
  14610. .m_free = _posix_free,
  14611. };
  14612. PyMODINIT_FUNC
  14613. INITFUNC(void)
  14614. {
  14615. return PyModuleDef_Init(&posixmodule);
  14616. }
  14617. #ifdef __cplusplus
  14618. }
  14619. #endif