posixmodule.c 446 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049
  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_moduleobject.h" // _PyModule_GetState()
  19. #include "pycore_object.h" // _PyObject_LookupSpecial()
  20. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  21. #include "pycore_signal.h" // Py_NSIG
  22. #ifdef MS_WINDOWS
  23. # include <windows.h>
  24. # if !defined(MS_WINDOWS_GAMES) || defined(MS_WINDOWS_DESKTOP)
  25. # include <pathcch.h>
  26. # endif
  27. # include <winioctl.h>
  28. # include <lmcons.h> // UNLEN
  29. # include "osdefs.h" // SEP
  30. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  31. # define HAVE_SYMLINK
  32. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_SYSTEM */
  33. #endif
  34. #include "structmember.h" // PyMemberDef
  35. #ifndef MS_WINDOWS
  36. # include "posixmodule.h"
  37. #else
  38. # include "pycore_fileutils_windows.h"
  39. # include "winreparse.h"
  40. #endif
  41. #if !defined(EX_OK) && defined(EXIT_SUCCESS)
  42. # define EX_OK EXIT_SUCCESS
  43. #endif
  44. /* On android API level 21, 'AT_EACCESS' is not declared although
  45. * HAVE_FACCESSAT is defined. */
  46. #ifdef __ANDROID__
  47. # undef HAVE_FACCESSAT
  48. #endif
  49. #include <stdio.h> // ctermid()
  50. #include <stdlib.h> // system()
  51. /*
  52. * A number of APIs are available on macOS from a certain macOS version.
  53. * To support building with a new SDK while deploying to older versions
  54. * the availability test is split into two:
  55. * - HAVE_<FUNCTION>: The configure check for compile time availability
  56. * - HAVE_<FUNCTION>_RUNTIME: Runtime check for availability
  57. *
  58. * The latter is always true when not on macOS, or when using a compiler
  59. * that does not support __has_builtin (older versions of Xcode).
  60. *
  61. * Due to compiler restrictions there is one valid use of HAVE_<FUNCTION>_RUNTIME:
  62. * if (HAVE_<FUNCTION>_RUNTIME) { ... }
  63. *
  64. * In mixing the test with other tests or using negations will result in compile
  65. * errors.
  66. */
  67. #if defined(__APPLE__)
  68. #include <mach/mach.h>
  69. #if defined(__has_builtin)
  70. #if __has_builtin(__builtin_available)
  71. #define HAVE_BUILTIN_AVAILABLE 1
  72. #endif
  73. #endif
  74. #ifdef HAVE_BUILTIN_AVAILABLE
  75. # define HAVE_FSTATAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  76. # define HAVE_FACCESSAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  77. # define HAVE_FCHMODAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  78. # define HAVE_FCHOWNAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  79. # define HAVE_LINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  80. # define HAVE_FDOPENDIR_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  81. # define HAVE_MKDIRAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  82. # define HAVE_RENAMEAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  83. # define HAVE_UNLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  84. # define HAVE_OPENAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  85. # define HAVE_READLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  86. # define HAVE_SYMLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  87. # define HAVE_FUTIMENS_RUNTIME __builtin_available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  88. # define HAVE_UTIMENSAT_RUNTIME __builtin_available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  89. # define HAVE_PWRITEV_RUNTIME __builtin_available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
  90. # define HAVE_MKFIFOAT_RUNTIME __builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
  91. # define HAVE_MKNODAT_RUNTIME __builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
  92. # define HAVE_POSIX_SPAWN_SETSID_RUNTIME __builtin_available(macOS 10.15, *)
  93. #else /* Xcode 8 or earlier */
  94. /* __builtin_available is not present in these compilers, but
  95. * some of the symbols might be weak linked (10.10 SDK or later
  96. * deploying on 10.9.
  97. *
  98. * Fall back to the older style of availability checking for
  99. * symbols introduced in macOS 10.10.
  100. */
  101. # ifdef HAVE_FSTATAT
  102. # define HAVE_FSTATAT_RUNTIME (fstatat != NULL)
  103. # endif
  104. # ifdef HAVE_FACCESSAT
  105. # define HAVE_FACCESSAT_RUNTIME (faccessat != NULL)
  106. # endif
  107. # ifdef HAVE_FCHMODAT
  108. # define HAVE_FCHMODAT_RUNTIME (fchmodat != NULL)
  109. # endif
  110. # ifdef HAVE_FCHOWNAT
  111. # define HAVE_FCHOWNAT_RUNTIME (fchownat != NULL)
  112. # endif
  113. # ifdef HAVE_LINKAT
  114. # define HAVE_LINKAT_RUNTIME (linkat != NULL)
  115. # endif
  116. # ifdef HAVE_FDOPENDIR
  117. # define HAVE_FDOPENDIR_RUNTIME (fdopendir != NULL)
  118. # endif
  119. # ifdef HAVE_MKDIRAT
  120. # define HAVE_MKDIRAT_RUNTIME (mkdirat != NULL)
  121. # endif
  122. # ifdef HAVE_RENAMEAT
  123. # define HAVE_RENAMEAT_RUNTIME (renameat != NULL)
  124. # endif
  125. # ifdef HAVE_UNLINKAT
  126. # define HAVE_UNLINKAT_RUNTIME (unlinkat != NULL)
  127. # endif
  128. # ifdef HAVE_OPENAT
  129. # define HAVE_OPENAT_RUNTIME (openat != NULL)
  130. # endif
  131. # ifdef HAVE_READLINKAT
  132. # define HAVE_READLINKAT_RUNTIME (readlinkat != NULL)
  133. # endif
  134. # ifdef HAVE_SYMLINKAT
  135. # define HAVE_SYMLINKAT_RUNTIME (symlinkat != NULL)
  136. # endif
  137. # ifdef HAVE_UTIMENSAT
  138. # define HAVE_UTIMENSAT_RUNTIME (utimensat != NULL)
  139. # endif
  140. # ifdef HAVE_FUTIMENS
  141. # define HAVE_FUTIMENS_RUNTIME (futimens != NULL)
  142. # endif
  143. # ifdef HAVE_PWRITEV
  144. # define HAVE_PWRITEV_RUNTIME (pwritev != NULL)
  145. # endif
  146. # ifdef HAVE_MKFIFOAT
  147. # define HAVE_MKFIFOAT_RUNTIME (mkfifoat != NULL)
  148. # endif
  149. # ifdef HAVE_MKNODAT
  150. # define HAVE_MKNODAT_RUNTIME (mknodat != NULL)
  151. # endif
  152. #endif
  153. #ifdef HAVE_FUTIMESAT
  154. /* Some of the logic for weak linking depends on this assertion */
  155. # error "HAVE_FUTIMESAT unexpectedly defined"
  156. #endif
  157. #else
  158. # define HAVE_FSTATAT_RUNTIME 1
  159. # define HAVE_FACCESSAT_RUNTIME 1
  160. # define HAVE_FCHMODAT_RUNTIME 1
  161. # define HAVE_FCHOWNAT_RUNTIME 1
  162. # define HAVE_LINKAT_RUNTIME 1
  163. # define HAVE_FDOPENDIR_RUNTIME 1
  164. # define HAVE_MKDIRAT_RUNTIME 1
  165. # define HAVE_RENAMEAT_RUNTIME 1
  166. # define HAVE_UNLINKAT_RUNTIME 1
  167. # define HAVE_OPENAT_RUNTIME 1
  168. # define HAVE_READLINKAT_RUNTIME 1
  169. # define HAVE_SYMLINKAT_RUNTIME 1
  170. # define HAVE_FUTIMENS_RUNTIME 1
  171. # define HAVE_UTIMENSAT_RUNTIME 1
  172. # define HAVE_PWRITEV_RUNTIME 1
  173. # define HAVE_MKFIFOAT_RUNTIME 1
  174. # define HAVE_MKNODAT_RUNTIME 1
  175. #endif
  176. #ifdef __cplusplus
  177. extern "C" {
  178. #endif
  179. PyDoc_STRVAR(posix__doc__,
  180. "This module provides access to operating system functionality that is\n\
  181. standardized by the C Standard and the POSIX standard (a thinly\n\
  182. disguised Unix interface). Refer to the library manual and\n\
  183. corresponding Unix manual entries for more information on calls.");
  184. #ifdef HAVE_SYS_UIO_H
  185. # include <sys/uio.h>
  186. #endif
  187. #ifdef HAVE_SYS_TYPES_H
  188. /* Should be included before <sys/sysmacros.h> on HP-UX v3 */
  189. # include <sys/types.h>
  190. #endif /* HAVE_SYS_TYPES_H */
  191. #ifdef HAVE_SYS_SYSMACROS_H
  192. /* GNU C Library: major(), minor(), makedev() */
  193. # include <sys/sysmacros.h>
  194. #endif
  195. #ifdef HAVE_SYS_STAT_H
  196. # include <sys/stat.h>
  197. #endif /* HAVE_SYS_STAT_H */
  198. #ifdef HAVE_SYS_WAIT_H
  199. # include <sys/wait.h> // WNOHANG
  200. #endif
  201. #ifdef HAVE_LINUX_WAIT_H
  202. # include <linux/wait.h> // P_PIDFD
  203. #endif
  204. #ifdef HAVE_SIGNAL_H
  205. # include <signal.h>
  206. #endif
  207. #ifdef HAVE_FCNTL_H
  208. # include <fcntl.h>
  209. #endif
  210. #ifdef HAVE_GRP_H
  211. # include <grp.h>
  212. #endif
  213. #ifdef HAVE_SYSEXITS_H
  214. # include <sysexits.h>
  215. #endif
  216. #ifdef HAVE_SYS_LOADAVG_H
  217. # include <sys/loadavg.h>
  218. #endif
  219. #ifdef HAVE_SYS_SENDFILE_H
  220. # include <sys/sendfile.h>
  221. #endif
  222. #if defined(__APPLE__)
  223. # include <copyfile.h>
  224. #endif
  225. #ifdef HAVE_SCHED_H
  226. # include <sched.h>
  227. #endif
  228. #ifdef HAVE_COPY_FILE_RANGE
  229. # include <unistd.h>
  230. #endif
  231. #if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
  232. # undef HAVE_SCHED_SETAFFINITY
  233. #endif
  234. #if defined(HAVE_SYS_XATTR_H) && defined(HAVE_LINUX_LIMITS_H) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
  235. # define USE_XATTRS
  236. # include <linux/limits.h> // Needed for XATTR_SIZE_MAX on musl libc.
  237. #endif
  238. #ifdef USE_XATTRS
  239. # include <sys/xattr.h>
  240. #endif
  241. #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
  242. # ifdef HAVE_SYS_SOCKET_H
  243. # include <sys/socket.h>
  244. # endif
  245. #endif
  246. #ifdef HAVE_DLFCN_H
  247. # include <dlfcn.h>
  248. #endif
  249. #ifdef __hpux
  250. # include <sys/mpctl.h>
  251. #endif
  252. #if defined(__DragonFly__) || \
  253. defined(__OpenBSD__) || \
  254. defined(__FreeBSD__) || \
  255. defined(__NetBSD__) || \
  256. defined(__APPLE__)
  257. # include <sys/sysctl.h>
  258. #endif
  259. #ifdef HAVE_LINUX_RANDOM_H
  260. # include <linux/random.h>
  261. #endif
  262. #ifdef HAVE_GETRANDOM_SYSCALL
  263. # include <sys/syscall.h>
  264. # include <sys/random.h>
  265. #endif
  266. #ifdef HAVE_WINDOWS_CONSOLE_IO
  267. # define TERMSIZE_USE_CONIO
  268. #elif defined(HAVE_SYS_IOCTL_H)
  269. # include <sys/ioctl.h>
  270. # if defined(HAVE_TERMIOS_H)
  271. # include <termios.h>
  272. # endif
  273. # if defined(TIOCGWINSZ)
  274. # define TERMSIZE_USE_IOCTL
  275. # endif
  276. #endif /* HAVE_WINDOWS_CONSOLE_IO */
  277. /* Various compilers have only certain posix functions */
  278. /* XXX Gosh I wish these were all moved into pyconfig.h */
  279. #if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
  280. # define HAVE_OPENDIR 1
  281. # define HAVE_SYSTEM 1
  282. # include <process.h>
  283. #elif defined( _MSC_VER)
  284. /* Microsoft compiler */
  285. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
  286. # define HAVE_GETPPID 1
  287. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_APP | MS_WINDOWS_SYSTEM */
  288. # if defined(MS_WINDOWS_DESKTOP)
  289. # define HAVE_GETLOGIN 1
  290. # endif /* MS_WINDOWS_DESKTOP */
  291. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  292. # define HAVE_SPAWNV 1
  293. # define HAVE_EXECV 1
  294. # define HAVE_WSPAWNV 1
  295. # define HAVE_WEXECV 1
  296. # define HAVE_SYSTEM 1
  297. # define HAVE_CWAIT 1
  298. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_SYSTEM */
  299. # define HAVE_PIPE 1
  300. # define HAVE_FSYNC 1
  301. # define fsync _commit
  302. #endif /* ! __WATCOMC__ || __QNX__ */
  303. /*[clinic input]
  304. # one of the few times we lie about this name!
  305. module os
  306. [clinic start generated code]*/
  307. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
  308. #ifndef _MSC_VER
  309. #if defined(__sgi)&&_COMPILER_VERSION>=700
  310. /* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
  311. (default) */
  312. extern char *ctermid_r(char *);
  313. #endif
  314. #endif /* !_MSC_VER */
  315. #if defined(__VXWORKS__)
  316. # error #include <vxCpuLib.h>
  317. # error #include <rtpLib.h>
  318. # include <wait.h>
  319. # error #include <taskLib.h>
  320. # ifndef _P_WAIT
  321. # define _P_WAIT 0
  322. # define _P_NOWAIT 1
  323. # define _P_NOWAITO 1
  324. # endif
  325. #endif /* __VXWORKS__ */
  326. #ifdef HAVE_POSIX_SPAWN
  327. # include <spawn.h>
  328. #endif
  329. #ifdef HAVE_UTIME_H
  330. # include <utime.h>
  331. #endif /* HAVE_UTIME_H */
  332. #ifdef HAVE_SYS_UTIME_H
  333. # include <sys/utime.h>
  334. # define HAVE_UTIME_H /* pretend we do for the rest of this file */
  335. #endif /* HAVE_SYS_UTIME_H */
  336. #ifdef HAVE_SYS_TIMES_H
  337. # include <sys/times.h>
  338. #endif /* HAVE_SYS_TIMES_H */
  339. #ifdef HAVE_SYS_PARAM_H
  340. # include <sys/param.h>
  341. #endif /* HAVE_SYS_PARAM_H */
  342. #ifdef HAVE_SYS_UTSNAME_H
  343. # include <sys/utsname.h>
  344. #endif /* HAVE_SYS_UTSNAME_H */
  345. #ifdef HAVE_DIRENT_H
  346. # include <dirent.h>
  347. # define NAMLEN(dirent) strlen((dirent)->d_name)
  348. #else
  349. # if defined(__WATCOMC__) && !defined(__QNX__)
  350. # include <direct.h>
  351. # define NAMLEN(dirent) strlen((dirent)->d_name)
  352. # else
  353. # define dirent direct
  354. # define NAMLEN(dirent) (dirent)->d_namlen
  355. # endif
  356. # ifdef HAVE_SYS_NDIR_H
  357. # include <sys/ndir.h>
  358. # endif
  359. # ifdef HAVE_SYS_DIR_H
  360. # include <sys/dir.h>
  361. # endif
  362. # ifdef HAVE_NDIR_H
  363. # include <ndir.h>
  364. # endif
  365. #endif
  366. #ifdef _MSC_VER
  367. # ifdef HAVE_DIRECT_H
  368. # include <direct.h>
  369. # endif
  370. # ifdef HAVE_IO_H
  371. # include <io.h>
  372. # endif
  373. # ifdef HAVE_PROCESS_H
  374. # include <process.h>
  375. # endif
  376. # include <malloc.h>
  377. #endif /* _MSC_VER */
  378. #ifndef MAXPATHLEN
  379. # if defined(PATH_MAX) && PATH_MAX > 1024
  380. # define MAXPATHLEN PATH_MAX
  381. # else
  382. # define MAXPATHLEN 1024
  383. # endif
  384. #endif /* MAXPATHLEN */
  385. #ifdef UNION_WAIT
  386. /* Emulate some macros on systems that have a union instead of macros */
  387. # ifndef WIFEXITED
  388. # define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
  389. # endif
  390. # ifndef WEXITSTATUS
  391. # define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
  392. # endif
  393. # ifndef WTERMSIG
  394. # define WTERMSIG(u_wait) ((u_wait).w_termsig)
  395. # endif
  396. # define WAIT_TYPE union wait
  397. # define WAIT_STATUS_INT(s) (s.w_status)
  398. #else
  399. /* !UNION_WAIT */
  400. # define WAIT_TYPE int
  401. # define WAIT_STATUS_INT(s) (s)
  402. #endif /* UNION_WAIT */
  403. /* Don't use the "_r" form if we don't need it (also, won't have a
  404. prototype for it, at least on Solaris -- maybe others as well?). */
  405. #if defined(HAVE_CTERMID_R)
  406. # define USE_CTERMID_R
  407. #endif
  408. /* choose the appropriate stat and fstat functions and return structs */
  409. #undef STAT
  410. #undef FSTAT
  411. #undef STRUCT_STAT
  412. #ifdef MS_WINDOWS
  413. # define STAT win32_stat
  414. # define LSTAT win32_lstat
  415. # define FSTAT _Py_fstat_noraise
  416. # define STRUCT_STAT struct _Py_stat_struct
  417. #else
  418. # define STAT stat
  419. # define LSTAT lstat
  420. # define FSTAT fstat
  421. # define STRUCT_STAT struct stat
  422. #endif
  423. #if defined(MAJOR_IN_MKDEV)
  424. # include <sys/mkdev.h>
  425. #else
  426. # if defined(MAJOR_IN_SYSMACROS)
  427. # include <sys/sysmacros.h>
  428. # endif
  429. # if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
  430. # include <sys/mkdev.h>
  431. # endif
  432. #endif
  433. #ifdef MS_WINDOWS
  434. # define INITFUNC PyInit_nt
  435. # define MODNAME "nt"
  436. # define MODNAME_OBJ &_Py_ID(nt)
  437. #else
  438. # define INITFUNC PyInit_posix
  439. # define MODNAME "posix"
  440. # define MODNAME_OBJ &_Py_ID(posix)
  441. #endif
  442. #if defined(__sun)
  443. /* Something to implement in autoconf, not present in autoconf 2.69 */
  444. # define HAVE_STRUCT_STAT_ST_FSTYPE 1
  445. #endif
  446. /* memfd_create is either defined in sys/mman.h or sys/memfd.h
  447. * linux/memfd.h defines additional flags
  448. */
  449. #ifdef HAVE_SYS_MMAN_H
  450. # include <sys/mman.h>
  451. #endif
  452. #ifdef HAVE_SYS_MEMFD_H
  453. # include <sys/memfd.h>
  454. #endif
  455. #ifdef HAVE_LINUX_MEMFD_H
  456. # include <linux/memfd.h>
  457. #endif
  458. /* eventfd() */
  459. #ifdef HAVE_SYS_EVENTFD_H
  460. # include <sys/eventfd.h>
  461. #endif
  462. #ifdef _Py_MEMORY_SANITIZER
  463. # include <sanitizer/msan_interface.h>
  464. #endif
  465. #ifdef HAVE_FORK
  466. static void
  467. run_at_forkers(PyObject *lst, int reverse)
  468. {
  469. Py_ssize_t i;
  470. PyObject *cpy;
  471. if (lst != NULL) {
  472. assert(PyList_CheckExact(lst));
  473. /* Use a list copy in case register_at_fork() is called from
  474. * one of the callbacks.
  475. */
  476. cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
  477. if (cpy == NULL)
  478. PyErr_WriteUnraisable(lst);
  479. else {
  480. if (reverse)
  481. PyList_Reverse(cpy);
  482. for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
  483. PyObject *func, *res;
  484. func = PyList_GET_ITEM(cpy, i);
  485. res = _PyObject_CallNoArgs(func);
  486. if (res == NULL)
  487. PyErr_WriteUnraisable(func);
  488. else
  489. Py_DECREF(res);
  490. }
  491. Py_DECREF(cpy);
  492. }
  493. }
  494. }
  495. void
  496. PyOS_BeforeFork(void)
  497. {
  498. PyInterpreterState *interp = _PyInterpreterState_GET();
  499. run_at_forkers(interp->before_forkers, 1);
  500. _PyImport_AcquireLock(interp);
  501. }
  502. void
  503. PyOS_AfterFork_Parent(void)
  504. {
  505. PyInterpreterState *interp = _PyInterpreterState_GET();
  506. if (_PyImport_ReleaseLock(interp) <= 0) {
  507. Py_FatalError("failed releasing import lock after fork");
  508. }
  509. run_at_forkers(interp->after_forkers_parent, 0);
  510. }
  511. void
  512. PyOS_AfterFork_Child(void)
  513. {
  514. PyStatus status;
  515. _PyRuntimeState *runtime = &_PyRuntime;
  516. status = _PyRuntimeState_ReInitThreads(runtime);
  517. if (_PyStatus_EXCEPTION(status)) {
  518. goto fatal_error;
  519. }
  520. PyThreadState *tstate = _PyThreadState_GET();
  521. _Py_EnsureTstateNotNULL(tstate);
  522. #ifdef PY_HAVE_THREAD_NATIVE_ID
  523. tstate->native_thread_id = PyThread_get_thread_native_id();
  524. #endif
  525. status = _PyEval_ReInitThreads(tstate);
  526. if (_PyStatus_EXCEPTION(status)) {
  527. goto fatal_error;
  528. }
  529. status = _PyImport_ReInitLock(tstate->interp);
  530. if (_PyStatus_EXCEPTION(status)) {
  531. goto fatal_error;
  532. }
  533. _PySignal_AfterFork();
  534. status = _PyInterpreterState_DeleteExceptMain(runtime);
  535. if (_PyStatus_EXCEPTION(status)) {
  536. goto fatal_error;
  537. }
  538. assert(_PyThreadState_GET() == tstate);
  539. status = _PyPerfTrampoline_AfterFork_Child();
  540. if (_PyStatus_EXCEPTION(status)) {
  541. goto fatal_error;
  542. }
  543. run_at_forkers(tstate->interp->after_forkers_child, 0);
  544. return;
  545. fatal_error:
  546. Py_ExitStatusException(status);
  547. }
  548. static int
  549. register_at_forker(PyObject **lst, PyObject *func)
  550. {
  551. if (func == NULL) /* nothing to register? do nothing. */
  552. return 0;
  553. if (*lst == NULL) {
  554. *lst = PyList_New(0);
  555. if (*lst == NULL)
  556. return -1;
  557. }
  558. return PyList_Append(*lst, func);
  559. }
  560. #endif /* HAVE_FORK */
  561. /* Legacy wrapper */
  562. void
  563. PyOS_AfterFork(void)
  564. {
  565. #ifdef HAVE_FORK
  566. PyOS_AfterFork_Child();
  567. #endif
  568. }
  569. #ifdef MS_WINDOWS
  570. /* defined in fileutils.c */
  571. void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
  572. void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *, ULONG,
  573. FILE_BASIC_INFO *, FILE_ID_INFO *,
  574. struct _Py_stat_struct *);
  575. void _Py_stat_basic_info_to_stat(FILE_STAT_BASIC_INFORMATION *,
  576. struct _Py_stat_struct *);
  577. #endif
  578. #ifndef MS_WINDOWS
  579. PyObject *
  580. _PyLong_FromUid(uid_t uid)
  581. {
  582. if (uid == (uid_t)-1)
  583. return PyLong_FromLong(-1);
  584. return PyLong_FromUnsignedLong(uid);
  585. }
  586. PyObject *
  587. _PyLong_FromGid(gid_t gid)
  588. {
  589. if (gid == (gid_t)-1)
  590. return PyLong_FromLong(-1);
  591. return PyLong_FromUnsignedLong(gid);
  592. }
  593. int
  594. _Py_Uid_Converter(PyObject *obj, uid_t *p)
  595. {
  596. uid_t uid;
  597. PyObject *index;
  598. int overflow;
  599. long result;
  600. unsigned long uresult;
  601. index = _PyNumber_Index(obj);
  602. if (index == NULL) {
  603. PyErr_Format(PyExc_TypeError,
  604. "uid should be integer, not %.200s",
  605. _PyType_Name(Py_TYPE(obj)));
  606. return 0;
  607. }
  608. /*
  609. * Handling uid_t is complicated for two reasons:
  610. * * Although uid_t is (always?) unsigned, it still
  611. * accepts -1.
  612. * * We don't know its size in advance--it may be
  613. * bigger than an int, or it may be smaller than
  614. * a long.
  615. *
  616. * So a bit of defensive programming is in order.
  617. * Start with interpreting the value passed
  618. * in as a signed long and see if it works.
  619. */
  620. result = PyLong_AsLongAndOverflow(index, &overflow);
  621. if (!overflow) {
  622. uid = (uid_t)result;
  623. if (result == -1) {
  624. if (PyErr_Occurred())
  625. goto fail;
  626. /* It's a legitimate -1, we're done. */
  627. goto success;
  628. }
  629. /* Any other negative number is disallowed. */
  630. if (result < 0)
  631. goto underflow;
  632. /* Ensure the value wasn't truncated. */
  633. if (sizeof(uid_t) < sizeof(long) &&
  634. (long)uid != result)
  635. goto underflow;
  636. goto success;
  637. }
  638. if (overflow < 0)
  639. goto underflow;
  640. /*
  641. * Okay, the value overflowed a signed long. If it
  642. * fits in an *unsigned* long, it may still be okay,
  643. * as uid_t may be unsigned long on this platform.
  644. */
  645. uresult = PyLong_AsUnsignedLong(index);
  646. if (PyErr_Occurred()) {
  647. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  648. goto overflow;
  649. goto fail;
  650. }
  651. uid = (uid_t)uresult;
  652. /*
  653. * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
  654. * but this value would get interpreted as (uid_t)-1 by chown
  655. * and its siblings. That's not what the user meant! So we
  656. * throw an overflow exception instead. (We already
  657. * handled a real -1 with PyLong_AsLongAndOverflow() above.)
  658. */
  659. if (uid == (uid_t)-1)
  660. goto overflow;
  661. /* Ensure the value wasn't truncated. */
  662. if (sizeof(uid_t) < sizeof(long) &&
  663. (unsigned long)uid != uresult)
  664. goto overflow;
  665. /* fallthrough */
  666. success:
  667. Py_DECREF(index);
  668. *p = uid;
  669. return 1;
  670. underflow:
  671. PyErr_SetString(PyExc_OverflowError,
  672. "uid is less than minimum");
  673. goto fail;
  674. overflow:
  675. PyErr_SetString(PyExc_OverflowError,
  676. "uid is greater than maximum");
  677. /* fallthrough */
  678. fail:
  679. Py_DECREF(index);
  680. return 0;
  681. }
  682. int
  683. _Py_Gid_Converter(PyObject *obj, gid_t *p)
  684. {
  685. gid_t gid;
  686. PyObject *index;
  687. int overflow;
  688. long result;
  689. unsigned long uresult;
  690. index = _PyNumber_Index(obj);
  691. if (index == NULL) {
  692. PyErr_Format(PyExc_TypeError,
  693. "gid should be integer, not %.200s",
  694. _PyType_Name(Py_TYPE(obj)));
  695. return 0;
  696. }
  697. /*
  698. * Handling gid_t is complicated for two reasons:
  699. * * Although gid_t is (always?) unsigned, it still
  700. * accepts -1.
  701. * * We don't know its size in advance--it may be
  702. * bigger than an int, or it may be smaller than
  703. * a long.
  704. *
  705. * So a bit of defensive programming is in order.
  706. * Start with interpreting the value passed
  707. * in as a signed long and see if it works.
  708. */
  709. result = PyLong_AsLongAndOverflow(index, &overflow);
  710. if (!overflow) {
  711. gid = (gid_t)result;
  712. if (result == -1) {
  713. if (PyErr_Occurred())
  714. goto fail;
  715. /* It's a legitimate -1, we're done. */
  716. goto success;
  717. }
  718. /* Any other negative number is disallowed. */
  719. if (result < 0) {
  720. goto underflow;
  721. }
  722. /* Ensure the value wasn't truncated. */
  723. if (sizeof(gid_t) < sizeof(long) &&
  724. (long)gid != result)
  725. goto underflow;
  726. goto success;
  727. }
  728. if (overflow < 0)
  729. goto underflow;
  730. /*
  731. * Okay, the value overflowed a signed long. If it
  732. * fits in an *unsigned* long, it may still be okay,
  733. * as gid_t may be unsigned long on this platform.
  734. */
  735. uresult = PyLong_AsUnsignedLong(index);
  736. if (PyErr_Occurred()) {
  737. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  738. goto overflow;
  739. goto fail;
  740. }
  741. gid = (gid_t)uresult;
  742. /*
  743. * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
  744. * but this value would get interpreted as (gid_t)-1 by chown
  745. * and its siblings. That's not what the user meant! So we
  746. * throw an overflow exception instead. (We already
  747. * handled a real -1 with PyLong_AsLongAndOverflow() above.)
  748. */
  749. if (gid == (gid_t)-1)
  750. goto overflow;
  751. /* Ensure the value wasn't truncated. */
  752. if (sizeof(gid_t) < sizeof(long) &&
  753. (unsigned long)gid != uresult)
  754. goto overflow;
  755. /* fallthrough */
  756. success:
  757. Py_DECREF(index);
  758. *p = gid;
  759. return 1;
  760. underflow:
  761. PyErr_SetString(PyExc_OverflowError,
  762. "gid is less than minimum");
  763. goto fail;
  764. overflow:
  765. PyErr_SetString(PyExc_OverflowError,
  766. "gid is greater than maximum");
  767. /* fallthrough */
  768. fail:
  769. Py_DECREF(index);
  770. return 0;
  771. }
  772. #endif /* MS_WINDOWS */
  773. #define _PyLong_FromDev PyLong_FromLongLong
  774. #if (defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)) || defined(HAVE_DEVICE_MACROS)
  775. static int
  776. _Py_Dev_Converter(PyObject *obj, void *p)
  777. {
  778. *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
  779. if (PyErr_Occurred())
  780. return 0;
  781. return 1;
  782. }
  783. #endif /* (HAVE_MKNOD && HAVE_MAKEDEV) || HAVE_DEVICE_MACROS */
  784. #ifdef AT_FDCWD
  785. /*
  786. * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
  787. * without the int cast, the value gets interpreted as uint (4291925331),
  788. * which doesn't play nicely with all the initializer lines in this file that
  789. * look like this:
  790. * int dir_fd = DEFAULT_DIR_FD;
  791. */
  792. #define DEFAULT_DIR_FD (int)AT_FDCWD
  793. #else
  794. #define DEFAULT_DIR_FD (-100)
  795. #endif
  796. static int
  797. _fd_converter(PyObject *o, int *p)
  798. {
  799. int overflow;
  800. long long_value;
  801. PyObject *index = _PyNumber_Index(o);
  802. if (index == NULL) {
  803. return 0;
  804. }
  805. assert(PyLong_Check(index));
  806. long_value = PyLong_AsLongAndOverflow(index, &overflow);
  807. Py_DECREF(index);
  808. assert(!PyErr_Occurred());
  809. if (overflow > 0 || long_value > INT_MAX) {
  810. PyErr_SetString(PyExc_OverflowError,
  811. "fd is greater than maximum");
  812. return 0;
  813. }
  814. if (overflow < 0 || long_value < INT_MIN) {
  815. PyErr_SetString(PyExc_OverflowError,
  816. "fd is less than minimum");
  817. return 0;
  818. }
  819. *p = (int)long_value;
  820. return 1;
  821. }
  822. static int
  823. dir_fd_converter(PyObject *o, void *p)
  824. {
  825. if (o == Py_None) {
  826. *(int *)p = DEFAULT_DIR_FD;
  827. return 1;
  828. }
  829. else if (PyIndex_Check(o)) {
  830. return _fd_converter(o, (int *)p);
  831. }
  832. else {
  833. PyErr_Format(PyExc_TypeError,
  834. "argument should be integer or None, not %.200s",
  835. _PyType_Name(Py_TYPE(o)));
  836. return 0;
  837. }
  838. }
  839. typedef struct {
  840. PyObject *billion;
  841. PyObject *DirEntryType;
  842. PyObject *ScandirIteratorType;
  843. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  844. PyObject *SchedParamType;
  845. #endif
  846. newfunc statresult_new_orig;
  847. PyObject *StatResultType;
  848. PyObject *StatVFSResultType;
  849. PyObject *TerminalSizeType;
  850. PyObject *TimesResultType;
  851. PyObject *UnameResultType;
  852. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  853. PyObject *WaitidResultType;
  854. #endif
  855. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  856. PyObject *struct_rusage;
  857. #endif
  858. PyObject *st_mode;
  859. } _posixstate;
  860. static inline _posixstate*
  861. get_posix_state(PyObject *module)
  862. {
  863. void *state = _PyModule_GetState(module);
  864. assert(state != NULL);
  865. return (_posixstate *)state;
  866. }
  867. /*
  868. * A PyArg_ParseTuple "converter" function
  869. * that handles filesystem paths in the manner
  870. * preferred by the os module.
  871. *
  872. * path_converter accepts (Unicode) strings and their
  873. * subclasses, and bytes and their subclasses. What
  874. * it does with the argument depends on the platform:
  875. *
  876. * * On Windows, if we get a (Unicode) string we
  877. * extract the wchar_t * and return it; if we get
  878. * bytes we decode to wchar_t * and return that.
  879. *
  880. * * On all other platforms, strings are encoded
  881. * to bytes using PyUnicode_FSConverter, then we
  882. * extract the char * from the bytes object and
  883. * return that.
  884. *
  885. * path_converter also optionally accepts signed
  886. * integers (representing open file descriptors) instead
  887. * of path strings.
  888. *
  889. * Input fields:
  890. * path.nullable
  891. * If nonzero, the path is permitted to be None.
  892. * path.allow_fd
  893. * If nonzero, the path is permitted to be a file handle
  894. * (a signed int) instead of a string.
  895. * path.function_name
  896. * If non-NULL, path_converter will use that as the name
  897. * of the function in error messages.
  898. * (If path.function_name is NULL it omits the function name.)
  899. * path.argument_name
  900. * If non-NULL, path_converter will use that as the name
  901. * of the parameter in error messages.
  902. * (If path.argument_name is NULL it uses "path".)
  903. *
  904. * Output fields:
  905. * path.wide
  906. * Points to the path if it was expressed as Unicode
  907. * and was not encoded. (Only used on Windows.)
  908. * path.narrow
  909. * Points to the path if it was expressed as bytes,
  910. * or it was Unicode and was encoded to bytes. (On Windows,
  911. * is a non-zero integer if the path was expressed as bytes.
  912. * The type is deliberately incompatible to prevent misuse.)
  913. * path.fd
  914. * Contains a file descriptor if path.accept_fd was true
  915. * and the caller provided a signed integer instead of any
  916. * sort of string.
  917. *
  918. * WARNING: if your "path" parameter is optional, and is
  919. * unspecified, path_converter will never get called.
  920. * So if you set allow_fd, you *MUST* initialize path.fd = -1
  921. * yourself!
  922. * path.length
  923. * The length of the path in characters, if specified as
  924. * a string.
  925. * path.object
  926. * The original object passed in (if get a PathLike object,
  927. * the result of PyOS_FSPath() is treated as the original object).
  928. * Own a reference to the object.
  929. * path.cleanup
  930. * For internal use only. May point to a temporary object.
  931. * (Pay no attention to the man behind the curtain.)
  932. *
  933. * At most one of path.wide or path.narrow will be non-NULL.
  934. * If path was None and path.nullable was set,
  935. * or if path was an integer and path.allow_fd was set,
  936. * both path.wide and path.narrow will be NULL
  937. * and path.length will be 0.
  938. *
  939. * path_converter takes care to not write to the path_t
  940. * unless it's successful. However it must reset the
  941. * "cleanup" field each time it's called.
  942. *
  943. * Use as follows:
  944. * path_t path;
  945. * memset(&path, 0, sizeof(path));
  946. * PyArg_ParseTuple(args, "O&", path_converter, &path);
  947. * // ... use values from path ...
  948. * path_cleanup(&path);
  949. *
  950. * (Note that if PyArg_Parse fails you don't need to call
  951. * path_cleanup(). However it is safe to do so.)
  952. */
  953. typedef struct {
  954. const char *function_name;
  955. const char *argument_name;
  956. int nullable;
  957. int allow_fd;
  958. const wchar_t *wide;
  959. #ifdef MS_WINDOWS
  960. BOOL narrow;
  961. #else
  962. const char *narrow;
  963. #endif
  964. int fd;
  965. Py_ssize_t length;
  966. PyObject *object;
  967. PyObject *cleanup;
  968. } path_t;
  969. #ifdef MS_WINDOWS
  970. #define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
  971. {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
  972. #else
  973. #define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
  974. {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
  975. #endif
  976. static void
  977. path_cleanup(path_t *path)
  978. {
  979. wchar_t *wide = (wchar_t *)path->wide;
  980. path->wide = NULL;
  981. PyMem_Free(wide);
  982. Py_CLEAR(path->object);
  983. Py_CLEAR(path->cleanup);
  984. }
  985. static int
  986. path_converter(PyObject *o, void *p)
  987. {
  988. path_t *path = (path_t *)p;
  989. PyObject *bytes = NULL;
  990. Py_ssize_t length = 0;
  991. int is_index, is_bytes, is_unicode;
  992. const char *narrow;
  993. #ifdef MS_WINDOWS
  994. PyObject *wo = NULL;
  995. wchar_t *wide = NULL;
  996. #endif
  997. #define FORMAT_EXCEPTION(exc, fmt) \
  998. PyErr_Format(exc, "%s%s" fmt, \
  999. path->function_name ? path->function_name : "", \
  1000. path->function_name ? ": " : "", \
  1001. path->argument_name ? path->argument_name : "path")
  1002. /* Py_CLEANUP_SUPPORTED support */
  1003. if (o == NULL) {
  1004. path_cleanup(path);
  1005. return 1;
  1006. }
  1007. /* Ensure it's always safe to call path_cleanup(). */
  1008. path->object = path->cleanup = NULL;
  1009. /* path->object owns a reference to the original object */
  1010. Py_INCREF(o);
  1011. if ((o == Py_None) && path->nullable) {
  1012. path->wide = NULL;
  1013. #ifdef MS_WINDOWS
  1014. path->narrow = FALSE;
  1015. #else
  1016. path->narrow = NULL;
  1017. #endif
  1018. path->fd = -1;
  1019. goto success_exit;
  1020. }
  1021. /* Only call this here so that we don't treat the return value of
  1022. os.fspath() as an fd or buffer. */
  1023. is_index = path->allow_fd && PyIndex_Check(o);
  1024. is_bytes = PyBytes_Check(o);
  1025. is_unicode = PyUnicode_Check(o);
  1026. if (!is_index && !is_unicode && !is_bytes) {
  1027. /* Inline PyOS_FSPath() for better error messages. */
  1028. PyObject *func, *res;
  1029. func = _PyObject_LookupSpecial(o, &_Py_ID(__fspath__));
  1030. if (NULL == func) {
  1031. goto error_format;
  1032. }
  1033. res = _PyObject_CallNoArgs(func);
  1034. Py_DECREF(func);
  1035. if (NULL == res) {
  1036. goto error_exit;
  1037. }
  1038. else if (PyUnicode_Check(res)) {
  1039. is_unicode = 1;
  1040. }
  1041. else if (PyBytes_Check(res)) {
  1042. is_bytes = 1;
  1043. }
  1044. else {
  1045. PyErr_Format(PyExc_TypeError,
  1046. "expected %.200s.__fspath__() to return str or bytes, "
  1047. "not %.200s", _PyType_Name(Py_TYPE(o)),
  1048. _PyType_Name(Py_TYPE(res)));
  1049. Py_DECREF(res);
  1050. goto error_exit;
  1051. }
  1052. /* still owns a reference to the original object */
  1053. Py_SETREF(o, res);
  1054. }
  1055. if (is_unicode) {
  1056. #ifdef MS_WINDOWS
  1057. wide = PyUnicode_AsWideCharString(o, &length);
  1058. if (!wide) {
  1059. goto error_exit;
  1060. }
  1061. if (length > 32767) {
  1062. FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
  1063. goto error_exit;
  1064. }
  1065. if (wcslen(wide) != length) {
  1066. FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
  1067. goto error_exit;
  1068. }
  1069. path->wide = wide;
  1070. path->narrow = FALSE;
  1071. path->fd = -1;
  1072. wide = NULL;
  1073. goto success_exit;
  1074. #else
  1075. if (!PyUnicode_FSConverter(o, &bytes)) {
  1076. goto error_exit;
  1077. }
  1078. #endif
  1079. }
  1080. else if (is_bytes) {
  1081. bytes = Py_NewRef(o);
  1082. }
  1083. else if (is_index) {
  1084. if (!_fd_converter(o, &path->fd)) {
  1085. goto error_exit;
  1086. }
  1087. path->wide = NULL;
  1088. #ifdef MS_WINDOWS
  1089. path->narrow = FALSE;
  1090. #else
  1091. path->narrow = NULL;
  1092. #endif
  1093. goto success_exit;
  1094. }
  1095. else {
  1096. error_format:
  1097. PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
  1098. path->function_name ? path->function_name : "",
  1099. path->function_name ? ": " : "",
  1100. path->argument_name ? path->argument_name : "path",
  1101. path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
  1102. "integer or None" :
  1103. path->allow_fd ? "string, bytes, os.PathLike or integer" :
  1104. path->nullable ? "string, bytes, os.PathLike or None" :
  1105. "string, bytes or os.PathLike",
  1106. _PyType_Name(Py_TYPE(o)));
  1107. goto error_exit;
  1108. }
  1109. length = PyBytes_GET_SIZE(bytes);
  1110. narrow = PyBytes_AS_STRING(bytes);
  1111. if ((size_t)length != strlen(narrow)) {
  1112. FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
  1113. goto error_exit;
  1114. }
  1115. #ifdef MS_WINDOWS
  1116. wo = PyUnicode_DecodeFSDefaultAndSize(
  1117. narrow,
  1118. length
  1119. );
  1120. if (!wo) {
  1121. goto error_exit;
  1122. }
  1123. wide = PyUnicode_AsWideCharString(wo, &length);
  1124. Py_DECREF(wo);
  1125. if (!wide) {
  1126. goto error_exit;
  1127. }
  1128. if (length > 32767) {
  1129. FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
  1130. goto error_exit;
  1131. }
  1132. if (wcslen(wide) != length) {
  1133. FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
  1134. goto error_exit;
  1135. }
  1136. path->wide = wide;
  1137. path->narrow = TRUE;
  1138. Py_DECREF(bytes);
  1139. wide = NULL;
  1140. #else
  1141. path->wide = NULL;
  1142. path->narrow = narrow;
  1143. if (bytes == o) {
  1144. /* Still a reference owned by path->object, don't have to
  1145. worry about path->narrow is used after free. */
  1146. Py_DECREF(bytes);
  1147. }
  1148. else {
  1149. path->cleanup = bytes;
  1150. }
  1151. #endif
  1152. path->fd = -1;
  1153. success_exit:
  1154. path->length = length;
  1155. path->object = o;
  1156. return Py_CLEANUP_SUPPORTED;
  1157. error_exit:
  1158. Py_XDECREF(o);
  1159. Py_XDECREF(bytes);
  1160. #ifdef MS_WINDOWS
  1161. PyMem_Free(wide);
  1162. #endif
  1163. return 0;
  1164. }
  1165. static void
  1166. argument_unavailable_error(const char *function_name, const char *argument_name)
  1167. {
  1168. PyErr_Format(PyExc_NotImplementedError,
  1169. "%s%s%s unavailable on this platform",
  1170. (function_name != NULL) ? function_name : "",
  1171. (function_name != NULL) ? ": ": "",
  1172. argument_name);
  1173. }
  1174. static int
  1175. dir_fd_unavailable(PyObject *o, void *p)
  1176. {
  1177. int dir_fd;
  1178. if (!dir_fd_converter(o, &dir_fd))
  1179. return 0;
  1180. if (dir_fd != DEFAULT_DIR_FD) {
  1181. argument_unavailable_error(NULL, "dir_fd");
  1182. return 0;
  1183. }
  1184. *(int *)p = dir_fd;
  1185. return 1;
  1186. }
  1187. static int
  1188. fd_specified(const char *function_name, int fd)
  1189. {
  1190. if (fd == -1)
  1191. return 0;
  1192. argument_unavailable_error(function_name, "fd");
  1193. return 1;
  1194. }
  1195. static int
  1196. follow_symlinks_specified(const char *function_name, int follow_symlinks)
  1197. {
  1198. if (follow_symlinks)
  1199. return 0;
  1200. argument_unavailable_error(function_name, "follow_symlinks");
  1201. return 1;
  1202. }
  1203. static int
  1204. path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
  1205. {
  1206. if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
  1207. #ifndef MS_WINDOWS
  1208. && !path->narrow
  1209. #endif
  1210. ) {
  1211. PyErr_Format(PyExc_ValueError,
  1212. "%s: can't specify dir_fd without matching path",
  1213. function_name);
  1214. return 1;
  1215. }
  1216. return 0;
  1217. }
  1218. static int
  1219. dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
  1220. {
  1221. if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
  1222. PyErr_Format(PyExc_ValueError,
  1223. "%s: can't specify both dir_fd and fd",
  1224. function_name);
  1225. return 1;
  1226. }
  1227. return 0;
  1228. }
  1229. static int
  1230. fd_and_follow_symlinks_invalid(const char *function_name, int fd,
  1231. int follow_symlinks)
  1232. {
  1233. if ((fd > 0) && (!follow_symlinks)) {
  1234. PyErr_Format(PyExc_ValueError,
  1235. "%s: cannot use fd and follow_symlinks together",
  1236. function_name);
  1237. return 1;
  1238. }
  1239. return 0;
  1240. }
  1241. static int
  1242. dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
  1243. int follow_symlinks)
  1244. {
  1245. if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
  1246. PyErr_Format(PyExc_ValueError,
  1247. "%s: cannot use dir_fd and follow_symlinks together",
  1248. function_name);
  1249. return 1;
  1250. }
  1251. return 0;
  1252. }
  1253. #ifdef MS_WINDOWS
  1254. typedef long long Py_off_t;
  1255. #else
  1256. typedef off_t Py_off_t;
  1257. #endif
  1258. static int
  1259. Py_off_t_converter(PyObject *arg, void *addr)
  1260. {
  1261. #ifdef HAVE_LARGEFILE_SUPPORT
  1262. *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
  1263. #else
  1264. *((Py_off_t *)addr) = PyLong_AsLong(arg);
  1265. #endif
  1266. if (PyErr_Occurred())
  1267. return 0;
  1268. return 1;
  1269. }
  1270. static PyObject *
  1271. PyLong_FromPy_off_t(Py_off_t offset)
  1272. {
  1273. #ifdef HAVE_LARGEFILE_SUPPORT
  1274. return PyLong_FromLongLong(offset);
  1275. #else
  1276. return PyLong_FromLong(offset);
  1277. #endif
  1278. }
  1279. #ifdef HAVE_SIGSET_T
  1280. /* Convert an iterable of integers to a sigset.
  1281. Return 1 on success, return 0 and raise an exception on error. */
  1282. int
  1283. _Py_Sigset_Converter(PyObject *obj, void *addr)
  1284. {
  1285. sigset_t *mask = (sigset_t *)addr;
  1286. PyObject *iterator, *item;
  1287. long signum;
  1288. int overflow;
  1289. // The extra parens suppress the unreachable-code warning with clang on MacOS
  1290. if (sigemptyset(mask) < (0)) {
  1291. /* Probably only if mask == NULL. */
  1292. PyErr_SetFromErrno(PyExc_OSError);
  1293. return 0;
  1294. }
  1295. iterator = PyObject_GetIter(obj);
  1296. if (iterator == NULL) {
  1297. return 0;
  1298. }
  1299. while ((item = PyIter_Next(iterator)) != NULL) {
  1300. signum = PyLong_AsLongAndOverflow(item, &overflow);
  1301. Py_DECREF(item);
  1302. if (signum <= 0 || signum >= Py_NSIG) {
  1303. if (overflow || signum != -1 || !PyErr_Occurred()) {
  1304. PyErr_Format(PyExc_ValueError,
  1305. "signal number %ld out of range [1; %i]",
  1306. signum, Py_NSIG - 1);
  1307. }
  1308. goto error;
  1309. }
  1310. if (sigaddset(mask, (int)signum)) {
  1311. if (errno != EINVAL) {
  1312. /* Probably impossible */
  1313. PyErr_SetFromErrno(PyExc_OSError);
  1314. goto error;
  1315. }
  1316. /* For backwards compatibility, allow idioms such as
  1317. * `range(1, NSIG)` but warn about invalid signal numbers
  1318. */
  1319. const char msg[] =
  1320. "invalid signal number %ld, please use valid_signals()";
  1321. if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
  1322. goto error;
  1323. }
  1324. }
  1325. }
  1326. if (!PyErr_Occurred()) {
  1327. Py_DECREF(iterator);
  1328. return 1;
  1329. }
  1330. error:
  1331. Py_DECREF(iterator);
  1332. return 0;
  1333. }
  1334. #endif /* HAVE_SIGSET_T */
  1335. /* Return a dictionary corresponding to the POSIX environment table */
  1336. #if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
  1337. /* On Darwin/MacOSX a shared library or framework has no access to
  1338. ** environ directly, we must obtain it with _NSGetEnviron(). See also
  1339. ** man environ(7).
  1340. */
  1341. #include <crt_externs.h>
  1342. #elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
  1343. extern char **environ;
  1344. #endif /* !_MSC_VER */
  1345. static PyObject *
  1346. convertenviron(void)
  1347. {
  1348. PyObject *d;
  1349. #ifdef MS_WINDOWS
  1350. wchar_t **e;
  1351. #else
  1352. char **e;
  1353. #endif
  1354. d = PyDict_New();
  1355. if (d == NULL)
  1356. return NULL;
  1357. #ifdef MS_WINDOWS
  1358. /* _wenviron must be initialized in this way if the program is started
  1359. through main() instead of wmain(). */
  1360. (void)_wgetenv(L"");
  1361. e = _wenviron;
  1362. #elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
  1363. /* environ is not accessible as an extern in a shared object on OSX; use
  1364. _NSGetEnviron to resolve it. The value changes if you add environment
  1365. variables between calls to Py_Initialize, so don't cache the value. */
  1366. e = *_NSGetEnviron();
  1367. #else
  1368. e = environ;
  1369. #endif
  1370. if (e == NULL)
  1371. return d;
  1372. for (; *e != NULL; e++) {
  1373. PyObject *k;
  1374. PyObject *v;
  1375. #ifdef MS_WINDOWS
  1376. const wchar_t *p = wcschr(*e, L'=');
  1377. #else
  1378. const char *p = strchr(*e, '=');
  1379. #endif
  1380. if (p == NULL)
  1381. continue;
  1382. #ifdef MS_WINDOWS
  1383. k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
  1384. #else
  1385. k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
  1386. #endif
  1387. if (k == NULL) {
  1388. Py_DECREF(d);
  1389. return NULL;
  1390. }
  1391. #ifdef MS_WINDOWS
  1392. v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
  1393. #else
  1394. v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
  1395. #endif
  1396. if (v == NULL) {
  1397. Py_DECREF(k);
  1398. Py_DECREF(d);
  1399. return NULL;
  1400. }
  1401. if (PyDict_SetDefault(d, k, v) == NULL) {
  1402. Py_DECREF(v);
  1403. Py_DECREF(k);
  1404. Py_DECREF(d);
  1405. return NULL;
  1406. }
  1407. Py_DECREF(k);
  1408. Py_DECREF(v);
  1409. }
  1410. return d;
  1411. }
  1412. /* Set a POSIX-specific error from errno, and return NULL */
  1413. static PyObject *
  1414. posix_error(void)
  1415. {
  1416. return PyErr_SetFromErrno(PyExc_OSError);
  1417. }
  1418. #ifdef MS_WINDOWS
  1419. static PyObject *
  1420. win32_error(const char* function, const char* filename)
  1421. {
  1422. /* XXX We should pass the function name along in the future.
  1423. (winreg.c also wants to pass the function name.)
  1424. This would however require an additional param to the
  1425. Windows error object, which is non-trivial.
  1426. */
  1427. errno = GetLastError();
  1428. if (filename)
  1429. return PyErr_SetFromWindowsErrWithFilename(errno, filename);
  1430. else
  1431. return PyErr_SetFromWindowsErr(errno);
  1432. }
  1433. static PyObject *
  1434. win32_error_object_err(const char* function, PyObject* filename, DWORD err)
  1435. {
  1436. /* XXX - see win32_error for comments on 'function' */
  1437. if (filename)
  1438. return PyErr_SetExcFromWindowsErrWithFilenameObject(
  1439. PyExc_OSError,
  1440. err,
  1441. filename);
  1442. else
  1443. return PyErr_SetFromWindowsErr(err);
  1444. }
  1445. static PyObject *
  1446. win32_error_object(const char* function, PyObject* filename)
  1447. {
  1448. errno = GetLastError();
  1449. return win32_error_object_err(function, filename, errno);
  1450. }
  1451. #endif /* MS_WINDOWS */
  1452. static PyObject *
  1453. posix_path_object_error(PyObject *path)
  1454. {
  1455. return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
  1456. }
  1457. static PyObject *
  1458. path_object_error(PyObject *path)
  1459. {
  1460. #ifdef MS_WINDOWS
  1461. return PyErr_SetExcFromWindowsErrWithFilenameObject(
  1462. PyExc_OSError, 0, path);
  1463. #else
  1464. return posix_path_object_error(path);
  1465. #endif
  1466. }
  1467. static PyObject *
  1468. path_object_error2(PyObject *path, PyObject *path2)
  1469. {
  1470. #ifdef MS_WINDOWS
  1471. return PyErr_SetExcFromWindowsErrWithFilenameObjects(
  1472. PyExc_OSError, 0, path, path2);
  1473. #else
  1474. return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
  1475. #endif
  1476. }
  1477. static PyObject *
  1478. path_error(path_t *path)
  1479. {
  1480. return path_object_error(path->object);
  1481. }
  1482. static PyObject *
  1483. posix_path_error(path_t *path)
  1484. {
  1485. return posix_path_object_error(path->object);
  1486. }
  1487. static PyObject *
  1488. path_error2(path_t *path, path_t *path2)
  1489. {
  1490. return path_object_error2(path->object, path2->object);
  1491. }
  1492. /* POSIX generic methods */
  1493. static PyObject *
  1494. posix_fildes_fd(int fd, int (*func)(int))
  1495. {
  1496. int res;
  1497. int async_err = 0;
  1498. do {
  1499. Py_BEGIN_ALLOW_THREADS
  1500. _Py_BEGIN_SUPPRESS_IPH
  1501. res = (*func)(fd);
  1502. _Py_END_SUPPRESS_IPH
  1503. Py_END_ALLOW_THREADS
  1504. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1505. if (res != 0)
  1506. return (!async_err) ? posix_error() : NULL;
  1507. Py_RETURN_NONE;
  1508. }
  1509. #ifdef MS_WINDOWS
  1510. /* This is a reimplementation of the C library's chdir function,
  1511. but one that produces Win32 errors instead of DOS error codes.
  1512. chdir is essentially a wrapper around SetCurrentDirectory; however,
  1513. it also needs to set "magic" environment variables indicating
  1514. the per-drive current directory, which are of the form =<drive>: */
  1515. static BOOL __stdcall
  1516. win32_wchdir(LPCWSTR path)
  1517. {
  1518. wchar_t path_buf[MAX_PATH], *new_path = path_buf;
  1519. int result;
  1520. wchar_t env[4] = L"=x:";
  1521. if(!SetCurrentDirectoryW(path))
  1522. return FALSE;
  1523. result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
  1524. if (!result)
  1525. return FALSE;
  1526. if (result > Py_ARRAY_LENGTH(path_buf)) {
  1527. new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
  1528. if (!new_path) {
  1529. SetLastError(ERROR_OUTOFMEMORY);
  1530. return FALSE;
  1531. }
  1532. result = GetCurrentDirectoryW(result, new_path);
  1533. if (!result) {
  1534. PyMem_RawFree(new_path);
  1535. return FALSE;
  1536. }
  1537. }
  1538. int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
  1539. wcsncmp(new_path, L"//", 2) == 0);
  1540. if (!is_unc_like_path) {
  1541. env[1] = new_path[0];
  1542. result = SetEnvironmentVariableW(env, new_path);
  1543. }
  1544. if (new_path != path_buf)
  1545. PyMem_RawFree(new_path);
  1546. return result ? TRUE : FALSE;
  1547. }
  1548. #endif
  1549. #ifdef MS_WINDOWS
  1550. /* The CRT of Windows has a number of flaws wrt. its stat() implementation:
  1551. - time stamps are restricted to second resolution
  1552. - file modification times suffer from forth-and-back conversions between
  1553. UTC and local time
  1554. Therefore, we implement our own stat, based on the Win32 API directly.
  1555. */
  1556. #define HAVE_STAT_NSEC 1
  1557. #define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
  1558. #define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
  1559. static void
  1560. find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
  1561. BY_HANDLE_FILE_INFORMATION *info,
  1562. ULONG *reparse_tag)
  1563. {
  1564. memset(info, 0, sizeof(*info));
  1565. info->dwFileAttributes = pFileData->dwFileAttributes;
  1566. info->ftCreationTime = pFileData->ftCreationTime;
  1567. info->ftLastAccessTime = pFileData->ftLastAccessTime;
  1568. info->ftLastWriteTime = pFileData->ftLastWriteTime;
  1569. info->nFileSizeHigh = pFileData->nFileSizeHigh;
  1570. info->nFileSizeLow = pFileData->nFileSizeLow;
  1571. /* info->nNumberOfLinks = 1; */
  1572. if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
  1573. *reparse_tag = pFileData->dwReserved0;
  1574. else
  1575. *reparse_tag = 0;
  1576. }
  1577. static BOOL
  1578. attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
  1579. {
  1580. HANDLE hFindFile;
  1581. WIN32_FIND_DATAW FileData;
  1582. LPCWSTR filename = pszFile;
  1583. size_t n = wcslen(pszFile);
  1584. if (n && (pszFile[n - 1] == L'\\' || pszFile[n - 1] == L'/')) {
  1585. // cannot use PyMem_Malloc here because we do not hold the GIL
  1586. filename = (LPCWSTR)malloc((n + 1) * sizeof(filename[0]));
  1587. if(!filename) {
  1588. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1589. return FALSE;
  1590. }
  1591. wcsncpy_s((LPWSTR)filename, n + 1, pszFile, n);
  1592. while (--n > 0 && (filename[n] == L'\\' || filename[n] == L'/')) {
  1593. ((LPWSTR)filename)[n] = L'\0';
  1594. }
  1595. if (!n || (n == 1 && filename[1] == L':')) {
  1596. // Nothing left to query
  1597. free((void *)filename);
  1598. return FALSE;
  1599. }
  1600. }
  1601. hFindFile = FindFirstFileW(filename, &FileData);
  1602. if (pszFile != filename) {
  1603. free((void *)filename);
  1604. }
  1605. if (hFindFile == INVALID_HANDLE_VALUE) {
  1606. return FALSE;
  1607. }
  1608. FindClose(hFindFile);
  1609. find_data_to_file_info(&FileData, info, reparse_tag);
  1610. return TRUE;
  1611. }
  1612. static void
  1613. update_st_mode_from_path(const wchar_t *path, DWORD attr,
  1614. struct _Py_stat_struct *result)
  1615. {
  1616. if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) {
  1617. /* Fix the file execute permissions. This hack sets S_IEXEC if
  1618. the filename has an extension that is commonly used by files
  1619. that CreateProcessW can execute. A real implementation calls
  1620. GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
  1621. AccessCheck to check for generic read, write, and execute
  1622. access. */
  1623. const wchar_t *fileExtension = wcsrchr(path, '.');
  1624. if (fileExtension) {
  1625. if (_wcsicmp(fileExtension, L".exe") == 0 ||
  1626. _wcsicmp(fileExtension, L".bat") == 0 ||
  1627. _wcsicmp(fileExtension, L".cmd") == 0 ||
  1628. _wcsicmp(fileExtension, L".com") == 0) {
  1629. result->st_mode |= 0111;
  1630. }
  1631. }
  1632. }
  1633. }
  1634. static int
  1635. win32_xstat_slow_impl(const wchar_t *path, struct _Py_stat_struct *result,
  1636. BOOL traverse)
  1637. {
  1638. HANDLE hFile;
  1639. BY_HANDLE_FILE_INFORMATION fileInfo;
  1640. FILE_BASIC_INFO basicInfo;
  1641. FILE_BASIC_INFO *pBasicInfo = NULL;
  1642. FILE_ID_INFO idInfo;
  1643. FILE_ID_INFO *pIdInfo = NULL;
  1644. FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
  1645. DWORD fileType, error;
  1646. BOOL isUnhandledTag = FALSE;
  1647. int retval = 0;
  1648. DWORD access = FILE_READ_ATTRIBUTES;
  1649. DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
  1650. if (!traverse) {
  1651. flags |= FILE_FLAG_OPEN_REPARSE_POINT;
  1652. }
  1653. hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
  1654. if (hFile == INVALID_HANDLE_VALUE) {
  1655. /* Either the path doesn't exist, or the caller lacks access. */
  1656. error = GetLastError();
  1657. switch (error) {
  1658. case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
  1659. case ERROR_SHARING_VIOLATION: /* It's a paging file. */
  1660. /* Try reading the parent directory. */
  1661. if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
  1662. /* Cannot read the parent directory. */
  1663. switch (GetLastError()) {
  1664. case ERROR_FILE_NOT_FOUND: /* File cannot be found */
  1665. case ERROR_PATH_NOT_FOUND: /* File parent directory cannot be found */
  1666. case ERROR_NOT_READY: /* Drive exists but unavailable */
  1667. case ERROR_BAD_NET_NAME: /* Remote drive unavailable */
  1668. break;
  1669. /* Restore the error from CreateFileW(). */
  1670. default:
  1671. SetLastError(error);
  1672. }
  1673. return -1;
  1674. }
  1675. if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
  1676. if (traverse ||
  1677. !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
  1678. /* The stat call has to traverse but cannot, so fail. */
  1679. SetLastError(error);
  1680. return -1;
  1681. }
  1682. }
  1683. break;
  1684. case ERROR_INVALID_PARAMETER:
  1685. /* \\.\con requires read or write access. */
  1686. hFile = CreateFileW(path, access | GENERIC_READ,
  1687. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
  1688. OPEN_EXISTING, flags, NULL);
  1689. if (hFile == INVALID_HANDLE_VALUE) {
  1690. SetLastError(error);
  1691. return -1;
  1692. }
  1693. break;
  1694. case ERROR_CANT_ACCESS_FILE:
  1695. /* bpo37834: open unhandled reparse points if traverse fails. */
  1696. if (traverse) {
  1697. traverse = FALSE;
  1698. isUnhandledTag = TRUE;
  1699. hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
  1700. flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
  1701. }
  1702. if (hFile == INVALID_HANDLE_VALUE) {
  1703. SetLastError(error);
  1704. return -1;
  1705. }
  1706. break;
  1707. default:
  1708. return -1;
  1709. }
  1710. }
  1711. if (hFile != INVALID_HANDLE_VALUE) {
  1712. /* Handle types other than files on disk. */
  1713. fileType = GetFileType(hFile);
  1714. if (fileType != FILE_TYPE_DISK) {
  1715. if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
  1716. retval = -1;
  1717. goto cleanup;
  1718. }
  1719. DWORD fileAttributes = GetFileAttributesW(path);
  1720. memset(result, 0, sizeof(*result));
  1721. if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
  1722. fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  1723. /* \\.\pipe\ or \\.\mailslot\ */
  1724. result->st_mode = _S_IFDIR;
  1725. } else if (fileType == FILE_TYPE_CHAR) {
  1726. /* \\.\nul */
  1727. result->st_mode = _S_IFCHR;
  1728. } else if (fileType == FILE_TYPE_PIPE) {
  1729. /* \\.\pipe\spam */
  1730. result->st_mode = _S_IFIFO;
  1731. }
  1732. /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
  1733. goto cleanup;
  1734. }
  1735. /* Query the reparse tag, and traverse a non-link. */
  1736. if (!traverse) {
  1737. if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
  1738. &tagInfo, sizeof(tagInfo))) {
  1739. /* Allow devices that do not support FileAttributeTagInfo. */
  1740. switch (GetLastError()) {
  1741. case ERROR_INVALID_PARAMETER:
  1742. case ERROR_INVALID_FUNCTION:
  1743. case ERROR_NOT_SUPPORTED:
  1744. tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
  1745. tagInfo.ReparseTag = 0;
  1746. break;
  1747. default:
  1748. retval = -1;
  1749. goto cleanup;
  1750. }
  1751. } else if (tagInfo.FileAttributes &
  1752. FILE_ATTRIBUTE_REPARSE_POINT) {
  1753. if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
  1754. if (isUnhandledTag) {
  1755. /* Traversing previously failed for either this link
  1756. or its target. */
  1757. SetLastError(ERROR_CANT_ACCESS_FILE);
  1758. retval = -1;
  1759. goto cleanup;
  1760. }
  1761. /* Traverse a non-link, but not if traversing already failed
  1762. for an unhandled tag. */
  1763. } else if (!isUnhandledTag) {
  1764. CloseHandle(hFile);
  1765. return win32_xstat_slow_impl(path, result, TRUE);
  1766. }
  1767. }
  1768. }
  1769. if (!GetFileInformationByHandle(hFile, &fileInfo) ||
  1770. !GetFileInformationByHandleEx(hFile, FileBasicInfo,
  1771. &basicInfo, sizeof(basicInfo))) {
  1772. switch (GetLastError()) {
  1773. case ERROR_INVALID_PARAMETER:
  1774. case ERROR_INVALID_FUNCTION:
  1775. case ERROR_NOT_SUPPORTED:
  1776. /* Volumes and physical disks are block devices, e.g.
  1777. \\.\C: and \\.\PhysicalDrive0. */
  1778. memset(result, 0, sizeof(*result));
  1779. result->st_mode = 0x6000; /* S_IFBLK */
  1780. goto cleanup;
  1781. }
  1782. retval = -1;
  1783. goto cleanup;
  1784. }
  1785. /* Successfully got FileBasicInfo, so we'll pass it along */
  1786. pBasicInfo = &basicInfo;
  1787. if (GetFileInformationByHandleEx(hFile, FileIdInfo, &idInfo, sizeof(idInfo))) {
  1788. /* Successfully got FileIdInfo, so pass it along */
  1789. pIdInfo = &idInfo;
  1790. }
  1791. }
  1792. _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, pBasicInfo, pIdInfo, result);
  1793. update_st_mode_from_path(path, fileInfo.dwFileAttributes, result);
  1794. cleanup:
  1795. if (hFile != INVALID_HANDLE_VALUE) {
  1796. /* Preserve last error if we are failing */
  1797. error = retval ? GetLastError() : 0;
  1798. if (!CloseHandle(hFile)) {
  1799. retval = -1;
  1800. } else if (retval) {
  1801. /* Restore last error */
  1802. SetLastError(error);
  1803. }
  1804. }
  1805. return retval;
  1806. }
  1807. static int
  1808. win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
  1809. BOOL traverse)
  1810. {
  1811. FILE_STAT_BASIC_INFORMATION statInfo;
  1812. if (_Py_GetFileInformationByName(path, FileStatBasicByNameInfo,
  1813. &statInfo, sizeof(statInfo))) {
  1814. if (// Cannot use fast path for reparse points ...
  1815. !(statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
  1816. // ... unless it's a name surrogate (symlink) and we're not following
  1817. || (!traverse && IsReparseTagNameSurrogate(statInfo.ReparseTag))
  1818. ) {
  1819. _Py_stat_basic_info_to_stat(&statInfo, result);
  1820. update_st_mode_from_path(path, statInfo.FileAttributes, result);
  1821. return 0;
  1822. }
  1823. } else {
  1824. switch(GetLastError()) {
  1825. case ERROR_FILE_NOT_FOUND:
  1826. case ERROR_PATH_NOT_FOUND:
  1827. case ERROR_NOT_READY:
  1828. case ERROR_BAD_NET_NAME:
  1829. /* These errors aren't worth retrying with the slow path */
  1830. return -1;
  1831. case ERROR_NOT_SUPPORTED:
  1832. /* indicates the API couldn't be loaded */
  1833. break;
  1834. }
  1835. }
  1836. return win32_xstat_slow_impl(path, result, traverse);
  1837. }
  1838. static int
  1839. win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
  1840. {
  1841. /* Protocol violation: we explicitly clear errno, instead of
  1842. setting it to a POSIX error. Callers should use GetLastError. */
  1843. int code = win32_xstat_impl(path, result, traverse);
  1844. errno = 0;
  1845. /* ctime is only deprecated from 3.12, so we copy birthtime across */
  1846. result->st_ctime = result->st_birthtime;
  1847. result->st_ctime_nsec = result->st_birthtime_nsec;
  1848. return code;
  1849. }
  1850. /* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
  1851. In Posix, stat automatically traverses symlinks and returns the stat
  1852. structure for the target. In Windows, the equivalent GetFileAttributes by
  1853. default does not traverse symlinks and instead returns attributes for
  1854. the symlink.
  1855. Instead, we will open the file (which *does* traverse symlinks by default)
  1856. and GetFileInformationByHandle(). */
  1857. static int
  1858. win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
  1859. {
  1860. return win32_xstat(path, result, FALSE);
  1861. }
  1862. static int
  1863. win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
  1864. {
  1865. return win32_xstat(path, result, TRUE);
  1866. }
  1867. #endif /* MS_WINDOWS */
  1868. PyDoc_STRVAR(stat_result__doc__,
  1869. "stat_result: Result from stat, fstat, or lstat.\n\n\
  1870. This object may be accessed either as a tuple of\n\
  1871. (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
  1872. or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
  1873. \n\
  1874. Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
  1875. or st_flags, they are available as attributes only.\n\
  1876. \n\
  1877. See os.stat for more information.");
  1878. static PyStructSequence_Field stat_result_fields[] = {
  1879. {"st_mode", "protection bits"},
  1880. {"st_ino", "inode"},
  1881. {"st_dev", "device"},
  1882. {"st_nlink", "number of hard links"},
  1883. {"st_uid", "user ID of owner"},
  1884. {"st_gid", "group ID of owner"},
  1885. {"st_size", "total size, in bytes"},
  1886. /* The NULL is replaced with PyStructSequence_UnnamedField later. */
  1887. {NULL, "integer time of last access"},
  1888. {NULL, "integer time of last modification"},
  1889. {NULL, "integer time of last change"},
  1890. {"st_atime", "time of last access"},
  1891. {"st_mtime", "time of last modification"},
  1892. {"st_ctime", "time of last change"},
  1893. {"st_atime_ns", "time of last access in nanoseconds"},
  1894. {"st_mtime_ns", "time of last modification in nanoseconds"},
  1895. {"st_ctime_ns", "time of last change in nanoseconds"},
  1896. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1897. {"st_blksize", "blocksize for filesystem I/O"},
  1898. #endif
  1899. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1900. {"st_blocks", "number of blocks allocated"},
  1901. #endif
  1902. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1903. {"st_rdev", "device type (if inode device)"},
  1904. #endif
  1905. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1906. {"st_flags", "user defined flags for file"},
  1907. #endif
  1908. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1909. {"st_gen", "generation number"},
  1910. #endif
  1911. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) || defined(MS_WINDOWS)
  1912. {"st_birthtime", "time of creation"},
  1913. #endif
  1914. #ifdef MS_WINDOWS
  1915. {"st_birthtime_ns", "time of creation in nanoseconds"},
  1916. #endif
  1917. #ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
  1918. {"st_file_attributes", "Windows file attribute bits"},
  1919. #endif
  1920. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  1921. {"st_fstype", "Type of filesystem"},
  1922. #endif
  1923. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  1924. {"st_reparse_tag", "Windows reparse tag"},
  1925. #endif
  1926. {0}
  1927. };
  1928. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1929. #define ST_BLKSIZE_IDX 16
  1930. #else
  1931. #define ST_BLKSIZE_IDX 15
  1932. #endif
  1933. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1934. #define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
  1935. #else
  1936. #define ST_BLOCKS_IDX ST_BLKSIZE_IDX
  1937. #endif
  1938. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1939. #define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
  1940. #else
  1941. #define ST_RDEV_IDX ST_BLOCKS_IDX
  1942. #endif
  1943. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1944. #define ST_FLAGS_IDX (ST_RDEV_IDX+1)
  1945. #else
  1946. #define ST_FLAGS_IDX ST_RDEV_IDX
  1947. #endif
  1948. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1949. #define ST_GEN_IDX (ST_FLAGS_IDX+1)
  1950. #else
  1951. #define ST_GEN_IDX ST_FLAGS_IDX
  1952. #endif
  1953. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) || defined(MS_WINDOWS)
  1954. #define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
  1955. #else
  1956. #define ST_BIRTHTIME_IDX ST_GEN_IDX
  1957. #endif
  1958. #ifdef MS_WINDOWS
  1959. #define ST_BIRTHTIME_NS_IDX (ST_BIRTHTIME_IDX+1)
  1960. #else
  1961. #define ST_BIRTHTIME_NS_IDX ST_BIRTHTIME_IDX
  1962. #endif
  1963. #if defined(HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES) || defined(MS_WINDOWS)
  1964. #define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_NS_IDX+1)
  1965. #else
  1966. #define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_NS_IDX
  1967. #endif
  1968. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  1969. #define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
  1970. #else
  1971. #define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
  1972. #endif
  1973. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  1974. #define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
  1975. #else
  1976. #define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
  1977. #endif
  1978. static PyStructSequence_Desc stat_result_desc = {
  1979. "stat_result", /* name */
  1980. stat_result__doc__, /* doc */
  1981. stat_result_fields,
  1982. 10
  1983. };
  1984. PyDoc_STRVAR(statvfs_result__doc__,
  1985. "statvfs_result: Result from statvfs or fstatvfs.\n\n\
  1986. This object may be accessed either as a tuple of\n\
  1987. (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
  1988. or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
  1989. \n\
  1990. See os.statvfs for more information.");
  1991. static PyStructSequence_Field statvfs_result_fields[] = {
  1992. {"f_bsize", },
  1993. {"f_frsize", },
  1994. {"f_blocks", },
  1995. {"f_bfree", },
  1996. {"f_bavail", },
  1997. {"f_files", },
  1998. {"f_ffree", },
  1999. {"f_favail", },
  2000. {"f_flag", },
  2001. {"f_namemax",},
  2002. {"f_fsid", },
  2003. {0}
  2004. };
  2005. static PyStructSequence_Desc statvfs_result_desc = {
  2006. "statvfs_result", /* name */
  2007. statvfs_result__doc__, /* doc */
  2008. statvfs_result_fields,
  2009. 10
  2010. };
  2011. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2012. PyDoc_STRVAR(waitid_result__doc__,
  2013. "waitid_result: Result from waitid.\n\n\
  2014. This object may be accessed either as a tuple of\n\
  2015. (si_pid, si_uid, si_signo, si_status, si_code),\n\
  2016. or via the attributes si_pid, si_uid, and so on.\n\
  2017. \n\
  2018. See os.waitid for more information.");
  2019. static PyStructSequence_Field waitid_result_fields[] = {
  2020. {"si_pid", },
  2021. {"si_uid", },
  2022. {"si_signo", },
  2023. {"si_status", },
  2024. {"si_code", },
  2025. {0}
  2026. };
  2027. static PyStructSequence_Desc waitid_result_desc = {
  2028. "waitid_result", /* name */
  2029. waitid_result__doc__, /* doc */
  2030. waitid_result_fields,
  2031. 5
  2032. };
  2033. #endif
  2034. static PyObject *
  2035. statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2036. {
  2037. PyStructSequence *result;
  2038. int i;
  2039. // ht_module doesn't get set in PyStructSequence_NewType(),
  2040. // so we can't use PyType_GetModule().
  2041. PyObject *mod = PyImport_GetModule(MODNAME_OBJ);
  2042. if (mod == NULL) {
  2043. return NULL;
  2044. }
  2045. _posixstate *state = get_posix_state(mod);
  2046. Py_DECREF(mod);
  2047. if (state == NULL) {
  2048. return NULL;
  2049. }
  2050. #define structseq_new state->statresult_new_orig
  2051. result = (PyStructSequence*)structseq_new(type, args, kwds);
  2052. if (!result)
  2053. return NULL;
  2054. /* If we have been initialized from a tuple,
  2055. st_?time might be set to None. Initialize it
  2056. from the int slots. */
  2057. for (i = 7; i <= 9; i++) {
  2058. if (result->ob_item[i+3] == Py_None) {
  2059. Py_DECREF(Py_None);
  2060. result->ob_item[i+3] = Py_NewRef(result->ob_item[i]);
  2061. }
  2062. }
  2063. return (PyObject*)result;
  2064. }
  2065. static int
  2066. _posix_clear(PyObject *module)
  2067. {
  2068. _posixstate *state = get_posix_state(module);
  2069. Py_CLEAR(state->billion);
  2070. Py_CLEAR(state->DirEntryType);
  2071. Py_CLEAR(state->ScandirIteratorType);
  2072. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  2073. Py_CLEAR(state->SchedParamType);
  2074. #endif
  2075. Py_CLEAR(state->StatResultType);
  2076. Py_CLEAR(state->StatVFSResultType);
  2077. Py_CLEAR(state->TerminalSizeType);
  2078. Py_CLEAR(state->TimesResultType);
  2079. Py_CLEAR(state->UnameResultType);
  2080. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2081. Py_CLEAR(state->WaitidResultType);
  2082. #endif
  2083. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  2084. Py_CLEAR(state->struct_rusage);
  2085. #endif
  2086. Py_CLEAR(state->st_mode);
  2087. return 0;
  2088. }
  2089. static int
  2090. _posix_traverse(PyObject *module, visitproc visit, void *arg)
  2091. {
  2092. _posixstate *state = get_posix_state(module);
  2093. Py_VISIT(state->billion);
  2094. Py_VISIT(state->DirEntryType);
  2095. Py_VISIT(state->ScandirIteratorType);
  2096. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  2097. Py_VISIT(state->SchedParamType);
  2098. #endif
  2099. Py_VISIT(state->StatResultType);
  2100. Py_VISIT(state->StatVFSResultType);
  2101. Py_VISIT(state->TerminalSizeType);
  2102. Py_VISIT(state->TimesResultType);
  2103. Py_VISIT(state->UnameResultType);
  2104. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2105. Py_VISIT(state->WaitidResultType);
  2106. #endif
  2107. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  2108. Py_VISIT(state->struct_rusage);
  2109. #endif
  2110. Py_VISIT(state->st_mode);
  2111. return 0;
  2112. }
  2113. static void
  2114. _posix_free(void *module)
  2115. {
  2116. _posix_clear((PyObject *)module);
  2117. }
  2118. static int
  2119. fill_time(PyObject *module, PyObject *v, int s_index, int f_index, int ns_index, time_t sec, unsigned long nsec)
  2120. {
  2121. assert(!PyErr_Occurred());
  2122. int res = -1;
  2123. PyObject *s_in_ns = NULL;
  2124. PyObject *ns_total = NULL;
  2125. PyObject *float_s = NULL;
  2126. PyObject *s = _PyLong_FromTime_t(sec);
  2127. PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
  2128. if (!(s && ns_fractional)) {
  2129. goto exit;
  2130. }
  2131. s_in_ns = PyNumber_Multiply(s, get_posix_state(module)->billion);
  2132. if (!s_in_ns) {
  2133. goto exit;
  2134. }
  2135. ns_total = PyNumber_Add(s_in_ns, ns_fractional);
  2136. if (!ns_total)
  2137. goto exit;
  2138. float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
  2139. if (!float_s) {
  2140. goto exit;
  2141. }
  2142. if (s_index >= 0) {
  2143. PyStructSequence_SET_ITEM(v, s_index, s);
  2144. s = NULL;
  2145. }
  2146. if (f_index >= 0) {
  2147. PyStructSequence_SET_ITEM(v, f_index, float_s);
  2148. float_s = NULL;
  2149. }
  2150. if (ns_index >= 0) {
  2151. PyStructSequence_SET_ITEM(v, ns_index, ns_total);
  2152. ns_total = NULL;
  2153. }
  2154. assert(!PyErr_Occurred());
  2155. res = 0;
  2156. exit:
  2157. Py_XDECREF(s);
  2158. Py_XDECREF(ns_fractional);
  2159. Py_XDECREF(s_in_ns);
  2160. Py_XDECREF(ns_total);
  2161. Py_XDECREF(float_s);
  2162. return res;
  2163. }
  2164. #ifdef MS_WINDOWS
  2165. static PyObject*
  2166. _pystat_l128_from_l64_l64(uint64_t low, uint64_t high)
  2167. {
  2168. PyObject *o_low = PyLong_FromUnsignedLongLong(low);
  2169. if (!o_low || !high) {
  2170. return o_low;
  2171. }
  2172. PyObject *o_high = PyLong_FromUnsignedLongLong(high);
  2173. PyObject *l64 = o_high ? PyLong_FromLong(64) : NULL;
  2174. if (!l64) {
  2175. Py_XDECREF(o_high);
  2176. Py_DECREF(o_low);
  2177. return NULL;
  2178. }
  2179. Py_SETREF(o_high, PyNumber_Lshift(o_high, l64));
  2180. Py_DECREF(l64);
  2181. if (!o_high) {
  2182. Py_DECREF(o_low);
  2183. return NULL;
  2184. }
  2185. Py_SETREF(o_low, PyNumber_Add(o_low, o_high));
  2186. Py_DECREF(o_high);
  2187. return o_low;
  2188. }
  2189. #endif
  2190. /* pack a system stat C structure into the Python stat tuple
  2191. (used by posix_stat() and posix_fstat()) */
  2192. static PyObject*
  2193. _pystat_fromstructstat(PyObject *module, STRUCT_STAT *st)
  2194. {
  2195. assert(!PyErr_Occurred());
  2196. PyObject *StatResultType = get_posix_state(module)->StatResultType;
  2197. PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
  2198. if (v == NULL) {
  2199. return NULL;
  2200. }
  2201. #define SET_ITEM(pos, expr) \
  2202. do { \
  2203. PyObject *obj = (expr); \
  2204. if (obj == NULL) { \
  2205. goto error; \
  2206. } \
  2207. PyStructSequence_SET_ITEM(v, (pos), obj); \
  2208. } while (0)
  2209. SET_ITEM(0, PyLong_FromLong((long)st->st_mode));
  2210. #ifdef MS_WINDOWS
  2211. SET_ITEM(1, _pystat_l128_from_l64_l64(st->st_ino, st->st_ino_high));
  2212. SET_ITEM(2, PyLong_FromUnsignedLongLong(st->st_dev));
  2213. #else
  2214. static_assert(sizeof(unsigned long long) >= sizeof(st->st_ino),
  2215. "stat.st_ino is larger than unsigned long long");
  2216. SET_ITEM(1, PyLong_FromUnsignedLongLong(st->st_ino));
  2217. SET_ITEM(2, _PyLong_FromDev(st->st_dev));
  2218. #endif
  2219. SET_ITEM(3, PyLong_FromLong((long)st->st_nlink));
  2220. #if defined(MS_WINDOWS)
  2221. SET_ITEM(4, PyLong_FromLong(0));
  2222. SET_ITEM(5, PyLong_FromLong(0));
  2223. #else
  2224. SET_ITEM(4, _PyLong_FromUid(st->st_uid));
  2225. SET_ITEM(5, _PyLong_FromGid(st->st_gid));
  2226. #endif
  2227. static_assert(sizeof(long long) >= sizeof(st->st_size),
  2228. "stat.st_size is larger than long long");
  2229. SET_ITEM(6, PyLong_FromLongLong(st->st_size));
  2230. // Set st_atime, st_mtime and st_ctime
  2231. unsigned long ansec, mnsec, cnsec;
  2232. #if defined(HAVE_STAT_TV_NSEC)
  2233. ansec = st->st_atim.tv_nsec;
  2234. mnsec = st->st_mtim.tv_nsec;
  2235. cnsec = st->st_ctim.tv_nsec;
  2236. #elif defined(HAVE_STAT_TV_NSEC2)
  2237. ansec = st->st_atimespec.tv_nsec;
  2238. mnsec = st->st_mtimespec.tv_nsec;
  2239. cnsec = st->st_ctimespec.tv_nsec;
  2240. #elif defined(HAVE_STAT_NSEC)
  2241. ansec = st->st_atime_nsec;
  2242. mnsec = st->st_mtime_nsec;
  2243. cnsec = st->st_ctime_nsec;
  2244. #else
  2245. ansec = mnsec = cnsec = 0;
  2246. #endif
  2247. if (fill_time(module, v, 7, 10, 13, st->st_atime, ansec) < 0) {
  2248. goto error;
  2249. }
  2250. if (fill_time(module, v, 8, 11, 14, st->st_mtime, mnsec) < 0) {
  2251. goto error;
  2252. }
  2253. if (fill_time(module, v, 9, 12, 15, st->st_ctime, cnsec) < 0) {
  2254. goto error;
  2255. }
  2256. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  2257. SET_ITEM(ST_BLKSIZE_IDX, PyLong_FromLong((long)st->st_blksize));
  2258. #endif
  2259. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  2260. SET_ITEM(ST_BLOCKS_IDX, PyLong_FromLong((long)st->st_blocks));
  2261. #endif
  2262. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  2263. SET_ITEM(ST_RDEV_IDX, PyLong_FromLong((long)st->st_rdev));
  2264. #endif
  2265. #ifdef HAVE_STRUCT_STAT_ST_GEN
  2266. SET_ITEM(ST_GEN_IDX, PyLong_FromLong((long)st->st_gen));
  2267. #endif
  2268. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME)
  2269. {
  2270. unsigned long bsec, bnsec;
  2271. bsec = (long)st->st_birthtime;
  2272. #ifdef HAVE_STAT_TV_NSEC2
  2273. bnsec = st->st_birthtimespec.tv_nsec;
  2274. #else
  2275. bnsec = 0;
  2276. #endif
  2277. SET_ITEM(ST_BIRTHTIME_IDX, PyFloat_FromDouble(bsec + bnsec * 1e-9));
  2278. }
  2279. #elif defined(MS_WINDOWS)
  2280. if (fill_time(module, v, -1, ST_BIRTHTIME_IDX, ST_BIRTHTIME_NS_IDX,
  2281. st->st_birthtime, st->st_birthtime_nsec) < 0) {
  2282. goto error;
  2283. }
  2284. #endif
  2285. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  2286. SET_ITEM(ST_FLAGS_IDX, PyLong_FromLong((long)st->st_flags));
  2287. #endif
  2288. #ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
  2289. SET_ITEM(ST_FILE_ATTRIBUTES_IDX,
  2290. PyLong_FromUnsignedLong(st->st_file_attributes));
  2291. #endif
  2292. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  2293. SET_ITEM(ST_FSTYPE_IDX, PyUnicode_FromString(st->st_fstype));
  2294. #endif
  2295. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  2296. SET_ITEM(ST_REPARSE_TAG_IDX, PyLong_FromUnsignedLong(st->st_reparse_tag));
  2297. #endif
  2298. assert(!PyErr_Occurred());
  2299. return v;
  2300. error:
  2301. Py_DECREF(v);
  2302. return NULL;
  2303. #undef SET_ITEM
  2304. }
  2305. /* POSIX methods */
  2306. static PyObject *
  2307. posix_do_stat(PyObject *module, const char *function_name, path_t *path,
  2308. int dir_fd, int follow_symlinks)
  2309. {
  2310. STRUCT_STAT st;
  2311. int result;
  2312. #ifdef HAVE_FSTATAT
  2313. int fstatat_unavailable = 0;
  2314. #endif
  2315. #if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
  2316. if (follow_symlinks_specified(function_name, follow_symlinks))
  2317. return NULL;
  2318. #endif
  2319. if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
  2320. dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
  2321. fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
  2322. return NULL;
  2323. Py_BEGIN_ALLOW_THREADS
  2324. if (path->fd != -1)
  2325. result = FSTAT(path->fd, &st);
  2326. #ifdef MS_WINDOWS
  2327. else if (follow_symlinks)
  2328. result = win32_stat(path->wide, &st);
  2329. else
  2330. result = win32_lstat(path->wide, &st);
  2331. #else
  2332. else
  2333. #if defined(HAVE_LSTAT)
  2334. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  2335. result = LSTAT(path->narrow, &st);
  2336. else
  2337. #endif /* HAVE_LSTAT */
  2338. #ifdef HAVE_FSTATAT
  2339. if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
  2340. if (HAVE_FSTATAT_RUNTIME) {
  2341. result = fstatat(dir_fd, path->narrow, &st,
  2342. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  2343. } else {
  2344. fstatat_unavailable = 1;
  2345. }
  2346. } else
  2347. #endif /* HAVE_FSTATAT */
  2348. result = STAT(path->narrow, &st);
  2349. #endif /* MS_WINDOWS */
  2350. Py_END_ALLOW_THREADS
  2351. #ifdef HAVE_FSTATAT
  2352. if (fstatat_unavailable) {
  2353. argument_unavailable_error("stat", "dir_fd");
  2354. return NULL;
  2355. }
  2356. #endif
  2357. if (result != 0) {
  2358. return path_error(path);
  2359. }
  2360. return _pystat_fromstructstat(module, &st);
  2361. }
  2362. /*[python input]
  2363. for s in """
  2364. FACCESSAT
  2365. FCHMODAT
  2366. FCHOWNAT
  2367. FSTATAT
  2368. LINKAT
  2369. MKDIRAT
  2370. MKFIFOAT
  2371. MKNODAT
  2372. OPENAT
  2373. READLINKAT
  2374. SYMLINKAT
  2375. UNLINKAT
  2376. """.strip().split():
  2377. s = s.strip()
  2378. print("""
  2379. #ifdef HAVE_{s}
  2380. #define {s}_DIR_FD_CONVERTER dir_fd_converter
  2381. #else
  2382. #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
  2383. #endif
  2384. """.rstrip().format(s=s))
  2385. for s in """
  2386. FCHDIR
  2387. FCHMOD
  2388. FCHOWN
  2389. FDOPENDIR
  2390. FEXECVE
  2391. FPATHCONF
  2392. FSTATVFS
  2393. FTRUNCATE
  2394. """.strip().split():
  2395. s = s.strip()
  2396. print("""
  2397. #ifdef HAVE_{s}
  2398. #define PATH_HAVE_{s} 1
  2399. #else
  2400. #define PATH_HAVE_{s} 0
  2401. #endif
  2402. """.rstrip().format(s=s))
  2403. [python start generated code]*/
  2404. #ifdef HAVE_FACCESSAT
  2405. #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
  2406. #else
  2407. #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
  2408. #endif
  2409. #ifdef HAVE_FCHMODAT
  2410. #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
  2411. #else
  2412. #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
  2413. #endif
  2414. #ifdef HAVE_FCHOWNAT
  2415. #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
  2416. #else
  2417. #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
  2418. #endif
  2419. #ifdef HAVE_FSTATAT
  2420. #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
  2421. #else
  2422. #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
  2423. #endif
  2424. #ifdef HAVE_LINKAT
  2425. #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
  2426. #else
  2427. #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2428. #endif
  2429. #ifdef HAVE_MKDIRAT
  2430. #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
  2431. #else
  2432. #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
  2433. #endif
  2434. #ifdef HAVE_MKFIFOAT
  2435. #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
  2436. #else
  2437. #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
  2438. #endif
  2439. #ifdef HAVE_MKNODAT
  2440. #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
  2441. #else
  2442. #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
  2443. #endif
  2444. #ifdef HAVE_OPENAT
  2445. #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
  2446. #else
  2447. #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
  2448. #endif
  2449. #ifdef HAVE_READLINKAT
  2450. #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2451. #else
  2452. #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2453. #endif
  2454. #ifdef HAVE_SYMLINKAT
  2455. #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2456. #else
  2457. #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2458. #endif
  2459. #ifdef HAVE_UNLINKAT
  2460. #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2461. #else
  2462. #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2463. #endif
  2464. #ifdef HAVE_FCHDIR
  2465. #define PATH_HAVE_FCHDIR 1
  2466. #else
  2467. #define PATH_HAVE_FCHDIR 0
  2468. #endif
  2469. #ifdef HAVE_FCHMOD
  2470. #define PATH_HAVE_FCHMOD 1
  2471. #else
  2472. #define PATH_HAVE_FCHMOD 0
  2473. #endif
  2474. #ifdef HAVE_FCHOWN
  2475. #define PATH_HAVE_FCHOWN 1
  2476. #else
  2477. #define PATH_HAVE_FCHOWN 0
  2478. #endif
  2479. #ifdef HAVE_FDOPENDIR
  2480. #define PATH_HAVE_FDOPENDIR 1
  2481. #else
  2482. #define PATH_HAVE_FDOPENDIR 0
  2483. #endif
  2484. #ifdef HAVE_FEXECVE
  2485. #define PATH_HAVE_FEXECVE 1
  2486. #else
  2487. #define PATH_HAVE_FEXECVE 0
  2488. #endif
  2489. #ifdef HAVE_FPATHCONF
  2490. #define PATH_HAVE_FPATHCONF 1
  2491. #else
  2492. #define PATH_HAVE_FPATHCONF 0
  2493. #endif
  2494. #ifdef HAVE_FSTATVFS
  2495. #define PATH_HAVE_FSTATVFS 1
  2496. #else
  2497. #define PATH_HAVE_FSTATVFS 0
  2498. #endif
  2499. #ifdef HAVE_FTRUNCATE
  2500. #define PATH_HAVE_FTRUNCATE 1
  2501. #else
  2502. #define PATH_HAVE_FTRUNCATE 0
  2503. #endif
  2504. /*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
  2505. #ifdef MS_WINDOWS
  2506. #undef PATH_HAVE_FTRUNCATE
  2507. #define PATH_HAVE_FTRUNCATE 1
  2508. #endif
  2509. /*[python input]
  2510. class path_t_converter(CConverter):
  2511. type = "path_t"
  2512. impl_by_reference = True
  2513. parse_by_reference = True
  2514. converter = 'path_converter'
  2515. def converter_init(self, *, allow_fd=False, nullable=False):
  2516. # right now path_t doesn't support default values.
  2517. # to support a default value, you'll need to override initialize().
  2518. if self.default not in (unspecified, None):
  2519. fail("Can't specify a default to the path_t converter!")
  2520. if self.c_default not in (None, 'Py_None'):
  2521. raise RuntimeError("Can't specify a c_default to the path_t converter!")
  2522. self.nullable = nullable
  2523. self.allow_fd = allow_fd
  2524. def pre_render(self):
  2525. def strify(value):
  2526. if isinstance(value, str):
  2527. return value
  2528. return str(int(bool(value)))
  2529. # add self.py_name here when merging with posixmodule conversion
  2530. self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
  2531. self.function.name,
  2532. self.name,
  2533. strify(self.nullable),
  2534. strify(self.allow_fd),
  2535. )
  2536. def cleanup(self):
  2537. return "path_cleanup(&" + self.name + ");\n"
  2538. class dir_fd_converter(CConverter):
  2539. type = 'int'
  2540. def converter_init(self, requires=None):
  2541. if self.default in (unspecified, None):
  2542. self.c_default = 'DEFAULT_DIR_FD'
  2543. if isinstance(requires, str):
  2544. self.converter = requires.upper() + '_DIR_FD_CONVERTER'
  2545. else:
  2546. self.converter = 'dir_fd_converter'
  2547. class uid_t_converter(CConverter):
  2548. type = "uid_t"
  2549. converter = '_Py_Uid_Converter'
  2550. class gid_t_converter(CConverter):
  2551. type = "gid_t"
  2552. converter = '_Py_Gid_Converter'
  2553. class dev_t_converter(CConverter):
  2554. type = 'dev_t'
  2555. converter = '_Py_Dev_Converter'
  2556. class dev_t_return_converter(unsigned_long_return_converter):
  2557. type = 'dev_t'
  2558. conversion_fn = '_PyLong_FromDev'
  2559. unsigned_cast = '(dev_t)'
  2560. class FSConverter_converter(CConverter):
  2561. type = 'PyObject *'
  2562. converter = 'PyUnicode_FSConverter'
  2563. def converter_init(self):
  2564. if self.default is not unspecified:
  2565. fail("FSConverter_converter does not support default values")
  2566. self.c_default = 'NULL'
  2567. def cleanup(self):
  2568. return "Py_XDECREF(" + self.name + ");\n"
  2569. class pid_t_converter(CConverter):
  2570. type = 'pid_t'
  2571. format_unit = '" _Py_PARSE_PID "'
  2572. class idtype_t_converter(int_converter):
  2573. type = 'idtype_t'
  2574. class id_t_converter(CConverter):
  2575. type = 'id_t'
  2576. format_unit = '" _Py_PARSE_PID "'
  2577. class intptr_t_converter(CConverter):
  2578. type = 'intptr_t'
  2579. format_unit = '" _Py_PARSE_INTPTR "'
  2580. class Py_off_t_converter(CConverter):
  2581. type = 'Py_off_t'
  2582. converter = 'Py_off_t_converter'
  2583. class Py_off_t_return_converter(long_return_converter):
  2584. type = 'Py_off_t'
  2585. conversion_fn = 'PyLong_FromPy_off_t'
  2586. class path_confname_converter(CConverter):
  2587. type="int"
  2588. converter="conv_path_confname"
  2589. class confstr_confname_converter(path_confname_converter):
  2590. converter='conv_confstr_confname'
  2591. class sysconf_confname_converter(path_confname_converter):
  2592. converter="conv_sysconf_confname"
  2593. [python start generated code]*/
  2594. /*[python end generated code: output=da39a3ee5e6b4b0d input=3338733161aa7879]*/
  2595. /*[clinic input]
  2596. os.stat
  2597. path : path_t(allow_fd=True)
  2598. Path to be examined; can be string, bytes, a path-like object or
  2599. open-file-descriptor int.
  2600. *
  2601. dir_fd : dir_fd(requires='fstatat') = None
  2602. If not None, it should be a file descriptor open to a directory,
  2603. and path should be a relative string; path will then be relative to
  2604. that directory.
  2605. follow_symlinks: bool = True
  2606. If False, and the last element of the path is a symbolic link,
  2607. stat will examine the symbolic link itself instead of the file
  2608. the link points to.
  2609. Perform a stat system call on the given path.
  2610. dir_fd and follow_symlinks may not be implemented
  2611. on your platform. If they are unavailable, using them will raise a
  2612. NotImplementedError.
  2613. It's an error to use dir_fd or follow_symlinks when specifying path as
  2614. an open file descriptor.
  2615. [clinic start generated code]*/
  2616. static PyObject *
  2617. os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
  2618. /*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
  2619. {
  2620. return posix_do_stat(module, "stat", path, dir_fd, follow_symlinks);
  2621. }
  2622. /*[clinic input]
  2623. os.lstat
  2624. path : path_t
  2625. *
  2626. dir_fd : dir_fd(requires='fstatat') = None
  2627. Perform a stat system call on the given path, without following symbolic links.
  2628. Like stat(), but do not follow symbolic links.
  2629. Equivalent to stat(path, follow_symlinks=False).
  2630. [clinic start generated code]*/
  2631. static PyObject *
  2632. os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
  2633. /*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
  2634. {
  2635. int follow_symlinks = 0;
  2636. return posix_do_stat(module, "lstat", path, dir_fd, follow_symlinks);
  2637. }
  2638. /*[clinic input]
  2639. os.access -> bool
  2640. path: path_t
  2641. Path to be tested; can be string, bytes, or a path-like object.
  2642. mode: int
  2643. Operating-system mode bitfield. Can be F_OK to test existence,
  2644. or the inclusive-OR of R_OK, W_OK, and X_OK.
  2645. *
  2646. dir_fd : dir_fd(requires='faccessat') = None
  2647. If not None, it should be a file descriptor open to a directory,
  2648. and path should be relative; path will then be relative to that
  2649. directory.
  2650. effective_ids: bool = False
  2651. If True, access will use the effective uid/gid instead of
  2652. the real uid/gid.
  2653. follow_symlinks: bool = True
  2654. If False, and the last element of the path is a symbolic link,
  2655. access will examine the symbolic link itself instead of the file
  2656. the link points to.
  2657. Use the real uid/gid to test for access to a path.
  2658. {parameters}
  2659. dir_fd, effective_ids, and follow_symlinks may not be implemented
  2660. on your platform. If they are unavailable, using them will raise a
  2661. NotImplementedError.
  2662. Note that most operations will use the effective uid/gid, therefore this
  2663. routine can be used in a suid/sgid environment to test if the invoking user
  2664. has the specified access to the path.
  2665. [clinic start generated code]*/
  2666. static int
  2667. os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
  2668. int effective_ids, int follow_symlinks)
  2669. /*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
  2670. {
  2671. int return_value;
  2672. #ifdef MS_WINDOWS
  2673. DWORD attr;
  2674. #else
  2675. int result;
  2676. #endif
  2677. #ifdef HAVE_FACCESSAT
  2678. int faccessat_unavailable = 0;
  2679. #endif
  2680. #ifndef HAVE_FACCESSAT
  2681. if (follow_symlinks_specified("access", follow_symlinks))
  2682. return -1;
  2683. if (effective_ids) {
  2684. argument_unavailable_error("access", "effective_ids");
  2685. return -1;
  2686. }
  2687. #endif
  2688. #ifdef MS_WINDOWS
  2689. Py_BEGIN_ALLOW_THREADS
  2690. attr = GetFileAttributesW(path->wide);
  2691. Py_END_ALLOW_THREADS
  2692. /*
  2693. * Access is possible if
  2694. * * we didn't get a -1, and
  2695. * * write access wasn't requested,
  2696. * * or the file isn't read-only,
  2697. * * or it's a directory.
  2698. * (Directories cannot be read-only on Windows.)
  2699. */
  2700. return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
  2701. (!(mode & 2) ||
  2702. !(attr & FILE_ATTRIBUTE_READONLY) ||
  2703. (attr & FILE_ATTRIBUTE_DIRECTORY));
  2704. #else
  2705. Py_BEGIN_ALLOW_THREADS
  2706. #ifdef HAVE_FACCESSAT
  2707. if ((dir_fd != DEFAULT_DIR_FD) ||
  2708. effective_ids ||
  2709. !follow_symlinks) {
  2710. if (HAVE_FACCESSAT_RUNTIME) {
  2711. int flags = 0;
  2712. if (!follow_symlinks)
  2713. flags |= AT_SYMLINK_NOFOLLOW;
  2714. if (effective_ids)
  2715. flags |= AT_EACCESS;
  2716. result = faccessat(dir_fd, path->narrow, mode, flags);
  2717. } else {
  2718. faccessat_unavailable = 1;
  2719. }
  2720. }
  2721. else
  2722. #endif
  2723. result = access(path->narrow, mode);
  2724. Py_END_ALLOW_THREADS
  2725. #ifdef HAVE_FACCESSAT
  2726. if (faccessat_unavailable) {
  2727. if (dir_fd != DEFAULT_DIR_FD) {
  2728. argument_unavailable_error("access", "dir_fd");
  2729. return -1;
  2730. }
  2731. if (follow_symlinks_specified("access", follow_symlinks))
  2732. return -1;
  2733. if (effective_ids) {
  2734. argument_unavailable_error("access", "effective_ids");
  2735. return -1;
  2736. }
  2737. /* should be unreachable */
  2738. return -1;
  2739. }
  2740. #endif
  2741. return_value = !result;
  2742. #endif
  2743. return return_value;
  2744. }
  2745. #ifndef F_OK
  2746. #define F_OK 0
  2747. #endif
  2748. #ifndef R_OK
  2749. #define R_OK 4
  2750. #endif
  2751. #ifndef W_OK
  2752. #define W_OK 2
  2753. #endif
  2754. #ifndef X_OK
  2755. #define X_OK 1
  2756. #endif
  2757. #ifdef HAVE_TTYNAME
  2758. /*[clinic input]
  2759. os.ttyname
  2760. fd: int
  2761. Integer file descriptor handle.
  2762. /
  2763. Return the name of the terminal device connected to 'fd'.
  2764. [clinic start generated code]*/
  2765. static PyObject *
  2766. os_ttyname_impl(PyObject *module, int fd)
  2767. /*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
  2768. {
  2769. long size = sysconf(_SC_TTY_NAME_MAX);
  2770. if (size == -1) {
  2771. return posix_error();
  2772. }
  2773. char *buffer = (char *)PyMem_RawMalloc(size);
  2774. if (buffer == NULL) {
  2775. return PyErr_NoMemory();
  2776. }
  2777. int ret = ttyname_r(fd, buffer, size);
  2778. if (ret != 0) {
  2779. PyMem_RawFree(buffer);
  2780. errno = ret;
  2781. return posix_error();
  2782. }
  2783. PyObject *res = PyUnicode_DecodeFSDefault(buffer);
  2784. PyMem_RawFree(buffer);
  2785. return res;
  2786. }
  2787. #endif
  2788. #ifdef HAVE_CTERMID
  2789. /*[clinic input]
  2790. os.ctermid
  2791. Return the name of the controlling terminal for this process.
  2792. [clinic start generated code]*/
  2793. static PyObject *
  2794. os_ctermid_impl(PyObject *module)
  2795. /*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
  2796. {
  2797. char *ret;
  2798. char buffer[L_ctermid];
  2799. #ifdef USE_CTERMID_R
  2800. ret = ctermid_r(buffer);
  2801. #else
  2802. ret = ctermid(buffer);
  2803. #endif
  2804. if (ret == NULL)
  2805. return posix_error();
  2806. return PyUnicode_DecodeFSDefault(buffer);
  2807. }
  2808. #endif /* HAVE_CTERMID */
  2809. /*[clinic input]
  2810. os.chdir
  2811. path: path_t(allow_fd='PATH_HAVE_FCHDIR')
  2812. Change the current working directory to the specified path.
  2813. path may always be specified as a string.
  2814. On some platforms, path may also be specified as an open file descriptor.
  2815. If this functionality is unavailable, using it raises an exception.
  2816. [clinic start generated code]*/
  2817. static PyObject *
  2818. os_chdir_impl(PyObject *module, path_t *path)
  2819. /*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
  2820. {
  2821. int result;
  2822. if (PySys_Audit("os.chdir", "(O)", path->object) < 0) {
  2823. return NULL;
  2824. }
  2825. Py_BEGIN_ALLOW_THREADS
  2826. #ifdef MS_WINDOWS
  2827. /* on unix, success = 0, on windows, success = !0 */
  2828. result = !win32_wchdir(path->wide);
  2829. #else
  2830. #ifdef HAVE_FCHDIR
  2831. if (path->fd != -1)
  2832. result = fchdir(path->fd);
  2833. else
  2834. #endif
  2835. result = chdir(path->narrow);
  2836. #endif
  2837. Py_END_ALLOW_THREADS
  2838. if (result) {
  2839. return path_error(path);
  2840. }
  2841. Py_RETURN_NONE;
  2842. }
  2843. #ifdef HAVE_FCHDIR
  2844. /*[clinic input]
  2845. os.fchdir
  2846. fd: fildes
  2847. Change to the directory of the given file descriptor.
  2848. fd must be opened on a directory, not a file.
  2849. Equivalent to os.chdir(fd).
  2850. [clinic start generated code]*/
  2851. static PyObject *
  2852. os_fchdir_impl(PyObject *module, int fd)
  2853. /*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
  2854. {
  2855. if (PySys_Audit("os.chdir", "(i)", fd) < 0) {
  2856. return NULL;
  2857. }
  2858. return posix_fildes_fd(fd, fchdir);
  2859. }
  2860. #endif /* HAVE_FCHDIR */
  2861. /*[clinic input]
  2862. os.chmod
  2863. path: path_t(allow_fd='PATH_HAVE_FCHMOD')
  2864. Path to be modified. May always be specified as a str, bytes, or a path-like object.
  2865. On some platforms, path may also be specified as an open file descriptor.
  2866. If this functionality is unavailable, using it raises an exception.
  2867. mode: int
  2868. Operating-system mode bitfield.
  2869. Be careful when using number literals for *mode*. The conventional UNIX notation for
  2870. numeric modes uses an octal base, which needs to be indicated with a ``0o`` prefix in
  2871. Python.
  2872. *
  2873. dir_fd : dir_fd(requires='fchmodat') = None
  2874. If not None, it should be a file descriptor open to a directory,
  2875. and path should be relative; path will then be relative to that
  2876. directory.
  2877. follow_symlinks: bool = True
  2878. If False, and the last element of the path is a symbolic link,
  2879. chmod will modify the symbolic link itself instead of the file
  2880. the link points to.
  2881. Change the access permissions of a file.
  2882. It is an error to use dir_fd or follow_symlinks when specifying path as
  2883. an open file descriptor.
  2884. dir_fd and follow_symlinks may not be implemented on your platform.
  2885. If they are unavailable, using them will raise a NotImplementedError.
  2886. [clinic start generated code]*/
  2887. static PyObject *
  2888. os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
  2889. int follow_symlinks)
  2890. /*[clinic end generated code: output=5cf6a94915cc7bff input=674a14bc998de09d]*/
  2891. {
  2892. int result;
  2893. #ifdef MS_WINDOWS
  2894. DWORD attr;
  2895. #endif
  2896. #ifdef HAVE_FCHMODAT
  2897. int fchmodat_nofollow_unsupported = 0;
  2898. int fchmodat_unsupported = 0;
  2899. #endif
  2900. #if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
  2901. if (follow_symlinks_specified("chmod", follow_symlinks))
  2902. return NULL;
  2903. #endif
  2904. if (PySys_Audit("os.chmod", "Oii", path->object, mode,
  2905. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  2906. return NULL;
  2907. }
  2908. #ifdef MS_WINDOWS
  2909. Py_BEGIN_ALLOW_THREADS
  2910. attr = GetFileAttributesW(path->wide);
  2911. if (attr == INVALID_FILE_ATTRIBUTES)
  2912. result = 0;
  2913. else {
  2914. if (mode & _S_IWRITE)
  2915. attr &= ~FILE_ATTRIBUTE_READONLY;
  2916. else
  2917. attr |= FILE_ATTRIBUTE_READONLY;
  2918. result = SetFileAttributesW(path->wide, attr);
  2919. }
  2920. Py_END_ALLOW_THREADS
  2921. if (!result) {
  2922. return path_error(path);
  2923. }
  2924. #else /* MS_WINDOWS */
  2925. Py_BEGIN_ALLOW_THREADS
  2926. #ifdef HAVE_FCHMOD
  2927. if (path->fd != -1)
  2928. result = fchmod(path->fd, mode);
  2929. else
  2930. #endif /* HAVE_CHMOD */
  2931. #ifdef HAVE_LCHMOD
  2932. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  2933. result = lchmod(path->narrow, mode);
  2934. else
  2935. #endif /* HAVE_LCHMOD */
  2936. #ifdef HAVE_FCHMODAT
  2937. if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
  2938. if (HAVE_FCHMODAT_RUNTIME) {
  2939. /*
  2940. * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
  2941. * The documentation specifically shows how to use it,
  2942. * and then says it isn't implemented yet.
  2943. * (true on linux with glibc 2.15, and openindiana 3.x)
  2944. *
  2945. * Once it is supported, os.chmod will automatically
  2946. * support dir_fd and follow_symlinks=False. (Hopefully.)
  2947. * Until then, we need to be careful what exception we raise.
  2948. */
  2949. result = fchmodat(dir_fd, path->narrow, mode,
  2950. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  2951. /*
  2952. * But wait! We can't throw the exception without allowing threads,
  2953. * and we can't do that in this nested scope. (Macro trickery, sigh.)
  2954. */
  2955. fchmodat_nofollow_unsupported =
  2956. result &&
  2957. ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
  2958. !follow_symlinks;
  2959. } else {
  2960. fchmodat_unsupported = 1;
  2961. fchmodat_nofollow_unsupported = 1;
  2962. result = -1;
  2963. }
  2964. }
  2965. else
  2966. #endif /* HAVE_FHCMODAT */
  2967. {
  2968. #ifdef HAVE_CHMOD
  2969. result = chmod(path->narrow, mode);
  2970. #elif defined(__wasi__)
  2971. // WASI SDK 15.0 does not support chmod.
  2972. // Ignore missing syscall for now.
  2973. result = 0;
  2974. #else
  2975. result = -1;
  2976. errno = ENOSYS;
  2977. #endif
  2978. }
  2979. Py_END_ALLOW_THREADS
  2980. if (result) {
  2981. #ifdef HAVE_FCHMODAT
  2982. if (fchmodat_unsupported) {
  2983. if (dir_fd != DEFAULT_DIR_FD) {
  2984. argument_unavailable_error("chmod", "dir_fd");
  2985. return NULL;
  2986. }
  2987. }
  2988. if (fchmodat_nofollow_unsupported) {
  2989. if (dir_fd != DEFAULT_DIR_FD)
  2990. dir_fd_and_follow_symlinks_invalid("chmod",
  2991. dir_fd, follow_symlinks);
  2992. else
  2993. follow_symlinks_specified("chmod", follow_symlinks);
  2994. return NULL;
  2995. }
  2996. else
  2997. #endif /* HAVE_FCHMODAT */
  2998. return path_error(path);
  2999. }
  3000. #endif /* MS_WINDOWS */
  3001. Py_RETURN_NONE;
  3002. }
  3003. #ifdef HAVE_FCHMOD
  3004. /*[clinic input]
  3005. os.fchmod
  3006. fd: int
  3007. The file descriptor of the file to be modified.
  3008. mode: int
  3009. Operating-system mode bitfield.
  3010. Be careful when using number literals for *mode*. The conventional UNIX notation for
  3011. numeric modes uses an octal base, which needs to be indicated with a ``0o`` prefix in
  3012. Python.
  3013. Change the access permissions of the file given by file descriptor fd.
  3014. Equivalent to os.chmod(fd, mode).
  3015. [clinic start generated code]*/
  3016. static PyObject *
  3017. os_fchmod_impl(PyObject *module, int fd, int mode)
  3018. /*[clinic end generated code: output=afd9bc05b4e426b3 input=b5594618bbbc22df]*/
  3019. {
  3020. int res;
  3021. int async_err = 0;
  3022. if (PySys_Audit("os.chmod", "iii", fd, mode, -1) < 0) {
  3023. return NULL;
  3024. }
  3025. do {
  3026. Py_BEGIN_ALLOW_THREADS
  3027. res = fchmod(fd, mode);
  3028. Py_END_ALLOW_THREADS
  3029. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  3030. if (res != 0)
  3031. return (!async_err) ? posix_error() : NULL;
  3032. Py_RETURN_NONE;
  3033. }
  3034. #endif /* HAVE_FCHMOD */
  3035. #ifdef HAVE_LCHMOD
  3036. /*[clinic input]
  3037. os.lchmod
  3038. path: path_t
  3039. mode: int
  3040. Change the access permissions of a file, without following symbolic links.
  3041. If path is a symlink, this affects the link itself rather than the target.
  3042. Equivalent to chmod(path, mode, follow_symlinks=False)."
  3043. [clinic start generated code]*/
  3044. static PyObject *
  3045. os_lchmod_impl(PyObject *module, path_t *path, int mode)
  3046. /*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
  3047. {
  3048. int res;
  3049. if (PySys_Audit("os.chmod", "Oii", path->object, mode, -1) < 0) {
  3050. return NULL;
  3051. }
  3052. Py_BEGIN_ALLOW_THREADS
  3053. res = lchmod(path->narrow, mode);
  3054. Py_END_ALLOW_THREADS
  3055. if (res < 0) {
  3056. path_error(path);
  3057. return NULL;
  3058. }
  3059. Py_RETURN_NONE;
  3060. }
  3061. #endif /* HAVE_LCHMOD */
  3062. #ifdef HAVE_CHFLAGS
  3063. /*[clinic input]
  3064. os.chflags
  3065. path: path_t
  3066. flags: unsigned_long(bitwise=True)
  3067. follow_symlinks: bool=True
  3068. Set file flags.
  3069. If follow_symlinks is False, and the last element of the path is a symbolic
  3070. link, chflags will change flags on the symbolic link itself instead of the
  3071. file the link points to.
  3072. follow_symlinks may not be implemented on your platform. If it is
  3073. unavailable, using it will raise a NotImplementedError.
  3074. [clinic start generated code]*/
  3075. static PyObject *
  3076. os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
  3077. int follow_symlinks)
  3078. /*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
  3079. {
  3080. int result;
  3081. #ifndef HAVE_LCHFLAGS
  3082. if (follow_symlinks_specified("chflags", follow_symlinks))
  3083. return NULL;
  3084. #endif
  3085. if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
  3086. return NULL;
  3087. }
  3088. Py_BEGIN_ALLOW_THREADS
  3089. #ifdef HAVE_LCHFLAGS
  3090. if (!follow_symlinks)
  3091. result = lchflags(path->narrow, flags);
  3092. else
  3093. #endif
  3094. result = chflags(path->narrow, flags);
  3095. Py_END_ALLOW_THREADS
  3096. if (result)
  3097. return path_error(path);
  3098. Py_RETURN_NONE;
  3099. }
  3100. #endif /* HAVE_CHFLAGS */
  3101. #ifdef HAVE_LCHFLAGS
  3102. /*[clinic input]
  3103. os.lchflags
  3104. path: path_t
  3105. flags: unsigned_long(bitwise=True)
  3106. Set file flags.
  3107. This function will not follow symbolic links.
  3108. Equivalent to chflags(path, flags, follow_symlinks=False).
  3109. [clinic start generated code]*/
  3110. static PyObject *
  3111. os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
  3112. /*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
  3113. {
  3114. int res;
  3115. if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
  3116. return NULL;
  3117. }
  3118. Py_BEGIN_ALLOW_THREADS
  3119. res = lchflags(path->narrow, flags);
  3120. Py_END_ALLOW_THREADS
  3121. if (res < 0) {
  3122. return path_error(path);
  3123. }
  3124. Py_RETURN_NONE;
  3125. }
  3126. #endif /* HAVE_LCHFLAGS */
  3127. #ifdef HAVE_CHROOT
  3128. /*[clinic input]
  3129. os.chroot
  3130. path: path_t
  3131. Change root directory to path.
  3132. [clinic start generated code]*/
  3133. static PyObject *
  3134. os_chroot_impl(PyObject *module, path_t *path)
  3135. /*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
  3136. {
  3137. int res;
  3138. Py_BEGIN_ALLOW_THREADS
  3139. res = chroot(path->narrow);
  3140. Py_END_ALLOW_THREADS
  3141. if (res < 0)
  3142. return path_error(path);
  3143. Py_RETURN_NONE;
  3144. }
  3145. #endif /* HAVE_CHROOT */
  3146. #ifdef HAVE_FSYNC
  3147. /*[clinic input]
  3148. os.fsync
  3149. fd: fildes
  3150. Force write of fd to disk.
  3151. [clinic start generated code]*/
  3152. static PyObject *
  3153. os_fsync_impl(PyObject *module, int fd)
  3154. /*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
  3155. {
  3156. return posix_fildes_fd(fd, fsync);
  3157. }
  3158. #endif /* HAVE_FSYNC */
  3159. #ifdef HAVE_SYNC
  3160. /*[clinic input]
  3161. os.sync
  3162. Force write of everything to disk.
  3163. [clinic start generated code]*/
  3164. static PyObject *
  3165. os_sync_impl(PyObject *module)
  3166. /*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
  3167. {
  3168. Py_BEGIN_ALLOW_THREADS
  3169. sync();
  3170. Py_END_ALLOW_THREADS
  3171. Py_RETURN_NONE;
  3172. }
  3173. #endif /* HAVE_SYNC */
  3174. #ifdef HAVE_FDATASYNC
  3175. #ifdef __hpux
  3176. extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
  3177. #endif
  3178. /*[clinic input]
  3179. os.fdatasync
  3180. fd: fildes
  3181. Force write of fd to disk without forcing update of metadata.
  3182. [clinic start generated code]*/
  3183. static PyObject *
  3184. os_fdatasync_impl(PyObject *module, int fd)
  3185. /*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
  3186. {
  3187. return posix_fildes_fd(fd, fdatasync);
  3188. }
  3189. #endif /* HAVE_FDATASYNC */
  3190. #ifdef HAVE_CHOWN
  3191. /*[clinic input]
  3192. os.chown
  3193. path : path_t(allow_fd='PATH_HAVE_FCHOWN')
  3194. Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
  3195. uid: uid_t
  3196. gid: gid_t
  3197. *
  3198. dir_fd : dir_fd(requires='fchownat') = None
  3199. If not None, it should be a file descriptor open to a directory,
  3200. and path should be relative; path will then be relative to that
  3201. directory.
  3202. follow_symlinks: bool = True
  3203. If False, and the last element of the path is a symbolic link,
  3204. stat will examine the symbolic link itself instead of the file
  3205. the link points to.
  3206. Change the owner and group id of path to the numeric uid and gid.\
  3207. path may always be specified as a string.
  3208. On some platforms, path may also be specified as an open file descriptor.
  3209. If this functionality is unavailable, using it raises an exception.
  3210. If dir_fd is not None, it should be a file descriptor open to a directory,
  3211. and path should be relative; path will then be relative to that directory.
  3212. If follow_symlinks is False, and the last element of the path is a symbolic
  3213. link, chown will modify the symbolic link itself instead of the file the
  3214. link points to.
  3215. It is an error to use dir_fd or follow_symlinks when specifying path as
  3216. an open file descriptor.
  3217. dir_fd and follow_symlinks may not be implemented on your platform.
  3218. If they are unavailable, using them will raise a NotImplementedError.
  3219. [clinic start generated code]*/
  3220. static PyObject *
  3221. os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
  3222. int dir_fd, int follow_symlinks)
  3223. /*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
  3224. {
  3225. int result;
  3226. #if defined(HAVE_FCHOWNAT)
  3227. int fchownat_unsupported = 0;
  3228. #endif
  3229. #if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
  3230. if (follow_symlinks_specified("chown", follow_symlinks))
  3231. return NULL;
  3232. #endif
  3233. if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
  3234. fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
  3235. return NULL;
  3236. if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid,
  3237. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  3238. return NULL;
  3239. }
  3240. Py_BEGIN_ALLOW_THREADS
  3241. #ifdef HAVE_FCHOWN
  3242. if (path->fd != -1)
  3243. result = fchown(path->fd, uid, gid);
  3244. else
  3245. #endif
  3246. #ifdef HAVE_LCHOWN
  3247. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  3248. result = lchown(path->narrow, uid, gid);
  3249. else
  3250. #endif
  3251. #ifdef HAVE_FCHOWNAT
  3252. if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks)) {
  3253. if (HAVE_FCHOWNAT_RUNTIME) {
  3254. result = fchownat(dir_fd, path->narrow, uid, gid,
  3255. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  3256. } else {
  3257. fchownat_unsupported = 1;
  3258. }
  3259. } else
  3260. #endif
  3261. result = chown(path->narrow, uid, gid);
  3262. Py_END_ALLOW_THREADS
  3263. #ifdef HAVE_FCHOWNAT
  3264. if (fchownat_unsupported) {
  3265. /* This would be incorrect if the current platform
  3266. * doesn't support lchown.
  3267. */
  3268. argument_unavailable_error(NULL, "dir_fd");
  3269. return NULL;
  3270. }
  3271. #endif
  3272. if (result)
  3273. return path_error(path);
  3274. Py_RETURN_NONE;
  3275. }
  3276. #endif /* HAVE_CHOWN */
  3277. #ifdef HAVE_FCHOWN
  3278. /*[clinic input]
  3279. os.fchown
  3280. fd: int
  3281. uid: uid_t
  3282. gid: gid_t
  3283. Change the owner and group id of the file specified by file descriptor.
  3284. Equivalent to os.chown(fd, uid, gid).
  3285. [clinic start generated code]*/
  3286. static PyObject *
  3287. os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
  3288. /*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
  3289. {
  3290. int res;
  3291. int async_err = 0;
  3292. if (PySys_Audit("os.chown", "iIIi", fd, uid, gid, -1) < 0) {
  3293. return NULL;
  3294. }
  3295. do {
  3296. Py_BEGIN_ALLOW_THREADS
  3297. res = fchown(fd, uid, gid);
  3298. Py_END_ALLOW_THREADS
  3299. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  3300. if (res != 0)
  3301. return (!async_err) ? posix_error() : NULL;
  3302. Py_RETURN_NONE;
  3303. }
  3304. #endif /* HAVE_FCHOWN */
  3305. #ifdef HAVE_LCHOWN
  3306. /*[clinic input]
  3307. os.lchown
  3308. path : path_t
  3309. uid: uid_t
  3310. gid: gid_t
  3311. Change the owner and group id of path to the numeric uid and gid.
  3312. This function will not follow symbolic links.
  3313. Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
  3314. [clinic start generated code]*/
  3315. static PyObject *
  3316. os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
  3317. /*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
  3318. {
  3319. int res;
  3320. if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid, -1) < 0) {
  3321. return NULL;
  3322. }
  3323. Py_BEGIN_ALLOW_THREADS
  3324. res = lchown(path->narrow, uid, gid);
  3325. Py_END_ALLOW_THREADS
  3326. if (res < 0) {
  3327. return path_error(path);
  3328. }
  3329. Py_RETURN_NONE;
  3330. }
  3331. #endif /* HAVE_LCHOWN */
  3332. static PyObject *
  3333. posix_getcwd(int use_bytes)
  3334. {
  3335. #ifdef MS_WINDOWS
  3336. wchar_t wbuf[MAXPATHLEN];
  3337. wchar_t *wbuf2 = wbuf;
  3338. DWORD len;
  3339. Py_BEGIN_ALLOW_THREADS
  3340. len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
  3341. /* If the buffer is large enough, len does not include the
  3342. terminating \0. If the buffer is too small, len includes
  3343. the space needed for the terminator. */
  3344. if (len >= Py_ARRAY_LENGTH(wbuf)) {
  3345. if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  3346. wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
  3347. }
  3348. else {
  3349. wbuf2 = NULL;
  3350. }
  3351. if (wbuf2) {
  3352. len = GetCurrentDirectoryW(len, wbuf2);
  3353. }
  3354. }
  3355. Py_END_ALLOW_THREADS
  3356. if (!wbuf2) {
  3357. PyErr_NoMemory();
  3358. return NULL;
  3359. }
  3360. if (!len) {
  3361. PyErr_SetFromWindowsErr(0);
  3362. if (wbuf2 != wbuf)
  3363. PyMem_RawFree(wbuf2);
  3364. return NULL;
  3365. }
  3366. PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
  3367. if (wbuf2 != wbuf) {
  3368. PyMem_RawFree(wbuf2);
  3369. }
  3370. if (use_bytes) {
  3371. if (resobj == NULL) {
  3372. return NULL;
  3373. }
  3374. Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
  3375. }
  3376. return resobj;
  3377. #else
  3378. const size_t chunk = 1024;
  3379. char *buf = NULL;
  3380. char *cwd = NULL;
  3381. size_t buflen = 0;
  3382. Py_BEGIN_ALLOW_THREADS
  3383. do {
  3384. char *newbuf;
  3385. if (buflen <= PY_SSIZE_T_MAX - chunk) {
  3386. buflen += chunk;
  3387. newbuf = PyMem_RawRealloc(buf, buflen);
  3388. }
  3389. else {
  3390. newbuf = NULL;
  3391. }
  3392. if (newbuf == NULL) {
  3393. PyMem_RawFree(buf);
  3394. buf = NULL;
  3395. break;
  3396. }
  3397. buf = newbuf;
  3398. cwd = getcwd(buf, buflen);
  3399. } while (cwd == NULL && errno == ERANGE);
  3400. Py_END_ALLOW_THREADS
  3401. if (buf == NULL) {
  3402. return PyErr_NoMemory();
  3403. }
  3404. if (cwd == NULL) {
  3405. posix_error();
  3406. PyMem_RawFree(buf);
  3407. return NULL;
  3408. }
  3409. PyObject *obj;
  3410. if (use_bytes) {
  3411. obj = PyBytes_FromStringAndSize(buf, strlen(buf));
  3412. }
  3413. else {
  3414. obj = PyUnicode_DecodeFSDefault(buf);
  3415. }
  3416. PyMem_RawFree(buf);
  3417. return obj;
  3418. #endif /* !MS_WINDOWS */
  3419. }
  3420. /*[clinic input]
  3421. os.getcwd
  3422. Return a unicode string representing the current working directory.
  3423. [clinic start generated code]*/
  3424. static PyObject *
  3425. os_getcwd_impl(PyObject *module)
  3426. /*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
  3427. {
  3428. return posix_getcwd(0);
  3429. }
  3430. /*[clinic input]
  3431. os.getcwdb
  3432. Return a bytes string representing the current working directory.
  3433. [clinic start generated code]*/
  3434. static PyObject *
  3435. os_getcwdb_impl(PyObject *module)
  3436. /*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
  3437. {
  3438. return posix_getcwd(1);
  3439. }
  3440. #if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
  3441. #define HAVE_LINK 1
  3442. #endif
  3443. #ifdef HAVE_LINK
  3444. /*[clinic input]
  3445. os.link
  3446. src : path_t
  3447. dst : path_t
  3448. *
  3449. src_dir_fd : dir_fd = None
  3450. dst_dir_fd : dir_fd = None
  3451. follow_symlinks: bool = True
  3452. Create a hard link to a file.
  3453. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  3454. descriptor open to a directory, and the respective path string (src or dst)
  3455. should be relative; the path will then be relative to that directory.
  3456. If follow_symlinks is False, and the last element of src is a symbolic
  3457. link, link will create a link to the symbolic link itself instead of the
  3458. file the link points to.
  3459. src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
  3460. platform. If they are unavailable, using them will raise a
  3461. NotImplementedError.
  3462. [clinic start generated code]*/
  3463. static PyObject *
  3464. os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  3465. int dst_dir_fd, int follow_symlinks)
  3466. /*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
  3467. {
  3468. #ifdef MS_WINDOWS
  3469. BOOL result = FALSE;
  3470. #else
  3471. int result;
  3472. #endif
  3473. #if defined(HAVE_LINKAT)
  3474. int linkat_unavailable = 0;
  3475. #endif
  3476. #ifndef HAVE_LINKAT
  3477. if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
  3478. argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
  3479. return NULL;
  3480. }
  3481. #endif
  3482. #ifndef MS_WINDOWS
  3483. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  3484. PyErr_SetString(PyExc_NotImplementedError,
  3485. "link: src and dst must be the same type");
  3486. return NULL;
  3487. }
  3488. #endif
  3489. if (PySys_Audit("os.link", "OOii", src->object, dst->object,
  3490. src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
  3491. dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
  3492. return NULL;
  3493. }
  3494. #ifdef MS_WINDOWS
  3495. Py_BEGIN_ALLOW_THREADS
  3496. result = CreateHardLinkW(dst->wide, src->wide, NULL);
  3497. Py_END_ALLOW_THREADS
  3498. if (!result)
  3499. return path_error2(src, dst);
  3500. #else
  3501. Py_BEGIN_ALLOW_THREADS
  3502. #ifdef HAVE_LINKAT
  3503. if ((src_dir_fd != DEFAULT_DIR_FD) ||
  3504. (dst_dir_fd != DEFAULT_DIR_FD) ||
  3505. (!follow_symlinks)) {
  3506. if (HAVE_LINKAT_RUNTIME) {
  3507. result = linkat(src_dir_fd, src->narrow,
  3508. dst_dir_fd, dst->narrow,
  3509. follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
  3510. }
  3511. #ifdef __APPLE__
  3512. else {
  3513. if (src_dir_fd == DEFAULT_DIR_FD && dst_dir_fd == DEFAULT_DIR_FD) {
  3514. /* See issue 41355: This matches the behaviour of !HAVE_LINKAT */
  3515. result = link(src->narrow, dst->narrow);
  3516. } else {
  3517. linkat_unavailable = 1;
  3518. }
  3519. }
  3520. #endif
  3521. }
  3522. else
  3523. #endif /* HAVE_LINKAT */
  3524. result = link(src->narrow, dst->narrow);
  3525. Py_END_ALLOW_THREADS
  3526. #ifdef HAVE_LINKAT
  3527. if (linkat_unavailable) {
  3528. /* Either or both dir_fd arguments were specified */
  3529. if (src_dir_fd != DEFAULT_DIR_FD) {
  3530. argument_unavailable_error("link", "src_dir_fd");
  3531. } else {
  3532. argument_unavailable_error("link", "dst_dir_fd");
  3533. }
  3534. return NULL;
  3535. }
  3536. #endif
  3537. if (result)
  3538. return path_error2(src, dst);
  3539. #endif /* MS_WINDOWS */
  3540. Py_RETURN_NONE;
  3541. }
  3542. #endif
  3543. #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
  3544. static PyObject *
  3545. _listdir_windows_no_opendir(path_t *path, PyObject *list)
  3546. {
  3547. PyObject *v;
  3548. HANDLE hFindFile = INVALID_HANDLE_VALUE;
  3549. BOOL result;
  3550. wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
  3551. /* only claim to have space for MAX_PATH */
  3552. Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
  3553. wchar_t *wnamebuf = NULL;
  3554. WIN32_FIND_DATAW wFileData;
  3555. const wchar_t *po_wchars;
  3556. if (!path->wide) { /* Default arg: "." */
  3557. po_wchars = L".";
  3558. len = 1;
  3559. } else {
  3560. po_wchars = path->wide;
  3561. len = wcslen(path->wide);
  3562. }
  3563. /* The +5 is so we can append "\\*.*\0" */
  3564. wnamebuf = PyMem_New(wchar_t, len + 5);
  3565. if (!wnamebuf) {
  3566. PyErr_NoMemory();
  3567. goto exit;
  3568. }
  3569. wcscpy(wnamebuf, po_wchars);
  3570. if (len > 0) {
  3571. wchar_t wch = wnamebuf[len-1];
  3572. if (wch != SEP && wch != ALTSEP && wch != L':')
  3573. wnamebuf[len++] = SEP;
  3574. wcscpy(wnamebuf + len, L"*.*");
  3575. }
  3576. if ((list = PyList_New(0)) == NULL) {
  3577. goto exit;
  3578. }
  3579. Py_BEGIN_ALLOW_THREADS
  3580. hFindFile = FindFirstFileW(wnamebuf, &wFileData);
  3581. Py_END_ALLOW_THREADS
  3582. if (hFindFile == INVALID_HANDLE_VALUE) {
  3583. int error = GetLastError();
  3584. if (error == ERROR_FILE_NOT_FOUND)
  3585. goto exit;
  3586. path_error(path);
  3587. Py_CLEAR(list);
  3588. goto exit;
  3589. }
  3590. do {
  3591. /* Skip over . and .. */
  3592. if (wcscmp(wFileData.cFileName, L".") != 0 &&
  3593. wcscmp(wFileData.cFileName, L"..") != 0) {
  3594. v = PyUnicode_FromWideChar(wFileData.cFileName,
  3595. wcslen(wFileData.cFileName));
  3596. if (path->narrow && v) {
  3597. Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
  3598. }
  3599. if (v == NULL) {
  3600. Py_CLEAR(list);
  3601. break;
  3602. }
  3603. if (PyList_Append(list, v) != 0) {
  3604. Py_DECREF(v);
  3605. Py_CLEAR(list);
  3606. break;
  3607. }
  3608. Py_DECREF(v);
  3609. }
  3610. Py_BEGIN_ALLOW_THREADS
  3611. result = FindNextFileW(hFindFile, &wFileData);
  3612. Py_END_ALLOW_THREADS
  3613. /* FindNextFile sets error to ERROR_NO_MORE_FILES if
  3614. it got to the end of the directory. */
  3615. if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
  3616. path_error(path);
  3617. Py_CLEAR(list);
  3618. goto exit;
  3619. }
  3620. } while (result == TRUE);
  3621. exit:
  3622. if (hFindFile != INVALID_HANDLE_VALUE) {
  3623. if (FindClose(hFindFile) == FALSE) {
  3624. if (list != NULL) {
  3625. path_error(path);
  3626. Py_CLEAR(list);
  3627. }
  3628. }
  3629. }
  3630. PyMem_Free(wnamebuf);
  3631. return list;
  3632. } /* end of _listdir_windows_no_opendir */
  3633. #else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
  3634. static PyObject *
  3635. _posix_listdir(path_t *path, PyObject *list)
  3636. {
  3637. PyObject *v;
  3638. DIR *dirp = NULL;
  3639. struct dirent *ep;
  3640. int return_str; /* if false, return bytes */
  3641. #ifdef HAVE_FDOPENDIR
  3642. int fd = -1;
  3643. #endif
  3644. errno = 0;
  3645. #ifdef HAVE_FDOPENDIR
  3646. if (path->fd != -1) {
  3647. if (HAVE_FDOPENDIR_RUNTIME) {
  3648. /* closedir() closes the FD, so we duplicate it */
  3649. fd = _Py_dup(path->fd);
  3650. if (fd == -1)
  3651. return NULL;
  3652. return_str = 1;
  3653. Py_BEGIN_ALLOW_THREADS
  3654. dirp = fdopendir(fd);
  3655. Py_END_ALLOW_THREADS
  3656. } else {
  3657. PyErr_SetString(PyExc_TypeError,
  3658. "listdir: path should be string, bytes, os.PathLike or None, not int");
  3659. return NULL;
  3660. }
  3661. }
  3662. else
  3663. #endif
  3664. {
  3665. const char *name;
  3666. if (path->narrow) {
  3667. name = path->narrow;
  3668. /* only return bytes if they specified a bytes object */
  3669. return_str = !PyBytes_Check(path->object);
  3670. }
  3671. else {
  3672. name = ".";
  3673. return_str = 1;
  3674. }
  3675. Py_BEGIN_ALLOW_THREADS
  3676. dirp = opendir(name);
  3677. Py_END_ALLOW_THREADS
  3678. }
  3679. if (dirp == NULL) {
  3680. path_error(path);
  3681. list = NULL;
  3682. #ifdef HAVE_FDOPENDIR
  3683. if (fd != -1) {
  3684. Py_BEGIN_ALLOW_THREADS
  3685. close(fd);
  3686. Py_END_ALLOW_THREADS
  3687. }
  3688. #endif
  3689. goto exit;
  3690. }
  3691. if ((list = PyList_New(0)) == NULL) {
  3692. goto exit;
  3693. }
  3694. for (;;) {
  3695. errno = 0;
  3696. Py_BEGIN_ALLOW_THREADS
  3697. ep = readdir(dirp);
  3698. Py_END_ALLOW_THREADS
  3699. if (ep == NULL) {
  3700. if (errno == 0) {
  3701. break;
  3702. } else {
  3703. path_error(path);
  3704. Py_CLEAR(list);
  3705. goto exit;
  3706. }
  3707. }
  3708. if (ep->d_name[0] == '.' &&
  3709. (NAMLEN(ep) == 1 ||
  3710. (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
  3711. continue;
  3712. if (return_str)
  3713. v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
  3714. else
  3715. v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
  3716. if (v == NULL) {
  3717. Py_CLEAR(list);
  3718. break;
  3719. }
  3720. if (PyList_Append(list, v) != 0) {
  3721. Py_DECREF(v);
  3722. Py_CLEAR(list);
  3723. break;
  3724. }
  3725. Py_DECREF(v);
  3726. }
  3727. exit:
  3728. if (dirp != NULL) {
  3729. Py_BEGIN_ALLOW_THREADS
  3730. #ifdef HAVE_FDOPENDIR
  3731. if (fd > -1)
  3732. rewinddir(dirp);
  3733. #endif
  3734. closedir(dirp);
  3735. Py_END_ALLOW_THREADS
  3736. }
  3737. return list;
  3738. } /* end of _posix_listdir */
  3739. #endif /* which OS */
  3740. /*[clinic input]
  3741. os.listdir
  3742. path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
  3743. Return a list containing the names of the files in the directory.
  3744. path can be specified as either str, bytes, or a path-like object. If path is bytes,
  3745. the filenames returned will also be bytes; in all other circumstances
  3746. the filenames returned will be str.
  3747. If path is None, uses the path='.'.
  3748. On some platforms, path may also be specified as an open file descriptor;\
  3749. the file descriptor must refer to a directory.
  3750. If this functionality is unavailable, using it raises NotImplementedError.
  3751. The list is in arbitrary order. It does not include the special
  3752. entries '.' and '..' even if they are present in the directory.
  3753. [clinic start generated code]*/
  3754. static PyObject *
  3755. os_listdir_impl(PyObject *module, path_t *path)
  3756. /*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
  3757. {
  3758. if (PySys_Audit("os.listdir", "O",
  3759. path->object ? path->object : Py_None) < 0) {
  3760. return NULL;
  3761. }
  3762. #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
  3763. return _listdir_windows_no_opendir(path, NULL);
  3764. #else
  3765. return _posix_listdir(path, NULL);
  3766. #endif
  3767. }
  3768. #ifdef MS_WINDOWS
  3769. /*[clinic input]
  3770. os.listdrives
  3771. Return a list containing the names of drives in the system.
  3772. A drive name typically looks like 'C:\\'.
  3773. [clinic start generated code]*/
  3774. static PyObject *
  3775. os_listdrives_impl(PyObject *module)
  3776. /*[clinic end generated code: output=aaece9dacdf682b5 input=1af9ccc9e583798e]*/
  3777. {
  3778. /* Number of possible drives is limited, so 256 should always be enough.
  3779. On the day when it is not, listmounts() will have to be used. */
  3780. wchar_t buffer[256];
  3781. DWORD buflen = Py_ARRAY_LENGTH(buffer);
  3782. PyObject *result = NULL;
  3783. if (PySys_Audit("os.listdrives", NULL) < 0) {
  3784. return NULL;
  3785. }
  3786. Py_BEGIN_ALLOW_THREADS;
  3787. buflen = GetLogicalDriveStringsW(buflen, buffer);
  3788. Py_END_ALLOW_THREADS;
  3789. if (!buflen) {
  3790. PyErr_SetFromWindowsErr(0);
  3791. return NULL;
  3792. } else if (buflen >= Py_ARRAY_LENGTH(buffer)) {
  3793. PyErr_SetFromWindowsErr(ERROR_MORE_DATA);
  3794. return NULL;
  3795. }
  3796. /* buflen includes a null terminator, so remove it */
  3797. PyObject *str = PyUnicode_FromWideChar(buffer, buflen - 1);
  3798. if (str) {
  3799. PyObject *nullchar = PyUnicode_FromStringAndSize("\0", 1);
  3800. if (nullchar) {
  3801. result = PyUnicode_Split(str, nullchar, -1);
  3802. Py_DECREF(nullchar);
  3803. }
  3804. Py_DECREF(str);
  3805. }
  3806. return result;
  3807. }
  3808. /*[clinic input]
  3809. os.listvolumes
  3810. Return a list containing the volumes in the system.
  3811. Volumes are typically represented as a GUID path.
  3812. [clinic start generated code]*/
  3813. static PyObject *
  3814. os_listvolumes_impl(PyObject *module)
  3815. /*[clinic end generated code: output=534e10ea2bf9d386 input=f6e4e70371f11e99]*/
  3816. {
  3817. PyObject *result = PyList_New(0);
  3818. HANDLE find = INVALID_HANDLE_VALUE;
  3819. wchar_t buffer[MAX_PATH + 1];
  3820. if (!result) {
  3821. return NULL;
  3822. }
  3823. if (PySys_Audit("os.listvolumes", NULL) < 0) {
  3824. Py_DECREF(result);
  3825. return NULL;
  3826. }
  3827. int err = 0;
  3828. Py_BEGIN_ALLOW_THREADS;
  3829. find = FindFirstVolumeW(buffer, Py_ARRAY_LENGTH(buffer));
  3830. if (find == INVALID_HANDLE_VALUE) {
  3831. err = GetLastError();
  3832. }
  3833. Py_END_ALLOW_THREADS;
  3834. while (!err) {
  3835. PyObject *s = PyUnicode_FromWideChar(buffer, -1);
  3836. if (!s || PyList_Append(result, s) < 0) {
  3837. Py_XDECREF(s);
  3838. Py_CLEAR(result);
  3839. break;
  3840. }
  3841. Py_DECREF(s);
  3842. Py_BEGIN_ALLOW_THREADS;
  3843. if (!FindNextVolumeW(find, buffer, Py_ARRAY_LENGTH(buffer))) {
  3844. err = GetLastError();
  3845. }
  3846. Py_END_ALLOW_THREADS;
  3847. }
  3848. if (find != INVALID_HANDLE_VALUE) {
  3849. Py_BEGIN_ALLOW_THREADS;
  3850. FindVolumeClose(find);
  3851. Py_END_ALLOW_THREADS;
  3852. }
  3853. if (err && err != ERROR_NO_MORE_FILES) {
  3854. PyErr_SetFromWindowsErr(err);
  3855. Py_XDECREF(result);
  3856. result = NULL;
  3857. }
  3858. return result;
  3859. }
  3860. /*[clinic input]
  3861. os.listmounts
  3862. volume: path_t
  3863. Return a list containing mount points for a particular volume.
  3864. 'volume' should be a GUID path as returned from os.listvolumes.
  3865. [clinic start generated code]*/
  3866. static PyObject *
  3867. os_listmounts_impl(PyObject *module, path_t *volume)
  3868. /*[clinic end generated code: output=06da49679de4512e input=a8a27178e3f67845]*/
  3869. {
  3870. wchar_t default_buffer[MAX_PATH + 1];
  3871. DWORD buflen = Py_ARRAY_LENGTH(default_buffer);
  3872. LPWSTR buffer = default_buffer;
  3873. DWORD attributes;
  3874. PyObject *str = NULL;
  3875. PyObject *nullchar = NULL;
  3876. PyObject *result = NULL;
  3877. /* Ensure we have a valid volume path before continuing */
  3878. Py_BEGIN_ALLOW_THREADS
  3879. attributes = GetFileAttributesW(volume->wide);
  3880. Py_END_ALLOW_THREADS
  3881. if (attributes == INVALID_FILE_ATTRIBUTES &&
  3882. GetLastError() == ERROR_UNRECOGNIZED_VOLUME)
  3883. {
  3884. return PyErr_SetFromWindowsErr(ERROR_UNRECOGNIZED_VOLUME);
  3885. }
  3886. if (PySys_Audit("os.listmounts", "O", volume->object) < 0) {
  3887. return NULL;
  3888. }
  3889. while (1) {
  3890. BOOL success;
  3891. Py_BEGIN_ALLOW_THREADS
  3892. success = GetVolumePathNamesForVolumeNameW(volume->wide, buffer,
  3893. buflen, &buflen);
  3894. Py_END_ALLOW_THREADS
  3895. if (success) {
  3896. break;
  3897. }
  3898. if (GetLastError() != ERROR_MORE_DATA) {
  3899. PyErr_SetFromWindowsErr(0);
  3900. goto exit;
  3901. }
  3902. if (buffer != default_buffer) {
  3903. PyMem_Free((void *)buffer);
  3904. }
  3905. buffer = (wchar_t*)PyMem_Malloc(sizeof(wchar_t) * buflen);
  3906. if (!buffer) {
  3907. PyErr_NoMemory();
  3908. goto exit;
  3909. }
  3910. }
  3911. if (buflen < 2) {
  3912. result = PyList_New(0);
  3913. goto exit;
  3914. }
  3915. // buflen includes two null terminators, one for the last string
  3916. // and one for the array of strings.
  3917. str = PyUnicode_FromWideChar(buffer, buflen - 2);
  3918. nullchar = PyUnicode_FromStringAndSize("\0", 1);
  3919. if (str && nullchar) {
  3920. result = PyUnicode_Split(str, nullchar, -1);
  3921. }
  3922. exit:
  3923. if (buffer != default_buffer) {
  3924. PyMem_Free(buffer);
  3925. }
  3926. Py_XDECREF(nullchar);
  3927. Py_XDECREF(str);
  3928. return result;
  3929. }
  3930. /*[clinic input]
  3931. os._path_isdevdrive
  3932. path: path_t
  3933. Determines whether the specified path is on a Windows Dev Drive.
  3934. [clinic start generated code]*/
  3935. static PyObject *
  3936. os__path_isdevdrive_impl(PyObject *module, path_t *path)
  3937. /*[clinic end generated code: output=1f437ea6677433a2 input=ee83e4996a48e23d]*/
  3938. {
  3939. #ifndef PERSISTENT_VOLUME_STATE_DEV_VOLUME
  3940. /* This flag will be documented at
  3941. https://learn.microsoft.com/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_fs_persistent_volume_information
  3942. after release, and will be available in the latest WinSDK.
  3943. We include the flag to avoid a specific version dependency
  3944. on the latest WinSDK. */
  3945. const int PERSISTENT_VOLUME_STATE_DEV_VOLUME = 0x00002000;
  3946. #endif
  3947. int err = 0;
  3948. PyObject *r = NULL;
  3949. wchar_t volume[MAX_PATH];
  3950. Py_BEGIN_ALLOW_THREADS
  3951. if (!GetVolumePathNameW(path->wide, volume, MAX_PATH)) {
  3952. /* invalid path of some kind */
  3953. /* Note that this also includes the case where a volume is mounted
  3954. in a path longer than 260 characters. This is likely to be rare
  3955. and problematic for other reasons, so a (soft) failure in this
  3956. check seems okay. */
  3957. err = GetLastError();
  3958. } else if (GetDriveTypeW(volume) != DRIVE_FIXED) {
  3959. /* only care about local dev drives */
  3960. r = Py_False;
  3961. } else {
  3962. HANDLE hVolume = CreateFileW(
  3963. volume,
  3964. FILE_READ_ATTRIBUTES,
  3965. FILE_SHARE_READ | FILE_SHARE_WRITE,
  3966. NULL,
  3967. OPEN_EXISTING,
  3968. FILE_FLAG_BACKUP_SEMANTICS,
  3969. NULL
  3970. );
  3971. if (hVolume == INVALID_HANDLE_VALUE) {
  3972. err = GetLastError();
  3973. } else {
  3974. FILE_FS_PERSISTENT_VOLUME_INFORMATION volumeState = {0};
  3975. volumeState.Version = 1;
  3976. volumeState.FlagMask = PERSISTENT_VOLUME_STATE_DEV_VOLUME;
  3977. if (!DeviceIoControl(
  3978. hVolume,
  3979. FSCTL_QUERY_PERSISTENT_VOLUME_STATE,
  3980. &volumeState,
  3981. sizeof(volumeState),
  3982. &volumeState,
  3983. sizeof(volumeState),
  3984. NULL,
  3985. NULL
  3986. )) {
  3987. err = GetLastError();
  3988. }
  3989. CloseHandle(hVolume);
  3990. if (err == ERROR_INVALID_PARAMETER) {
  3991. /* not supported on this platform */
  3992. r = Py_False;
  3993. } else if (!err) {
  3994. r = (volumeState.VolumeFlags & PERSISTENT_VOLUME_STATE_DEV_VOLUME)
  3995. ? Py_True : Py_False;
  3996. }
  3997. }
  3998. }
  3999. Py_END_ALLOW_THREADS
  4000. if (err) {
  4001. PyErr_SetFromWindowsErr(err);
  4002. return NULL;
  4003. }
  4004. if (r) {
  4005. return Py_NewRef(r);
  4006. }
  4007. return NULL;
  4008. }
  4009. int
  4010. _PyOS_getfullpathname(const wchar_t *path, wchar_t **abspath_p)
  4011. {
  4012. wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
  4013. DWORD result;
  4014. result = GetFullPathNameW(path,
  4015. Py_ARRAY_LENGTH(woutbuf), woutbuf,
  4016. NULL);
  4017. if (!result) {
  4018. return -1;
  4019. }
  4020. if (result >= Py_ARRAY_LENGTH(woutbuf)) {
  4021. if ((size_t)result <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  4022. woutbufp = PyMem_RawMalloc((size_t)result * sizeof(wchar_t));
  4023. }
  4024. else {
  4025. woutbufp = NULL;
  4026. }
  4027. if (!woutbufp) {
  4028. *abspath_p = NULL;
  4029. return 0;
  4030. }
  4031. result = GetFullPathNameW(path, result, woutbufp, NULL);
  4032. if (!result) {
  4033. PyMem_RawFree(woutbufp);
  4034. return -1;
  4035. }
  4036. }
  4037. if (woutbufp != woutbuf) {
  4038. *abspath_p = woutbufp;
  4039. return 0;
  4040. }
  4041. *abspath_p = _PyMem_RawWcsdup(woutbufp);
  4042. return 0;
  4043. }
  4044. /* A helper function for abspath on win32 */
  4045. /*[clinic input]
  4046. os._getfullpathname
  4047. path: path_t
  4048. /
  4049. [clinic start generated code]*/
  4050. static PyObject *
  4051. os__getfullpathname_impl(PyObject *module, path_t *path)
  4052. /*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
  4053. {
  4054. wchar_t *abspath;
  4055. if (_PyOS_getfullpathname(path->wide, &abspath) < 0) {
  4056. return win32_error_object("GetFullPathNameW", path->object);
  4057. }
  4058. if (abspath == NULL) {
  4059. return PyErr_NoMemory();
  4060. }
  4061. PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
  4062. PyMem_RawFree(abspath);
  4063. if (str == NULL) {
  4064. return NULL;
  4065. }
  4066. if (path->narrow) {
  4067. Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
  4068. }
  4069. return str;
  4070. }
  4071. /*[clinic input]
  4072. os._getfinalpathname
  4073. path: path_t
  4074. /
  4075. A helper function for samepath on windows.
  4076. [clinic start generated code]*/
  4077. static PyObject *
  4078. os__getfinalpathname_impl(PyObject *module, path_t *path)
  4079. /*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
  4080. {
  4081. HANDLE hFile;
  4082. wchar_t buf[MAXPATHLEN], *target_path = buf;
  4083. int buf_size = Py_ARRAY_LENGTH(buf);
  4084. int result_length;
  4085. PyObject *result;
  4086. Py_BEGIN_ALLOW_THREADS
  4087. hFile = CreateFileW(
  4088. path->wide,
  4089. 0, /* desired access */
  4090. 0, /* share mode */
  4091. NULL, /* security attributes */
  4092. OPEN_EXISTING,
  4093. /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
  4094. FILE_FLAG_BACKUP_SEMANTICS,
  4095. NULL);
  4096. Py_END_ALLOW_THREADS
  4097. if (hFile == INVALID_HANDLE_VALUE) {
  4098. return win32_error_object("CreateFileW", path->object);
  4099. }
  4100. /* We have a good handle to the target, use it to determine the
  4101. target path name. */
  4102. while (1) {
  4103. Py_BEGIN_ALLOW_THREADS
  4104. result_length = GetFinalPathNameByHandleW(hFile, target_path,
  4105. buf_size, VOLUME_NAME_DOS);
  4106. Py_END_ALLOW_THREADS
  4107. if (!result_length) {
  4108. result = win32_error_object("GetFinalPathNameByHandleW",
  4109. path->object);
  4110. goto cleanup;
  4111. }
  4112. if (result_length < buf_size) {
  4113. break;
  4114. }
  4115. wchar_t *tmp;
  4116. tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
  4117. result_length * sizeof(*tmp));
  4118. if (!tmp) {
  4119. result = PyErr_NoMemory();
  4120. goto cleanup;
  4121. }
  4122. buf_size = result_length;
  4123. target_path = tmp;
  4124. }
  4125. result = PyUnicode_FromWideChar(target_path, result_length);
  4126. if (result && path->narrow) {
  4127. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  4128. }
  4129. cleanup:
  4130. if (target_path != buf) {
  4131. PyMem_Free(target_path);
  4132. }
  4133. CloseHandle(hFile);
  4134. return result;
  4135. }
  4136. /*[clinic input]
  4137. os._getvolumepathname
  4138. path: path_t
  4139. A helper function for ismount on Win32.
  4140. [clinic start generated code]*/
  4141. static PyObject *
  4142. os__getvolumepathname_impl(PyObject *module, path_t *path)
  4143. /*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
  4144. {
  4145. PyObject *result;
  4146. wchar_t *mountpath=NULL;
  4147. size_t buflen;
  4148. BOOL ret;
  4149. /* Volume path should be shorter than entire path */
  4150. buflen = Py_MAX(path->length, MAX_PATH);
  4151. if (buflen > PY_DWORD_MAX) {
  4152. PyErr_SetString(PyExc_OverflowError, "path too long");
  4153. return NULL;
  4154. }
  4155. mountpath = PyMem_New(wchar_t, buflen);
  4156. if (mountpath == NULL)
  4157. return PyErr_NoMemory();
  4158. Py_BEGIN_ALLOW_THREADS
  4159. ret = GetVolumePathNameW(path->wide, mountpath,
  4160. Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
  4161. Py_END_ALLOW_THREADS
  4162. if (!ret) {
  4163. result = win32_error_object("_getvolumepathname", path->object);
  4164. goto exit;
  4165. }
  4166. result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
  4167. if (path->narrow)
  4168. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  4169. exit:
  4170. PyMem_Free(mountpath);
  4171. return result;
  4172. }
  4173. /*[clinic input]
  4174. os._path_splitroot
  4175. path: path_t
  4176. Removes everything after the root on Win32.
  4177. [clinic start generated code]*/
  4178. static PyObject *
  4179. os__path_splitroot_impl(PyObject *module, path_t *path)
  4180. /*[clinic end generated code: output=ab7f1a88b654581c input=dc93b1d3984cffb6]*/
  4181. {
  4182. wchar_t *buffer;
  4183. wchar_t *end;
  4184. PyObject *result = NULL;
  4185. HRESULT ret;
  4186. buffer = (wchar_t*)PyMem_Malloc(sizeof(wchar_t) * (wcslen(path->wide) + 1));
  4187. if (!buffer) {
  4188. return NULL;
  4189. }
  4190. wcscpy(buffer, path->wide);
  4191. for (wchar_t *p = wcschr(buffer, L'/'); p; p = wcschr(p, L'/')) {
  4192. *p = L'\\';
  4193. }
  4194. Py_BEGIN_ALLOW_THREADS
  4195. ret = PathCchSkipRoot(buffer, &end);
  4196. Py_END_ALLOW_THREADS
  4197. if (FAILED(ret)) {
  4198. result = Py_BuildValue("sO", "", path->object);
  4199. } else if (end != buffer) {
  4200. size_t rootLen = (size_t)(end - buffer);
  4201. result = Py_BuildValue("NN",
  4202. PyUnicode_FromWideChar(path->wide, rootLen),
  4203. PyUnicode_FromWideChar(path->wide + rootLen, -1)
  4204. );
  4205. } else {
  4206. result = Py_BuildValue("Os", path->object, "");
  4207. }
  4208. PyMem_Free(buffer);
  4209. return result;
  4210. }
  4211. /*[clinic input]
  4212. os._path_isdir
  4213. s: 'O'
  4214. Return true if the pathname refers to an existing directory.
  4215. [clinic start generated code]*/
  4216. static PyObject *
  4217. os__path_isdir_impl(PyObject *module, PyObject *s)
  4218. /*[clinic end generated code: output=9d87ab3c8b8a4e61 input=c17f7ef21d22d64e]*/
  4219. {
  4220. HANDLE hfile;
  4221. BOOL close_file = TRUE;
  4222. FILE_BASIC_INFO info;
  4223. path_t _path = PATH_T_INITIALIZE("isdir", "s", 0, 1);
  4224. int result;
  4225. BOOL slow_path = TRUE;
  4226. FILE_STAT_BASIC_INFORMATION statInfo;
  4227. if (!path_converter(s, &_path)) {
  4228. path_cleanup(&_path);
  4229. if (PyErr_ExceptionMatches(PyExc_ValueError)) {
  4230. PyErr_Clear();
  4231. Py_RETURN_FALSE;
  4232. }
  4233. return NULL;
  4234. }
  4235. Py_BEGIN_ALLOW_THREADS
  4236. if (_path.wide) {
  4237. if (_Py_GetFileInformationByName(_path.wide, FileStatBasicByNameInfo,
  4238. &statInfo, sizeof(statInfo))) {
  4239. if (!(statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
  4240. slow_path = FALSE;
  4241. result = statInfo.FileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4242. } else if (!(statInfo.FileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
  4243. slow_path = FALSE;
  4244. result = 0;
  4245. }
  4246. } else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(GetLastError())) {
  4247. slow_path = FALSE;
  4248. result = 0;
  4249. }
  4250. }
  4251. if (slow_path) {
  4252. if (_path.fd != -1) {
  4253. hfile = _Py_get_osfhandle_noraise(_path.fd);
  4254. close_file = FALSE;
  4255. }
  4256. else {
  4257. hfile = CreateFileW(_path.wide, FILE_READ_ATTRIBUTES, 0, NULL,
  4258. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  4259. }
  4260. if (hfile != INVALID_HANDLE_VALUE) {
  4261. if (GetFileInformationByHandleEx(hfile, FileBasicInfo, &info,
  4262. sizeof(info)))
  4263. {
  4264. result = info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4265. }
  4266. else {
  4267. result = 0;
  4268. }
  4269. if (close_file) {
  4270. CloseHandle(hfile);
  4271. }
  4272. }
  4273. else {
  4274. STRUCT_STAT st;
  4275. switch (GetLastError()) {
  4276. case ERROR_ACCESS_DENIED:
  4277. case ERROR_SHARING_VIOLATION:
  4278. case ERROR_CANT_ACCESS_FILE:
  4279. case ERROR_INVALID_PARAMETER:
  4280. if (STAT(_path.wide, &st)) {
  4281. result = 0;
  4282. }
  4283. else {
  4284. result = S_ISDIR(st.st_mode);
  4285. }
  4286. break;
  4287. default:
  4288. result = 0;
  4289. }
  4290. }
  4291. }
  4292. Py_END_ALLOW_THREADS
  4293. path_cleanup(&_path);
  4294. if (result) {
  4295. Py_RETURN_TRUE;
  4296. }
  4297. Py_RETURN_FALSE;
  4298. }
  4299. /*[clinic input]
  4300. os._path_isfile
  4301. path: 'O'
  4302. Test whether a path is a regular file
  4303. [clinic start generated code]*/
  4304. static PyObject *
  4305. os__path_isfile_impl(PyObject *module, PyObject *path)
  4306. /*[clinic end generated code: output=2394ed7c4b5cfd85 input=de22d74960ade365]*/
  4307. {
  4308. HANDLE hfile;
  4309. BOOL close_file = TRUE;
  4310. FILE_BASIC_INFO info;
  4311. path_t _path = PATH_T_INITIALIZE("isfile", "path", 0, 1);
  4312. int result;
  4313. BOOL slow_path = TRUE;
  4314. FILE_STAT_BASIC_INFORMATION statInfo;
  4315. if (!path_converter(path, &_path)) {
  4316. path_cleanup(&_path);
  4317. if (PyErr_ExceptionMatches(PyExc_ValueError)) {
  4318. PyErr_Clear();
  4319. Py_RETURN_FALSE;
  4320. }
  4321. return NULL;
  4322. }
  4323. Py_BEGIN_ALLOW_THREADS
  4324. if (_path.wide) {
  4325. if (_Py_GetFileInformationByName(_path.wide, FileStatBasicByNameInfo,
  4326. &statInfo, sizeof(statInfo))) {
  4327. if (!(statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
  4328. slow_path = FALSE;
  4329. result = !(statInfo.FileAttributes & FILE_ATTRIBUTE_DIRECTORY);
  4330. } else if (statInfo.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  4331. slow_path = FALSE;
  4332. result = 0;
  4333. }
  4334. } else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(GetLastError())) {
  4335. slow_path = FALSE;
  4336. result = 0;
  4337. }
  4338. }
  4339. if (slow_path) {
  4340. if (_path.fd != -1) {
  4341. hfile = _Py_get_osfhandle_noraise(_path.fd);
  4342. close_file = FALSE;
  4343. }
  4344. else {
  4345. hfile = CreateFileW(_path.wide, FILE_READ_ATTRIBUTES, 0, NULL,
  4346. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  4347. }
  4348. if (hfile != INVALID_HANDLE_VALUE) {
  4349. if (GetFileInformationByHandleEx(hfile, FileBasicInfo, &info,
  4350. sizeof(info)))
  4351. {
  4352. result = !(info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY);
  4353. }
  4354. else {
  4355. result = 0;
  4356. }
  4357. if (close_file) {
  4358. CloseHandle(hfile);
  4359. }
  4360. }
  4361. else {
  4362. STRUCT_STAT st;
  4363. switch (GetLastError()) {
  4364. case ERROR_ACCESS_DENIED:
  4365. case ERROR_SHARING_VIOLATION:
  4366. case ERROR_CANT_ACCESS_FILE:
  4367. case ERROR_INVALID_PARAMETER:
  4368. if (STAT(_path.wide, &st)) {
  4369. result = 0;
  4370. }
  4371. else {
  4372. result = S_ISREG(st.st_mode);
  4373. }
  4374. break;
  4375. default:
  4376. result = 0;
  4377. }
  4378. }
  4379. }
  4380. Py_END_ALLOW_THREADS
  4381. path_cleanup(&_path);
  4382. if (result) {
  4383. Py_RETURN_TRUE;
  4384. }
  4385. Py_RETURN_FALSE;
  4386. }
  4387. /*[clinic input]
  4388. os._path_exists
  4389. path: 'O'
  4390. Test whether a path exists. Returns False for broken symbolic links
  4391. [clinic start generated code]*/
  4392. static PyObject *
  4393. os__path_exists_impl(PyObject *module, PyObject *path)
  4394. /*[clinic end generated code: output=f508c3b35e13a249 input=380f77cdfa0f7ae8]*/
  4395. {
  4396. HANDLE hfile;
  4397. BOOL close_file = TRUE;
  4398. path_t _path = PATH_T_INITIALIZE("exists", "path", 0, 1);
  4399. int result;
  4400. BOOL slow_path = TRUE;
  4401. FILE_STAT_BASIC_INFORMATION statInfo;
  4402. if (!path_converter(path, &_path)) {
  4403. path_cleanup(&_path);
  4404. if (PyErr_ExceptionMatches(PyExc_ValueError)) {
  4405. PyErr_Clear();
  4406. Py_RETURN_FALSE;
  4407. }
  4408. return NULL;
  4409. }
  4410. Py_BEGIN_ALLOW_THREADS
  4411. if (_path.wide) {
  4412. if (_Py_GetFileInformationByName(_path.wide, FileStatBasicByNameInfo,
  4413. &statInfo, sizeof(statInfo))) {
  4414. if (!(statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
  4415. slow_path = FALSE;
  4416. result = 1;
  4417. }
  4418. } else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(GetLastError())) {
  4419. slow_path = FALSE;
  4420. result = 0;
  4421. }
  4422. }
  4423. if (slow_path) {
  4424. if (_path.fd != -1) {
  4425. hfile = _Py_get_osfhandle_noraise(_path.fd);
  4426. close_file = FALSE;
  4427. }
  4428. else {
  4429. hfile = CreateFileW(_path.wide, FILE_READ_ATTRIBUTES, 0, NULL,
  4430. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  4431. }
  4432. if (hfile != INVALID_HANDLE_VALUE) {
  4433. result = 1;
  4434. if (close_file) {
  4435. CloseHandle(hfile);
  4436. }
  4437. }
  4438. else {
  4439. STRUCT_STAT st;
  4440. switch (GetLastError()) {
  4441. case ERROR_ACCESS_DENIED:
  4442. case ERROR_SHARING_VIOLATION:
  4443. case ERROR_CANT_ACCESS_FILE:
  4444. case ERROR_INVALID_PARAMETER:
  4445. if (STAT(_path.wide, &st)) {
  4446. result = 0;
  4447. }
  4448. else {
  4449. result = 1;
  4450. }
  4451. break;
  4452. default:
  4453. result = 0;
  4454. }
  4455. }
  4456. }
  4457. Py_END_ALLOW_THREADS
  4458. path_cleanup(&_path);
  4459. if (result) {
  4460. Py_RETURN_TRUE;
  4461. }
  4462. Py_RETURN_FALSE;
  4463. }
  4464. /*[clinic input]
  4465. os._path_islink
  4466. path: 'O'
  4467. Test whether a path is a symbolic link
  4468. [clinic start generated code]*/
  4469. static PyObject *
  4470. os__path_islink_impl(PyObject *module, PyObject *path)
  4471. /*[clinic end generated code: output=6d8640b1a390c054 input=38a3cb937ccf59bf]*/
  4472. {
  4473. HANDLE hfile;
  4474. BOOL close_file = TRUE;
  4475. FILE_ATTRIBUTE_TAG_INFO info;
  4476. path_t _path = PATH_T_INITIALIZE("islink", "path", 0, 1);
  4477. int result;
  4478. BOOL slow_path = TRUE;
  4479. FILE_STAT_BASIC_INFORMATION statInfo;
  4480. if (!path_converter(path, &_path)) {
  4481. path_cleanup(&_path);
  4482. if (PyErr_ExceptionMatches(PyExc_ValueError)) {
  4483. PyErr_Clear();
  4484. Py_RETURN_FALSE;
  4485. }
  4486. return NULL;
  4487. }
  4488. Py_BEGIN_ALLOW_THREADS
  4489. if (_path.wide) {
  4490. if (_Py_GetFileInformationByName(_path.wide, FileStatBasicByNameInfo,
  4491. &statInfo, sizeof(statInfo))) {
  4492. slow_path = FALSE;
  4493. if (statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
  4494. result = (statInfo.ReparseTag == IO_REPARSE_TAG_SYMLINK);
  4495. }
  4496. else {
  4497. result = 0;
  4498. }
  4499. } else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(GetLastError())) {
  4500. slow_path = FALSE;
  4501. result = 0;
  4502. }
  4503. }
  4504. if (slow_path) {
  4505. if (_path.fd != -1) {
  4506. hfile = _Py_get_osfhandle_noraise(_path.fd);
  4507. close_file = FALSE;
  4508. }
  4509. else {
  4510. hfile = CreateFileW(_path.wide, FILE_READ_ATTRIBUTES, 0, NULL,
  4511. OPEN_EXISTING,
  4512. FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
  4513. NULL);
  4514. }
  4515. if (hfile != INVALID_HANDLE_VALUE) {
  4516. if (GetFileInformationByHandleEx(hfile, FileAttributeTagInfo, &info,
  4517. sizeof(info)))
  4518. {
  4519. result = (info.ReparseTag == IO_REPARSE_TAG_SYMLINK);
  4520. }
  4521. else {
  4522. result = 0;
  4523. }
  4524. if (close_file) {
  4525. CloseHandle(hfile);
  4526. }
  4527. }
  4528. else {
  4529. STRUCT_STAT st;
  4530. switch (GetLastError()) {
  4531. case ERROR_ACCESS_DENIED:
  4532. case ERROR_SHARING_VIOLATION:
  4533. case ERROR_CANT_ACCESS_FILE:
  4534. case ERROR_INVALID_PARAMETER:
  4535. if (LSTAT(_path.wide, &st)) {
  4536. result = 0;
  4537. }
  4538. else {
  4539. result = S_ISLNK(st.st_mode);
  4540. }
  4541. break;
  4542. default:
  4543. result = 0;
  4544. }
  4545. }
  4546. }
  4547. Py_END_ALLOW_THREADS
  4548. path_cleanup(&_path);
  4549. if (result) {
  4550. Py_RETURN_TRUE;
  4551. }
  4552. Py_RETURN_FALSE;
  4553. }
  4554. #endif /* MS_WINDOWS */
  4555. /*[clinic input]
  4556. os._path_normpath
  4557. path: object
  4558. Basic path normalization.
  4559. [clinic start generated code]*/
  4560. static PyObject *
  4561. os__path_normpath_impl(PyObject *module, PyObject *path)
  4562. /*[clinic end generated code: output=b94d696d828019da input=5e90c39e12549dc0]*/
  4563. {
  4564. if (!PyUnicode_Check(path)) {
  4565. PyErr_Format(PyExc_TypeError, "expected 'str', not '%.200s'",
  4566. Py_TYPE(path)->tp_name);
  4567. return NULL;
  4568. }
  4569. Py_ssize_t len;
  4570. wchar_t *buffer = PyUnicode_AsWideCharString(path, &len);
  4571. if (!buffer) {
  4572. return NULL;
  4573. }
  4574. Py_ssize_t norm_len;
  4575. wchar_t *norm_path = _Py_normpath_and_size(buffer, len, &norm_len);
  4576. PyObject *result = PyUnicode_FromWideChar(norm_path, norm_len);
  4577. PyMem_Free(buffer);
  4578. return result;
  4579. }
  4580. /*[clinic input]
  4581. os.mkdir
  4582. path : path_t
  4583. mode: int = 0o777
  4584. *
  4585. dir_fd : dir_fd(requires='mkdirat') = None
  4586. # "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
  4587. Create a directory.
  4588. If dir_fd is not None, it should be a file descriptor open to a directory,
  4589. and path should be relative; path will then be relative to that directory.
  4590. dir_fd may not be implemented on your platform.
  4591. If it is unavailable, using it will raise a NotImplementedError.
  4592. The mode argument is ignored on Windows. Where it is used, the current umask
  4593. value is first masked out.
  4594. [clinic start generated code]*/
  4595. static PyObject *
  4596. os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
  4597. /*[clinic end generated code: output=a70446903abe821f input=a61722e1576fab03]*/
  4598. {
  4599. int result;
  4600. #ifdef HAVE_MKDIRAT
  4601. int mkdirat_unavailable = 0;
  4602. #endif
  4603. if (PySys_Audit("os.mkdir", "Oii", path->object, mode,
  4604. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4605. return NULL;
  4606. }
  4607. #ifdef MS_WINDOWS
  4608. Py_BEGIN_ALLOW_THREADS
  4609. result = CreateDirectoryW(path->wide, NULL);
  4610. Py_END_ALLOW_THREADS
  4611. if (!result)
  4612. return path_error(path);
  4613. #else
  4614. Py_BEGIN_ALLOW_THREADS
  4615. #if HAVE_MKDIRAT
  4616. if (dir_fd != DEFAULT_DIR_FD) {
  4617. if (HAVE_MKDIRAT_RUNTIME) {
  4618. result = mkdirat(dir_fd, path->narrow, mode);
  4619. } else {
  4620. mkdirat_unavailable = 1;
  4621. }
  4622. } else
  4623. #endif
  4624. #if defined(__WATCOMC__) && !defined(__QNX__)
  4625. result = mkdir(path->narrow);
  4626. #else
  4627. result = mkdir(path->narrow, mode);
  4628. #endif
  4629. Py_END_ALLOW_THREADS
  4630. #if HAVE_MKDIRAT
  4631. if (mkdirat_unavailable) {
  4632. argument_unavailable_error(NULL, "dir_fd");
  4633. return NULL;
  4634. }
  4635. #endif
  4636. if (result < 0)
  4637. return path_error(path);
  4638. #endif /* MS_WINDOWS */
  4639. Py_RETURN_NONE;
  4640. }
  4641. /* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
  4642. #if defined(HAVE_SYS_RESOURCE_H)
  4643. #include <sys/resource.h>
  4644. #endif
  4645. #ifdef HAVE_NICE
  4646. /*[clinic input]
  4647. os.nice
  4648. increment: int
  4649. /
  4650. Add increment to the priority of process and return the new priority.
  4651. [clinic start generated code]*/
  4652. static PyObject *
  4653. os_nice_impl(PyObject *module, int increment)
  4654. /*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
  4655. {
  4656. int value;
  4657. /* There are two flavours of 'nice': one that returns the new
  4658. priority (as required by almost all standards out there) and the
  4659. Linux/FreeBSD one, which returns '0' on success and advices
  4660. the use of getpriority() to get the new priority.
  4661. If we are of the nice family that returns the new priority, we
  4662. need to clear errno before the call, and check if errno is filled
  4663. before calling posix_error() on a returnvalue of -1, because the
  4664. -1 may be the actual new priority! */
  4665. errno = 0;
  4666. value = nice(increment);
  4667. #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
  4668. if (value == 0)
  4669. value = getpriority(PRIO_PROCESS, 0);
  4670. #endif
  4671. if (value == -1 && errno != 0)
  4672. /* either nice() or getpriority() returned an error */
  4673. return posix_error();
  4674. return PyLong_FromLong((long) value);
  4675. }
  4676. #endif /* HAVE_NICE */
  4677. #ifdef HAVE_GETPRIORITY
  4678. /*[clinic input]
  4679. os.getpriority
  4680. which: int
  4681. who: int
  4682. Return program scheduling priority.
  4683. [clinic start generated code]*/
  4684. static PyObject *
  4685. os_getpriority_impl(PyObject *module, int which, int who)
  4686. /*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
  4687. {
  4688. int retval;
  4689. errno = 0;
  4690. retval = getpriority(which, who);
  4691. if (errno != 0)
  4692. return posix_error();
  4693. return PyLong_FromLong((long)retval);
  4694. }
  4695. #endif /* HAVE_GETPRIORITY */
  4696. #ifdef HAVE_SETPRIORITY
  4697. /*[clinic input]
  4698. os.setpriority
  4699. which: int
  4700. who: int
  4701. priority: int
  4702. Set program scheduling priority.
  4703. [clinic start generated code]*/
  4704. static PyObject *
  4705. os_setpriority_impl(PyObject *module, int which, int who, int priority)
  4706. /*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
  4707. {
  4708. int retval;
  4709. retval = setpriority(which, who, priority);
  4710. if (retval == -1)
  4711. return posix_error();
  4712. Py_RETURN_NONE;
  4713. }
  4714. #endif /* HAVE_SETPRIORITY */
  4715. static PyObject *
  4716. internal_rename(path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int is_replace)
  4717. {
  4718. const char *function_name = is_replace ? "replace" : "rename";
  4719. int dir_fd_specified;
  4720. #ifdef HAVE_RENAMEAT
  4721. int renameat_unavailable = 0;
  4722. #endif
  4723. #ifdef MS_WINDOWS
  4724. BOOL result;
  4725. int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
  4726. #else
  4727. int result;
  4728. #endif
  4729. dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
  4730. (dst_dir_fd != DEFAULT_DIR_FD);
  4731. #ifndef HAVE_RENAMEAT
  4732. if (dir_fd_specified) {
  4733. argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
  4734. return NULL;
  4735. }
  4736. #endif
  4737. if (PySys_Audit("os.rename", "OOii", src->object, dst->object,
  4738. src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
  4739. dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
  4740. return NULL;
  4741. }
  4742. #ifdef MS_WINDOWS
  4743. Py_BEGIN_ALLOW_THREADS
  4744. result = MoveFileExW(src->wide, dst->wide, flags);
  4745. Py_END_ALLOW_THREADS
  4746. if (!result)
  4747. return path_error2(src, dst);
  4748. #else
  4749. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  4750. PyErr_Format(PyExc_ValueError,
  4751. "%s: src and dst must be the same type", function_name);
  4752. return NULL;
  4753. }
  4754. Py_BEGIN_ALLOW_THREADS
  4755. #ifdef HAVE_RENAMEAT
  4756. if (dir_fd_specified) {
  4757. if (HAVE_RENAMEAT_RUNTIME) {
  4758. result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
  4759. } else {
  4760. renameat_unavailable = 1;
  4761. }
  4762. } else
  4763. #endif
  4764. result = rename(src->narrow, dst->narrow);
  4765. Py_END_ALLOW_THREADS
  4766. #ifdef HAVE_RENAMEAT
  4767. if (renameat_unavailable) {
  4768. argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
  4769. return NULL;
  4770. }
  4771. #endif
  4772. if (result)
  4773. return path_error2(src, dst);
  4774. #endif
  4775. Py_RETURN_NONE;
  4776. }
  4777. /*[clinic input]
  4778. os.rename
  4779. src : path_t
  4780. dst : path_t
  4781. *
  4782. src_dir_fd : dir_fd = None
  4783. dst_dir_fd : dir_fd = None
  4784. Rename a file or directory.
  4785. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  4786. descriptor open to a directory, and the respective path string (src or dst)
  4787. should be relative; the path will then be relative to that directory.
  4788. src_dir_fd and dst_dir_fd, may not be implemented on your platform.
  4789. If they are unavailable, using them will raise a NotImplementedError.
  4790. [clinic start generated code]*/
  4791. static PyObject *
  4792. os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  4793. int dst_dir_fd)
  4794. /*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
  4795. {
  4796. return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
  4797. }
  4798. /*[clinic input]
  4799. os.replace = os.rename
  4800. Rename a file or directory, overwriting the destination.
  4801. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  4802. descriptor open to a directory, and the respective path string (src or dst)
  4803. should be relative; the path will then be relative to that directory.
  4804. src_dir_fd and dst_dir_fd, may not be implemented on your platform.
  4805. If they are unavailable, using them will raise a NotImplementedError.
  4806. [clinic start generated code]*/
  4807. static PyObject *
  4808. os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  4809. int dst_dir_fd)
  4810. /*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
  4811. {
  4812. return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
  4813. }
  4814. /*[clinic input]
  4815. os.rmdir
  4816. path: path_t
  4817. *
  4818. dir_fd: dir_fd(requires='unlinkat') = None
  4819. Remove a directory.
  4820. If dir_fd is not None, it should be a file descriptor open to a directory,
  4821. and path should be relative; path will then be relative to that directory.
  4822. dir_fd may not be implemented on your platform.
  4823. If it is unavailable, using it will raise a NotImplementedError.
  4824. [clinic start generated code]*/
  4825. static PyObject *
  4826. os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
  4827. /*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
  4828. {
  4829. int result;
  4830. #ifdef HAVE_UNLINKAT
  4831. int unlinkat_unavailable = 0;
  4832. #endif
  4833. if (PySys_Audit("os.rmdir", "Oi", path->object,
  4834. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4835. return NULL;
  4836. }
  4837. Py_BEGIN_ALLOW_THREADS
  4838. #ifdef MS_WINDOWS
  4839. /* Windows, success=1, UNIX, success=0 */
  4840. result = !RemoveDirectoryW(path->wide);
  4841. #else
  4842. #ifdef HAVE_UNLINKAT
  4843. if (dir_fd != DEFAULT_DIR_FD) {
  4844. if (HAVE_UNLINKAT_RUNTIME) {
  4845. result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
  4846. } else {
  4847. unlinkat_unavailable = 1;
  4848. result = -1;
  4849. }
  4850. } else
  4851. #endif
  4852. result = rmdir(path->narrow);
  4853. #endif
  4854. Py_END_ALLOW_THREADS
  4855. #ifdef HAVE_UNLINKAT
  4856. if (unlinkat_unavailable) {
  4857. argument_unavailable_error("rmdir", "dir_fd");
  4858. return NULL;
  4859. }
  4860. #endif
  4861. if (result)
  4862. return path_error(path);
  4863. Py_RETURN_NONE;
  4864. }
  4865. #ifdef HAVE_SYSTEM
  4866. #ifdef MS_WINDOWS
  4867. /*[clinic input]
  4868. os.system -> long
  4869. command: Py_UNICODE
  4870. Execute the command in a subshell.
  4871. [clinic start generated code]*/
  4872. static long
  4873. os_system_impl(PyObject *module, const Py_UNICODE *command)
  4874. /*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
  4875. {
  4876. long result;
  4877. if (PySys_Audit("os.system", "(u)", command) < 0) {
  4878. return -1;
  4879. }
  4880. Py_BEGIN_ALLOW_THREADS
  4881. _Py_BEGIN_SUPPRESS_IPH
  4882. result = _wsystem(command);
  4883. _Py_END_SUPPRESS_IPH
  4884. Py_END_ALLOW_THREADS
  4885. return result;
  4886. }
  4887. #else /* MS_WINDOWS */
  4888. /*[clinic input]
  4889. os.system -> long
  4890. command: FSConverter
  4891. Execute the command in a subshell.
  4892. [clinic start generated code]*/
  4893. static long
  4894. os_system_impl(PyObject *module, PyObject *command)
  4895. /*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
  4896. {
  4897. long result;
  4898. const char *bytes = PyBytes_AsString(command);
  4899. if (PySys_Audit("os.system", "(O)", command) < 0) {
  4900. return -1;
  4901. }
  4902. Py_BEGIN_ALLOW_THREADS
  4903. result = system(bytes);
  4904. Py_END_ALLOW_THREADS
  4905. return result;
  4906. }
  4907. #endif
  4908. #endif /* HAVE_SYSTEM */
  4909. #ifdef HAVE_UMASK
  4910. /*[clinic input]
  4911. os.umask
  4912. mask: int
  4913. /
  4914. Set the current numeric umask and return the previous umask.
  4915. [clinic start generated code]*/
  4916. static PyObject *
  4917. os_umask_impl(PyObject *module, int mask)
  4918. /*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
  4919. {
  4920. int i = (int)umask(mask);
  4921. if (i < 0)
  4922. return posix_error();
  4923. return PyLong_FromLong((long)i);
  4924. }
  4925. #endif
  4926. #ifdef MS_WINDOWS
  4927. /* override the default DeleteFileW behavior so that directory
  4928. symlinks can be removed with this function, the same as with
  4929. Unix symlinks */
  4930. BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
  4931. {
  4932. WIN32_FILE_ATTRIBUTE_DATA info;
  4933. WIN32_FIND_DATAW find_data;
  4934. HANDLE find_data_handle;
  4935. int is_directory = 0;
  4936. int is_link = 0;
  4937. if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
  4938. is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4939. /* Get WIN32_FIND_DATA structure for the path to determine if
  4940. it is a symlink */
  4941. if(is_directory &&
  4942. info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
  4943. find_data_handle = FindFirstFileW(lpFileName, &find_data);
  4944. if(find_data_handle != INVALID_HANDLE_VALUE) {
  4945. /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
  4946. IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
  4947. is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
  4948. find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
  4949. FindClose(find_data_handle);
  4950. }
  4951. }
  4952. }
  4953. if (is_directory && is_link)
  4954. return RemoveDirectoryW(lpFileName);
  4955. return DeleteFileW(lpFileName);
  4956. }
  4957. #endif /* MS_WINDOWS */
  4958. /*[clinic input]
  4959. os.unlink
  4960. path: path_t
  4961. *
  4962. dir_fd: dir_fd(requires='unlinkat')=None
  4963. Remove a file (same as remove()).
  4964. If dir_fd is not None, it should be a file descriptor open to a directory,
  4965. and path should be relative; path will then be relative to that directory.
  4966. dir_fd may not be implemented on your platform.
  4967. If it is unavailable, using it will raise a NotImplementedError.
  4968. [clinic start generated code]*/
  4969. static PyObject *
  4970. os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
  4971. /*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
  4972. {
  4973. int result;
  4974. #ifdef HAVE_UNLINKAT
  4975. int unlinkat_unavailable = 0;
  4976. #endif
  4977. if (PySys_Audit("os.remove", "Oi", path->object,
  4978. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4979. return NULL;
  4980. }
  4981. Py_BEGIN_ALLOW_THREADS
  4982. _Py_BEGIN_SUPPRESS_IPH
  4983. #ifdef MS_WINDOWS
  4984. /* Windows, success=1, UNIX, success=0 */
  4985. result = !Py_DeleteFileW(path->wide);
  4986. #else
  4987. #ifdef HAVE_UNLINKAT
  4988. if (dir_fd != DEFAULT_DIR_FD) {
  4989. if (HAVE_UNLINKAT_RUNTIME) {
  4990. result = unlinkat(dir_fd, path->narrow, 0);
  4991. } else {
  4992. unlinkat_unavailable = 1;
  4993. }
  4994. } else
  4995. #endif /* HAVE_UNLINKAT */
  4996. result = unlink(path->narrow);
  4997. #endif
  4998. _Py_END_SUPPRESS_IPH
  4999. Py_END_ALLOW_THREADS
  5000. #ifdef HAVE_UNLINKAT
  5001. if (unlinkat_unavailable) {
  5002. argument_unavailable_error(NULL, "dir_fd");
  5003. return NULL;
  5004. }
  5005. #endif
  5006. if (result)
  5007. return path_error(path);
  5008. Py_RETURN_NONE;
  5009. }
  5010. /*[clinic input]
  5011. os.remove = os.unlink
  5012. Remove a file (same as unlink()).
  5013. If dir_fd is not None, it should be a file descriptor open to a directory,
  5014. and path should be relative; path will then be relative to that directory.
  5015. dir_fd may not be implemented on your platform.
  5016. If it is unavailable, using it will raise a NotImplementedError.
  5017. [clinic start generated code]*/
  5018. static PyObject *
  5019. os_remove_impl(PyObject *module, path_t *path, int dir_fd)
  5020. /*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
  5021. {
  5022. return os_unlink_impl(module, path, dir_fd);
  5023. }
  5024. static PyStructSequence_Field uname_result_fields[] = {
  5025. {"sysname", "operating system name"},
  5026. {"nodename", "name of machine on network (implementation-defined)"},
  5027. {"release", "operating system release"},
  5028. {"version", "operating system version"},
  5029. {"machine", "hardware identifier"},
  5030. {NULL}
  5031. };
  5032. PyDoc_STRVAR(uname_result__doc__,
  5033. "uname_result: Result from os.uname().\n\n\
  5034. This object may be accessed either as a tuple of\n\
  5035. (sysname, nodename, release, version, machine),\n\
  5036. or via the attributes sysname, nodename, release, version, and machine.\n\
  5037. \n\
  5038. See os.uname for more information.");
  5039. static PyStructSequence_Desc uname_result_desc = {
  5040. MODNAME ".uname_result", /* name */
  5041. uname_result__doc__, /* doc */
  5042. uname_result_fields,
  5043. 5
  5044. };
  5045. #ifdef HAVE_UNAME
  5046. /*[clinic input]
  5047. os.uname
  5048. Return an object identifying the current operating system.
  5049. The object behaves like a named tuple with the following fields:
  5050. (sysname, nodename, release, version, machine)
  5051. [clinic start generated code]*/
  5052. static PyObject *
  5053. os_uname_impl(PyObject *module)
  5054. /*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
  5055. {
  5056. struct utsname u;
  5057. int res;
  5058. PyObject *value;
  5059. Py_BEGIN_ALLOW_THREADS
  5060. res = uname(&u);
  5061. Py_END_ALLOW_THREADS
  5062. if (res < 0)
  5063. return posix_error();
  5064. PyObject *UnameResultType = get_posix_state(module)->UnameResultType;
  5065. value = PyStructSequence_New((PyTypeObject *)UnameResultType);
  5066. if (value == NULL)
  5067. return NULL;
  5068. #define SET(i, field) \
  5069. { \
  5070. PyObject *o = PyUnicode_DecodeFSDefault(field); \
  5071. if (!o) { \
  5072. Py_DECREF(value); \
  5073. return NULL; \
  5074. } \
  5075. PyStructSequence_SET_ITEM(value, i, o); \
  5076. } \
  5077. SET(0, u.sysname);
  5078. SET(1, u.nodename);
  5079. SET(2, u.release);
  5080. SET(3, u.version);
  5081. SET(4, u.machine);
  5082. #undef SET
  5083. return value;
  5084. }
  5085. #endif /* HAVE_UNAME */
  5086. typedef struct {
  5087. int now;
  5088. time_t atime_s;
  5089. long atime_ns;
  5090. time_t mtime_s;
  5091. long mtime_ns;
  5092. } utime_t;
  5093. /*
  5094. * these macros assume that "ut" is a pointer to a utime_t
  5095. * they also intentionally leak the declaration of a pointer named "time"
  5096. */
  5097. #define UTIME_TO_TIMESPEC \
  5098. struct timespec ts[2]; \
  5099. struct timespec *time; \
  5100. if (ut->now) \
  5101. time = NULL; \
  5102. else { \
  5103. ts[0].tv_sec = ut->atime_s; \
  5104. ts[0].tv_nsec = ut->atime_ns; \
  5105. ts[1].tv_sec = ut->mtime_s; \
  5106. ts[1].tv_nsec = ut->mtime_ns; \
  5107. time = ts; \
  5108. } \
  5109. #define UTIME_TO_TIMEVAL \
  5110. struct timeval tv[2]; \
  5111. struct timeval *time; \
  5112. if (ut->now) \
  5113. time = NULL; \
  5114. else { \
  5115. tv[0].tv_sec = ut->atime_s; \
  5116. tv[0].tv_usec = ut->atime_ns / 1000; \
  5117. tv[1].tv_sec = ut->mtime_s; \
  5118. tv[1].tv_usec = ut->mtime_ns / 1000; \
  5119. time = tv; \
  5120. } \
  5121. #define UTIME_TO_UTIMBUF \
  5122. struct utimbuf u; \
  5123. struct utimbuf *time; \
  5124. if (ut->now) \
  5125. time = NULL; \
  5126. else { \
  5127. u.actime = ut->atime_s; \
  5128. u.modtime = ut->mtime_s; \
  5129. time = &u; \
  5130. }
  5131. #define UTIME_TO_TIME_T \
  5132. time_t timet[2]; \
  5133. time_t *time; \
  5134. if (ut->now) \
  5135. time = NULL; \
  5136. else { \
  5137. timet[0] = ut->atime_s; \
  5138. timet[1] = ut->mtime_s; \
  5139. time = timet; \
  5140. } \
  5141. #if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
  5142. static int
  5143. utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
  5144. {
  5145. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5146. if (HAVE_UTIMENSAT_RUNTIME) {
  5147. int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
  5148. UTIME_TO_TIMESPEC;
  5149. return utimensat(dir_fd, path, time, flags);
  5150. } else {
  5151. errno = ENOSYS;
  5152. return -1;
  5153. }
  5154. #elif defined(HAVE_UTIMENSAT)
  5155. int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
  5156. UTIME_TO_TIMESPEC;
  5157. return utimensat(dir_fd, path, time, flags);
  5158. #elif defined(HAVE_FUTIMESAT)
  5159. UTIME_TO_TIMEVAL;
  5160. /*
  5161. * follow_symlinks will never be false here;
  5162. * we only allow !follow_symlinks and dir_fd together
  5163. * if we have utimensat()
  5164. */
  5165. assert(follow_symlinks);
  5166. return futimesat(dir_fd, path, time);
  5167. #endif
  5168. }
  5169. #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
  5170. #else
  5171. #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
  5172. #endif
  5173. #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
  5174. static int
  5175. utime_fd(utime_t *ut, int fd)
  5176. {
  5177. #ifdef HAVE_FUTIMENS
  5178. if (HAVE_FUTIMENS_RUNTIME) {
  5179. UTIME_TO_TIMESPEC;
  5180. return futimens(fd, time);
  5181. } else
  5182. #ifndef HAVE_FUTIMES
  5183. {
  5184. /* Not sure if this can happen */
  5185. PyErr_SetString(
  5186. PyExc_RuntimeError,
  5187. "neither futimens nor futimes are supported"
  5188. " on this system");
  5189. return -1;
  5190. }
  5191. #endif
  5192. #endif
  5193. #ifdef HAVE_FUTIMES
  5194. {
  5195. UTIME_TO_TIMEVAL;
  5196. return futimes(fd, time);
  5197. }
  5198. #endif
  5199. }
  5200. #define PATH_UTIME_HAVE_FD 1
  5201. #else
  5202. #define PATH_UTIME_HAVE_FD 0
  5203. #endif
  5204. #if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
  5205. # define UTIME_HAVE_NOFOLLOW_SYMLINKS
  5206. #endif
  5207. #ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
  5208. static int
  5209. utime_nofollow_symlinks(utime_t *ut, const char *path)
  5210. {
  5211. #ifdef HAVE_UTIMENSAT
  5212. if (HAVE_UTIMENSAT_RUNTIME) {
  5213. UTIME_TO_TIMESPEC;
  5214. return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
  5215. } else
  5216. #ifndef HAVE_LUTIMES
  5217. {
  5218. /* Not sure if this can happen */
  5219. PyErr_SetString(
  5220. PyExc_RuntimeError,
  5221. "neither utimensat nor lutimes are supported"
  5222. " on this system");
  5223. return -1;
  5224. }
  5225. #endif
  5226. #endif
  5227. #ifdef HAVE_LUTIMES
  5228. {
  5229. UTIME_TO_TIMEVAL;
  5230. return lutimes(path, time);
  5231. }
  5232. #endif
  5233. }
  5234. #endif
  5235. #ifndef MS_WINDOWS
  5236. static int
  5237. utime_default(utime_t *ut, const char *path)
  5238. {
  5239. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5240. if (HAVE_UTIMENSAT_RUNTIME) {
  5241. UTIME_TO_TIMESPEC;
  5242. return utimensat(DEFAULT_DIR_FD, path, time, 0);
  5243. } else {
  5244. UTIME_TO_TIMEVAL;
  5245. return utimes(path, time);
  5246. }
  5247. #elif defined(HAVE_UTIMENSAT)
  5248. UTIME_TO_TIMESPEC;
  5249. return utimensat(DEFAULT_DIR_FD, path, time, 0);
  5250. #elif defined(HAVE_UTIMES)
  5251. UTIME_TO_TIMEVAL;
  5252. return utimes(path, time);
  5253. #elif defined(HAVE_UTIME_H)
  5254. UTIME_TO_UTIMBUF;
  5255. return utime(path, time);
  5256. #else
  5257. UTIME_TO_TIME_T;
  5258. return utime(path, time);
  5259. #endif
  5260. }
  5261. #endif
  5262. static int
  5263. split_py_long_to_s_and_ns(PyObject *module, PyObject *py_long, time_t *s, long *ns)
  5264. {
  5265. int result = 0;
  5266. PyObject *divmod;
  5267. divmod = PyNumber_Divmod(py_long, get_posix_state(module)->billion);
  5268. if (!divmod)
  5269. goto exit;
  5270. if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
  5271. PyErr_Format(PyExc_TypeError,
  5272. "%.200s.__divmod__() must return a 2-tuple, not %.200s",
  5273. _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
  5274. goto exit;
  5275. }
  5276. *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
  5277. if ((*s == -1) && PyErr_Occurred())
  5278. goto exit;
  5279. *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
  5280. if ((*ns == -1) && PyErr_Occurred())
  5281. goto exit;
  5282. result = 1;
  5283. exit:
  5284. Py_XDECREF(divmod);
  5285. return result;
  5286. }
  5287. /*[clinic input]
  5288. os.utime
  5289. path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
  5290. times: object = None
  5291. *
  5292. ns: object = NULL
  5293. dir_fd: dir_fd(requires='futimensat') = None
  5294. follow_symlinks: bool=True
  5295. # "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
  5296. Set the access and modified time of path.
  5297. path may always be specified as a string.
  5298. On some platforms, path may also be specified as an open file descriptor.
  5299. If this functionality is unavailable, using it raises an exception.
  5300. If times is not None, it must be a tuple (atime, mtime);
  5301. atime and mtime should be expressed as float seconds since the epoch.
  5302. If ns is specified, it must be a tuple (atime_ns, mtime_ns);
  5303. atime_ns and mtime_ns should be expressed as integer nanoseconds
  5304. since the epoch.
  5305. If times is None and ns is unspecified, utime uses the current time.
  5306. Specifying tuples for both times and ns is an error.
  5307. If dir_fd is not None, it should be a file descriptor open to a directory,
  5308. and path should be relative; path will then be relative to that directory.
  5309. If follow_symlinks is False, and the last element of the path is a symbolic
  5310. link, utime will modify the symbolic link itself instead of the file the
  5311. link points to.
  5312. It is an error to use dir_fd or follow_symlinks when specifying path
  5313. as an open file descriptor.
  5314. dir_fd and follow_symlinks may not be available on your platform.
  5315. If they are unavailable, using them will raise a NotImplementedError.
  5316. [clinic start generated code]*/
  5317. static PyObject *
  5318. os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
  5319. int dir_fd, int follow_symlinks)
  5320. /*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
  5321. {
  5322. #ifdef MS_WINDOWS
  5323. HANDLE hFile;
  5324. FILETIME atime, mtime;
  5325. #else
  5326. int result;
  5327. #endif
  5328. utime_t utime;
  5329. memset(&utime, 0, sizeof(utime_t));
  5330. if (times != Py_None && ns) {
  5331. PyErr_SetString(PyExc_ValueError,
  5332. "utime: you may specify either 'times'"
  5333. " or 'ns' but not both");
  5334. return NULL;
  5335. }
  5336. if (times != Py_None) {
  5337. time_t a_sec, m_sec;
  5338. long a_nsec, m_nsec;
  5339. if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
  5340. PyErr_SetString(PyExc_TypeError,
  5341. "utime: 'times' must be either"
  5342. " a tuple of two ints or None");
  5343. return NULL;
  5344. }
  5345. utime.now = 0;
  5346. if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
  5347. &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
  5348. _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
  5349. &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
  5350. return NULL;
  5351. }
  5352. utime.atime_s = a_sec;
  5353. utime.atime_ns = a_nsec;
  5354. utime.mtime_s = m_sec;
  5355. utime.mtime_ns = m_nsec;
  5356. }
  5357. else if (ns) {
  5358. if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
  5359. PyErr_SetString(PyExc_TypeError,
  5360. "utime: 'ns' must be a tuple of two ints");
  5361. return NULL;
  5362. }
  5363. utime.now = 0;
  5364. if (!split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 0),
  5365. &utime.atime_s, &utime.atime_ns) ||
  5366. !split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 1),
  5367. &utime.mtime_s, &utime.mtime_ns)) {
  5368. return NULL;
  5369. }
  5370. }
  5371. else {
  5372. /* times and ns are both None/unspecified. use "now". */
  5373. utime.now = 1;
  5374. }
  5375. #if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
  5376. if (follow_symlinks_specified("utime", follow_symlinks))
  5377. return NULL;
  5378. #endif
  5379. if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
  5380. dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
  5381. fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
  5382. return NULL;
  5383. #if !defined(HAVE_UTIMENSAT)
  5384. if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
  5385. PyErr_SetString(PyExc_ValueError,
  5386. "utime: cannot use dir_fd and follow_symlinks "
  5387. "together on this platform");
  5388. return NULL;
  5389. }
  5390. #endif
  5391. if (PySys_Audit("os.utime", "OOOi", path->object, times, ns ? ns : Py_None,
  5392. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  5393. return NULL;
  5394. }
  5395. #ifdef MS_WINDOWS
  5396. Py_BEGIN_ALLOW_THREADS
  5397. hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
  5398. NULL, OPEN_EXISTING,
  5399. FILE_FLAG_BACKUP_SEMANTICS, NULL);
  5400. Py_END_ALLOW_THREADS
  5401. if (hFile == INVALID_HANDLE_VALUE) {
  5402. path_error(path);
  5403. return NULL;
  5404. }
  5405. if (utime.now) {
  5406. GetSystemTimeAsFileTime(&mtime);
  5407. atime = mtime;
  5408. }
  5409. else {
  5410. _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
  5411. _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
  5412. }
  5413. if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
  5414. /* Avoid putting the file name into the error here,
  5415. as that may confuse the user into believing that
  5416. something is wrong with the file, when it also
  5417. could be the time stamp that gives a problem. */
  5418. PyErr_SetFromWindowsErr(0);
  5419. CloseHandle(hFile);
  5420. return NULL;
  5421. }
  5422. CloseHandle(hFile);
  5423. #else /* MS_WINDOWS */
  5424. Py_BEGIN_ALLOW_THREADS
  5425. #ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
  5426. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  5427. result = utime_nofollow_symlinks(&utime, path->narrow);
  5428. else
  5429. #endif
  5430. #if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
  5431. if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks)) {
  5432. result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
  5433. } else
  5434. #endif
  5435. #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
  5436. if (path->fd != -1)
  5437. result = utime_fd(&utime, path->fd);
  5438. else
  5439. #endif
  5440. result = utime_default(&utime, path->narrow);
  5441. Py_END_ALLOW_THREADS
  5442. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5443. /* See utime_dir_fd implementation */
  5444. if (result == -1 && errno == ENOSYS) {
  5445. argument_unavailable_error(NULL, "dir_fd");
  5446. return NULL;
  5447. }
  5448. #endif
  5449. if (result < 0) {
  5450. /* see previous comment about not putting filename in error here */
  5451. posix_error();
  5452. return NULL;
  5453. }
  5454. #endif /* MS_WINDOWS */
  5455. Py_RETURN_NONE;
  5456. }
  5457. /* Process operations */
  5458. /*[clinic input]
  5459. os._exit
  5460. status: int
  5461. Exit to the system with specified status, without normal exit processing.
  5462. [clinic start generated code]*/
  5463. static PyObject *
  5464. os__exit_impl(PyObject *module, int status)
  5465. /*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
  5466. {
  5467. _exit(status);
  5468. return NULL; /* Make gcc -Wall happy */
  5469. }
  5470. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5471. #define EXECV_CHAR wchar_t
  5472. #else
  5473. #define EXECV_CHAR char
  5474. #endif
  5475. #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
  5476. static void
  5477. free_string_array(EXECV_CHAR **array, Py_ssize_t count)
  5478. {
  5479. Py_ssize_t i;
  5480. for (i = 0; i < count; i++)
  5481. PyMem_Free(array[i]);
  5482. PyMem_Free(array);
  5483. }
  5484. static int
  5485. fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
  5486. {
  5487. Py_ssize_t size;
  5488. PyObject *ub;
  5489. int result = 0;
  5490. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5491. if (!PyUnicode_FSDecoder(o, &ub))
  5492. return 0;
  5493. *out = PyUnicode_AsWideCharString(ub, &size);
  5494. if (*out)
  5495. result = 1;
  5496. #else
  5497. if (!PyUnicode_FSConverter(o, &ub))
  5498. return 0;
  5499. size = PyBytes_GET_SIZE(ub);
  5500. *out = PyMem_Malloc(size + 1);
  5501. if (*out) {
  5502. memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
  5503. result = 1;
  5504. } else
  5505. PyErr_NoMemory();
  5506. #endif
  5507. Py_DECREF(ub);
  5508. return result;
  5509. }
  5510. #endif
  5511. #if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
  5512. static EXECV_CHAR**
  5513. parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
  5514. {
  5515. Py_ssize_t i, pos, envc;
  5516. PyObject *keys=NULL, *vals=NULL;
  5517. PyObject *key2, *val2, *keyval;
  5518. EXECV_CHAR **envlist;
  5519. i = PyMapping_Size(env);
  5520. if (i < 0)
  5521. return NULL;
  5522. envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
  5523. if (envlist == NULL) {
  5524. PyErr_NoMemory();
  5525. return NULL;
  5526. }
  5527. envc = 0;
  5528. keys = PyMapping_Keys(env);
  5529. if (!keys)
  5530. goto error;
  5531. vals = PyMapping_Values(env);
  5532. if (!vals)
  5533. goto error;
  5534. if (!PyList_Check(keys) || !PyList_Check(vals)) {
  5535. PyErr_Format(PyExc_TypeError,
  5536. "env.keys() or env.values() is not a list");
  5537. goto error;
  5538. }
  5539. for (pos = 0; pos < i; pos++) {
  5540. PyObject *key = PyList_GetItem(keys, pos); // Borrowed ref.
  5541. if (key == NULL) {
  5542. goto error;
  5543. }
  5544. PyObject *val = PyList_GetItem(vals, pos); // Borrowed ref.
  5545. if (val == NULL) {
  5546. goto error;
  5547. }
  5548. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5549. if (!PyUnicode_FSDecoder(key, &key2))
  5550. goto error;
  5551. if (!PyUnicode_FSDecoder(val, &val2)) {
  5552. Py_DECREF(key2);
  5553. goto error;
  5554. }
  5555. /* Search from index 1 because on Windows starting '=' is allowed for
  5556. defining hidden environment variables. */
  5557. if (PyUnicode_GET_LENGTH(key2) == 0 ||
  5558. PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
  5559. {
  5560. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  5561. Py_DECREF(key2);
  5562. Py_DECREF(val2);
  5563. goto error;
  5564. }
  5565. keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
  5566. #else
  5567. if (!PyUnicode_FSConverter(key, &key2))
  5568. goto error;
  5569. if (!PyUnicode_FSConverter(val, &val2)) {
  5570. Py_DECREF(key2);
  5571. goto error;
  5572. }
  5573. if (PyBytes_GET_SIZE(key2) == 0 ||
  5574. strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
  5575. {
  5576. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  5577. Py_DECREF(key2);
  5578. Py_DECREF(val2);
  5579. goto error;
  5580. }
  5581. keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
  5582. PyBytes_AS_STRING(val2));
  5583. #endif
  5584. Py_DECREF(key2);
  5585. Py_DECREF(val2);
  5586. if (!keyval)
  5587. goto error;
  5588. if (!fsconvert_strdup(keyval, &envlist[envc++])) {
  5589. Py_DECREF(keyval);
  5590. goto error;
  5591. }
  5592. Py_DECREF(keyval);
  5593. }
  5594. Py_DECREF(vals);
  5595. Py_DECREF(keys);
  5596. envlist[envc] = 0;
  5597. *envc_ptr = envc;
  5598. return envlist;
  5599. error:
  5600. Py_XDECREF(keys);
  5601. Py_XDECREF(vals);
  5602. free_string_array(envlist, envc);
  5603. return NULL;
  5604. }
  5605. static EXECV_CHAR**
  5606. parse_arglist(PyObject* argv, Py_ssize_t *argc)
  5607. {
  5608. int i;
  5609. EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
  5610. if (argvlist == NULL) {
  5611. PyErr_NoMemory();
  5612. return NULL;
  5613. }
  5614. for (i = 0; i < *argc; i++) {
  5615. PyObject* item = PySequence_ITEM(argv, i);
  5616. if (item == NULL)
  5617. goto fail;
  5618. if (!fsconvert_strdup(item, &argvlist[i])) {
  5619. Py_DECREF(item);
  5620. goto fail;
  5621. }
  5622. Py_DECREF(item);
  5623. }
  5624. argvlist[*argc] = NULL;
  5625. return argvlist;
  5626. fail:
  5627. *argc = i;
  5628. free_string_array(argvlist, *argc);
  5629. return NULL;
  5630. }
  5631. #endif
  5632. #ifdef HAVE_EXECV
  5633. /*[clinic input]
  5634. os.execv
  5635. path: path_t
  5636. Path of executable file.
  5637. argv: object
  5638. Tuple or list of strings.
  5639. /
  5640. Execute an executable path with arguments, replacing current process.
  5641. [clinic start generated code]*/
  5642. static PyObject *
  5643. os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
  5644. /*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
  5645. {
  5646. EXECV_CHAR **argvlist;
  5647. Py_ssize_t argc;
  5648. PyInterpreterState *interp = _PyInterpreterState_GET();
  5649. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_EXEC)) {
  5650. PyErr_SetString(PyExc_RuntimeError,
  5651. "exec not supported for isolated subinterpreters");
  5652. return NULL;
  5653. }
  5654. /* execv has two arguments: (path, argv), where
  5655. argv is a list or tuple of strings. */
  5656. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  5657. PyErr_SetString(PyExc_TypeError,
  5658. "execv() arg 2 must be a tuple or list");
  5659. return NULL;
  5660. }
  5661. argc = PySequence_Size(argv);
  5662. if (argc < 1) {
  5663. PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
  5664. return NULL;
  5665. }
  5666. argvlist = parse_arglist(argv, &argc);
  5667. if (argvlist == NULL) {
  5668. return NULL;
  5669. }
  5670. if (!argvlist[0][0]) {
  5671. PyErr_SetString(PyExc_ValueError,
  5672. "execv() arg 2 first element cannot be empty");
  5673. free_string_array(argvlist, argc);
  5674. return NULL;
  5675. }
  5676. if (PySys_Audit("os.exec", "OOO", path->object, argv, Py_None) < 0) {
  5677. free_string_array(argvlist, argc);
  5678. return NULL;
  5679. }
  5680. _Py_BEGIN_SUPPRESS_IPH
  5681. #ifdef HAVE_WEXECV
  5682. _wexecv(path->wide, argvlist);
  5683. #else
  5684. execv(path->narrow, argvlist);
  5685. #endif
  5686. _Py_END_SUPPRESS_IPH
  5687. /* If we get here it's definitely an error */
  5688. posix_error();
  5689. free_string_array(argvlist, argc);
  5690. return NULL;
  5691. }
  5692. /*[clinic input]
  5693. os.execve
  5694. path: path_t(allow_fd='PATH_HAVE_FEXECVE')
  5695. Path of executable file.
  5696. argv: object
  5697. Tuple or list of strings.
  5698. env: object
  5699. Dictionary of strings mapping to strings.
  5700. Execute an executable path with arguments, replacing current process.
  5701. [clinic start generated code]*/
  5702. static PyObject *
  5703. os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
  5704. /*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
  5705. {
  5706. EXECV_CHAR **argvlist = NULL;
  5707. EXECV_CHAR **envlist;
  5708. Py_ssize_t argc, envc;
  5709. PyInterpreterState *interp = _PyInterpreterState_GET();
  5710. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_EXEC)) {
  5711. PyErr_SetString(PyExc_RuntimeError,
  5712. "exec not supported for isolated subinterpreters");
  5713. return NULL;
  5714. }
  5715. /* execve has three arguments: (path, argv, env), where
  5716. argv is a list or tuple of strings and env is a dictionary
  5717. like posix.environ. */
  5718. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  5719. PyErr_SetString(PyExc_TypeError,
  5720. "execve: argv must be a tuple or list");
  5721. goto fail_0;
  5722. }
  5723. argc = PySequence_Size(argv);
  5724. if (argc < 1) {
  5725. PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
  5726. return NULL;
  5727. }
  5728. if (!PyMapping_Check(env)) {
  5729. PyErr_SetString(PyExc_TypeError,
  5730. "execve: environment must be a mapping object");
  5731. goto fail_0;
  5732. }
  5733. argvlist = parse_arglist(argv, &argc);
  5734. if (argvlist == NULL) {
  5735. goto fail_0;
  5736. }
  5737. if (!argvlist[0][0]) {
  5738. PyErr_SetString(PyExc_ValueError,
  5739. "execve: argv first element cannot be empty");
  5740. goto fail_0;
  5741. }
  5742. envlist = parse_envlist(env, &envc);
  5743. if (envlist == NULL)
  5744. goto fail_0;
  5745. if (PySys_Audit("os.exec", "OOO", path->object, argv, env) < 0) {
  5746. goto fail_1;
  5747. }
  5748. _Py_BEGIN_SUPPRESS_IPH
  5749. #ifdef HAVE_FEXECVE
  5750. if (path->fd > -1)
  5751. fexecve(path->fd, argvlist, envlist);
  5752. else
  5753. #endif
  5754. #ifdef HAVE_WEXECV
  5755. _wexecve(path->wide, argvlist, envlist);
  5756. #else
  5757. execve(path->narrow, argvlist, envlist);
  5758. #endif
  5759. _Py_END_SUPPRESS_IPH
  5760. /* If we get here it's definitely an error */
  5761. posix_path_error(path);
  5762. fail_1:
  5763. free_string_array(envlist, envc);
  5764. fail_0:
  5765. if (argvlist)
  5766. free_string_array(argvlist, argc);
  5767. return NULL;
  5768. }
  5769. #endif /* HAVE_EXECV */
  5770. #ifdef HAVE_POSIX_SPAWN
  5771. enum posix_spawn_file_actions_identifier {
  5772. POSIX_SPAWN_OPEN,
  5773. POSIX_SPAWN_CLOSE,
  5774. POSIX_SPAWN_DUP2
  5775. };
  5776. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  5777. static int
  5778. convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res);
  5779. #endif
  5780. static int
  5781. parse_posix_spawn_flags(PyObject *module, const char *func_name, PyObject *setpgroup,
  5782. int resetids, int setsid, PyObject *setsigmask,
  5783. PyObject *setsigdef, PyObject *scheduler,
  5784. posix_spawnattr_t *attrp)
  5785. {
  5786. long all_flags = 0;
  5787. errno = posix_spawnattr_init(attrp);
  5788. if (errno) {
  5789. posix_error();
  5790. return -1;
  5791. }
  5792. if (setpgroup) {
  5793. pid_t pgid = PyLong_AsPid(setpgroup);
  5794. if (pgid == (pid_t)-1 && PyErr_Occurred()) {
  5795. goto fail;
  5796. }
  5797. errno = posix_spawnattr_setpgroup(attrp, pgid);
  5798. if (errno) {
  5799. posix_error();
  5800. goto fail;
  5801. }
  5802. all_flags |= POSIX_SPAWN_SETPGROUP;
  5803. }
  5804. if (resetids) {
  5805. all_flags |= POSIX_SPAWN_RESETIDS;
  5806. }
  5807. if (setsid) {
  5808. #ifdef HAVE_POSIX_SPAWN_SETSID_RUNTIME
  5809. if (HAVE_POSIX_SPAWN_SETSID_RUNTIME) {
  5810. #endif
  5811. #ifdef POSIX_SPAWN_SETSID
  5812. all_flags |= POSIX_SPAWN_SETSID;
  5813. #elif defined(POSIX_SPAWN_SETSID_NP)
  5814. all_flags |= POSIX_SPAWN_SETSID_NP;
  5815. #else
  5816. argument_unavailable_error(func_name, "setsid");
  5817. return -1;
  5818. #endif
  5819. #ifdef HAVE_POSIX_SPAWN_SETSID_RUNTIME
  5820. } else {
  5821. argument_unavailable_error(func_name, "setsid");
  5822. return -1;
  5823. }
  5824. #endif /* HAVE_POSIX_SPAWN_SETSID_RUNTIME */
  5825. }
  5826. #ifdef HAVE_SIGSET_T
  5827. if (setsigmask) {
  5828. sigset_t set;
  5829. if (!_Py_Sigset_Converter(setsigmask, &set)) {
  5830. goto fail;
  5831. }
  5832. errno = posix_spawnattr_setsigmask(attrp, &set);
  5833. if (errno) {
  5834. posix_error();
  5835. goto fail;
  5836. }
  5837. all_flags |= POSIX_SPAWN_SETSIGMASK;
  5838. }
  5839. if (setsigdef) {
  5840. sigset_t set;
  5841. if (!_Py_Sigset_Converter(setsigdef, &set)) {
  5842. goto fail;
  5843. }
  5844. errno = posix_spawnattr_setsigdefault(attrp, &set);
  5845. if (errno) {
  5846. posix_error();
  5847. goto fail;
  5848. }
  5849. all_flags |= POSIX_SPAWN_SETSIGDEF;
  5850. }
  5851. #else
  5852. if (setsigmask || setsigdef) {
  5853. PyErr_SetString(PyExc_NotImplementedError,
  5854. "sigset is not supported on this platform");
  5855. goto fail;
  5856. }
  5857. #endif
  5858. if (scheduler) {
  5859. #ifdef POSIX_SPAWN_SETSCHEDULER
  5860. PyObject *py_schedpolicy;
  5861. PyObject *schedparam_obj;
  5862. struct sched_param schedparam;
  5863. if (!PyArg_ParseTuple(scheduler, "OO"
  5864. ";A scheduler tuple must have two elements",
  5865. &py_schedpolicy, &schedparam_obj)) {
  5866. goto fail;
  5867. }
  5868. if (!convert_sched_param(module, schedparam_obj, &schedparam)) {
  5869. goto fail;
  5870. }
  5871. if (py_schedpolicy != Py_None) {
  5872. int schedpolicy = _PyLong_AsInt(py_schedpolicy);
  5873. if (schedpolicy == -1 && PyErr_Occurred()) {
  5874. goto fail;
  5875. }
  5876. errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
  5877. if (errno) {
  5878. posix_error();
  5879. goto fail;
  5880. }
  5881. all_flags |= POSIX_SPAWN_SETSCHEDULER;
  5882. }
  5883. errno = posix_spawnattr_setschedparam(attrp, &schedparam);
  5884. if (errno) {
  5885. posix_error();
  5886. goto fail;
  5887. }
  5888. all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
  5889. #else
  5890. PyErr_SetString(PyExc_NotImplementedError,
  5891. "The scheduler option is not supported in this system.");
  5892. goto fail;
  5893. #endif
  5894. }
  5895. errno = posix_spawnattr_setflags(attrp, all_flags);
  5896. if (errno) {
  5897. posix_error();
  5898. goto fail;
  5899. }
  5900. return 0;
  5901. fail:
  5902. (void)posix_spawnattr_destroy(attrp);
  5903. return -1;
  5904. }
  5905. static int
  5906. parse_file_actions(PyObject *file_actions,
  5907. posix_spawn_file_actions_t *file_actionsp,
  5908. PyObject *temp_buffer)
  5909. {
  5910. PyObject *seq;
  5911. PyObject *file_action = NULL;
  5912. PyObject *tag_obj;
  5913. seq = PySequence_Fast(file_actions,
  5914. "file_actions must be a sequence or None");
  5915. if (seq == NULL) {
  5916. return -1;
  5917. }
  5918. errno = posix_spawn_file_actions_init(file_actionsp);
  5919. if (errno) {
  5920. posix_error();
  5921. Py_DECREF(seq);
  5922. return -1;
  5923. }
  5924. for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
  5925. file_action = PySequence_Fast_GET_ITEM(seq, i);
  5926. Py_INCREF(file_action);
  5927. if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
  5928. PyErr_SetString(PyExc_TypeError,
  5929. "Each file_actions element must be a non-empty tuple");
  5930. goto fail;
  5931. }
  5932. long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
  5933. if (tag == -1 && PyErr_Occurred()) {
  5934. goto fail;
  5935. }
  5936. /* Populate the file_actions object */
  5937. switch (tag) {
  5938. case POSIX_SPAWN_OPEN: {
  5939. int fd, oflag;
  5940. PyObject *path;
  5941. unsigned long mode;
  5942. if (!PyArg_ParseTuple(file_action, "OiO&ik"
  5943. ";A open file_action tuple must have 5 elements",
  5944. &tag_obj, &fd, PyUnicode_FSConverter, &path,
  5945. &oflag, &mode))
  5946. {
  5947. goto fail;
  5948. }
  5949. if (PyList_Append(temp_buffer, path)) {
  5950. Py_DECREF(path);
  5951. goto fail;
  5952. }
  5953. errno = posix_spawn_file_actions_addopen(file_actionsp,
  5954. fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
  5955. if (errno) {
  5956. posix_error();
  5957. Py_DECREF(path);
  5958. goto fail;
  5959. }
  5960. Py_DECREF(path);
  5961. break;
  5962. }
  5963. case POSIX_SPAWN_CLOSE: {
  5964. int fd;
  5965. if (!PyArg_ParseTuple(file_action, "Oi"
  5966. ";A close file_action tuple must have 2 elements",
  5967. &tag_obj, &fd))
  5968. {
  5969. goto fail;
  5970. }
  5971. errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
  5972. if (errno) {
  5973. posix_error();
  5974. goto fail;
  5975. }
  5976. break;
  5977. }
  5978. case POSIX_SPAWN_DUP2: {
  5979. int fd1, fd2;
  5980. if (!PyArg_ParseTuple(file_action, "Oii"
  5981. ";A dup2 file_action tuple must have 3 elements",
  5982. &tag_obj, &fd1, &fd2))
  5983. {
  5984. goto fail;
  5985. }
  5986. errno = posix_spawn_file_actions_adddup2(file_actionsp,
  5987. fd1, fd2);
  5988. if (errno) {
  5989. posix_error();
  5990. goto fail;
  5991. }
  5992. break;
  5993. }
  5994. default: {
  5995. PyErr_SetString(PyExc_TypeError,
  5996. "Unknown file_actions identifier");
  5997. goto fail;
  5998. }
  5999. }
  6000. Py_DECREF(file_action);
  6001. }
  6002. Py_DECREF(seq);
  6003. return 0;
  6004. fail:
  6005. Py_DECREF(seq);
  6006. Py_DECREF(file_action);
  6007. (void)posix_spawn_file_actions_destroy(file_actionsp);
  6008. return -1;
  6009. }
  6010. static PyObject *
  6011. py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
  6012. PyObject *env, PyObject *file_actions,
  6013. PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
  6014. PyObject *setsigdef, PyObject *scheduler)
  6015. {
  6016. const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
  6017. EXECV_CHAR **argvlist = NULL;
  6018. EXECV_CHAR **envlist = NULL;
  6019. posix_spawn_file_actions_t file_actions_buf;
  6020. posix_spawn_file_actions_t *file_actionsp = NULL;
  6021. posix_spawnattr_t attr;
  6022. posix_spawnattr_t *attrp = NULL;
  6023. Py_ssize_t argc, envc;
  6024. PyObject *result = NULL;
  6025. PyObject *temp_buffer = NULL;
  6026. pid_t pid;
  6027. int err_code;
  6028. /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
  6029. argv is a list or tuple of strings and env is a dictionary
  6030. like posix.environ. */
  6031. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  6032. PyErr_Format(PyExc_TypeError,
  6033. "%s: argv must be a tuple or list", func_name);
  6034. goto exit;
  6035. }
  6036. argc = PySequence_Size(argv);
  6037. if (argc < 1) {
  6038. PyErr_Format(PyExc_ValueError,
  6039. "%s: argv must not be empty", func_name);
  6040. return NULL;
  6041. }
  6042. if (!PyMapping_Check(env)) {
  6043. PyErr_Format(PyExc_TypeError,
  6044. "%s: environment must be a mapping object", func_name);
  6045. goto exit;
  6046. }
  6047. argvlist = parse_arglist(argv, &argc);
  6048. if (argvlist == NULL) {
  6049. goto exit;
  6050. }
  6051. if (!argvlist[0][0]) {
  6052. PyErr_Format(PyExc_ValueError,
  6053. "%s: argv first element cannot be empty", func_name);
  6054. goto exit;
  6055. }
  6056. envlist = parse_envlist(env, &envc);
  6057. if (envlist == NULL) {
  6058. goto exit;
  6059. }
  6060. if (file_actions != NULL && file_actions != Py_None) {
  6061. /* There is a bug in old versions of glibc that makes some of the
  6062. * helper functions for manipulating file actions not copy the provided
  6063. * buffers. The problem is that posix_spawn_file_actions_addopen does not
  6064. * copy the value of path for some old versions of glibc (<2.20).
  6065. * The use of temp_buffer here is a workaround that keeps the
  6066. * python objects that own the buffers alive until posix_spawn gets called.
  6067. * Check https://bugs.python.org/issue33630 and
  6068. * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
  6069. temp_buffer = PyList_New(0);
  6070. if (!temp_buffer) {
  6071. goto exit;
  6072. }
  6073. if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
  6074. goto exit;
  6075. }
  6076. file_actionsp = &file_actions_buf;
  6077. }
  6078. if (parse_posix_spawn_flags(module, func_name, setpgroup, resetids, setsid,
  6079. setsigmask, setsigdef, scheduler, &attr)) {
  6080. goto exit;
  6081. }
  6082. attrp = &attr;
  6083. if (PySys_Audit("os.posix_spawn", "OOO", path->object, argv, env) < 0) {
  6084. goto exit;
  6085. }
  6086. _Py_BEGIN_SUPPRESS_IPH
  6087. #ifdef HAVE_POSIX_SPAWNP
  6088. if (use_posix_spawnp) {
  6089. err_code = posix_spawnp(&pid, path->narrow,
  6090. file_actionsp, attrp, argvlist, envlist);
  6091. }
  6092. else
  6093. #endif /* HAVE_POSIX_SPAWNP */
  6094. {
  6095. err_code = posix_spawn(&pid, path->narrow,
  6096. file_actionsp, attrp, argvlist, envlist);
  6097. }
  6098. _Py_END_SUPPRESS_IPH
  6099. if (err_code) {
  6100. errno = err_code;
  6101. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
  6102. goto exit;
  6103. }
  6104. #ifdef _Py_MEMORY_SANITIZER
  6105. __msan_unpoison(&pid, sizeof(pid));
  6106. #endif
  6107. result = PyLong_FromPid(pid);
  6108. exit:
  6109. if (file_actionsp) {
  6110. (void)posix_spawn_file_actions_destroy(file_actionsp);
  6111. }
  6112. if (attrp) {
  6113. (void)posix_spawnattr_destroy(attrp);
  6114. }
  6115. if (envlist) {
  6116. free_string_array(envlist, envc);
  6117. }
  6118. if (argvlist) {
  6119. free_string_array(argvlist, argc);
  6120. }
  6121. Py_XDECREF(temp_buffer);
  6122. return result;
  6123. }
  6124. /*[clinic input]
  6125. os.posix_spawn
  6126. path: path_t
  6127. Path of executable file.
  6128. argv: object
  6129. Tuple or list of strings.
  6130. env: object
  6131. Dictionary of strings mapping to strings.
  6132. /
  6133. *
  6134. file_actions: object(c_default='NULL') = ()
  6135. A sequence of file action tuples.
  6136. setpgroup: object = NULL
  6137. The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
  6138. resetids: bool = False
  6139. If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
  6140. setsid: bool = False
  6141. If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
  6142. setsigmask: object(c_default='NULL') = ()
  6143. The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
  6144. setsigdef: object(c_default='NULL') = ()
  6145. The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
  6146. scheduler: object = NULL
  6147. A tuple with the scheduler policy (optional) and parameters.
  6148. Execute the program specified by path in a new process.
  6149. [clinic start generated code]*/
  6150. static PyObject *
  6151. os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
  6152. PyObject *env, PyObject *file_actions,
  6153. PyObject *setpgroup, int resetids, int setsid,
  6154. PyObject *setsigmask, PyObject *setsigdef,
  6155. PyObject *scheduler)
  6156. /*[clinic end generated code: output=14a1098c566bc675 input=808aed1090d84e33]*/
  6157. {
  6158. return py_posix_spawn(0, module, path, argv, env, file_actions,
  6159. setpgroup, resetids, setsid, setsigmask, setsigdef,
  6160. scheduler);
  6161. }
  6162. #endif /* HAVE_POSIX_SPAWN */
  6163. #ifdef HAVE_POSIX_SPAWNP
  6164. /*[clinic input]
  6165. os.posix_spawnp
  6166. path: path_t
  6167. Path of executable file.
  6168. argv: object
  6169. Tuple or list of strings.
  6170. env: object
  6171. Dictionary of strings mapping to strings.
  6172. /
  6173. *
  6174. file_actions: object(c_default='NULL') = ()
  6175. A sequence of file action tuples.
  6176. setpgroup: object = NULL
  6177. The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
  6178. resetids: bool = False
  6179. If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
  6180. setsid: bool = False
  6181. If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
  6182. setsigmask: object(c_default='NULL') = ()
  6183. The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
  6184. setsigdef: object(c_default='NULL') = ()
  6185. The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
  6186. scheduler: object = NULL
  6187. A tuple with the scheduler policy (optional) and parameters.
  6188. Execute the program specified by path in a new process.
  6189. [clinic start generated code]*/
  6190. static PyObject *
  6191. os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
  6192. PyObject *env, PyObject *file_actions,
  6193. PyObject *setpgroup, int resetids, int setsid,
  6194. PyObject *setsigmask, PyObject *setsigdef,
  6195. PyObject *scheduler)
  6196. /*[clinic end generated code: output=7b9aaefe3031238d input=9e89e616116752a1]*/
  6197. {
  6198. return py_posix_spawn(1, module, path, argv, env, file_actions,
  6199. setpgroup, resetids, setsid, setsigmask, setsigdef,
  6200. scheduler);
  6201. }
  6202. #endif /* HAVE_POSIX_SPAWNP */
  6203. #ifdef HAVE_RTPSPAWN
  6204. static intptr_t
  6205. _rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
  6206. const char *envp[])
  6207. {
  6208. RTP_ID rtpid;
  6209. int status;
  6210. pid_t res;
  6211. int async_err = 0;
  6212. /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
  6213. uStackSize=0 cannot be used, the default stack size is too small for
  6214. Python. */
  6215. if (envp) {
  6216. rtpid = rtpSpawn(rtpFileName, argv, envp,
  6217. 100, 0x1000000, 0, VX_FP_TASK);
  6218. }
  6219. else {
  6220. rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
  6221. 100, 0x1000000, 0, VX_FP_TASK);
  6222. }
  6223. if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
  6224. do {
  6225. res = waitpid((pid_t)rtpid, &status, 0);
  6226. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  6227. if (res < 0)
  6228. return RTP_ID_ERROR;
  6229. return ((intptr_t)status);
  6230. }
  6231. return ((intptr_t)rtpid);
  6232. }
  6233. #endif
  6234. #if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
  6235. /*[clinic input]
  6236. os.spawnv
  6237. mode: int
  6238. Mode of process creation.
  6239. path: path_t
  6240. Path of executable file.
  6241. argv: object
  6242. Tuple or list of strings.
  6243. /
  6244. Execute the program specified by path in a new process.
  6245. [clinic start generated code]*/
  6246. static PyObject *
  6247. os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
  6248. /*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
  6249. {
  6250. EXECV_CHAR **argvlist;
  6251. int i;
  6252. Py_ssize_t argc;
  6253. intptr_t spawnval;
  6254. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  6255. /* spawnv has three arguments: (mode, path, argv), where
  6256. argv is a list or tuple of strings. */
  6257. if (PyList_Check(argv)) {
  6258. argc = PyList_Size(argv);
  6259. getitem = PyList_GetItem;
  6260. }
  6261. else if (PyTuple_Check(argv)) {
  6262. argc = PyTuple_Size(argv);
  6263. getitem = PyTuple_GetItem;
  6264. }
  6265. else {
  6266. PyErr_SetString(PyExc_TypeError,
  6267. "spawnv() arg 2 must be a tuple or list");
  6268. return NULL;
  6269. }
  6270. if (argc == 0) {
  6271. PyErr_SetString(PyExc_ValueError,
  6272. "spawnv() arg 2 cannot be empty");
  6273. return NULL;
  6274. }
  6275. argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
  6276. if (argvlist == NULL) {
  6277. return PyErr_NoMemory();
  6278. }
  6279. for (i = 0; i < argc; i++) {
  6280. if (!fsconvert_strdup((*getitem)(argv, i),
  6281. &argvlist[i])) {
  6282. free_string_array(argvlist, i);
  6283. PyErr_SetString(
  6284. PyExc_TypeError,
  6285. "spawnv() arg 2 must contain only strings");
  6286. return NULL;
  6287. }
  6288. if (i == 0 && !argvlist[0][0]) {
  6289. free_string_array(argvlist, i + 1);
  6290. PyErr_SetString(
  6291. PyExc_ValueError,
  6292. "spawnv() arg 2 first element cannot be empty");
  6293. return NULL;
  6294. }
  6295. }
  6296. argvlist[argc] = NULL;
  6297. #if !defined(HAVE_RTPSPAWN)
  6298. if (mode == _OLD_P_OVERLAY)
  6299. mode = _P_OVERLAY;
  6300. #endif
  6301. if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv,
  6302. Py_None) < 0) {
  6303. free_string_array(argvlist, argc);
  6304. return NULL;
  6305. }
  6306. Py_BEGIN_ALLOW_THREADS
  6307. _Py_BEGIN_SUPPRESS_IPH
  6308. #ifdef HAVE_WSPAWNV
  6309. spawnval = _wspawnv(mode, path->wide, argvlist);
  6310. #elif defined(HAVE_RTPSPAWN)
  6311. spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
  6312. #else
  6313. spawnval = _spawnv(mode, path->narrow, argvlist);
  6314. #endif
  6315. _Py_END_SUPPRESS_IPH
  6316. Py_END_ALLOW_THREADS
  6317. int saved_errno = errno;
  6318. free_string_array(argvlist, argc);
  6319. if (spawnval == -1) {
  6320. errno = saved_errno;
  6321. posix_error();
  6322. return NULL;
  6323. }
  6324. return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
  6325. }
  6326. /*[clinic input]
  6327. os.spawnve
  6328. mode: int
  6329. Mode of process creation.
  6330. path: path_t
  6331. Path of executable file.
  6332. argv: object
  6333. Tuple or list of strings.
  6334. env: object
  6335. Dictionary of strings mapping to strings.
  6336. /
  6337. Execute the program specified by path in a new process.
  6338. [clinic start generated code]*/
  6339. static PyObject *
  6340. os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
  6341. PyObject *env)
  6342. /*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
  6343. {
  6344. EXECV_CHAR **argvlist;
  6345. EXECV_CHAR **envlist;
  6346. PyObject *res = NULL;
  6347. Py_ssize_t argc, i, envc;
  6348. intptr_t spawnval;
  6349. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  6350. Py_ssize_t lastarg = 0;
  6351. /* spawnve has four arguments: (mode, path, argv, env), where
  6352. argv is a list or tuple of strings and env is a dictionary
  6353. like posix.environ. */
  6354. if (PyList_Check(argv)) {
  6355. argc = PyList_Size(argv);
  6356. getitem = PyList_GetItem;
  6357. }
  6358. else if (PyTuple_Check(argv)) {
  6359. argc = PyTuple_Size(argv);
  6360. getitem = PyTuple_GetItem;
  6361. }
  6362. else {
  6363. PyErr_SetString(PyExc_TypeError,
  6364. "spawnve() arg 2 must be a tuple or list");
  6365. goto fail_0;
  6366. }
  6367. if (argc == 0) {
  6368. PyErr_SetString(PyExc_ValueError,
  6369. "spawnve() arg 2 cannot be empty");
  6370. goto fail_0;
  6371. }
  6372. if (!PyMapping_Check(env)) {
  6373. PyErr_SetString(PyExc_TypeError,
  6374. "spawnve() arg 3 must be a mapping object");
  6375. goto fail_0;
  6376. }
  6377. argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
  6378. if (argvlist == NULL) {
  6379. PyErr_NoMemory();
  6380. goto fail_0;
  6381. }
  6382. for (i = 0; i < argc; i++) {
  6383. if (!fsconvert_strdup((*getitem)(argv, i),
  6384. &argvlist[i]))
  6385. {
  6386. lastarg = i;
  6387. goto fail_1;
  6388. }
  6389. if (i == 0 && !argvlist[0][0]) {
  6390. lastarg = i + 1;
  6391. PyErr_SetString(
  6392. PyExc_ValueError,
  6393. "spawnv() arg 2 first element cannot be empty");
  6394. goto fail_1;
  6395. }
  6396. }
  6397. lastarg = argc;
  6398. argvlist[argc] = NULL;
  6399. envlist = parse_envlist(env, &envc);
  6400. if (envlist == NULL)
  6401. goto fail_1;
  6402. #if !defined(HAVE_RTPSPAWN)
  6403. if (mode == _OLD_P_OVERLAY)
  6404. mode = _P_OVERLAY;
  6405. #endif
  6406. if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv, env) < 0) {
  6407. goto fail_2;
  6408. }
  6409. Py_BEGIN_ALLOW_THREADS
  6410. _Py_BEGIN_SUPPRESS_IPH
  6411. #ifdef HAVE_WSPAWNV
  6412. spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
  6413. #elif defined(HAVE_RTPSPAWN)
  6414. spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
  6415. (const char **)envlist);
  6416. #else
  6417. spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
  6418. #endif
  6419. _Py_END_SUPPRESS_IPH
  6420. Py_END_ALLOW_THREADS
  6421. if (spawnval == -1)
  6422. (void) posix_error();
  6423. else
  6424. res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
  6425. fail_2:
  6426. while (--envc >= 0) {
  6427. PyMem_Free(envlist[envc]);
  6428. }
  6429. PyMem_Free(envlist);
  6430. fail_1:
  6431. free_string_array(argvlist, lastarg);
  6432. fail_0:
  6433. return res;
  6434. }
  6435. #endif /* HAVE_SPAWNV */
  6436. #ifdef HAVE_FORK
  6437. /* Helper function to validate arguments.
  6438. Returns 0 on success. non-zero on failure with a TypeError raised.
  6439. If obj is non-NULL it must be callable. */
  6440. static int
  6441. check_null_or_callable(PyObject *obj, const char* obj_name)
  6442. {
  6443. if (obj && !PyCallable_Check(obj)) {
  6444. PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
  6445. obj_name, _PyType_Name(Py_TYPE(obj)));
  6446. return -1;
  6447. }
  6448. return 0;
  6449. }
  6450. /*[clinic input]
  6451. os.register_at_fork
  6452. *
  6453. before: object=NULL
  6454. A callable to be called in the parent before the fork() syscall.
  6455. after_in_child: object=NULL
  6456. A callable to be called in the child after fork().
  6457. after_in_parent: object=NULL
  6458. A callable to be called in the parent after fork().
  6459. Register callables to be called when forking a new process.
  6460. 'before' callbacks are called in reverse order.
  6461. 'after_in_child' and 'after_in_parent' callbacks are called in order.
  6462. [clinic start generated code]*/
  6463. static PyObject *
  6464. os_register_at_fork_impl(PyObject *module, PyObject *before,
  6465. PyObject *after_in_child, PyObject *after_in_parent)
  6466. /*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
  6467. {
  6468. PyInterpreterState *interp;
  6469. if (!before && !after_in_child && !after_in_parent) {
  6470. PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
  6471. return NULL;
  6472. }
  6473. if (check_null_or_callable(before, "before") ||
  6474. check_null_or_callable(after_in_child, "after_in_child") ||
  6475. check_null_or_callable(after_in_parent, "after_in_parent")) {
  6476. return NULL;
  6477. }
  6478. interp = _PyInterpreterState_GET();
  6479. if (register_at_forker(&interp->before_forkers, before)) {
  6480. return NULL;
  6481. }
  6482. if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
  6483. return NULL;
  6484. }
  6485. if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
  6486. return NULL;
  6487. }
  6488. Py_RETURN_NONE;
  6489. }
  6490. #endif /* HAVE_FORK */
  6491. // Common code to raise a warning if we detect there is more than one thread
  6492. // running in the process. Best effort, silent if unable to count threads.
  6493. // Constraint: Quick. Never overcounts. Never leaves an error set.
  6494. //
  6495. // This code might do an import, thus acquiring the import lock, which
  6496. // PyOS_BeforeFork() also does. As this should only be called from
  6497. // the parent process, it is in the same thread so that works.
  6498. static void warn_about_fork_with_threads(const char* name) {
  6499. // TODO: Consider making an `os` module API to return the current number
  6500. // of threads in the process. That'd presumably use this platform code but
  6501. // raise an error rather than using the inaccurate fallback.
  6502. Py_ssize_t num_python_threads = 0;
  6503. #if defined(__APPLE__) && defined(HAVE_GETPID)
  6504. mach_port_t macos_self = mach_task_self();
  6505. mach_port_t macos_task;
  6506. if (task_for_pid(macos_self, getpid(), &macos_task) == KERN_SUCCESS) {
  6507. thread_array_t macos_threads;
  6508. mach_msg_type_number_t macos_n_threads;
  6509. if (task_threads(macos_task, &macos_threads,
  6510. &macos_n_threads) == KERN_SUCCESS) {
  6511. num_python_threads = macos_n_threads;
  6512. }
  6513. }
  6514. #elif defined(__linux__)
  6515. // Linux /proc/self/stat 20th field is the number of threads.
  6516. FILE* proc_stat = fopen("/proc/self/stat", "r");
  6517. if (proc_stat) {
  6518. size_t n;
  6519. // Size chosen arbitrarily. ~60% more bytes than a 20th column index
  6520. // observed on the author's workstation.
  6521. char stat_line[160];
  6522. n = fread(&stat_line, 1, 159, proc_stat);
  6523. stat_line[n] = '\0';
  6524. fclose(proc_stat);
  6525. char *saveptr = NULL;
  6526. char *field = strtok_r(stat_line, " ", &saveptr);
  6527. unsigned int idx;
  6528. for (idx = 19; idx && field; --idx) {
  6529. field = strtok_r(NULL, " ", &saveptr);
  6530. }
  6531. if (idx == 0 && field) { // found the 20th field
  6532. num_python_threads = atoi(field); // 0 on error
  6533. }
  6534. }
  6535. #endif
  6536. if (num_python_threads <= 0) {
  6537. // Fall back to just the number our threading module knows about.
  6538. // An incomplete view of the world, but better than nothing.
  6539. PyObject *threading = PyImport_GetModule(&_Py_ID(threading));
  6540. if (!threading) {
  6541. PyErr_Clear();
  6542. return;
  6543. }
  6544. PyObject *threading_active =
  6545. PyObject_GetAttr(threading, &_Py_ID(_active));
  6546. if (!threading_active) {
  6547. PyErr_Clear();
  6548. Py_DECREF(threading);
  6549. return;
  6550. }
  6551. PyObject *threading_limbo =
  6552. PyObject_GetAttr(threading, &_Py_ID(_limbo));
  6553. if (!threading_limbo) {
  6554. PyErr_Clear();
  6555. Py_DECREF(threading);
  6556. Py_DECREF(threading_active);
  6557. return;
  6558. }
  6559. Py_DECREF(threading);
  6560. // Duplicating what threading.active_count() does but without holding
  6561. // threading._active_limbo_lock so our count could be inaccurate if
  6562. // these dicts are mid-update from another thread. Not a big deal.
  6563. // Worst case if someone replaced threading._active or threading._limbo
  6564. // with non-dicts, we get -1 from *Length() below and undercount.
  6565. // Nobody should, but we're best effort so we clear errors and move on.
  6566. num_python_threads = (PyMapping_Length(threading_active)
  6567. + PyMapping_Length(threading_limbo));
  6568. PyErr_Clear();
  6569. Py_DECREF(threading_active);
  6570. Py_DECREF(threading_limbo);
  6571. }
  6572. if (num_python_threads > 1) {
  6573. PyErr_WarnFormat(
  6574. PyExc_DeprecationWarning, 1,
  6575. #ifdef HAVE_GETPID
  6576. "This process (pid=%d) is multi-threaded, "
  6577. #else
  6578. "This process is multi-threaded, "
  6579. #endif
  6580. "use of %s() may lead to deadlocks in the child.",
  6581. #ifdef HAVE_GETPID
  6582. getpid(),
  6583. #endif
  6584. name);
  6585. PyErr_Clear();
  6586. }
  6587. }
  6588. #ifdef HAVE_FORK1
  6589. /*[clinic input]
  6590. os.fork1
  6591. Fork a child process with a single multiplexed (i.e., not bound) thread.
  6592. Return 0 to child process and PID of child to parent process.
  6593. [clinic start generated code]*/
  6594. static PyObject *
  6595. os_fork1_impl(PyObject *module)
  6596. /*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
  6597. {
  6598. pid_t pid;
  6599. PyInterpreterState *interp = _PyInterpreterState_GET();
  6600. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  6601. PyErr_SetString(PyExc_RuntimeError,
  6602. "can't fork at interpreter shutdown");
  6603. return NULL;
  6604. }
  6605. if (!_Py_IsMainInterpreter(interp)) {
  6606. PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
  6607. return NULL;
  6608. }
  6609. PyOS_BeforeFork();
  6610. pid = fork1();
  6611. int saved_errno = errno;
  6612. if (pid == 0) {
  6613. /* child: this clobbers and resets the import lock. */
  6614. PyOS_AfterFork_Child();
  6615. } else {
  6616. warn_about_fork_with_threads("fork1");
  6617. /* parent: release the import lock. */
  6618. PyOS_AfterFork_Parent();
  6619. }
  6620. if (pid == -1) {
  6621. errno = saved_errno;
  6622. return posix_error();
  6623. }
  6624. return PyLong_FromPid(pid);
  6625. }
  6626. #endif /* HAVE_FORK1 */
  6627. #ifdef HAVE_FORK
  6628. /*[clinic input]
  6629. os.fork
  6630. Fork a child process.
  6631. Return 0 to child process and PID of child to parent process.
  6632. [clinic start generated code]*/
  6633. static PyObject *
  6634. os_fork_impl(PyObject *module)
  6635. /*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
  6636. {
  6637. pid_t pid;
  6638. PyInterpreterState *interp = _PyInterpreterState_GET();
  6639. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  6640. PyErr_SetString(PyExc_RuntimeError,
  6641. "can't fork at interpreter shutdown");
  6642. return NULL;
  6643. }
  6644. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_FORK)) {
  6645. PyErr_SetString(PyExc_RuntimeError,
  6646. "fork not supported for isolated subinterpreters");
  6647. return NULL;
  6648. }
  6649. if (PySys_Audit("os.fork", NULL) < 0) {
  6650. return NULL;
  6651. }
  6652. PyOS_BeforeFork();
  6653. pid = fork();
  6654. int saved_errno = errno;
  6655. if (pid == 0) {
  6656. /* child: this clobbers and resets the import lock. */
  6657. PyOS_AfterFork_Child();
  6658. } else {
  6659. warn_about_fork_with_threads("fork");
  6660. /* parent: release the import lock. */
  6661. PyOS_AfterFork_Parent();
  6662. }
  6663. if (pid == -1) {
  6664. errno = saved_errno;
  6665. return posix_error();
  6666. }
  6667. return PyLong_FromPid(pid);
  6668. }
  6669. #endif /* HAVE_FORK */
  6670. #ifdef HAVE_SCHED_H
  6671. #ifdef HAVE_SCHED_GET_PRIORITY_MAX
  6672. /*[clinic input]
  6673. os.sched_get_priority_max
  6674. policy: int
  6675. Get the maximum scheduling priority for policy.
  6676. [clinic start generated code]*/
  6677. static PyObject *
  6678. os_sched_get_priority_max_impl(PyObject *module, int policy)
  6679. /*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
  6680. {
  6681. int max;
  6682. max = sched_get_priority_max(policy);
  6683. if (max < 0)
  6684. return posix_error();
  6685. return PyLong_FromLong(max);
  6686. }
  6687. /*[clinic input]
  6688. os.sched_get_priority_min
  6689. policy: int
  6690. Get the minimum scheduling priority for policy.
  6691. [clinic start generated code]*/
  6692. static PyObject *
  6693. os_sched_get_priority_min_impl(PyObject *module, int policy)
  6694. /*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
  6695. {
  6696. int min = sched_get_priority_min(policy);
  6697. if (min < 0)
  6698. return posix_error();
  6699. return PyLong_FromLong(min);
  6700. }
  6701. #endif /* HAVE_SCHED_GET_PRIORITY_MAX */
  6702. #ifdef HAVE_SCHED_SETSCHEDULER
  6703. /*[clinic input]
  6704. os.sched_getscheduler
  6705. pid: pid_t
  6706. /
  6707. Get the scheduling policy for the process identified by pid.
  6708. Passing 0 for pid returns the scheduling policy for the calling process.
  6709. [clinic start generated code]*/
  6710. static PyObject *
  6711. os_sched_getscheduler_impl(PyObject *module, pid_t pid)
  6712. /*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
  6713. {
  6714. int policy;
  6715. policy = sched_getscheduler(pid);
  6716. if (policy < 0)
  6717. return posix_error();
  6718. return PyLong_FromLong(policy);
  6719. }
  6720. #endif /* HAVE_SCHED_SETSCHEDULER */
  6721. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  6722. /*[clinic input]
  6723. class os.sched_param "PyObject *" "SchedParamType"
  6724. @classmethod
  6725. os.sched_param.__new__
  6726. sched_priority: object
  6727. A scheduling parameter.
  6728. Currently has only one field: sched_priority
  6729. [clinic start generated code]*/
  6730. static PyObject *
  6731. os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
  6732. /*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
  6733. {
  6734. PyObject *res;
  6735. res = PyStructSequence_New(type);
  6736. if (!res)
  6737. return NULL;
  6738. PyStructSequence_SET_ITEM(res, 0, Py_NewRef(sched_priority));
  6739. return res;
  6740. }
  6741. PyDoc_VAR(os_sched_param__doc__);
  6742. static PyStructSequence_Field sched_param_fields[] = {
  6743. {"sched_priority", "the scheduling priority"},
  6744. {0}
  6745. };
  6746. static PyStructSequence_Desc sched_param_desc = {
  6747. "sched_param", /* name */
  6748. os_sched_param__doc__, /* doc */
  6749. sched_param_fields,
  6750. 1
  6751. };
  6752. static int
  6753. convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res)
  6754. {
  6755. long priority;
  6756. if (!Py_IS_TYPE(param, (PyTypeObject *)get_posix_state(module)->SchedParamType)) {
  6757. PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
  6758. return 0;
  6759. }
  6760. priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
  6761. if (priority == -1 && PyErr_Occurred())
  6762. return 0;
  6763. if (priority > INT_MAX || priority < INT_MIN) {
  6764. PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
  6765. return 0;
  6766. }
  6767. res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
  6768. return 1;
  6769. }
  6770. #endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
  6771. #ifdef HAVE_SCHED_SETSCHEDULER
  6772. /*[clinic input]
  6773. os.sched_setscheduler
  6774. pid: pid_t
  6775. policy: int
  6776. param as param_obj: object
  6777. /
  6778. Set the scheduling policy for the process identified by pid.
  6779. If pid is 0, the calling process is changed.
  6780. param is an instance of sched_param.
  6781. [clinic start generated code]*/
  6782. static PyObject *
  6783. os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
  6784. PyObject *param_obj)
  6785. /*[clinic end generated code: output=cde27faa55dc993e input=73013d731bd8fbe9]*/
  6786. {
  6787. struct sched_param param;
  6788. if (!convert_sched_param(module, param_obj, &param)) {
  6789. return NULL;
  6790. }
  6791. /*
  6792. ** sched_setscheduler() returns 0 in Linux, but the previous
  6793. ** scheduling policy under Solaris/Illumos, and others.
  6794. ** On error, -1 is returned in all Operating Systems.
  6795. */
  6796. if (sched_setscheduler(pid, policy, &param) == -1)
  6797. return posix_error();
  6798. Py_RETURN_NONE;
  6799. }
  6800. #endif /* HAVE_SCHED_SETSCHEDULER*/
  6801. #ifdef HAVE_SCHED_SETPARAM
  6802. /*[clinic input]
  6803. os.sched_getparam
  6804. pid: pid_t
  6805. /
  6806. Returns scheduling parameters for the process identified by pid.
  6807. If pid is 0, returns parameters for the calling process.
  6808. Return value is an instance of sched_param.
  6809. [clinic start generated code]*/
  6810. static PyObject *
  6811. os_sched_getparam_impl(PyObject *module, pid_t pid)
  6812. /*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
  6813. {
  6814. struct sched_param param;
  6815. PyObject *result;
  6816. PyObject *priority;
  6817. if (sched_getparam(pid, &param))
  6818. return posix_error();
  6819. PyObject *SchedParamType = get_posix_state(module)->SchedParamType;
  6820. result = PyStructSequence_New((PyTypeObject *)SchedParamType);
  6821. if (!result)
  6822. return NULL;
  6823. priority = PyLong_FromLong(param.sched_priority);
  6824. if (!priority) {
  6825. Py_DECREF(result);
  6826. return NULL;
  6827. }
  6828. PyStructSequence_SET_ITEM(result, 0, priority);
  6829. return result;
  6830. }
  6831. /*[clinic input]
  6832. os.sched_setparam
  6833. pid: pid_t
  6834. param as param_obj: object
  6835. /
  6836. Set scheduling parameters for the process identified by pid.
  6837. If pid is 0, sets parameters for the calling process.
  6838. param should be an instance of sched_param.
  6839. [clinic start generated code]*/
  6840. static PyObject *
  6841. os_sched_setparam_impl(PyObject *module, pid_t pid, PyObject *param_obj)
  6842. /*[clinic end generated code: output=f19fe020a53741c1 input=27b98337c8b2dcc7]*/
  6843. {
  6844. struct sched_param param;
  6845. if (!convert_sched_param(module, param_obj, &param)) {
  6846. return NULL;
  6847. }
  6848. if (sched_setparam(pid, &param))
  6849. return posix_error();
  6850. Py_RETURN_NONE;
  6851. }
  6852. #endif /* HAVE_SCHED_SETPARAM */
  6853. #ifdef HAVE_SCHED_RR_GET_INTERVAL
  6854. /*[clinic input]
  6855. os.sched_rr_get_interval -> double
  6856. pid: pid_t
  6857. /
  6858. Return the round-robin quantum for the process identified by pid, in seconds.
  6859. Value returned is a float.
  6860. [clinic start generated code]*/
  6861. static double
  6862. os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
  6863. /*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
  6864. {
  6865. struct timespec interval;
  6866. if (sched_rr_get_interval(pid, &interval)) {
  6867. posix_error();
  6868. return -1.0;
  6869. }
  6870. #ifdef _Py_MEMORY_SANITIZER
  6871. __msan_unpoison(&interval, sizeof(interval));
  6872. #endif
  6873. return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
  6874. }
  6875. #endif /* HAVE_SCHED_RR_GET_INTERVAL */
  6876. /*[clinic input]
  6877. os.sched_yield
  6878. Voluntarily relinquish the CPU.
  6879. [clinic start generated code]*/
  6880. static PyObject *
  6881. os_sched_yield_impl(PyObject *module)
  6882. /*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
  6883. {
  6884. int result;
  6885. Py_BEGIN_ALLOW_THREADS
  6886. result = sched_yield();
  6887. Py_END_ALLOW_THREADS
  6888. if (result < 0) {
  6889. return posix_error();
  6890. }
  6891. Py_RETURN_NONE;
  6892. }
  6893. #ifdef HAVE_SCHED_SETAFFINITY
  6894. /* The minimum number of CPUs allocated in a cpu_set_t */
  6895. static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
  6896. /*[clinic input]
  6897. os.sched_setaffinity
  6898. pid: pid_t
  6899. mask : object
  6900. /
  6901. Set the CPU affinity of the process identified by pid to mask.
  6902. mask should be an iterable of integers identifying CPUs.
  6903. [clinic start generated code]*/
  6904. static PyObject *
  6905. os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
  6906. /*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
  6907. {
  6908. int ncpus;
  6909. size_t setsize;
  6910. cpu_set_t *cpu_set = NULL;
  6911. PyObject *iterator = NULL, *item;
  6912. iterator = PyObject_GetIter(mask);
  6913. if (iterator == NULL)
  6914. return NULL;
  6915. ncpus = NCPUS_START;
  6916. setsize = CPU_ALLOC_SIZE(ncpus);
  6917. cpu_set = CPU_ALLOC(ncpus);
  6918. if (cpu_set == NULL) {
  6919. PyErr_NoMemory();
  6920. goto error;
  6921. }
  6922. CPU_ZERO_S(setsize, cpu_set);
  6923. while ((item = PyIter_Next(iterator))) {
  6924. long cpu;
  6925. if (!PyLong_Check(item)) {
  6926. PyErr_Format(PyExc_TypeError,
  6927. "expected an iterator of ints, "
  6928. "but iterator yielded %R",
  6929. Py_TYPE(item));
  6930. Py_DECREF(item);
  6931. goto error;
  6932. }
  6933. cpu = PyLong_AsLong(item);
  6934. Py_DECREF(item);
  6935. if (cpu < 0) {
  6936. if (!PyErr_Occurred())
  6937. PyErr_SetString(PyExc_ValueError, "negative CPU number");
  6938. goto error;
  6939. }
  6940. if (cpu > INT_MAX - 1) {
  6941. PyErr_SetString(PyExc_OverflowError, "CPU number too large");
  6942. goto error;
  6943. }
  6944. if (cpu >= ncpus) {
  6945. /* Grow CPU mask to fit the CPU number */
  6946. int newncpus = ncpus;
  6947. cpu_set_t *newmask;
  6948. size_t newsetsize;
  6949. while (newncpus <= cpu) {
  6950. if (newncpus > INT_MAX / 2)
  6951. newncpus = cpu + 1;
  6952. else
  6953. newncpus = newncpus * 2;
  6954. }
  6955. newmask = CPU_ALLOC(newncpus);
  6956. if (newmask == NULL) {
  6957. PyErr_NoMemory();
  6958. goto error;
  6959. }
  6960. newsetsize = CPU_ALLOC_SIZE(newncpus);
  6961. CPU_ZERO_S(newsetsize, newmask);
  6962. memcpy(newmask, cpu_set, setsize);
  6963. CPU_FREE(cpu_set);
  6964. setsize = newsetsize;
  6965. cpu_set = newmask;
  6966. ncpus = newncpus;
  6967. }
  6968. CPU_SET_S(cpu, setsize, cpu_set);
  6969. }
  6970. if (PyErr_Occurred()) {
  6971. goto error;
  6972. }
  6973. Py_CLEAR(iterator);
  6974. if (sched_setaffinity(pid, setsize, cpu_set)) {
  6975. posix_error();
  6976. goto error;
  6977. }
  6978. CPU_FREE(cpu_set);
  6979. Py_RETURN_NONE;
  6980. error:
  6981. if (cpu_set)
  6982. CPU_FREE(cpu_set);
  6983. Py_XDECREF(iterator);
  6984. return NULL;
  6985. }
  6986. /*[clinic input]
  6987. os.sched_getaffinity
  6988. pid: pid_t
  6989. /
  6990. Return the affinity of the process identified by pid (or the current process if zero).
  6991. The affinity is returned as a set of CPU identifiers.
  6992. [clinic start generated code]*/
  6993. static PyObject *
  6994. os_sched_getaffinity_impl(PyObject *module, pid_t pid)
  6995. /*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
  6996. {
  6997. int cpu, ncpus, count;
  6998. size_t setsize;
  6999. cpu_set_t *mask = NULL;
  7000. PyObject *res = NULL;
  7001. ncpus = NCPUS_START;
  7002. while (1) {
  7003. setsize = CPU_ALLOC_SIZE(ncpus);
  7004. mask = CPU_ALLOC(ncpus);
  7005. if (mask == NULL)
  7006. return PyErr_NoMemory();
  7007. if (sched_getaffinity(pid, setsize, mask) == 0)
  7008. break;
  7009. CPU_FREE(mask);
  7010. if (errno != EINVAL)
  7011. return posix_error();
  7012. if (ncpus > INT_MAX / 2) {
  7013. PyErr_SetString(PyExc_OverflowError, "could not allocate "
  7014. "a large enough CPU set");
  7015. return NULL;
  7016. }
  7017. ncpus = ncpus * 2;
  7018. }
  7019. res = PySet_New(NULL);
  7020. if (res == NULL)
  7021. goto error;
  7022. for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
  7023. if (CPU_ISSET_S(cpu, setsize, mask)) {
  7024. PyObject *cpu_num = PyLong_FromLong(cpu);
  7025. --count;
  7026. if (cpu_num == NULL)
  7027. goto error;
  7028. if (PySet_Add(res, cpu_num)) {
  7029. Py_DECREF(cpu_num);
  7030. goto error;
  7031. }
  7032. Py_DECREF(cpu_num);
  7033. }
  7034. }
  7035. CPU_FREE(mask);
  7036. return res;
  7037. error:
  7038. if (mask)
  7039. CPU_FREE(mask);
  7040. Py_XDECREF(res);
  7041. return NULL;
  7042. }
  7043. #endif /* HAVE_SCHED_SETAFFINITY */
  7044. #endif /* HAVE_SCHED_H */
  7045. /* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
  7046. #if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
  7047. # define DEV_PTY_FILE "/dev/ptc"
  7048. # define HAVE_DEV_PTMX
  7049. #else
  7050. # define DEV_PTY_FILE "/dev/ptmx"
  7051. #endif
  7052. #if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX)
  7053. #ifdef HAVE_PTY_H
  7054. #include <pty.h>
  7055. #ifdef HAVE_UTMP_H
  7056. #include <utmp.h>
  7057. #endif /* HAVE_UTMP_H */
  7058. #elif defined(HAVE_LIBUTIL_H)
  7059. #include <libutil.h>
  7060. #elif defined(HAVE_UTIL_H)
  7061. #include <util.h>
  7062. #endif /* HAVE_PTY_H */
  7063. #ifdef HAVE_STROPTS_H
  7064. #include <stropts.h>
  7065. #else
  7066. #define __SID ('S' << 8)
  7067. #define I_PUSH (__SID | 2)
  7068. #endif
  7069. #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX) */
  7070. #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
  7071. /*[clinic input]
  7072. os.openpty
  7073. Open a pseudo-terminal.
  7074. Return a tuple of (master_fd, slave_fd) containing open file descriptors
  7075. for both the master and slave ends.
  7076. [clinic start generated code]*/
  7077. static PyObject *
  7078. os_openpty_impl(PyObject *module)
  7079. /*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
  7080. {
  7081. int master_fd = -1, slave_fd = -1;
  7082. #ifndef HAVE_OPENPTY
  7083. char * slave_name;
  7084. #endif
  7085. #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
  7086. PyOS_sighandler_t sig_saved;
  7087. #if defined(__sun) && defined(__SVR4)
  7088. extern char *ptsname(int fildes);
  7089. #endif
  7090. #endif
  7091. #ifdef HAVE_OPENPTY
  7092. if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
  7093. goto posix_error;
  7094. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7095. goto error;
  7096. if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
  7097. goto error;
  7098. #elif defined(HAVE__GETPTY)
  7099. slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
  7100. if (slave_name == NULL)
  7101. goto posix_error;
  7102. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7103. goto error;
  7104. slave_fd = _Py_open(slave_name, O_RDWR);
  7105. if (slave_fd < 0)
  7106. goto error;
  7107. #else
  7108. master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
  7109. if (master_fd < 0)
  7110. goto posix_error;
  7111. sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
  7112. /* change permission of slave */
  7113. if (grantpt(master_fd) < 0) {
  7114. int saved_errno = errno;
  7115. PyOS_setsig(SIGCHLD, sig_saved);
  7116. errno = saved_errno;
  7117. goto posix_error;
  7118. }
  7119. /* unlock slave */
  7120. if (unlockpt(master_fd) < 0) {
  7121. int saved_errno = errno;
  7122. PyOS_setsig(SIGCHLD, sig_saved);
  7123. errno = saved_errno;
  7124. goto posix_error;
  7125. }
  7126. PyOS_setsig(SIGCHLD, sig_saved);
  7127. slave_name = ptsname(master_fd); /* get name of slave */
  7128. if (slave_name == NULL)
  7129. goto posix_error;
  7130. slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
  7131. if (slave_fd == -1)
  7132. goto error;
  7133. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7134. goto posix_error;
  7135. #if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
  7136. ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
  7137. ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
  7138. #ifndef __hpux
  7139. ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
  7140. #endif /* __hpux */
  7141. #endif /* HAVE_CYGWIN */
  7142. #endif /* HAVE_OPENPTY */
  7143. return Py_BuildValue("(ii)", master_fd, slave_fd);
  7144. posix_error:
  7145. posix_error();
  7146. error:
  7147. if (master_fd != -1)
  7148. close(master_fd);
  7149. if (slave_fd != -1)
  7150. close(slave_fd);
  7151. return NULL;
  7152. }
  7153. #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
  7154. #if defined(HAVE_SETSID) && defined(TIOCSCTTY)
  7155. #define HAVE_FALLBACK_LOGIN_TTY 1
  7156. #endif /* defined(HAVE_SETSID) && defined(TIOCSCTTY) */
  7157. #if defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY)
  7158. /*[clinic input]
  7159. os.login_tty
  7160. fd: fildes
  7161. /
  7162. Prepare the tty of which fd is a file descriptor for a new login session.
  7163. Make the calling process a session leader; make the tty the
  7164. controlling tty, the stdin, the stdout, and the stderr of the
  7165. calling process; close fd.
  7166. [clinic start generated code]*/
  7167. static PyObject *
  7168. os_login_tty_impl(PyObject *module, int fd)
  7169. /*[clinic end generated code: output=495a79911b4cc1bc input=5f298565099903a2]*/
  7170. {
  7171. #ifdef HAVE_LOGIN_TTY
  7172. if (login_tty(fd) == -1) {
  7173. return posix_error();
  7174. }
  7175. #else /* defined(HAVE_FALLBACK_LOGIN_TTY) */
  7176. /* Establish a new session. */
  7177. if (setsid() == -1) {
  7178. return posix_error();
  7179. }
  7180. /* The tty becomes the controlling terminal. */
  7181. if (ioctl(fd, TIOCSCTTY, (char *)NULL) == -1) {
  7182. return posix_error();
  7183. }
  7184. /* The tty becomes stdin/stdout/stderr */
  7185. if (dup2(fd, 0) == -1 || dup2(fd, 1) == -1 || dup2(fd, 2) == -1) {
  7186. return posix_error();
  7187. }
  7188. if (fd > 2) {
  7189. close(fd);
  7190. }
  7191. #endif /* HAVE_LOGIN_TTY */
  7192. Py_RETURN_NONE;
  7193. }
  7194. #endif /* defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY) */
  7195. #ifdef HAVE_FORKPTY
  7196. /*[clinic input]
  7197. os.forkpty
  7198. Fork a new process with a new pseudo-terminal as controlling tty.
  7199. Returns a tuple of (pid, master_fd).
  7200. Like fork(), return pid of 0 to the child process,
  7201. and pid of child to the parent process.
  7202. To both, return fd of newly opened pseudo-terminal.
  7203. [clinic start generated code]*/
  7204. static PyObject *
  7205. os_forkpty_impl(PyObject *module)
  7206. /*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
  7207. {
  7208. int master_fd = -1;
  7209. pid_t pid;
  7210. PyInterpreterState *interp = _PyInterpreterState_GET();
  7211. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  7212. PyErr_SetString(PyExc_RuntimeError,
  7213. "can't fork at interpreter shutdown");
  7214. return NULL;
  7215. }
  7216. if (!_Py_IsMainInterpreter(interp)) {
  7217. PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
  7218. return NULL;
  7219. }
  7220. if (PySys_Audit("os.forkpty", NULL) < 0) {
  7221. return NULL;
  7222. }
  7223. PyOS_BeforeFork();
  7224. pid = forkpty(&master_fd, NULL, NULL, NULL);
  7225. if (pid == 0) {
  7226. /* child: this clobbers and resets the import lock. */
  7227. PyOS_AfterFork_Child();
  7228. } else {
  7229. warn_about_fork_with_threads("forkpty");
  7230. /* parent: release the import lock. */
  7231. PyOS_AfterFork_Parent();
  7232. }
  7233. if (pid == -1) {
  7234. return posix_error();
  7235. }
  7236. return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
  7237. }
  7238. #endif /* HAVE_FORKPTY */
  7239. #ifdef HAVE_GETEGID
  7240. /*[clinic input]
  7241. os.getegid
  7242. Return the current process's effective group id.
  7243. [clinic start generated code]*/
  7244. static PyObject *
  7245. os_getegid_impl(PyObject *module)
  7246. /*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
  7247. {
  7248. return _PyLong_FromGid(getegid());
  7249. }
  7250. #endif /* HAVE_GETEGID */
  7251. #ifdef HAVE_GETEUID
  7252. /*[clinic input]
  7253. os.geteuid
  7254. Return the current process's effective user id.
  7255. [clinic start generated code]*/
  7256. static PyObject *
  7257. os_geteuid_impl(PyObject *module)
  7258. /*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
  7259. {
  7260. return _PyLong_FromUid(geteuid());
  7261. }
  7262. #endif /* HAVE_GETEUID */
  7263. #ifdef HAVE_GETGID
  7264. /*[clinic input]
  7265. os.getgid
  7266. Return the current process's group id.
  7267. [clinic start generated code]*/
  7268. static PyObject *
  7269. os_getgid_impl(PyObject *module)
  7270. /*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
  7271. {
  7272. return _PyLong_FromGid(getgid());
  7273. }
  7274. #endif /* HAVE_GETGID */
  7275. #if defined(HAVE_GETPID)
  7276. /*[clinic input]
  7277. os.getpid
  7278. Return the current process id.
  7279. [clinic start generated code]*/
  7280. static PyObject *
  7281. os_getpid_impl(PyObject *module)
  7282. /*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
  7283. {
  7284. #if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  7285. return PyLong_FromPid(getpid());
  7286. #else
  7287. return PyLong_FromUnsignedLong(GetCurrentProcessId());
  7288. #endif
  7289. }
  7290. #endif /* defined(HAVE_GETPID) */
  7291. #ifdef NGROUPS_MAX
  7292. #define MAX_GROUPS NGROUPS_MAX
  7293. #else
  7294. /* defined to be 16 on Solaris7, so this should be a small number */
  7295. #define MAX_GROUPS 64
  7296. #endif
  7297. #ifdef HAVE_GETGROUPLIST
  7298. #ifdef __APPLE__
  7299. /*[clinic input]
  7300. os.getgrouplist
  7301. user: str
  7302. username to lookup
  7303. group as basegid: int
  7304. base group id of the user
  7305. /
  7306. Returns a list of groups to which a user belongs.
  7307. [clinic start generated code]*/
  7308. static PyObject *
  7309. os_getgrouplist_impl(PyObject *module, const char *user, int basegid)
  7310. /*[clinic end generated code: output=6e734697b8c26de0 input=f8d870374b09a490]*/
  7311. #else
  7312. /*[clinic input]
  7313. os.getgrouplist
  7314. user: str
  7315. username to lookup
  7316. group as basegid: gid_t
  7317. base group id of the user
  7318. /
  7319. Returns a list of groups to which a user belongs.
  7320. [clinic start generated code]*/
  7321. static PyObject *
  7322. os_getgrouplist_impl(PyObject *module, const char *user, gid_t basegid)
  7323. /*[clinic end generated code: output=0ebd7fb70115575b input=cc61d5c20b08958d]*/
  7324. #endif
  7325. {
  7326. int i, ngroups;
  7327. PyObject *list;
  7328. #ifdef __APPLE__
  7329. int *groups;
  7330. #else
  7331. gid_t *groups;
  7332. #endif
  7333. /*
  7334. * NGROUPS_MAX is defined by POSIX.1 as the maximum
  7335. * number of supplimental groups a users can belong to.
  7336. * We have to increment it by one because
  7337. * getgrouplist() returns both the supplemental groups
  7338. * and the primary group, i.e. all of the groups the
  7339. * user belongs to.
  7340. */
  7341. ngroups = 1 + MAX_GROUPS;
  7342. while (1) {
  7343. #ifdef __APPLE__
  7344. groups = PyMem_New(int, ngroups);
  7345. #else
  7346. groups = PyMem_New(gid_t, ngroups);
  7347. #endif
  7348. if (groups == NULL) {
  7349. return PyErr_NoMemory();
  7350. }
  7351. int old_ngroups = ngroups;
  7352. if (getgrouplist(user, basegid, groups, &ngroups) != -1) {
  7353. /* Success */
  7354. break;
  7355. }
  7356. /* getgrouplist() fails if the group list is too small */
  7357. PyMem_Free(groups);
  7358. if (ngroups > old_ngroups) {
  7359. /* If the group list is too small, the glibc implementation of
  7360. getgrouplist() sets ngroups to the total number of groups and
  7361. returns -1. */
  7362. }
  7363. else {
  7364. /* Double the group list size */
  7365. if (ngroups > INT_MAX / 2) {
  7366. return PyErr_NoMemory();
  7367. }
  7368. ngroups *= 2;
  7369. }
  7370. /* Retry getgrouplist() with a larger group list */
  7371. }
  7372. #ifdef _Py_MEMORY_SANITIZER
  7373. /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
  7374. __msan_unpoison(&ngroups, sizeof(ngroups));
  7375. __msan_unpoison(groups, ngroups*sizeof(*groups));
  7376. #endif
  7377. list = PyList_New(ngroups);
  7378. if (list == NULL) {
  7379. PyMem_Free(groups);
  7380. return NULL;
  7381. }
  7382. for (i = 0; i < ngroups; i++) {
  7383. #ifdef __APPLE__
  7384. PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
  7385. #else
  7386. PyObject *o = _PyLong_FromGid(groups[i]);
  7387. #endif
  7388. if (o == NULL) {
  7389. Py_DECREF(list);
  7390. PyMem_Free(groups);
  7391. return NULL;
  7392. }
  7393. PyList_SET_ITEM(list, i, o);
  7394. }
  7395. PyMem_Free(groups);
  7396. return list;
  7397. }
  7398. #endif /* HAVE_GETGROUPLIST */
  7399. #ifdef HAVE_GETGROUPS
  7400. /*[clinic input]
  7401. os.getgroups
  7402. Return list of supplemental group IDs for the process.
  7403. [clinic start generated code]*/
  7404. static PyObject *
  7405. os_getgroups_impl(PyObject *module)
  7406. /*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
  7407. {
  7408. // Call getgroups with length 0 to get the actual number of groups
  7409. int n = getgroups(0, NULL);
  7410. if (n < 0) {
  7411. return posix_error();
  7412. }
  7413. if (n == 0) {
  7414. return PyList_New(0);
  7415. }
  7416. gid_t *grouplist = PyMem_New(gid_t, n);
  7417. if (grouplist == NULL) {
  7418. return PyErr_NoMemory();
  7419. }
  7420. n = getgroups(n, grouplist);
  7421. if (n == -1) {
  7422. posix_error();
  7423. PyMem_Free(grouplist);
  7424. return NULL;
  7425. }
  7426. PyObject *result = PyList_New(n);
  7427. if (result == NULL) {
  7428. goto error;
  7429. }
  7430. for (int i = 0; i < n; ++i) {
  7431. PyObject *group = _PyLong_FromGid(grouplist[i]);
  7432. if (group == NULL) {
  7433. goto error;
  7434. }
  7435. PyList_SET_ITEM(result, i, group);
  7436. }
  7437. PyMem_Free(grouplist);
  7438. return result;
  7439. error:
  7440. PyMem_Free(grouplist);
  7441. Py_XDECREF(result);
  7442. return NULL;
  7443. }
  7444. #endif /* HAVE_GETGROUPS */
  7445. #ifdef HAVE_INITGROUPS
  7446. #ifdef __APPLE__
  7447. /*[clinic input]
  7448. os.initgroups
  7449. username as oname: FSConverter
  7450. gid: int
  7451. /
  7452. Initialize the group access list.
  7453. Call the system initgroups() to initialize the group access list with all of
  7454. the groups of which the specified username is a member, plus the specified
  7455. group id.
  7456. [clinic start generated code]*/
  7457. static PyObject *
  7458. os_initgroups_impl(PyObject *module, PyObject *oname, int gid)
  7459. /*[clinic end generated code: output=7f074d30a425fd3a input=df3d54331b0af204]*/
  7460. #else
  7461. /*[clinic input]
  7462. os.initgroups
  7463. username as oname: FSConverter
  7464. gid: gid_t
  7465. /
  7466. Initialize the group access list.
  7467. Call the system initgroups() to initialize the group access list with all of
  7468. the groups of which the specified username is a member, plus the specified
  7469. group id.
  7470. [clinic start generated code]*/
  7471. static PyObject *
  7472. os_initgroups_impl(PyObject *module, PyObject *oname, gid_t gid)
  7473. /*[clinic end generated code: output=59341244521a9e3f input=0cb91bdc59a4c564]*/
  7474. #endif
  7475. {
  7476. const char *username = PyBytes_AS_STRING(oname);
  7477. if (initgroups(username, gid) == -1)
  7478. return PyErr_SetFromErrno(PyExc_OSError);
  7479. Py_RETURN_NONE;
  7480. }
  7481. #endif /* HAVE_INITGROUPS */
  7482. #ifdef HAVE_GETPGID
  7483. /*[clinic input]
  7484. os.getpgid
  7485. pid: pid_t
  7486. Call the system call getpgid(), and return the result.
  7487. [clinic start generated code]*/
  7488. static PyObject *
  7489. os_getpgid_impl(PyObject *module, pid_t pid)
  7490. /*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
  7491. {
  7492. pid_t pgid = getpgid(pid);
  7493. if (pgid < 0)
  7494. return posix_error();
  7495. return PyLong_FromPid(pgid);
  7496. }
  7497. #endif /* HAVE_GETPGID */
  7498. #ifdef HAVE_GETPGRP
  7499. /*[clinic input]
  7500. os.getpgrp
  7501. Return the current process group id.
  7502. [clinic start generated code]*/
  7503. static PyObject *
  7504. os_getpgrp_impl(PyObject *module)
  7505. /*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
  7506. {
  7507. #ifdef GETPGRP_HAVE_ARG
  7508. return PyLong_FromPid(getpgrp(0));
  7509. #else /* GETPGRP_HAVE_ARG */
  7510. return PyLong_FromPid(getpgrp());
  7511. #endif /* GETPGRP_HAVE_ARG */
  7512. }
  7513. #endif /* HAVE_GETPGRP */
  7514. #ifdef HAVE_SETPGRP
  7515. /*[clinic input]
  7516. os.setpgrp
  7517. Make the current process the leader of its process group.
  7518. [clinic start generated code]*/
  7519. static PyObject *
  7520. os_setpgrp_impl(PyObject *module)
  7521. /*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
  7522. {
  7523. #ifdef SETPGRP_HAVE_ARG
  7524. if (setpgrp(0, 0) < 0)
  7525. #else /* SETPGRP_HAVE_ARG */
  7526. if (setpgrp() < 0)
  7527. #endif /* SETPGRP_HAVE_ARG */
  7528. return posix_error();
  7529. Py_RETURN_NONE;
  7530. }
  7531. #endif /* HAVE_SETPGRP */
  7532. #ifdef HAVE_GETPPID
  7533. #ifdef MS_WINDOWS
  7534. #include <processsnapshot.h>
  7535. static PyObject*
  7536. win32_getppid(void)
  7537. {
  7538. DWORD error;
  7539. PyObject* result = NULL;
  7540. HANDLE process = GetCurrentProcess();
  7541. HPSS snapshot = NULL;
  7542. error = PssCaptureSnapshot(process, PSS_CAPTURE_NONE, 0, &snapshot);
  7543. if (error != ERROR_SUCCESS) {
  7544. return PyErr_SetFromWindowsErr(error);
  7545. }
  7546. PSS_PROCESS_INFORMATION info;
  7547. error = PssQuerySnapshot(snapshot, PSS_QUERY_PROCESS_INFORMATION, &info,
  7548. sizeof(info));
  7549. if (error == ERROR_SUCCESS) {
  7550. result = PyLong_FromUnsignedLong(info.ParentProcessId);
  7551. }
  7552. else {
  7553. result = PyErr_SetFromWindowsErr(error);
  7554. }
  7555. PssFreeSnapshot(process, snapshot);
  7556. return result;
  7557. }
  7558. #endif /*MS_WINDOWS*/
  7559. /*[clinic input]
  7560. os.getppid
  7561. Return the parent's process id.
  7562. If the parent process has already exited, Windows machines will still
  7563. return its id; others systems will return the id of the 'init' process (1).
  7564. [clinic start generated code]*/
  7565. static PyObject *
  7566. os_getppid_impl(PyObject *module)
  7567. /*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
  7568. {
  7569. #ifdef MS_WINDOWS
  7570. return win32_getppid();
  7571. #else
  7572. return PyLong_FromPid(getppid());
  7573. #endif
  7574. }
  7575. #endif /* HAVE_GETPPID */
  7576. #ifdef HAVE_GETLOGIN
  7577. /*[clinic input]
  7578. os.getlogin
  7579. Return the actual login name.
  7580. [clinic start generated code]*/
  7581. static PyObject *
  7582. os_getlogin_impl(PyObject *module)
  7583. /*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
  7584. {
  7585. PyObject *result = NULL;
  7586. #ifdef MS_WINDOWS
  7587. wchar_t user_name[UNLEN + 1];
  7588. DWORD num_chars = Py_ARRAY_LENGTH(user_name);
  7589. if (GetUserNameW(user_name, &num_chars)) {
  7590. /* num_chars is the number of unicode chars plus null terminator */
  7591. result = PyUnicode_FromWideChar(user_name, num_chars - 1);
  7592. }
  7593. else
  7594. result = PyErr_SetFromWindowsErr(GetLastError());
  7595. #else
  7596. char *name;
  7597. int old_errno = errno;
  7598. errno = 0;
  7599. name = getlogin();
  7600. if (name == NULL) {
  7601. if (errno)
  7602. posix_error();
  7603. else
  7604. PyErr_SetString(PyExc_OSError, "unable to determine login name");
  7605. }
  7606. else
  7607. result = PyUnicode_DecodeFSDefault(name);
  7608. errno = old_errno;
  7609. #endif
  7610. return result;
  7611. }
  7612. #endif /* HAVE_GETLOGIN */
  7613. #ifdef HAVE_GETUID
  7614. /*[clinic input]
  7615. os.getuid
  7616. Return the current process's user id.
  7617. [clinic start generated code]*/
  7618. static PyObject *
  7619. os_getuid_impl(PyObject *module)
  7620. /*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
  7621. {
  7622. return _PyLong_FromUid(getuid());
  7623. }
  7624. #endif /* HAVE_GETUID */
  7625. #ifdef MS_WINDOWS
  7626. #define HAVE_KILL
  7627. #endif /* MS_WINDOWS */
  7628. #ifdef HAVE_KILL
  7629. /*[clinic input]
  7630. os.kill
  7631. pid: pid_t
  7632. signal: Py_ssize_t
  7633. /
  7634. Kill a process with a signal.
  7635. [clinic start generated code]*/
  7636. static PyObject *
  7637. os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
  7638. /*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
  7639. {
  7640. if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
  7641. return NULL;
  7642. }
  7643. #ifndef MS_WINDOWS
  7644. if (kill(pid, (int)signal) == -1) {
  7645. return posix_error();
  7646. }
  7647. // Check immediately if the signal was sent to the current process.
  7648. // Don't micro-optimize pid == getpid(), since PyErr_SetString() check
  7649. // is cheap.
  7650. if (PyErr_CheckSignals()) {
  7651. return NULL;
  7652. }
  7653. Py_RETURN_NONE;
  7654. #else /* !MS_WINDOWS */
  7655. PyObject *result;
  7656. DWORD sig = (DWORD)signal;
  7657. DWORD err;
  7658. HANDLE handle;
  7659. #ifdef HAVE_WINDOWS_CONSOLE_IO
  7660. /* Console processes which share a common console can be sent CTRL+C or
  7661. CTRL+BREAK events, provided they handle said events. */
  7662. if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
  7663. if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
  7664. err = GetLastError();
  7665. PyErr_SetFromWindowsErr(err);
  7666. }
  7667. else {
  7668. Py_RETURN_NONE;
  7669. }
  7670. }
  7671. #endif /* HAVE_WINDOWS_CONSOLE_IO */
  7672. /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
  7673. attempt to open and terminate the process. */
  7674. handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
  7675. if (handle == NULL) {
  7676. err = GetLastError();
  7677. return PyErr_SetFromWindowsErr(err);
  7678. }
  7679. if (TerminateProcess(handle, sig) == 0) {
  7680. err = GetLastError();
  7681. result = PyErr_SetFromWindowsErr(err);
  7682. } else {
  7683. result = Py_NewRef(Py_None);
  7684. }
  7685. CloseHandle(handle);
  7686. return result;
  7687. #endif /* !MS_WINDOWS */
  7688. }
  7689. #endif /* HAVE_KILL */
  7690. #ifdef HAVE_KILLPG
  7691. /*[clinic input]
  7692. os.killpg
  7693. pgid: pid_t
  7694. signal: int
  7695. /
  7696. Kill a process group with a signal.
  7697. [clinic start generated code]*/
  7698. static PyObject *
  7699. os_killpg_impl(PyObject *module, pid_t pgid, int signal)
  7700. /*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
  7701. {
  7702. if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
  7703. return NULL;
  7704. }
  7705. /* XXX some man pages make the `pgid` parameter an int, others
  7706. a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
  7707. take the same type. Moreover, pid_t is always at least as wide as
  7708. int (else compilation of this module fails), which is safe. */
  7709. if (killpg(pgid, signal) == -1)
  7710. return posix_error();
  7711. Py_RETURN_NONE;
  7712. }
  7713. #endif /* HAVE_KILLPG */
  7714. #ifdef HAVE_PLOCK
  7715. #ifdef HAVE_SYS_LOCK_H
  7716. #include <sys/lock.h>
  7717. #endif
  7718. /*[clinic input]
  7719. os.plock
  7720. op: int
  7721. /
  7722. Lock program segments into memory.");
  7723. [clinic start generated code]*/
  7724. static PyObject *
  7725. os_plock_impl(PyObject *module, int op)
  7726. /*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
  7727. {
  7728. if (plock(op) == -1)
  7729. return posix_error();
  7730. Py_RETURN_NONE;
  7731. }
  7732. #endif /* HAVE_PLOCK */
  7733. #ifdef HAVE_SETUID
  7734. /*[clinic input]
  7735. os.setuid
  7736. uid: uid_t
  7737. /
  7738. Set the current process's user id.
  7739. [clinic start generated code]*/
  7740. static PyObject *
  7741. os_setuid_impl(PyObject *module, uid_t uid)
  7742. /*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
  7743. {
  7744. if (setuid(uid) < 0)
  7745. return posix_error();
  7746. Py_RETURN_NONE;
  7747. }
  7748. #endif /* HAVE_SETUID */
  7749. #ifdef HAVE_SETEUID
  7750. /*[clinic input]
  7751. os.seteuid
  7752. euid: uid_t
  7753. /
  7754. Set the current process's effective user id.
  7755. [clinic start generated code]*/
  7756. static PyObject *
  7757. os_seteuid_impl(PyObject *module, uid_t euid)
  7758. /*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
  7759. {
  7760. if (seteuid(euid) < 0)
  7761. return posix_error();
  7762. Py_RETURN_NONE;
  7763. }
  7764. #endif /* HAVE_SETEUID */
  7765. #ifdef HAVE_SETEGID
  7766. /*[clinic input]
  7767. os.setegid
  7768. egid: gid_t
  7769. /
  7770. Set the current process's effective group id.
  7771. [clinic start generated code]*/
  7772. static PyObject *
  7773. os_setegid_impl(PyObject *module, gid_t egid)
  7774. /*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
  7775. {
  7776. if (setegid(egid) < 0)
  7777. return posix_error();
  7778. Py_RETURN_NONE;
  7779. }
  7780. #endif /* HAVE_SETEGID */
  7781. #ifdef HAVE_SETREUID
  7782. /*[clinic input]
  7783. os.setreuid
  7784. ruid: uid_t
  7785. euid: uid_t
  7786. /
  7787. Set the current process's real and effective user ids.
  7788. [clinic start generated code]*/
  7789. static PyObject *
  7790. os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
  7791. /*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
  7792. {
  7793. if (setreuid(ruid, euid) < 0) {
  7794. return posix_error();
  7795. } else {
  7796. Py_RETURN_NONE;
  7797. }
  7798. }
  7799. #endif /* HAVE_SETREUID */
  7800. #ifdef HAVE_SETREGID
  7801. /*[clinic input]
  7802. os.setregid
  7803. rgid: gid_t
  7804. egid: gid_t
  7805. /
  7806. Set the current process's real and effective group ids.
  7807. [clinic start generated code]*/
  7808. static PyObject *
  7809. os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
  7810. /*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
  7811. {
  7812. if (setregid(rgid, egid) < 0)
  7813. return posix_error();
  7814. Py_RETURN_NONE;
  7815. }
  7816. #endif /* HAVE_SETREGID */
  7817. #ifdef HAVE_SETGID
  7818. /*[clinic input]
  7819. os.setgid
  7820. gid: gid_t
  7821. /
  7822. Set the current process's group id.
  7823. [clinic start generated code]*/
  7824. static PyObject *
  7825. os_setgid_impl(PyObject *module, gid_t gid)
  7826. /*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
  7827. {
  7828. if (setgid(gid) < 0)
  7829. return posix_error();
  7830. Py_RETURN_NONE;
  7831. }
  7832. #endif /* HAVE_SETGID */
  7833. #ifdef HAVE_SETGROUPS
  7834. /*[clinic input]
  7835. os.setgroups
  7836. groups: object
  7837. /
  7838. Set the groups of the current process to list.
  7839. [clinic start generated code]*/
  7840. static PyObject *
  7841. os_setgroups(PyObject *module, PyObject *groups)
  7842. /*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
  7843. {
  7844. if (!PySequence_Check(groups)) {
  7845. PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
  7846. return NULL;
  7847. }
  7848. Py_ssize_t len = PySequence_Size(groups);
  7849. if (len < 0) {
  7850. return NULL;
  7851. }
  7852. if (len > MAX_GROUPS) {
  7853. PyErr_SetString(PyExc_ValueError, "too many groups");
  7854. return NULL;
  7855. }
  7856. gid_t *grouplist = PyMem_New(gid_t, len);
  7857. for (Py_ssize_t i = 0; i < len; i++) {
  7858. PyObject *elem;
  7859. elem = PySequence_GetItem(groups, i);
  7860. if (!elem) {
  7861. PyMem_Free(grouplist);
  7862. return NULL;
  7863. }
  7864. if (!PyLong_Check(elem)) {
  7865. PyErr_SetString(PyExc_TypeError,
  7866. "groups must be integers");
  7867. Py_DECREF(elem);
  7868. PyMem_Free(grouplist);
  7869. return NULL;
  7870. } else {
  7871. if (!_Py_Gid_Converter(elem, &grouplist[i])) {
  7872. Py_DECREF(elem);
  7873. PyMem_Free(grouplist);
  7874. return NULL;
  7875. }
  7876. }
  7877. Py_DECREF(elem);
  7878. }
  7879. if (setgroups(len, grouplist) < 0) {
  7880. posix_error();
  7881. PyMem_Free(grouplist);
  7882. return NULL;
  7883. }
  7884. PyMem_Free(grouplist);
  7885. Py_RETURN_NONE;
  7886. }
  7887. #endif /* HAVE_SETGROUPS */
  7888. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  7889. static PyObject *
  7890. wait_helper(PyObject *module, pid_t pid, int status, struct rusage *ru)
  7891. {
  7892. PyObject *result;
  7893. PyObject *struct_rusage;
  7894. if (pid == -1)
  7895. return posix_error();
  7896. // If wait succeeded but no child was ready to report status, ru will not
  7897. // have been populated.
  7898. if (pid == 0) {
  7899. memset(ru, 0, sizeof(*ru));
  7900. }
  7901. struct_rusage = _PyImport_GetModuleAttrString("resource", "struct_rusage");
  7902. if (struct_rusage == NULL)
  7903. return NULL;
  7904. /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
  7905. result = PyStructSequence_New((PyTypeObject*) struct_rusage);
  7906. Py_DECREF(struct_rusage);
  7907. if (!result)
  7908. return NULL;
  7909. int pos = 0;
  7910. #ifndef doubletime
  7911. #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
  7912. #endif
  7913. #define SET_RESULT(CALL) \
  7914. do { \
  7915. PyObject *item = (CALL); \
  7916. if (item == NULL) { \
  7917. Py_DECREF(result); \
  7918. return NULL; \
  7919. } \
  7920. PyStructSequence_SET_ITEM(result, pos++, item); \
  7921. } while(0)
  7922. SET_RESULT(PyFloat_FromDouble(doubletime(ru->ru_utime)));
  7923. SET_RESULT(PyFloat_FromDouble(doubletime(ru->ru_stime)));
  7924. SET_RESULT(PyLong_FromLong(ru->ru_maxrss));
  7925. SET_RESULT(PyLong_FromLong(ru->ru_ixrss));
  7926. SET_RESULT(PyLong_FromLong(ru->ru_idrss));
  7927. SET_RESULT(PyLong_FromLong(ru->ru_isrss));
  7928. SET_RESULT(PyLong_FromLong(ru->ru_minflt));
  7929. SET_RESULT(PyLong_FromLong(ru->ru_majflt));
  7930. SET_RESULT(PyLong_FromLong(ru->ru_nswap));
  7931. SET_RESULT(PyLong_FromLong(ru->ru_inblock));
  7932. SET_RESULT(PyLong_FromLong(ru->ru_oublock));
  7933. SET_RESULT(PyLong_FromLong(ru->ru_msgsnd));
  7934. SET_RESULT(PyLong_FromLong(ru->ru_msgrcv));
  7935. SET_RESULT(PyLong_FromLong(ru->ru_nsignals));
  7936. SET_RESULT(PyLong_FromLong(ru->ru_nvcsw));
  7937. SET_RESULT(PyLong_FromLong(ru->ru_nivcsw));
  7938. #undef SET_RESULT
  7939. return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
  7940. }
  7941. #endif /* HAVE_WAIT3 || HAVE_WAIT4 */
  7942. #ifdef HAVE_WAIT3
  7943. /*[clinic input]
  7944. os.wait3
  7945. options: int
  7946. Wait for completion of a child process.
  7947. Returns a tuple of information about the child process:
  7948. (pid, status, rusage)
  7949. [clinic start generated code]*/
  7950. static PyObject *
  7951. os_wait3_impl(PyObject *module, int options)
  7952. /*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
  7953. {
  7954. pid_t pid;
  7955. struct rusage ru;
  7956. int async_err = 0;
  7957. WAIT_TYPE status;
  7958. WAIT_STATUS_INT(status) = 0;
  7959. do {
  7960. Py_BEGIN_ALLOW_THREADS
  7961. pid = wait3(&status, options, &ru);
  7962. Py_END_ALLOW_THREADS
  7963. } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  7964. if (pid < 0)
  7965. return (!async_err) ? posix_error() : NULL;
  7966. return wait_helper(module, pid, WAIT_STATUS_INT(status), &ru);
  7967. }
  7968. #endif /* HAVE_WAIT3 */
  7969. #ifdef HAVE_WAIT4
  7970. /*[clinic input]
  7971. os.wait4
  7972. pid: pid_t
  7973. options: int
  7974. Wait for completion of a specific child process.
  7975. Returns a tuple of information about the child process:
  7976. (pid, status, rusage)
  7977. [clinic start generated code]*/
  7978. static PyObject *
  7979. os_wait4_impl(PyObject *module, pid_t pid, int options)
  7980. /*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
  7981. {
  7982. pid_t res;
  7983. struct rusage ru;
  7984. int async_err = 0;
  7985. WAIT_TYPE status;
  7986. WAIT_STATUS_INT(status) = 0;
  7987. do {
  7988. Py_BEGIN_ALLOW_THREADS
  7989. res = wait4(pid, &status, options, &ru);
  7990. Py_END_ALLOW_THREADS
  7991. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  7992. if (res < 0)
  7993. return (!async_err) ? posix_error() : NULL;
  7994. return wait_helper(module, res, WAIT_STATUS_INT(status), &ru);
  7995. }
  7996. #endif /* HAVE_WAIT4 */
  7997. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  7998. /*[clinic input]
  7999. os.waitid
  8000. idtype: idtype_t
  8001. Must be one of be P_PID, P_PGID or P_ALL.
  8002. id: id_t
  8003. The id to wait on.
  8004. options: int
  8005. Constructed from the ORing of one or more of WEXITED, WSTOPPED
  8006. or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
  8007. /
  8008. Returns the result of waiting for a process or processes.
  8009. Returns either waitid_result or None if WNOHANG is specified and there are
  8010. no children in a waitable state.
  8011. [clinic start generated code]*/
  8012. static PyObject *
  8013. os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
  8014. /*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
  8015. {
  8016. PyObject *result;
  8017. int res;
  8018. int async_err = 0;
  8019. siginfo_t si;
  8020. si.si_pid = 0;
  8021. do {
  8022. Py_BEGIN_ALLOW_THREADS
  8023. res = waitid(idtype, id, &si, options);
  8024. Py_END_ALLOW_THREADS
  8025. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8026. if (res < 0)
  8027. return (!async_err) ? posix_error() : NULL;
  8028. if (si.si_pid == 0)
  8029. Py_RETURN_NONE;
  8030. PyObject *WaitidResultType = get_posix_state(module)->WaitidResultType;
  8031. result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
  8032. if (!result)
  8033. return NULL;
  8034. int pos = 0;
  8035. #define SET_RESULT(CALL) \
  8036. do { \
  8037. PyObject *item = (CALL); \
  8038. if (item == NULL) { \
  8039. Py_DECREF(result); \
  8040. return NULL; \
  8041. } \
  8042. PyStructSequence_SET_ITEM(result, pos++, item); \
  8043. } while(0)
  8044. SET_RESULT(PyLong_FromPid(si.si_pid));
  8045. SET_RESULT(_PyLong_FromUid(si.si_uid));
  8046. SET_RESULT(PyLong_FromLong((long)(si.si_signo)));
  8047. SET_RESULT(PyLong_FromLong((long)(si.si_status)));
  8048. SET_RESULT(PyLong_FromLong((long)(si.si_code)));
  8049. #undef SET_RESULT
  8050. return result;
  8051. }
  8052. #endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
  8053. #if defined(HAVE_WAITPID)
  8054. /*[clinic input]
  8055. os.waitpid
  8056. pid: pid_t
  8057. options: int
  8058. /
  8059. Wait for completion of a given child process.
  8060. Returns a tuple of information regarding the child process:
  8061. (pid, status)
  8062. The options argument is ignored on Windows.
  8063. [clinic start generated code]*/
  8064. static PyObject *
  8065. os_waitpid_impl(PyObject *module, pid_t pid, int options)
  8066. /*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
  8067. {
  8068. pid_t res;
  8069. int async_err = 0;
  8070. WAIT_TYPE status;
  8071. WAIT_STATUS_INT(status) = 0;
  8072. do {
  8073. Py_BEGIN_ALLOW_THREADS
  8074. res = waitpid(pid, &status, options);
  8075. Py_END_ALLOW_THREADS
  8076. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8077. if (res < 0)
  8078. return (!async_err) ? posix_error() : NULL;
  8079. return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
  8080. }
  8081. #elif defined(HAVE_CWAIT)
  8082. /* MS C has a variant of waitpid() that's usable for most purposes. */
  8083. /*[clinic input]
  8084. os.waitpid
  8085. pid: intptr_t
  8086. options: int
  8087. /
  8088. Wait for completion of a given process.
  8089. Returns a tuple of information regarding the process:
  8090. (pid, status << 8)
  8091. The options argument is ignored on Windows.
  8092. [clinic start generated code]*/
  8093. static PyObject *
  8094. os_waitpid_impl(PyObject *module, intptr_t pid, int options)
  8095. /*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
  8096. {
  8097. int status;
  8098. intptr_t res;
  8099. int async_err = 0;
  8100. do {
  8101. Py_BEGIN_ALLOW_THREADS
  8102. _Py_BEGIN_SUPPRESS_IPH
  8103. res = _cwait(&status, pid, options);
  8104. _Py_END_SUPPRESS_IPH
  8105. Py_END_ALLOW_THREADS
  8106. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8107. if (res < 0)
  8108. return (!async_err) ? posix_error() : NULL;
  8109. unsigned long long ustatus = (unsigned int)status;
  8110. /* shift the status left a byte so this is more like the POSIX waitpid */
  8111. return Py_BuildValue(_Py_PARSE_INTPTR "K", res, ustatus << 8);
  8112. }
  8113. #endif
  8114. #ifdef HAVE_WAIT
  8115. /*[clinic input]
  8116. os.wait
  8117. Wait for completion of a child process.
  8118. Returns a tuple of information about the child process:
  8119. (pid, status)
  8120. [clinic start generated code]*/
  8121. static PyObject *
  8122. os_wait_impl(PyObject *module)
  8123. /*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
  8124. {
  8125. pid_t pid;
  8126. int async_err = 0;
  8127. WAIT_TYPE status;
  8128. WAIT_STATUS_INT(status) = 0;
  8129. do {
  8130. Py_BEGIN_ALLOW_THREADS
  8131. pid = wait(&status);
  8132. Py_END_ALLOW_THREADS
  8133. } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8134. if (pid < 0)
  8135. return (!async_err) ? posix_error() : NULL;
  8136. return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
  8137. }
  8138. #endif /* HAVE_WAIT */
  8139. #if defined(__linux__) && defined(__NR_pidfd_open)
  8140. /*[clinic input]
  8141. os.pidfd_open
  8142. pid: pid_t
  8143. flags: unsigned_int = 0
  8144. Return a file descriptor referring to the process *pid*.
  8145. The descriptor can be used to perform process management without races and
  8146. signals.
  8147. [clinic start generated code]*/
  8148. static PyObject *
  8149. os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
  8150. /*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
  8151. {
  8152. int fd = syscall(__NR_pidfd_open, pid, flags);
  8153. if (fd < 0) {
  8154. return posix_error();
  8155. }
  8156. return PyLong_FromLong(fd);
  8157. }
  8158. #endif
  8159. #ifdef HAVE_SETNS
  8160. /*[clinic input]
  8161. os.setns
  8162. fd: fildes
  8163. A file descriptor to a namespace.
  8164. nstype: int = 0
  8165. Type of namespace.
  8166. Move the calling thread into different namespaces.
  8167. [clinic start generated code]*/
  8168. static PyObject *
  8169. os_setns_impl(PyObject *module, int fd, int nstype)
  8170. /*[clinic end generated code: output=5dbd055bfb66ecd0 input=42787871226bf3ee]*/
  8171. {
  8172. int res;
  8173. Py_BEGIN_ALLOW_THREADS
  8174. res = setns(fd, nstype);
  8175. Py_END_ALLOW_THREADS
  8176. if (res != 0) {
  8177. return posix_error();
  8178. }
  8179. Py_RETURN_NONE;
  8180. }
  8181. #endif
  8182. #ifdef HAVE_UNSHARE
  8183. /*[clinic input]
  8184. os.unshare
  8185. flags: int
  8186. Namespaces to be unshared.
  8187. Disassociate parts of a process (or thread) execution context.
  8188. [clinic start generated code]*/
  8189. static PyObject *
  8190. os_unshare_impl(PyObject *module, int flags)
  8191. /*[clinic end generated code: output=1b3177906dd237ee input=9e065db3232b8b1b]*/
  8192. {
  8193. int res;
  8194. Py_BEGIN_ALLOW_THREADS
  8195. res = unshare(flags);
  8196. Py_END_ALLOW_THREADS
  8197. if (res != 0) {
  8198. return posix_error();
  8199. }
  8200. Py_RETURN_NONE;
  8201. }
  8202. #endif
  8203. #if defined(HAVE_READLINK) || defined(MS_WINDOWS)
  8204. /*[clinic input]
  8205. os.readlink
  8206. path: path_t
  8207. *
  8208. dir_fd: dir_fd(requires='readlinkat') = None
  8209. Return a string representing the path to which the symbolic link points.
  8210. If dir_fd is not None, it should be a file descriptor open to a directory,
  8211. and path should be relative; path will then be relative to that directory.
  8212. dir_fd may not be implemented on your platform. If it is unavailable,
  8213. using it will raise a NotImplementedError.
  8214. [clinic start generated code]*/
  8215. static PyObject *
  8216. os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
  8217. /*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
  8218. {
  8219. #if defined(HAVE_READLINK)
  8220. char buffer[MAXPATHLEN+1];
  8221. ssize_t length;
  8222. #ifdef HAVE_READLINKAT
  8223. int readlinkat_unavailable = 0;
  8224. #endif
  8225. Py_BEGIN_ALLOW_THREADS
  8226. #ifdef HAVE_READLINKAT
  8227. if (dir_fd != DEFAULT_DIR_FD) {
  8228. if (HAVE_READLINKAT_RUNTIME) {
  8229. length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
  8230. } else {
  8231. readlinkat_unavailable = 1;
  8232. }
  8233. } else
  8234. #endif
  8235. length = readlink(path->narrow, buffer, MAXPATHLEN);
  8236. Py_END_ALLOW_THREADS
  8237. #ifdef HAVE_READLINKAT
  8238. if (readlinkat_unavailable) {
  8239. argument_unavailable_error(NULL, "dir_fd");
  8240. return NULL;
  8241. }
  8242. #endif
  8243. if (length < 0) {
  8244. return path_error(path);
  8245. }
  8246. buffer[length] = '\0';
  8247. if (PyUnicode_Check(path->object))
  8248. return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
  8249. else
  8250. return PyBytes_FromStringAndSize(buffer, length);
  8251. #elif defined(MS_WINDOWS)
  8252. DWORD n_bytes_returned;
  8253. DWORD io_result = 0;
  8254. HANDLE reparse_point_handle;
  8255. char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
  8256. _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
  8257. PyObject *result = NULL;
  8258. /* First get a handle to the reparse point */
  8259. Py_BEGIN_ALLOW_THREADS
  8260. reparse_point_handle = CreateFileW(
  8261. path->wide,
  8262. 0,
  8263. 0,
  8264. 0,
  8265. OPEN_EXISTING,
  8266. FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
  8267. 0);
  8268. if (reparse_point_handle != INVALID_HANDLE_VALUE) {
  8269. /* New call DeviceIoControl to read the reparse point */
  8270. io_result = DeviceIoControl(
  8271. reparse_point_handle,
  8272. FSCTL_GET_REPARSE_POINT,
  8273. 0, 0, /* in buffer */
  8274. target_buffer, sizeof(target_buffer),
  8275. &n_bytes_returned,
  8276. 0 /* we're not using OVERLAPPED_IO */
  8277. );
  8278. CloseHandle(reparse_point_handle);
  8279. }
  8280. Py_END_ALLOW_THREADS
  8281. if (io_result == 0) {
  8282. return path_error(path);
  8283. }
  8284. wchar_t *name = NULL;
  8285. Py_ssize_t nameLen = 0;
  8286. if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
  8287. {
  8288. name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
  8289. rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
  8290. nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
  8291. }
  8292. else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
  8293. {
  8294. name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
  8295. rdb->MountPointReparseBuffer.SubstituteNameOffset);
  8296. nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
  8297. }
  8298. else
  8299. {
  8300. PyErr_SetString(PyExc_ValueError, "not a symbolic link");
  8301. }
  8302. if (name) {
  8303. if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
  8304. /* Our buffer is mutable, so this is okay */
  8305. name[1] = L'\\';
  8306. }
  8307. result = PyUnicode_FromWideChar(name, nameLen);
  8308. if (result && path->narrow) {
  8309. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  8310. }
  8311. }
  8312. return result;
  8313. #endif
  8314. }
  8315. #endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
  8316. #if defined(MS_WINDOWS)
  8317. /* Remove the last portion of the path - return 0 on success */
  8318. static int
  8319. _dirnameW(WCHAR *path)
  8320. {
  8321. WCHAR *ptr;
  8322. size_t length = wcsnlen_s(path, MAX_PATH);
  8323. if (length == MAX_PATH) {
  8324. return -1;
  8325. }
  8326. /* walk the path from the end until a backslash is encountered */
  8327. for(ptr = path + length; ptr != path; ptr--) {
  8328. if (*ptr == L'\\' || *ptr == L'/') {
  8329. break;
  8330. }
  8331. }
  8332. *ptr = 0;
  8333. return 0;
  8334. }
  8335. #endif
  8336. #ifdef HAVE_SYMLINK
  8337. #if defined(MS_WINDOWS)
  8338. /* Is this path absolute? */
  8339. static int
  8340. _is_absW(const WCHAR *path)
  8341. {
  8342. return path[0] == L'\\' || path[0] == L'/' ||
  8343. (path[0] && path[1] == L':');
  8344. }
  8345. /* join root and rest with a backslash - return 0 on success */
  8346. static int
  8347. _joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
  8348. {
  8349. if (_is_absW(rest)) {
  8350. return wcscpy_s(dest_path, MAX_PATH, rest);
  8351. }
  8352. if (wcscpy_s(dest_path, MAX_PATH, root)) {
  8353. return -1;
  8354. }
  8355. if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
  8356. return -1;
  8357. }
  8358. return wcscat_s(dest_path, MAX_PATH, rest);
  8359. }
  8360. /* Return True if the path at src relative to dest is a directory */
  8361. static int
  8362. _check_dirW(LPCWSTR src, LPCWSTR dest)
  8363. {
  8364. WIN32_FILE_ATTRIBUTE_DATA src_info;
  8365. WCHAR dest_parent[MAX_PATH];
  8366. WCHAR src_resolved[MAX_PATH] = L"";
  8367. /* dest_parent = os.path.dirname(dest) */
  8368. if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
  8369. _dirnameW(dest_parent)) {
  8370. return 0;
  8371. }
  8372. /* src_resolved = os.path.join(dest_parent, src) */
  8373. if (_joinW(src_resolved, dest_parent, src)) {
  8374. return 0;
  8375. }
  8376. return (
  8377. GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
  8378. && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
  8379. );
  8380. }
  8381. #endif
  8382. /*[clinic input]
  8383. os.symlink
  8384. src: path_t
  8385. dst: path_t
  8386. target_is_directory: bool = False
  8387. *
  8388. dir_fd: dir_fd(requires='symlinkat')=None
  8389. # "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
  8390. Create a symbolic link pointing to src named dst.
  8391. target_is_directory is required on Windows if the target is to be
  8392. interpreted as a directory. (On Windows, symlink requires
  8393. Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
  8394. target_is_directory is ignored on non-Windows platforms.
  8395. If dir_fd is not None, it should be a file descriptor open to a directory,
  8396. and path should be relative; path will then be relative to that directory.
  8397. dir_fd may not be implemented on your platform.
  8398. If it is unavailable, using it will raise a NotImplementedError.
  8399. [clinic start generated code]*/
  8400. static PyObject *
  8401. os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
  8402. int target_is_directory, int dir_fd)
  8403. /*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
  8404. {
  8405. #ifdef MS_WINDOWS
  8406. DWORD result;
  8407. DWORD flags = 0;
  8408. /* Assumed true, set to false if detected to not be available. */
  8409. static int windows_has_symlink_unprivileged_flag = TRUE;
  8410. #else
  8411. int result;
  8412. #ifdef HAVE_SYMLINKAT
  8413. int symlinkat_unavailable = 0;
  8414. #endif
  8415. #endif
  8416. if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
  8417. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  8418. return NULL;
  8419. }
  8420. #ifdef MS_WINDOWS
  8421. if (windows_has_symlink_unprivileged_flag) {
  8422. /* Allow non-admin symlinks if system allows it. */
  8423. flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
  8424. }
  8425. Py_BEGIN_ALLOW_THREADS
  8426. _Py_BEGIN_SUPPRESS_IPH
  8427. /* if src is a directory, ensure flags==1 (target_is_directory bit) */
  8428. if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
  8429. flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
  8430. }
  8431. result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
  8432. _Py_END_SUPPRESS_IPH
  8433. Py_END_ALLOW_THREADS
  8434. if (windows_has_symlink_unprivileged_flag && !result &&
  8435. ERROR_INVALID_PARAMETER == GetLastError()) {
  8436. Py_BEGIN_ALLOW_THREADS
  8437. _Py_BEGIN_SUPPRESS_IPH
  8438. /* This error might be caused by
  8439. SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
  8440. Try again, and update windows_has_symlink_unprivileged_flag if we
  8441. are successful this time.
  8442. NOTE: There is a risk of a race condition here if there are other
  8443. conditions than the flag causing ERROR_INVALID_PARAMETER, and
  8444. another process (or thread) changes that condition in between our
  8445. calls to CreateSymbolicLink.
  8446. */
  8447. flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
  8448. result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
  8449. _Py_END_SUPPRESS_IPH
  8450. Py_END_ALLOW_THREADS
  8451. if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
  8452. windows_has_symlink_unprivileged_flag = FALSE;
  8453. }
  8454. }
  8455. if (!result)
  8456. return path_error2(src, dst);
  8457. #else
  8458. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  8459. PyErr_SetString(PyExc_ValueError,
  8460. "symlink: src and dst must be the same type");
  8461. return NULL;
  8462. }
  8463. Py_BEGIN_ALLOW_THREADS
  8464. #ifdef HAVE_SYMLINKAT
  8465. if (dir_fd != DEFAULT_DIR_FD) {
  8466. if (HAVE_SYMLINKAT_RUNTIME) {
  8467. result = symlinkat(src->narrow, dir_fd, dst->narrow);
  8468. } else {
  8469. symlinkat_unavailable = 1;
  8470. }
  8471. } else
  8472. #endif
  8473. result = symlink(src->narrow, dst->narrow);
  8474. Py_END_ALLOW_THREADS
  8475. #ifdef HAVE_SYMLINKAT
  8476. if (symlinkat_unavailable) {
  8477. argument_unavailable_error(NULL, "dir_fd");
  8478. return NULL;
  8479. }
  8480. #endif
  8481. if (result)
  8482. return path_error2(src, dst);
  8483. #endif
  8484. Py_RETURN_NONE;
  8485. }
  8486. #endif /* HAVE_SYMLINK */
  8487. static PyStructSequence_Field times_result_fields[] = {
  8488. {"user", "user time"},
  8489. {"system", "system time"},
  8490. {"children_user", "user time of children"},
  8491. {"children_system", "system time of children"},
  8492. {"elapsed", "elapsed time since an arbitrary point in the past"},
  8493. {NULL}
  8494. };
  8495. PyDoc_STRVAR(times_result__doc__,
  8496. "times_result: Result from os.times().\n\n\
  8497. This object may be accessed either as a tuple of\n\
  8498. (user, system, children_user, children_system, elapsed),\n\
  8499. or via the attributes user, system, children_user, children_system,\n\
  8500. and elapsed.\n\
  8501. \n\
  8502. See os.times for more information.");
  8503. static PyStructSequence_Desc times_result_desc = {
  8504. "times_result", /* name */
  8505. times_result__doc__, /* doc */
  8506. times_result_fields,
  8507. 5
  8508. };
  8509. #ifdef MS_WINDOWS
  8510. #define HAVE_TIMES /* mandatory, for the method table */
  8511. #endif
  8512. #ifdef HAVE_TIMES
  8513. static PyObject *
  8514. build_times_result(PyObject *module, double user, double system,
  8515. double children_user, double children_system,
  8516. double elapsed)
  8517. {
  8518. PyObject *TimesResultType = get_posix_state(module)->TimesResultType;
  8519. PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
  8520. if (value == NULL)
  8521. return NULL;
  8522. #define SET(i, field) \
  8523. { \
  8524. PyObject *o = PyFloat_FromDouble(field); \
  8525. if (!o) { \
  8526. Py_DECREF(value); \
  8527. return NULL; \
  8528. } \
  8529. PyStructSequence_SET_ITEM(value, i, o); \
  8530. } \
  8531. SET(0, user);
  8532. SET(1, system);
  8533. SET(2, children_user);
  8534. SET(3, children_system);
  8535. SET(4, elapsed);
  8536. #undef SET
  8537. return value;
  8538. }
  8539. /*[clinic input]
  8540. os.times
  8541. Return a collection containing process timing information.
  8542. The object returned behaves like a named tuple with these fields:
  8543. (utime, stime, cutime, cstime, elapsed_time)
  8544. All fields are floating point numbers.
  8545. [clinic start generated code]*/
  8546. static PyObject *
  8547. os_times_impl(PyObject *module)
  8548. /*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
  8549. #ifdef MS_WINDOWS
  8550. {
  8551. FILETIME create, exit, kernel, user;
  8552. HANDLE hProc;
  8553. hProc = GetCurrentProcess();
  8554. GetProcessTimes(hProc, &create, &exit, &kernel, &user);
  8555. /* The fields of a FILETIME structure are the hi and lo part
  8556. of a 64-bit value expressed in 100 nanosecond units.
  8557. 1e7 is one second in such units; 1e-7 the inverse.
  8558. 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
  8559. */
  8560. return build_times_result(module,
  8561. (double)(user.dwHighDateTime*429.4967296 +
  8562. user.dwLowDateTime*1e-7),
  8563. (double)(kernel.dwHighDateTime*429.4967296 +
  8564. kernel.dwLowDateTime*1e-7),
  8565. (double)0,
  8566. (double)0,
  8567. (double)0);
  8568. }
  8569. #else /* MS_WINDOWS */
  8570. {
  8571. struct tms t;
  8572. clock_t c;
  8573. errno = 0;
  8574. c = times(&t);
  8575. if (c == (clock_t) -1) {
  8576. return posix_error();
  8577. }
  8578. assert(_PyRuntime.time.ticks_per_second_initialized);
  8579. #define ticks_per_second _PyRuntime.time.ticks_per_second
  8580. return build_times_result(module,
  8581. (double)t.tms_utime / ticks_per_second,
  8582. (double)t.tms_stime / ticks_per_second,
  8583. (double)t.tms_cutime / ticks_per_second,
  8584. (double)t.tms_cstime / ticks_per_second,
  8585. (double)c / ticks_per_second);
  8586. #undef ticks_per_second
  8587. }
  8588. #endif /* MS_WINDOWS */
  8589. #endif /* HAVE_TIMES */
  8590. #ifdef HAVE_GETSID
  8591. /*[clinic input]
  8592. os.getsid
  8593. pid: pid_t
  8594. /
  8595. Call the system call getsid(pid) and return the result.
  8596. [clinic start generated code]*/
  8597. static PyObject *
  8598. os_getsid_impl(PyObject *module, pid_t pid)
  8599. /*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
  8600. {
  8601. int sid;
  8602. sid = getsid(pid);
  8603. if (sid < 0)
  8604. return posix_error();
  8605. return PyLong_FromLong((long)sid);
  8606. }
  8607. #endif /* HAVE_GETSID */
  8608. #ifdef HAVE_SETSID
  8609. /*[clinic input]
  8610. os.setsid
  8611. Call the system call setsid().
  8612. [clinic start generated code]*/
  8613. static PyObject *
  8614. os_setsid_impl(PyObject *module)
  8615. /*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
  8616. {
  8617. if (setsid() < 0)
  8618. return posix_error();
  8619. Py_RETURN_NONE;
  8620. }
  8621. #endif /* HAVE_SETSID */
  8622. #ifdef HAVE_SETPGID
  8623. /*[clinic input]
  8624. os.setpgid
  8625. pid: pid_t
  8626. pgrp: pid_t
  8627. /
  8628. Call the system call setpgid(pid, pgrp).
  8629. [clinic start generated code]*/
  8630. static PyObject *
  8631. os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
  8632. /*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
  8633. {
  8634. if (setpgid(pid, pgrp) < 0)
  8635. return posix_error();
  8636. Py_RETURN_NONE;
  8637. }
  8638. #endif /* HAVE_SETPGID */
  8639. #ifdef HAVE_TCGETPGRP
  8640. /*[clinic input]
  8641. os.tcgetpgrp
  8642. fd: int
  8643. /
  8644. Return the process group associated with the terminal specified by fd.
  8645. [clinic start generated code]*/
  8646. static PyObject *
  8647. os_tcgetpgrp_impl(PyObject *module, int fd)
  8648. /*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
  8649. {
  8650. pid_t pgid = tcgetpgrp(fd);
  8651. if (pgid < 0)
  8652. return posix_error();
  8653. return PyLong_FromPid(pgid);
  8654. }
  8655. #endif /* HAVE_TCGETPGRP */
  8656. #ifdef HAVE_TCSETPGRP
  8657. /*[clinic input]
  8658. os.tcsetpgrp
  8659. fd: int
  8660. pgid: pid_t
  8661. /
  8662. Set the process group associated with the terminal specified by fd.
  8663. [clinic start generated code]*/
  8664. static PyObject *
  8665. os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
  8666. /*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
  8667. {
  8668. if (tcsetpgrp(fd, pgid) < 0)
  8669. return posix_error();
  8670. Py_RETURN_NONE;
  8671. }
  8672. #endif /* HAVE_TCSETPGRP */
  8673. /* Functions acting on file descriptors */
  8674. #ifdef O_CLOEXEC
  8675. extern int _Py_open_cloexec_works;
  8676. #endif
  8677. /*[clinic input]
  8678. os.open -> int
  8679. path: path_t
  8680. flags: int
  8681. mode: int = 0o777
  8682. *
  8683. dir_fd: dir_fd(requires='openat') = None
  8684. # "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
  8685. Open a file for low level IO. Returns a file descriptor (integer).
  8686. If dir_fd is not None, it should be a file descriptor open to a directory,
  8687. and path should be relative; path will then be relative to that directory.
  8688. dir_fd may not be implemented on your platform.
  8689. If it is unavailable, using it will raise a NotImplementedError.
  8690. [clinic start generated code]*/
  8691. static int
  8692. os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
  8693. /*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
  8694. {
  8695. int fd;
  8696. int async_err = 0;
  8697. #ifdef HAVE_OPENAT
  8698. int openat_unavailable = 0;
  8699. #endif
  8700. #ifdef O_CLOEXEC
  8701. int *atomic_flag_works = &_Py_open_cloexec_works;
  8702. #elif !defined(MS_WINDOWS)
  8703. int *atomic_flag_works = NULL;
  8704. #endif
  8705. #ifdef MS_WINDOWS
  8706. flags |= O_NOINHERIT;
  8707. #elif defined(O_CLOEXEC)
  8708. flags |= O_CLOEXEC;
  8709. #endif
  8710. if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
  8711. return -1;
  8712. }
  8713. _Py_BEGIN_SUPPRESS_IPH
  8714. do {
  8715. Py_BEGIN_ALLOW_THREADS
  8716. #ifdef MS_WINDOWS
  8717. fd = _wopen(path->wide, flags, mode);
  8718. #else
  8719. #ifdef HAVE_OPENAT
  8720. if (dir_fd != DEFAULT_DIR_FD) {
  8721. if (HAVE_OPENAT_RUNTIME) {
  8722. fd = openat(dir_fd, path->narrow, flags, mode);
  8723. } else {
  8724. openat_unavailable = 1;
  8725. fd = -1;
  8726. }
  8727. } else
  8728. #endif /* HAVE_OPENAT */
  8729. fd = open(path->narrow, flags, mode);
  8730. #endif /* !MS_WINDOWS */
  8731. Py_END_ALLOW_THREADS
  8732. } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8733. _Py_END_SUPPRESS_IPH
  8734. #ifdef HAVE_OPENAT
  8735. if (openat_unavailable) {
  8736. argument_unavailable_error(NULL, "dir_fd");
  8737. return -1;
  8738. }
  8739. #endif
  8740. if (fd < 0) {
  8741. if (!async_err)
  8742. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
  8743. return -1;
  8744. }
  8745. #ifndef MS_WINDOWS
  8746. if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
  8747. close(fd);
  8748. return -1;
  8749. }
  8750. #endif
  8751. return fd;
  8752. }
  8753. /*[clinic input]
  8754. os.close
  8755. fd: int
  8756. Close a file descriptor.
  8757. [clinic start generated code]*/
  8758. static PyObject *
  8759. os_close_impl(PyObject *module, int fd)
  8760. /*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
  8761. {
  8762. int res;
  8763. /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
  8764. * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
  8765. * for more details.
  8766. */
  8767. Py_BEGIN_ALLOW_THREADS
  8768. _Py_BEGIN_SUPPRESS_IPH
  8769. res = close(fd);
  8770. _Py_END_SUPPRESS_IPH
  8771. Py_END_ALLOW_THREADS
  8772. if (res < 0)
  8773. return posix_error();
  8774. Py_RETURN_NONE;
  8775. }
  8776. /*[clinic input]
  8777. os.closerange
  8778. fd_low: int
  8779. fd_high: int
  8780. /
  8781. Closes all file descriptors in [fd_low, fd_high), ignoring errors.
  8782. [clinic start generated code]*/
  8783. static PyObject *
  8784. os_closerange_impl(PyObject *module, int fd_low, int fd_high)
  8785. /*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
  8786. {
  8787. Py_BEGIN_ALLOW_THREADS
  8788. _Py_closerange(fd_low, fd_high - 1);
  8789. Py_END_ALLOW_THREADS
  8790. Py_RETURN_NONE;
  8791. }
  8792. /*[clinic input]
  8793. os.dup -> int
  8794. fd: int
  8795. /
  8796. Return a duplicate of a file descriptor.
  8797. [clinic start generated code]*/
  8798. static int
  8799. os_dup_impl(PyObject *module, int fd)
  8800. /*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
  8801. {
  8802. return _Py_dup(fd);
  8803. }
  8804. // dup2() is either provided by libc or dup2.c with AC_REPLACE_FUNCS().
  8805. // dup2.c provides working dup2() if and only if F_DUPFD is available.
  8806. #if (defined(HAVE_DUP3) || defined(F_DUPFD) || defined(MS_WINDOWS))
  8807. /*[clinic input]
  8808. os.dup2 -> int
  8809. fd: int
  8810. fd2: int
  8811. inheritable: bool=True
  8812. Duplicate file descriptor.
  8813. [clinic start generated code]*/
  8814. static int
  8815. os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
  8816. /*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
  8817. {
  8818. int res = 0;
  8819. #if defined(HAVE_DUP3) && \
  8820. !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
  8821. /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
  8822. static int dup3_works = -1;
  8823. #endif
  8824. /* dup2() can fail with EINTR if the target FD is already open, because it
  8825. * then has to be closed. See os_close_impl() for why we don't handle EINTR
  8826. * upon close(), and therefore below.
  8827. */
  8828. #ifdef MS_WINDOWS
  8829. Py_BEGIN_ALLOW_THREADS
  8830. _Py_BEGIN_SUPPRESS_IPH
  8831. res = dup2(fd, fd2);
  8832. _Py_END_SUPPRESS_IPH
  8833. Py_END_ALLOW_THREADS
  8834. if (res < 0) {
  8835. posix_error();
  8836. return -1;
  8837. }
  8838. res = fd2; // msvcrt dup2 returns 0 on success.
  8839. /* Character files like console cannot be make non-inheritable */
  8840. if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
  8841. close(fd2);
  8842. return -1;
  8843. }
  8844. #elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
  8845. Py_BEGIN_ALLOW_THREADS
  8846. if (!inheritable)
  8847. res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
  8848. else
  8849. res = dup2(fd, fd2);
  8850. Py_END_ALLOW_THREADS
  8851. if (res < 0) {
  8852. posix_error();
  8853. return -1;
  8854. }
  8855. #else
  8856. #ifdef HAVE_DUP3
  8857. if (!inheritable && dup3_works != 0) {
  8858. Py_BEGIN_ALLOW_THREADS
  8859. res = dup3(fd, fd2, O_CLOEXEC);
  8860. Py_END_ALLOW_THREADS
  8861. if (res < 0) {
  8862. if (dup3_works == -1)
  8863. dup3_works = (errno != ENOSYS);
  8864. if (dup3_works) {
  8865. posix_error();
  8866. return -1;
  8867. }
  8868. }
  8869. }
  8870. if (inheritable || dup3_works == 0)
  8871. {
  8872. #endif
  8873. Py_BEGIN_ALLOW_THREADS
  8874. res = dup2(fd, fd2);
  8875. Py_END_ALLOW_THREADS
  8876. if (res < 0) {
  8877. posix_error();
  8878. return -1;
  8879. }
  8880. if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
  8881. close(fd2);
  8882. return -1;
  8883. }
  8884. #ifdef HAVE_DUP3
  8885. }
  8886. #endif
  8887. #endif
  8888. return res;
  8889. }
  8890. #endif
  8891. #ifdef HAVE_LOCKF
  8892. /*[clinic input]
  8893. os.lockf
  8894. fd: int
  8895. An open file descriptor.
  8896. command: int
  8897. One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
  8898. length: Py_off_t
  8899. The number of bytes to lock, starting at the current position.
  8900. /
  8901. Apply, test or remove a POSIX lock on an open file descriptor.
  8902. [clinic start generated code]*/
  8903. static PyObject *
  8904. os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
  8905. /*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
  8906. {
  8907. int res;
  8908. if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
  8909. return NULL;
  8910. }
  8911. Py_BEGIN_ALLOW_THREADS
  8912. res = lockf(fd, command, length);
  8913. Py_END_ALLOW_THREADS
  8914. if (res < 0)
  8915. return posix_error();
  8916. Py_RETURN_NONE;
  8917. }
  8918. #endif /* HAVE_LOCKF */
  8919. /*[clinic input]
  8920. os.lseek -> Py_off_t
  8921. fd: int
  8922. An open file descriptor, as returned by os.open().
  8923. position: Py_off_t
  8924. Position, interpreted relative to 'whence'.
  8925. whence as how: int
  8926. The relative position to seek from. Valid values are:
  8927. - SEEK_SET: seek from the start of the file.
  8928. - SEEK_CUR: seek from the current file position.
  8929. - SEEK_END: seek from the end of the file.
  8930. /
  8931. Set the position of a file descriptor. Return the new position.
  8932. The return value is the number of bytes relative to the beginning of the file.
  8933. [clinic start generated code]*/
  8934. static Py_off_t
  8935. os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
  8936. /*[clinic end generated code: output=971e1efb6b30bd2f input=f096e754c5367504]*/
  8937. {
  8938. Py_off_t result;
  8939. #ifdef SEEK_SET
  8940. /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
  8941. switch (how) {
  8942. case 0: how = SEEK_SET; break;
  8943. case 1: how = SEEK_CUR; break;
  8944. case 2: how = SEEK_END; break;
  8945. }
  8946. #endif /* SEEK_END */
  8947. Py_BEGIN_ALLOW_THREADS
  8948. _Py_BEGIN_SUPPRESS_IPH
  8949. #ifdef MS_WINDOWS
  8950. result = _lseeki64(fd, position, how);
  8951. #else
  8952. result = lseek(fd, position, how);
  8953. #endif
  8954. _Py_END_SUPPRESS_IPH
  8955. Py_END_ALLOW_THREADS
  8956. if (result < 0)
  8957. posix_error();
  8958. return result;
  8959. }
  8960. /*[clinic input]
  8961. os.read
  8962. fd: int
  8963. length: Py_ssize_t
  8964. /
  8965. Read from a file descriptor. Returns a bytes object.
  8966. [clinic start generated code]*/
  8967. static PyObject *
  8968. os_read_impl(PyObject *module, int fd, Py_ssize_t length)
  8969. /*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
  8970. {
  8971. Py_ssize_t n;
  8972. PyObject *buffer;
  8973. if (length < 0) {
  8974. errno = EINVAL;
  8975. return posix_error();
  8976. }
  8977. length = Py_MIN(length, _PY_READ_MAX);
  8978. buffer = PyBytes_FromStringAndSize((char *)NULL, length);
  8979. if (buffer == NULL)
  8980. return NULL;
  8981. n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
  8982. if (n == -1) {
  8983. Py_DECREF(buffer);
  8984. return NULL;
  8985. }
  8986. if (n != length)
  8987. _PyBytes_Resize(&buffer, n);
  8988. return buffer;
  8989. }
  8990. #if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
  8991. || defined(__APPLE__))) \
  8992. || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
  8993. || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
  8994. static int
  8995. iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
  8996. {
  8997. Py_ssize_t i, j;
  8998. *iov = PyMem_New(struct iovec, cnt);
  8999. if (*iov == NULL) {
  9000. PyErr_NoMemory();
  9001. return -1;
  9002. }
  9003. *buf = PyMem_New(Py_buffer, cnt);
  9004. if (*buf == NULL) {
  9005. PyMem_Free(*iov);
  9006. PyErr_NoMemory();
  9007. return -1;
  9008. }
  9009. for (i = 0; i < cnt; i++) {
  9010. PyObject *item = PySequence_GetItem(seq, i);
  9011. if (item == NULL)
  9012. goto fail;
  9013. if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
  9014. Py_DECREF(item);
  9015. goto fail;
  9016. }
  9017. Py_DECREF(item);
  9018. (*iov)[i].iov_base = (*buf)[i].buf;
  9019. (*iov)[i].iov_len = (*buf)[i].len;
  9020. }
  9021. return 0;
  9022. fail:
  9023. PyMem_Free(*iov);
  9024. for (j = 0; j < i; j++) {
  9025. PyBuffer_Release(&(*buf)[j]);
  9026. }
  9027. PyMem_Free(*buf);
  9028. return -1;
  9029. }
  9030. static void
  9031. iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
  9032. {
  9033. int i;
  9034. PyMem_Free(iov);
  9035. for (i = 0; i < cnt; i++) {
  9036. PyBuffer_Release(&buf[i]);
  9037. }
  9038. PyMem_Free(buf);
  9039. }
  9040. #endif
  9041. #ifdef HAVE_READV
  9042. /*[clinic input]
  9043. os.readv -> Py_ssize_t
  9044. fd: int
  9045. buffers: object
  9046. /
  9047. Read from a file descriptor fd into an iterable of buffers.
  9048. The buffers should be mutable buffers accepting bytes.
  9049. readv will transfer data into each buffer until it is full
  9050. and then move on to the next buffer in the sequence to hold
  9051. the rest of the data.
  9052. readv returns the total number of bytes read,
  9053. which may be less than the total capacity of all the buffers.
  9054. [clinic start generated code]*/
  9055. static Py_ssize_t
  9056. os_readv_impl(PyObject *module, int fd, PyObject *buffers)
  9057. /*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
  9058. {
  9059. Py_ssize_t cnt, n;
  9060. int async_err = 0;
  9061. struct iovec *iov;
  9062. Py_buffer *buf;
  9063. if (!PySequence_Check(buffers)) {
  9064. PyErr_SetString(PyExc_TypeError,
  9065. "readv() arg 2 must be a sequence");
  9066. return -1;
  9067. }
  9068. cnt = PySequence_Size(buffers);
  9069. if (cnt < 0)
  9070. return -1;
  9071. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
  9072. return -1;
  9073. do {
  9074. Py_BEGIN_ALLOW_THREADS
  9075. n = readv(fd, iov, cnt);
  9076. Py_END_ALLOW_THREADS
  9077. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9078. int saved_errno = errno;
  9079. iov_cleanup(iov, buf, cnt);
  9080. if (n < 0) {
  9081. if (!async_err) {
  9082. errno = saved_errno;
  9083. posix_error();
  9084. }
  9085. return -1;
  9086. }
  9087. return n;
  9088. }
  9089. #endif /* HAVE_READV */
  9090. #ifdef HAVE_PREAD
  9091. /*[clinic input]
  9092. os.pread
  9093. fd: int
  9094. length: Py_ssize_t
  9095. offset: Py_off_t
  9096. /
  9097. Read a number of bytes from a file descriptor starting at a particular offset.
  9098. Read length bytes from file descriptor fd, starting at offset bytes from
  9099. the beginning of the file. The file offset remains unchanged.
  9100. [clinic start generated code]*/
  9101. static PyObject *
  9102. os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
  9103. /*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
  9104. {
  9105. Py_ssize_t n;
  9106. int async_err = 0;
  9107. PyObject *buffer;
  9108. if (length < 0) {
  9109. errno = EINVAL;
  9110. return posix_error();
  9111. }
  9112. buffer = PyBytes_FromStringAndSize((char *)NULL, length);
  9113. if (buffer == NULL)
  9114. return NULL;
  9115. do {
  9116. Py_BEGIN_ALLOW_THREADS
  9117. _Py_BEGIN_SUPPRESS_IPH
  9118. n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
  9119. _Py_END_SUPPRESS_IPH
  9120. Py_END_ALLOW_THREADS
  9121. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9122. if (n < 0) {
  9123. if (!async_err) {
  9124. posix_error();
  9125. }
  9126. Py_DECREF(buffer);
  9127. return NULL;
  9128. }
  9129. if (n != length)
  9130. _PyBytes_Resize(&buffer, n);
  9131. return buffer;
  9132. }
  9133. #endif /* HAVE_PREAD */
  9134. #if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
  9135. /*[clinic input]
  9136. os.preadv -> Py_ssize_t
  9137. fd: int
  9138. buffers: object
  9139. offset: Py_off_t
  9140. flags: int = 0
  9141. /
  9142. Reads from a file descriptor into a number of mutable bytes-like objects.
  9143. Combines the functionality of readv() and pread(). As readv(), it will
  9144. transfer data into each buffer until it is full and then move on to the next
  9145. buffer in the sequence to hold the rest of the data. Its fourth argument,
  9146. specifies the file offset at which the input operation is to be performed. It
  9147. will return the total number of bytes read (which can be less than the total
  9148. capacity of all the objects).
  9149. The flags argument contains a bitwise OR of zero or more of the following flags:
  9150. - RWF_HIPRI
  9151. - RWF_NOWAIT
  9152. Using non-zero flags requires Linux 4.6 or newer.
  9153. [clinic start generated code]*/
  9154. static Py_ssize_t
  9155. os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
  9156. int flags)
  9157. /*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
  9158. {
  9159. Py_ssize_t cnt, n;
  9160. int async_err = 0;
  9161. struct iovec *iov;
  9162. Py_buffer *buf;
  9163. if (!PySequence_Check(buffers)) {
  9164. PyErr_SetString(PyExc_TypeError,
  9165. "preadv2() arg 2 must be a sequence");
  9166. return -1;
  9167. }
  9168. cnt = PySequence_Size(buffers);
  9169. if (cnt < 0) {
  9170. return -1;
  9171. }
  9172. #ifndef HAVE_PREADV2
  9173. if(flags != 0) {
  9174. argument_unavailable_error("preadv2", "flags");
  9175. return -1;
  9176. }
  9177. #endif
  9178. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
  9179. return -1;
  9180. }
  9181. #ifdef HAVE_PREADV2
  9182. do {
  9183. Py_BEGIN_ALLOW_THREADS
  9184. _Py_BEGIN_SUPPRESS_IPH
  9185. n = preadv2(fd, iov, cnt, offset, flags);
  9186. _Py_END_SUPPRESS_IPH
  9187. Py_END_ALLOW_THREADS
  9188. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9189. #else
  9190. do {
  9191. #if defined(__APPLE__) && defined(__clang__)
  9192. /* This entire function will be removed from the module dict when the API
  9193. * is not available.
  9194. */
  9195. #pragma clang diagnostic push
  9196. #pragma clang diagnostic ignored "-Wunguarded-availability"
  9197. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  9198. #endif
  9199. Py_BEGIN_ALLOW_THREADS
  9200. _Py_BEGIN_SUPPRESS_IPH
  9201. n = preadv(fd, iov, cnt, offset);
  9202. _Py_END_SUPPRESS_IPH
  9203. Py_END_ALLOW_THREADS
  9204. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9205. #if defined(__APPLE__) && defined(__clang__)
  9206. #pragma clang diagnostic pop
  9207. #endif
  9208. #endif
  9209. int saved_errno = errno;
  9210. iov_cleanup(iov, buf, cnt);
  9211. if (n < 0) {
  9212. if (!async_err) {
  9213. errno = saved_errno;
  9214. posix_error();
  9215. }
  9216. return -1;
  9217. }
  9218. return n;
  9219. }
  9220. #endif /* HAVE_PREADV */
  9221. /*[clinic input]
  9222. os.write -> Py_ssize_t
  9223. fd: int
  9224. data: Py_buffer
  9225. /
  9226. Write a bytes object to a file descriptor.
  9227. [clinic start generated code]*/
  9228. static Py_ssize_t
  9229. os_write_impl(PyObject *module, int fd, Py_buffer *data)
  9230. /*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
  9231. {
  9232. return _Py_write(fd, data->buf, data->len);
  9233. }
  9234. #ifdef HAVE_SENDFILE
  9235. #ifdef __APPLE__
  9236. /*[clinic input]
  9237. os.sendfile
  9238. out_fd: int
  9239. in_fd: int
  9240. offset: Py_off_t
  9241. count as sbytes: Py_off_t
  9242. headers: object(c_default="NULL") = ()
  9243. trailers: object(c_default="NULL") = ()
  9244. flags: int = 0
  9245. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9246. [clinic start generated code]*/
  9247. static PyObject *
  9248. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
  9249. Py_off_t sbytes, PyObject *headers, PyObject *trailers,
  9250. int flags)
  9251. /*[clinic end generated code: output=81c4bcd143f5c82b input=b0d72579d4c69afa]*/
  9252. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  9253. /*[clinic input]
  9254. os.sendfile
  9255. out_fd: int
  9256. in_fd: int
  9257. offset: Py_off_t
  9258. count: Py_ssize_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_ssize_t count, PyObject *headers, PyObject *trailers,
  9267. int flags)
  9268. /*[clinic end generated code: output=329ea009bdd55afc input=338adb8ff84ae8cd]*/
  9269. #else
  9270. /*[clinic input]
  9271. os.sendfile
  9272. out_fd: int
  9273. in_fd: int
  9274. offset as offobj: object
  9275. count: Py_ssize_t
  9276. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9277. [clinic start generated code]*/
  9278. static PyObject *
  9279. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, PyObject *offobj,
  9280. Py_ssize_t count)
  9281. /*[clinic end generated code: output=ae81216e40f167d8 input=76d64058c74477ba]*/
  9282. #endif
  9283. {
  9284. Py_ssize_t ret;
  9285. int async_err = 0;
  9286. #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
  9287. #ifndef __APPLE__
  9288. off_t sbytes;
  9289. #endif
  9290. Py_buffer *hbuf, *tbuf;
  9291. struct sf_hdtr sf;
  9292. sf.headers = NULL;
  9293. sf.trailers = NULL;
  9294. if (headers != NULL) {
  9295. if (!PySequence_Check(headers)) {
  9296. PyErr_SetString(PyExc_TypeError,
  9297. "sendfile() headers must be a sequence");
  9298. return NULL;
  9299. } else {
  9300. Py_ssize_t i = PySequence_Size(headers);
  9301. if (i < 0)
  9302. return NULL;
  9303. if (i > INT_MAX) {
  9304. PyErr_SetString(PyExc_OverflowError,
  9305. "sendfile() header is too large");
  9306. return NULL;
  9307. }
  9308. if (i > 0) {
  9309. sf.hdr_cnt = (int)i;
  9310. if (iov_setup(&(sf.headers), &hbuf,
  9311. headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
  9312. return NULL;
  9313. #ifdef __APPLE__
  9314. for (i = 0; i < sf.hdr_cnt; i++) {
  9315. Py_ssize_t blen = sf.headers[i].iov_len;
  9316. # define OFF_T_MAX 0x7fffffffffffffff
  9317. if (sbytes >= OFF_T_MAX - blen) {
  9318. PyErr_SetString(PyExc_OverflowError,
  9319. "sendfile() header is too large");
  9320. return NULL;
  9321. }
  9322. sbytes += blen;
  9323. }
  9324. #endif
  9325. }
  9326. }
  9327. }
  9328. if (trailers != NULL) {
  9329. if (!PySequence_Check(trailers)) {
  9330. PyErr_SetString(PyExc_TypeError,
  9331. "sendfile() trailers must be a sequence");
  9332. return NULL;
  9333. } else {
  9334. Py_ssize_t i = PySequence_Size(trailers);
  9335. if (i < 0)
  9336. return NULL;
  9337. if (i > INT_MAX) {
  9338. PyErr_SetString(PyExc_OverflowError,
  9339. "sendfile() trailer is too large");
  9340. return NULL;
  9341. }
  9342. if (i > 0) {
  9343. sf.trl_cnt = (int)i;
  9344. if (iov_setup(&(sf.trailers), &tbuf,
  9345. trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
  9346. return NULL;
  9347. }
  9348. }
  9349. }
  9350. _Py_BEGIN_SUPPRESS_IPH
  9351. do {
  9352. Py_BEGIN_ALLOW_THREADS
  9353. #ifdef __APPLE__
  9354. ret = sendfile(in_fd, out_fd, offset, &sbytes, &sf, flags);
  9355. #else
  9356. ret = sendfile(in_fd, out_fd, offset, count, &sf, &sbytes, flags);
  9357. #endif
  9358. Py_END_ALLOW_THREADS
  9359. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9360. _Py_END_SUPPRESS_IPH
  9361. int saved_errno = errno;
  9362. if (sf.headers != NULL)
  9363. iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
  9364. if (sf.trailers != NULL)
  9365. iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
  9366. if (ret < 0) {
  9367. if ((saved_errno == EAGAIN) || (saved_errno == EBUSY)) {
  9368. if (sbytes != 0) {
  9369. // some data has been sent
  9370. goto done;
  9371. }
  9372. // no data has been sent; upper application is supposed
  9373. // to retry on EAGAIN or EBUSY
  9374. }
  9375. if (!async_err) {
  9376. errno = saved_errno;
  9377. posix_error();
  9378. }
  9379. return NULL;
  9380. }
  9381. goto done;
  9382. done:
  9383. #if !defined(HAVE_LARGEFILE_SUPPORT)
  9384. return Py_BuildValue("l", sbytes);
  9385. #else
  9386. return Py_BuildValue("L", sbytes);
  9387. #endif
  9388. #else
  9389. #ifdef __linux__
  9390. if (offobj == Py_None) {
  9391. do {
  9392. Py_BEGIN_ALLOW_THREADS
  9393. ret = sendfile(out_fd, in_fd, NULL, count);
  9394. Py_END_ALLOW_THREADS
  9395. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9396. if (ret < 0)
  9397. return (!async_err) ? posix_error() : NULL;
  9398. return Py_BuildValue("n", ret);
  9399. }
  9400. #endif
  9401. off_t offset;
  9402. if (!Py_off_t_converter(offobj, &offset))
  9403. return NULL;
  9404. #if defined(__sun) && defined(__SVR4)
  9405. // On Solaris, sendfile raises EINVAL rather than returning 0
  9406. // when the offset is equal or bigger than the in_fd size.
  9407. struct stat st;
  9408. do {
  9409. Py_BEGIN_ALLOW_THREADS
  9410. ret = fstat(in_fd, &st);
  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. if (offset >= st.st_size) {
  9416. return Py_BuildValue("i", 0);
  9417. }
  9418. // On illumos specifically sendfile() may perform a partial write but
  9419. // return -1/an error (in one confirmed case the destination socket
  9420. // had a 5 second timeout set and errno was EAGAIN) and it's on the client
  9421. // code to check if the offset parameter was modified by sendfile().
  9422. //
  9423. // We need this variable to track said change.
  9424. off_t original_offset = offset;
  9425. #endif
  9426. do {
  9427. Py_BEGIN_ALLOW_THREADS
  9428. ret = sendfile(out_fd, in_fd, &offset, count);
  9429. #if defined(__sun) && defined(__SVR4)
  9430. // This handles illumos-specific sendfile() partial write behavior,
  9431. // see a comment above for more details.
  9432. if (ret < 0 && offset != original_offset) {
  9433. ret = offset - original_offset;
  9434. }
  9435. #endif
  9436. Py_END_ALLOW_THREADS
  9437. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9438. if (ret < 0)
  9439. return (!async_err) ? posix_error() : NULL;
  9440. return Py_BuildValue("n", ret);
  9441. #endif
  9442. }
  9443. #endif /* HAVE_SENDFILE */
  9444. #if defined(__APPLE__)
  9445. /*[clinic input]
  9446. os._fcopyfile
  9447. in_fd: int
  9448. out_fd: int
  9449. flags: int
  9450. /
  9451. Efficiently copy content or metadata of 2 regular file descriptors (macOS).
  9452. [clinic start generated code]*/
  9453. static PyObject *
  9454. os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
  9455. /*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
  9456. {
  9457. int ret;
  9458. Py_BEGIN_ALLOW_THREADS
  9459. ret = fcopyfile(in_fd, out_fd, NULL, flags);
  9460. Py_END_ALLOW_THREADS
  9461. if (ret < 0)
  9462. return posix_error();
  9463. Py_RETURN_NONE;
  9464. }
  9465. #endif
  9466. /*[clinic input]
  9467. os.fstat
  9468. fd : int
  9469. Perform a stat system call on the given file descriptor.
  9470. Like stat(), but for an open file descriptor.
  9471. Equivalent to os.stat(fd).
  9472. [clinic start generated code]*/
  9473. static PyObject *
  9474. os_fstat_impl(PyObject *module, int fd)
  9475. /*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
  9476. {
  9477. STRUCT_STAT st;
  9478. int res;
  9479. int async_err = 0;
  9480. do {
  9481. Py_BEGIN_ALLOW_THREADS
  9482. res = FSTAT(fd, &st);
  9483. Py_END_ALLOW_THREADS
  9484. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9485. if (res != 0) {
  9486. #ifdef MS_WINDOWS
  9487. return PyErr_SetFromWindowsErr(0);
  9488. #else
  9489. return (!async_err) ? posix_error() : NULL;
  9490. #endif
  9491. }
  9492. return _pystat_fromstructstat(module, &st);
  9493. }
  9494. /*[clinic input]
  9495. os.isatty -> bool
  9496. fd: int
  9497. /
  9498. Return True if the fd is connected to a terminal.
  9499. Return True if the file descriptor is an open file descriptor
  9500. connected to the slave end of a terminal.
  9501. [clinic start generated code]*/
  9502. static int
  9503. os_isatty_impl(PyObject *module, int fd)
  9504. /*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
  9505. {
  9506. int return_value;
  9507. Py_BEGIN_ALLOW_THREADS
  9508. _Py_BEGIN_SUPPRESS_IPH
  9509. return_value = isatty(fd);
  9510. _Py_END_SUPPRESS_IPH
  9511. Py_END_ALLOW_THREADS
  9512. return return_value;
  9513. }
  9514. #ifdef HAVE_PIPE
  9515. /*[clinic input]
  9516. os.pipe
  9517. Create a pipe.
  9518. Returns a tuple of two file descriptors:
  9519. (read_fd, write_fd)
  9520. [clinic start generated code]*/
  9521. static PyObject *
  9522. os_pipe_impl(PyObject *module)
  9523. /*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
  9524. {
  9525. int fds[2];
  9526. #ifdef MS_WINDOWS
  9527. HANDLE read, write;
  9528. SECURITY_ATTRIBUTES attr;
  9529. BOOL ok;
  9530. #else
  9531. int res;
  9532. #endif
  9533. #ifdef MS_WINDOWS
  9534. attr.nLength = sizeof(attr);
  9535. attr.lpSecurityDescriptor = NULL;
  9536. attr.bInheritHandle = FALSE;
  9537. Py_BEGIN_ALLOW_THREADS
  9538. ok = CreatePipe(&read, &write, &attr, 0);
  9539. if (ok) {
  9540. fds[0] = _Py_open_osfhandle_noraise(read, _O_RDONLY);
  9541. fds[1] = _Py_open_osfhandle_noraise(write, _O_WRONLY);
  9542. if (fds[0] == -1 || fds[1] == -1) {
  9543. CloseHandle(read);
  9544. CloseHandle(write);
  9545. ok = 0;
  9546. }
  9547. }
  9548. Py_END_ALLOW_THREADS
  9549. if (!ok)
  9550. return PyErr_SetFromWindowsErr(0);
  9551. #else
  9552. #ifdef HAVE_PIPE2
  9553. Py_BEGIN_ALLOW_THREADS
  9554. res = pipe2(fds, O_CLOEXEC);
  9555. Py_END_ALLOW_THREADS
  9556. if (res != 0 && errno == ENOSYS)
  9557. {
  9558. #endif
  9559. Py_BEGIN_ALLOW_THREADS
  9560. res = pipe(fds);
  9561. Py_END_ALLOW_THREADS
  9562. if (res == 0) {
  9563. if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
  9564. close(fds[0]);
  9565. close(fds[1]);
  9566. return NULL;
  9567. }
  9568. if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
  9569. close(fds[0]);
  9570. close(fds[1]);
  9571. return NULL;
  9572. }
  9573. }
  9574. #ifdef HAVE_PIPE2
  9575. }
  9576. #endif
  9577. if (res != 0)
  9578. return PyErr_SetFromErrno(PyExc_OSError);
  9579. #endif /* !MS_WINDOWS */
  9580. return Py_BuildValue("(ii)", fds[0], fds[1]);
  9581. }
  9582. #endif /* HAVE_PIPE */
  9583. #ifdef HAVE_PIPE2
  9584. /*[clinic input]
  9585. os.pipe2
  9586. flags: int
  9587. /
  9588. Create a pipe with flags set atomically.
  9589. Returns a tuple of two file descriptors:
  9590. (read_fd, write_fd)
  9591. flags can be constructed by ORing together one or more of these values:
  9592. O_NONBLOCK, O_CLOEXEC.
  9593. [clinic start generated code]*/
  9594. static PyObject *
  9595. os_pipe2_impl(PyObject *module, int flags)
  9596. /*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
  9597. {
  9598. int fds[2];
  9599. int res;
  9600. res = pipe2(fds, flags);
  9601. if (res != 0)
  9602. return posix_error();
  9603. return Py_BuildValue("(ii)", fds[0], fds[1]);
  9604. }
  9605. #endif /* HAVE_PIPE2 */
  9606. #ifdef HAVE_WRITEV
  9607. /*[clinic input]
  9608. os.writev -> Py_ssize_t
  9609. fd: int
  9610. buffers: object
  9611. /
  9612. Iterate over buffers, and write the contents of each to a file descriptor.
  9613. Returns the total number of bytes written.
  9614. buffers must be a sequence of bytes-like objects.
  9615. [clinic start generated code]*/
  9616. static Py_ssize_t
  9617. os_writev_impl(PyObject *module, int fd, PyObject *buffers)
  9618. /*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
  9619. {
  9620. Py_ssize_t cnt;
  9621. Py_ssize_t result;
  9622. int async_err = 0;
  9623. struct iovec *iov;
  9624. Py_buffer *buf;
  9625. if (!PySequence_Check(buffers)) {
  9626. PyErr_SetString(PyExc_TypeError,
  9627. "writev() arg 2 must be a sequence");
  9628. return -1;
  9629. }
  9630. cnt = PySequence_Size(buffers);
  9631. if (cnt < 0)
  9632. return -1;
  9633. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
  9634. return -1;
  9635. }
  9636. do {
  9637. Py_BEGIN_ALLOW_THREADS
  9638. result = writev(fd, iov, cnt);
  9639. Py_END_ALLOW_THREADS
  9640. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9641. if (result < 0 && !async_err)
  9642. posix_error();
  9643. iov_cleanup(iov, buf, cnt);
  9644. return result;
  9645. }
  9646. #endif /* HAVE_WRITEV */
  9647. #ifdef HAVE_PWRITE
  9648. /*[clinic input]
  9649. os.pwrite -> Py_ssize_t
  9650. fd: int
  9651. buffer: Py_buffer
  9652. offset: Py_off_t
  9653. /
  9654. Write bytes to a file descriptor starting at a particular offset.
  9655. Write buffer to fd, starting at offset bytes from the beginning of
  9656. the file. Returns the number of bytes writte. Does not change the
  9657. current file offset.
  9658. [clinic start generated code]*/
  9659. static Py_ssize_t
  9660. os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
  9661. /*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
  9662. {
  9663. Py_ssize_t size;
  9664. int async_err = 0;
  9665. do {
  9666. Py_BEGIN_ALLOW_THREADS
  9667. _Py_BEGIN_SUPPRESS_IPH
  9668. size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
  9669. _Py_END_SUPPRESS_IPH
  9670. Py_END_ALLOW_THREADS
  9671. } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9672. if (size < 0 && !async_err)
  9673. posix_error();
  9674. return size;
  9675. }
  9676. #endif /* HAVE_PWRITE */
  9677. #if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
  9678. /*[clinic input]
  9679. os.pwritev -> Py_ssize_t
  9680. fd: int
  9681. buffers: object
  9682. offset: Py_off_t
  9683. flags: int = 0
  9684. /
  9685. Writes the contents of bytes-like objects to a file descriptor at a given offset.
  9686. Combines the functionality of writev() and pwrite(). All buffers must be a sequence
  9687. of bytes-like objects. Buffers are processed in array order. Entire contents of first
  9688. buffer is written before proceeding to second, and so on. The operating system may
  9689. set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
  9690. This function writes the contents of each object to the file descriptor and returns
  9691. the total number of bytes written.
  9692. The flags argument contains a bitwise OR of zero or more of the following flags:
  9693. - RWF_DSYNC
  9694. - RWF_SYNC
  9695. - RWF_APPEND
  9696. Using non-zero flags requires Linux 4.7 or newer.
  9697. [clinic start generated code]*/
  9698. static Py_ssize_t
  9699. os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
  9700. int flags)
  9701. /*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=35358c327e1a2a8e]*/
  9702. {
  9703. Py_ssize_t cnt;
  9704. Py_ssize_t result;
  9705. int async_err = 0;
  9706. struct iovec *iov;
  9707. Py_buffer *buf;
  9708. if (!PySequence_Check(buffers)) {
  9709. PyErr_SetString(PyExc_TypeError,
  9710. "pwritev() arg 2 must be a sequence");
  9711. return -1;
  9712. }
  9713. cnt = PySequence_Size(buffers);
  9714. if (cnt < 0) {
  9715. return -1;
  9716. }
  9717. #ifndef HAVE_PWRITEV2
  9718. if(flags != 0) {
  9719. argument_unavailable_error("pwritev2", "flags");
  9720. return -1;
  9721. }
  9722. #endif
  9723. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
  9724. return -1;
  9725. }
  9726. #ifdef HAVE_PWRITEV2
  9727. do {
  9728. Py_BEGIN_ALLOW_THREADS
  9729. _Py_BEGIN_SUPPRESS_IPH
  9730. result = pwritev2(fd, iov, cnt, offset, flags);
  9731. _Py_END_SUPPRESS_IPH
  9732. Py_END_ALLOW_THREADS
  9733. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9734. #else
  9735. #if defined(__APPLE__) && defined(__clang__)
  9736. /* This entire function will be removed from the module dict when the API
  9737. * is not available.
  9738. */
  9739. #pragma clang diagnostic push
  9740. #pragma clang diagnostic ignored "-Wunguarded-availability"
  9741. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  9742. #endif
  9743. do {
  9744. Py_BEGIN_ALLOW_THREADS
  9745. _Py_BEGIN_SUPPRESS_IPH
  9746. result = pwritev(fd, iov, cnt, offset);
  9747. _Py_END_SUPPRESS_IPH
  9748. Py_END_ALLOW_THREADS
  9749. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9750. #if defined(__APPLE__) && defined(__clang__)
  9751. #pragma clang diagnostic pop
  9752. #endif
  9753. #endif
  9754. if (result < 0) {
  9755. if (!async_err) {
  9756. posix_error();
  9757. }
  9758. result = -1;
  9759. }
  9760. iov_cleanup(iov, buf, cnt);
  9761. return result;
  9762. }
  9763. #endif /* HAVE_PWRITEV */
  9764. #ifdef HAVE_COPY_FILE_RANGE
  9765. /*[clinic input]
  9766. os.copy_file_range
  9767. src: int
  9768. Source file descriptor.
  9769. dst: int
  9770. Destination file descriptor.
  9771. count: Py_ssize_t
  9772. Number of bytes to copy.
  9773. offset_src: object = None
  9774. Starting offset in src.
  9775. offset_dst: object = None
  9776. Starting offset in dst.
  9777. Copy count bytes from one file descriptor to another.
  9778. If offset_src is None, then src is read from the current position;
  9779. respectively for offset_dst.
  9780. [clinic start generated code]*/
  9781. static PyObject *
  9782. os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
  9783. PyObject *offset_src, PyObject *offset_dst)
  9784. /*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
  9785. {
  9786. off_t offset_src_val, offset_dst_val;
  9787. off_t *p_offset_src = NULL;
  9788. off_t *p_offset_dst = NULL;
  9789. Py_ssize_t ret;
  9790. int async_err = 0;
  9791. /* The flags argument is provided to allow
  9792. * for future extensions and currently must be to 0. */
  9793. int flags = 0;
  9794. if (count < 0) {
  9795. PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
  9796. return NULL;
  9797. }
  9798. if (offset_src != Py_None) {
  9799. if (!Py_off_t_converter(offset_src, &offset_src_val)) {
  9800. return NULL;
  9801. }
  9802. p_offset_src = &offset_src_val;
  9803. }
  9804. if (offset_dst != Py_None) {
  9805. if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
  9806. return NULL;
  9807. }
  9808. p_offset_dst = &offset_dst_val;
  9809. }
  9810. do {
  9811. Py_BEGIN_ALLOW_THREADS
  9812. ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
  9813. Py_END_ALLOW_THREADS
  9814. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9815. if (ret < 0) {
  9816. return (!async_err) ? posix_error() : NULL;
  9817. }
  9818. return PyLong_FromSsize_t(ret);
  9819. }
  9820. #endif /* HAVE_COPY_FILE_RANGE*/
  9821. #if (defined(HAVE_SPLICE) && !defined(_AIX))
  9822. /*[clinic input]
  9823. os.splice
  9824. src: int
  9825. Source file descriptor.
  9826. dst: int
  9827. Destination file descriptor.
  9828. count: Py_ssize_t
  9829. Number of bytes to copy.
  9830. offset_src: object = None
  9831. Starting offset in src.
  9832. offset_dst: object = None
  9833. Starting offset in dst.
  9834. flags: unsigned_int = 0
  9835. Flags to modify the semantics of the call.
  9836. Transfer count bytes from one pipe to a descriptor or vice versa.
  9837. If offset_src is None, then src is read from the current position;
  9838. respectively for offset_dst. The offset associated to the file
  9839. descriptor that refers to a pipe must be None.
  9840. [clinic start generated code]*/
  9841. static PyObject *
  9842. os_splice_impl(PyObject *module, int src, int dst, Py_ssize_t count,
  9843. PyObject *offset_src, PyObject *offset_dst,
  9844. unsigned int flags)
  9845. /*[clinic end generated code: output=d0386f25a8519dc5 input=047527c66c6d2e0a]*/
  9846. {
  9847. off_t offset_src_val, offset_dst_val;
  9848. off_t *p_offset_src = NULL;
  9849. off_t *p_offset_dst = NULL;
  9850. Py_ssize_t ret;
  9851. int async_err = 0;
  9852. if (count < 0) {
  9853. PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
  9854. return NULL;
  9855. }
  9856. if (offset_src != Py_None) {
  9857. if (!Py_off_t_converter(offset_src, &offset_src_val)) {
  9858. return NULL;
  9859. }
  9860. p_offset_src = &offset_src_val;
  9861. }
  9862. if (offset_dst != Py_None) {
  9863. if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
  9864. return NULL;
  9865. }
  9866. p_offset_dst = &offset_dst_val;
  9867. }
  9868. do {
  9869. Py_BEGIN_ALLOW_THREADS
  9870. ret = splice(src, p_offset_src, dst, p_offset_dst, count, flags);
  9871. Py_END_ALLOW_THREADS
  9872. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9873. if (ret < 0) {
  9874. return (!async_err) ? posix_error() : NULL;
  9875. }
  9876. return PyLong_FromSsize_t(ret);
  9877. }
  9878. #endif /* HAVE_SPLICE*/
  9879. #ifdef HAVE_MKFIFO
  9880. /*[clinic input]
  9881. os.mkfifo
  9882. path: path_t
  9883. mode: int=0o666
  9884. *
  9885. dir_fd: dir_fd(requires='mkfifoat')=None
  9886. Create a "fifo" (a POSIX named pipe).
  9887. If dir_fd is not None, it should be a file descriptor open to a directory,
  9888. and path should be relative; path will then be relative to that directory.
  9889. dir_fd may not be implemented on your platform.
  9890. If it is unavailable, using it will raise a NotImplementedError.
  9891. [clinic start generated code]*/
  9892. static PyObject *
  9893. os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
  9894. /*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
  9895. {
  9896. int result;
  9897. int async_err = 0;
  9898. #ifdef HAVE_MKFIFOAT
  9899. int mkfifoat_unavailable = 0;
  9900. #endif
  9901. do {
  9902. Py_BEGIN_ALLOW_THREADS
  9903. #ifdef HAVE_MKFIFOAT
  9904. if (dir_fd != DEFAULT_DIR_FD) {
  9905. if (HAVE_MKFIFOAT_RUNTIME) {
  9906. result = mkfifoat(dir_fd, path->narrow, mode);
  9907. } else {
  9908. mkfifoat_unavailable = 1;
  9909. result = 0;
  9910. }
  9911. } else
  9912. #endif
  9913. result = mkfifo(path->narrow, mode);
  9914. Py_END_ALLOW_THREADS
  9915. } while (result != 0 && errno == EINTR &&
  9916. !(async_err = PyErr_CheckSignals()));
  9917. #ifdef HAVE_MKFIFOAT
  9918. if (mkfifoat_unavailable) {
  9919. argument_unavailable_error(NULL, "dir_fd");
  9920. return NULL;
  9921. }
  9922. #endif
  9923. if (result != 0)
  9924. return (!async_err) ? posix_error() : NULL;
  9925. Py_RETURN_NONE;
  9926. }
  9927. #endif /* HAVE_MKFIFO */
  9928. #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
  9929. /*[clinic input]
  9930. os.mknod
  9931. path: path_t
  9932. mode: int=0o600
  9933. device: dev_t=0
  9934. *
  9935. dir_fd: dir_fd(requires='mknodat')=None
  9936. Create a node in the file system.
  9937. Create a node in the file system (file, device special file or named pipe)
  9938. at path. mode specifies both the permissions to use and the
  9939. type of node to be created, being combined (bitwise OR) with one of
  9940. S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
  9941. device defines the newly created device special file (probably using
  9942. os.makedev()). Otherwise device is ignored.
  9943. If dir_fd is not None, it should be a file descriptor open to a directory,
  9944. and path should be relative; path will then be relative to that directory.
  9945. dir_fd may not be implemented on your platform.
  9946. If it is unavailable, using it will raise a NotImplementedError.
  9947. [clinic start generated code]*/
  9948. static PyObject *
  9949. os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
  9950. int dir_fd)
  9951. /*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
  9952. {
  9953. int result;
  9954. int async_err = 0;
  9955. #ifdef HAVE_MKNODAT
  9956. int mknodat_unavailable = 0;
  9957. #endif
  9958. do {
  9959. Py_BEGIN_ALLOW_THREADS
  9960. #ifdef HAVE_MKNODAT
  9961. if (dir_fd != DEFAULT_DIR_FD) {
  9962. if (HAVE_MKNODAT_RUNTIME) {
  9963. result = mknodat(dir_fd, path->narrow, mode, device);
  9964. } else {
  9965. mknodat_unavailable = 1;
  9966. result = 0;
  9967. }
  9968. } else
  9969. #endif
  9970. result = mknod(path->narrow, mode, device);
  9971. Py_END_ALLOW_THREADS
  9972. } while (result != 0 && errno == EINTR &&
  9973. !(async_err = PyErr_CheckSignals()));
  9974. #ifdef HAVE_MKNODAT
  9975. if (mknodat_unavailable) {
  9976. argument_unavailable_error(NULL, "dir_fd");
  9977. return NULL;
  9978. }
  9979. #endif
  9980. if (result != 0)
  9981. return (!async_err) ? posix_error() : NULL;
  9982. Py_RETURN_NONE;
  9983. }
  9984. #endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
  9985. #ifdef HAVE_DEVICE_MACROS
  9986. /*[clinic input]
  9987. os.major -> unsigned_int
  9988. device: dev_t
  9989. /
  9990. Extracts a device major number from a raw device number.
  9991. [clinic start generated code]*/
  9992. static unsigned int
  9993. os_major_impl(PyObject *module, dev_t device)
  9994. /*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
  9995. {
  9996. return major(device);
  9997. }
  9998. /*[clinic input]
  9999. os.minor -> unsigned_int
  10000. device: dev_t
  10001. /
  10002. Extracts a device minor number from a raw device number.
  10003. [clinic start generated code]*/
  10004. static unsigned int
  10005. os_minor_impl(PyObject *module, dev_t device)
  10006. /*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
  10007. {
  10008. return minor(device);
  10009. }
  10010. /*[clinic input]
  10011. os.makedev -> dev_t
  10012. major: int
  10013. minor: int
  10014. /
  10015. Composes a raw device number from the major and minor device numbers.
  10016. [clinic start generated code]*/
  10017. static dev_t
  10018. os_makedev_impl(PyObject *module, int major, int minor)
  10019. /*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
  10020. {
  10021. return makedev(major, minor);
  10022. }
  10023. #endif /* HAVE_DEVICE_MACROS */
  10024. #if defined HAVE_FTRUNCATE || defined MS_WINDOWS
  10025. /*[clinic input]
  10026. os.ftruncate
  10027. fd: int
  10028. length: Py_off_t
  10029. /
  10030. Truncate a file, specified by file descriptor, to a specific length.
  10031. [clinic start generated code]*/
  10032. static PyObject *
  10033. os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
  10034. /*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
  10035. {
  10036. int result;
  10037. int async_err = 0;
  10038. if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
  10039. return NULL;
  10040. }
  10041. do {
  10042. Py_BEGIN_ALLOW_THREADS
  10043. _Py_BEGIN_SUPPRESS_IPH
  10044. #ifdef MS_WINDOWS
  10045. result = _chsize_s(fd, length);
  10046. #else
  10047. result = ftruncate(fd, length);
  10048. #endif
  10049. _Py_END_SUPPRESS_IPH
  10050. Py_END_ALLOW_THREADS
  10051. } while (result != 0 && errno == EINTR &&
  10052. !(async_err = PyErr_CheckSignals()));
  10053. if (result != 0)
  10054. return (!async_err) ? posix_error() : NULL;
  10055. Py_RETURN_NONE;
  10056. }
  10057. #endif /* HAVE_FTRUNCATE || MS_WINDOWS */
  10058. #if defined HAVE_TRUNCATE || defined MS_WINDOWS
  10059. /*[clinic input]
  10060. os.truncate
  10061. path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
  10062. length: Py_off_t
  10063. Truncate a file, specified by path, to a specific length.
  10064. On some platforms, path may also be specified as an open file descriptor.
  10065. If this functionality is unavailable, using it raises an exception.
  10066. [clinic start generated code]*/
  10067. static PyObject *
  10068. os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
  10069. /*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
  10070. {
  10071. int result;
  10072. #ifdef MS_WINDOWS
  10073. int fd;
  10074. #endif
  10075. if (path->fd != -1)
  10076. return os_ftruncate_impl(module, path->fd, length);
  10077. if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
  10078. return NULL;
  10079. }
  10080. Py_BEGIN_ALLOW_THREADS
  10081. _Py_BEGIN_SUPPRESS_IPH
  10082. #ifdef MS_WINDOWS
  10083. fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
  10084. if (fd < 0)
  10085. result = -1;
  10086. else {
  10087. result = _chsize_s(fd, length);
  10088. close(fd);
  10089. if (result < 0)
  10090. errno = result;
  10091. }
  10092. #else
  10093. result = truncate(path->narrow, length);
  10094. #endif
  10095. _Py_END_SUPPRESS_IPH
  10096. Py_END_ALLOW_THREADS
  10097. if (result < 0)
  10098. return posix_path_error(path);
  10099. Py_RETURN_NONE;
  10100. }
  10101. #endif /* HAVE_TRUNCATE || MS_WINDOWS */
  10102. /* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
  10103. and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
  10104. defined, which is the case in Python on AIX. AIX bug report:
  10105. http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
  10106. #if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
  10107. # define POSIX_FADVISE_AIX_BUG
  10108. #endif
  10109. /* GH-111804: Due to posix_fallocate() not having consistent semantics across
  10110. OSs, support was dropped in WASI preview2. */
  10111. #if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG) && \
  10112. !defined(__wasi__)
  10113. /*[clinic input]
  10114. os.posix_fallocate
  10115. fd: int
  10116. offset: Py_off_t
  10117. length: Py_off_t
  10118. /
  10119. Ensure a file has allocated at least a particular number of bytes on disk.
  10120. Ensure that the file specified by fd encompasses a range of bytes
  10121. starting at offset bytes from the beginning and continuing for length bytes.
  10122. [clinic start generated code]*/
  10123. static PyObject *
  10124. os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
  10125. Py_off_t length)
  10126. /*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
  10127. {
  10128. int result;
  10129. int async_err = 0;
  10130. do {
  10131. Py_BEGIN_ALLOW_THREADS
  10132. result = posix_fallocate(fd, offset, length);
  10133. Py_END_ALLOW_THREADS
  10134. } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
  10135. if (result == 0)
  10136. Py_RETURN_NONE;
  10137. if (async_err)
  10138. return NULL;
  10139. errno = result;
  10140. return posix_error();
  10141. }
  10142. #endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG && !defined(__wasi__) */
  10143. #if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
  10144. /*[clinic input]
  10145. os.posix_fadvise
  10146. fd: int
  10147. offset: Py_off_t
  10148. length: Py_off_t
  10149. advice: int
  10150. /
  10151. Announce an intention to access data in a specific pattern.
  10152. Announce an intention to access data in a specific pattern, thus allowing
  10153. the kernel to make optimizations.
  10154. The advice applies to the region of the file specified by fd starting at
  10155. offset and continuing for length bytes.
  10156. advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
  10157. POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
  10158. POSIX_FADV_DONTNEED.
  10159. [clinic start generated code]*/
  10160. static PyObject *
  10161. os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
  10162. Py_off_t length, int advice)
  10163. /*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
  10164. {
  10165. int result;
  10166. int async_err = 0;
  10167. do {
  10168. Py_BEGIN_ALLOW_THREADS
  10169. result = posix_fadvise(fd, offset, length, advice);
  10170. Py_END_ALLOW_THREADS
  10171. } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
  10172. if (result == 0)
  10173. Py_RETURN_NONE;
  10174. if (async_err)
  10175. return NULL;
  10176. errno = result;
  10177. return posix_error();
  10178. }
  10179. #endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
  10180. #ifdef MS_WINDOWS
  10181. static PyObject*
  10182. win32_putenv(PyObject *name, PyObject *value)
  10183. {
  10184. /* Search from index 1 because on Windows starting '=' is allowed for
  10185. defining hidden environment variables. */
  10186. if (PyUnicode_GET_LENGTH(name) == 0 ||
  10187. PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
  10188. {
  10189. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  10190. return NULL;
  10191. }
  10192. PyObject *unicode;
  10193. if (value != NULL) {
  10194. unicode = PyUnicode_FromFormat("%U=%U", name, value);
  10195. }
  10196. else {
  10197. unicode = PyUnicode_FromFormat("%U=", name);
  10198. }
  10199. if (unicode == NULL) {
  10200. return NULL;
  10201. }
  10202. Py_ssize_t size;
  10203. wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
  10204. Py_DECREF(unicode);
  10205. if (env == NULL) {
  10206. return NULL;
  10207. }
  10208. if (size > _MAX_ENV) {
  10209. PyErr_Format(PyExc_ValueError,
  10210. "the environment variable is longer than %u characters",
  10211. _MAX_ENV);
  10212. PyMem_Free(env);
  10213. return NULL;
  10214. }
  10215. if (wcslen(env) != (size_t)size) {
  10216. PyErr_SetString(PyExc_ValueError,
  10217. "embedded null character");
  10218. PyMem_Free(env);
  10219. return NULL;
  10220. }
  10221. /* _wputenv() and SetEnvironmentVariableW() update the environment in the
  10222. Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
  10223. and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
  10224. Prefer _wputenv() to be compatible with C libraries using CRT
  10225. variables and CRT functions using these variables (ex: getenv()). */
  10226. int err = _wputenv(env);
  10227. if (err) {
  10228. posix_error();
  10229. PyMem_Free(env);
  10230. return NULL;
  10231. }
  10232. PyMem_Free(env);
  10233. Py_RETURN_NONE;
  10234. }
  10235. #endif
  10236. #ifdef MS_WINDOWS
  10237. /*[clinic input]
  10238. os.putenv
  10239. name: unicode
  10240. value: unicode
  10241. /
  10242. Change or add an environment variable.
  10243. [clinic start generated code]*/
  10244. static PyObject *
  10245. os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
  10246. /*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
  10247. {
  10248. if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
  10249. return NULL;
  10250. }
  10251. return win32_putenv(name, value);
  10252. }
  10253. #else
  10254. /*[clinic input]
  10255. os.putenv
  10256. name: FSConverter
  10257. value: FSConverter
  10258. /
  10259. Change or add an environment variable.
  10260. [clinic start generated code]*/
  10261. static PyObject *
  10262. os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
  10263. /*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
  10264. {
  10265. const char *name_string = PyBytes_AS_STRING(name);
  10266. const char *value_string = PyBytes_AS_STRING(value);
  10267. if (strchr(name_string, '=') != NULL) {
  10268. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  10269. return NULL;
  10270. }
  10271. if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
  10272. return NULL;
  10273. }
  10274. if (setenv(name_string, value_string, 1)) {
  10275. return posix_error();
  10276. }
  10277. Py_RETURN_NONE;
  10278. }
  10279. #endif /* !defined(MS_WINDOWS) */
  10280. #ifdef MS_WINDOWS
  10281. /*[clinic input]
  10282. os.unsetenv
  10283. name: unicode
  10284. /
  10285. Delete an environment variable.
  10286. [clinic start generated code]*/
  10287. static PyObject *
  10288. os_unsetenv_impl(PyObject *module, PyObject *name)
  10289. /*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
  10290. {
  10291. if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
  10292. return NULL;
  10293. }
  10294. return win32_putenv(name, NULL);
  10295. }
  10296. #else
  10297. /*[clinic input]
  10298. os.unsetenv
  10299. name: FSConverter
  10300. /
  10301. Delete an environment variable.
  10302. [clinic start generated code]*/
  10303. static PyObject *
  10304. os_unsetenv_impl(PyObject *module, PyObject *name)
  10305. /*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
  10306. {
  10307. if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
  10308. return NULL;
  10309. }
  10310. #ifdef HAVE_BROKEN_UNSETENV
  10311. unsetenv(PyBytes_AS_STRING(name));
  10312. #else
  10313. int err = unsetenv(PyBytes_AS_STRING(name));
  10314. if (err) {
  10315. return posix_error();
  10316. }
  10317. #endif
  10318. Py_RETURN_NONE;
  10319. }
  10320. #endif /* !MS_WINDOWS */
  10321. /*[clinic input]
  10322. os.strerror
  10323. code: int
  10324. /
  10325. Translate an error code to a message string.
  10326. [clinic start generated code]*/
  10327. static PyObject *
  10328. os_strerror_impl(PyObject *module, int code)
  10329. /*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
  10330. {
  10331. char *message = strerror(code);
  10332. if (message == NULL) {
  10333. PyErr_SetString(PyExc_ValueError,
  10334. "strerror() argument out of range");
  10335. return NULL;
  10336. }
  10337. return PyUnicode_DecodeLocale(message, "surrogateescape");
  10338. }
  10339. #ifdef HAVE_SYS_WAIT_H
  10340. #ifdef WCOREDUMP
  10341. /*[clinic input]
  10342. os.WCOREDUMP -> bool
  10343. status: int
  10344. /
  10345. Return True if the process returning status was dumped to a core file.
  10346. [clinic start generated code]*/
  10347. static int
  10348. os_WCOREDUMP_impl(PyObject *module, int status)
  10349. /*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
  10350. {
  10351. WAIT_TYPE wait_status;
  10352. WAIT_STATUS_INT(wait_status) = status;
  10353. return WCOREDUMP(wait_status);
  10354. }
  10355. #endif /* WCOREDUMP */
  10356. #ifdef WIFCONTINUED
  10357. /*[clinic input]
  10358. os.WIFCONTINUED -> bool
  10359. status: int
  10360. Return True if a particular process was continued from a job control stop.
  10361. Return True if the process returning status was continued from a
  10362. job control stop.
  10363. [clinic start generated code]*/
  10364. static int
  10365. os_WIFCONTINUED_impl(PyObject *module, int status)
  10366. /*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
  10367. {
  10368. WAIT_TYPE wait_status;
  10369. WAIT_STATUS_INT(wait_status) = status;
  10370. return WIFCONTINUED(wait_status);
  10371. }
  10372. #endif /* WIFCONTINUED */
  10373. #ifdef WIFSTOPPED
  10374. /*[clinic input]
  10375. os.WIFSTOPPED -> bool
  10376. status: int
  10377. Return True if the process returning status was stopped.
  10378. [clinic start generated code]*/
  10379. static int
  10380. os_WIFSTOPPED_impl(PyObject *module, int status)
  10381. /*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
  10382. {
  10383. WAIT_TYPE wait_status;
  10384. WAIT_STATUS_INT(wait_status) = status;
  10385. return WIFSTOPPED(wait_status);
  10386. }
  10387. #endif /* WIFSTOPPED */
  10388. #ifdef WIFSIGNALED
  10389. /*[clinic input]
  10390. os.WIFSIGNALED -> bool
  10391. status: int
  10392. Return True if the process returning status was terminated by a signal.
  10393. [clinic start generated code]*/
  10394. static int
  10395. os_WIFSIGNALED_impl(PyObject *module, int status)
  10396. /*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
  10397. {
  10398. WAIT_TYPE wait_status;
  10399. WAIT_STATUS_INT(wait_status) = status;
  10400. return WIFSIGNALED(wait_status);
  10401. }
  10402. #endif /* WIFSIGNALED */
  10403. #ifdef WIFEXITED
  10404. /*[clinic input]
  10405. os.WIFEXITED -> bool
  10406. status: int
  10407. Return True if the process returning status exited via the exit() system call.
  10408. [clinic start generated code]*/
  10409. static int
  10410. os_WIFEXITED_impl(PyObject *module, int status)
  10411. /*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
  10412. {
  10413. WAIT_TYPE wait_status;
  10414. WAIT_STATUS_INT(wait_status) = status;
  10415. return WIFEXITED(wait_status);
  10416. }
  10417. #endif /* WIFEXITED */
  10418. #ifdef WEXITSTATUS
  10419. /*[clinic input]
  10420. os.WEXITSTATUS -> int
  10421. status: int
  10422. Return the process return code from status.
  10423. [clinic start generated code]*/
  10424. static int
  10425. os_WEXITSTATUS_impl(PyObject *module, int status)
  10426. /*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
  10427. {
  10428. WAIT_TYPE wait_status;
  10429. WAIT_STATUS_INT(wait_status) = status;
  10430. return WEXITSTATUS(wait_status);
  10431. }
  10432. #endif /* WEXITSTATUS */
  10433. #ifdef WTERMSIG
  10434. /*[clinic input]
  10435. os.WTERMSIG -> int
  10436. status: int
  10437. Return the signal that terminated the process that provided the status value.
  10438. [clinic start generated code]*/
  10439. static int
  10440. os_WTERMSIG_impl(PyObject *module, int status)
  10441. /*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
  10442. {
  10443. WAIT_TYPE wait_status;
  10444. WAIT_STATUS_INT(wait_status) = status;
  10445. return WTERMSIG(wait_status);
  10446. }
  10447. #endif /* WTERMSIG */
  10448. #ifdef WSTOPSIG
  10449. /*[clinic input]
  10450. os.WSTOPSIG -> int
  10451. status: int
  10452. Return the signal that stopped the process that provided the status value.
  10453. [clinic start generated code]*/
  10454. static int
  10455. os_WSTOPSIG_impl(PyObject *module, int status)
  10456. /*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
  10457. {
  10458. WAIT_TYPE wait_status;
  10459. WAIT_STATUS_INT(wait_status) = status;
  10460. return WSTOPSIG(wait_status);
  10461. }
  10462. #endif /* WSTOPSIG */
  10463. #endif /* HAVE_SYS_WAIT_H */
  10464. #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
  10465. #ifdef _SCO_DS
  10466. /* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
  10467. needed definitions in sys/statvfs.h */
  10468. #define _SVID3
  10469. #endif
  10470. #include <sys/statvfs.h>
  10471. static PyObject*
  10472. _pystatvfs_fromstructstatvfs(PyObject *module, struct statvfs st) {
  10473. PyObject *StatVFSResultType = get_posix_state(module)->StatVFSResultType;
  10474. PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
  10475. if (v == NULL)
  10476. return NULL;
  10477. int pos = 0;
  10478. #define SET_RESULT(CALL) \
  10479. do { \
  10480. PyObject *item = (CALL); \
  10481. if (item == NULL) { \
  10482. Py_DECREF(v); \
  10483. return NULL; \
  10484. } \
  10485. PyStructSequence_SET_ITEM(v, pos++, item); \
  10486. } while(0)
  10487. #if !defined(HAVE_LARGEFILE_SUPPORT)
  10488. SET_RESULT(PyLong_FromLong((long) st.f_bsize));
  10489. SET_RESULT(PyLong_FromLong((long) st.f_frsize));
  10490. SET_RESULT(PyLong_FromLong((long) st.f_blocks));
  10491. SET_RESULT(PyLong_FromLong((long) st.f_bfree));
  10492. SET_RESULT(PyLong_FromLong((long) st.f_bavail));
  10493. SET_RESULT(PyLong_FromLong((long) st.f_files));
  10494. SET_RESULT(PyLong_FromLong((long) st.f_ffree));
  10495. SET_RESULT(PyLong_FromLong((long) st.f_favail));
  10496. SET_RESULT(PyLong_FromLong((long) st.f_flag));
  10497. SET_RESULT(PyLong_FromLong((long) st.f_namemax));
  10498. #else
  10499. SET_RESULT(PyLong_FromLong((long) st.f_bsize));
  10500. SET_RESULT(PyLong_FromLong((long) st.f_frsize));
  10501. SET_RESULT(PyLong_FromLongLong((long long) st.f_blocks));
  10502. SET_RESULT(PyLong_FromLongLong((long long) st.f_bfree));
  10503. SET_RESULT(PyLong_FromLongLong((long long) st.f_bavail));
  10504. SET_RESULT(PyLong_FromLongLong((long long) st.f_files));
  10505. SET_RESULT(PyLong_FromLongLong((long long) st.f_ffree));
  10506. SET_RESULT(PyLong_FromLongLong((long long) st.f_favail));
  10507. SET_RESULT(PyLong_FromLong((long) st.f_flag));
  10508. SET_RESULT(PyLong_FromLong((long) st.f_namemax));
  10509. #endif
  10510. /* The _ALL_SOURCE feature test macro defines f_fsid as a structure
  10511. * (issue #32390). */
  10512. #if defined(_AIX) && defined(_ALL_SOURCE)
  10513. SET_RESULT(PyLong_FromUnsignedLong(st.f_fsid.val[0]));
  10514. #else
  10515. SET_RESULT(PyLong_FromUnsignedLong(st.f_fsid));
  10516. #endif
  10517. #undef SET_RESULT
  10518. return v;
  10519. }
  10520. /*[clinic input]
  10521. os.fstatvfs
  10522. fd: int
  10523. /
  10524. Perform an fstatvfs system call on the given fd.
  10525. Equivalent to statvfs(fd).
  10526. [clinic start generated code]*/
  10527. static PyObject *
  10528. os_fstatvfs_impl(PyObject *module, int fd)
  10529. /*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
  10530. {
  10531. int result;
  10532. int async_err = 0;
  10533. struct statvfs st;
  10534. do {
  10535. Py_BEGIN_ALLOW_THREADS
  10536. result = fstatvfs(fd, &st);
  10537. Py_END_ALLOW_THREADS
  10538. } while (result != 0 && errno == EINTR &&
  10539. !(async_err = PyErr_CheckSignals()));
  10540. if (result != 0)
  10541. return (!async_err) ? posix_error() : NULL;
  10542. return _pystatvfs_fromstructstatvfs(module, st);
  10543. }
  10544. #endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
  10545. #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
  10546. #include <sys/statvfs.h>
  10547. /*[clinic input]
  10548. os.statvfs
  10549. path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
  10550. Perform a statvfs system call on the given path.
  10551. path may always be specified as a string.
  10552. On some platforms, path may also be specified as an open file descriptor.
  10553. If this functionality is unavailable, using it raises an exception.
  10554. [clinic start generated code]*/
  10555. static PyObject *
  10556. os_statvfs_impl(PyObject *module, path_t *path)
  10557. /*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
  10558. {
  10559. int result;
  10560. struct statvfs st;
  10561. Py_BEGIN_ALLOW_THREADS
  10562. #ifdef HAVE_FSTATVFS
  10563. if (path->fd != -1) {
  10564. result = fstatvfs(path->fd, &st);
  10565. }
  10566. else
  10567. #endif
  10568. result = statvfs(path->narrow, &st);
  10569. Py_END_ALLOW_THREADS
  10570. if (result) {
  10571. return path_error(path);
  10572. }
  10573. return _pystatvfs_fromstructstatvfs(module, st);
  10574. }
  10575. #endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
  10576. #ifdef MS_WINDOWS
  10577. /*[clinic input]
  10578. os._getdiskusage
  10579. path: path_t
  10580. Return disk usage statistics about the given path as a (total, free) tuple.
  10581. [clinic start generated code]*/
  10582. static PyObject *
  10583. os__getdiskusage_impl(PyObject *module, path_t *path)
  10584. /*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
  10585. {
  10586. BOOL retval;
  10587. ULARGE_INTEGER _, total, free;
  10588. DWORD err = 0;
  10589. Py_BEGIN_ALLOW_THREADS
  10590. retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
  10591. Py_END_ALLOW_THREADS
  10592. if (retval == 0) {
  10593. if (GetLastError() == ERROR_DIRECTORY) {
  10594. wchar_t *dir_path = NULL;
  10595. dir_path = PyMem_New(wchar_t, path->length + 1);
  10596. if (dir_path == NULL) {
  10597. return PyErr_NoMemory();
  10598. }
  10599. wcscpy_s(dir_path, path->length + 1, path->wide);
  10600. if (_dirnameW(dir_path) != -1) {
  10601. Py_BEGIN_ALLOW_THREADS
  10602. retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
  10603. Py_END_ALLOW_THREADS
  10604. }
  10605. /* Record the last error in case it's modified by PyMem_Free. */
  10606. err = GetLastError();
  10607. PyMem_Free(dir_path);
  10608. if (retval) {
  10609. goto success;
  10610. }
  10611. }
  10612. return PyErr_SetFromWindowsErr(err);
  10613. }
  10614. success:
  10615. return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
  10616. }
  10617. #endif /* MS_WINDOWS */
  10618. /* This is used for fpathconf(), pathconf(), confstr() and sysconf().
  10619. * It maps strings representing configuration variable names to
  10620. * integer values, allowing those functions to be called with the
  10621. * magic names instead of polluting the module's namespace with tons of
  10622. * rarely-used constants. There are three separate tables that use
  10623. * these definitions.
  10624. *
  10625. * This code is always included, even if none of the interfaces that
  10626. * need it are included. The #if hackery needed to avoid it would be
  10627. * sufficiently pervasive that it's not worth the loss of readability.
  10628. */
  10629. struct constdef {
  10630. const char *name;
  10631. int value;
  10632. };
  10633. static int
  10634. conv_confname(PyObject *arg, int *valuep, struct constdef *table,
  10635. size_t tablesize)
  10636. {
  10637. if (PyLong_Check(arg)) {
  10638. int value = _PyLong_AsInt(arg);
  10639. if (value == -1 && PyErr_Occurred())
  10640. return 0;
  10641. *valuep = value;
  10642. return 1;
  10643. }
  10644. else {
  10645. /* look up the value in the table using a binary search */
  10646. size_t lo = 0;
  10647. size_t mid;
  10648. size_t hi = tablesize;
  10649. int cmp;
  10650. const char *confname;
  10651. if (!PyUnicode_Check(arg)) {
  10652. PyErr_SetString(PyExc_TypeError,
  10653. "configuration names must be strings or integers");
  10654. return 0;
  10655. }
  10656. confname = PyUnicode_AsUTF8(arg);
  10657. if (confname == NULL)
  10658. return 0;
  10659. while (lo < hi) {
  10660. mid = (lo + hi) / 2;
  10661. cmp = strcmp(confname, table[mid].name);
  10662. if (cmp < 0)
  10663. hi = mid;
  10664. else if (cmp > 0)
  10665. lo = mid + 1;
  10666. else {
  10667. *valuep = table[mid].value;
  10668. return 1;
  10669. }
  10670. }
  10671. PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
  10672. return 0;
  10673. }
  10674. }
  10675. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  10676. static struct constdef posix_constants_pathconf[] = {
  10677. #ifdef _PC_ABI_AIO_XFER_MAX
  10678. {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
  10679. #endif
  10680. #ifdef _PC_ABI_ASYNC_IO
  10681. {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
  10682. #endif
  10683. #ifdef _PC_ASYNC_IO
  10684. {"PC_ASYNC_IO", _PC_ASYNC_IO},
  10685. #endif
  10686. #ifdef _PC_CHOWN_RESTRICTED
  10687. {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
  10688. #endif
  10689. #ifdef _PC_FILESIZEBITS
  10690. {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
  10691. #endif
  10692. #ifdef _PC_LAST
  10693. {"PC_LAST", _PC_LAST},
  10694. #endif
  10695. #ifdef _PC_LINK_MAX
  10696. {"PC_LINK_MAX", _PC_LINK_MAX},
  10697. #endif
  10698. #ifdef _PC_MAX_CANON
  10699. {"PC_MAX_CANON", _PC_MAX_CANON},
  10700. #endif
  10701. #ifdef _PC_MAX_INPUT
  10702. {"PC_MAX_INPUT", _PC_MAX_INPUT},
  10703. #endif
  10704. #ifdef _PC_NAME_MAX
  10705. {"PC_NAME_MAX", _PC_NAME_MAX},
  10706. #endif
  10707. #ifdef _PC_NO_TRUNC
  10708. {"PC_NO_TRUNC", _PC_NO_TRUNC},
  10709. #endif
  10710. #ifdef _PC_PATH_MAX
  10711. {"PC_PATH_MAX", _PC_PATH_MAX},
  10712. #endif
  10713. #ifdef _PC_PIPE_BUF
  10714. {"PC_PIPE_BUF", _PC_PIPE_BUF},
  10715. #endif
  10716. #ifdef _PC_PRIO_IO
  10717. {"PC_PRIO_IO", _PC_PRIO_IO},
  10718. #endif
  10719. #ifdef _PC_SOCK_MAXBUF
  10720. {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
  10721. #endif
  10722. #ifdef _PC_SYNC_IO
  10723. {"PC_SYNC_IO", _PC_SYNC_IO},
  10724. #endif
  10725. #ifdef _PC_VDISABLE
  10726. {"PC_VDISABLE", _PC_VDISABLE},
  10727. #endif
  10728. #ifdef _PC_ACL_ENABLED
  10729. {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
  10730. #endif
  10731. #ifdef _PC_MIN_HOLE_SIZE
  10732. {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
  10733. #endif
  10734. #ifdef _PC_ALLOC_SIZE_MIN
  10735. {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
  10736. #endif
  10737. #ifdef _PC_REC_INCR_XFER_SIZE
  10738. {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
  10739. #endif
  10740. #ifdef _PC_REC_MAX_XFER_SIZE
  10741. {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
  10742. #endif
  10743. #ifdef _PC_REC_MIN_XFER_SIZE
  10744. {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
  10745. #endif
  10746. #ifdef _PC_REC_XFER_ALIGN
  10747. {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
  10748. #endif
  10749. #ifdef _PC_SYMLINK_MAX
  10750. {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
  10751. #endif
  10752. #ifdef _PC_XATTR_ENABLED
  10753. {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
  10754. #endif
  10755. #ifdef _PC_XATTR_EXISTS
  10756. {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
  10757. #endif
  10758. #ifdef _PC_TIMESTAMP_RESOLUTION
  10759. {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
  10760. #endif
  10761. };
  10762. static int
  10763. conv_path_confname(PyObject *arg, int *valuep)
  10764. {
  10765. return conv_confname(arg, valuep, posix_constants_pathconf,
  10766. sizeof(posix_constants_pathconf)
  10767. / sizeof(struct constdef));
  10768. }
  10769. #endif
  10770. #ifdef HAVE_FPATHCONF
  10771. /*[clinic input]
  10772. os.fpathconf -> long
  10773. fd: fildes
  10774. name: path_confname
  10775. /
  10776. Return the configuration limit name for the file descriptor fd.
  10777. If there is no limit, return -1.
  10778. [clinic start generated code]*/
  10779. static long
  10780. os_fpathconf_impl(PyObject *module, int fd, int name)
  10781. /*[clinic end generated code: output=d5b7042425fc3e21 input=5b8d2471cfaae186]*/
  10782. {
  10783. long limit;
  10784. errno = 0;
  10785. limit = fpathconf(fd, name);
  10786. if (limit == -1 && errno != 0)
  10787. posix_error();
  10788. return limit;
  10789. }
  10790. #endif /* HAVE_FPATHCONF */
  10791. #ifdef HAVE_PATHCONF
  10792. /*[clinic input]
  10793. os.pathconf -> long
  10794. path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
  10795. name: path_confname
  10796. Return the configuration limit name for the file or directory path.
  10797. If there is no limit, return -1.
  10798. On some platforms, path may also be specified as an open file descriptor.
  10799. If this functionality is unavailable, using it raises an exception.
  10800. [clinic start generated code]*/
  10801. static long
  10802. os_pathconf_impl(PyObject *module, path_t *path, int name)
  10803. /*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
  10804. {
  10805. long limit;
  10806. errno = 0;
  10807. #ifdef HAVE_FPATHCONF
  10808. if (path->fd != -1)
  10809. limit = fpathconf(path->fd, name);
  10810. else
  10811. #endif
  10812. limit = pathconf(path->narrow, name);
  10813. if (limit == -1 && errno != 0) {
  10814. if (errno == EINVAL)
  10815. /* could be a path or name problem */
  10816. posix_error();
  10817. else
  10818. path_error(path);
  10819. }
  10820. return limit;
  10821. }
  10822. #endif /* HAVE_PATHCONF */
  10823. #ifdef HAVE_CONFSTR
  10824. static struct constdef posix_constants_confstr[] = {
  10825. #ifdef _CS_ARCHITECTURE
  10826. {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
  10827. #endif
  10828. #ifdef _CS_GNU_LIBC_VERSION
  10829. {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
  10830. #endif
  10831. #ifdef _CS_GNU_LIBPTHREAD_VERSION
  10832. {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
  10833. #endif
  10834. #ifdef _CS_HOSTNAME
  10835. {"CS_HOSTNAME", _CS_HOSTNAME},
  10836. #endif
  10837. #ifdef _CS_HW_PROVIDER
  10838. {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
  10839. #endif
  10840. #ifdef _CS_HW_SERIAL
  10841. {"CS_HW_SERIAL", _CS_HW_SERIAL},
  10842. #endif
  10843. #ifdef _CS_INITTAB_NAME
  10844. {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
  10845. #endif
  10846. #ifdef _CS_LFS64_CFLAGS
  10847. {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
  10848. #endif
  10849. #ifdef _CS_LFS64_LDFLAGS
  10850. {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
  10851. #endif
  10852. #ifdef _CS_LFS64_LIBS
  10853. {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
  10854. #endif
  10855. #ifdef _CS_LFS64_LINTFLAGS
  10856. {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
  10857. #endif
  10858. #ifdef _CS_LFS_CFLAGS
  10859. {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
  10860. #endif
  10861. #ifdef _CS_LFS_LDFLAGS
  10862. {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
  10863. #endif
  10864. #ifdef _CS_LFS_LIBS
  10865. {"CS_LFS_LIBS", _CS_LFS_LIBS},
  10866. #endif
  10867. #ifdef _CS_LFS_LINTFLAGS
  10868. {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
  10869. #endif
  10870. #ifdef _CS_MACHINE
  10871. {"CS_MACHINE", _CS_MACHINE},
  10872. #endif
  10873. #ifdef _CS_PATH
  10874. {"CS_PATH", _CS_PATH},
  10875. #endif
  10876. #ifdef _CS_RELEASE
  10877. {"CS_RELEASE", _CS_RELEASE},
  10878. #endif
  10879. #ifdef _CS_SRPC_DOMAIN
  10880. {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
  10881. #endif
  10882. #ifdef _CS_SYSNAME
  10883. {"CS_SYSNAME", _CS_SYSNAME},
  10884. #endif
  10885. #ifdef _CS_VERSION
  10886. {"CS_VERSION", _CS_VERSION},
  10887. #endif
  10888. #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
  10889. {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
  10890. #endif
  10891. #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
  10892. {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
  10893. #endif
  10894. #ifdef _CS_XBS5_ILP32_OFF32_LIBS
  10895. {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
  10896. #endif
  10897. #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
  10898. {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
  10899. #endif
  10900. #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
  10901. {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
  10902. #endif
  10903. #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
  10904. {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
  10905. #endif
  10906. #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
  10907. {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
  10908. #endif
  10909. #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
  10910. {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
  10911. #endif
  10912. #ifdef _CS_XBS5_LP64_OFF64_CFLAGS
  10913. {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
  10914. #endif
  10915. #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
  10916. {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
  10917. #endif
  10918. #ifdef _CS_XBS5_LP64_OFF64_LIBS
  10919. {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
  10920. #endif
  10921. #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
  10922. {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
  10923. #endif
  10924. #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
  10925. {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
  10926. #endif
  10927. #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
  10928. {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
  10929. #endif
  10930. #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
  10931. {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
  10932. #endif
  10933. #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
  10934. {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
  10935. #endif
  10936. #ifdef _MIPS_CS_AVAIL_PROCESSORS
  10937. {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
  10938. #endif
  10939. #ifdef _MIPS_CS_BASE
  10940. {"MIPS_CS_BASE", _MIPS_CS_BASE},
  10941. #endif
  10942. #ifdef _MIPS_CS_HOSTID
  10943. {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
  10944. #endif
  10945. #ifdef _MIPS_CS_HW_NAME
  10946. {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
  10947. #endif
  10948. #ifdef _MIPS_CS_NUM_PROCESSORS
  10949. {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
  10950. #endif
  10951. #ifdef _MIPS_CS_OSREL_MAJ
  10952. {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
  10953. #endif
  10954. #ifdef _MIPS_CS_OSREL_MIN
  10955. {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
  10956. #endif
  10957. #ifdef _MIPS_CS_OSREL_PATCH
  10958. {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
  10959. #endif
  10960. #ifdef _MIPS_CS_OS_NAME
  10961. {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
  10962. #endif
  10963. #ifdef _MIPS_CS_OS_PROVIDER
  10964. {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
  10965. #endif
  10966. #ifdef _MIPS_CS_PROCESSORS
  10967. {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
  10968. #endif
  10969. #ifdef _MIPS_CS_SERIAL
  10970. {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
  10971. #endif
  10972. #ifdef _MIPS_CS_VENDOR
  10973. {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
  10974. #endif
  10975. };
  10976. static int
  10977. conv_confstr_confname(PyObject *arg, int *valuep)
  10978. {
  10979. return conv_confname(arg, valuep, posix_constants_confstr,
  10980. sizeof(posix_constants_confstr)
  10981. / sizeof(struct constdef));
  10982. }
  10983. /*[clinic input]
  10984. os.confstr
  10985. name: confstr_confname
  10986. /
  10987. Return a string-valued system configuration variable.
  10988. [clinic start generated code]*/
  10989. static PyObject *
  10990. os_confstr_impl(PyObject *module, int name)
  10991. /*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
  10992. {
  10993. PyObject *result = NULL;
  10994. char buffer[255];
  10995. size_t len;
  10996. errno = 0;
  10997. len = confstr(name, buffer, sizeof(buffer));
  10998. if (len == 0) {
  10999. if (errno) {
  11000. posix_error();
  11001. return NULL;
  11002. }
  11003. else {
  11004. Py_RETURN_NONE;
  11005. }
  11006. }
  11007. if (len >= sizeof(buffer)) {
  11008. size_t len2;
  11009. char *buf = PyMem_Malloc(len);
  11010. if (buf == NULL)
  11011. return PyErr_NoMemory();
  11012. len2 = confstr(name, buf, len);
  11013. assert(len == len2);
  11014. result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
  11015. PyMem_Free(buf);
  11016. }
  11017. else
  11018. result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
  11019. return result;
  11020. }
  11021. #endif /* HAVE_CONFSTR */
  11022. #ifdef HAVE_SYSCONF
  11023. static struct constdef posix_constants_sysconf[] = {
  11024. #ifdef _SC_2_CHAR_TERM
  11025. {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
  11026. #endif
  11027. #ifdef _SC_2_C_BIND
  11028. {"SC_2_C_BIND", _SC_2_C_BIND},
  11029. #endif
  11030. #ifdef _SC_2_C_DEV
  11031. {"SC_2_C_DEV", _SC_2_C_DEV},
  11032. #endif
  11033. #ifdef _SC_2_C_VERSION
  11034. {"SC_2_C_VERSION", _SC_2_C_VERSION},
  11035. #endif
  11036. #ifdef _SC_2_FORT_DEV
  11037. {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
  11038. #endif
  11039. #ifdef _SC_2_FORT_RUN
  11040. {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
  11041. #endif
  11042. #ifdef _SC_2_LOCALEDEF
  11043. {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
  11044. #endif
  11045. #ifdef _SC_2_SW_DEV
  11046. {"SC_2_SW_DEV", _SC_2_SW_DEV},
  11047. #endif
  11048. #ifdef _SC_2_UPE
  11049. {"SC_2_UPE", _SC_2_UPE},
  11050. #endif
  11051. #ifdef _SC_2_VERSION
  11052. {"SC_2_VERSION", _SC_2_VERSION},
  11053. #endif
  11054. #ifdef _SC_ABI_ASYNCHRONOUS_IO
  11055. {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
  11056. #endif
  11057. #ifdef _SC_ACL
  11058. {"SC_ACL", _SC_ACL},
  11059. #endif
  11060. #ifdef _SC_AIO_LISTIO_MAX
  11061. {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
  11062. #endif
  11063. #ifdef _SC_AIO_MAX
  11064. {"SC_AIO_MAX", _SC_AIO_MAX},
  11065. #endif
  11066. #ifdef _SC_AIO_PRIO_DELTA_MAX
  11067. {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
  11068. #endif
  11069. #ifdef _SC_ARG_MAX
  11070. {"SC_ARG_MAX", _SC_ARG_MAX},
  11071. #endif
  11072. #ifdef _SC_ASYNCHRONOUS_IO
  11073. {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
  11074. #endif
  11075. #ifdef _SC_ATEXIT_MAX
  11076. {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
  11077. #endif
  11078. #ifdef _SC_AUDIT
  11079. {"SC_AUDIT", _SC_AUDIT},
  11080. #endif
  11081. #ifdef _SC_AVPHYS_PAGES
  11082. {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
  11083. #endif
  11084. #ifdef _SC_BC_BASE_MAX
  11085. {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
  11086. #endif
  11087. #ifdef _SC_BC_DIM_MAX
  11088. {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
  11089. #endif
  11090. #ifdef _SC_BC_SCALE_MAX
  11091. {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
  11092. #endif
  11093. #ifdef _SC_BC_STRING_MAX
  11094. {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
  11095. #endif
  11096. #ifdef _SC_CAP
  11097. {"SC_CAP", _SC_CAP},
  11098. #endif
  11099. #ifdef _SC_CHARCLASS_NAME_MAX
  11100. {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
  11101. #endif
  11102. #ifdef _SC_CHAR_BIT
  11103. {"SC_CHAR_BIT", _SC_CHAR_BIT},
  11104. #endif
  11105. #ifdef _SC_CHAR_MAX
  11106. {"SC_CHAR_MAX", _SC_CHAR_MAX},
  11107. #endif
  11108. #ifdef _SC_CHAR_MIN
  11109. {"SC_CHAR_MIN", _SC_CHAR_MIN},
  11110. #endif
  11111. #ifdef _SC_CHILD_MAX
  11112. {"SC_CHILD_MAX", _SC_CHILD_MAX},
  11113. #endif
  11114. #ifdef _SC_CLK_TCK
  11115. {"SC_CLK_TCK", _SC_CLK_TCK},
  11116. #endif
  11117. #ifdef _SC_COHER_BLKSZ
  11118. {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
  11119. #endif
  11120. #ifdef _SC_COLL_WEIGHTS_MAX
  11121. {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
  11122. #endif
  11123. #ifdef _SC_DCACHE_ASSOC
  11124. {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
  11125. #endif
  11126. #ifdef _SC_DCACHE_BLKSZ
  11127. {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
  11128. #endif
  11129. #ifdef _SC_DCACHE_LINESZ
  11130. {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
  11131. #endif
  11132. #ifdef _SC_DCACHE_SZ
  11133. {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
  11134. #endif
  11135. #ifdef _SC_DCACHE_TBLKSZ
  11136. {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
  11137. #endif
  11138. #ifdef _SC_DELAYTIMER_MAX
  11139. {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
  11140. #endif
  11141. #ifdef _SC_EQUIV_CLASS_MAX
  11142. {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
  11143. #endif
  11144. #ifdef _SC_EXPR_NEST_MAX
  11145. {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
  11146. #endif
  11147. #ifdef _SC_FSYNC
  11148. {"SC_FSYNC", _SC_FSYNC},
  11149. #endif
  11150. #ifdef _SC_GETGR_R_SIZE_MAX
  11151. {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
  11152. #endif
  11153. #ifdef _SC_GETPW_R_SIZE_MAX
  11154. {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
  11155. #endif
  11156. #ifdef _SC_ICACHE_ASSOC
  11157. {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
  11158. #endif
  11159. #ifdef _SC_ICACHE_BLKSZ
  11160. {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
  11161. #endif
  11162. #ifdef _SC_ICACHE_LINESZ
  11163. {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
  11164. #endif
  11165. #ifdef _SC_ICACHE_SZ
  11166. {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
  11167. #endif
  11168. #ifdef _SC_INF
  11169. {"SC_INF", _SC_INF},
  11170. #endif
  11171. #ifdef _SC_INT_MAX
  11172. {"SC_INT_MAX", _SC_INT_MAX},
  11173. #endif
  11174. #ifdef _SC_INT_MIN
  11175. {"SC_INT_MIN", _SC_INT_MIN},
  11176. #endif
  11177. #ifdef _SC_IOV_MAX
  11178. {"SC_IOV_MAX", _SC_IOV_MAX},
  11179. #endif
  11180. #ifdef _SC_IP_SECOPTS
  11181. {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
  11182. #endif
  11183. #ifdef _SC_JOB_CONTROL
  11184. {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
  11185. #endif
  11186. #ifdef _SC_KERN_POINTERS
  11187. {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
  11188. #endif
  11189. #ifdef _SC_KERN_SIM
  11190. {"SC_KERN_SIM", _SC_KERN_SIM},
  11191. #endif
  11192. #ifdef _SC_LINE_MAX
  11193. {"SC_LINE_MAX", _SC_LINE_MAX},
  11194. #endif
  11195. #ifdef _SC_LOGIN_NAME_MAX
  11196. {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
  11197. #endif
  11198. #ifdef _SC_LOGNAME_MAX
  11199. {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
  11200. #endif
  11201. #ifdef _SC_LONG_BIT
  11202. {"SC_LONG_BIT", _SC_LONG_BIT},
  11203. #endif
  11204. #ifdef _SC_MAC
  11205. {"SC_MAC", _SC_MAC},
  11206. #endif
  11207. #ifdef _SC_MAPPED_FILES
  11208. {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
  11209. #endif
  11210. #ifdef _SC_MAXPID
  11211. {"SC_MAXPID", _SC_MAXPID},
  11212. #endif
  11213. #ifdef _SC_MB_LEN_MAX
  11214. {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
  11215. #endif
  11216. #ifdef _SC_MEMLOCK
  11217. {"SC_MEMLOCK", _SC_MEMLOCK},
  11218. #endif
  11219. #ifdef _SC_MEMLOCK_RANGE
  11220. {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
  11221. #endif
  11222. #ifdef _SC_MEMORY_PROTECTION
  11223. {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
  11224. #endif
  11225. #ifdef _SC_MESSAGE_PASSING
  11226. {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
  11227. #endif
  11228. #ifdef _SC_MMAP_FIXED_ALIGNMENT
  11229. {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
  11230. #endif
  11231. #ifdef _SC_MQ_OPEN_MAX
  11232. {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
  11233. #endif
  11234. #ifdef _SC_MQ_PRIO_MAX
  11235. {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
  11236. #endif
  11237. #ifdef _SC_NACLS_MAX
  11238. {"SC_NACLS_MAX", _SC_NACLS_MAX},
  11239. #endif
  11240. #ifdef _SC_NGROUPS_MAX
  11241. {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
  11242. #endif
  11243. #ifdef _SC_NL_ARGMAX
  11244. {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
  11245. #endif
  11246. #ifdef _SC_NL_LANGMAX
  11247. {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
  11248. #endif
  11249. #ifdef _SC_NL_MSGMAX
  11250. {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
  11251. #endif
  11252. #ifdef _SC_NL_NMAX
  11253. {"SC_NL_NMAX", _SC_NL_NMAX},
  11254. #endif
  11255. #ifdef _SC_NL_SETMAX
  11256. {"SC_NL_SETMAX", _SC_NL_SETMAX},
  11257. #endif
  11258. #ifdef _SC_NL_TEXTMAX
  11259. {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
  11260. #endif
  11261. #ifdef _SC_NPROCESSORS_CONF
  11262. {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
  11263. #endif
  11264. #ifdef _SC_NPROCESSORS_ONLN
  11265. {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
  11266. #endif
  11267. #ifdef _SC_NPROC_CONF
  11268. {"SC_NPROC_CONF", _SC_NPROC_CONF},
  11269. #endif
  11270. #ifdef _SC_NPROC_ONLN
  11271. {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
  11272. #endif
  11273. #ifdef _SC_NZERO
  11274. {"SC_NZERO", _SC_NZERO},
  11275. #endif
  11276. #ifdef _SC_OPEN_MAX
  11277. {"SC_OPEN_MAX", _SC_OPEN_MAX},
  11278. #endif
  11279. #ifdef _SC_PAGESIZE
  11280. {"SC_PAGESIZE", _SC_PAGESIZE},
  11281. #endif
  11282. #ifdef _SC_PAGE_SIZE
  11283. {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
  11284. #endif
  11285. #ifdef _SC_AIX_REALMEM
  11286. {"SC_AIX_REALMEM", _SC_AIX_REALMEM},
  11287. #endif
  11288. #ifdef _SC_PASS_MAX
  11289. {"SC_PASS_MAX", _SC_PASS_MAX},
  11290. #endif
  11291. #ifdef _SC_PHYS_PAGES
  11292. {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
  11293. #endif
  11294. #ifdef _SC_PII
  11295. {"SC_PII", _SC_PII},
  11296. #endif
  11297. #ifdef _SC_PII_INTERNET
  11298. {"SC_PII_INTERNET", _SC_PII_INTERNET},
  11299. #endif
  11300. #ifdef _SC_PII_INTERNET_DGRAM
  11301. {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
  11302. #endif
  11303. #ifdef _SC_PII_INTERNET_STREAM
  11304. {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
  11305. #endif
  11306. #ifdef _SC_PII_OSI
  11307. {"SC_PII_OSI", _SC_PII_OSI},
  11308. #endif
  11309. #ifdef _SC_PII_OSI_CLTS
  11310. {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
  11311. #endif
  11312. #ifdef _SC_PII_OSI_COTS
  11313. {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
  11314. #endif
  11315. #ifdef _SC_PII_OSI_M
  11316. {"SC_PII_OSI_M", _SC_PII_OSI_M},
  11317. #endif
  11318. #ifdef _SC_PII_SOCKET
  11319. {"SC_PII_SOCKET", _SC_PII_SOCKET},
  11320. #endif
  11321. #ifdef _SC_PII_XTI
  11322. {"SC_PII_XTI", _SC_PII_XTI},
  11323. #endif
  11324. #ifdef _SC_POLL
  11325. {"SC_POLL", _SC_POLL},
  11326. #endif
  11327. #ifdef _SC_PRIORITIZED_IO
  11328. {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
  11329. #endif
  11330. #ifdef _SC_PRIORITY_SCHEDULING
  11331. {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
  11332. #endif
  11333. #ifdef _SC_REALTIME_SIGNALS
  11334. {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
  11335. #endif
  11336. #ifdef _SC_RE_DUP_MAX
  11337. {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
  11338. #endif
  11339. #ifdef _SC_RTSIG_MAX
  11340. {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
  11341. #endif
  11342. #ifdef _SC_SAVED_IDS
  11343. {"SC_SAVED_IDS", _SC_SAVED_IDS},
  11344. #endif
  11345. #ifdef _SC_SCHAR_MAX
  11346. {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
  11347. #endif
  11348. #ifdef _SC_SCHAR_MIN
  11349. {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
  11350. #endif
  11351. #ifdef _SC_SELECT
  11352. {"SC_SELECT", _SC_SELECT},
  11353. #endif
  11354. #ifdef _SC_SEMAPHORES
  11355. {"SC_SEMAPHORES", _SC_SEMAPHORES},
  11356. #endif
  11357. #ifdef _SC_SEM_NSEMS_MAX
  11358. {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
  11359. #endif
  11360. #ifdef _SC_SEM_VALUE_MAX
  11361. {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
  11362. #endif
  11363. #ifdef _SC_SHARED_MEMORY_OBJECTS
  11364. {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
  11365. #endif
  11366. #ifdef _SC_SHRT_MAX
  11367. {"SC_SHRT_MAX", _SC_SHRT_MAX},
  11368. #endif
  11369. #ifdef _SC_SHRT_MIN
  11370. {"SC_SHRT_MIN", _SC_SHRT_MIN},
  11371. #endif
  11372. #ifdef _SC_SIGQUEUE_MAX
  11373. {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
  11374. #endif
  11375. #ifdef _SC_SIGRT_MAX
  11376. {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
  11377. #endif
  11378. #ifdef _SC_SIGRT_MIN
  11379. {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
  11380. #endif
  11381. #ifdef _SC_SOFTPOWER
  11382. {"SC_SOFTPOWER", _SC_SOFTPOWER},
  11383. #endif
  11384. #ifdef _SC_SPLIT_CACHE
  11385. {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
  11386. #endif
  11387. #ifdef _SC_SSIZE_MAX
  11388. {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
  11389. #endif
  11390. #ifdef _SC_STACK_PROT
  11391. {"SC_STACK_PROT", _SC_STACK_PROT},
  11392. #endif
  11393. #ifdef _SC_STREAM_MAX
  11394. {"SC_STREAM_MAX", _SC_STREAM_MAX},
  11395. #endif
  11396. #ifdef _SC_SYNCHRONIZED_IO
  11397. {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
  11398. #endif
  11399. #ifdef _SC_THREADS
  11400. {"SC_THREADS", _SC_THREADS},
  11401. #endif
  11402. #ifdef _SC_THREAD_ATTR_STACKADDR
  11403. {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
  11404. #endif
  11405. #ifdef _SC_THREAD_ATTR_STACKSIZE
  11406. {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
  11407. #endif
  11408. #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
  11409. {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
  11410. #endif
  11411. #ifdef _SC_THREAD_KEYS_MAX
  11412. {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
  11413. #endif
  11414. #ifdef _SC_THREAD_PRIORITY_SCHEDULING
  11415. {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
  11416. #endif
  11417. #ifdef _SC_THREAD_PRIO_INHERIT
  11418. {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
  11419. #endif
  11420. #ifdef _SC_THREAD_PRIO_PROTECT
  11421. {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
  11422. #endif
  11423. #ifdef _SC_THREAD_PROCESS_SHARED
  11424. {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
  11425. #endif
  11426. #ifdef _SC_THREAD_SAFE_FUNCTIONS
  11427. {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
  11428. #endif
  11429. #ifdef _SC_THREAD_STACK_MIN
  11430. {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
  11431. #endif
  11432. #ifdef _SC_THREAD_THREADS_MAX
  11433. {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
  11434. #endif
  11435. #ifdef _SC_TIMERS
  11436. {"SC_TIMERS", _SC_TIMERS},
  11437. #endif
  11438. #ifdef _SC_TIMER_MAX
  11439. {"SC_TIMER_MAX", _SC_TIMER_MAX},
  11440. #endif
  11441. #ifdef _SC_TTY_NAME_MAX
  11442. {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
  11443. #endif
  11444. #ifdef _SC_TZNAME_MAX
  11445. {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
  11446. #endif
  11447. #ifdef _SC_T_IOV_MAX
  11448. {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
  11449. #endif
  11450. #ifdef _SC_UCHAR_MAX
  11451. {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
  11452. #endif
  11453. #ifdef _SC_UINT_MAX
  11454. {"SC_UINT_MAX", _SC_UINT_MAX},
  11455. #endif
  11456. #ifdef _SC_UIO_MAXIOV
  11457. {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
  11458. #endif
  11459. #ifdef _SC_ULONG_MAX
  11460. {"SC_ULONG_MAX", _SC_ULONG_MAX},
  11461. #endif
  11462. #ifdef _SC_USHRT_MAX
  11463. {"SC_USHRT_MAX", _SC_USHRT_MAX},
  11464. #endif
  11465. #ifdef _SC_VERSION
  11466. {"SC_VERSION", _SC_VERSION},
  11467. #endif
  11468. #ifdef _SC_WORD_BIT
  11469. {"SC_WORD_BIT", _SC_WORD_BIT},
  11470. #endif
  11471. #ifdef _SC_XBS5_ILP32_OFF32
  11472. {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
  11473. #endif
  11474. #ifdef _SC_XBS5_ILP32_OFFBIG
  11475. {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
  11476. #endif
  11477. #ifdef _SC_XBS5_LP64_OFF64
  11478. {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
  11479. #endif
  11480. #ifdef _SC_XBS5_LPBIG_OFFBIG
  11481. {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
  11482. #endif
  11483. #ifdef _SC_XOPEN_CRYPT
  11484. {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
  11485. #endif
  11486. #ifdef _SC_XOPEN_ENH_I18N
  11487. {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
  11488. #endif
  11489. #ifdef _SC_XOPEN_LEGACY
  11490. {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
  11491. #endif
  11492. #ifdef _SC_XOPEN_REALTIME
  11493. {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
  11494. #endif
  11495. #ifdef _SC_XOPEN_REALTIME_THREADS
  11496. {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
  11497. #endif
  11498. #ifdef _SC_XOPEN_SHM
  11499. {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
  11500. #endif
  11501. #ifdef _SC_XOPEN_UNIX
  11502. {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
  11503. #endif
  11504. #ifdef _SC_XOPEN_VERSION
  11505. {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
  11506. #endif
  11507. #ifdef _SC_XOPEN_XCU_VERSION
  11508. {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
  11509. #endif
  11510. #ifdef _SC_XOPEN_XPG2
  11511. {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
  11512. #endif
  11513. #ifdef _SC_XOPEN_XPG3
  11514. {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
  11515. #endif
  11516. #ifdef _SC_XOPEN_XPG4
  11517. {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
  11518. #endif
  11519. #ifdef _SC_MINSIGSTKSZ
  11520. {"SC_MINSIGSTKSZ", _SC_MINSIGSTKSZ},
  11521. #endif
  11522. };
  11523. static int
  11524. conv_sysconf_confname(PyObject *arg, int *valuep)
  11525. {
  11526. return conv_confname(arg, valuep, posix_constants_sysconf,
  11527. sizeof(posix_constants_sysconf)
  11528. / sizeof(struct constdef));
  11529. }
  11530. /*[clinic input]
  11531. os.sysconf -> long
  11532. name: sysconf_confname
  11533. /
  11534. Return an integer-valued system configuration variable.
  11535. [clinic start generated code]*/
  11536. static long
  11537. os_sysconf_impl(PyObject *module, int name)
  11538. /*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
  11539. {
  11540. long value;
  11541. errno = 0;
  11542. value = sysconf(name);
  11543. if (value == -1 && errno != 0)
  11544. posix_error();
  11545. return value;
  11546. }
  11547. #endif /* HAVE_SYSCONF */
  11548. /* This code is used to ensure that the tables of configuration value names
  11549. * are in sorted order as required by conv_confname(), and also to build
  11550. * the exported dictionaries that are used to publish information about the
  11551. * names available on the host platform.
  11552. *
  11553. * Sorting the table at runtime ensures that the table is properly ordered
  11554. * when used, even for platforms we're not able to test on. It also makes
  11555. * it easier to add additional entries to the tables.
  11556. */
  11557. static int
  11558. cmp_constdefs(const void *v1, const void *v2)
  11559. {
  11560. const struct constdef *c1 =
  11561. (const struct constdef *) v1;
  11562. const struct constdef *c2 =
  11563. (const struct constdef *) v2;
  11564. return strcmp(c1->name, c2->name);
  11565. }
  11566. static int
  11567. setup_confname_table(struct constdef *table, size_t tablesize,
  11568. const char *tablename, PyObject *module)
  11569. {
  11570. PyObject *d = NULL;
  11571. size_t i;
  11572. qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
  11573. d = PyDict_New();
  11574. if (d == NULL)
  11575. return -1;
  11576. for (i=0; i < tablesize; ++i) {
  11577. PyObject *o = PyLong_FromLong(table[i].value);
  11578. if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
  11579. Py_XDECREF(o);
  11580. Py_DECREF(d);
  11581. return -1;
  11582. }
  11583. Py_DECREF(o);
  11584. }
  11585. return _PyModule_Add(module, tablename, d);
  11586. }
  11587. /* Return -1 on failure, 0 on success. */
  11588. static int
  11589. setup_confname_tables(PyObject *module)
  11590. {
  11591. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  11592. if (setup_confname_table(posix_constants_pathconf,
  11593. sizeof(posix_constants_pathconf)
  11594. / sizeof(struct constdef),
  11595. "pathconf_names", module))
  11596. return -1;
  11597. #endif
  11598. #ifdef HAVE_CONFSTR
  11599. if (setup_confname_table(posix_constants_confstr,
  11600. sizeof(posix_constants_confstr)
  11601. / sizeof(struct constdef),
  11602. "confstr_names", module))
  11603. return -1;
  11604. #endif
  11605. #ifdef HAVE_SYSCONF
  11606. if (setup_confname_table(posix_constants_sysconf,
  11607. sizeof(posix_constants_sysconf)
  11608. / sizeof(struct constdef),
  11609. "sysconf_names", module))
  11610. return -1;
  11611. #endif
  11612. return 0;
  11613. }
  11614. /*[clinic input]
  11615. os.abort
  11616. Abort the interpreter immediately.
  11617. This function 'dumps core' or otherwise fails in the hardest way possible
  11618. on the hosting operating system. This function never returns.
  11619. [clinic start generated code]*/
  11620. static PyObject *
  11621. os_abort_impl(PyObject *module)
  11622. /*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
  11623. {
  11624. abort();
  11625. /*NOTREACHED*/
  11626. #ifndef __clang__
  11627. /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
  11628. GCC emits a warning without "return NULL;" (compiler bug?), but Clang
  11629. is smarter and emits a warning on the return. */
  11630. Py_FatalError("abort() called from Python code didn't abort!");
  11631. return NULL;
  11632. #endif
  11633. }
  11634. #ifdef MS_WINDOWS
  11635. /* Grab ShellExecute dynamically from shell32 */
  11636. static int has_ShellExecute = -1;
  11637. static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
  11638. LPCWSTR, INT);
  11639. static int
  11640. check_ShellExecute(void)
  11641. {
  11642. HINSTANCE hShell32;
  11643. /* only recheck */
  11644. if (-1 == has_ShellExecute) {
  11645. Py_BEGIN_ALLOW_THREADS
  11646. /* Security note: this call is not vulnerable to "DLL hijacking".
  11647. SHELL32 is part of "KnownDLLs" and so Windows always load
  11648. the system SHELL32.DLL, even if there is another SHELL32.DLL
  11649. in the DLL search path. */
  11650. hShell32 = LoadLibraryW(L"SHELL32");
  11651. if (hShell32) {
  11652. *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
  11653. "ShellExecuteW");
  11654. has_ShellExecute = Py_ShellExecuteW != NULL;
  11655. } else {
  11656. has_ShellExecute = 0;
  11657. }
  11658. Py_END_ALLOW_THREADS
  11659. }
  11660. return has_ShellExecute;
  11661. }
  11662. /*[clinic input]
  11663. os.startfile
  11664. filepath: path_t
  11665. operation: Py_UNICODE = NULL
  11666. arguments: Py_UNICODE = NULL
  11667. cwd: path_t(nullable=True) = None
  11668. show_cmd: int = 1
  11669. Start a file with its associated application.
  11670. When "operation" is not specified or "open", this acts like
  11671. double-clicking the file in Explorer, or giving the file name as an
  11672. argument to the DOS "start" command: the file is opened with whatever
  11673. application (if any) its extension is associated.
  11674. When another "operation" is given, it specifies what should be done with
  11675. the file. A typical operation is "print".
  11676. "arguments" is passed to the application, but should be omitted if the
  11677. file is a document.
  11678. "cwd" is the working directory for the operation. If "filepath" is
  11679. relative, it will be resolved against this directory. This argument
  11680. should usually be an absolute path.
  11681. "show_cmd" can be used to override the recommended visibility option.
  11682. See the Windows ShellExecute documentation for values.
  11683. startfile returns as soon as the associated application is launched.
  11684. There is no option to wait for the application to close, and no way
  11685. to retrieve the application's exit status.
  11686. The filepath is relative to the current directory. If you want to use
  11687. an absolute path, make sure the first character is not a slash ("/");
  11688. the underlying Win32 ShellExecute function doesn't work if it is.
  11689. [clinic start generated code]*/
  11690. static PyObject *
  11691. os_startfile_impl(PyObject *module, path_t *filepath,
  11692. const Py_UNICODE *operation, const Py_UNICODE *arguments,
  11693. path_t *cwd, int show_cmd)
  11694. /*[clinic end generated code: output=3baa4f9795841880 input=8248997b80669622]*/
  11695. {
  11696. HINSTANCE rc;
  11697. if(!check_ShellExecute()) {
  11698. /* If the OS doesn't have ShellExecute, return a
  11699. NotImplementedError. */
  11700. return PyErr_Format(PyExc_NotImplementedError,
  11701. "startfile not available on this platform");
  11702. }
  11703. if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
  11704. return NULL;
  11705. }
  11706. if (PySys_Audit("os.startfile/2", "OuuOi", filepath->object, operation,
  11707. arguments, cwd->object ? cwd->object : Py_None,
  11708. show_cmd) < 0) {
  11709. return NULL;
  11710. }
  11711. Py_BEGIN_ALLOW_THREADS
  11712. rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
  11713. arguments, cwd->wide, show_cmd);
  11714. Py_END_ALLOW_THREADS
  11715. if (rc <= (HINSTANCE)32) {
  11716. win32_error_object("startfile", filepath->object);
  11717. return NULL;
  11718. }
  11719. Py_RETURN_NONE;
  11720. }
  11721. #endif /* MS_WINDOWS */
  11722. #ifdef HAVE_GETLOADAVG
  11723. /*[clinic input]
  11724. os.getloadavg
  11725. Return average recent system load information.
  11726. Return the number of processes in the system run queue averaged over
  11727. the last 1, 5, and 15 minutes as a tuple of three floats.
  11728. Raises OSError if the load average was unobtainable.
  11729. [clinic start generated code]*/
  11730. static PyObject *
  11731. os_getloadavg_impl(PyObject *module)
  11732. /*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
  11733. {
  11734. double loadavg[3];
  11735. if (getloadavg(loadavg, 3)!=3) {
  11736. PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
  11737. return NULL;
  11738. } else
  11739. return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
  11740. }
  11741. #endif /* HAVE_GETLOADAVG */
  11742. /*[clinic input]
  11743. os.device_encoding
  11744. fd: int
  11745. Return a string describing the encoding of a terminal's file descriptor.
  11746. The file descriptor must be attached to a terminal.
  11747. If the device is not a terminal, return None.
  11748. [clinic start generated code]*/
  11749. static PyObject *
  11750. os_device_encoding_impl(PyObject *module, int fd)
  11751. /*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
  11752. {
  11753. return _Py_device_encoding(fd);
  11754. }
  11755. #ifdef HAVE_SETRESUID
  11756. /*[clinic input]
  11757. os.setresuid
  11758. ruid: uid_t
  11759. euid: uid_t
  11760. suid: uid_t
  11761. /
  11762. Set the current process's real, effective, and saved user ids.
  11763. [clinic start generated code]*/
  11764. static PyObject *
  11765. os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
  11766. /*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
  11767. {
  11768. if (setresuid(ruid, euid, suid) < 0)
  11769. return posix_error();
  11770. Py_RETURN_NONE;
  11771. }
  11772. #endif /* HAVE_SETRESUID */
  11773. #ifdef HAVE_SETRESGID
  11774. /*[clinic input]
  11775. os.setresgid
  11776. rgid: gid_t
  11777. egid: gid_t
  11778. sgid: gid_t
  11779. /
  11780. Set the current process's real, effective, and saved group ids.
  11781. [clinic start generated code]*/
  11782. static PyObject *
  11783. os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
  11784. /*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
  11785. {
  11786. if (setresgid(rgid, egid, sgid) < 0)
  11787. return posix_error();
  11788. Py_RETURN_NONE;
  11789. }
  11790. #endif /* HAVE_SETRESGID */
  11791. #ifdef HAVE_GETRESUID
  11792. /*[clinic input]
  11793. os.getresuid
  11794. Return a tuple of the current process's real, effective, and saved user ids.
  11795. [clinic start generated code]*/
  11796. static PyObject *
  11797. os_getresuid_impl(PyObject *module)
  11798. /*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
  11799. {
  11800. uid_t ruid, euid, suid;
  11801. if (getresuid(&ruid, &euid, &suid) < 0)
  11802. return posix_error();
  11803. return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
  11804. _PyLong_FromUid(euid),
  11805. _PyLong_FromUid(suid));
  11806. }
  11807. #endif /* HAVE_GETRESUID */
  11808. #ifdef HAVE_GETRESGID
  11809. /*[clinic input]
  11810. os.getresgid
  11811. Return a tuple of the current process's real, effective, and saved group ids.
  11812. [clinic start generated code]*/
  11813. static PyObject *
  11814. os_getresgid_impl(PyObject *module)
  11815. /*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
  11816. {
  11817. gid_t rgid, egid, sgid;
  11818. if (getresgid(&rgid, &egid, &sgid) < 0)
  11819. return posix_error();
  11820. return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
  11821. _PyLong_FromGid(egid),
  11822. _PyLong_FromGid(sgid));
  11823. }
  11824. #endif /* HAVE_GETRESGID */
  11825. #ifdef USE_XATTRS
  11826. /*[clinic input]
  11827. os.getxattr
  11828. path: path_t(allow_fd=True)
  11829. attribute: path_t
  11830. *
  11831. follow_symlinks: bool = True
  11832. Return the value of extended attribute attribute on path.
  11833. path may be either a string, a path-like object, or an open file descriptor.
  11834. If follow_symlinks is False, and the last element of the path is a symbolic
  11835. link, getxattr will examine the symbolic link itself instead of the file
  11836. the link points to.
  11837. [clinic start generated code]*/
  11838. static PyObject *
  11839. os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11840. int follow_symlinks)
  11841. /*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
  11842. {
  11843. Py_ssize_t i;
  11844. PyObject *buffer = NULL;
  11845. if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
  11846. return NULL;
  11847. if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
  11848. return NULL;
  11849. }
  11850. for (i = 0; ; i++) {
  11851. void *ptr;
  11852. ssize_t result;
  11853. static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
  11854. Py_ssize_t buffer_size = buffer_sizes[i];
  11855. if (!buffer_size) {
  11856. path_error(path);
  11857. return NULL;
  11858. }
  11859. buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
  11860. if (!buffer)
  11861. return NULL;
  11862. ptr = PyBytes_AS_STRING(buffer);
  11863. Py_BEGIN_ALLOW_THREADS;
  11864. if (path->fd >= 0)
  11865. result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
  11866. else if (follow_symlinks)
  11867. result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
  11868. else
  11869. result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
  11870. Py_END_ALLOW_THREADS;
  11871. if (result < 0) {
  11872. if (errno == ERANGE) {
  11873. Py_DECREF(buffer);
  11874. continue;
  11875. }
  11876. path_error(path);
  11877. Py_DECREF(buffer);
  11878. return NULL;
  11879. }
  11880. if (result != buffer_size) {
  11881. /* Can only shrink. */
  11882. _PyBytes_Resize(&buffer, result);
  11883. }
  11884. break;
  11885. }
  11886. return buffer;
  11887. }
  11888. /*[clinic input]
  11889. os.setxattr
  11890. path: path_t(allow_fd=True)
  11891. attribute: path_t
  11892. value: Py_buffer
  11893. flags: int = 0
  11894. *
  11895. follow_symlinks: bool = True
  11896. Set extended attribute attribute on path to value.
  11897. path may be either a string, a path-like object, or an open file descriptor.
  11898. If follow_symlinks is False, and the last element of the path is a symbolic
  11899. link, setxattr will modify the symbolic link itself instead of the file
  11900. the link points to.
  11901. [clinic start generated code]*/
  11902. static PyObject *
  11903. os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11904. Py_buffer *value, int flags, int follow_symlinks)
  11905. /*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
  11906. {
  11907. ssize_t result;
  11908. if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
  11909. return NULL;
  11910. if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
  11911. value->buf, value->len, flags) < 0) {
  11912. return NULL;
  11913. }
  11914. Py_BEGIN_ALLOW_THREADS;
  11915. if (path->fd > -1)
  11916. result = fsetxattr(path->fd, attribute->narrow,
  11917. value->buf, value->len, flags);
  11918. else if (follow_symlinks)
  11919. result = setxattr(path->narrow, attribute->narrow,
  11920. value->buf, value->len, flags);
  11921. else
  11922. result = lsetxattr(path->narrow, attribute->narrow,
  11923. value->buf, value->len, flags);
  11924. Py_END_ALLOW_THREADS;
  11925. if (result) {
  11926. path_error(path);
  11927. return NULL;
  11928. }
  11929. Py_RETURN_NONE;
  11930. }
  11931. /*[clinic input]
  11932. os.removexattr
  11933. path: path_t(allow_fd=True)
  11934. attribute: path_t
  11935. *
  11936. follow_symlinks: bool = True
  11937. Remove extended attribute attribute on path.
  11938. path may be either a string, a path-like object, or an open file descriptor.
  11939. If follow_symlinks is False, and the last element of the path is a symbolic
  11940. link, removexattr will modify the symbolic link itself instead of the file
  11941. the link points to.
  11942. [clinic start generated code]*/
  11943. static PyObject *
  11944. os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11945. int follow_symlinks)
  11946. /*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
  11947. {
  11948. ssize_t result;
  11949. if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
  11950. return NULL;
  11951. if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
  11952. return NULL;
  11953. }
  11954. Py_BEGIN_ALLOW_THREADS;
  11955. if (path->fd > -1)
  11956. result = fremovexattr(path->fd, attribute->narrow);
  11957. else if (follow_symlinks)
  11958. result = removexattr(path->narrow, attribute->narrow);
  11959. else
  11960. result = lremovexattr(path->narrow, attribute->narrow);
  11961. Py_END_ALLOW_THREADS;
  11962. if (result) {
  11963. return path_error(path);
  11964. }
  11965. Py_RETURN_NONE;
  11966. }
  11967. /*[clinic input]
  11968. os.listxattr
  11969. path: path_t(allow_fd=True, nullable=True) = None
  11970. *
  11971. follow_symlinks: bool = True
  11972. Return a list of extended attributes on path.
  11973. path may be either None, a string, a path-like object, or an open file descriptor.
  11974. if path is None, listxattr will examine the current directory.
  11975. If follow_symlinks is False, and the last element of the path is a symbolic
  11976. link, listxattr will examine the symbolic link itself instead of the file
  11977. the link points to.
  11978. [clinic start generated code]*/
  11979. static PyObject *
  11980. os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
  11981. /*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
  11982. {
  11983. Py_ssize_t i;
  11984. PyObject *result = NULL;
  11985. const char *name;
  11986. char *buffer = NULL;
  11987. if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
  11988. goto exit;
  11989. if (PySys_Audit("os.listxattr", "(O)",
  11990. path->object ? path->object : Py_None) < 0) {
  11991. return NULL;
  11992. }
  11993. name = path->narrow ? path->narrow : ".";
  11994. for (i = 0; ; i++) {
  11995. const char *start, *trace, *end;
  11996. ssize_t length;
  11997. static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
  11998. Py_ssize_t buffer_size = buffer_sizes[i];
  11999. if (!buffer_size) {
  12000. /* ERANGE */
  12001. path_error(path);
  12002. break;
  12003. }
  12004. buffer = PyMem_Malloc(buffer_size);
  12005. if (!buffer) {
  12006. PyErr_NoMemory();
  12007. break;
  12008. }
  12009. Py_BEGIN_ALLOW_THREADS;
  12010. if (path->fd > -1)
  12011. length = flistxattr(path->fd, buffer, buffer_size);
  12012. else if (follow_symlinks)
  12013. length = listxattr(name, buffer, buffer_size);
  12014. else
  12015. length = llistxattr(name, buffer, buffer_size);
  12016. Py_END_ALLOW_THREADS;
  12017. if (length < 0) {
  12018. if (errno == ERANGE) {
  12019. PyMem_Free(buffer);
  12020. buffer = NULL;
  12021. continue;
  12022. }
  12023. path_error(path);
  12024. break;
  12025. }
  12026. result = PyList_New(0);
  12027. if (!result) {
  12028. goto exit;
  12029. }
  12030. end = buffer + length;
  12031. for (trace = start = buffer; trace != end; trace++) {
  12032. if (!*trace) {
  12033. int error;
  12034. PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
  12035. trace - start);
  12036. if (!attribute) {
  12037. Py_SETREF(result, NULL);
  12038. goto exit;
  12039. }
  12040. error = PyList_Append(result, attribute);
  12041. Py_DECREF(attribute);
  12042. if (error) {
  12043. Py_SETREF(result, NULL);
  12044. goto exit;
  12045. }
  12046. start = trace + 1;
  12047. }
  12048. }
  12049. break;
  12050. }
  12051. exit:
  12052. if (buffer)
  12053. PyMem_Free(buffer);
  12054. return result;
  12055. }
  12056. #endif /* USE_XATTRS */
  12057. /*[clinic input]
  12058. os.urandom
  12059. size: Py_ssize_t
  12060. /
  12061. Return a bytes object containing random bytes suitable for cryptographic use.
  12062. [clinic start generated code]*/
  12063. static PyObject *
  12064. os_urandom_impl(PyObject *module, Py_ssize_t size)
  12065. /*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
  12066. {
  12067. PyObject *bytes;
  12068. int result;
  12069. if (size < 0)
  12070. return PyErr_Format(PyExc_ValueError,
  12071. "negative argument not allowed");
  12072. bytes = PyBytes_FromStringAndSize(NULL, size);
  12073. if (bytes == NULL)
  12074. return NULL;
  12075. result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
  12076. if (result == -1) {
  12077. Py_DECREF(bytes);
  12078. return NULL;
  12079. }
  12080. return bytes;
  12081. }
  12082. #ifdef HAVE_MEMFD_CREATE
  12083. /*[clinic input]
  12084. os.memfd_create
  12085. name: FSConverter
  12086. flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
  12087. [clinic start generated code]*/
  12088. static PyObject *
  12089. os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
  12090. /*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
  12091. {
  12092. int fd;
  12093. const char *bytes = PyBytes_AS_STRING(name);
  12094. Py_BEGIN_ALLOW_THREADS
  12095. fd = memfd_create(bytes, flags);
  12096. Py_END_ALLOW_THREADS
  12097. if (fd == -1) {
  12098. return PyErr_SetFromErrno(PyExc_OSError);
  12099. }
  12100. return PyLong_FromLong(fd);
  12101. }
  12102. #endif
  12103. #if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
  12104. /*[clinic input]
  12105. os.eventfd
  12106. initval: unsigned_int
  12107. flags: int(c_default="EFD_CLOEXEC") = EFD_CLOEXEC
  12108. Creates and returns an event notification file descriptor.
  12109. [clinic start generated code]*/
  12110. static PyObject *
  12111. os_eventfd_impl(PyObject *module, unsigned int initval, int flags)
  12112. /*[clinic end generated code: output=ce9c9bbd1446f2de input=66203e3c50c4028b]*/
  12113. {
  12114. /* initval is limited to uint32_t, internal counter is uint64_t */
  12115. int fd;
  12116. Py_BEGIN_ALLOW_THREADS
  12117. fd = eventfd(initval, flags);
  12118. Py_END_ALLOW_THREADS
  12119. if (fd == -1) {
  12120. return PyErr_SetFromErrno(PyExc_OSError);
  12121. }
  12122. return PyLong_FromLong(fd);
  12123. }
  12124. /*[clinic input]
  12125. os.eventfd_read
  12126. fd: fildes
  12127. Read eventfd value
  12128. [clinic start generated code]*/
  12129. static PyObject *
  12130. os_eventfd_read_impl(PyObject *module, int fd)
  12131. /*[clinic end generated code: output=8f2c7b59a3521fd1 input=110f8b57fa596afe]*/
  12132. {
  12133. eventfd_t value;
  12134. int result;
  12135. Py_BEGIN_ALLOW_THREADS
  12136. result = eventfd_read(fd, &value);
  12137. Py_END_ALLOW_THREADS
  12138. if (result == -1) {
  12139. return PyErr_SetFromErrno(PyExc_OSError);
  12140. }
  12141. return PyLong_FromUnsignedLongLong(value);
  12142. }
  12143. /*[clinic input]
  12144. os.eventfd_write
  12145. fd: fildes
  12146. value: unsigned_long_long
  12147. Write eventfd value.
  12148. [clinic start generated code]*/
  12149. static PyObject *
  12150. os_eventfd_write_impl(PyObject *module, int fd, unsigned long long value)
  12151. /*[clinic end generated code: output=bebd9040bbf987f5 input=156de8555be5a949]*/
  12152. {
  12153. int result;
  12154. Py_BEGIN_ALLOW_THREADS
  12155. result = eventfd_write(fd, value);
  12156. Py_END_ALLOW_THREADS
  12157. if (result == -1) {
  12158. return PyErr_SetFromErrno(PyExc_OSError);
  12159. }
  12160. Py_RETURN_NONE;
  12161. }
  12162. #endif /* HAVE_EVENTFD && EFD_CLOEXEC */
  12163. /* Terminal size querying */
  12164. PyDoc_STRVAR(TerminalSize_docstring,
  12165. "A tuple of (columns, lines) for holding terminal window size");
  12166. static PyStructSequence_Field TerminalSize_fields[] = {
  12167. {"columns", "width of the terminal window in characters"},
  12168. {"lines", "height of the terminal window in characters"},
  12169. {NULL, NULL}
  12170. };
  12171. static PyStructSequence_Desc TerminalSize_desc = {
  12172. "os.terminal_size",
  12173. TerminalSize_docstring,
  12174. TerminalSize_fields,
  12175. 2,
  12176. };
  12177. #if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
  12178. /*[clinic input]
  12179. os.get_terminal_size
  12180. fd: int(c_default="fileno(stdout)", py_default="<unrepresentable>") = -1
  12181. /
  12182. Return the size of the terminal window as (columns, lines).
  12183. The optional argument fd (default standard output) specifies
  12184. which file descriptor should be queried.
  12185. If the file descriptor is not connected to a terminal, an OSError
  12186. is thrown.
  12187. This function will only be defined if an implementation is
  12188. available for this system.
  12189. shutil.get_terminal_size is the high-level function which should
  12190. normally be used, os.get_terminal_size is the low-level implementation.
  12191. [clinic start generated code]*/
  12192. static PyObject *
  12193. os_get_terminal_size_impl(PyObject *module, int fd)
  12194. /*[clinic end generated code: output=fbab93acef980508 input=ead5679b82ddb920]*/
  12195. {
  12196. int columns, lines;
  12197. PyObject *termsize;
  12198. /* Under some conditions stdout may not be connected and
  12199. * fileno(stdout) may point to an invalid file descriptor. For example
  12200. * GUI apps don't have valid standard streams by default.
  12201. *
  12202. * If this happens, and the optional fd argument is not present,
  12203. * the ioctl below will fail returning EBADF. This is what we want.
  12204. */
  12205. #ifdef TERMSIZE_USE_IOCTL
  12206. {
  12207. struct winsize w;
  12208. if (ioctl(fd, TIOCGWINSZ, &w))
  12209. return PyErr_SetFromErrno(PyExc_OSError);
  12210. columns = w.ws_col;
  12211. lines = w.ws_row;
  12212. }
  12213. #endif /* TERMSIZE_USE_IOCTL */
  12214. #ifdef TERMSIZE_USE_CONIO
  12215. {
  12216. HANDLE handle;
  12217. CONSOLE_SCREEN_BUFFER_INFO csbi;
  12218. handle = _Py_get_osfhandle(fd);
  12219. if (handle == INVALID_HANDLE_VALUE)
  12220. return NULL;
  12221. if (!GetConsoleScreenBufferInfo(handle, &csbi))
  12222. return PyErr_SetFromWindowsErr(0);
  12223. columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
  12224. lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
  12225. }
  12226. #endif /* TERMSIZE_USE_CONIO */
  12227. PyObject *TerminalSizeType = get_posix_state(module)->TerminalSizeType;
  12228. termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
  12229. if (termsize == NULL)
  12230. return NULL;
  12231. int pos = 0;
  12232. #define SET_TERMSIZE(CALL) \
  12233. do { \
  12234. PyObject *item = (CALL); \
  12235. if (item == NULL) { \
  12236. Py_DECREF(termsize); \
  12237. return NULL; \
  12238. } \
  12239. PyStructSequence_SET_ITEM(termsize, pos++, item); \
  12240. } while(0)
  12241. SET_TERMSIZE(PyLong_FromLong(columns));
  12242. SET_TERMSIZE(PyLong_FromLong(lines));
  12243. #undef SET_TERMSIZE
  12244. return termsize;
  12245. }
  12246. #endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
  12247. /*[clinic input]
  12248. os.cpu_count
  12249. Return the number of CPUs in the system; return None if indeterminable.
  12250. This number is not equivalent to the number of CPUs the current process can
  12251. use. The number of usable CPUs can be obtained with
  12252. ``len(os.sched_getaffinity(0))``
  12253. [clinic start generated code]*/
  12254. static PyObject *
  12255. os_cpu_count_impl(PyObject *module)
  12256. /*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
  12257. {
  12258. int ncpu = 0;
  12259. #ifdef MS_WINDOWS
  12260. #ifdef MS_WINDOWS_DESKTOP
  12261. ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
  12262. #endif
  12263. #elif defined(__hpux)
  12264. ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
  12265. #elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
  12266. ncpu = sysconf(_SC_NPROCESSORS_ONLN);
  12267. #elif defined(__VXWORKS__)
  12268. ncpu = _Py_popcount32(vxCpuEnabledGet());
  12269. #elif defined(__DragonFly__) || \
  12270. defined(__OpenBSD__) || \
  12271. defined(__FreeBSD__) || \
  12272. defined(__NetBSD__) || \
  12273. defined(__APPLE__)
  12274. int mib[2];
  12275. size_t len = sizeof(ncpu);
  12276. mib[0] = CTL_HW;
  12277. mib[1] = HW_NCPU;
  12278. if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
  12279. ncpu = 0;
  12280. #endif
  12281. if (ncpu >= 1)
  12282. return PyLong_FromLong(ncpu);
  12283. else
  12284. Py_RETURN_NONE;
  12285. }
  12286. /*[clinic input]
  12287. os.get_inheritable -> bool
  12288. fd: int
  12289. /
  12290. Get the close-on-exe flag of the specified file descriptor.
  12291. [clinic start generated code]*/
  12292. static int
  12293. os_get_inheritable_impl(PyObject *module, int fd)
  12294. /*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
  12295. {
  12296. int return_value;
  12297. _Py_BEGIN_SUPPRESS_IPH
  12298. return_value = _Py_get_inheritable(fd);
  12299. _Py_END_SUPPRESS_IPH
  12300. return return_value;
  12301. }
  12302. /*[clinic input]
  12303. os.set_inheritable
  12304. fd: int
  12305. inheritable: int
  12306. /
  12307. Set the inheritable flag of the specified file descriptor.
  12308. [clinic start generated code]*/
  12309. static PyObject *
  12310. os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
  12311. /*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
  12312. {
  12313. int result;
  12314. _Py_BEGIN_SUPPRESS_IPH
  12315. result = _Py_set_inheritable(fd, inheritable, NULL);
  12316. _Py_END_SUPPRESS_IPH
  12317. if (result < 0)
  12318. return NULL;
  12319. Py_RETURN_NONE;
  12320. }
  12321. #ifdef MS_WINDOWS
  12322. #ifndef HANDLE_FLAG_INHERIT
  12323. #define HANDLE_FLAG_INHERIT 0x00000001
  12324. #endif
  12325. /*[clinic input]
  12326. os.get_handle_inheritable -> bool
  12327. handle: intptr_t
  12328. /
  12329. Get the close-on-exe flag of the specified file descriptor.
  12330. [clinic start generated code]*/
  12331. static int
  12332. os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
  12333. /*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
  12334. {
  12335. DWORD flags;
  12336. if (!GetHandleInformation((HANDLE)handle, &flags)) {
  12337. PyErr_SetFromWindowsErr(0);
  12338. return -1;
  12339. }
  12340. return flags & HANDLE_FLAG_INHERIT;
  12341. }
  12342. /*[clinic input]
  12343. os.set_handle_inheritable
  12344. handle: intptr_t
  12345. inheritable: bool
  12346. /
  12347. Set the inheritable flag of the specified handle.
  12348. [clinic start generated code]*/
  12349. static PyObject *
  12350. os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
  12351. int inheritable)
  12352. /*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
  12353. {
  12354. DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
  12355. if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
  12356. PyErr_SetFromWindowsErr(0);
  12357. return NULL;
  12358. }
  12359. Py_RETURN_NONE;
  12360. }
  12361. #endif /* MS_WINDOWS */
  12362. /*[clinic input]
  12363. os.get_blocking -> bool
  12364. fd: int
  12365. /
  12366. Get the blocking mode of the file descriptor.
  12367. Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
  12368. [clinic start generated code]*/
  12369. static int
  12370. os_get_blocking_impl(PyObject *module, int fd)
  12371. /*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
  12372. {
  12373. int blocking;
  12374. _Py_BEGIN_SUPPRESS_IPH
  12375. blocking = _Py_get_blocking(fd);
  12376. _Py_END_SUPPRESS_IPH
  12377. return blocking;
  12378. }
  12379. /*[clinic input]
  12380. os.set_blocking
  12381. fd: int
  12382. blocking: bool
  12383. /
  12384. Set the blocking mode of the specified file descriptor.
  12385. Set the O_NONBLOCK flag if blocking is False,
  12386. clear the O_NONBLOCK flag otherwise.
  12387. [clinic start generated code]*/
  12388. static PyObject *
  12389. os_set_blocking_impl(PyObject *module, int fd, int blocking)
  12390. /*[clinic end generated code: output=384eb43aa0762a9d input=7e9dfc9b14804dd4]*/
  12391. {
  12392. int result;
  12393. _Py_BEGIN_SUPPRESS_IPH
  12394. result = _Py_set_blocking(fd, blocking);
  12395. _Py_END_SUPPRESS_IPH
  12396. if (result < 0)
  12397. return NULL;
  12398. Py_RETURN_NONE;
  12399. }
  12400. /*[clinic input]
  12401. class os.DirEntry "DirEntry *" "DirEntryType"
  12402. [clinic start generated code]*/
  12403. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
  12404. typedef struct {
  12405. PyObject_HEAD
  12406. PyObject *name;
  12407. PyObject *path;
  12408. PyObject *stat;
  12409. PyObject *lstat;
  12410. #ifdef MS_WINDOWS
  12411. struct _Py_stat_struct win32_lstat;
  12412. uint64_t win32_file_index;
  12413. uint64_t win32_file_index_high;
  12414. int got_file_index;
  12415. #else /* POSIX */
  12416. #ifdef HAVE_DIRENT_D_TYPE
  12417. unsigned char d_type;
  12418. #endif
  12419. ino_t d_ino;
  12420. int dir_fd;
  12421. #endif
  12422. } DirEntry;
  12423. static void
  12424. DirEntry_dealloc(DirEntry *entry)
  12425. {
  12426. PyTypeObject *tp = Py_TYPE(entry);
  12427. Py_XDECREF(entry->name);
  12428. Py_XDECREF(entry->path);
  12429. Py_XDECREF(entry->stat);
  12430. Py_XDECREF(entry->lstat);
  12431. freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
  12432. free_func(entry);
  12433. Py_DECREF(tp);
  12434. }
  12435. /* Forward reference */
  12436. static int
  12437. DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
  12438. int follow_symlinks, unsigned short mode_bits);
  12439. /*[clinic input]
  12440. os.DirEntry.is_symlink -> bool
  12441. defining_class: defining_class
  12442. /
  12443. Return True if the entry is a symbolic link; cached per entry.
  12444. [clinic start generated code]*/
  12445. static int
  12446. os_DirEntry_is_symlink_impl(DirEntry *self, PyTypeObject *defining_class)
  12447. /*[clinic end generated code: output=293096d589b6d47c input=e9acc5ee4d511113]*/
  12448. {
  12449. #ifdef MS_WINDOWS
  12450. return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
  12451. #elif defined(HAVE_DIRENT_D_TYPE)
  12452. /* POSIX */
  12453. if (self->d_type != DT_UNKNOWN)
  12454. return self->d_type == DT_LNK;
  12455. else
  12456. return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
  12457. #else
  12458. /* POSIX without d_type */
  12459. return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
  12460. #endif
  12461. }
  12462. /*[clinic input]
  12463. os.DirEntry.is_junction -> bool
  12464. defining_class: defining_class
  12465. /
  12466. Return True if the entry is a junction; cached per entry.
  12467. [clinic start generated code]*/
  12468. static int
  12469. os_DirEntry_is_junction_impl(DirEntry *self, PyTypeObject *defining_class)
  12470. /*[clinic end generated code: output=7061a07b0ef2cd1f input=475cd36fb7d4723f]*/
  12471. {
  12472. #ifdef MS_WINDOWS
  12473. return self->win32_lstat.st_reparse_tag == IO_REPARSE_TAG_MOUNT_POINT;
  12474. #else
  12475. return 0;
  12476. #endif
  12477. }
  12478. static PyObject *
  12479. DirEntry_fetch_stat(PyObject *module, DirEntry *self, int follow_symlinks)
  12480. {
  12481. int result;
  12482. STRUCT_STAT st;
  12483. PyObject *ub;
  12484. #ifdef MS_WINDOWS
  12485. if (!PyUnicode_FSDecoder(self->path, &ub))
  12486. return NULL;
  12487. wchar_t *path = PyUnicode_AsWideCharString(ub, NULL);
  12488. Py_DECREF(ub);
  12489. #else /* POSIX */
  12490. if (!PyUnicode_FSConverter(self->path, &ub))
  12491. return NULL;
  12492. const char *path = PyBytes_AS_STRING(ub);
  12493. if (self->dir_fd != DEFAULT_DIR_FD) {
  12494. #ifdef HAVE_FSTATAT
  12495. if (HAVE_FSTATAT_RUNTIME) {
  12496. Py_BEGIN_ALLOW_THREADS
  12497. result = fstatat(self->dir_fd, path, &st,
  12498. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  12499. Py_END_ALLOW_THREADS
  12500. } else
  12501. #endif /* HAVE_FSTATAT */
  12502. {
  12503. Py_DECREF(ub);
  12504. PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
  12505. return NULL;
  12506. }
  12507. }
  12508. else
  12509. #endif
  12510. {
  12511. Py_BEGIN_ALLOW_THREADS
  12512. if (follow_symlinks) {
  12513. result = STAT(path, &st);
  12514. }
  12515. else {
  12516. result = LSTAT(path, &st);
  12517. }
  12518. Py_END_ALLOW_THREADS
  12519. }
  12520. int saved_errno = errno;
  12521. #if defined(MS_WINDOWS)
  12522. PyMem_Free(path);
  12523. #else
  12524. Py_DECREF(ub);
  12525. #endif
  12526. if (result != 0) {
  12527. errno = saved_errno;
  12528. path_object_error(self->path);
  12529. return NULL;
  12530. }
  12531. return _pystat_fromstructstat(module, &st);
  12532. }
  12533. static PyObject *
  12534. DirEntry_get_lstat(PyTypeObject *defining_class, DirEntry *self)
  12535. {
  12536. if (!self->lstat) {
  12537. PyObject *module = PyType_GetModule(defining_class);
  12538. #ifdef MS_WINDOWS
  12539. self->lstat = _pystat_fromstructstat(module, &self->win32_lstat);
  12540. #else /* POSIX */
  12541. self->lstat = DirEntry_fetch_stat(module, self, 0);
  12542. #endif
  12543. }
  12544. return Py_XNewRef(self->lstat);
  12545. }
  12546. /*[clinic input]
  12547. os.DirEntry.stat
  12548. defining_class: defining_class
  12549. /
  12550. *
  12551. follow_symlinks: bool = True
  12552. Return stat_result object for the entry; cached per entry.
  12553. [clinic start generated code]*/
  12554. static PyObject *
  12555. os_DirEntry_stat_impl(DirEntry *self, PyTypeObject *defining_class,
  12556. int follow_symlinks)
  12557. /*[clinic end generated code: output=23f803e19c3e780e input=e816273c4e67ee98]*/
  12558. {
  12559. if (!follow_symlinks) {
  12560. return DirEntry_get_lstat(defining_class, self);
  12561. }
  12562. if (!self->stat) {
  12563. int result = os_DirEntry_is_symlink_impl(self, defining_class);
  12564. if (result == -1) {
  12565. return NULL;
  12566. }
  12567. if (result) {
  12568. PyObject *module = PyType_GetModule(defining_class);
  12569. self->stat = DirEntry_fetch_stat(module, self, 1);
  12570. }
  12571. else {
  12572. self->stat = DirEntry_get_lstat(defining_class, self);
  12573. }
  12574. }
  12575. return Py_XNewRef(self->stat);
  12576. }
  12577. /* Set exception and return -1 on error, 0 for False, 1 for True */
  12578. static int
  12579. DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
  12580. int follow_symlinks, unsigned short mode_bits)
  12581. {
  12582. PyObject *stat = NULL;
  12583. PyObject *st_mode = NULL;
  12584. long mode;
  12585. int result;
  12586. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12587. int is_symlink;
  12588. int need_stat;
  12589. #endif
  12590. #ifdef MS_WINDOWS
  12591. unsigned long dir_bits;
  12592. #endif
  12593. #ifdef MS_WINDOWS
  12594. is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
  12595. need_stat = follow_symlinks && is_symlink;
  12596. #elif defined(HAVE_DIRENT_D_TYPE)
  12597. is_symlink = self->d_type == DT_LNK;
  12598. need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
  12599. #endif
  12600. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12601. if (need_stat) {
  12602. #endif
  12603. stat = os_DirEntry_stat_impl(self, defining_class, follow_symlinks);
  12604. if (!stat) {
  12605. if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
  12606. /* If file doesn't exist (anymore), then return False
  12607. (i.e., say it's not a file/directory) */
  12608. PyErr_Clear();
  12609. return 0;
  12610. }
  12611. goto error;
  12612. }
  12613. _posixstate* state = get_posix_state(PyType_GetModule(defining_class));
  12614. st_mode = PyObject_GetAttr(stat, state->st_mode);
  12615. if (!st_mode)
  12616. goto error;
  12617. mode = PyLong_AsLong(st_mode);
  12618. if (mode == -1 && PyErr_Occurred())
  12619. goto error;
  12620. Py_CLEAR(st_mode);
  12621. Py_CLEAR(stat);
  12622. result = (mode & S_IFMT) == mode_bits;
  12623. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12624. }
  12625. else if (is_symlink) {
  12626. assert(mode_bits != S_IFLNK);
  12627. result = 0;
  12628. }
  12629. else {
  12630. assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
  12631. #ifdef MS_WINDOWS
  12632. dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
  12633. if (mode_bits == S_IFDIR)
  12634. result = dir_bits != 0;
  12635. else
  12636. result = dir_bits == 0;
  12637. #else /* POSIX */
  12638. if (mode_bits == S_IFDIR)
  12639. result = self->d_type == DT_DIR;
  12640. else
  12641. result = self->d_type == DT_REG;
  12642. #endif
  12643. }
  12644. #endif
  12645. return result;
  12646. error:
  12647. Py_XDECREF(st_mode);
  12648. Py_XDECREF(stat);
  12649. return -1;
  12650. }
  12651. /*[clinic input]
  12652. os.DirEntry.is_dir -> bool
  12653. defining_class: defining_class
  12654. /
  12655. *
  12656. follow_symlinks: bool = True
  12657. Return True if the entry is a directory; cached per entry.
  12658. [clinic start generated code]*/
  12659. static int
  12660. os_DirEntry_is_dir_impl(DirEntry *self, PyTypeObject *defining_class,
  12661. int follow_symlinks)
  12662. /*[clinic end generated code: output=0cd453b9c0987fdf input=1a4ffd6dec9920cb]*/
  12663. {
  12664. return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFDIR);
  12665. }
  12666. /*[clinic input]
  12667. os.DirEntry.is_file -> bool
  12668. defining_class: defining_class
  12669. /
  12670. *
  12671. follow_symlinks: bool = True
  12672. Return True if the entry is a file; cached per entry.
  12673. [clinic start generated code]*/
  12674. static int
  12675. os_DirEntry_is_file_impl(DirEntry *self, PyTypeObject *defining_class,
  12676. int follow_symlinks)
  12677. /*[clinic end generated code: output=f7c277ab5ba80908 input=0a64c5a12e802e3b]*/
  12678. {
  12679. return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFREG);
  12680. }
  12681. /*[clinic input]
  12682. os.DirEntry.inode
  12683. Return inode of the entry; cached per entry.
  12684. [clinic start generated code]*/
  12685. static PyObject *
  12686. os_DirEntry_inode_impl(DirEntry *self)
  12687. /*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
  12688. {
  12689. #ifdef MS_WINDOWS
  12690. if (!self->got_file_index) {
  12691. PyObject *unicode;
  12692. STRUCT_STAT stat;
  12693. int result;
  12694. if (!PyUnicode_FSDecoder(self->path, &unicode))
  12695. return NULL;
  12696. wchar_t *path = PyUnicode_AsWideCharString(unicode, NULL);
  12697. Py_DECREF(unicode);
  12698. result = LSTAT(path, &stat);
  12699. int saved_errno = errno;
  12700. PyMem_Free(path);
  12701. if (result != 0) {
  12702. errno = saved_errno;
  12703. return path_object_error(self->path);
  12704. }
  12705. self->win32_file_index = stat.st_ino;
  12706. self->win32_file_index_high = stat.st_ino_high;
  12707. self->got_file_index = 1;
  12708. }
  12709. return _pystat_l128_from_l64_l64(self->win32_file_index, self->win32_file_index_high);
  12710. #else /* POSIX */
  12711. static_assert(sizeof(unsigned long long) >= sizeof(self->d_ino),
  12712. "DirEntry.d_ino is larger than unsigned long long");
  12713. return PyLong_FromUnsignedLongLong(self->d_ino);
  12714. #endif
  12715. }
  12716. static PyObject *
  12717. DirEntry_repr(DirEntry *self)
  12718. {
  12719. return PyUnicode_FromFormat("<DirEntry %R>", self->name);
  12720. }
  12721. /*[clinic input]
  12722. os.DirEntry.__fspath__
  12723. Returns the path for the entry.
  12724. [clinic start generated code]*/
  12725. static PyObject *
  12726. os_DirEntry___fspath___impl(DirEntry *self)
  12727. /*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
  12728. {
  12729. return Py_NewRef(self->path);
  12730. }
  12731. static PyMemberDef DirEntry_members[] = {
  12732. {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
  12733. "the entry's base filename, relative to scandir() \"path\" argument"},
  12734. {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
  12735. "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
  12736. {NULL}
  12737. };
  12738. #include "clinic/posixmodule.c.h"
  12739. static PyMethodDef DirEntry_methods[] = {
  12740. OS_DIRENTRY_IS_DIR_METHODDEF
  12741. OS_DIRENTRY_IS_FILE_METHODDEF
  12742. OS_DIRENTRY_IS_SYMLINK_METHODDEF
  12743. OS_DIRENTRY_IS_JUNCTION_METHODDEF
  12744. OS_DIRENTRY_STAT_METHODDEF
  12745. OS_DIRENTRY_INODE_METHODDEF
  12746. OS_DIRENTRY___FSPATH___METHODDEF
  12747. {"__class_getitem__", Py_GenericAlias,
  12748. METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  12749. {NULL}
  12750. };
  12751. static PyType_Slot DirEntryType_slots[] = {
  12752. {Py_tp_dealloc, DirEntry_dealloc},
  12753. {Py_tp_repr, DirEntry_repr},
  12754. {Py_tp_methods, DirEntry_methods},
  12755. {Py_tp_members, DirEntry_members},
  12756. {0, 0},
  12757. };
  12758. static PyType_Spec DirEntryType_spec = {
  12759. MODNAME ".DirEntry",
  12760. sizeof(DirEntry),
  12761. 0,
  12762. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
  12763. DirEntryType_slots
  12764. };
  12765. #ifdef MS_WINDOWS
  12766. static wchar_t *
  12767. join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
  12768. {
  12769. Py_ssize_t path_len;
  12770. Py_ssize_t size;
  12771. wchar_t *result;
  12772. wchar_t ch;
  12773. if (!path_wide) { /* Default arg: "." */
  12774. path_wide = L".";
  12775. path_len = 1;
  12776. }
  12777. else {
  12778. path_len = wcslen(path_wide);
  12779. }
  12780. /* The +1's are for the path separator and the NUL */
  12781. size = path_len + 1 + wcslen(filename) + 1;
  12782. result = PyMem_New(wchar_t, size);
  12783. if (!result) {
  12784. PyErr_NoMemory();
  12785. return NULL;
  12786. }
  12787. wcscpy(result, path_wide);
  12788. if (path_len > 0) {
  12789. ch = result[path_len - 1];
  12790. if (ch != SEP && ch != ALTSEP && ch != L':')
  12791. result[path_len++] = SEP;
  12792. wcscpy(result + path_len, filename);
  12793. }
  12794. return result;
  12795. }
  12796. static PyObject *
  12797. DirEntry_from_find_data(PyObject *module, path_t *path, WIN32_FIND_DATAW *dataW)
  12798. {
  12799. DirEntry *entry;
  12800. BY_HANDLE_FILE_INFORMATION file_info;
  12801. ULONG reparse_tag;
  12802. wchar_t *joined_path;
  12803. PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
  12804. entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
  12805. if (!entry)
  12806. return NULL;
  12807. entry->name = NULL;
  12808. entry->path = NULL;
  12809. entry->stat = NULL;
  12810. entry->lstat = NULL;
  12811. entry->got_file_index = 0;
  12812. entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
  12813. if (!entry->name)
  12814. goto error;
  12815. if (path->narrow) {
  12816. Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
  12817. if (!entry->name)
  12818. goto error;
  12819. }
  12820. joined_path = join_path_filenameW(path->wide, dataW->cFileName);
  12821. if (!joined_path)
  12822. goto error;
  12823. entry->path = PyUnicode_FromWideChar(joined_path, -1);
  12824. PyMem_Free(joined_path);
  12825. if (!entry->path)
  12826. goto error;
  12827. if (path->narrow) {
  12828. Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
  12829. if (!entry->path)
  12830. goto error;
  12831. }
  12832. find_data_to_file_info(dataW, &file_info, &reparse_tag);
  12833. _Py_attribute_data_to_stat(&file_info, reparse_tag, NULL, NULL, &entry->win32_lstat);
  12834. /* ctime is only deprecated from 3.12, so we copy birthtime across */
  12835. entry->win32_lstat.st_ctime = entry->win32_lstat.st_birthtime;
  12836. entry->win32_lstat.st_ctime_nsec = entry->win32_lstat.st_birthtime_nsec;
  12837. return (PyObject *)entry;
  12838. error:
  12839. Py_DECREF(entry);
  12840. return NULL;
  12841. }
  12842. #else /* POSIX */
  12843. static char *
  12844. join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
  12845. {
  12846. Py_ssize_t path_len;
  12847. Py_ssize_t size;
  12848. char *result;
  12849. if (!path_narrow) { /* Default arg: "." */
  12850. path_narrow = ".";
  12851. path_len = 1;
  12852. }
  12853. else {
  12854. path_len = strlen(path_narrow);
  12855. }
  12856. if (filename_len == -1)
  12857. filename_len = strlen(filename);
  12858. /* The +1's are for the path separator and the NUL */
  12859. size = path_len + 1 + filename_len + 1;
  12860. result = PyMem_New(char, size);
  12861. if (!result) {
  12862. PyErr_NoMemory();
  12863. return NULL;
  12864. }
  12865. strcpy(result, path_narrow);
  12866. if (path_len > 0 && result[path_len - 1] != '/')
  12867. result[path_len++] = '/';
  12868. strcpy(result + path_len, filename);
  12869. return result;
  12870. }
  12871. static PyObject *
  12872. DirEntry_from_posix_info(PyObject *module, path_t *path, const char *name,
  12873. Py_ssize_t name_len, ino_t d_ino
  12874. #ifdef HAVE_DIRENT_D_TYPE
  12875. , unsigned char d_type
  12876. #endif
  12877. )
  12878. {
  12879. DirEntry *entry;
  12880. char *joined_path;
  12881. PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
  12882. entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
  12883. if (!entry)
  12884. return NULL;
  12885. entry->name = NULL;
  12886. entry->path = NULL;
  12887. entry->stat = NULL;
  12888. entry->lstat = NULL;
  12889. if (path->fd != -1) {
  12890. entry->dir_fd = path->fd;
  12891. joined_path = NULL;
  12892. }
  12893. else {
  12894. entry->dir_fd = DEFAULT_DIR_FD;
  12895. joined_path = join_path_filename(path->narrow, name, name_len);
  12896. if (!joined_path)
  12897. goto error;
  12898. }
  12899. if (!path->narrow || !PyBytes_Check(path->object)) {
  12900. entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
  12901. if (joined_path)
  12902. entry->path = PyUnicode_DecodeFSDefault(joined_path);
  12903. }
  12904. else {
  12905. entry->name = PyBytes_FromStringAndSize(name, name_len);
  12906. if (joined_path)
  12907. entry->path = PyBytes_FromString(joined_path);
  12908. }
  12909. PyMem_Free(joined_path);
  12910. if (!entry->name)
  12911. goto error;
  12912. if (path->fd != -1) {
  12913. entry->path = Py_NewRef(entry->name);
  12914. }
  12915. else if (!entry->path)
  12916. goto error;
  12917. #ifdef HAVE_DIRENT_D_TYPE
  12918. entry->d_type = d_type;
  12919. #endif
  12920. entry->d_ino = d_ino;
  12921. return (PyObject *)entry;
  12922. error:
  12923. Py_XDECREF(entry);
  12924. return NULL;
  12925. }
  12926. #endif
  12927. typedef struct {
  12928. PyObject_HEAD
  12929. path_t path;
  12930. #ifdef MS_WINDOWS
  12931. HANDLE handle;
  12932. WIN32_FIND_DATAW file_data;
  12933. int first_time;
  12934. #else /* POSIX */
  12935. DIR *dirp;
  12936. #endif
  12937. #ifdef HAVE_FDOPENDIR
  12938. int fd;
  12939. #endif
  12940. } ScandirIterator;
  12941. #ifdef MS_WINDOWS
  12942. static int
  12943. ScandirIterator_is_closed(ScandirIterator *iterator)
  12944. {
  12945. return iterator->handle == INVALID_HANDLE_VALUE;
  12946. }
  12947. static void
  12948. ScandirIterator_closedir(ScandirIterator *iterator)
  12949. {
  12950. HANDLE handle = iterator->handle;
  12951. if (handle == INVALID_HANDLE_VALUE)
  12952. return;
  12953. iterator->handle = INVALID_HANDLE_VALUE;
  12954. Py_BEGIN_ALLOW_THREADS
  12955. FindClose(handle);
  12956. Py_END_ALLOW_THREADS
  12957. }
  12958. static PyObject *
  12959. ScandirIterator_iternext(ScandirIterator *iterator)
  12960. {
  12961. WIN32_FIND_DATAW *file_data = &iterator->file_data;
  12962. BOOL success;
  12963. PyObject *entry;
  12964. /* Happens if the iterator is iterated twice, or closed explicitly */
  12965. if (iterator->handle == INVALID_HANDLE_VALUE)
  12966. return NULL;
  12967. while (1) {
  12968. if (!iterator->first_time) {
  12969. Py_BEGIN_ALLOW_THREADS
  12970. success = FindNextFileW(iterator->handle, file_data);
  12971. Py_END_ALLOW_THREADS
  12972. if (!success) {
  12973. /* Error or no more files */
  12974. if (GetLastError() != ERROR_NO_MORE_FILES)
  12975. path_error(&iterator->path);
  12976. break;
  12977. }
  12978. }
  12979. iterator->first_time = 0;
  12980. /* Skip over . and .. */
  12981. if (wcscmp(file_data->cFileName, L".") != 0 &&
  12982. wcscmp(file_data->cFileName, L"..") != 0)
  12983. {
  12984. PyObject *module = PyType_GetModule(Py_TYPE(iterator));
  12985. entry = DirEntry_from_find_data(module, &iterator->path, file_data);
  12986. if (!entry)
  12987. break;
  12988. return entry;
  12989. }
  12990. /* Loop till we get a non-dot directory or finish iterating */
  12991. }
  12992. /* Error or no more files */
  12993. ScandirIterator_closedir(iterator);
  12994. return NULL;
  12995. }
  12996. #else /* POSIX */
  12997. static int
  12998. ScandirIterator_is_closed(ScandirIterator *iterator)
  12999. {
  13000. return !iterator->dirp;
  13001. }
  13002. static void
  13003. ScandirIterator_closedir(ScandirIterator *iterator)
  13004. {
  13005. DIR *dirp = iterator->dirp;
  13006. if (!dirp)
  13007. return;
  13008. iterator->dirp = NULL;
  13009. Py_BEGIN_ALLOW_THREADS
  13010. #ifdef HAVE_FDOPENDIR
  13011. if (iterator->path.fd != -1)
  13012. rewinddir(dirp);
  13013. #endif
  13014. closedir(dirp);
  13015. Py_END_ALLOW_THREADS
  13016. return;
  13017. }
  13018. static PyObject *
  13019. ScandirIterator_iternext(ScandirIterator *iterator)
  13020. {
  13021. struct dirent *direntp;
  13022. Py_ssize_t name_len;
  13023. int is_dot;
  13024. PyObject *entry;
  13025. /* Happens if the iterator is iterated twice, or closed explicitly */
  13026. if (!iterator->dirp)
  13027. return NULL;
  13028. while (1) {
  13029. errno = 0;
  13030. Py_BEGIN_ALLOW_THREADS
  13031. direntp = readdir(iterator->dirp);
  13032. Py_END_ALLOW_THREADS
  13033. if (!direntp) {
  13034. /* Error or no more files */
  13035. if (errno != 0)
  13036. path_error(&iterator->path);
  13037. break;
  13038. }
  13039. /* Skip over . and .. */
  13040. name_len = NAMLEN(direntp);
  13041. is_dot = direntp->d_name[0] == '.' &&
  13042. (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
  13043. if (!is_dot) {
  13044. PyObject *module = PyType_GetModule(Py_TYPE(iterator));
  13045. entry = DirEntry_from_posix_info(module,
  13046. &iterator->path, direntp->d_name,
  13047. name_len, direntp->d_ino
  13048. #ifdef HAVE_DIRENT_D_TYPE
  13049. , direntp->d_type
  13050. #endif
  13051. );
  13052. if (!entry)
  13053. break;
  13054. return entry;
  13055. }
  13056. /* Loop till we get a non-dot directory or finish iterating */
  13057. }
  13058. /* Error or no more files */
  13059. ScandirIterator_closedir(iterator);
  13060. return NULL;
  13061. }
  13062. #endif
  13063. static PyObject *
  13064. ScandirIterator_close(ScandirIterator *self, PyObject *args)
  13065. {
  13066. ScandirIterator_closedir(self);
  13067. Py_RETURN_NONE;
  13068. }
  13069. static PyObject *
  13070. ScandirIterator_enter(PyObject *self, PyObject *args)
  13071. {
  13072. return Py_NewRef(self);
  13073. }
  13074. static PyObject *
  13075. ScandirIterator_exit(ScandirIterator *self, PyObject *args)
  13076. {
  13077. ScandirIterator_closedir(self);
  13078. Py_RETURN_NONE;
  13079. }
  13080. static void
  13081. ScandirIterator_finalize(ScandirIterator *iterator)
  13082. {
  13083. /* Save the current exception, if any. */
  13084. PyObject *exc = PyErr_GetRaisedException();
  13085. if (!ScandirIterator_is_closed(iterator)) {
  13086. ScandirIterator_closedir(iterator);
  13087. if (PyErr_ResourceWarning((PyObject *)iterator, 1,
  13088. "unclosed scandir iterator %R", iterator)) {
  13089. /* Spurious errors can appear at shutdown */
  13090. if (PyErr_ExceptionMatches(PyExc_Warning)) {
  13091. PyErr_WriteUnraisable((PyObject *) iterator);
  13092. }
  13093. }
  13094. }
  13095. path_cleanup(&iterator->path);
  13096. /* Restore the saved exception. */
  13097. PyErr_SetRaisedException(exc);
  13098. }
  13099. static void
  13100. ScandirIterator_dealloc(ScandirIterator *iterator)
  13101. {
  13102. PyTypeObject *tp = Py_TYPE(iterator);
  13103. if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
  13104. return;
  13105. freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
  13106. free_func(iterator);
  13107. Py_DECREF(tp);
  13108. }
  13109. static PyMethodDef ScandirIterator_methods[] = {
  13110. {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
  13111. {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
  13112. {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
  13113. {NULL}
  13114. };
  13115. static PyType_Slot ScandirIteratorType_slots[] = {
  13116. {Py_tp_dealloc, ScandirIterator_dealloc},
  13117. {Py_tp_finalize, ScandirIterator_finalize},
  13118. {Py_tp_iter, PyObject_SelfIter},
  13119. {Py_tp_iternext, ScandirIterator_iternext},
  13120. {Py_tp_methods, ScandirIterator_methods},
  13121. {0, 0},
  13122. };
  13123. static PyType_Spec ScandirIteratorType_spec = {
  13124. MODNAME ".ScandirIterator",
  13125. sizeof(ScandirIterator),
  13126. 0,
  13127. // bpo-40549: Py_TPFLAGS_BASETYPE should not be used, since
  13128. // PyType_GetModule(Py_TYPE(self)) doesn't work on a subclass instance.
  13129. (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE
  13130. | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  13131. ScandirIteratorType_slots
  13132. };
  13133. /*[clinic input]
  13134. os.scandir
  13135. path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
  13136. Return an iterator of DirEntry objects for given path.
  13137. path can be specified as either str, bytes, or a path-like object. If path
  13138. is bytes, the names of yielded DirEntry objects will also be bytes; in
  13139. all other circumstances they will be str.
  13140. If path is None, uses the path='.'.
  13141. [clinic start generated code]*/
  13142. static PyObject *
  13143. os_scandir_impl(PyObject *module, path_t *path)
  13144. /*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
  13145. {
  13146. ScandirIterator *iterator;
  13147. #ifdef MS_WINDOWS
  13148. wchar_t *path_strW;
  13149. #else
  13150. const char *path_str;
  13151. #ifdef HAVE_FDOPENDIR
  13152. int fd = -1;
  13153. #endif
  13154. #endif
  13155. if (PySys_Audit("os.scandir", "O",
  13156. path->object ? path->object : Py_None) < 0) {
  13157. return NULL;
  13158. }
  13159. PyObject *ScandirIteratorType = get_posix_state(module)->ScandirIteratorType;
  13160. iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
  13161. if (!iterator)
  13162. return NULL;
  13163. #ifdef MS_WINDOWS
  13164. iterator->handle = INVALID_HANDLE_VALUE;
  13165. #else
  13166. iterator->dirp = NULL;
  13167. #endif
  13168. /* Move the ownership to iterator->path */
  13169. memcpy(&iterator->path, path, sizeof(path_t));
  13170. memset(path, 0, sizeof(path_t));
  13171. #ifdef MS_WINDOWS
  13172. iterator->first_time = 1;
  13173. path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
  13174. if (!path_strW)
  13175. goto error;
  13176. Py_BEGIN_ALLOW_THREADS
  13177. iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
  13178. Py_END_ALLOW_THREADS
  13179. if (iterator->handle == INVALID_HANDLE_VALUE) {
  13180. path_error(&iterator->path);
  13181. PyMem_Free(path_strW);
  13182. goto error;
  13183. }
  13184. PyMem_Free(path_strW);
  13185. #else /* POSIX */
  13186. errno = 0;
  13187. #ifdef HAVE_FDOPENDIR
  13188. if (iterator->path.fd != -1) {
  13189. if (HAVE_FDOPENDIR_RUNTIME) {
  13190. /* closedir() closes the FD, so we duplicate it */
  13191. fd = _Py_dup(iterator->path.fd);
  13192. if (fd == -1)
  13193. goto error;
  13194. Py_BEGIN_ALLOW_THREADS
  13195. iterator->dirp = fdopendir(fd);
  13196. Py_END_ALLOW_THREADS
  13197. } else {
  13198. PyErr_SetString(PyExc_TypeError,
  13199. "scandir: path should be string, bytes, os.PathLike or None, not int");
  13200. return NULL;
  13201. }
  13202. }
  13203. else
  13204. #endif
  13205. {
  13206. if (iterator->path.narrow)
  13207. path_str = iterator->path.narrow;
  13208. else
  13209. path_str = ".";
  13210. Py_BEGIN_ALLOW_THREADS
  13211. iterator->dirp = opendir(path_str);
  13212. Py_END_ALLOW_THREADS
  13213. }
  13214. if (!iterator->dirp) {
  13215. path_error(&iterator->path);
  13216. #ifdef HAVE_FDOPENDIR
  13217. if (fd != -1) {
  13218. Py_BEGIN_ALLOW_THREADS
  13219. close(fd);
  13220. Py_END_ALLOW_THREADS
  13221. }
  13222. #endif
  13223. goto error;
  13224. }
  13225. #endif
  13226. return (PyObject *)iterator;
  13227. error:
  13228. Py_DECREF(iterator);
  13229. return NULL;
  13230. }
  13231. /*
  13232. Return the file system path representation of the object.
  13233. If the object is str or bytes, then allow it to pass through with
  13234. an incremented refcount. If the object defines __fspath__(), then
  13235. return the result of that method. All other types raise a TypeError.
  13236. */
  13237. PyObject *
  13238. PyOS_FSPath(PyObject *path)
  13239. {
  13240. /* For error message reasons, this function is manually inlined in
  13241. path_converter(). */
  13242. PyObject *func = NULL;
  13243. PyObject *path_repr = NULL;
  13244. if (PyUnicode_Check(path) || PyBytes_Check(path)) {
  13245. return Py_NewRef(path);
  13246. }
  13247. func = _PyObject_LookupSpecial(path, &_Py_ID(__fspath__));
  13248. if (NULL == func) {
  13249. return PyErr_Format(PyExc_TypeError,
  13250. "expected str, bytes or os.PathLike object, "
  13251. "not %.200s",
  13252. _PyType_Name(Py_TYPE(path)));
  13253. }
  13254. path_repr = _PyObject_CallNoArgs(func);
  13255. Py_DECREF(func);
  13256. if (NULL == path_repr) {
  13257. return NULL;
  13258. }
  13259. if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
  13260. PyErr_Format(PyExc_TypeError,
  13261. "expected %.200s.__fspath__() to return str or bytes, "
  13262. "not %.200s", _PyType_Name(Py_TYPE(path)),
  13263. _PyType_Name(Py_TYPE(path_repr)));
  13264. Py_DECREF(path_repr);
  13265. return NULL;
  13266. }
  13267. return path_repr;
  13268. }
  13269. /*[clinic input]
  13270. os.fspath
  13271. path: object
  13272. Return the file system path representation of the object.
  13273. If the object is str or bytes, then allow it to pass through as-is. If the
  13274. object defines __fspath__(), then return the result of that method. All other
  13275. types raise a TypeError.
  13276. [clinic start generated code]*/
  13277. static PyObject *
  13278. os_fspath_impl(PyObject *module, PyObject *path)
  13279. /*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
  13280. {
  13281. return PyOS_FSPath(path);
  13282. }
  13283. #ifdef HAVE_GETRANDOM_SYSCALL
  13284. /*[clinic input]
  13285. os.getrandom
  13286. size: Py_ssize_t
  13287. flags: int=0
  13288. Obtain a series of random bytes.
  13289. [clinic start generated code]*/
  13290. static PyObject *
  13291. os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
  13292. /*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
  13293. {
  13294. PyObject *bytes;
  13295. Py_ssize_t n;
  13296. if (size < 0) {
  13297. errno = EINVAL;
  13298. return posix_error();
  13299. }
  13300. bytes = PyBytes_FromStringAndSize(NULL, size);
  13301. if (bytes == NULL) {
  13302. PyErr_NoMemory();
  13303. return NULL;
  13304. }
  13305. while (1) {
  13306. n = syscall(SYS_getrandom,
  13307. PyBytes_AS_STRING(bytes),
  13308. PyBytes_GET_SIZE(bytes),
  13309. flags);
  13310. if (n < 0 && errno == EINTR) {
  13311. if (PyErr_CheckSignals() < 0) {
  13312. goto error;
  13313. }
  13314. /* getrandom() was interrupted by a signal: retry */
  13315. continue;
  13316. }
  13317. break;
  13318. }
  13319. if (n < 0) {
  13320. PyErr_SetFromErrno(PyExc_OSError);
  13321. goto error;
  13322. }
  13323. if (n != size) {
  13324. _PyBytes_Resize(&bytes, n);
  13325. }
  13326. return bytes;
  13327. error:
  13328. Py_DECREF(bytes);
  13329. return NULL;
  13330. }
  13331. #endif /* HAVE_GETRANDOM_SYSCALL */
  13332. #if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
  13333. /* bpo-36085: Helper functions for managing DLL search directories
  13334. * on win32
  13335. */
  13336. /*[clinic input]
  13337. os._add_dll_directory
  13338. path: path_t
  13339. Add a path to the DLL search path.
  13340. This search path is used when resolving dependencies for imported
  13341. extension modules (the module itself is resolved through sys.path),
  13342. and also by ctypes.
  13343. Returns an opaque value that may be passed to os.remove_dll_directory
  13344. to remove this directory from the search path.
  13345. [clinic start generated code]*/
  13346. static PyObject *
  13347. os__add_dll_directory_impl(PyObject *module, path_t *path)
  13348. /*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
  13349. {
  13350. DLL_DIRECTORY_COOKIE cookie = 0;
  13351. DWORD err = 0;
  13352. if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
  13353. return NULL;
  13354. }
  13355. Py_BEGIN_ALLOW_THREADS
  13356. if (!(cookie = AddDllDirectory(path->wide))) {
  13357. err = GetLastError();
  13358. }
  13359. Py_END_ALLOW_THREADS
  13360. if (err) {
  13361. return win32_error_object_err("add_dll_directory",
  13362. path->object, err);
  13363. }
  13364. return PyCapsule_New(cookie, "DLL directory cookie", NULL);
  13365. }
  13366. /*[clinic input]
  13367. os._remove_dll_directory
  13368. cookie: object
  13369. Removes a path from the DLL search path.
  13370. The parameter is an opaque value that was returned from
  13371. os.add_dll_directory. You can only remove directories that you added
  13372. yourself.
  13373. [clinic start generated code]*/
  13374. static PyObject *
  13375. os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
  13376. /*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
  13377. {
  13378. DLL_DIRECTORY_COOKIE cookieValue;
  13379. DWORD err = 0;
  13380. if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
  13381. PyErr_SetString(PyExc_TypeError,
  13382. "Provided cookie was not returned from os.add_dll_directory");
  13383. return NULL;
  13384. }
  13385. cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
  13386. cookie, "DLL directory cookie");
  13387. Py_BEGIN_ALLOW_THREADS
  13388. if (!RemoveDllDirectory(cookieValue)) {
  13389. err = GetLastError();
  13390. }
  13391. Py_END_ALLOW_THREADS
  13392. if (err) {
  13393. return win32_error_object_err("remove_dll_directory",
  13394. NULL, err);
  13395. }
  13396. if (PyCapsule_SetName(cookie, NULL)) {
  13397. return NULL;
  13398. }
  13399. Py_RETURN_NONE;
  13400. }
  13401. #endif /* MS_WINDOWS_APP || MS_WINDOWS_SYSTEM */
  13402. /* Only check if WIFEXITED is available: expect that it comes
  13403. with WEXITSTATUS, WIFSIGNALED, etc.
  13404. os.waitstatus_to_exitcode() is implemented in C and not in Python, so
  13405. subprocess can safely call it during late Python finalization without
  13406. risking that used os attributes were set to None by finalize_modules(). */
  13407. #if defined(WIFEXITED) || defined(MS_WINDOWS)
  13408. /*[clinic input]
  13409. os.waitstatus_to_exitcode
  13410. status as status_obj: object
  13411. Convert a wait status to an exit code.
  13412. On Unix:
  13413. * If WIFEXITED(status) is true, return WEXITSTATUS(status).
  13414. * If WIFSIGNALED(status) is true, return -WTERMSIG(status).
  13415. * Otherwise, raise a ValueError.
  13416. On Windows, return status shifted right by 8 bits.
  13417. On Unix, if the process is being traced or if waitpid() was called with
  13418. WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true.
  13419. This function must not be called if WIFSTOPPED(status) is true.
  13420. [clinic start generated code]*/
  13421. static PyObject *
  13422. os_waitstatus_to_exitcode_impl(PyObject *module, PyObject *status_obj)
  13423. /*[clinic end generated code: output=db50b1b0ba3c7153 input=7fe2d7fdaea3db42]*/
  13424. {
  13425. #ifndef MS_WINDOWS
  13426. int status = _PyLong_AsInt(status_obj);
  13427. if (status == -1 && PyErr_Occurred()) {
  13428. return NULL;
  13429. }
  13430. WAIT_TYPE wait_status;
  13431. WAIT_STATUS_INT(wait_status) = status;
  13432. int exitcode;
  13433. if (WIFEXITED(wait_status)) {
  13434. exitcode = WEXITSTATUS(wait_status);
  13435. /* Sanity check to provide warranty on the function behavior.
  13436. It should not occur in practice */
  13437. if (exitcode < 0) {
  13438. PyErr_Format(PyExc_ValueError, "invalid WEXITSTATUS: %i", exitcode);
  13439. return NULL;
  13440. }
  13441. }
  13442. else if (WIFSIGNALED(wait_status)) {
  13443. int signum = WTERMSIG(wait_status);
  13444. /* Sanity check to provide warranty on the function behavior.
  13445. It should not occurs in practice */
  13446. if (signum <= 0) {
  13447. PyErr_Format(PyExc_ValueError, "invalid WTERMSIG: %i", signum);
  13448. return NULL;
  13449. }
  13450. exitcode = -signum;
  13451. } else if (WIFSTOPPED(wait_status)) {
  13452. /* Status only received if the process is being traced
  13453. or if waitpid() was called with WUNTRACED option. */
  13454. int signum = WSTOPSIG(wait_status);
  13455. PyErr_Format(PyExc_ValueError,
  13456. "process stopped by delivery of signal %i",
  13457. signum);
  13458. return NULL;
  13459. }
  13460. else {
  13461. PyErr_Format(PyExc_ValueError, "invalid wait status: %i", status);
  13462. return NULL;
  13463. }
  13464. return PyLong_FromLong(exitcode);
  13465. #else
  13466. /* Windows implementation: see os.waitpid() implementation
  13467. which uses _cwait(). */
  13468. unsigned long long status = PyLong_AsUnsignedLongLong(status_obj);
  13469. if (status == (unsigned long long)-1 && PyErr_Occurred()) {
  13470. return NULL;
  13471. }
  13472. unsigned long long exitcode = (status >> 8);
  13473. /* ExitProcess() accepts an UINT type:
  13474. reject exit code which doesn't fit in an UINT */
  13475. if (exitcode > UINT_MAX) {
  13476. PyErr_Format(PyExc_ValueError, "invalid exit code: %llu", exitcode);
  13477. return NULL;
  13478. }
  13479. return PyLong_FromUnsignedLong((unsigned long)exitcode);
  13480. #endif
  13481. }
  13482. #endif
  13483. static PyMethodDef posix_methods[] = {
  13484. OS_STAT_METHODDEF
  13485. OS_ACCESS_METHODDEF
  13486. OS_TTYNAME_METHODDEF
  13487. OS_CHDIR_METHODDEF
  13488. OS_CHFLAGS_METHODDEF
  13489. OS_CHMOD_METHODDEF
  13490. OS_FCHMOD_METHODDEF
  13491. OS_LCHMOD_METHODDEF
  13492. OS_CHOWN_METHODDEF
  13493. OS_FCHOWN_METHODDEF
  13494. OS_LCHOWN_METHODDEF
  13495. OS_LCHFLAGS_METHODDEF
  13496. OS_CHROOT_METHODDEF
  13497. OS_CTERMID_METHODDEF
  13498. OS_GETCWD_METHODDEF
  13499. OS_GETCWDB_METHODDEF
  13500. OS_LINK_METHODDEF
  13501. OS_LISTDIR_METHODDEF
  13502. OS_LISTDRIVES_METHODDEF
  13503. OS_LISTMOUNTS_METHODDEF
  13504. OS_LISTVOLUMES_METHODDEF
  13505. OS_LSTAT_METHODDEF
  13506. OS_MKDIR_METHODDEF
  13507. OS_NICE_METHODDEF
  13508. OS_GETPRIORITY_METHODDEF
  13509. OS_SETPRIORITY_METHODDEF
  13510. OS_POSIX_SPAWN_METHODDEF
  13511. OS_POSIX_SPAWNP_METHODDEF
  13512. OS_READLINK_METHODDEF
  13513. OS_COPY_FILE_RANGE_METHODDEF
  13514. OS_SPLICE_METHODDEF
  13515. OS_RENAME_METHODDEF
  13516. OS_REPLACE_METHODDEF
  13517. OS_RMDIR_METHODDEF
  13518. OS_SYMLINK_METHODDEF
  13519. OS_SYSTEM_METHODDEF
  13520. OS_UMASK_METHODDEF
  13521. OS_UNAME_METHODDEF
  13522. OS_UNLINK_METHODDEF
  13523. OS_REMOVE_METHODDEF
  13524. OS_UTIME_METHODDEF
  13525. OS_TIMES_METHODDEF
  13526. OS__EXIT_METHODDEF
  13527. OS__FCOPYFILE_METHODDEF
  13528. OS_EXECV_METHODDEF
  13529. OS_EXECVE_METHODDEF
  13530. OS_SPAWNV_METHODDEF
  13531. OS_SPAWNVE_METHODDEF
  13532. OS_FORK1_METHODDEF
  13533. OS_FORK_METHODDEF
  13534. OS_REGISTER_AT_FORK_METHODDEF
  13535. OS_SCHED_GET_PRIORITY_MAX_METHODDEF
  13536. OS_SCHED_GET_PRIORITY_MIN_METHODDEF
  13537. OS_SCHED_GETPARAM_METHODDEF
  13538. OS_SCHED_GETSCHEDULER_METHODDEF
  13539. OS_SCHED_RR_GET_INTERVAL_METHODDEF
  13540. OS_SCHED_SETPARAM_METHODDEF
  13541. OS_SCHED_SETSCHEDULER_METHODDEF
  13542. OS_SCHED_YIELD_METHODDEF
  13543. OS_SCHED_SETAFFINITY_METHODDEF
  13544. OS_SCHED_GETAFFINITY_METHODDEF
  13545. OS_OPENPTY_METHODDEF
  13546. OS_LOGIN_TTY_METHODDEF
  13547. OS_FORKPTY_METHODDEF
  13548. OS_GETEGID_METHODDEF
  13549. OS_GETEUID_METHODDEF
  13550. OS_GETGID_METHODDEF
  13551. OS_GETGROUPLIST_METHODDEF
  13552. OS_GETGROUPS_METHODDEF
  13553. OS_GETPID_METHODDEF
  13554. OS_GETPGRP_METHODDEF
  13555. OS_GETPPID_METHODDEF
  13556. OS_GETUID_METHODDEF
  13557. OS_GETLOGIN_METHODDEF
  13558. OS_KILL_METHODDEF
  13559. OS_KILLPG_METHODDEF
  13560. OS_PLOCK_METHODDEF
  13561. OS_STARTFILE_METHODDEF
  13562. OS_SETUID_METHODDEF
  13563. OS_SETEUID_METHODDEF
  13564. OS_SETREUID_METHODDEF
  13565. OS_SETGID_METHODDEF
  13566. OS_SETEGID_METHODDEF
  13567. OS_SETREGID_METHODDEF
  13568. OS_SETGROUPS_METHODDEF
  13569. OS_INITGROUPS_METHODDEF
  13570. OS_GETPGID_METHODDEF
  13571. OS_SETPGRP_METHODDEF
  13572. OS_WAIT_METHODDEF
  13573. OS_WAIT3_METHODDEF
  13574. OS_WAIT4_METHODDEF
  13575. OS_WAITID_METHODDEF
  13576. OS_WAITPID_METHODDEF
  13577. OS_PIDFD_OPEN_METHODDEF
  13578. OS_GETSID_METHODDEF
  13579. OS_SETSID_METHODDEF
  13580. OS_SETPGID_METHODDEF
  13581. OS_TCGETPGRP_METHODDEF
  13582. OS_TCSETPGRP_METHODDEF
  13583. OS_OPEN_METHODDEF
  13584. OS_CLOSE_METHODDEF
  13585. OS_CLOSERANGE_METHODDEF
  13586. OS_DEVICE_ENCODING_METHODDEF
  13587. OS_DUP_METHODDEF
  13588. OS_DUP2_METHODDEF
  13589. OS_LOCKF_METHODDEF
  13590. OS_LSEEK_METHODDEF
  13591. OS_READ_METHODDEF
  13592. OS_READV_METHODDEF
  13593. OS_PREAD_METHODDEF
  13594. OS_PREADV_METHODDEF
  13595. OS_WRITE_METHODDEF
  13596. OS_WRITEV_METHODDEF
  13597. OS_PWRITE_METHODDEF
  13598. OS_PWRITEV_METHODDEF
  13599. OS_SENDFILE_METHODDEF
  13600. OS_FSTAT_METHODDEF
  13601. OS_ISATTY_METHODDEF
  13602. OS_PIPE_METHODDEF
  13603. OS_PIPE2_METHODDEF
  13604. OS_MKFIFO_METHODDEF
  13605. OS_MKNOD_METHODDEF
  13606. OS_MAJOR_METHODDEF
  13607. OS_MINOR_METHODDEF
  13608. OS_MAKEDEV_METHODDEF
  13609. OS_FTRUNCATE_METHODDEF
  13610. OS_TRUNCATE_METHODDEF
  13611. OS_POSIX_FALLOCATE_METHODDEF
  13612. OS_POSIX_FADVISE_METHODDEF
  13613. OS_PUTENV_METHODDEF
  13614. OS_UNSETENV_METHODDEF
  13615. OS_STRERROR_METHODDEF
  13616. OS_FCHDIR_METHODDEF
  13617. OS_FSYNC_METHODDEF
  13618. OS_SYNC_METHODDEF
  13619. OS_FDATASYNC_METHODDEF
  13620. OS_WCOREDUMP_METHODDEF
  13621. OS_WIFCONTINUED_METHODDEF
  13622. OS_WIFSTOPPED_METHODDEF
  13623. OS_WIFSIGNALED_METHODDEF
  13624. OS_WIFEXITED_METHODDEF
  13625. OS_WEXITSTATUS_METHODDEF
  13626. OS_WTERMSIG_METHODDEF
  13627. OS_WSTOPSIG_METHODDEF
  13628. OS_FSTATVFS_METHODDEF
  13629. OS_STATVFS_METHODDEF
  13630. OS_CONFSTR_METHODDEF
  13631. OS_SYSCONF_METHODDEF
  13632. OS_FPATHCONF_METHODDEF
  13633. OS_PATHCONF_METHODDEF
  13634. OS_ABORT_METHODDEF
  13635. OS__GETFULLPATHNAME_METHODDEF
  13636. OS__GETDISKUSAGE_METHODDEF
  13637. OS__GETFINALPATHNAME_METHODDEF
  13638. OS__GETVOLUMEPATHNAME_METHODDEF
  13639. OS__PATH_SPLITROOT_METHODDEF
  13640. OS__PATH_NORMPATH_METHODDEF
  13641. OS_GETLOADAVG_METHODDEF
  13642. OS_URANDOM_METHODDEF
  13643. OS_SETRESUID_METHODDEF
  13644. OS_SETRESGID_METHODDEF
  13645. OS_GETRESUID_METHODDEF
  13646. OS_GETRESGID_METHODDEF
  13647. OS_GETXATTR_METHODDEF
  13648. OS_SETXATTR_METHODDEF
  13649. OS_REMOVEXATTR_METHODDEF
  13650. OS_LISTXATTR_METHODDEF
  13651. OS_GET_TERMINAL_SIZE_METHODDEF
  13652. OS_CPU_COUNT_METHODDEF
  13653. OS_GET_INHERITABLE_METHODDEF
  13654. OS_SET_INHERITABLE_METHODDEF
  13655. OS_GET_HANDLE_INHERITABLE_METHODDEF
  13656. OS_SET_HANDLE_INHERITABLE_METHODDEF
  13657. OS_GET_BLOCKING_METHODDEF
  13658. OS_SET_BLOCKING_METHODDEF
  13659. OS_SCANDIR_METHODDEF
  13660. OS_FSPATH_METHODDEF
  13661. OS_GETRANDOM_METHODDEF
  13662. OS_MEMFD_CREATE_METHODDEF
  13663. OS_EVENTFD_METHODDEF
  13664. OS_EVENTFD_READ_METHODDEF
  13665. OS_EVENTFD_WRITE_METHODDEF
  13666. OS__ADD_DLL_DIRECTORY_METHODDEF
  13667. OS__REMOVE_DLL_DIRECTORY_METHODDEF
  13668. OS_WAITSTATUS_TO_EXITCODE_METHODDEF
  13669. OS_SETNS_METHODDEF
  13670. OS_UNSHARE_METHODDEF
  13671. OS__PATH_ISDEVDRIVE_METHODDEF
  13672. OS__PATH_ISDIR_METHODDEF
  13673. OS__PATH_ISFILE_METHODDEF
  13674. OS__PATH_ISLINK_METHODDEF
  13675. OS__PATH_EXISTS_METHODDEF
  13676. {NULL, NULL} /* Sentinel */
  13677. };
  13678. static int
  13679. all_ins(PyObject *m)
  13680. {
  13681. #ifdef F_OK
  13682. if (PyModule_AddIntMacro(m, F_OK)) return -1;
  13683. #endif
  13684. #ifdef R_OK
  13685. if (PyModule_AddIntMacro(m, R_OK)) return -1;
  13686. #endif
  13687. #ifdef W_OK
  13688. if (PyModule_AddIntMacro(m, W_OK)) return -1;
  13689. #endif
  13690. #ifdef X_OK
  13691. if (PyModule_AddIntMacro(m, X_OK)) return -1;
  13692. #endif
  13693. #ifdef NGROUPS_MAX
  13694. if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
  13695. #endif
  13696. #ifdef TMP_MAX
  13697. if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
  13698. #endif
  13699. #ifdef WCONTINUED
  13700. if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
  13701. #endif
  13702. #ifdef WNOHANG
  13703. if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
  13704. #endif
  13705. #ifdef WUNTRACED
  13706. if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
  13707. #endif
  13708. #ifdef O_RDONLY
  13709. if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
  13710. #endif
  13711. #ifdef O_WRONLY
  13712. if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
  13713. #endif
  13714. #ifdef O_RDWR
  13715. if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
  13716. #endif
  13717. #ifdef O_NDELAY
  13718. if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
  13719. #endif
  13720. #ifdef O_NONBLOCK
  13721. if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
  13722. #endif
  13723. #ifdef O_APPEND
  13724. if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
  13725. #endif
  13726. #ifdef O_DSYNC
  13727. if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
  13728. #endif
  13729. #ifdef O_RSYNC
  13730. if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
  13731. #endif
  13732. #ifdef O_SYNC
  13733. if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
  13734. #endif
  13735. #ifdef O_NOCTTY
  13736. if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
  13737. #endif
  13738. #ifdef O_CREAT
  13739. if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
  13740. #endif
  13741. #ifdef O_EXCL
  13742. if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
  13743. #endif
  13744. #ifdef O_TRUNC
  13745. if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
  13746. #endif
  13747. #ifdef O_BINARY
  13748. if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
  13749. #endif
  13750. #ifdef O_TEXT
  13751. if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
  13752. #endif
  13753. #ifdef O_XATTR
  13754. if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
  13755. #endif
  13756. #ifdef O_LARGEFILE
  13757. if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
  13758. #endif
  13759. #ifndef __GNU__
  13760. #ifdef O_SHLOCK
  13761. if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
  13762. #endif
  13763. #ifdef O_EXLOCK
  13764. if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
  13765. #endif
  13766. #endif
  13767. #ifdef O_EXEC
  13768. if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
  13769. #endif
  13770. #ifdef O_SEARCH
  13771. if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
  13772. #endif
  13773. #ifdef O_PATH
  13774. if (PyModule_AddIntMacro(m, O_PATH)) return -1;
  13775. #endif
  13776. #ifdef O_TTY_INIT
  13777. if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
  13778. #endif
  13779. #ifdef O_TMPFILE
  13780. if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
  13781. #endif
  13782. #ifdef PRIO_PROCESS
  13783. if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
  13784. #endif
  13785. #ifdef PRIO_PGRP
  13786. if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
  13787. #endif
  13788. #ifdef PRIO_USER
  13789. if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
  13790. #endif
  13791. #ifdef PRIO_DARWIN_THREAD
  13792. if (PyModule_AddIntMacro(m, PRIO_DARWIN_THREAD)) return -1;
  13793. #endif
  13794. #ifdef PRIO_DARWIN_PROCESS
  13795. if (PyModule_AddIntMacro(m, PRIO_DARWIN_PROCESS)) return -1;
  13796. #endif
  13797. #ifdef PRIO_DARWIN_BG
  13798. if (PyModule_AddIntMacro(m, PRIO_DARWIN_BG)) return -1;
  13799. #endif
  13800. #ifdef PRIO_DARWIN_NONUI
  13801. if (PyModule_AddIntMacro(m, PRIO_DARWIN_NONUI)) return -1;
  13802. #endif
  13803. #ifdef O_CLOEXEC
  13804. if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
  13805. #endif
  13806. #ifdef O_ACCMODE
  13807. if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
  13808. #endif
  13809. #ifdef O_EVTONLY
  13810. if (PyModule_AddIntMacro(m, O_EVTONLY)) return -1;
  13811. #endif
  13812. #ifdef O_FSYNC
  13813. if (PyModule_AddIntMacro(m, O_FSYNC)) return -1;
  13814. #endif
  13815. #ifdef O_SYMLINK
  13816. if (PyModule_AddIntMacro(m, O_SYMLINK)) return -1;
  13817. #endif
  13818. #ifdef SEEK_HOLE
  13819. if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
  13820. #endif
  13821. #ifdef SEEK_DATA
  13822. if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
  13823. #endif
  13824. /* MS Windows */
  13825. #ifdef O_NOINHERIT
  13826. /* Don't inherit in child processes. */
  13827. if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
  13828. #endif
  13829. #ifdef _O_SHORT_LIVED
  13830. /* Optimize for short life (keep in memory). */
  13831. /* MS forgot to define this one with a non-underscore form too. */
  13832. if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
  13833. #endif
  13834. #ifdef O_TEMPORARY
  13835. /* Automatically delete when last handle is closed. */
  13836. if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
  13837. #endif
  13838. #ifdef O_RANDOM
  13839. /* Optimize for random access. */
  13840. if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
  13841. #endif
  13842. #ifdef O_SEQUENTIAL
  13843. /* Optimize for sequential access. */
  13844. if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
  13845. #endif
  13846. /* GNU extensions. */
  13847. #ifdef O_ASYNC
  13848. /* Send a SIGIO signal whenever input or output
  13849. becomes available on file descriptor */
  13850. if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
  13851. #endif
  13852. #ifdef O_DIRECT
  13853. /* Direct disk access. */
  13854. if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
  13855. #endif
  13856. #ifdef O_DIRECTORY
  13857. /* Must be a directory. */
  13858. if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
  13859. #endif
  13860. #ifdef O_NOFOLLOW
  13861. /* Do not follow links. */
  13862. if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
  13863. #endif
  13864. #ifdef O_NOFOLLOW_ANY
  13865. if (PyModule_AddIntMacro(m, O_NOFOLLOW_ANY)) return -1;
  13866. #endif
  13867. #ifdef O_NOLINKS
  13868. /* Fails if link count of the named file is greater than 1 */
  13869. if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
  13870. #endif
  13871. #ifdef O_NOATIME
  13872. /* Do not update the access time. */
  13873. if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
  13874. #endif
  13875. /* These come from sysexits.h */
  13876. #ifdef EX_OK
  13877. if (PyModule_AddIntMacro(m, EX_OK)) return -1;
  13878. #endif /* EX_OK */
  13879. #ifdef EX_USAGE
  13880. if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
  13881. #endif /* EX_USAGE */
  13882. #ifdef EX_DATAERR
  13883. if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
  13884. #endif /* EX_DATAERR */
  13885. #ifdef EX_NOINPUT
  13886. if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
  13887. #endif /* EX_NOINPUT */
  13888. #ifdef EX_NOUSER
  13889. if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
  13890. #endif /* EX_NOUSER */
  13891. #ifdef EX_NOHOST
  13892. if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
  13893. #endif /* EX_NOHOST */
  13894. #ifdef EX_UNAVAILABLE
  13895. if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
  13896. #endif /* EX_UNAVAILABLE */
  13897. #ifdef EX_SOFTWARE
  13898. if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
  13899. #endif /* EX_SOFTWARE */
  13900. #ifdef EX_OSERR
  13901. if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
  13902. #endif /* EX_OSERR */
  13903. #ifdef EX_OSFILE
  13904. if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
  13905. #endif /* EX_OSFILE */
  13906. #ifdef EX_CANTCREAT
  13907. if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
  13908. #endif /* EX_CANTCREAT */
  13909. #ifdef EX_IOERR
  13910. if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
  13911. #endif /* EX_IOERR */
  13912. #ifdef EX_TEMPFAIL
  13913. if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
  13914. #endif /* EX_TEMPFAIL */
  13915. #ifdef EX_PROTOCOL
  13916. if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
  13917. #endif /* EX_PROTOCOL */
  13918. #ifdef EX_NOPERM
  13919. if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
  13920. #endif /* EX_NOPERM */
  13921. #ifdef EX_CONFIG
  13922. if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
  13923. #endif /* EX_CONFIG */
  13924. #ifdef EX_NOTFOUND
  13925. if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
  13926. #endif /* EX_NOTFOUND */
  13927. /* statvfs */
  13928. #ifdef ST_RDONLY
  13929. if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
  13930. #endif /* ST_RDONLY */
  13931. #ifdef ST_NOSUID
  13932. if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
  13933. #endif /* ST_NOSUID */
  13934. /* GNU extensions */
  13935. #ifdef ST_NODEV
  13936. if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
  13937. #endif /* ST_NODEV */
  13938. #ifdef ST_NOEXEC
  13939. if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
  13940. #endif /* ST_NOEXEC */
  13941. #ifdef ST_SYNCHRONOUS
  13942. if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
  13943. #endif /* ST_SYNCHRONOUS */
  13944. #ifdef ST_MANDLOCK
  13945. if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
  13946. #endif /* ST_MANDLOCK */
  13947. #ifdef ST_WRITE
  13948. if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
  13949. #endif /* ST_WRITE */
  13950. #ifdef ST_APPEND
  13951. if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
  13952. #endif /* ST_APPEND */
  13953. #ifdef ST_NOATIME
  13954. if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
  13955. #endif /* ST_NOATIME */
  13956. #ifdef ST_NODIRATIME
  13957. if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
  13958. #endif /* ST_NODIRATIME */
  13959. #ifdef ST_RELATIME
  13960. if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
  13961. #endif /* ST_RELATIME */
  13962. /* FreeBSD sendfile() constants */
  13963. #ifdef SF_NODISKIO
  13964. if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
  13965. #endif
  13966. /* is obsolete since the 11.x release */
  13967. #ifdef SF_MNOWAIT
  13968. if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
  13969. #endif
  13970. #ifdef SF_SYNC
  13971. if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
  13972. #endif
  13973. #ifdef SF_NOCACHE
  13974. if (PyModule_AddIntMacro(m, SF_NOCACHE)) return -1;
  13975. #endif
  13976. /* constants for posix_fadvise */
  13977. #ifdef POSIX_FADV_NORMAL
  13978. if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
  13979. #endif
  13980. #ifdef POSIX_FADV_SEQUENTIAL
  13981. if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
  13982. #endif
  13983. #ifdef POSIX_FADV_RANDOM
  13984. if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
  13985. #endif
  13986. #ifdef POSIX_FADV_NOREUSE
  13987. if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
  13988. #endif
  13989. #ifdef POSIX_FADV_WILLNEED
  13990. if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
  13991. #endif
  13992. #ifdef POSIX_FADV_DONTNEED
  13993. if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
  13994. #endif
  13995. /* constants for waitid */
  13996. #if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
  13997. if (PyModule_AddIntMacro(m, P_PID)) return -1;
  13998. if (PyModule_AddIntMacro(m, P_PGID)) return -1;
  13999. if (PyModule_AddIntMacro(m, P_ALL)) return -1;
  14000. #ifdef P_PIDFD
  14001. if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
  14002. #endif
  14003. #ifdef PIDFD_NONBLOCK
  14004. if (PyModule_AddIntMacro(m, PIDFD_NONBLOCK)) return -1;
  14005. #endif
  14006. #endif
  14007. #ifdef WEXITED
  14008. if (PyModule_AddIntMacro(m, WEXITED)) return -1;
  14009. #endif
  14010. #ifdef WNOWAIT
  14011. if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
  14012. #endif
  14013. #ifdef WSTOPPED
  14014. if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
  14015. #endif
  14016. #ifdef CLD_EXITED
  14017. if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
  14018. #endif
  14019. #ifdef CLD_KILLED
  14020. if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
  14021. #endif
  14022. #ifdef CLD_DUMPED
  14023. if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
  14024. #endif
  14025. #ifdef CLD_TRAPPED
  14026. if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
  14027. #endif
  14028. #ifdef CLD_STOPPED
  14029. if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
  14030. #endif
  14031. #ifdef CLD_CONTINUED
  14032. if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
  14033. #endif
  14034. /* constants for lockf */
  14035. #ifdef F_LOCK
  14036. if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
  14037. #endif
  14038. #ifdef F_TLOCK
  14039. if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
  14040. #endif
  14041. #ifdef F_ULOCK
  14042. if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
  14043. #endif
  14044. #ifdef F_TEST
  14045. if (PyModule_AddIntMacro(m, F_TEST)) return -1;
  14046. #endif
  14047. #ifdef RWF_DSYNC
  14048. if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
  14049. #endif
  14050. #ifdef RWF_HIPRI
  14051. if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
  14052. #endif
  14053. #ifdef RWF_SYNC
  14054. if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
  14055. #endif
  14056. #ifdef RWF_NOWAIT
  14057. if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
  14058. #endif
  14059. #ifdef RWF_APPEND
  14060. if (PyModule_AddIntConstant(m, "RWF_APPEND", RWF_APPEND)) return -1;
  14061. #endif
  14062. /* constants for splice */
  14063. #if defined(HAVE_SPLICE) && defined(__linux__)
  14064. if (PyModule_AddIntConstant(m, "SPLICE_F_MOVE", SPLICE_F_MOVE)) return -1;
  14065. if (PyModule_AddIntConstant(m, "SPLICE_F_NONBLOCK", SPLICE_F_NONBLOCK)) return -1;
  14066. if (PyModule_AddIntConstant(m, "SPLICE_F_MORE", SPLICE_F_MORE)) return -1;
  14067. #endif
  14068. /* constants for posix_spawn */
  14069. #ifdef HAVE_POSIX_SPAWN
  14070. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
  14071. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
  14072. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
  14073. #endif
  14074. #if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
  14075. if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
  14076. if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
  14077. if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
  14078. #endif
  14079. #ifdef HAVE_SPAWNV
  14080. if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
  14081. if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
  14082. #endif
  14083. #ifdef HAVE_SCHED_H
  14084. #ifdef SCHED_OTHER
  14085. if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
  14086. #endif
  14087. #ifdef SCHED_FIFO
  14088. if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
  14089. #endif
  14090. #ifdef SCHED_RR
  14091. if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
  14092. #endif
  14093. #ifdef SCHED_SPORADIC
  14094. if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
  14095. #endif
  14096. #ifdef SCHED_BATCH
  14097. if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
  14098. #endif
  14099. #ifdef SCHED_IDLE
  14100. if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
  14101. #endif
  14102. #ifdef SCHED_RESET_ON_FORK
  14103. if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
  14104. #endif
  14105. #ifdef SCHED_SYS
  14106. if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
  14107. #endif
  14108. #ifdef SCHED_IA
  14109. if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
  14110. #endif
  14111. #ifdef SCHED_FSS
  14112. if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
  14113. #endif
  14114. #ifdef SCHED_FX
  14115. if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
  14116. #endif
  14117. /* constants for namespaces */
  14118. #if defined(HAVE_SETNS) || defined(HAVE_UNSHARE)
  14119. #ifdef CLONE_FS
  14120. if (PyModule_AddIntMacro(m, CLONE_FS)) return -1;
  14121. #endif
  14122. #ifdef CLONE_FILES
  14123. if (PyModule_AddIntMacro(m, CLONE_FILES)) return -1;
  14124. #endif
  14125. #ifdef CLONE_NEWNS
  14126. if (PyModule_AddIntMacro(m, CLONE_NEWNS)) return -1;
  14127. #endif
  14128. #ifdef CLONE_NEWCGROUP
  14129. if (PyModule_AddIntMacro(m, CLONE_NEWCGROUP)) return -1;
  14130. #endif
  14131. #ifdef CLONE_NEWUTS
  14132. if (PyModule_AddIntMacro(m, CLONE_NEWUTS)) return -1;
  14133. #endif
  14134. #ifdef CLONE_NEWIPC
  14135. if (PyModule_AddIntMacro(m, CLONE_NEWIPC)) return -1;
  14136. #endif
  14137. #ifdef CLONE_NEWUSER
  14138. if (PyModule_AddIntMacro(m, CLONE_NEWUSER)) return -1;
  14139. #endif
  14140. #ifdef CLONE_NEWPID
  14141. if (PyModule_AddIntMacro(m, CLONE_NEWPID)) return -1;
  14142. #endif
  14143. #ifdef CLONE_NEWNET
  14144. if (PyModule_AddIntMacro(m, CLONE_NEWNET)) return -1;
  14145. #endif
  14146. #ifdef CLONE_NEWTIME
  14147. if (PyModule_AddIntMacro(m, CLONE_NEWTIME)) return -1;
  14148. #endif
  14149. #ifdef CLONE_SYSVSEM
  14150. if (PyModule_AddIntMacro(m, CLONE_SYSVSEM)) return -1;
  14151. #endif
  14152. #ifdef CLONE_THREAD
  14153. if (PyModule_AddIntMacro(m, CLONE_THREAD)) return -1;
  14154. #endif
  14155. #ifdef CLONE_SIGHAND
  14156. if (PyModule_AddIntMacro(m, CLONE_SIGHAND)) return -1;
  14157. #endif
  14158. #ifdef CLONE_VM
  14159. if (PyModule_AddIntMacro(m, CLONE_VM)) return -1;
  14160. #endif
  14161. #endif
  14162. #endif
  14163. #ifdef USE_XATTRS
  14164. if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
  14165. if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
  14166. if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
  14167. #endif
  14168. #if HAVE_DECL_RTLD_LAZY
  14169. if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
  14170. #endif
  14171. #if HAVE_DECL_RTLD_NOW
  14172. if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
  14173. #endif
  14174. #if HAVE_DECL_RTLD_GLOBAL
  14175. if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
  14176. #endif
  14177. #if HAVE_DECL_RTLD_LOCAL
  14178. if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
  14179. #endif
  14180. #if HAVE_DECL_RTLD_NODELETE
  14181. if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
  14182. #endif
  14183. #if HAVE_DECL_RTLD_NOLOAD
  14184. if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
  14185. #endif
  14186. #if HAVE_DECL_RTLD_DEEPBIND
  14187. if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
  14188. #endif
  14189. #if HAVE_DECL_RTLD_MEMBER
  14190. if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
  14191. #endif
  14192. #ifdef HAVE_GETRANDOM_SYSCALL
  14193. if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
  14194. if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
  14195. #endif
  14196. #ifdef HAVE_MEMFD_CREATE
  14197. if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
  14198. if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
  14199. #ifdef MFD_HUGETLB
  14200. if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
  14201. #endif
  14202. #ifdef MFD_HUGE_SHIFT
  14203. if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
  14204. #endif
  14205. #ifdef MFD_HUGE_MASK
  14206. if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
  14207. #endif
  14208. #ifdef MFD_HUGE_64KB
  14209. if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
  14210. #endif
  14211. #ifdef MFD_HUGE_512KB
  14212. if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
  14213. #endif
  14214. #ifdef MFD_HUGE_1MB
  14215. if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
  14216. #endif
  14217. #ifdef MFD_HUGE_2MB
  14218. if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
  14219. #endif
  14220. #ifdef MFD_HUGE_8MB
  14221. if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
  14222. #endif
  14223. #ifdef MFD_HUGE_16MB
  14224. if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
  14225. #endif
  14226. #ifdef MFD_HUGE_32MB
  14227. if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
  14228. #endif
  14229. #ifdef MFD_HUGE_256MB
  14230. if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
  14231. #endif
  14232. #ifdef MFD_HUGE_512MB
  14233. if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
  14234. #endif
  14235. #ifdef MFD_HUGE_1GB
  14236. if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
  14237. #endif
  14238. #ifdef MFD_HUGE_2GB
  14239. if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
  14240. #endif
  14241. #ifdef MFD_HUGE_16GB
  14242. if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
  14243. #endif
  14244. #endif /* HAVE_MEMFD_CREATE */
  14245. #if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
  14246. if (PyModule_AddIntMacro(m, EFD_CLOEXEC)) return -1;
  14247. #ifdef EFD_NONBLOCK
  14248. if (PyModule_AddIntMacro(m, EFD_NONBLOCK)) return -1;
  14249. #endif
  14250. #ifdef EFD_SEMAPHORE
  14251. if (PyModule_AddIntMacro(m, EFD_SEMAPHORE)) return -1;
  14252. #endif
  14253. #endif /* HAVE_EVENTFD && EFD_CLOEXEC */
  14254. #if defined(__APPLE__)
  14255. if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
  14256. if (PyModule_AddIntConstant(m, "_COPYFILE_STAT", COPYFILE_STAT)) return -1;
  14257. if (PyModule_AddIntConstant(m, "_COPYFILE_ACL", COPYFILE_ACL)) return -1;
  14258. if (PyModule_AddIntConstant(m, "_COPYFILE_XATTR", COPYFILE_XATTR)) return -1;
  14259. #endif
  14260. #ifdef MS_WINDOWS
  14261. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
  14262. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
  14263. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
  14264. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
  14265. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
  14266. #endif
  14267. return 0;
  14268. }
  14269. #define PROBE(name, test) \
  14270. static int name(void) \
  14271. { \
  14272. if (test) { \
  14273. return 1; \
  14274. } else { \
  14275. return 0; \
  14276. } \
  14277. }
  14278. #ifdef HAVE_FSTATAT
  14279. PROBE(probe_fstatat, HAVE_FSTATAT_RUNTIME)
  14280. #endif
  14281. #ifdef HAVE_FACCESSAT
  14282. PROBE(probe_faccessat, HAVE_FACCESSAT_RUNTIME)
  14283. #endif
  14284. #ifdef HAVE_FCHMODAT
  14285. PROBE(probe_fchmodat, HAVE_FCHMODAT_RUNTIME)
  14286. #endif
  14287. #ifdef HAVE_FCHOWNAT
  14288. PROBE(probe_fchownat, HAVE_FCHOWNAT_RUNTIME)
  14289. #endif
  14290. #ifdef HAVE_LINKAT
  14291. PROBE(probe_linkat, HAVE_LINKAT_RUNTIME)
  14292. #endif
  14293. #ifdef HAVE_FDOPENDIR
  14294. PROBE(probe_fdopendir, HAVE_FDOPENDIR_RUNTIME)
  14295. #endif
  14296. #ifdef HAVE_MKDIRAT
  14297. PROBE(probe_mkdirat, HAVE_MKDIRAT_RUNTIME)
  14298. #endif
  14299. #ifdef HAVE_MKFIFOAT
  14300. PROBE(probe_mkfifoat, HAVE_MKFIFOAT_RUNTIME)
  14301. #endif
  14302. #ifdef HAVE_MKNODAT
  14303. PROBE(probe_mknodat, HAVE_MKNODAT_RUNTIME)
  14304. #endif
  14305. #ifdef HAVE_RENAMEAT
  14306. PROBE(probe_renameat, HAVE_RENAMEAT_RUNTIME)
  14307. #endif
  14308. #ifdef HAVE_UNLINKAT
  14309. PROBE(probe_unlinkat, HAVE_UNLINKAT_RUNTIME)
  14310. #endif
  14311. #ifdef HAVE_OPENAT
  14312. PROBE(probe_openat, HAVE_OPENAT_RUNTIME)
  14313. #endif
  14314. #ifdef HAVE_READLINKAT
  14315. PROBE(probe_readlinkat, HAVE_READLINKAT_RUNTIME)
  14316. #endif
  14317. #ifdef HAVE_SYMLINKAT
  14318. PROBE(probe_symlinkat, HAVE_SYMLINKAT_RUNTIME)
  14319. #endif
  14320. #ifdef HAVE_FUTIMENS
  14321. PROBE(probe_futimens, HAVE_FUTIMENS_RUNTIME)
  14322. #endif
  14323. #ifdef HAVE_UTIMENSAT
  14324. PROBE(probe_utimensat, HAVE_UTIMENSAT_RUNTIME)
  14325. #endif
  14326. static const struct have_function {
  14327. const char * const label;
  14328. int (*probe)(void);
  14329. } have_functions[] = {
  14330. #ifdef HAVE_EVENTFD
  14331. {"HAVE_EVENTFD", NULL},
  14332. #endif
  14333. #ifdef HAVE_FACCESSAT
  14334. { "HAVE_FACCESSAT", probe_faccessat },
  14335. #endif
  14336. #ifdef HAVE_FCHDIR
  14337. { "HAVE_FCHDIR", NULL },
  14338. #endif
  14339. #ifdef HAVE_FCHMOD
  14340. { "HAVE_FCHMOD", NULL },
  14341. #endif
  14342. #ifdef HAVE_FCHMODAT
  14343. { "HAVE_FCHMODAT", probe_fchmodat },
  14344. #endif
  14345. #ifdef HAVE_FCHOWN
  14346. { "HAVE_FCHOWN", NULL },
  14347. #endif
  14348. #ifdef HAVE_FCHOWNAT
  14349. { "HAVE_FCHOWNAT", probe_fchownat },
  14350. #endif
  14351. #ifdef HAVE_FEXECVE
  14352. { "HAVE_FEXECVE", NULL },
  14353. #endif
  14354. #ifdef HAVE_FDOPENDIR
  14355. { "HAVE_FDOPENDIR", probe_fdopendir },
  14356. #endif
  14357. #ifdef HAVE_FPATHCONF
  14358. { "HAVE_FPATHCONF", NULL },
  14359. #endif
  14360. #ifdef HAVE_FSTATAT
  14361. { "HAVE_FSTATAT", probe_fstatat },
  14362. #endif
  14363. #ifdef HAVE_FSTATVFS
  14364. { "HAVE_FSTATVFS", NULL },
  14365. #endif
  14366. #if defined HAVE_FTRUNCATE || defined MS_WINDOWS
  14367. { "HAVE_FTRUNCATE", NULL },
  14368. #endif
  14369. #ifdef HAVE_FUTIMENS
  14370. { "HAVE_FUTIMENS", probe_futimens },
  14371. #endif
  14372. #ifdef HAVE_FUTIMES
  14373. { "HAVE_FUTIMES", NULL },
  14374. #endif
  14375. #ifdef HAVE_FUTIMESAT
  14376. { "HAVE_FUTIMESAT", NULL },
  14377. #endif
  14378. #ifdef HAVE_LINKAT
  14379. { "HAVE_LINKAT", probe_linkat },
  14380. #endif
  14381. #ifdef HAVE_LCHFLAGS
  14382. { "HAVE_LCHFLAGS", NULL },
  14383. #endif
  14384. #ifdef HAVE_LCHMOD
  14385. { "HAVE_LCHMOD", NULL },
  14386. #endif
  14387. #ifdef HAVE_LCHOWN
  14388. { "HAVE_LCHOWN", NULL },
  14389. #endif
  14390. #ifdef HAVE_LSTAT
  14391. { "HAVE_LSTAT", NULL },
  14392. #endif
  14393. #ifdef HAVE_LUTIMES
  14394. { "HAVE_LUTIMES", NULL },
  14395. #endif
  14396. #ifdef HAVE_MEMFD_CREATE
  14397. { "HAVE_MEMFD_CREATE", NULL },
  14398. #endif
  14399. #ifdef HAVE_MKDIRAT
  14400. { "HAVE_MKDIRAT", probe_mkdirat },
  14401. #endif
  14402. #ifdef HAVE_MKFIFOAT
  14403. { "HAVE_MKFIFOAT", probe_mkfifoat },
  14404. #endif
  14405. #ifdef HAVE_MKNODAT
  14406. { "HAVE_MKNODAT", probe_mknodat },
  14407. #endif
  14408. #ifdef HAVE_OPENAT
  14409. { "HAVE_OPENAT", probe_openat },
  14410. #endif
  14411. #ifdef HAVE_READLINKAT
  14412. { "HAVE_READLINKAT", probe_readlinkat },
  14413. #endif
  14414. #ifdef HAVE_RENAMEAT
  14415. { "HAVE_RENAMEAT", probe_renameat },
  14416. #endif
  14417. #ifdef HAVE_SYMLINKAT
  14418. { "HAVE_SYMLINKAT", probe_symlinkat },
  14419. #endif
  14420. #ifdef HAVE_UNLINKAT
  14421. { "HAVE_UNLINKAT", probe_unlinkat },
  14422. #endif
  14423. #ifdef HAVE_UTIMENSAT
  14424. { "HAVE_UTIMENSAT", probe_utimensat },
  14425. #endif
  14426. #ifdef MS_WINDOWS
  14427. { "MS_WINDOWS", NULL },
  14428. #endif
  14429. { NULL, NULL }
  14430. };
  14431. static int
  14432. posixmodule_exec(PyObject *m)
  14433. {
  14434. _posixstate *state = get_posix_state(m);
  14435. #if defined(HAVE_PWRITEV)
  14436. if (HAVE_PWRITEV_RUNTIME) {} else {
  14437. PyObject* dct = PyModule_GetDict(m);
  14438. if (dct == NULL) {
  14439. return -1;
  14440. }
  14441. if (PyDict_DelItemString(dct, "pwritev") == -1) {
  14442. PyErr_Clear();
  14443. }
  14444. if (PyDict_DelItemString(dct, "preadv") == -1) {
  14445. PyErr_Clear();
  14446. }
  14447. }
  14448. #endif
  14449. /* Initialize environ dictionary */
  14450. if (_PyModule_Add(m, "environ", convertenviron()) != 0) {
  14451. return -1;
  14452. }
  14453. if (all_ins(m))
  14454. return -1;
  14455. if (setup_confname_tables(m))
  14456. return -1;
  14457. if (PyModule_AddObjectRef(m, "error", PyExc_OSError) < 0) {
  14458. return -1;
  14459. }
  14460. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  14461. waitid_result_desc.name = MODNAME ".waitid_result";
  14462. state->WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
  14463. if (PyModule_AddObjectRef(m, "waitid_result", state->WaitidResultType) < 0) {
  14464. return -1;
  14465. }
  14466. #endif
  14467. stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
  14468. stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
  14469. stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
  14470. stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
  14471. state->StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
  14472. if (PyModule_AddObjectRef(m, "stat_result", state->StatResultType) < 0) {
  14473. return -1;
  14474. }
  14475. state->statresult_new_orig = ((PyTypeObject *)state->StatResultType)->tp_new;
  14476. ((PyTypeObject *)state->StatResultType)->tp_new = statresult_new;
  14477. statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
  14478. state->StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
  14479. if (PyModule_AddObjectRef(m, "statvfs_result", state->StatVFSResultType) < 0) {
  14480. return -1;
  14481. }
  14482. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  14483. sched_param_desc.name = MODNAME ".sched_param";
  14484. state->SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
  14485. if (PyModule_AddObjectRef(m, "sched_param", state->SchedParamType) < 0) {
  14486. return -1;
  14487. }
  14488. ((PyTypeObject *)state->SchedParamType)->tp_new = os_sched_param;
  14489. #endif
  14490. /* initialize TerminalSize_info */
  14491. state->TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
  14492. if (PyModule_AddObjectRef(m, "terminal_size", state->TerminalSizeType) < 0) {
  14493. return -1;
  14494. }
  14495. /* initialize scandir types */
  14496. PyObject *ScandirIteratorType = PyType_FromModuleAndSpec(m, &ScandirIteratorType_spec, NULL);
  14497. if (ScandirIteratorType == NULL) {
  14498. return -1;
  14499. }
  14500. state->ScandirIteratorType = ScandirIteratorType;
  14501. state->DirEntryType = PyType_FromModuleAndSpec(m, &DirEntryType_spec, NULL);
  14502. if (PyModule_AddObjectRef(m, "DirEntry", state->DirEntryType) < 0) {
  14503. return -1;
  14504. }
  14505. times_result_desc.name = MODNAME ".times_result";
  14506. state->TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
  14507. if (PyModule_AddObjectRef(m, "times_result", state->TimesResultType) < 0) {
  14508. return -1;
  14509. }
  14510. state->UnameResultType = (PyObject *)PyStructSequence_NewType(&uname_result_desc);
  14511. if (PyModule_AddObjectRef(m, "uname_result", state->UnameResultType) < 0) {
  14512. return -1;
  14513. }
  14514. if ((state->billion = PyLong_FromLong(1000000000)) == NULL)
  14515. return -1;
  14516. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  14517. state->struct_rusage = PyUnicode_InternFromString("struct_rusage");
  14518. if (state->struct_rusage == NULL)
  14519. return -1;
  14520. #endif
  14521. state->st_mode = PyUnicode_InternFromString("st_mode");
  14522. if (state->st_mode == NULL)
  14523. return -1;
  14524. /* suppress "function not used" warnings */
  14525. {
  14526. int ignored;
  14527. fd_specified("", -1);
  14528. follow_symlinks_specified("", 1);
  14529. dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
  14530. dir_fd_converter(Py_None, &ignored);
  14531. dir_fd_unavailable(Py_None, &ignored);
  14532. }
  14533. /*
  14534. * provide list of locally available functions
  14535. * so os.py can populate support_* lists
  14536. */
  14537. PyObject *list = PyList_New(0);
  14538. if (!list) {
  14539. return -1;
  14540. }
  14541. for (const struct have_function *trace = have_functions; trace->label; trace++) {
  14542. PyObject *unicode;
  14543. if (trace->probe && !trace->probe()) continue;
  14544. unicode = PyUnicode_DecodeASCII(trace->label, strlen(trace->label), NULL);
  14545. if (!unicode)
  14546. return -1;
  14547. if (PyList_Append(list, unicode))
  14548. return -1;
  14549. Py_DECREF(unicode);
  14550. }
  14551. return _PyModule_Add(m, "_have_functions", list);
  14552. }
  14553. static PyModuleDef_Slot posixmodile_slots[] = {
  14554. {Py_mod_exec, posixmodule_exec},
  14555. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  14556. {0, NULL}
  14557. };
  14558. static struct PyModuleDef posixmodule = {
  14559. PyModuleDef_HEAD_INIT,
  14560. .m_name = MODNAME,
  14561. .m_doc = posix__doc__,
  14562. .m_size = sizeof(_posixstate),
  14563. .m_methods = posix_methods,
  14564. .m_slots = posixmodile_slots,
  14565. .m_traverse = _posix_traverse,
  14566. .m_clear = _posix_clear,
  14567. .m_free = _posix_free,
  14568. };
  14569. PyMODINIT_FUNC
  14570. INITFUNC(void)
  14571. {
  14572. return PyModuleDef_Init(&posixmodule);
  14573. }
  14574. #ifdef __cplusplus
  14575. }
  14576. #endif