posixmodule.c 450 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120
  1. /* POSIX module implementation */
  2. /* This file is also used for Windows NT/MS-Win. In that case the
  3. module actually calls itself 'nt', not 'posix', and a few
  4. functions are either unimplemented or implemented differently. The source
  5. assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
  6. of the compiler used. Different compilers define their own feature
  7. test macro, e.g. '_MSC_VER'. */
  8. #define PY_SSIZE_T_CLEAN
  9. #include "Python.h"
  10. #ifdef __VXWORKS__
  11. # include "pycore_bitutils.h" // _Py_popcount32()
  12. #endif
  13. #include "pycore_call.h" // _PyObject_CallNoArgs()
  14. #include "pycore_ceval.h" // _PyEval_ReInitThreads()
  15. #include "pycore_fileutils.h" // _Py_closerange()
  16. #include "pycore_import.h" // _PyImport_ReInitLock()
  17. #include "pycore_initconfig.h" // _PyStatus_EXCEPTION()
  18. #include "pycore_long.h" // _PyLong_IsNegative()
  19. #include "pycore_moduleobject.h" // _PyModule_GetState()
  20. #include "pycore_object.h" // _PyObject_LookupSpecial()
  21. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  22. #include "pycore_signal.h" // Py_NSIG
  23. #include "pycore_typeobject.h" // _PyType_AddMethod()
  24. #ifdef MS_WINDOWS
  25. # include <windows.h>
  26. # if !defined(MS_WINDOWS_GAMES) || defined(MS_WINDOWS_DESKTOP)
  27. # include <pathcch.h>
  28. # endif
  29. # include <winioctl.h>
  30. # include <lmcons.h> // UNLEN
  31. # include "osdefs.h" // SEP
  32. # include <aclapi.h> // SetEntriesInAcl
  33. # include <sddl.h> // SDDL_REVISION_1
  34. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  35. # define HAVE_SYMLINK
  36. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_SYSTEM */
  37. #endif
  38. #include "structmember.h" // PyMemberDef
  39. #ifndef MS_WINDOWS
  40. # include "posixmodule.h"
  41. #else
  42. # include "pycore_fileutils_windows.h"
  43. # include "winreparse.h"
  44. #endif
  45. /* On android API level 21, 'AT_EACCESS' is not declared although
  46. * HAVE_FACCESSAT is defined. */
  47. #ifdef __ANDROID__
  48. # undef HAVE_FACCESSAT
  49. #endif
  50. #include <stdio.h> // ctermid()
  51. #include <stdlib.h> // system()
  52. #ifdef HAVE_SYS_PIDFD_H
  53. # error #include <sys/pidfd.h> // PIDFD_NONBLOCK
  54. #endif
  55. /*
  56. * A number of APIs are available on macOS from a certain macOS version.
  57. * To support building with a new SDK while deploying to older versions
  58. * the availability test is split into two:
  59. * - HAVE_<FUNCTION>: The configure check for compile time availability
  60. * - HAVE_<FUNCTION>_RUNTIME: Runtime check for availability
  61. *
  62. * The latter is always true when not on macOS, or when using a compiler
  63. * that does not support __has_builtin (older versions of Xcode).
  64. *
  65. * Due to compiler restrictions there is one valid use of HAVE_<FUNCTION>_RUNTIME:
  66. * if (HAVE_<FUNCTION>_RUNTIME) { ... }
  67. *
  68. * In mixing the test with other tests or using negations will result in compile
  69. * errors.
  70. */
  71. #if defined(__APPLE__)
  72. #include <mach/mach.h>
  73. #if defined(__has_builtin)
  74. #if __has_builtin(__builtin_available)
  75. #define HAVE_BUILTIN_AVAILABLE 1
  76. #endif
  77. #endif
  78. #ifdef HAVE_BUILTIN_AVAILABLE
  79. # define HAVE_FSTATAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  80. # define HAVE_FACCESSAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  81. # define HAVE_FCHMODAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  82. # define HAVE_FCHOWNAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  83. # define HAVE_LINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  84. # define HAVE_FDOPENDIR_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  85. # define HAVE_MKDIRAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  86. # define HAVE_RENAMEAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  87. # define HAVE_UNLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  88. # define HAVE_OPENAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  89. # define HAVE_READLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  90. # define HAVE_SYMLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  91. # define HAVE_FUTIMENS_RUNTIME __builtin_available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  92. # define HAVE_UTIMENSAT_RUNTIME __builtin_available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  93. # define HAVE_PWRITEV_RUNTIME __builtin_available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
  94. # define HAVE_MKFIFOAT_RUNTIME __builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
  95. # define HAVE_MKNODAT_RUNTIME __builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
  96. # define HAVE_POSIX_SPAWN_SETSID_RUNTIME __builtin_available(macOS 10.15, *)
  97. #else /* Xcode 8 or earlier */
  98. /* __builtin_available is not present in these compilers, but
  99. * some of the symbols might be weak linked (10.10 SDK or later
  100. * deploying on 10.9.
  101. *
  102. * Fall back to the older style of availability checking for
  103. * symbols introduced in macOS 10.10.
  104. */
  105. # ifdef HAVE_FSTATAT
  106. # define HAVE_FSTATAT_RUNTIME (fstatat != NULL)
  107. # endif
  108. # ifdef HAVE_FACCESSAT
  109. # define HAVE_FACCESSAT_RUNTIME (faccessat != NULL)
  110. # endif
  111. # ifdef HAVE_FCHMODAT
  112. # define HAVE_FCHMODAT_RUNTIME (fchmodat != NULL)
  113. # endif
  114. # ifdef HAVE_FCHOWNAT
  115. # define HAVE_FCHOWNAT_RUNTIME (fchownat != NULL)
  116. # endif
  117. # ifdef HAVE_LINKAT
  118. # define HAVE_LINKAT_RUNTIME (linkat != NULL)
  119. # endif
  120. # ifdef HAVE_FDOPENDIR
  121. # define HAVE_FDOPENDIR_RUNTIME (fdopendir != NULL)
  122. # endif
  123. # ifdef HAVE_MKDIRAT
  124. # define HAVE_MKDIRAT_RUNTIME (mkdirat != NULL)
  125. # endif
  126. # ifdef HAVE_RENAMEAT
  127. # define HAVE_RENAMEAT_RUNTIME (renameat != NULL)
  128. # endif
  129. # ifdef HAVE_UNLINKAT
  130. # define HAVE_UNLINKAT_RUNTIME (unlinkat != NULL)
  131. # endif
  132. # ifdef HAVE_OPENAT
  133. # define HAVE_OPENAT_RUNTIME (openat != NULL)
  134. # endif
  135. # ifdef HAVE_READLINKAT
  136. # define HAVE_READLINKAT_RUNTIME (readlinkat != NULL)
  137. # endif
  138. # ifdef HAVE_SYMLINKAT
  139. # define HAVE_SYMLINKAT_RUNTIME (symlinkat != NULL)
  140. # endif
  141. # ifdef HAVE_UTIMENSAT
  142. # define HAVE_UTIMENSAT_RUNTIME (utimensat != NULL)
  143. # endif
  144. # ifdef HAVE_FUTIMENS
  145. # define HAVE_FUTIMENS_RUNTIME (futimens != NULL)
  146. # endif
  147. # ifdef HAVE_PWRITEV
  148. # define HAVE_PWRITEV_RUNTIME (pwritev != NULL)
  149. # endif
  150. # ifdef HAVE_MKFIFOAT
  151. # define HAVE_MKFIFOAT_RUNTIME (mkfifoat != NULL)
  152. # endif
  153. # ifdef HAVE_MKNODAT
  154. # define HAVE_MKNODAT_RUNTIME (mknodat != NULL)
  155. # endif
  156. #endif
  157. #ifdef HAVE_FUTIMESAT
  158. /* Some of the logic for weak linking depends on this assertion */
  159. # error "HAVE_FUTIMESAT unexpectedly defined"
  160. #endif
  161. #else
  162. # define HAVE_FSTATAT_RUNTIME 1
  163. # define HAVE_FACCESSAT_RUNTIME 1
  164. # define HAVE_FCHMODAT_RUNTIME 1
  165. # define HAVE_FCHOWNAT_RUNTIME 1
  166. # define HAVE_LINKAT_RUNTIME 1
  167. # define HAVE_FDOPENDIR_RUNTIME 1
  168. # define HAVE_MKDIRAT_RUNTIME 1
  169. # define HAVE_RENAMEAT_RUNTIME 1
  170. # define HAVE_UNLINKAT_RUNTIME 1
  171. # define HAVE_OPENAT_RUNTIME 1
  172. # define HAVE_READLINKAT_RUNTIME 1
  173. # define HAVE_SYMLINKAT_RUNTIME 1
  174. # define HAVE_FUTIMENS_RUNTIME 1
  175. # define HAVE_UTIMENSAT_RUNTIME 1
  176. # define HAVE_PWRITEV_RUNTIME 1
  177. # define HAVE_MKFIFOAT_RUNTIME 1
  178. # define HAVE_MKNODAT_RUNTIME 1
  179. #endif
  180. #ifdef __cplusplus
  181. extern "C" {
  182. #endif
  183. PyDoc_STRVAR(posix__doc__,
  184. "This module provides access to operating system functionality that is\n\
  185. standardized by the C Standard and the POSIX standard (a thinly\n\
  186. disguised Unix interface). Refer to the library manual and\n\
  187. corresponding Unix manual entries for more information on calls.");
  188. #ifdef HAVE_SYS_UIO_H
  189. # include <sys/uio.h>
  190. #endif
  191. #ifdef HAVE_SYS_TYPES_H
  192. /* Should be included before <sys/sysmacros.h> on HP-UX v3 */
  193. # include <sys/types.h>
  194. #endif /* HAVE_SYS_TYPES_H */
  195. #ifdef HAVE_SYS_SYSMACROS_H
  196. /* GNU C Library: major(), minor(), makedev() */
  197. # include <sys/sysmacros.h>
  198. #endif
  199. #ifdef HAVE_SYS_STAT_H
  200. # include <sys/stat.h>
  201. #endif /* HAVE_SYS_STAT_H */
  202. #ifdef HAVE_SYS_WAIT_H
  203. # include <sys/wait.h> // WNOHANG
  204. #endif
  205. #ifdef HAVE_LINUX_WAIT_H
  206. # include <linux/wait.h> // P_PIDFD
  207. #endif
  208. #ifdef HAVE_SIGNAL_H
  209. # include <signal.h>
  210. #endif
  211. #ifdef HAVE_FCNTL_H
  212. # include <fcntl.h>
  213. #endif
  214. #ifdef HAVE_GRP_H
  215. # include <grp.h>
  216. #endif
  217. #ifdef HAVE_SYSEXITS_H
  218. # include <sysexits.h>
  219. #endif
  220. #if !defined(EX_OK) && defined(EXIT_SUCCESS)
  221. # define EX_OK EXIT_SUCCESS
  222. #endif
  223. #ifdef HAVE_SYS_LOADAVG_H
  224. # include <sys/loadavg.h>
  225. #endif
  226. #ifdef HAVE_SYS_SENDFILE_H
  227. # include <sys/sendfile.h>
  228. #endif
  229. #if defined(__APPLE__)
  230. # include <copyfile.h>
  231. #endif
  232. #ifdef HAVE_SCHED_H
  233. # include <sched.h>
  234. #endif
  235. #ifdef HAVE_COPY_FILE_RANGE
  236. # include <unistd.h>
  237. #endif
  238. #if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
  239. # undef HAVE_SCHED_SETAFFINITY
  240. #endif
  241. #if defined(HAVE_SYS_XATTR_H) && defined(HAVE_LINUX_LIMITS_H) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
  242. # define USE_XATTRS
  243. # include <linux/limits.h> // Needed for XATTR_SIZE_MAX on musl libc.
  244. #endif
  245. #ifdef USE_XATTRS
  246. # include <sys/xattr.h>
  247. #endif
  248. #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
  249. # ifdef HAVE_SYS_SOCKET_H
  250. # include <sys/socket.h>
  251. # endif
  252. #endif
  253. #ifdef HAVE_DLFCN_H
  254. # include <dlfcn.h>
  255. #endif
  256. #ifdef __hpux
  257. # include <sys/mpctl.h>
  258. #endif
  259. #if defined(__DragonFly__) || \
  260. defined(__OpenBSD__) || \
  261. defined(__FreeBSD__) || \
  262. defined(__NetBSD__) || \
  263. defined(__APPLE__)
  264. # include <sys/sysctl.h>
  265. #endif
  266. #ifdef HAVE_LINUX_RANDOM_H
  267. # include <linux/random.h>
  268. #endif
  269. #ifdef HAVE_GETRANDOM_SYSCALL
  270. # include <sys/syscall.h>
  271. # include <sys/random.h>
  272. #endif
  273. #ifdef HAVE_WINDOWS_CONSOLE_IO
  274. # define TERMSIZE_USE_CONIO
  275. #elif defined(HAVE_SYS_IOCTL_H)
  276. # include <sys/ioctl.h>
  277. # if defined(HAVE_TERMIOS_H)
  278. # include <termios.h>
  279. # endif
  280. # if defined(TIOCGWINSZ)
  281. # define TERMSIZE_USE_IOCTL
  282. # endif
  283. #endif /* HAVE_WINDOWS_CONSOLE_IO */
  284. /* Various compilers have only certain posix functions */
  285. /* XXX Gosh I wish these were all moved into pyconfig.h */
  286. #if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
  287. # define HAVE_OPENDIR 1
  288. # define HAVE_SYSTEM 1
  289. # include <process.h>
  290. #elif defined( _MSC_VER)
  291. /* Microsoft compiler */
  292. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
  293. # define HAVE_GETPPID 1
  294. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_APP | MS_WINDOWS_SYSTEM */
  295. # if defined(MS_WINDOWS_DESKTOP)
  296. # define HAVE_GETLOGIN 1
  297. # endif /* MS_WINDOWS_DESKTOP */
  298. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  299. # define HAVE_SPAWNV 1
  300. # define HAVE_EXECV 1
  301. # define HAVE_WSPAWNV 1
  302. # define HAVE_WEXECV 1
  303. # define HAVE_SYSTEM 1
  304. # define HAVE_CWAIT 1
  305. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_SYSTEM */
  306. # define HAVE_PIPE 1
  307. # define HAVE_FSYNC 1
  308. # define fsync _commit
  309. #endif /* ! __WATCOMC__ || __QNX__ */
  310. /*[clinic input]
  311. # one of the few times we lie about this name!
  312. module os
  313. [clinic start generated code]*/
  314. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
  315. #ifndef _MSC_VER
  316. #if defined(__sgi)&&_COMPILER_VERSION>=700
  317. /* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
  318. (default) */
  319. extern char *ctermid_r(char *);
  320. #endif
  321. #endif /* !_MSC_VER */
  322. #if defined(__VXWORKS__)
  323. # error #include <vxCpuLib.h>
  324. # error #include <rtpLib.h>
  325. # include <wait.h>
  326. # error #include <taskLib.h>
  327. # ifndef _P_WAIT
  328. # define _P_WAIT 0
  329. # define _P_NOWAIT 1
  330. # define _P_NOWAITO 1
  331. # endif
  332. #endif /* __VXWORKS__ */
  333. #ifdef HAVE_POSIX_SPAWN
  334. # include <spawn.h>
  335. #endif
  336. #ifdef HAVE_UTIME_H
  337. # include <utime.h>
  338. #endif /* HAVE_UTIME_H */
  339. #ifdef HAVE_SYS_UTIME_H
  340. # include <sys/utime.h>
  341. # define HAVE_UTIME_H /* pretend we do for the rest of this file */
  342. #endif /* HAVE_SYS_UTIME_H */
  343. #ifdef HAVE_SYS_TIMES_H
  344. # include <sys/times.h>
  345. #endif /* HAVE_SYS_TIMES_H */
  346. #ifdef HAVE_SYS_PARAM_H
  347. # include <sys/param.h>
  348. #endif /* HAVE_SYS_PARAM_H */
  349. #ifdef HAVE_SYS_UTSNAME_H
  350. # include <sys/utsname.h>
  351. #endif /* HAVE_SYS_UTSNAME_H */
  352. #ifdef HAVE_DIRENT_H
  353. # include <dirent.h>
  354. # define NAMLEN(dirent) strlen((dirent)->d_name)
  355. #else
  356. # if defined(__WATCOMC__) && !defined(__QNX__)
  357. # include <direct.h>
  358. # define NAMLEN(dirent) strlen((dirent)->d_name)
  359. # else
  360. # define dirent direct
  361. # define NAMLEN(dirent) (dirent)->d_namlen
  362. # endif
  363. # ifdef HAVE_SYS_NDIR_H
  364. # include <sys/ndir.h>
  365. # endif
  366. # ifdef HAVE_SYS_DIR_H
  367. # include <sys/dir.h>
  368. # endif
  369. # ifdef HAVE_NDIR_H
  370. # include <ndir.h>
  371. # endif
  372. #endif
  373. #ifdef _MSC_VER
  374. # ifdef HAVE_DIRECT_H
  375. # include <direct.h>
  376. # endif
  377. # ifdef HAVE_IO_H
  378. # include <io.h>
  379. # endif
  380. # ifdef HAVE_PROCESS_H
  381. # include <process.h>
  382. # endif
  383. # include <malloc.h>
  384. #endif /* _MSC_VER */
  385. #ifndef MAXPATHLEN
  386. # if defined(PATH_MAX) && PATH_MAX > 1024
  387. # define MAXPATHLEN PATH_MAX
  388. # else
  389. # define MAXPATHLEN 1024
  390. # endif
  391. #endif /* MAXPATHLEN */
  392. #ifdef UNION_WAIT
  393. /* Emulate some macros on systems that have a union instead of macros */
  394. # ifndef WIFEXITED
  395. # define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
  396. # endif
  397. # ifndef WEXITSTATUS
  398. # define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
  399. # endif
  400. # ifndef WTERMSIG
  401. # define WTERMSIG(u_wait) ((u_wait).w_termsig)
  402. # endif
  403. # define WAIT_TYPE union wait
  404. # define WAIT_STATUS_INT(s) (s.w_status)
  405. #else
  406. /* !UNION_WAIT */
  407. # define WAIT_TYPE int
  408. # define WAIT_STATUS_INT(s) (s)
  409. #endif /* UNION_WAIT */
  410. /* Don't use the "_r" form if we don't need it (also, won't have a
  411. prototype for it, at least on Solaris -- maybe others as well?). */
  412. #if defined(HAVE_CTERMID_R)
  413. # define USE_CTERMID_R
  414. #endif
  415. /* choose the appropriate stat and fstat functions and return structs */
  416. #undef STAT
  417. #undef FSTAT
  418. #undef STRUCT_STAT
  419. #ifdef MS_WINDOWS
  420. # define STAT win32_stat
  421. # define LSTAT win32_lstat
  422. # define FSTAT _Py_fstat_noraise
  423. # define STRUCT_STAT struct _Py_stat_struct
  424. #else
  425. # define STAT stat
  426. # define LSTAT lstat
  427. # define FSTAT fstat
  428. # define STRUCT_STAT struct stat
  429. #endif
  430. #if defined(MAJOR_IN_MKDEV)
  431. # include <sys/mkdev.h>
  432. #else
  433. # if defined(MAJOR_IN_SYSMACROS)
  434. # include <sys/sysmacros.h>
  435. # endif
  436. # if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
  437. # include <sys/mkdev.h>
  438. # endif
  439. #endif
  440. #ifdef MS_WINDOWS
  441. # define INITFUNC PyInit_nt
  442. # define MODNAME "nt"
  443. # define MODNAME_OBJ &_Py_ID(nt)
  444. #else
  445. # define INITFUNC PyInit_posix
  446. # define MODNAME "posix"
  447. # define MODNAME_OBJ &_Py_ID(posix)
  448. #endif
  449. #if defined(__sun)
  450. /* Something to implement in autoconf, not present in autoconf 2.69 */
  451. # define HAVE_STRUCT_STAT_ST_FSTYPE 1
  452. #endif
  453. /* memfd_create is either defined in sys/mman.h or sys/memfd.h
  454. * linux/memfd.h defines additional flags
  455. */
  456. #ifdef HAVE_SYS_MMAN_H
  457. # include <sys/mman.h>
  458. #endif
  459. #ifdef HAVE_SYS_MEMFD_H
  460. # error #include <sys/memfd.h>
  461. #endif
  462. #ifdef HAVE_LINUX_MEMFD_H
  463. # include <linux/memfd.h>
  464. #endif
  465. /* eventfd() */
  466. #ifdef HAVE_SYS_EVENTFD_H
  467. # include <sys/eventfd.h>
  468. #endif
  469. #ifdef _Py_MEMORY_SANITIZER
  470. # include <sanitizer/msan_interface.h>
  471. #endif
  472. #ifdef HAVE_FORK
  473. static void
  474. run_at_forkers(PyObject *lst, int reverse)
  475. {
  476. Py_ssize_t i;
  477. PyObject *cpy;
  478. if (lst != NULL) {
  479. assert(PyList_CheckExact(lst));
  480. /* Use a list copy in case register_at_fork() is called from
  481. * one of the callbacks.
  482. */
  483. cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
  484. if (cpy == NULL)
  485. PyErr_WriteUnraisable(lst);
  486. else {
  487. if (reverse)
  488. PyList_Reverse(cpy);
  489. for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
  490. PyObject *func, *res;
  491. func = PyList_GET_ITEM(cpy, i);
  492. res = _PyObject_CallNoArgs(func);
  493. if (res == NULL)
  494. PyErr_WriteUnraisable(func);
  495. else
  496. Py_DECREF(res);
  497. }
  498. Py_DECREF(cpy);
  499. }
  500. }
  501. }
  502. void
  503. PyOS_BeforeFork(void)
  504. {
  505. PyInterpreterState *interp = _PyInterpreterState_GET();
  506. run_at_forkers(interp->before_forkers, 1);
  507. _PyImport_AcquireLock(interp);
  508. }
  509. void
  510. PyOS_AfterFork_Parent(void)
  511. {
  512. PyInterpreterState *interp = _PyInterpreterState_GET();
  513. if (_PyImport_ReleaseLock(interp) <= 0) {
  514. Py_FatalError("failed releasing import lock after fork");
  515. }
  516. run_at_forkers(interp->after_forkers_parent, 0);
  517. }
  518. void
  519. PyOS_AfterFork_Child(void)
  520. {
  521. PyStatus status;
  522. _PyRuntimeState *runtime = &_PyRuntime;
  523. status = _PyRuntimeState_ReInitThreads(runtime);
  524. if (_PyStatus_EXCEPTION(status)) {
  525. goto fatal_error;
  526. }
  527. PyThreadState *tstate = _PyThreadState_GET();
  528. _Py_EnsureTstateNotNULL(tstate);
  529. #ifdef PY_HAVE_THREAD_NATIVE_ID
  530. tstate->native_thread_id = PyThread_get_thread_native_id();
  531. #endif
  532. status = _PyEval_ReInitThreads(tstate);
  533. if (_PyStatus_EXCEPTION(status)) {
  534. goto fatal_error;
  535. }
  536. status = _PyImport_ReInitLock(tstate->interp);
  537. if (_PyStatus_EXCEPTION(status)) {
  538. goto fatal_error;
  539. }
  540. _PySignal_AfterFork();
  541. status = _PyInterpreterState_DeleteExceptMain(runtime);
  542. if (_PyStatus_EXCEPTION(status)) {
  543. goto fatal_error;
  544. }
  545. assert(_PyThreadState_GET() == tstate);
  546. status = _PyPerfTrampoline_AfterFork_Child();
  547. if (_PyStatus_EXCEPTION(status)) {
  548. goto fatal_error;
  549. }
  550. run_at_forkers(tstate->interp->after_forkers_child, 0);
  551. return;
  552. fatal_error:
  553. Py_ExitStatusException(status);
  554. }
  555. static int
  556. register_at_forker(PyObject **lst, PyObject *func)
  557. {
  558. if (func == NULL) /* nothing to register? do nothing. */
  559. return 0;
  560. if (*lst == NULL) {
  561. *lst = PyList_New(0);
  562. if (*lst == NULL)
  563. return -1;
  564. }
  565. return PyList_Append(*lst, func);
  566. }
  567. #endif /* HAVE_FORK */
  568. /* Legacy wrapper */
  569. void
  570. PyOS_AfterFork(void)
  571. {
  572. #ifdef HAVE_FORK
  573. PyOS_AfterFork_Child();
  574. #endif
  575. }
  576. #ifdef MS_WINDOWS
  577. /* defined in fileutils.c */
  578. void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
  579. void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *, ULONG,
  580. FILE_BASIC_INFO *, FILE_ID_INFO *,
  581. struct _Py_stat_struct *);
  582. void _Py_stat_basic_info_to_stat(FILE_STAT_BASIC_INFORMATION *,
  583. struct _Py_stat_struct *);
  584. #endif
  585. #ifndef MS_WINDOWS
  586. PyObject *
  587. _PyLong_FromUid(uid_t uid)
  588. {
  589. if (uid == (uid_t)-1)
  590. return PyLong_FromLong(-1);
  591. return PyLong_FromUnsignedLong(uid);
  592. }
  593. PyObject *
  594. _PyLong_FromGid(gid_t gid)
  595. {
  596. if (gid == (gid_t)-1)
  597. return PyLong_FromLong(-1);
  598. return PyLong_FromUnsignedLong(gid);
  599. }
  600. int
  601. _Py_Uid_Converter(PyObject *obj, uid_t *p)
  602. {
  603. uid_t uid;
  604. PyObject *index;
  605. int overflow;
  606. long result;
  607. unsigned long uresult;
  608. index = _PyNumber_Index(obj);
  609. if (index == NULL) {
  610. PyErr_Format(PyExc_TypeError,
  611. "uid should be integer, not %.200s",
  612. _PyType_Name(Py_TYPE(obj)));
  613. return 0;
  614. }
  615. /*
  616. * Handling uid_t is complicated for two reasons:
  617. * * Although uid_t is (always?) unsigned, it still
  618. * accepts -1.
  619. * * We don't know its size in advance--it may be
  620. * bigger than an int, or it may be smaller than
  621. * a long.
  622. *
  623. * So a bit of defensive programming is in order.
  624. * Start with interpreting the value passed
  625. * in as a signed long and see if it works.
  626. */
  627. result = PyLong_AsLongAndOverflow(index, &overflow);
  628. if (!overflow) {
  629. uid = (uid_t)result;
  630. if (result == -1) {
  631. if (PyErr_Occurred())
  632. goto fail;
  633. /* It's a legitimate -1, we're done. */
  634. goto success;
  635. }
  636. /* Any other negative number is disallowed. */
  637. if (result < 0)
  638. goto underflow;
  639. /* Ensure the value wasn't truncated. */
  640. if (sizeof(uid_t) < sizeof(long) &&
  641. (long)uid != result)
  642. goto underflow;
  643. goto success;
  644. }
  645. if (overflow < 0)
  646. goto underflow;
  647. /*
  648. * Okay, the value overflowed a signed long. If it
  649. * fits in an *unsigned* long, it may still be okay,
  650. * as uid_t may be unsigned long on this platform.
  651. */
  652. uresult = PyLong_AsUnsignedLong(index);
  653. if (PyErr_Occurred()) {
  654. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  655. goto overflow;
  656. goto fail;
  657. }
  658. uid = (uid_t)uresult;
  659. /*
  660. * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
  661. * but this value would get interpreted as (uid_t)-1 by chown
  662. * and its siblings. That's not what the user meant! So we
  663. * throw an overflow exception instead. (We already
  664. * handled a real -1 with PyLong_AsLongAndOverflow() above.)
  665. */
  666. if (uid == (uid_t)-1)
  667. goto overflow;
  668. /* Ensure the value wasn't truncated. */
  669. if (sizeof(uid_t) < sizeof(long) &&
  670. (unsigned long)uid != uresult)
  671. goto overflow;
  672. /* fallthrough */
  673. success:
  674. Py_DECREF(index);
  675. *p = uid;
  676. return 1;
  677. underflow:
  678. PyErr_SetString(PyExc_OverflowError,
  679. "uid is less than minimum");
  680. goto fail;
  681. overflow:
  682. PyErr_SetString(PyExc_OverflowError,
  683. "uid is greater than maximum");
  684. /* fallthrough */
  685. fail:
  686. Py_DECREF(index);
  687. return 0;
  688. }
  689. int
  690. _Py_Gid_Converter(PyObject *obj, gid_t *p)
  691. {
  692. gid_t gid;
  693. PyObject *index;
  694. int overflow;
  695. long result;
  696. unsigned long uresult;
  697. index = _PyNumber_Index(obj);
  698. if (index == NULL) {
  699. PyErr_Format(PyExc_TypeError,
  700. "gid should be integer, not %.200s",
  701. _PyType_Name(Py_TYPE(obj)));
  702. return 0;
  703. }
  704. /*
  705. * Handling gid_t is complicated for two reasons:
  706. * * Although gid_t is (always?) unsigned, it still
  707. * accepts -1.
  708. * * We don't know its size in advance--it may be
  709. * bigger than an int, or it may be smaller than
  710. * a long.
  711. *
  712. * So a bit of defensive programming is in order.
  713. * Start with interpreting the value passed
  714. * in as a signed long and see if it works.
  715. */
  716. result = PyLong_AsLongAndOverflow(index, &overflow);
  717. if (!overflow) {
  718. gid = (gid_t)result;
  719. if (result == -1) {
  720. if (PyErr_Occurred())
  721. goto fail;
  722. /* It's a legitimate -1, we're done. */
  723. goto success;
  724. }
  725. /* Any other negative number is disallowed. */
  726. if (result < 0) {
  727. goto underflow;
  728. }
  729. /* Ensure the value wasn't truncated. */
  730. if (sizeof(gid_t) < sizeof(long) &&
  731. (long)gid != result)
  732. goto underflow;
  733. goto success;
  734. }
  735. if (overflow < 0)
  736. goto underflow;
  737. /*
  738. * Okay, the value overflowed a signed long. If it
  739. * fits in an *unsigned* long, it may still be okay,
  740. * as gid_t may be unsigned long on this platform.
  741. */
  742. uresult = PyLong_AsUnsignedLong(index);
  743. if (PyErr_Occurred()) {
  744. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  745. goto overflow;
  746. goto fail;
  747. }
  748. gid = (gid_t)uresult;
  749. /*
  750. * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
  751. * but this value would get interpreted as (gid_t)-1 by chown
  752. * and its siblings. That's not what the user meant! So we
  753. * throw an overflow exception instead. (We already
  754. * handled a real -1 with PyLong_AsLongAndOverflow() above.)
  755. */
  756. if (gid == (gid_t)-1)
  757. goto overflow;
  758. /* Ensure the value wasn't truncated. */
  759. if (sizeof(gid_t) < sizeof(long) &&
  760. (unsigned long)gid != uresult)
  761. goto overflow;
  762. /* fallthrough */
  763. success:
  764. Py_DECREF(index);
  765. *p = gid;
  766. return 1;
  767. underflow:
  768. PyErr_SetString(PyExc_OverflowError,
  769. "gid is less than minimum");
  770. goto fail;
  771. overflow:
  772. PyErr_SetString(PyExc_OverflowError,
  773. "gid is greater than maximum");
  774. /* fallthrough */
  775. fail:
  776. Py_DECREF(index);
  777. return 0;
  778. }
  779. #endif /* MS_WINDOWS */
  780. static PyObject *
  781. _PyLong_FromDev(dev_t dev)
  782. {
  783. #ifdef NODEV
  784. if (dev == NODEV) {
  785. return PyLong_FromLongLong((long long)dev);
  786. }
  787. #endif
  788. return PyLong_FromUnsignedLongLong((unsigned long long)dev);
  789. }
  790. #if (defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)) || defined(HAVE_DEVICE_MACROS)
  791. static int
  792. _Py_Dev_Converter(PyObject *obj, void *p)
  793. {
  794. #ifdef NODEV
  795. if (PyLong_Check(obj) && _PyLong_IsNegative((PyLongObject *)obj)) {
  796. int overflow;
  797. long long result = PyLong_AsLongLongAndOverflow(obj, &overflow);
  798. if (result == -1 && PyErr_Occurred()) {
  799. return 0;
  800. }
  801. if (!overflow && result == (long long)NODEV) {
  802. *((dev_t *)p) = NODEV;
  803. return 1;
  804. }
  805. }
  806. #endif
  807. unsigned long long result = PyLong_AsUnsignedLongLong(obj);
  808. if (result == (unsigned long long)-1 && PyErr_Occurred()) {
  809. return 0;
  810. }
  811. if ((unsigned long long)(dev_t)result != result) {
  812. PyErr_SetString(PyExc_OverflowError,
  813. "Python int too large to convert to C dev_t");
  814. return 0;
  815. }
  816. *((dev_t *)p) = (dev_t)result;
  817. return 1;
  818. }
  819. #endif /* (HAVE_MKNOD && HAVE_MAKEDEV) || HAVE_DEVICE_MACROS */
  820. #ifdef AT_FDCWD
  821. /*
  822. * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
  823. * without the int cast, the value gets interpreted as uint (4291925331),
  824. * which doesn't play nicely with all the initializer lines in this file that
  825. * look like this:
  826. * int dir_fd = DEFAULT_DIR_FD;
  827. */
  828. #define DEFAULT_DIR_FD (int)AT_FDCWD
  829. #else
  830. #define DEFAULT_DIR_FD (-100)
  831. #endif
  832. static int
  833. _fd_converter(PyObject *o, int *p)
  834. {
  835. int overflow;
  836. long long_value;
  837. PyObject *index = _PyNumber_Index(o);
  838. if (index == NULL) {
  839. return 0;
  840. }
  841. assert(PyLong_Check(index));
  842. long_value = PyLong_AsLongAndOverflow(index, &overflow);
  843. Py_DECREF(index);
  844. assert(!PyErr_Occurred());
  845. if (overflow > 0 || long_value > INT_MAX) {
  846. PyErr_SetString(PyExc_OverflowError,
  847. "fd is greater than maximum");
  848. return 0;
  849. }
  850. if (overflow < 0 || long_value < INT_MIN) {
  851. PyErr_SetString(PyExc_OverflowError,
  852. "fd is less than minimum");
  853. return 0;
  854. }
  855. *p = (int)long_value;
  856. return 1;
  857. }
  858. static int
  859. dir_fd_converter(PyObject *o, void *p)
  860. {
  861. if (o == Py_None) {
  862. *(int *)p = DEFAULT_DIR_FD;
  863. return 1;
  864. }
  865. else if (PyIndex_Check(o)) {
  866. return _fd_converter(o, (int *)p);
  867. }
  868. else {
  869. PyErr_Format(PyExc_TypeError,
  870. "argument should be integer or None, not %.200s",
  871. _PyType_Name(Py_TYPE(o)));
  872. return 0;
  873. }
  874. }
  875. typedef struct {
  876. PyObject *billion;
  877. PyObject *DirEntryType;
  878. PyObject *ScandirIteratorType;
  879. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  880. PyObject *SchedParamType;
  881. #endif
  882. newfunc statresult_new_orig;
  883. PyObject *StatResultType;
  884. PyObject *StatVFSResultType;
  885. PyObject *TerminalSizeType;
  886. PyObject *TimesResultType;
  887. PyObject *UnameResultType;
  888. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  889. PyObject *WaitidResultType;
  890. #endif
  891. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  892. PyObject *struct_rusage;
  893. #endif
  894. PyObject *st_mode;
  895. } _posixstate;
  896. static inline _posixstate*
  897. get_posix_state(PyObject *module)
  898. {
  899. void *state = _PyModule_GetState(module);
  900. assert(state != NULL);
  901. return (_posixstate *)state;
  902. }
  903. /*
  904. * A PyArg_ParseTuple "converter" function
  905. * that handles filesystem paths in the manner
  906. * preferred by the os module.
  907. *
  908. * path_converter accepts (Unicode) strings and their
  909. * subclasses, and bytes and their subclasses. What
  910. * it does with the argument depends on path.make_wide:
  911. *
  912. * * If path.make_wide is nonzero, if we get a (Unicode)
  913. * string we extract the wchar_t * and return it; if we
  914. * get bytes we decode to wchar_t * and return that.
  915. *
  916. * * If path.make_wide is zero, if we get bytes we extract
  917. * the char_t * and return it; if we get a (Unicode)
  918. * string we encode to char_t * and return that.
  919. *
  920. * path_converter also optionally accepts signed
  921. * integers (representing open file descriptors) instead
  922. * of path strings.
  923. *
  924. * Input fields:
  925. * path.nullable
  926. * If nonzero, the path is permitted to be None.
  927. * path.nonstrict
  928. * If nonzero, the path is permitted to contain
  929. * embedded null characters and have any length.
  930. * path.make_wide
  931. * If nonzero, the converter always uses wide, decoding if necessary, else
  932. * it always uses narrow, encoding if necessary. The default value is
  933. * nonzero on Windows, else zero.
  934. * path.suppress_value_error
  935. * If nonzero, raising ValueError is suppressed.
  936. * path.allow_fd
  937. * If nonzero, the path is permitted to be a file handle
  938. * (a signed int) instead of a string.
  939. * path.function_name
  940. * If non-NULL, path_converter will use that as the name
  941. * of the function in error messages.
  942. * (If path.function_name is NULL it omits the function name.)
  943. * path.argument_name
  944. * If non-NULL, path_converter will use that as the name
  945. * of the parameter in error messages.
  946. * (If path.argument_name is NULL it uses "path".)
  947. *
  948. * Output fields:
  949. * path.wide
  950. * Points to the path if it was expressed as Unicode
  951. * or if it was bytes and decoded to Unicode.
  952. * path.narrow
  953. * Points to the path if it was expressed as bytes,
  954. * or if it was Unicode and encoded to bytes.
  955. * path.fd
  956. * Contains a file descriptor if path.accept_fd was true
  957. * and the caller provided a signed integer instead of any
  958. * sort of string.
  959. *
  960. * WARNING: if your "path" parameter is optional, and is
  961. * unspecified, path_converter will never get called.
  962. * So if you set allow_fd, you *MUST* initialize path.fd = -1
  963. * yourself!
  964. * path.value_error
  965. * If nonzero, then suppress_value_error was specified and a ValueError
  966. * occurred.
  967. * path.length
  968. * The length of the path in characters, if specified as
  969. * a string.
  970. * path.object
  971. * The original object passed in (if get a PathLike object,
  972. * the result of PyOS_FSPath() is treated as the original object).
  973. * Own a reference to the object.
  974. * path.cleanup
  975. * For internal use only. May point to a temporary object.
  976. * (Pay no attention to the man behind the curtain.)
  977. *
  978. * At most one of path.wide or path.narrow will be non-NULL.
  979. * If path was None and path.nullable was set,
  980. * or if path was an integer and path.allow_fd was set,
  981. * both path.wide and path.narrow will be NULL
  982. * and path.length will be 0.
  983. *
  984. * path_converter takes care to not write to the path_t
  985. * unless it's successful. However it must reset the
  986. * "cleanup" field each time it's called.
  987. *
  988. * Use as follows:
  989. * path_t path;
  990. * memset(&path, 0, sizeof(path));
  991. * PyArg_ParseTuple(args, "O&", path_converter, &path);
  992. * // ... use values from path ...
  993. * path_cleanup(&path);
  994. *
  995. * (Note that if PyArg_Parse fails you don't need to call
  996. * path_cleanup(). However it is safe to do so.)
  997. */
  998. typedef struct {
  999. // Input fields
  1000. const char *function_name;
  1001. const char *argument_name;
  1002. int nullable;
  1003. int nonstrict;
  1004. int make_wide;
  1005. int suppress_value_error;
  1006. int allow_fd;
  1007. // Output fields
  1008. const wchar_t *wide;
  1009. const char *narrow;
  1010. int fd;
  1011. int value_error;
  1012. Py_ssize_t length;
  1013. PyObject *object;
  1014. PyObject *cleanup;
  1015. } path_t;
  1016. #define PATH_T_INITIALIZE(function_name, argument_name, nullable, nonstrict, \
  1017. make_wide, suppress_value_error, allow_fd) \
  1018. {function_name, argument_name, nullable, nonstrict, make_wide, \
  1019. suppress_value_error, allow_fd, NULL, NULL, -1, 0, 0, NULL, NULL}
  1020. #ifdef MS_WINDOWS
  1021. #define PATH_T_INITIALIZE_P(function_name, argument_name, nullable, \
  1022. nonstrict, suppress_value_error, allow_fd) \
  1023. PATH_T_INITIALIZE(function_name, argument_name, nullable, nonstrict, 1, \
  1024. suppress_value_error, allow_fd)
  1025. #else
  1026. #define PATH_T_INITIALIZE_P(function_name, argument_name, nullable, \
  1027. nonstrict, suppress_value_error, allow_fd) \
  1028. PATH_T_INITIALIZE(function_name, argument_name, nullable, nonstrict, 0, \
  1029. suppress_value_error, allow_fd)
  1030. #endif
  1031. static void
  1032. path_cleanup(path_t *path)
  1033. {
  1034. wchar_t *wide = (wchar_t *)path->wide;
  1035. path->wide = NULL;
  1036. PyMem_Free(wide);
  1037. Py_CLEAR(path->object);
  1038. Py_CLEAR(path->cleanup);
  1039. }
  1040. static int
  1041. path_converter(PyObject *o, void *p)
  1042. {
  1043. path_t *path = (path_t *)p;
  1044. PyObject *bytes = NULL;
  1045. Py_ssize_t length = 0;
  1046. int is_index, is_bytes, is_unicode;
  1047. const char *narrow;
  1048. PyObject *wo = NULL;
  1049. wchar_t *wide = NULL;
  1050. #define FORMAT_EXCEPTION(exc, fmt) \
  1051. PyErr_Format(exc, "%s%s" fmt, \
  1052. path->function_name ? path->function_name : "", \
  1053. path->function_name ? ": " : "", \
  1054. path->argument_name ? path->argument_name : "path")
  1055. /* Py_CLEANUP_SUPPORTED support */
  1056. if (o == NULL) {
  1057. path_cleanup(path);
  1058. return 1;
  1059. }
  1060. /* Ensure it's always safe to call path_cleanup(). */
  1061. path->object = path->cleanup = NULL;
  1062. /* path->object owns a reference to the original object */
  1063. Py_INCREF(o);
  1064. if ((o == Py_None) && path->nullable) {
  1065. path->wide = NULL;
  1066. path->narrow = NULL;
  1067. path->fd = -1;
  1068. goto success_exit;
  1069. }
  1070. /* Only call this here so that we don't treat the return value of
  1071. os.fspath() as an fd or buffer. */
  1072. is_index = path->allow_fd && PyIndex_Check(o);
  1073. is_bytes = PyBytes_Check(o);
  1074. is_unicode = PyUnicode_Check(o);
  1075. if (!is_index && !is_unicode && !is_bytes) {
  1076. /* Inline PyOS_FSPath() for better error messages. */
  1077. PyObject *func, *res;
  1078. func = _PyObject_LookupSpecial(o, &_Py_ID(__fspath__));
  1079. if (NULL == func) {
  1080. goto error_format;
  1081. }
  1082. res = _PyObject_CallNoArgs(func);
  1083. Py_DECREF(func);
  1084. if (NULL == res) {
  1085. goto error_exit;
  1086. }
  1087. else if (PyUnicode_Check(res)) {
  1088. is_unicode = 1;
  1089. }
  1090. else if (PyBytes_Check(res)) {
  1091. is_bytes = 1;
  1092. }
  1093. else {
  1094. PyErr_Format(PyExc_TypeError,
  1095. "expected %.200s.__fspath__() to return str or bytes, "
  1096. "not %.200s", _PyType_Name(Py_TYPE(o)),
  1097. _PyType_Name(Py_TYPE(res)));
  1098. Py_DECREF(res);
  1099. goto error_exit;
  1100. }
  1101. /* still owns a reference to the original object */
  1102. Py_SETREF(o, res);
  1103. }
  1104. if (is_unicode) {
  1105. if (path->make_wide) {
  1106. wide = PyUnicode_AsWideCharString(o, &length);
  1107. if (!wide) {
  1108. goto error_exit;
  1109. }
  1110. #ifdef MS_WINDOWS
  1111. if (!path->nonstrict && length > 32767) {
  1112. FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
  1113. goto error_exit;
  1114. }
  1115. #endif
  1116. if (!path->nonstrict && wcslen(wide) != (size_t)length) {
  1117. FORMAT_EXCEPTION(PyExc_ValueError,
  1118. "embedded null character in %s");
  1119. goto error_exit;
  1120. }
  1121. path->wide = wide;
  1122. path->narrow = NULL;
  1123. path->fd = -1;
  1124. wide = NULL;
  1125. goto success_exit;
  1126. }
  1127. bytes = PyUnicode_EncodeFSDefault(o);
  1128. if (!bytes) {
  1129. goto error_exit;
  1130. }
  1131. }
  1132. else if (is_bytes) {
  1133. bytes = Py_NewRef(o);
  1134. }
  1135. else if (is_index) {
  1136. if (!_fd_converter(o, &path->fd)) {
  1137. goto error_exit;
  1138. }
  1139. path->wide = NULL;
  1140. path->narrow = NULL;
  1141. goto success_exit;
  1142. }
  1143. else {
  1144. error_format:
  1145. PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
  1146. path->function_name ? path->function_name : "",
  1147. path->function_name ? ": " : "",
  1148. path->argument_name ? path->argument_name : "path",
  1149. path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
  1150. "integer or None" :
  1151. path->allow_fd ? "string, bytes, os.PathLike or integer" :
  1152. path->nullable ? "string, bytes, os.PathLike or None" :
  1153. "string, bytes or os.PathLike",
  1154. _PyType_Name(Py_TYPE(o)));
  1155. goto error_exit;
  1156. }
  1157. length = PyBytes_GET_SIZE(bytes);
  1158. narrow = PyBytes_AS_STRING(bytes);
  1159. if (!path->nonstrict && strlen(narrow) != (size_t)length) {
  1160. FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
  1161. goto error_exit;
  1162. }
  1163. if (path->make_wide) {
  1164. wo = PyUnicode_DecodeFSDefaultAndSize(narrow, length);
  1165. if (!wo) {
  1166. goto error_exit;
  1167. }
  1168. wide = PyUnicode_AsWideCharString(wo, &length);
  1169. Py_DECREF(wo);
  1170. if (!wide) {
  1171. goto error_exit;
  1172. }
  1173. #ifdef MS_WINDOWS
  1174. if (!path->nonstrict && length > 32767) {
  1175. FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
  1176. goto error_exit;
  1177. }
  1178. #endif
  1179. if (!path->nonstrict && wcslen(wide) != (size_t)length) {
  1180. FORMAT_EXCEPTION(PyExc_ValueError,
  1181. "embedded null character in %s");
  1182. goto error_exit;
  1183. }
  1184. path->wide = wide;
  1185. path->narrow = NULL;
  1186. Py_DECREF(bytes);
  1187. wide = NULL;
  1188. }
  1189. else {
  1190. path->wide = NULL;
  1191. path->narrow = narrow;
  1192. if (bytes == o) {
  1193. /* Still a reference owned by path->object, don't have to
  1194. worry about path->narrow is used after free. */
  1195. Py_DECREF(bytes);
  1196. }
  1197. else {
  1198. path->cleanup = bytes;
  1199. }
  1200. }
  1201. path->fd = -1;
  1202. success_exit:
  1203. path->value_error = 0;
  1204. path->length = length;
  1205. path->object = o;
  1206. return Py_CLEANUP_SUPPORTED;
  1207. error_exit:
  1208. Py_XDECREF(o);
  1209. Py_XDECREF(bytes);
  1210. PyMem_Free(wide);
  1211. if (!path->suppress_value_error ||
  1212. !PyErr_ExceptionMatches(PyExc_ValueError))
  1213. {
  1214. return 0;
  1215. }
  1216. PyErr_Clear();
  1217. path->wide = NULL;
  1218. path->narrow = NULL;
  1219. path->fd = -1;
  1220. path->value_error = 1;
  1221. path->length = 0;
  1222. path->object = NULL;
  1223. return Py_CLEANUP_SUPPORTED;
  1224. }
  1225. static void
  1226. argument_unavailable_error(const char *function_name, const char *argument_name)
  1227. {
  1228. PyErr_Format(PyExc_NotImplementedError,
  1229. "%s%s%s unavailable on this platform",
  1230. (function_name != NULL) ? function_name : "",
  1231. (function_name != NULL) ? ": ": "",
  1232. argument_name);
  1233. }
  1234. static int
  1235. dir_fd_unavailable(PyObject *o, void *p)
  1236. {
  1237. int dir_fd;
  1238. if (!dir_fd_converter(o, &dir_fd))
  1239. return 0;
  1240. if (dir_fd != DEFAULT_DIR_FD) {
  1241. argument_unavailable_error(NULL, "dir_fd");
  1242. return 0;
  1243. }
  1244. *(int *)p = dir_fd;
  1245. return 1;
  1246. }
  1247. static int
  1248. fd_specified(const char *function_name, int fd)
  1249. {
  1250. if (fd == -1)
  1251. return 0;
  1252. argument_unavailable_error(function_name, "fd");
  1253. return 1;
  1254. }
  1255. static int
  1256. follow_symlinks_specified(const char *function_name, int follow_symlinks)
  1257. {
  1258. if (follow_symlinks)
  1259. return 0;
  1260. argument_unavailable_error(function_name, "follow_symlinks");
  1261. return 1;
  1262. }
  1263. static int
  1264. path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
  1265. {
  1266. if (!path->wide && (dir_fd != DEFAULT_DIR_FD) && !path->narrow) {
  1267. PyErr_Format(PyExc_ValueError,
  1268. "%s: can't specify dir_fd without matching path",
  1269. function_name);
  1270. return 1;
  1271. }
  1272. return 0;
  1273. }
  1274. static int
  1275. dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
  1276. {
  1277. if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
  1278. PyErr_Format(PyExc_ValueError,
  1279. "%s: can't specify both dir_fd and fd",
  1280. function_name);
  1281. return 1;
  1282. }
  1283. return 0;
  1284. }
  1285. static int
  1286. fd_and_follow_symlinks_invalid(const char *function_name, int fd,
  1287. int follow_symlinks)
  1288. {
  1289. if ((fd > 0) && (!follow_symlinks)) {
  1290. PyErr_Format(PyExc_ValueError,
  1291. "%s: cannot use fd and follow_symlinks together",
  1292. function_name);
  1293. return 1;
  1294. }
  1295. return 0;
  1296. }
  1297. static int
  1298. dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
  1299. int follow_symlinks)
  1300. {
  1301. if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
  1302. PyErr_Format(PyExc_ValueError,
  1303. "%s: cannot use dir_fd and follow_symlinks together",
  1304. function_name);
  1305. return 1;
  1306. }
  1307. return 0;
  1308. }
  1309. #ifdef MS_WINDOWS
  1310. typedef long long Py_off_t;
  1311. #else
  1312. typedef off_t Py_off_t;
  1313. #endif
  1314. static int
  1315. Py_off_t_converter(PyObject *arg, void *addr)
  1316. {
  1317. #ifdef HAVE_LARGEFILE_SUPPORT
  1318. *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
  1319. #else
  1320. *((Py_off_t *)addr) = PyLong_AsLong(arg);
  1321. #endif
  1322. if (PyErr_Occurred())
  1323. return 0;
  1324. return 1;
  1325. }
  1326. static PyObject *
  1327. PyLong_FromPy_off_t(Py_off_t offset)
  1328. {
  1329. #ifdef HAVE_LARGEFILE_SUPPORT
  1330. return PyLong_FromLongLong(offset);
  1331. #else
  1332. return PyLong_FromLong(offset);
  1333. #endif
  1334. }
  1335. #ifdef HAVE_SIGSET_T
  1336. /* Convert an iterable of integers to a sigset.
  1337. Return 1 on success, return 0 and raise an exception on error. */
  1338. int
  1339. _Py_Sigset_Converter(PyObject *obj, void *addr)
  1340. {
  1341. sigset_t *mask = (sigset_t *)addr;
  1342. PyObject *iterator, *item;
  1343. long signum;
  1344. int overflow;
  1345. // The extra parens suppress the unreachable-code warning with clang on MacOS
  1346. if (sigemptyset(mask) < (0)) {
  1347. /* Probably only if mask == NULL. */
  1348. PyErr_SetFromErrno(PyExc_OSError);
  1349. return 0;
  1350. }
  1351. iterator = PyObject_GetIter(obj);
  1352. if (iterator == NULL) {
  1353. return 0;
  1354. }
  1355. while ((item = PyIter_Next(iterator)) != NULL) {
  1356. signum = PyLong_AsLongAndOverflow(item, &overflow);
  1357. Py_DECREF(item);
  1358. if (signum <= 0 || signum >= Py_NSIG) {
  1359. if (overflow || signum != -1 || !PyErr_Occurred()) {
  1360. PyErr_Format(PyExc_ValueError,
  1361. "signal number %ld out of range [1; %i]",
  1362. signum, Py_NSIG - 1);
  1363. }
  1364. goto error;
  1365. }
  1366. if (sigaddset(mask, (int)signum)) {
  1367. if (errno != EINVAL) {
  1368. /* Probably impossible */
  1369. PyErr_SetFromErrno(PyExc_OSError);
  1370. goto error;
  1371. }
  1372. /* For backwards compatibility, allow idioms such as
  1373. * `range(1, NSIG)` but warn about invalid signal numbers
  1374. */
  1375. const char msg[] =
  1376. "invalid signal number %ld, please use valid_signals()";
  1377. if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
  1378. goto error;
  1379. }
  1380. }
  1381. }
  1382. if (!PyErr_Occurred()) {
  1383. Py_DECREF(iterator);
  1384. return 1;
  1385. }
  1386. error:
  1387. Py_DECREF(iterator);
  1388. return 0;
  1389. }
  1390. #endif /* HAVE_SIGSET_T */
  1391. /* Return a dictionary corresponding to the POSIX environment table */
  1392. #if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
  1393. /* On Darwin/MacOSX a shared library or framework has no access to
  1394. ** environ directly, we must obtain it with _NSGetEnviron(). See also
  1395. ** man environ(7).
  1396. */
  1397. #include <crt_externs.h>
  1398. #elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
  1399. extern char **environ;
  1400. #endif /* !_MSC_VER */
  1401. static PyObject *
  1402. convertenviron(void)
  1403. {
  1404. PyObject *d;
  1405. #ifdef MS_WINDOWS
  1406. wchar_t **e;
  1407. #else
  1408. char **e;
  1409. #endif
  1410. d = PyDict_New();
  1411. if (d == NULL)
  1412. return NULL;
  1413. #ifdef MS_WINDOWS
  1414. /* _wenviron must be initialized in this way if the program is started
  1415. through main() instead of wmain(). */
  1416. (void)_wgetenv(L"");
  1417. e = _wenviron;
  1418. #elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
  1419. /* environ is not accessible as an extern in a shared object on OSX; use
  1420. _NSGetEnviron to resolve it. The value changes if you add environment
  1421. variables between calls to Py_Initialize, so don't cache the value. */
  1422. e = *_NSGetEnviron();
  1423. #else
  1424. e = environ;
  1425. #endif
  1426. if (e == NULL)
  1427. return d;
  1428. for (; *e != NULL; e++) {
  1429. PyObject *k;
  1430. PyObject *v;
  1431. #ifdef MS_WINDOWS
  1432. const wchar_t *p = wcschr(*e, L'=');
  1433. #else
  1434. const char *p = strchr(*e, '=');
  1435. #endif
  1436. if (p == NULL)
  1437. continue;
  1438. #ifdef MS_WINDOWS
  1439. k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
  1440. #else
  1441. k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
  1442. #endif
  1443. if (k == NULL) {
  1444. Py_DECREF(d);
  1445. return NULL;
  1446. }
  1447. #ifdef MS_WINDOWS
  1448. v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
  1449. #else
  1450. v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
  1451. #endif
  1452. if (v == NULL) {
  1453. Py_DECREF(k);
  1454. Py_DECREF(d);
  1455. return NULL;
  1456. }
  1457. if (PyDict_SetDefault(d, k, v) == NULL) {
  1458. Py_DECREF(v);
  1459. Py_DECREF(k);
  1460. Py_DECREF(d);
  1461. return NULL;
  1462. }
  1463. Py_DECREF(k);
  1464. Py_DECREF(v);
  1465. }
  1466. return d;
  1467. }
  1468. /* Set a POSIX-specific error from errno, and return NULL */
  1469. static PyObject *
  1470. posix_error(void)
  1471. {
  1472. return PyErr_SetFromErrno(PyExc_OSError);
  1473. }
  1474. #ifdef MS_WINDOWS
  1475. static PyObject *
  1476. win32_error(const char* function, const char* filename)
  1477. {
  1478. /* XXX We should pass the function name along in the future.
  1479. (winreg.c also wants to pass the function name.)
  1480. This would however require an additional param to the
  1481. Windows error object, which is non-trivial.
  1482. */
  1483. errno = GetLastError();
  1484. if (filename)
  1485. return PyErr_SetFromWindowsErrWithFilename(errno, filename);
  1486. else
  1487. return PyErr_SetFromWindowsErr(errno);
  1488. }
  1489. static PyObject *
  1490. win32_error_object_err(const char* function, PyObject* filename, DWORD err)
  1491. {
  1492. /* XXX - see win32_error for comments on 'function' */
  1493. if (filename)
  1494. return PyErr_SetExcFromWindowsErrWithFilenameObject(
  1495. PyExc_OSError,
  1496. err,
  1497. filename);
  1498. else
  1499. return PyErr_SetFromWindowsErr(err);
  1500. }
  1501. static PyObject *
  1502. win32_error_object(const char* function, PyObject* filename)
  1503. {
  1504. errno = GetLastError();
  1505. return win32_error_object_err(function, filename, errno);
  1506. }
  1507. #endif /* MS_WINDOWS */
  1508. static PyObject *
  1509. posix_path_object_error(PyObject *path)
  1510. {
  1511. return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
  1512. }
  1513. static PyObject *
  1514. path_object_error(PyObject *path)
  1515. {
  1516. #ifdef MS_WINDOWS
  1517. return PyErr_SetExcFromWindowsErrWithFilenameObject(
  1518. PyExc_OSError, 0, path);
  1519. #else
  1520. return posix_path_object_error(path);
  1521. #endif
  1522. }
  1523. static PyObject *
  1524. path_object_error2(PyObject *path, PyObject *path2)
  1525. {
  1526. #ifdef MS_WINDOWS
  1527. return PyErr_SetExcFromWindowsErrWithFilenameObjects(
  1528. PyExc_OSError, 0, path, path2);
  1529. #else
  1530. return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
  1531. #endif
  1532. }
  1533. static PyObject *
  1534. path_error(path_t *path)
  1535. {
  1536. return path_object_error(path->object);
  1537. }
  1538. static PyObject *
  1539. posix_path_error(path_t *path)
  1540. {
  1541. return posix_path_object_error(path->object);
  1542. }
  1543. static PyObject *
  1544. path_error2(path_t *path, path_t *path2)
  1545. {
  1546. return path_object_error2(path->object, path2->object);
  1547. }
  1548. /* POSIX generic methods */
  1549. static PyObject *
  1550. posix_fildes_fd(int fd, int (*func)(int))
  1551. {
  1552. int res;
  1553. int async_err = 0;
  1554. do {
  1555. Py_BEGIN_ALLOW_THREADS
  1556. _Py_BEGIN_SUPPRESS_IPH
  1557. res = (*func)(fd);
  1558. _Py_END_SUPPRESS_IPH
  1559. Py_END_ALLOW_THREADS
  1560. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1561. if (res != 0)
  1562. return (!async_err) ? posix_error() : NULL;
  1563. Py_RETURN_NONE;
  1564. }
  1565. #ifdef MS_WINDOWS
  1566. /* This is a reimplementation of the C library's chdir function,
  1567. but one that produces Win32 errors instead of DOS error codes.
  1568. chdir is essentially a wrapper around SetCurrentDirectory; however,
  1569. it also needs to set "magic" environment variables indicating
  1570. the per-drive current directory, which are of the form =<drive>: */
  1571. static BOOL __stdcall
  1572. win32_wchdir(LPCWSTR path)
  1573. {
  1574. wchar_t path_buf[MAX_PATH], *new_path = path_buf;
  1575. int result;
  1576. wchar_t env[4] = L"=x:";
  1577. if(!SetCurrentDirectoryW(path))
  1578. return FALSE;
  1579. result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
  1580. if (!result)
  1581. return FALSE;
  1582. if (result > Py_ARRAY_LENGTH(path_buf)) {
  1583. new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
  1584. if (!new_path) {
  1585. SetLastError(ERROR_OUTOFMEMORY);
  1586. return FALSE;
  1587. }
  1588. result = GetCurrentDirectoryW(result, new_path);
  1589. if (!result) {
  1590. PyMem_RawFree(new_path);
  1591. return FALSE;
  1592. }
  1593. }
  1594. int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
  1595. wcsncmp(new_path, L"//", 2) == 0);
  1596. if (!is_unc_like_path) {
  1597. env[1] = new_path[0];
  1598. result = SetEnvironmentVariableW(env, new_path);
  1599. }
  1600. if (new_path != path_buf)
  1601. PyMem_RawFree(new_path);
  1602. return result ? TRUE : FALSE;
  1603. }
  1604. #endif
  1605. #ifdef MS_WINDOWS
  1606. /* The CRT of Windows has a number of flaws wrt. its stat() implementation:
  1607. - time stamps are restricted to second resolution
  1608. - file modification times suffer from forth-and-back conversions between
  1609. UTC and local time
  1610. Therefore, we implement our own stat, based on the Win32 API directly.
  1611. */
  1612. #define HAVE_STAT_NSEC 1
  1613. #define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
  1614. #define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
  1615. static void
  1616. find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
  1617. BY_HANDLE_FILE_INFORMATION *info,
  1618. ULONG *reparse_tag)
  1619. {
  1620. memset(info, 0, sizeof(*info));
  1621. info->dwFileAttributes = pFileData->dwFileAttributes;
  1622. info->ftCreationTime = pFileData->ftCreationTime;
  1623. info->ftLastAccessTime = pFileData->ftLastAccessTime;
  1624. info->ftLastWriteTime = pFileData->ftLastWriteTime;
  1625. info->nFileSizeHigh = pFileData->nFileSizeHigh;
  1626. info->nFileSizeLow = pFileData->nFileSizeLow;
  1627. /* info->nNumberOfLinks = 1; */
  1628. if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
  1629. *reparse_tag = pFileData->dwReserved0;
  1630. else
  1631. *reparse_tag = 0;
  1632. }
  1633. static BOOL
  1634. attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
  1635. {
  1636. HANDLE hFindFile;
  1637. WIN32_FIND_DATAW FileData;
  1638. LPCWSTR filename = pszFile;
  1639. size_t n = wcslen(pszFile);
  1640. if (n && (pszFile[n - 1] == L'\\' || pszFile[n - 1] == L'/')) {
  1641. // cannot use PyMem_Malloc here because we do not hold the GIL
  1642. filename = (LPCWSTR)malloc((n + 1) * sizeof(filename[0]));
  1643. if(!filename) {
  1644. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1645. return FALSE;
  1646. }
  1647. wcsncpy_s((LPWSTR)filename, n + 1, pszFile, n);
  1648. while (--n > 0 && (filename[n] == L'\\' || filename[n] == L'/')) {
  1649. ((LPWSTR)filename)[n] = L'\0';
  1650. }
  1651. if (!n || (n == 1 && filename[1] == L':')) {
  1652. // Nothing left to query
  1653. free((void *)filename);
  1654. return FALSE;
  1655. }
  1656. }
  1657. hFindFile = FindFirstFileW(filename, &FileData);
  1658. if (pszFile != filename) {
  1659. free((void *)filename);
  1660. }
  1661. if (hFindFile == INVALID_HANDLE_VALUE) {
  1662. return FALSE;
  1663. }
  1664. FindClose(hFindFile);
  1665. find_data_to_file_info(&FileData, info, reparse_tag);
  1666. return TRUE;
  1667. }
  1668. static void
  1669. update_st_mode_from_path(const wchar_t *path, DWORD attr,
  1670. struct _Py_stat_struct *result)
  1671. {
  1672. if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) {
  1673. /* Fix the file execute permissions. This hack sets S_IEXEC if
  1674. the filename has an extension that is commonly used by files
  1675. that CreateProcessW can execute. A real implementation calls
  1676. GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
  1677. AccessCheck to check for generic read, write, and execute
  1678. access. */
  1679. const wchar_t *fileExtension = wcsrchr(path, '.');
  1680. if (fileExtension) {
  1681. if (_wcsicmp(fileExtension, L".exe") == 0 ||
  1682. _wcsicmp(fileExtension, L".bat") == 0 ||
  1683. _wcsicmp(fileExtension, L".cmd") == 0 ||
  1684. _wcsicmp(fileExtension, L".com") == 0) {
  1685. result->st_mode |= 0111;
  1686. }
  1687. }
  1688. }
  1689. }
  1690. static int
  1691. win32_xstat_slow_impl(const wchar_t *path, struct _Py_stat_struct *result,
  1692. BOOL traverse)
  1693. {
  1694. HANDLE hFile;
  1695. BY_HANDLE_FILE_INFORMATION fileInfo;
  1696. FILE_BASIC_INFO basicInfo;
  1697. FILE_BASIC_INFO *pBasicInfo = NULL;
  1698. FILE_ID_INFO idInfo;
  1699. FILE_ID_INFO *pIdInfo = NULL;
  1700. FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
  1701. DWORD fileType, error;
  1702. BOOL isUnhandledTag = FALSE;
  1703. int retval = 0;
  1704. DWORD access = FILE_READ_ATTRIBUTES;
  1705. DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
  1706. if (!traverse) {
  1707. flags |= FILE_FLAG_OPEN_REPARSE_POINT;
  1708. }
  1709. hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
  1710. if (hFile == INVALID_HANDLE_VALUE) {
  1711. /* Either the path doesn't exist, or the caller lacks access. */
  1712. error = GetLastError();
  1713. switch (error) {
  1714. case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
  1715. case ERROR_SHARING_VIOLATION: /* It's a paging file. */
  1716. /* Try reading the parent directory. */
  1717. if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
  1718. /* Cannot read the parent directory. */
  1719. switch (GetLastError()) {
  1720. case ERROR_FILE_NOT_FOUND: /* File cannot be found */
  1721. case ERROR_PATH_NOT_FOUND: /* File parent directory cannot be found */
  1722. case ERROR_NOT_READY: /* Drive exists but unavailable */
  1723. case ERROR_BAD_NET_NAME: /* Remote drive unavailable */
  1724. break;
  1725. /* Restore the error from CreateFileW(). */
  1726. default:
  1727. SetLastError(error);
  1728. }
  1729. return -1;
  1730. }
  1731. if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
  1732. if (traverse ||
  1733. !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
  1734. /* The stat call has to traverse but cannot, so fail. */
  1735. SetLastError(error);
  1736. return -1;
  1737. }
  1738. }
  1739. break;
  1740. case ERROR_INVALID_PARAMETER:
  1741. /* \\.\con requires read or write access. */
  1742. hFile = CreateFileW(path, access | GENERIC_READ,
  1743. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
  1744. OPEN_EXISTING, flags, NULL);
  1745. if (hFile == INVALID_HANDLE_VALUE) {
  1746. SetLastError(error);
  1747. return -1;
  1748. }
  1749. break;
  1750. case ERROR_CANT_ACCESS_FILE:
  1751. /* bpo37834: open unhandled reparse points if traverse fails. */
  1752. if (traverse) {
  1753. traverse = FALSE;
  1754. isUnhandledTag = TRUE;
  1755. hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
  1756. flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
  1757. }
  1758. if (hFile == INVALID_HANDLE_VALUE) {
  1759. SetLastError(error);
  1760. return -1;
  1761. }
  1762. break;
  1763. default:
  1764. return -1;
  1765. }
  1766. }
  1767. if (hFile != INVALID_HANDLE_VALUE) {
  1768. /* Handle types other than files on disk. */
  1769. fileType = GetFileType(hFile);
  1770. if (fileType != FILE_TYPE_DISK) {
  1771. if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
  1772. retval = -1;
  1773. goto cleanup;
  1774. }
  1775. DWORD fileAttributes = GetFileAttributesW(path);
  1776. memset(result, 0, sizeof(*result));
  1777. if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
  1778. fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  1779. /* \\.\pipe\ or \\.\mailslot\ */
  1780. result->st_mode = _S_IFDIR;
  1781. } else if (fileType == FILE_TYPE_CHAR) {
  1782. /* \\.\nul */
  1783. result->st_mode = _S_IFCHR;
  1784. } else if (fileType == FILE_TYPE_PIPE) {
  1785. /* \\.\pipe\spam */
  1786. result->st_mode = _S_IFIFO;
  1787. }
  1788. /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
  1789. goto cleanup;
  1790. }
  1791. /* Query the reparse tag, and traverse a non-link. */
  1792. if (!traverse) {
  1793. if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
  1794. &tagInfo, sizeof(tagInfo))) {
  1795. /* Allow devices that do not support FileAttributeTagInfo. */
  1796. switch (GetLastError()) {
  1797. case ERROR_INVALID_PARAMETER:
  1798. case ERROR_INVALID_FUNCTION:
  1799. case ERROR_NOT_SUPPORTED:
  1800. tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
  1801. tagInfo.ReparseTag = 0;
  1802. break;
  1803. default:
  1804. retval = -1;
  1805. goto cleanup;
  1806. }
  1807. } else if (tagInfo.FileAttributes &
  1808. FILE_ATTRIBUTE_REPARSE_POINT) {
  1809. if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
  1810. if (isUnhandledTag) {
  1811. /* Traversing previously failed for either this link
  1812. or its target. */
  1813. SetLastError(ERROR_CANT_ACCESS_FILE);
  1814. retval = -1;
  1815. goto cleanup;
  1816. }
  1817. /* Traverse a non-link, but not if traversing already failed
  1818. for an unhandled tag. */
  1819. } else if (!isUnhandledTag) {
  1820. CloseHandle(hFile);
  1821. return win32_xstat_slow_impl(path, result, TRUE);
  1822. }
  1823. }
  1824. }
  1825. if (!GetFileInformationByHandle(hFile, &fileInfo) ||
  1826. !GetFileInformationByHandleEx(hFile, FileBasicInfo,
  1827. &basicInfo, sizeof(basicInfo))) {
  1828. switch (GetLastError()) {
  1829. case ERROR_INVALID_PARAMETER:
  1830. case ERROR_INVALID_FUNCTION:
  1831. case ERROR_NOT_SUPPORTED:
  1832. /* Volumes and physical disks are block devices, e.g.
  1833. \\.\C: and \\.\PhysicalDrive0. */
  1834. memset(result, 0, sizeof(*result));
  1835. result->st_mode = 0x6000; /* S_IFBLK */
  1836. goto cleanup;
  1837. }
  1838. retval = -1;
  1839. goto cleanup;
  1840. }
  1841. /* Successfully got FileBasicInfo, so we'll pass it along */
  1842. pBasicInfo = &basicInfo;
  1843. if (GetFileInformationByHandleEx(hFile, FileIdInfo, &idInfo, sizeof(idInfo))) {
  1844. /* Successfully got FileIdInfo, so pass it along */
  1845. pIdInfo = &idInfo;
  1846. }
  1847. }
  1848. _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, pBasicInfo, pIdInfo, result);
  1849. update_st_mode_from_path(path, fileInfo.dwFileAttributes, result);
  1850. cleanup:
  1851. if (hFile != INVALID_HANDLE_VALUE) {
  1852. /* Preserve last error if we are failing */
  1853. error = retval ? GetLastError() : 0;
  1854. if (!CloseHandle(hFile)) {
  1855. retval = -1;
  1856. } else if (retval) {
  1857. /* Restore last error */
  1858. SetLastError(error);
  1859. }
  1860. }
  1861. return retval;
  1862. }
  1863. static int
  1864. win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
  1865. BOOL traverse)
  1866. {
  1867. FILE_STAT_BASIC_INFORMATION statInfo;
  1868. if (_Py_GetFileInformationByName(path, FileStatBasicByNameInfo,
  1869. &statInfo, sizeof(statInfo))) {
  1870. if (// Cannot use fast path for reparse points ...
  1871. !(statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
  1872. // ... unless it's a name surrogate (symlink) and we're not following
  1873. || (!traverse && IsReparseTagNameSurrogate(statInfo.ReparseTag))
  1874. ) {
  1875. _Py_stat_basic_info_to_stat(&statInfo, result);
  1876. update_st_mode_from_path(path, statInfo.FileAttributes, result);
  1877. return 0;
  1878. }
  1879. } else {
  1880. switch(GetLastError()) {
  1881. case ERROR_FILE_NOT_FOUND:
  1882. case ERROR_PATH_NOT_FOUND:
  1883. case ERROR_NOT_READY:
  1884. case ERROR_BAD_NET_NAME:
  1885. /* These errors aren't worth retrying with the slow path */
  1886. return -1;
  1887. case ERROR_NOT_SUPPORTED:
  1888. /* indicates the API couldn't be loaded */
  1889. break;
  1890. }
  1891. }
  1892. return win32_xstat_slow_impl(path, result, traverse);
  1893. }
  1894. static int
  1895. win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
  1896. {
  1897. /* Protocol violation: we explicitly clear errno, instead of
  1898. setting it to a POSIX error. Callers should use GetLastError. */
  1899. int code = win32_xstat_impl(path, result, traverse);
  1900. errno = 0;
  1901. /* ctime is only deprecated from 3.12, so we copy birthtime across */
  1902. result->st_ctime = result->st_birthtime;
  1903. result->st_ctime_nsec = result->st_birthtime_nsec;
  1904. return code;
  1905. }
  1906. /* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
  1907. In Posix, stat automatically traverses symlinks and returns the stat
  1908. structure for the target. In Windows, the equivalent GetFileAttributes by
  1909. default does not traverse symlinks and instead returns attributes for
  1910. the symlink.
  1911. Instead, we will open the file (which *does* traverse symlinks by default)
  1912. and GetFileInformationByHandle(). */
  1913. static int
  1914. win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
  1915. {
  1916. return win32_xstat(path, result, FALSE);
  1917. }
  1918. static int
  1919. win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
  1920. {
  1921. return win32_xstat(path, result, TRUE);
  1922. }
  1923. #endif /* MS_WINDOWS */
  1924. PyDoc_STRVAR(stat_result__doc__,
  1925. "stat_result: Result from stat, fstat, or lstat.\n\n\
  1926. This object may be accessed either as a tuple of\n\
  1927. (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
  1928. or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
  1929. \n\
  1930. Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
  1931. or st_flags, they are available as attributes only.\n\
  1932. \n\
  1933. See os.stat for more information.");
  1934. static PyStructSequence_Field stat_result_fields[] = {
  1935. {"st_mode", "protection bits"},
  1936. {"st_ino", "inode"},
  1937. {"st_dev", "device"},
  1938. {"st_nlink", "number of hard links"},
  1939. {"st_uid", "user ID of owner"},
  1940. {"st_gid", "group ID of owner"},
  1941. {"st_size", "total size, in bytes"},
  1942. /* The NULL is replaced with PyStructSequence_UnnamedField later. */
  1943. {NULL, "integer time of last access"},
  1944. {NULL, "integer time of last modification"},
  1945. {NULL, "integer time of last change"},
  1946. {"st_atime", "time of last access"},
  1947. {"st_mtime", "time of last modification"},
  1948. {"st_ctime", "time of last change"},
  1949. {"st_atime_ns", "time of last access in nanoseconds"},
  1950. {"st_mtime_ns", "time of last modification in nanoseconds"},
  1951. {"st_ctime_ns", "time of last change in nanoseconds"},
  1952. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1953. {"st_blksize", "blocksize for filesystem I/O"},
  1954. #endif
  1955. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1956. {"st_blocks", "number of blocks allocated"},
  1957. #endif
  1958. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1959. {"st_rdev", "device type (if inode device)"},
  1960. #endif
  1961. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1962. {"st_flags", "user defined flags for file"},
  1963. #endif
  1964. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1965. {"st_gen", "generation number"},
  1966. #endif
  1967. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) || defined(MS_WINDOWS)
  1968. {"st_birthtime", "time of creation"},
  1969. #endif
  1970. #ifdef MS_WINDOWS
  1971. {"st_birthtime_ns", "time of creation in nanoseconds"},
  1972. #endif
  1973. #ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
  1974. {"st_file_attributes", "Windows file attribute bits"},
  1975. #endif
  1976. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  1977. {"st_fstype", "Type of filesystem"},
  1978. #endif
  1979. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  1980. {"st_reparse_tag", "Windows reparse tag"},
  1981. #endif
  1982. {0}
  1983. };
  1984. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1985. #define ST_BLKSIZE_IDX 16
  1986. #else
  1987. #define ST_BLKSIZE_IDX 15
  1988. #endif
  1989. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1990. #define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
  1991. #else
  1992. #define ST_BLOCKS_IDX ST_BLKSIZE_IDX
  1993. #endif
  1994. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1995. #define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
  1996. #else
  1997. #define ST_RDEV_IDX ST_BLOCKS_IDX
  1998. #endif
  1999. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  2000. #define ST_FLAGS_IDX (ST_RDEV_IDX+1)
  2001. #else
  2002. #define ST_FLAGS_IDX ST_RDEV_IDX
  2003. #endif
  2004. #ifdef HAVE_STRUCT_STAT_ST_GEN
  2005. #define ST_GEN_IDX (ST_FLAGS_IDX+1)
  2006. #else
  2007. #define ST_GEN_IDX ST_FLAGS_IDX
  2008. #endif
  2009. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) || defined(MS_WINDOWS)
  2010. #define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
  2011. #else
  2012. #define ST_BIRTHTIME_IDX ST_GEN_IDX
  2013. #endif
  2014. #ifdef MS_WINDOWS
  2015. #define ST_BIRTHTIME_NS_IDX (ST_BIRTHTIME_IDX+1)
  2016. #else
  2017. #define ST_BIRTHTIME_NS_IDX ST_BIRTHTIME_IDX
  2018. #endif
  2019. #if defined(HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES) || defined(MS_WINDOWS)
  2020. #define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_NS_IDX+1)
  2021. #else
  2022. #define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_NS_IDX
  2023. #endif
  2024. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  2025. #define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
  2026. #else
  2027. #define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
  2028. #endif
  2029. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  2030. #define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
  2031. #else
  2032. #define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
  2033. #endif
  2034. static PyStructSequence_Desc stat_result_desc = {
  2035. "stat_result", /* name */
  2036. stat_result__doc__, /* doc */
  2037. stat_result_fields,
  2038. 10
  2039. };
  2040. PyDoc_STRVAR(statvfs_result__doc__,
  2041. "statvfs_result: Result from statvfs or fstatvfs.\n\n\
  2042. This object may be accessed either as a tuple of\n\
  2043. (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
  2044. or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
  2045. \n\
  2046. See os.statvfs for more information.");
  2047. static PyStructSequence_Field statvfs_result_fields[] = {
  2048. {"f_bsize", },
  2049. {"f_frsize", },
  2050. {"f_blocks", },
  2051. {"f_bfree", },
  2052. {"f_bavail", },
  2053. {"f_files", },
  2054. {"f_ffree", },
  2055. {"f_favail", },
  2056. {"f_flag", },
  2057. {"f_namemax",},
  2058. {"f_fsid", },
  2059. {0}
  2060. };
  2061. static PyStructSequence_Desc statvfs_result_desc = {
  2062. "statvfs_result", /* name */
  2063. statvfs_result__doc__, /* doc */
  2064. statvfs_result_fields,
  2065. 10
  2066. };
  2067. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2068. PyDoc_STRVAR(waitid_result__doc__,
  2069. "waitid_result: Result from waitid.\n\n\
  2070. This object may be accessed either as a tuple of\n\
  2071. (si_pid, si_uid, si_signo, si_status, si_code),\n\
  2072. or via the attributes si_pid, si_uid, and so on.\n\
  2073. \n\
  2074. See os.waitid for more information.");
  2075. static PyStructSequence_Field waitid_result_fields[] = {
  2076. {"si_pid", },
  2077. {"si_uid", },
  2078. {"si_signo", },
  2079. {"si_status", },
  2080. {"si_code", },
  2081. {0}
  2082. };
  2083. static PyStructSequence_Desc waitid_result_desc = {
  2084. "waitid_result", /* name */
  2085. waitid_result__doc__, /* doc */
  2086. waitid_result_fields,
  2087. 5
  2088. };
  2089. #endif
  2090. static PyObject *
  2091. statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2092. {
  2093. PyStructSequence *result;
  2094. int i;
  2095. // ht_module doesn't get set in PyStructSequence_NewType(),
  2096. // so we can't use PyType_GetModule().
  2097. PyObject *mod = PyImport_GetModule(MODNAME_OBJ);
  2098. if (mod == NULL) {
  2099. return NULL;
  2100. }
  2101. _posixstate *state = get_posix_state(mod);
  2102. Py_DECREF(mod);
  2103. if (state == NULL) {
  2104. return NULL;
  2105. }
  2106. #define structseq_new state->statresult_new_orig
  2107. result = (PyStructSequence*)structseq_new(type, args, kwds);
  2108. if (!result)
  2109. return NULL;
  2110. /* If we have been initialized from a tuple,
  2111. st_?time might be set to None. Initialize it
  2112. from the int slots. */
  2113. for (i = 7; i <= 9; i++) {
  2114. if (result->ob_item[i+3] == Py_None) {
  2115. Py_DECREF(Py_None);
  2116. result->ob_item[i+3] = Py_NewRef(result->ob_item[i]);
  2117. }
  2118. }
  2119. return (PyObject*)result;
  2120. }
  2121. static int
  2122. _posix_clear(PyObject *module)
  2123. {
  2124. _posixstate *state = get_posix_state(module);
  2125. Py_CLEAR(state->billion);
  2126. Py_CLEAR(state->DirEntryType);
  2127. Py_CLEAR(state->ScandirIteratorType);
  2128. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  2129. Py_CLEAR(state->SchedParamType);
  2130. #endif
  2131. Py_CLEAR(state->StatResultType);
  2132. Py_CLEAR(state->StatVFSResultType);
  2133. Py_CLEAR(state->TerminalSizeType);
  2134. Py_CLEAR(state->TimesResultType);
  2135. Py_CLEAR(state->UnameResultType);
  2136. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2137. Py_CLEAR(state->WaitidResultType);
  2138. #endif
  2139. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  2140. Py_CLEAR(state->struct_rusage);
  2141. #endif
  2142. Py_CLEAR(state->st_mode);
  2143. return 0;
  2144. }
  2145. static int
  2146. _posix_traverse(PyObject *module, visitproc visit, void *arg)
  2147. {
  2148. _posixstate *state = get_posix_state(module);
  2149. Py_VISIT(state->billion);
  2150. Py_VISIT(state->DirEntryType);
  2151. Py_VISIT(state->ScandirIteratorType);
  2152. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  2153. Py_VISIT(state->SchedParamType);
  2154. #endif
  2155. Py_VISIT(state->StatResultType);
  2156. Py_VISIT(state->StatVFSResultType);
  2157. Py_VISIT(state->TerminalSizeType);
  2158. Py_VISIT(state->TimesResultType);
  2159. Py_VISIT(state->UnameResultType);
  2160. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2161. Py_VISIT(state->WaitidResultType);
  2162. #endif
  2163. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  2164. Py_VISIT(state->struct_rusage);
  2165. #endif
  2166. Py_VISIT(state->st_mode);
  2167. return 0;
  2168. }
  2169. static void
  2170. _posix_free(void *module)
  2171. {
  2172. _posix_clear((PyObject *)module);
  2173. }
  2174. static int
  2175. fill_time(PyObject *module, PyObject *v, int s_index, int f_index, int ns_index, time_t sec, unsigned long nsec)
  2176. {
  2177. assert(!PyErr_Occurred());
  2178. int res = -1;
  2179. PyObject *s_in_ns = NULL;
  2180. PyObject *ns_total = NULL;
  2181. PyObject *float_s = NULL;
  2182. PyObject *s = _PyLong_FromTime_t(sec);
  2183. PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
  2184. if (!(s && ns_fractional)) {
  2185. goto exit;
  2186. }
  2187. s_in_ns = PyNumber_Multiply(s, get_posix_state(module)->billion);
  2188. if (!s_in_ns) {
  2189. goto exit;
  2190. }
  2191. ns_total = PyNumber_Add(s_in_ns, ns_fractional);
  2192. if (!ns_total)
  2193. goto exit;
  2194. float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
  2195. if (!float_s) {
  2196. goto exit;
  2197. }
  2198. if (s_index >= 0) {
  2199. PyStructSequence_SET_ITEM(v, s_index, s);
  2200. s = NULL;
  2201. }
  2202. if (f_index >= 0) {
  2203. PyStructSequence_SET_ITEM(v, f_index, float_s);
  2204. float_s = NULL;
  2205. }
  2206. if (ns_index >= 0) {
  2207. PyStructSequence_SET_ITEM(v, ns_index, ns_total);
  2208. ns_total = NULL;
  2209. }
  2210. assert(!PyErr_Occurred());
  2211. res = 0;
  2212. exit:
  2213. Py_XDECREF(s);
  2214. Py_XDECREF(ns_fractional);
  2215. Py_XDECREF(s_in_ns);
  2216. Py_XDECREF(ns_total);
  2217. Py_XDECREF(float_s);
  2218. return res;
  2219. }
  2220. #ifdef MS_WINDOWS
  2221. static PyObject*
  2222. _pystat_l128_from_l64_l64(uint64_t low, uint64_t high)
  2223. {
  2224. PyObject *o_low = PyLong_FromUnsignedLongLong(low);
  2225. if (!o_low || !high) {
  2226. return o_low;
  2227. }
  2228. PyObject *o_high = PyLong_FromUnsignedLongLong(high);
  2229. PyObject *l64 = o_high ? PyLong_FromLong(64) : NULL;
  2230. if (!l64) {
  2231. Py_XDECREF(o_high);
  2232. Py_DECREF(o_low);
  2233. return NULL;
  2234. }
  2235. Py_SETREF(o_high, PyNumber_Lshift(o_high, l64));
  2236. Py_DECREF(l64);
  2237. if (!o_high) {
  2238. Py_DECREF(o_low);
  2239. return NULL;
  2240. }
  2241. Py_SETREF(o_low, PyNumber_Add(o_low, o_high));
  2242. Py_DECREF(o_high);
  2243. return o_low;
  2244. }
  2245. #endif
  2246. /* pack a system stat C structure into the Python stat tuple
  2247. (used by posix_stat() and posix_fstat()) */
  2248. static PyObject*
  2249. _pystat_fromstructstat(PyObject *module, STRUCT_STAT *st)
  2250. {
  2251. assert(!PyErr_Occurred());
  2252. PyObject *StatResultType = get_posix_state(module)->StatResultType;
  2253. PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
  2254. if (v == NULL) {
  2255. return NULL;
  2256. }
  2257. #define SET_ITEM(pos, expr) \
  2258. do { \
  2259. PyObject *obj = (expr); \
  2260. if (obj == NULL) { \
  2261. goto error; \
  2262. } \
  2263. PyStructSequence_SET_ITEM(v, (pos), obj); \
  2264. } while (0)
  2265. SET_ITEM(0, PyLong_FromLong((long)st->st_mode));
  2266. #ifdef MS_WINDOWS
  2267. SET_ITEM(1, _pystat_l128_from_l64_l64(st->st_ino, st->st_ino_high));
  2268. SET_ITEM(2, PyLong_FromUnsignedLongLong(st->st_dev));
  2269. #else
  2270. static_assert(sizeof(unsigned long long) >= sizeof(st->st_ino),
  2271. "stat.st_ino is larger than unsigned long long");
  2272. SET_ITEM(1, PyLong_FromUnsignedLongLong(st->st_ino));
  2273. SET_ITEM(2, _PyLong_FromDev(st->st_dev));
  2274. #endif
  2275. SET_ITEM(3, PyLong_FromLong((long)st->st_nlink));
  2276. #if defined(MS_WINDOWS)
  2277. SET_ITEM(4, PyLong_FromLong(0));
  2278. SET_ITEM(5, PyLong_FromLong(0));
  2279. #else
  2280. SET_ITEM(4, _PyLong_FromUid(st->st_uid));
  2281. SET_ITEM(5, _PyLong_FromGid(st->st_gid));
  2282. #endif
  2283. static_assert(sizeof(long long) >= sizeof(st->st_size),
  2284. "stat.st_size is larger than long long");
  2285. SET_ITEM(6, PyLong_FromLongLong(st->st_size));
  2286. // Set st_atime, st_mtime and st_ctime
  2287. unsigned long ansec, mnsec, cnsec;
  2288. #if defined(HAVE_STAT_TV_NSEC)
  2289. ansec = st->st_atim.tv_nsec;
  2290. mnsec = st->st_mtim.tv_nsec;
  2291. cnsec = st->st_ctim.tv_nsec;
  2292. #elif defined(HAVE_STAT_TV_NSEC2)
  2293. ansec = st->st_atimespec.tv_nsec;
  2294. mnsec = st->st_mtimespec.tv_nsec;
  2295. cnsec = st->st_ctimespec.tv_nsec;
  2296. #elif defined(HAVE_STAT_NSEC)
  2297. ansec = st->st_atime_nsec;
  2298. mnsec = st->st_mtime_nsec;
  2299. cnsec = st->st_ctime_nsec;
  2300. #else
  2301. ansec = mnsec = cnsec = 0;
  2302. #endif
  2303. if (fill_time(module, v, 7, 10, 13, st->st_atime, ansec) < 0) {
  2304. goto error;
  2305. }
  2306. if (fill_time(module, v, 8, 11, 14, st->st_mtime, mnsec) < 0) {
  2307. goto error;
  2308. }
  2309. if (fill_time(module, v, 9, 12, 15, st->st_ctime, cnsec) < 0) {
  2310. goto error;
  2311. }
  2312. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  2313. SET_ITEM(ST_BLKSIZE_IDX, PyLong_FromLong((long)st->st_blksize));
  2314. #endif
  2315. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  2316. SET_ITEM(ST_BLOCKS_IDX, PyLong_FromLong((long)st->st_blocks));
  2317. #endif
  2318. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  2319. SET_ITEM(ST_RDEV_IDX, PyLong_FromLong((long)st->st_rdev));
  2320. #endif
  2321. #ifdef HAVE_STRUCT_STAT_ST_GEN
  2322. SET_ITEM(ST_GEN_IDX, PyLong_FromLong((long)st->st_gen));
  2323. #endif
  2324. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME)
  2325. {
  2326. unsigned long bsec, bnsec;
  2327. bsec = (long)st->st_birthtime;
  2328. #ifdef HAVE_STAT_TV_NSEC2
  2329. bnsec = st->st_birthtimespec.tv_nsec;
  2330. #else
  2331. bnsec = 0;
  2332. #endif
  2333. SET_ITEM(ST_BIRTHTIME_IDX, PyFloat_FromDouble(bsec + bnsec * 1e-9));
  2334. }
  2335. #elif defined(MS_WINDOWS)
  2336. if (fill_time(module, v, -1, ST_BIRTHTIME_IDX, ST_BIRTHTIME_NS_IDX,
  2337. st->st_birthtime, st->st_birthtime_nsec) < 0) {
  2338. goto error;
  2339. }
  2340. #endif
  2341. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  2342. SET_ITEM(ST_FLAGS_IDX, PyLong_FromLong((long)st->st_flags));
  2343. #endif
  2344. #ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
  2345. SET_ITEM(ST_FILE_ATTRIBUTES_IDX,
  2346. PyLong_FromUnsignedLong(st->st_file_attributes));
  2347. #endif
  2348. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  2349. SET_ITEM(ST_FSTYPE_IDX, PyUnicode_FromString(st->st_fstype));
  2350. #endif
  2351. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  2352. SET_ITEM(ST_REPARSE_TAG_IDX, PyLong_FromUnsignedLong(st->st_reparse_tag));
  2353. #endif
  2354. assert(!PyErr_Occurred());
  2355. return v;
  2356. error:
  2357. Py_DECREF(v);
  2358. return NULL;
  2359. #undef SET_ITEM
  2360. }
  2361. /* POSIX methods */
  2362. static PyObject *
  2363. posix_do_stat(PyObject *module, const char *function_name, path_t *path,
  2364. int dir_fd, int follow_symlinks)
  2365. {
  2366. STRUCT_STAT st;
  2367. int result;
  2368. #ifdef HAVE_FSTATAT
  2369. int fstatat_unavailable = 0;
  2370. #endif
  2371. #if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
  2372. if (follow_symlinks_specified(function_name, follow_symlinks))
  2373. return NULL;
  2374. #endif
  2375. if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
  2376. dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
  2377. fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
  2378. return NULL;
  2379. Py_BEGIN_ALLOW_THREADS
  2380. if (path->fd != -1)
  2381. result = FSTAT(path->fd, &st);
  2382. #ifdef MS_WINDOWS
  2383. else if (follow_symlinks)
  2384. result = win32_stat(path->wide, &st);
  2385. else
  2386. result = win32_lstat(path->wide, &st);
  2387. #else
  2388. else
  2389. #if defined(HAVE_LSTAT)
  2390. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  2391. result = LSTAT(path->narrow, &st);
  2392. else
  2393. #endif /* HAVE_LSTAT */
  2394. #ifdef HAVE_FSTATAT
  2395. if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
  2396. if (HAVE_FSTATAT_RUNTIME) {
  2397. result = fstatat(dir_fd, path->narrow, &st,
  2398. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  2399. } else {
  2400. fstatat_unavailable = 1;
  2401. }
  2402. } else
  2403. #endif /* HAVE_FSTATAT */
  2404. result = STAT(path->narrow, &st);
  2405. #endif /* MS_WINDOWS */
  2406. Py_END_ALLOW_THREADS
  2407. #ifdef HAVE_FSTATAT
  2408. if (fstatat_unavailable) {
  2409. argument_unavailable_error("stat", "dir_fd");
  2410. return NULL;
  2411. }
  2412. #endif
  2413. if (result != 0) {
  2414. return path_error(path);
  2415. }
  2416. return _pystat_fromstructstat(module, &st);
  2417. }
  2418. /*[python input]
  2419. for s in """
  2420. FACCESSAT
  2421. FCHMODAT
  2422. FCHOWNAT
  2423. FSTATAT
  2424. LINKAT
  2425. MKDIRAT
  2426. MKFIFOAT
  2427. MKNODAT
  2428. OPENAT
  2429. READLINKAT
  2430. SYMLINKAT
  2431. UNLINKAT
  2432. """.strip().split():
  2433. s = s.strip()
  2434. print("""
  2435. #ifdef HAVE_{s}
  2436. #define {s}_DIR_FD_CONVERTER dir_fd_converter
  2437. #else
  2438. #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
  2439. #endif
  2440. """.rstrip().format(s=s))
  2441. for s in """
  2442. FCHDIR
  2443. FCHMOD
  2444. FCHOWN
  2445. FDOPENDIR
  2446. FEXECVE
  2447. FPATHCONF
  2448. FSTATVFS
  2449. FTRUNCATE
  2450. """.strip().split():
  2451. s = s.strip()
  2452. print("""
  2453. #ifdef HAVE_{s}
  2454. #define PATH_HAVE_{s} 1
  2455. #else
  2456. #define PATH_HAVE_{s} 0
  2457. #endif
  2458. """.rstrip().format(s=s))
  2459. [python start generated code]*/
  2460. #ifdef HAVE_FACCESSAT
  2461. #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
  2462. #else
  2463. #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
  2464. #endif
  2465. #ifdef HAVE_FCHMODAT
  2466. #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
  2467. #else
  2468. #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
  2469. #endif
  2470. #ifdef HAVE_FCHOWNAT
  2471. #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
  2472. #else
  2473. #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
  2474. #endif
  2475. #ifdef HAVE_FSTATAT
  2476. #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
  2477. #else
  2478. #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
  2479. #endif
  2480. #ifdef HAVE_LINKAT
  2481. #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
  2482. #else
  2483. #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2484. #endif
  2485. #ifdef HAVE_MKDIRAT
  2486. #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
  2487. #else
  2488. #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
  2489. #endif
  2490. #ifdef HAVE_MKFIFOAT
  2491. #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
  2492. #else
  2493. #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
  2494. #endif
  2495. #ifdef HAVE_MKNODAT
  2496. #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
  2497. #else
  2498. #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
  2499. #endif
  2500. #ifdef HAVE_OPENAT
  2501. #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
  2502. #else
  2503. #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
  2504. #endif
  2505. #ifdef HAVE_READLINKAT
  2506. #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2507. #else
  2508. #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2509. #endif
  2510. #ifdef HAVE_SYMLINKAT
  2511. #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2512. #else
  2513. #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2514. #endif
  2515. #ifdef HAVE_UNLINKAT
  2516. #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2517. #else
  2518. #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2519. #endif
  2520. #ifdef HAVE_FCHDIR
  2521. #define PATH_HAVE_FCHDIR 1
  2522. #else
  2523. #define PATH_HAVE_FCHDIR 0
  2524. #endif
  2525. #ifdef HAVE_FCHMOD
  2526. #define PATH_HAVE_FCHMOD 1
  2527. #else
  2528. #define PATH_HAVE_FCHMOD 0
  2529. #endif
  2530. #ifdef HAVE_FCHOWN
  2531. #define PATH_HAVE_FCHOWN 1
  2532. #else
  2533. #define PATH_HAVE_FCHOWN 0
  2534. #endif
  2535. #ifdef HAVE_FDOPENDIR
  2536. #define PATH_HAVE_FDOPENDIR 1
  2537. #else
  2538. #define PATH_HAVE_FDOPENDIR 0
  2539. #endif
  2540. #ifdef HAVE_FEXECVE
  2541. #define PATH_HAVE_FEXECVE 1
  2542. #else
  2543. #define PATH_HAVE_FEXECVE 0
  2544. #endif
  2545. #ifdef HAVE_FPATHCONF
  2546. #define PATH_HAVE_FPATHCONF 1
  2547. #else
  2548. #define PATH_HAVE_FPATHCONF 0
  2549. #endif
  2550. #ifdef HAVE_FSTATVFS
  2551. #define PATH_HAVE_FSTATVFS 1
  2552. #else
  2553. #define PATH_HAVE_FSTATVFS 0
  2554. #endif
  2555. #ifdef HAVE_FTRUNCATE
  2556. #define PATH_HAVE_FTRUNCATE 1
  2557. #else
  2558. #define PATH_HAVE_FTRUNCATE 0
  2559. #endif
  2560. /*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
  2561. #ifdef MS_WINDOWS
  2562. #undef PATH_HAVE_FTRUNCATE
  2563. #define PATH_HAVE_FTRUNCATE 1
  2564. #endif
  2565. /*[python input]
  2566. class path_t_converter(CConverter):
  2567. type = "path_t"
  2568. impl_by_reference = True
  2569. parse_by_reference = True
  2570. converter = 'path_converter'
  2571. def converter_init(self, *, allow_fd=False, make_wide=None,
  2572. nonstrict=False, nullable=False,
  2573. suppress_value_error=False):
  2574. # right now path_t doesn't support default values.
  2575. # to support a default value, you'll need to override initialize().
  2576. if self.default not in (unspecified, None):
  2577. fail("Can't specify a default to the path_t converter!")
  2578. if self.c_default not in (None, 'Py_None'):
  2579. raise RuntimeError("Can't specify a c_default to the path_t converter!")
  2580. self.nullable = nullable
  2581. self.nonstrict = nonstrict
  2582. self.make_wide = make_wide
  2583. self.suppress_value_error = suppress_value_error
  2584. self.allow_fd = allow_fd
  2585. def pre_render(self):
  2586. def strify(value):
  2587. if isinstance(value, str):
  2588. return value
  2589. return str(int(bool(value)))
  2590. # add self.py_name here when merging with posixmodule conversion
  2591. if self.make_wide is None:
  2592. self.c_default = 'PATH_T_INITIALIZE_P("{}", "{}", {}, {}, {}, {})'.format(
  2593. self.function.name,
  2594. self.name,
  2595. strify(self.nullable),
  2596. strify(self.nonstrict),
  2597. strify(self.suppress_value_error),
  2598. strify(self.allow_fd),
  2599. )
  2600. else:
  2601. self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {}, {}, {}, {})'.format(
  2602. self.function.name,
  2603. self.name,
  2604. strify(self.nullable),
  2605. strify(self.nonstrict),
  2606. strify(self.make_wide),
  2607. strify(self.suppress_value_error),
  2608. strify(self.allow_fd),
  2609. )
  2610. def cleanup(self):
  2611. return "path_cleanup(&" + self.name + ");\n"
  2612. class dir_fd_converter(CConverter):
  2613. type = 'int'
  2614. def converter_init(self, requires=None):
  2615. if self.default in (unspecified, None):
  2616. self.c_default = 'DEFAULT_DIR_FD'
  2617. if isinstance(requires, str):
  2618. self.converter = requires.upper() + '_DIR_FD_CONVERTER'
  2619. else:
  2620. self.converter = 'dir_fd_converter'
  2621. class uid_t_converter(CConverter):
  2622. type = "uid_t"
  2623. converter = '_Py_Uid_Converter'
  2624. class gid_t_converter(CConverter):
  2625. type = "gid_t"
  2626. converter = '_Py_Gid_Converter'
  2627. class dev_t_converter(CConverter):
  2628. type = 'dev_t'
  2629. converter = '_Py_Dev_Converter'
  2630. class dev_t_return_converter(unsigned_long_return_converter):
  2631. type = 'dev_t'
  2632. conversion_fn = '_PyLong_FromDev'
  2633. unsigned_cast = '(dev_t)'
  2634. class FSConverter_converter(CConverter):
  2635. type = 'PyObject *'
  2636. converter = 'PyUnicode_FSConverter'
  2637. def converter_init(self):
  2638. if self.default is not unspecified:
  2639. fail("FSConverter_converter does not support default values")
  2640. self.c_default = 'NULL'
  2641. def cleanup(self):
  2642. return "Py_XDECREF(" + self.name + ");\n"
  2643. class pid_t_converter(CConverter):
  2644. type = 'pid_t'
  2645. format_unit = '" _Py_PARSE_PID "'
  2646. class idtype_t_converter(int_converter):
  2647. type = 'idtype_t'
  2648. class id_t_converter(CConverter):
  2649. type = 'id_t'
  2650. format_unit = '" _Py_PARSE_PID "'
  2651. class intptr_t_converter(CConverter):
  2652. type = 'intptr_t'
  2653. format_unit = '" _Py_PARSE_INTPTR "'
  2654. class Py_off_t_converter(CConverter):
  2655. type = 'Py_off_t'
  2656. converter = 'Py_off_t_converter'
  2657. class Py_off_t_return_converter(long_return_converter):
  2658. type = 'Py_off_t'
  2659. conversion_fn = 'PyLong_FromPy_off_t'
  2660. class path_confname_converter(CConverter):
  2661. type="int"
  2662. converter="conv_path_confname"
  2663. class confstr_confname_converter(path_confname_converter):
  2664. converter='conv_confstr_confname'
  2665. class sysconf_confname_converter(path_confname_converter):
  2666. converter="conv_sysconf_confname"
  2667. [python start generated code]*/
  2668. /*[python end generated code: output=da39a3ee5e6b4b0d input=577cb476e5d64960]*/
  2669. /*[clinic input]
  2670. os.stat
  2671. path : path_t(allow_fd=True)
  2672. Path to be examined; can be string, bytes, a path-like object or
  2673. open-file-descriptor int.
  2674. *
  2675. dir_fd : dir_fd(requires='fstatat') = None
  2676. If not None, it should be a file descriptor open to a directory,
  2677. and path should be a relative string; path will then be relative to
  2678. that directory.
  2679. follow_symlinks: bool = True
  2680. If False, and the last element of the path is a symbolic link,
  2681. stat will examine the symbolic link itself instead of the file
  2682. the link points to.
  2683. Perform a stat system call on the given path.
  2684. dir_fd and follow_symlinks may not be implemented
  2685. on your platform. If they are unavailable, using them will raise a
  2686. NotImplementedError.
  2687. It's an error to use dir_fd or follow_symlinks when specifying path as
  2688. an open file descriptor.
  2689. [clinic start generated code]*/
  2690. static PyObject *
  2691. os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
  2692. /*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
  2693. {
  2694. return posix_do_stat(module, "stat", path, dir_fd, follow_symlinks);
  2695. }
  2696. /*[clinic input]
  2697. os.lstat
  2698. path : path_t
  2699. *
  2700. dir_fd : dir_fd(requires='fstatat') = None
  2701. Perform a stat system call on the given path, without following symbolic links.
  2702. Like stat(), but do not follow symbolic links.
  2703. Equivalent to stat(path, follow_symlinks=False).
  2704. [clinic start generated code]*/
  2705. static PyObject *
  2706. os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
  2707. /*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
  2708. {
  2709. int follow_symlinks = 0;
  2710. return posix_do_stat(module, "lstat", path, dir_fd, follow_symlinks);
  2711. }
  2712. /*[clinic input]
  2713. os.access -> bool
  2714. path: path_t
  2715. Path to be tested; can be string, bytes, or a path-like object.
  2716. mode: int
  2717. Operating-system mode bitfield. Can be F_OK to test existence,
  2718. or the inclusive-OR of R_OK, W_OK, and X_OK.
  2719. *
  2720. dir_fd : dir_fd(requires='faccessat') = None
  2721. If not None, it should be a file descriptor open to a directory,
  2722. and path should be relative; path will then be relative to that
  2723. directory.
  2724. effective_ids: bool = False
  2725. If True, access will use the effective uid/gid instead of
  2726. the real uid/gid.
  2727. follow_symlinks: bool = True
  2728. If False, and the last element of the path is a symbolic link,
  2729. access will examine the symbolic link itself instead of the file
  2730. the link points to.
  2731. Use the real uid/gid to test for access to a path.
  2732. {parameters}
  2733. dir_fd, effective_ids, and follow_symlinks may not be implemented
  2734. on your platform. If they are unavailable, using them will raise a
  2735. NotImplementedError.
  2736. Note that most operations will use the effective uid/gid, therefore this
  2737. routine can be used in a suid/sgid environment to test if the invoking user
  2738. has the specified access to the path.
  2739. [clinic start generated code]*/
  2740. static int
  2741. os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
  2742. int effective_ids, int follow_symlinks)
  2743. /*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
  2744. {
  2745. int return_value;
  2746. #ifdef MS_WINDOWS
  2747. DWORD attr;
  2748. #else
  2749. int result;
  2750. #endif
  2751. #ifdef HAVE_FACCESSAT
  2752. int faccessat_unavailable = 0;
  2753. #endif
  2754. #ifndef HAVE_FACCESSAT
  2755. if (follow_symlinks_specified("access", follow_symlinks))
  2756. return -1;
  2757. if (effective_ids) {
  2758. argument_unavailable_error("access", "effective_ids");
  2759. return -1;
  2760. }
  2761. #endif
  2762. #ifdef MS_WINDOWS
  2763. Py_BEGIN_ALLOW_THREADS
  2764. attr = GetFileAttributesW(path->wide);
  2765. Py_END_ALLOW_THREADS
  2766. /*
  2767. * Access is possible if
  2768. * * we didn't get a -1, and
  2769. * * write access wasn't requested,
  2770. * * or the file isn't read-only,
  2771. * * or it's a directory.
  2772. * (Directories cannot be read-only on Windows.)
  2773. */
  2774. return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
  2775. (!(mode & 2) ||
  2776. !(attr & FILE_ATTRIBUTE_READONLY) ||
  2777. (attr & FILE_ATTRIBUTE_DIRECTORY));
  2778. #else
  2779. Py_BEGIN_ALLOW_THREADS
  2780. #ifdef HAVE_FACCESSAT
  2781. if ((dir_fd != DEFAULT_DIR_FD) ||
  2782. effective_ids ||
  2783. !follow_symlinks) {
  2784. if (HAVE_FACCESSAT_RUNTIME) {
  2785. int flags = 0;
  2786. if (!follow_symlinks)
  2787. flags |= AT_SYMLINK_NOFOLLOW;
  2788. if (effective_ids)
  2789. flags |= AT_EACCESS;
  2790. result = faccessat(dir_fd, path->narrow, mode, flags);
  2791. } else {
  2792. faccessat_unavailable = 1;
  2793. }
  2794. }
  2795. else
  2796. #endif
  2797. result = access(path->narrow, mode);
  2798. Py_END_ALLOW_THREADS
  2799. #ifdef HAVE_FACCESSAT
  2800. if (faccessat_unavailable) {
  2801. if (dir_fd != DEFAULT_DIR_FD) {
  2802. argument_unavailable_error("access", "dir_fd");
  2803. return -1;
  2804. }
  2805. if (follow_symlinks_specified("access", follow_symlinks))
  2806. return -1;
  2807. if (effective_ids) {
  2808. argument_unavailable_error("access", "effective_ids");
  2809. return -1;
  2810. }
  2811. /* should be unreachable */
  2812. return -1;
  2813. }
  2814. #endif
  2815. return_value = !result;
  2816. #endif
  2817. return return_value;
  2818. }
  2819. #ifndef F_OK
  2820. #define F_OK 0
  2821. #endif
  2822. #ifndef R_OK
  2823. #define R_OK 4
  2824. #endif
  2825. #ifndef W_OK
  2826. #define W_OK 2
  2827. #endif
  2828. #ifndef X_OK
  2829. #define X_OK 1
  2830. #endif
  2831. #ifdef HAVE_TTYNAME_R
  2832. /*[clinic input]
  2833. os.ttyname
  2834. fd: int
  2835. Integer file descriptor handle.
  2836. /
  2837. Return the name of the terminal device connected to 'fd'.
  2838. [clinic start generated code]*/
  2839. static PyObject *
  2840. os_ttyname_impl(PyObject *module, int fd)
  2841. /*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
  2842. {
  2843. long size = sysconf(_SC_TTY_NAME_MAX);
  2844. if (size == -1) {
  2845. return posix_error();
  2846. }
  2847. char *buffer = (char *)PyMem_RawMalloc(size);
  2848. if (buffer == NULL) {
  2849. return PyErr_NoMemory();
  2850. }
  2851. int ret = ttyname_r(fd, buffer, size);
  2852. if (ret != 0) {
  2853. PyMem_RawFree(buffer);
  2854. errno = ret;
  2855. return posix_error();
  2856. }
  2857. PyObject *res = PyUnicode_DecodeFSDefault(buffer);
  2858. PyMem_RawFree(buffer);
  2859. return res;
  2860. }
  2861. #endif
  2862. #ifdef HAVE_CTERMID
  2863. /*[clinic input]
  2864. os.ctermid
  2865. Return the name of the controlling terminal for this process.
  2866. [clinic start generated code]*/
  2867. static PyObject *
  2868. os_ctermid_impl(PyObject *module)
  2869. /*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
  2870. {
  2871. char *ret;
  2872. char buffer[L_ctermid];
  2873. #ifdef USE_CTERMID_R
  2874. ret = ctermid_r(buffer);
  2875. #else
  2876. ret = ctermid(buffer);
  2877. #endif
  2878. if (ret == NULL)
  2879. return posix_error();
  2880. return PyUnicode_DecodeFSDefault(buffer);
  2881. }
  2882. #endif /* HAVE_CTERMID */
  2883. /*[clinic input]
  2884. os.chdir
  2885. path: path_t(allow_fd='PATH_HAVE_FCHDIR')
  2886. Change the current working directory to the specified path.
  2887. path may always be specified as a string.
  2888. On some platforms, path may also be specified as an open file descriptor.
  2889. If this functionality is unavailable, using it raises an exception.
  2890. [clinic start generated code]*/
  2891. static PyObject *
  2892. os_chdir_impl(PyObject *module, path_t *path)
  2893. /*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
  2894. {
  2895. int result;
  2896. if (PySys_Audit("os.chdir", "(O)", path->object) < 0) {
  2897. return NULL;
  2898. }
  2899. Py_BEGIN_ALLOW_THREADS
  2900. #ifdef MS_WINDOWS
  2901. /* on unix, success = 0, on windows, success = !0 */
  2902. result = !win32_wchdir(path->wide);
  2903. #else
  2904. #ifdef HAVE_FCHDIR
  2905. if (path->fd != -1)
  2906. result = fchdir(path->fd);
  2907. else
  2908. #endif
  2909. result = chdir(path->narrow);
  2910. #endif
  2911. Py_END_ALLOW_THREADS
  2912. if (result) {
  2913. return path_error(path);
  2914. }
  2915. Py_RETURN_NONE;
  2916. }
  2917. #ifdef HAVE_FCHDIR
  2918. /*[clinic input]
  2919. os.fchdir
  2920. fd: fildes
  2921. Change to the directory of the given file descriptor.
  2922. fd must be opened on a directory, not a file.
  2923. Equivalent to os.chdir(fd).
  2924. [clinic start generated code]*/
  2925. static PyObject *
  2926. os_fchdir_impl(PyObject *module, int fd)
  2927. /*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
  2928. {
  2929. if (PySys_Audit("os.chdir", "(i)", fd) < 0) {
  2930. return NULL;
  2931. }
  2932. return posix_fildes_fd(fd, fchdir);
  2933. }
  2934. #endif /* HAVE_FCHDIR */
  2935. /*[clinic input]
  2936. os.chmod
  2937. path: path_t(allow_fd='PATH_HAVE_FCHMOD')
  2938. Path to be modified. May always be specified as a str, bytes, or a path-like object.
  2939. On some platforms, path may also be specified as an open file descriptor.
  2940. If this functionality is unavailable, using it raises an exception.
  2941. mode: int
  2942. Operating-system mode bitfield.
  2943. Be careful when using number literals for *mode*. The conventional UNIX notation for
  2944. numeric modes uses an octal base, which needs to be indicated with a ``0o`` prefix in
  2945. Python.
  2946. *
  2947. dir_fd : dir_fd(requires='fchmodat') = None
  2948. If not None, it should be a file descriptor open to a directory,
  2949. and path should be relative; path will then be relative to that
  2950. directory.
  2951. follow_symlinks: bool = True
  2952. If False, and the last element of the path is a symbolic link,
  2953. chmod will modify the symbolic link itself instead of the file
  2954. the link points to.
  2955. Change the access permissions of a file.
  2956. It is an error to use dir_fd or follow_symlinks when specifying path as
  2957. an open file descriptor.
  2958. dir_fd and follow_symlinks may not be implemented on your platform.
  2959. If they are unavailable, using them will raise a NotImplementedError.
  2960. [clinic start generated code]*/
  2961. static PyObject *
  2962. os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
  2963. int follow_symlinks)
  2964. /*[clinic end generated code: output=5cf6a94915cc7bff input=674a14bc998de09d]*/
  2965. {
  2966. int result;
  2967. #ifdef MS_WINDOWS
  2968. DWORD attr;
  2969. #endif
  2970. #ifdef HAVE_FCHMODAT
  2971. int fchmodat_nofollow_unsupported = 0;
  2972. int fchmodat_unsupported = 0;
  2973. #endif
  2974. #if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
  2975. if (follow_symlinks_specified("chmod", follow_symlinks))
  2976. return NULL;
  2977. #endif
  2978. if (PySys_Audit("os.chmod", "Oii", path->object, mode,
  2979. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  2980. return NULL;
  2981. }
  2982. #ifdef MS_WINDOWS
  2983. Py_BEGIN_ALLOW_THREADS
  2984. attr = GetFileAttributesW(path->wide);
  2985. if (attr == INVALID_FILE_ATTRIBUTES)
  2986. result = 0;
  2987. else {
  2988. if (mode & _S_IWRITE)
  2989. attr &= ~FILE_ATTRIBUTE_READONLY;
  2990. else
  2991. attr |= FILE_ATTRIBUTE_READONLY;
  2992. result = SetFileAttributesW(path->wide, attr);
  2993. }
  2994. Py_END_ALLOW_THREADS
  2995. if (!result) {
  2996. return path_error(path);
  2997. }
  2998. #else /* MS_WINDOWS */
  2999. Py_BEGIN_ALLOW_THREADS
  3000. #ifdef HAVE_FCHMOD
  3001. if (path->fd != -1)
  3002. result = fchmod(path->fd, mode);
  3003. else
  3004. #endif /* HAVE_CHMOD */
  3005. #ifdef HAVE_LCHMOD
  3006. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  3007. result = lchmod(path->narrow, mode);
  3008. else
  3009. #endif /* HAVE_LCHMOD */
  3010. #ifdef HAVE_FCHMODAT
  3011. if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
  3012. if (HAVE_FCHMODAT_RUNTIME) {
  3013. /*
  3014. * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
  3015. * The documentation specifically shows how to use it,
  3016. * and then says it isn't implemented yet.
  3017. * (true on linux with glibc 2.15, and openindiana 3.x)
  3018. *
  3019. * Once it is supported, os.chmod will automatically
  3020. * support dir_fd and follow_symlinks=False. (Hopefully.)
  3021. * Until then, we need to be careful what exception we raise.
  3022. */
  3023. result = fchmodat(dir_fd, path->narrow, mode,
  3024. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  3025. /*
  3026. * But wait! We can't throw the exception without allowing threads,
  3027. * and we can't do that in this nested scope. (Macro trickery, sigh.)
  3028. */
  3029. fchmodat_nofollow_unsupported =
  3030. result &&
  3031. ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
  3032. !follow_symlinks;
  3033. } else {
  3034. fchmodat_unsupported = 1;
  3035. fchmodat_nofollow_unsupported = 1;
  3036. result = -1;
  3037. }
  3038. }
  3039. else
  3040. #endif /* HAVE_FHCMODAT */
  3041. {
  3042. #ifdef HAVE_CHMOD
  3043. result = chmod(path->narrow, mode);
  3044. #elif defined(__wasi__)
  3045. // WASI SDK 15.0 does not support chmod.
  3046. // Ignore missing syscall for now.
  3047. result = 0;
  3048. #else
  3049. result = -1;
  3050. errno = ENOSYS;
  3051. #endif
  3052. }
  3053. Py_END_ALLOW_THREADS
  3054. if (result) {
  3055. #ifdef HAVE_FCHMODAT
  3056. if (fchmodat_unsupported) {
  3057. if (dir_fd != DEFAULT_DIR_FD) {
  3058. argument_unavailable_error("chmod", "dir_fd");
  3059. return NULL;
  3060. }
  3061. }
  3062. if (fchmodat_nofollow_unsupported) {
  3063. if (dir_fd != DEFAULT_DIR_FD)
  3064. dir_fd_and_follow_symlinks_invalid("chmod",
  3065. dir_fd, follow_symlinks);
  3066. else
  3067. follow_symlinks_specified("chmod", follow_symlinks);
  3068. return NULL;
  3069. }
  3070. else
  3071. #endif /* HAVE_FCHMODAT */
  3072. return path_error(path);
  3073. }
  3074. #endif /* MS_WINDOWS */
  3075. Py_RETURN_NONE;
  3076. }
  3077. #ifdef HAVE_FCHMOD
  3078. /*[clinic input]
  3079. os.fchmod
  3080. fd: int
  3081. The file descriptor of the file to be modified.
  3082. mode: int
  3083. Operating-system mode bitfield.
  3084. Be careful when using number literals for *mode*. The conventional UNIX notation for
  3085. numeric modes uses an octal base, which needs to be indicated with a ``0o`` prefix in
  3086. Python.
  3087. Change the access permissions of the file given by file descriptor fd.
  3088. Equivalent to os.chmod(fd, mode).
  3089. [clinic start generated code]*/
  3090. static PyObject *
  3091. os_fchmod_impl(PyObject *module, int fd, int mode)
  3092. /*[clinic end generated code: output=afd9bc05b4e426b3 input=b5594618bbbc22df]*/
  3093. {
  3094. int res;
  3095. int async_err = 0;
  3096. if (PySys_Audit("os.chmod", "iii", fd, mode, -1) < 0) {
  3097. return NULL;
  3098. }
  3099. do {
  3100. Py_BEGIN_ALLOW_THREADS
  3101. res = fchmod(fd, mode);
  3102. Py_END_ALLOW_THREADS
  3103. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  3104. if (res != 0)
  3105. return (!async_err) ? posix_error() : NULL;
  3106. Py_RETURN_NONE;
  3107. }
  3108. #endif /* HAVE_FCHMOD */
  3109. #ifdef HAVE_LCHMOD
  3110. /*[clinic input]
  3111. os.lchmod
  3112. path: path_t
  3113. mode: int
  3114. Change the access permissions of a file, without following symbolic links.
  3115. If path is a symlink, this affects the link itself rather than the target.
  3116. Equivalent to chmod(path, mode, follow_symlinks=False)."
  3117. [clinic start generated code]*/
  3118. static PyObject *
  3119. os_lchmod_impl(PyObject *module, path_t *path, int mode)
  3120. /*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
  3121. {
  3122. int res;
  3123. if (PySys_Audit("os.chmod", "Oii", path->object, mode, -1) < 0) {
  3124. return NULL;
  3125. }
  3126. Py_BEGIN_ALLOW_THREADS
  3127. res = lchmod(path->narrow, mode);
  3128. Py_END_ALLOW_THREADS
  3129. if (res < 0) {
  3130. path_error(path);
  3131. return NULL;
  3132. }
  3133. Py_RETURN_NONE;
  3134. }
  3135. #endif /* HAVE_LCHMOD */
  3136. #ifdef HAVE_CHFLAGS
  3137. /*[clinic input]
  3138. os.chflags
  3139. path: path_t
  3140. flags: unsigned_long(bitwise=True)
  3141. follow_symlinks: bool=True
  3142. Set file flags.
  3143. If follow_symlinks is False, and the last element of the path is a symbolic
  3144. link, chflags will change flags on the symbolic link itself instead of the
  3145. file the link points to.
  3146. follow_symlinks may not be implemented on your platform. If it is
  3147. unavailable, using it will raise a NotImplementedError.
  3148. [clinic start generated code]*/
  3149. static PyObject *
  3150. os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
  3151. int follow_symlinks)
  3152. /*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
  3153. {
  3154. int result;
  3155. #ifndef HAVE_LCHFLAGS
  3156. if (follow_symlinks_specified("chflags", follow_symlinks))
  3157. return NULL;
  3158. #endif
  3159. if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
  3160. return NULL;
  3161. }
  3162. Py_BEGIN_ALLOW_THREADS
  3163. #ifdef HAVE_LCHFLAGS
  3164. if (!follow_symlinks)
  3165. result = lchflags(path->narrow, flags);
  3166. else
  3167. #endif
  3168. result = chflags(path->narrow, flags);
  3169. Py_END_ALLOW_THREADS
  3170. if (result)
  3171. return path_error(path);
  3172. Py_RETURN_NONE;
  3173. }
  3174. #endif /* HAVE_CHFLAGS */
  3175. #ifdef HAVE_LCHFLAGS
  3176. /*[clinic input]
  3177. os.lchflags
  3178. path: path_t
  3179. flags: unsigned_long(bitwise=True)
  3180. Set file flags.
  3181. This function will not follow symbolic links.
  3182. Equivalent to chflags(path, flags, follow_symlinks=False).
  3183. [clinic start generated code]*/
  3184. static PyObject *
  3185. os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
  3186. /*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
  3187. {
  3188. int res;
  3189. if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
  3190. return NULL;
  3191. }
  3192. Py_BEGIN_ALLOW_THREADS
  3193. res = lchflags(path->narrow, flags);
  3194. Py_END_ALLOW_THREADS
  3195. if (res < 0) {
  3196. return path_error(path);
  3197. }
  3198. Py_RETURN_NONE;
  3199. }
  3200. #endif /* HAVE_LCHFLAGS */
  3201. #ifdef HAVE_CHROOT
  3202. /*[clinic input]
  3203. os.chroot
  3204. path: path_t
  3205. Change root directory to path.
  3206. [clinic start generated code]*/
  3207. static PyObject *
  3208. os_chroot_impl(PyObject *module, path_t *path)
  3209. /*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
  3210. {
  3211. int res;
  3212. Py_BEGIN_ALLOW_THREADS
  3213. res = chroot(path->narrow);
  3214. Py_END_ALLOW_THREADS
  3215. if (res < 0)
  3216. return path_error(path);
  3217. Py_RETURN_NONE;
  3218. }
  3219. #endif /* HAVE_CHROOT */
  3220. #ifdef HAVE_FSYNC
  3221. /*[clinic input]
  3222. os.fsync
  3223. fd: fildes
  3224. Force write of fd to disk.
  3225. [clinic start generated code]*/
  3226. static PyObject *
  3227. os_fsync_impl(PyObject *module, int fd)
  3228. /*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
  3229. {
  3230. return posix_fildes_fd(fd, fsync);
  3231. }
  3232. #endif /* HAVE_FSYNC */
  3233. #ifdef HAVE_SYNC
  3234. /*[clinic input]
  3235. os.sync
  3236. Force write of everything to disk.
  3237. [clinic start generated code]*/
  3238. static PyObject *
  3239. os_sync_impl(PyObject *module)
  3240. /*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
  3241. {
  3242. Py_BEGIN_ALLOW_THREADS
  3243. sync();
  3244. Py_END_ALLOW_THREADS
  3245. Py_RETURN_NONE;
  3246. }
  3247. #endif /* HAVE_SYNC */
  3248. #ifdef HAVE_FDATASYNC
  3249. #ifdef __hpux
  3250. extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
  3251. #endif
  3252. /*[clinic input]
  3253. os.fdatasync
  3254. fd: fildes
  3255. Force write of fd to disk without forcing update of metadata.
  3256. [clinic start generated code]*/
  3257. static PyObject *
  3258. os_fdatasync_impl(PyObject *module, int fd)
  3259. /*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
  3260. {
  3261. return posix_fildes_fd(fd, fdatasync);
  3262. }
  3263. #endif /* HAVE_FDATASYNC */
  3264. #ifdef HAVE_CHOWN
  3265. /*[clinic input]
  3266. os.chown
  3267. path : path_t(allow_fd='PATH_HAVE_FCHOWN')
  3268. Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
  3269. uid: uid_t
  3270. gid: gid_t
  3271. *
  3272. dir_fd : dir_fd(requires='fchownat') = None
  3273. If not None, it should be a file descriptor open to a directory,
  3274. and path should be relative; path will then be relative to that
  3275. directory.
  3276. follow_symlinks: bool = True
  3277. If False, and the last element of the path is a symbolic link,
  3278. stat will examine the symbolic link itself instead of the file
  3279. the link points to.
  3280. Change the owner and group id of path to the numeric uid and gid.\
  3281. path may always be specified as a string.
  3282. On some platforms, path may also be specified as an open file descriptor.
  3283. If this functionality is unavailable, using it raises an exception.
  3284. If dir_fd is not None, it should be a file descriptor open to a directory,
  3285. and path should be relative; path will then be relative to that directory.
  3286. If follow_symlinks is False, and the last element of the path is a symbolic
  3287. link, chown will modify the symbolic link itself instead of the file the
  3288. link points to.
  3289. It is an error to use dir_fd or follow_symlinks when specifying path as
  3290. an open file descriptor.
  3291. dir_fd and follow_symlinks may not be implemented on your platform.
  3292. If they are unavailable, using them will raise a NotImplementedError.
  3293. [clinic start generated code]*/
  3294. static PyObject *
  3295. os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
  3296. int dir_fd, int follow_symlinks)
  3297. /*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
  3298. {
  3299. int result;
  3300. #if defined(HAVE_FCHOWNAT)
  3301. int fchownat_unsupported = 0;
  3302. #endif
  3303. #if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
  3304. if (follow_symlinks_specified("chown", follow_symlinks))
  3305. return NULL;
  3306. #endif
  3307. if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
  3308. fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
  3309. return NULL;
  3310. if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid,
  3311. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  3312. return NULL;
  3313. }
  3314. Py_BEGIN_ALLOW_THREADS
  3315. #ifdef HAVE_FCHOWN
  3316. if (path->fd != -1)
  3317. result = fchown(path->fd, uid, gid);
  3318. else
  3319. #endif
  3320. #ifdef HAVE_LCHOWN
  3321. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  3322. result = lchown(path->narrow, uid, gid);
  3323. else
  3324. #endif
  3325. #ifdef HAVE_FCHOWNAT
  3326. if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks)) {
  3327. if (HAVE_FCHOWNAT_RUNTIME) {
  3328. result = fchownat(dir_fd, path->narrow, uid, gid,
  3329. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  3330. } else {
  3331. fchownat_unsupported = 1;
  3332. }
  3333. } else
  3334. #endif
  3335. result = chown(path->narrow, uid, gid);
  3336. Py_END_ALLOW_THREADS
  3337. #ifdef HAVE_FCHOWNAT
  3338. if (fchownat_unsupported) {
  3339. /* This would be incorrect if the current platform
  3340. * doesn't support lchown.
  3341. */
  3342. argument_unavailable_error(NULL, "dir_fd");
  3343. return NULL;
  3344. }
  3345. #endif
  3346. if (result)
  3347. return path_error(path);
  3348. Py_RETURN_NONE;
  3349. }
  3350. #endif /* HAVE_CHOWN */
  3351. #ifdef HAVE_FCHOWN
  3352. /*[clinic input]
  3353. os.fchown
  3354. fd: int
  3355. uid: uid_t
  3356. gid: gid_t
  3357. Change the owner and group id of the file specified by file descriptor.
  3358. Equivalent to os.chown(fd, uid, gid).
  3359. [clinic start generated code]*/
  3360. static PyObject *
  3361. os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
  3362. /*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
  3363. {
  3364. int res;
  3365. int async_err = 0;
  3366. if (PySys_Audit("os.chown", "iIIi", fd, uid, gid, -1) < 0) {
  3367. return NULL;
  3368. }
  3369. do {
  3370. Py_BEGIN_ALLOW_THREADS
  3371. res = fchown(fd, uid, gid);
  3372. Py_END_ALLOW_THREADS
  3373. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  3374. if (res != 0)
  3375. return (!async_err) ? posix_error() : NULL;
  3376. Py_RETURN_NONE;
  3377. }
  3378. #endif /* HAVE_FCHOWN */
  3379. #ifdef HAVE_LCHOWN
  3380. /*[clinic input]
  3381. os.lchown
  3382. path : path_t
  3383. uid: uid_t
  3384. gid: gid_t
  3385. Change the owner and group id of path to the numeric uid and gid.
  3386. This function will not follow symbolic links.
  3387. Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
  3388. [clinic start generated code]*/
  3389. static PyObject *
  3390. os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
  3391. /*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
  3392. {
  3393. int res;
  3394. if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid, -1) < 0) {
  3395. return NULL;
  3396. }
  3397. Py_BEGIN_ALLOW_THREADS
  3398. res = lchown(path->narrow, uid, gid);
  3399. Py_END_ALLOW_THREADS
  3400. if (res < 0) {
  3401. return path_error(path);
  3402. }
  3403. Py_RETURN_NONE;
  3404. }
  3405. #endif /* HAVE_LCHOWN */
  3406. static PyObject *
  3407. posix_getcwd(int use_bytes)
  3408. {
  3409. #ifdef MS_WINDOWS
  3410. wchar_t wbuf[MAXPATHLEN];
  3411. wchar_t *wbuf2 = wbuf;
  3412. DWORD len;
  3413. Py_BEGIN_ALLOW_THREADS
  3414. len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
  3415. /* If the buffer is large enough, len does not include the
  3416. terminating \0. If the buffer is too small, len includes
  3417. the space needed for the terminator. */
  3418. if (len >= Py_ARRAY_LENGTH(wbuf)) {
  3419. if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  3420. wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
  3421. }
  3422. else {
  3423. wbuf2 = NULL;
  3424. }
  3425. if (wbuf2) {
  3426. len = GetCurrentDirectoryW(len, wbuf2);
  3427. }
  3428. }
  3429. Py_END_ALLOW_THREADS
  3430. if (!wbuf2) {
  3431. PyErr_NoMemory();
  3432. return NULL;
  3433. }
  3434. if (!len) {
  3435. PyErr_SetFromWindowsErr(0);
  3436. if (wbuf2 != wbuf)
  3437. PyMem_RawFree(wbuf2);
  3438. return NULL;
  3439. }
  3440. PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
  3441. if (wbuf2 != wbuf) {
  3442. PyMem_RawFree(wbuf2);
  3443. }
  3444. if (use_bytes) {
  3445. if (resobj == NULL) {
  3446. return NULL;
  3447. }
  3448. Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
  3449. }
  3450. return resobj;
  3451. #else
  3452. const size_t chunk = 1024;
  3453. char *buf = NULL;
  3454. char *cwd = NULL;
  3455. size_t buflen = 0;
  3456. Py_BEGIN_ALLOW_THREADS
  3457. do {
  3458. char *newbuf;
  3459. if (buflen <= PY_SSIZE_T_MAX - chunk) {
  3460. buflen += chunk;
  3461. newbuf = PyMem_RawRealloc(buf, buflen);
  3462. }
  3463. else {
  3464. newbuf = NULL;
  3465. }
  3466. if (newbuf == NULL) {
  3467. PyMem_RawFree(buf);
  3468. buf = NULL;
  3469. break;
  3470. }
  3471. buf = newbuf;
  3472. cwd = getcwd(buf, buflen);
  3473. } while (cwd == NULL && errno == ERANGE);
  3474. Py_END_ALLOW_THREADS
  3475. if (buf == NULL) {
  3476. return PyErr_NoMemory();
  3477. }
  3478. if (cwd == NULL) {
  3479. posix_error();
  3480. PyMem_RawFree(buf);
  3481. return NULL;
  3482. }
  3483. PyObject *obj;
  3484. if (use_bytes) {
  3485. obj = PyBytes_FromStringAndSize(buf, strlen(buf));
  3486. }
  3487. else {
  3488. obj = PyUnicode_DecodeFSDefault(buf);
  3489. }
  3490. PyMem_RawFree(buf);
  3491. return obj;
  3492. #endif /* !MS_WINDOWS */
  3493. }
  3494. /*[clinic input]
  3495. os.getcwd
  3496. Return a unicode string representing the current working directory.
  3497. [clinic start generated code]*/
  3498. static PyObject *
  3499. os_getcwd_impl(PyObject *module)
  3500. /*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
  3501. {
  3502. return posix_getcwd(0);
  3503. }
  3504. /*[clinic input]
  3505. os.getcwdb
  3506. Return a bytes string representing the current working directory.
  3507. [clinic start generated code]*/
  3508. static PyObject *
  3509. os_getcwdb_impl(PyObject *module)
  3510. /*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
  3511. {
  3512. return posix_getcwd(1);
  3513. }
  3514. #if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
  3515. #define HAVE_LINK 1
  3516. #endif
  3517. #ifdef HAVE_LINK
  3518. /*[clinic input]
  3519. os.link
  3520. src : path_t
  3521. dst : path_t
  3522. *
  3523. src_dir_fd : dir_fd = None
  3524. dst_dir_fd : dir_fd = None
  3525. follow_symlinks: bool = True
  3526. Create a hard link to a file.
  3527. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  3528. descriptor open to a directory, and the respective path string (src or dst)
  3529. should be relative; the path will then be relative to that directory.
  3530. If follow_symlinks is False, and the last element of src is a symbolic
  3531. link, link will create a link to the symbolic link itself instead of the
  3532. file the link points to.
  3533. src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
  3534. platform. If they are unavailable, using them will raise a
  3535. NotImplementedError.
  3536. [clinic start generated code]*/
  3537. static PyObject *
  3538. os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  3539. int dst_dir_fd, int follow_symlinks)
  3540. /*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
  3541. {
  3542. #ifdef MS_WINDOWS
  3543. BOOL result = FALSE;
  3544. #else
  3545. int result;
  3546. #endif
  3547. #if defined(HAVE_LINKAT)
  3548. int linkat_unavailable = 0;
  3549. #endif
  3550. #ifndef HAVE_LINKAT
  3551. if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
  3552. argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
  3553. return NULL;
  3554. }
  3555. #endif
  3556. #ifndef MS_WINDOWS
  3557. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  3558. PyErr_SetString(PyExc_NotImplementedError,
  3559. "link: src and dst must be the same type");
  3560. return NULL;
  3561. }
  3562. #endif
  3563. if (PySys_Audit("os.link", "OOii", src->object, dst->object,
  3564. src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
  3565. dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
  3566. return NULL;
  3567. }
  3568. #ifdef MS_WINDOWS
  3569. Py_BEGIN_ALLOW_THREADS
  3570. result = CreateHardLinkW(dst->wide, src->wide, NULL);
  3571. Py_END_ALLOW_THREADS
  3572. if (!result)
  3573. return path_error2(src, dst);
  3574. #else
  3575. Py_BEGIN_ALLOW_THREADS
  3576. #ifdef HAVE_LINKAT
  3577. if ((src_dir_fd != DEFAULT_DIR_FD) ||
  3578. (dst_dir_fd != DEFAULT_DIR_FD) ||
  3579. (!follow_symlinks)) {
  3580. if (HAVE_LINKAT_RUNTIME) {
  3581. result = linkat(src_dir_fd, src->narrow,
  3582. dst_dir_fd, dst->narrow,
  3583. follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
  3584. }
  3585. #ifdef __APPLE__
  3586. else {
  3587. if (src_dir_fd == DEFAULT_DIR_FD && dst_dir_fd == DEFAULT_DIR_FD) {
  3588. /* See issue 41355: This matches the behaviour of !HAVE_LINKAT */
  3589. result = link(src->narrow, dst->narrow);
  3590. } else {
  3591. linkat_unavailable = 1;
  3592. }
  3593. }
  3594. #endif
  3595. }
  3596. else
  3597. #endif /* HAVE_LINKAT */
  3598. result = link(src->narrow, dst->narrow);
  3599. Py_END_ALLOW_THREADS
  3600. #ifdef HAVE_LINKAT
  3601. if (linkat_unavailable) {
  3602. /* Either or both dir_fd arguments were specified */
  3603. if (src_dir_fd != DEFAULT_DIR_FD) {
  3604. argument_unavailable_error("link", "src_dir_fd");
  3605. } else {
  3606. argument_unavailable_error("link", "dst_dir_fd");
  3607. }
  3608. return NULL;
  3609. }
  3610. #endif
  3611. if (result)
  3612. return path_error2(src, dst);
  3613. #endif /* MS_WINDOWS */
  3614. Py_RETURN_NONE;
  3615. }
  3616. #endif
  3617. #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
  3618. static PyObject *
  3619. _listdir_windows_no_opendir(path_t *path, PyObject *list)
  3620. {
  3621. PyObject *v;
  3622. HANDLE hFindFile = INVALID_HANDLE_VALUE;
  3623. BOOL result, return_bytes;
  3624. wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
  3625. /* only claim to have space for MAX_PATH */
  3626. Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
  3627. wchar_t *wnamebuf = NULL;
  3628. WIN32_FIND_DATAW wFileData;
  3629. const wchar_t *po_wchars;
  3630. if (!path->wide) { /* Default arg: "." */
  3631. po_wchars = L".";
  3632. len = 1;
  3633. return_bytes = 0;
  3634. } else {
  3635. po_wchars = path->wide;
  3636. len = wcslen(path->wide);
  3637. return_bytes = PyBytes_Check(path->object);
  3638. }
  3639. /* The +5 is so we can append "\\*.*\0" */
  3640. wnamebuf = PyMem_New(wchar_t, len + 5);
  3641. if (!wnamebuf) {
  3642. PyErr_NoMemory();
  3643. goto exit;
  3644. }
  3645. wcscpy(wnamebuf, po_wchars);
  3646. if (len > 0) {
  3647. wchar_t wch = wnamebuf[len-1];
  3648. if (wch != SEP && wch != ALTSEP && wch != L':')
  3649. wnamebuf[len++] = SEP;
  3650. wcscpy(wnamebuf + len, L"*.*");
  3651. }
  3652. if ((list = PyList_New(0)) == NULL) {
  3653. goto exit;
  3654. }
  3655. Py_BEGIN_ALLOW_THREADS
  3656. hFindFile = FindFirstFileW(wnamebuf, &wFileData);
  3657. Py_END_ALLOW_THREADS
  3658. if (hFindFile == INVALID_HANDLE_VALUE) {
  3659. int error = GetLastError();
  3660. if (error == ERROR_FILE_NOT_FOUND)
  3661. goto exit;
  3662. path_error(path);
  3663. Py_CLEAR(list);
  3664. goto exit;
  3665. }
  3666. do {
  3667. /* Skip over . and .. */
  3668. if (wcscmp(wFileData.cFileName, L".") != 0 &&
  3669. wcscmp(wFileData.cFileName, L"..") != 0) {
  3670. v = PyUnicode_FromWideChar(wFileData.cFileName,
  3671. wcslen(wFileData.cFileName));
  3672. if (return_bytes && v) {
  3673. Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
  3674. }
  3675. if (v == NULL) {
  3676. Py_CLEAR(list);
  3677. break;
  3678. }
  3679. if (PyList_Append(list, v) != 0) {
  3680. Py_DECREF(v);
  3681. Py_CLEAR(list);
  3682. break;
  3683. }
  3684. Py_DECREF(v);
  3685. }
  3686. Py_BEGIN_ALLOW_THREADS
  3687. result = FindNextFileW(hFindFile, &wFileData);
  3688. Py_END_ALLOW_THREADS
  3689. /* FindNextFile sets error to ERROR_NO_MORE_FILES if
  3690. it got to the end of the directory. */
  3691. if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
  3692. path_error(path);
  3693. Py_CLEAR(list);
  3694. goto exit;
  3695. }
  3696. } while (result == TRUE);
  3697. exit:
  3698. if (hFindFile != INVALID_HANDLE_VALUE) {
  3699. if (FindClose(hFindFile) == FALSE) {
  3700. if (list != NULL) {
  3701. path_error(path);
  3702. Py_CLEAR(list);
  3703. }
  3704. }
  3705. }
  3706. PyMem_Free(wnamebuf);
  3707. return list;
  3708. } /* end of _listdir_windows_no_opendir */
  3709. #else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
  3710. static PyObject *
  3711. _posix_listdir(path_t *path, PyObject *list)
  3712. {
  3713. PyObject *v;
  3714. DIR *dirp = NULL;
  3715. struct dirent *ep;
  3716. int return_str; /* if false, return bytes */
  3717. #ifdef HAVE_FDOPENDIR
  3718. int fd = -1;
  3719. #endif
  3720. errno = 0;
  3721. #ifdef HAVE_FDOPENDIR
  3722. if (path->fd != -1) {
  3723. if (HAVE_FDOPENDIR_RUNTIME) {
  3724. /* closedir() closes the FD, so we duplicate it */
  3725. fd = _Py_dup(path->fd);
  3726. if (fd == -1)
  3727. return NULL;
  3728. return_str = 1;
  3729. Py_BEGIN_ALLOW_THREADS
  3730. dirp = fdopendir(fd);
  3731. Py_END_ALLOW_THREADS
  3732. } else {
  3733. PyErr_SetString(PyExc_TypeError,
  3734. "listdir: path should be string, bytes, os.PathLike or None, not int");
  3735. return NULL;
  3736. }
  3737. }
  3738. else
  3739. #endif
  3740. {
  3741. const char *name;
  3742. if (path->narrow) {
  3743. name = path->narrow;
  3744. /* only return bytes if they specified a bytes object */
  3745. return_str = !PyBytes_Check(path->object);
  3746. }
  3747. else {
  3748. name = ".";
  3749. return_str = 1;
  3750. }
  3751. Py_BEGIN_ALLOW_THREADS
  3752. dirp = opendir(name);
  3753. Py_END_ALLOW_THREADS
  3754. }
  3755. if (dirp == NULL) {
  3756. path_error(path);
  3757. list = NULL;
  3758. #ifdef HAVE_FDOPENDIR
  3759. if (fd != -1) {
  3760. Py_BEGIN_ALLOW_THREADS
  3761. close(fd);
  3762. Py_END_ALLOW_THREADS
  3763. }
  3764. #endif
  3765. goto exit;
  3766. }
  3767. if ((list = PyList_New(0)) == NULL) {
  3768. goto exit;
  3769. }
  3770. for (;;) {
  3771. errno = 0;
  3772. Py_BEGIN_ALLOW_THREADS
  3773. ep = readdir(dirp);
  3774. Py_END_ALLOW_THREADS
  3775. if (ep == NULL) {
  3776. if (errno == 0) {
  3777. break;
  3778. } else {
  3779. path_error(path);
  3780. Py_CLEAR(list);
  3781. goto exit;
  3782. }
  3783. }
  3784. if (ep->d_name[0] == '.' &&
  3785. (NAMLEN(ep) == 1 ||
  3786. (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
  3787. continue;
  3788. if (return_str)
  3789. v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
  3790. else
  3791. v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
  3792. if (v == NULL) {
  3793. Py_CLEAR(list);
  3794. break;
  3795. }
  3796. if (PyList_Append(list, v) != 0) {
  3797. Py_DECREF(v);
  3798. Py_CLEAR(list);
  3799. break;
  3800. }
  3801. Py_DECREF(v);
  3802. }
  3803. exit:
  3804. if (dirp != NULL) {
  3805. Py_BEGIN_ALLOW_THREADS
  3806. #ifdef HAVE_FDOPENDIR
  3807. if (fd > -1)
  3808. rewinddir(dirp);
  3809. #endif
  3810. closedir(dirp);
  3811. Py_END_ALLOW_THREADS
  3812. }
  3813. return list;
  3814. } /* end of _posix_listdir */
  3815. #endif /* which OS */
  3816. /*[clinic input]
  3817. os.listdir
  3818. path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
  3819. Return a list containing the names of the files in the directory.
  3820. path can be specified as either str, bytes, or a path-like object. If path is bytes,
  3821. the filenames returned will also be bytes; in all other circumstances
  3822. the filenames returned will be str.
  3823. If path is None, uses the path='.'.
  3824. On some platforms, path may also be specified as an open file descriptor;\
  3825. the file descriptor must refer to a directory.
  3826. If this functionality is unavailable, using it raises NotImplementedError.
  3827. The list is in arbitrary order. It does not include the special
  3828. entries '.' and '..' even if they are present in the directory.
  3829. [clinic start generated code]*/
  3830. static PyObject *
  3831. os_listdir_impl(PyObject *module, path_t *path)
  3832. /*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
  3833. {
  3834. if (PySys_Audit("os.listdir", "O",
  3835. path->object ? path->object : Py_None) < 0) {
  3836. return NULL;
  3837. }
  3838. #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
  3839. return _listdir_windows_no_opendir(path, NULL);
  3840. #else
  3841. return _posix_listdir(path, NULL);
  3842. #endif
  3843. }
  3844. #ifdef MS_WINDOWS
  3845. /*[clinic input]
  3846. os.listdrives
  3847. Return a list containing the names of drives in the system.
  3848. A drive name typically looks like 'C:\\'.
  3849. [clinic start generated code]*/
  3850. static PyObject *
  3851. os_listdrives_impl(PyObject *module)
  3852. /*[clinic end generated code: output=aaece9dacdf682b5 input=1af9ccc9e583798e]*/
  3853. {
  3854. /* Number of possible drives is limited, so 256 should always be enough.
  3855. On the day when it is not, listmounts() will have to be used. */
  3856. wchar_t buffer[256];
  3857. DWORD buflen = Py_ARRAY_LENGTH(buffer);
  3858. PyObject *result = NULL;
  3859. if (PySys_Audit("os.listdrives", NULL) < 0) {
  3860. return NULL;
  3861. }
  3862. Py_BEGIN_ALLOW_THREADS;
  3863. buflen = GetLogicalDriveStringsW(buflen, buffer);
  3864. Py_END_ALLOW_THREADS;
  3865. if (!buflen) {
  3866. PyErr_SetFromWindowsErr(0);
  3867. return NULL;
  3868. } else if (buflen >= Py_ARRAY_LENGTH(buffer)) {
  3869. PyErr_SetFromWindowsErr(ERROR_MORE_DATA);
  3870. return NULL;
  3871. }
  3872. /* buflen includes a null terminator, so remove it */
  3873. PyObject *str = PyUnicode_FromWideChar(buffer, buflen - 1);
  3874. if (str) {
  3875. PyObject *nullchar = PyUnicode_FromStringAndSize("\0", 1);
  3876. if (nullchar) {
  3877. result = PyUnicode_Split(str, nullchar, -1);
  3878. Py_DECREF(nullchar);
  3879. }
  3880. Py_DECREF(str);
  3881. }
  3882. return result;
  3883. }
  3884. /*[clinic input]
  3885. os.listvolumes
  3886. Return a list containing the volumes in the system.
  3887. Volumes are typically represented as a GUID path.
  3888. [clinic start generated code]*/
  3889. static PyObject *
  3890. os_listvolumes_impl(PyObject *module)
  3891. /*[clinic end generated code: output=534e10ea2bf9d386 input=f6e4e70371f11e99]*/
  3892. {
  3893. PyObject *result = PyList_New(0);
  3894. HANDLE find = INVALID_HANDLE_VALUE;
  3895. wchar_t buffer[MAX_PATH + 1];
  3896. if (!result) {
  3897. return NULL;
  3898. }
  3899. if (PySys_Audit("os.listvolumes", NULL) < 0) {
  3900. Py_DECREF(result);
  3901. return NULL;
  3902. }
  3903. int err = 0;
  3904. Py_BEGIN_ALLOW_THREADS;
  3905. find = FindFirstVolumeW(buffer, Py_ARRAY_LENGTH(buffer));
  3906. if (find == INVALID_HANDLE_VALUE) {
  3907. err = GetLastError();
  3908. }
  3909. Py_END_ALLOW_THREADS;
  3910. while (!err) {
  3911. PyObject *s = PyUnicode_FromWideChar(buffer, -1);
  3912. if (!s || PyList_Append(result, s) < 0) {
  3913. Py_XDECREF(s);
  3914. Py_CLEAR(result);
  3915. break;
  3916. }
  3917. Py_DECREF(s);
  3918. Py_BEGIN_ALLOW_THREADS;
  3919. if (!FindNextVolumeW(find, buffer, Py_ARRAY_LENGTH(buffer))) {
  3920. err = GetLastError();
  3921. }
  3922. Py_END_ALLOW_THREADS;
  3923. }
  3924. if (find != INVALID_HANDLE_VALUE) {
  3925. Py_BEGIN_ALLOW_THREADS;
  3926. FindVolumeClose(find);
  3927. Py_END_ALLOW_THREADS;
  3928. }
  3929. if (err && err != ERROR_NO_MORE_FILES) {
  3930. PyErr_SetFromWindowsErr(err);
  3931. Py_XDECREF(result);
  3932. result = NULL;
  3933. }
  3934. return result;
  3935. }
  3936. /*[clinic input]
  3937. os.listmounts
  3938. volume: path_t
  3939. Return a list containing mount points for a particular volume.
  3940. 'volume' should be a GUID path as returned from os.listvolumes.
  3941. [clinic start generated code]*/
  3942. static PyObject *
  3943. os_listmounts_impl(PyObject *module, path_t *volume)
  3944. /*[clinic end generated code: output=06da49679de4512e input=a8a27178e3f67845]*/
  3945. {
  3946. wchar_t default_buffer[MAX_PATH + 1];
  3947. DWORD buflen = Py_ARRAY_LENGTH(default_buffer);
  3948. LPWSTR buffer = default_buffer;
  3949. DWORD attributes;
  3950. PyObject *str = NULL;
  3951. PyObject *nullchar = NULL;
  3952. PyObject *result = NULL;
  3953. /* Ensure we have a valid volume path before continuing */
  3954. Py_BEGIN_ALLOW_THREADS
  3955. attributes = GetFileAttributesW(volume->wide);
  3956. Py_END_ALLOW_THREADS
  3957. if (attributes == INVALID_FILE_ATTRIBUTES &&
  3958. GetLastError() == ERROR_UNRECOGNIZED_VOLUME)
  3959. {
  3960. return PyErr_SetFromWindowsErr(ERROR_UNRECOGNIZED_VOLUME);
  3961. }
  3962. if (PySys_Audit("os.listmounts", "O", volume->object) < 0) {
  3963. return NULL;
  3964. }
  3965. while (1) {
  3966. BOOL success;
  3967. Py_BEGIN_ALLOW_THREADS
  3968. success = GetVolumePathNamesForVolumeNameW(volume->wide, buffer,
  3969. buflen, &buflen);
  3970. Py_END_ALLOW_THREADS
  3971. if (success) {
  3972. break;
  3973. }
  3974. if (GetLastError() != ERROR_MORE_DATA) {
  3975. PyErr_SetFromWindowsErr(0);
  3976. goto exit;
  3977. }
  3978. if (buffer != default_buffer) {
  3979. PyMem_Free((void *)buffer);
  3980. }
  3981. buffer = (wchar_t*)PyMem_Malloc(sizeof(wchar_t) * buflen);
  3982. if (!buffer) {
  3983. PyErr_NoMemory();
  3984. goto exit;
  3985. }
  3986. }
  3987. if (buflen < 2) {
  3988. result = PyList_New(0);
  3989. goto exit;
  3990. }
  3991. // buflen includes two null terminators, one for the last string
  3992. // and one for the array of strings.
  3993. str = PyUnicode_FromWideChar(buffer, buflen - 2);
  3994. nullchar = PyUnicode_FromStringAndSize("\0", 1);
  3995. if (str && nullchar) {
  3996. result = PyUnicode_Split(str, nullchar, -1);
  3997. }
  3998. exit:
  3999. if (buffer != default_buffer) {
  4000. PyMem_Free(buffer);
  4001. }
  4002. Py_XDECREF(nullchar);
  4003. Py_XDECREF(str);
  4004. return result;
  4005. }
  4006. /*[clinic input]
  4007. os._path_isdevdrive
  4008. path: path_t
  4009. Determines whether the specified path is on a Windows Dev Drive.
  4010. [clinic start generated code]*/
  4011. static PyObject *
  4012. os__path_isdevdrive_impl(PyObject *module, path_t *path)
  4013. /*[clinic end generated code: output=1f437ea6677433a2 input=ee83e4996a48e23d]*/
  4014. {
  4015. #ifndef PERSISTENT_VOLUME_STATE_DEV_VOLUME
  4016. /* This flag will be documented at
  4017. https://learn.microsoft.com/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_fs_persistent_volume_information
  4018. after release, and will be available in the latest WinSDK.
  4019. We include the flag to avoid a specific version dependency
  4020. on the latest WinSDK. */
  4021. const int PERSISTENT_VOLUME_STATE_DEV_VOLUME = 0x00002000;
  4022. #endif
  4023. int err = 0;
  4024. PyObject *r = NULL;
  4025. wchar_t volume[MAX_PATH];
  4026. Py_BEGIN_ALLOW_THREADS
  4027. if (!GetVolumePathNameW(path->wide, volume, MAX_PATH)) {
  4028. /* invalid path of some kind */
  4029. /* Note that this also includes the case where a volume is mounted
  4030. in a path longer than 260 characters. This is likely to be rare
  4031. and problematic for other reasons, so a (soft) failure in this
  4032. check seems okay. */
  4033. err = GetLastError();
  4034. } else if (GetDriveTypeW(volume) != DRIVE_FIXED) {
  4035. /* only care about local dev drives */
  4036. r = Py_False;
  4037. } else {
  4038. HANDLE hVolume = CreateFileW(
  4039. volume,
  4040. FILE_READ_ATTRIBUTES,
  4041. FILE_SHARE_READ | FILE_SHARE_WRITE,
  4042. NULL,
  4043. OPEN_EXISTING,
  4044. FILE_FLAG_BACKUP_SEMANTICS,
  4045. NULL
  4046. );
  4047. if (hVolume == INVALID_HANDLE_VALUE) {
  4048. err = GetLastError();
  4049. } else {
  4050. FILE_FS_PERSISTENT_VOLUME_INFORMATION volumeState = {0};
  4051. volumeState.Version = 1;
  4052. volumeState.FlagMask = PERSISTENT_VOLUME_STATE_DEV_VOLUME;
  4053. if (!DeviceIoControl(
  4054. hVolume,
  4055. FSCTL_QUERY_PERSISTENT_VOLUME_STATE,
  4056. &volumeState,
  4057. sizeof(volumeState),
  4058. &volumeState,
  4059. sizeof(volumeState),
  4060. NULL,
  4061. NULL
  4062. )) {
  4063. err = GetLastError();
  4064. }
  4065. CloseHandle(hVolume);
  4066. if (err == ERROR_INVALID_PARAMETER) {
  4067. /* not supported on this platform */
  4068. r = Py_False;
  4069. } else if (!err) {
  4070. r = (volumeState.VolumeFlags & PERSISTENT_VOLUME_STATE_DEV_VOLUME)
  4071. ? Py_True : Py_False;
  4072. }
  4073. }
  4074. }
  4075. Py_END_ALLOW_THREADS
  4076. if (err) {
  4077. PyErr_SetFromWindowsErr(err);
  4078. return NULL;
  4079. }
  4080. if (r) {
  4081. return Py_NewRef(r);
  4082. }
  4083. return NULL;
  4084. }
  4085. int
  4086. _PyOS_getfullpathname(const wchar_t *path, wchar_t **abspath_p)
  4087. {
  4088. wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
  4089. DWORD result;
  4090. result = GetFullPathNameW(path,
  4091. Py_ARRAY_LENGTH(woutbuf), woutbuf,
  4092. NULL);
  4093. if (!result) {
  4094. return -1;
  4095. }
  4096. if (result >= Py_ARRAY_LENGTH(woutbuf)) {
  4097. if ((size_t)result <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  4098. woutbufp = PyMem_RawMalloc((size_t)result * sizeof(wchar_t));
  4099. }
  4100. else {
  4101. woutbufp = NULL;
  4102. }
  4103. if (!woutbufp) {
  4104. *abspath_p = NULL;
  4105. return 0;
  4106. }
  4107. result = GetFullPathNameW(path, result, woutbufp, NULL);
  4108. if (!result) {
  4109. PyMem_RawFree(woutbufp);
  4110. return -1;
  4111. }
  4112. }
  4113. if (woutbufp != woutbuf) {
  4114. *abspath_p = woutbufp;
  4115. return 0;
  4116. }
  4117. *abspath_p = _PyMem_RawWcsdup(woutbufp);
  4118. return 0;
  4119. }
  4120. /* A helper function for abspath on win32 */
  4121. /*[clinic input]
  4122. os._getfullpathname
  4123. path: path_t
  4124. /
  4125. [clinic start generated code]*/
  4126. static PyObject *
  4127. os__getfullpathname_impl(PyObject *module, path_t *path)
  4128. /*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
  4129. {
  4130. wchar_t *abspath;
  4131. if (_PyOS_getfullpathname(path->wide, &abspath) < 0) {
  4132. return win32_error_object("GetFullPathNameW", path->object);
  4133. }
  4134. if (abspath == NULL) {
  4135. return PyErr_NoMemory();
  4136. }
  4137. PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
  4138. PyMem_RawFree(abspath);
  4139. if (str == NULL) {
  4140. return NULL;
  4141. }
  4142. if (PyBytes_Check(path->object)) {
  4143. Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
  4144. }
  4145. return str;
  4146. }
  4147. /*[clinic input]
  4148. os._getfinalpathname
  4149. path: path_t
  4150. /
  4151. A helper function for samepath on windows.
  4152. [clinic start generated code]*/
  4153. static PyObject *
  4154. os__getfinalpathname_impl(PyObject *module, path_t *path)
  4155. /*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
  4156. {
  4157. HANDLE hFile;
  4158. wchar_t buf[MAXPATHLEN], *target_path = buf;
  4159. int buf_size = Py_ARRAY_LENGTH(buf);
  4160. int result_length;
  4161. PyObject *result;
  4162. Py_BEGIN_ALLOW_THREADS
  4163. hFile = CreateFileW(
  4164. path->wide,
  4165. 0, /* desired access */
  4166. 0, /* share mode */
  4167. NULL, /* security attributes */
  4168. OPEN_EXISTING,
  4169. /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
  4170. FILE_FLAG_BACKUP_SEMANTICS,
  4171. NULL);
  4172. Py_END_ALLOW_THREADS
  4173. if (hFile == INVALID_HANDLE_VALUE) {
  4174. return win32_error_object("CreateFileW", path->object);
  4175. }
  4176. /* We have a good handle to the target, use it to determine the
  4177. target path name. */
  4178. while (1) {
  4179. Py_BEGIN_ALLOW_THREADS
  4180. result_length = GetFinalPathNameByHandleW(hFile, target_path,
  4181. buf_size, VOLUME_NAME_DOS);
  4182. Py_END_ALLOW_THREADS
  4183. if (!result_length) {
  4184. result = win32_error_object("GetFinalPathNameByHandleW",
  4185. path->object);
  4186. goto cleanup;
  4187. }
  4188. if (result_length < buf_size) {
  4189. break;
  4190. }
  4191. wchar_t *tmp;
  4192. tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
  4193. result_length * sizeof(*tmp));
  4194. if (!tmp) {
  4195. result = PyErr_NoMemory();
  4196. goto cleanup;
  4197. }
  4198. buf_size = result_length;
  4199. target_path = tmp;
  4200. }
  4201. result = PyUnicode_FromWideChar(target_path, result_length);
  4202. if (result && PyBytes_Check(path->object)) {
  4203. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  4204. }
  4205. cleanup:
  4206. if (target_path != buf) {
  4207. PyMem_Free(target_path);
  4208. }
  4209. CloseHandle(hFile);
  4210. return result;
  4211. }
  4212. /*[clinic input]
  4213. os._getvolumepathname
  4214. path: path_t
  4215. A helper function for ismount on Win32.
  4216. [clinic start generated code]*/
  4217. static PyObject *
  4218. os__getvolumepathname_impl(PyObject *module, path_t *path)
  4219. /*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
  4220. {
  4221. PyObject *result;
  4222. wchar_t *mountpath=NULL;
  4223. size_t buflen;
  4224. BOOL ret;
  4225. /* Volume path should be shorter than entire path */
  4226. buflen = Py_MAX(path->length, MAX_PATH);
  4227. if (buflen > PY_DWORD_MAX) {
  4228. PyErr_SetString(PyExc_OverflowError, "path too long");
  4229. return NULL;
  4230. }
  4231. mountpath = PyMem_New(wchar_t, buflen);
  4232. if (mountpath == NULL)
  4233. return PyErr_NoMemory();
  4234. Py_BEGIN_ALLOW_THREADS
  4235. ret = GetVolumePathNameW(path->wide, mountpath,
  4236. Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
  4237. Py_END_ALLOW_THREADS
  4238. if (!ret) {
  4239. result = win32_error_object("_getvolumepathname", path->object);
  4240. goto exit;
  4241. }
  4242. result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
  4243. if (PyBytes_Check(path->object))
  4244. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  4245. exit:
  4246. PyMem_Free(mountpath);
  4247. return result;
  4248. }
  4249. /*[clinic input]
  4250. os._path_splitroot
  4251. path: path_t
  4252. Removes everything after the root on Win32.
  4253. [clinic start generated code]*/
  4254. static PyObject *
  4255. os__path_splitroot_impl(PyObject *module, path_t *path)
  4256. /*[clinic end generated code: output=ab7f1a88b654581c input=dc93b1d3984cffb6]*/
  4257. {
  4258. wchar_t *buffer;
  4259. wchar_t *end;
  4260. PyObject *result = NULL;
  4261. HRESULT ret;
  4262. buffer = (wchar_t*)PyMem_Malloc(sizeof(wchar_t) * (wcslen(path->wide) + 1));
  4263. if (!buffer) {
  4264. return NULL;
  4265. }
  4266. wcscpy(buffer, path->wide);
  4267. for (wchar_t *p = wcschr(buffer, L'/'); p; p = wcschr(p, L'/')) {
  4268. *p = L'\\';
  4269. }
  4270. Py_BEGIN_ALLOW_THREADS
  4271. ret = PathCchSkipRoot(buffer, &end);
  4272. Py_END_ALLOW_THREADS
  4273. if (FAILED(ret)) {
  4274. result = Py_BuildValue("sO", "", path->object);
  4275. } else if (end != buffer) {
  4276. size_t rootLen = (size_t)(end - buffer);
  4277. result = Py_BuildValue("NN",
  4278. PyUnicode_FromWideChar(path->wide, rootLen),
  4279. PyUnicode_FromWideChar(path->wide + rootLen, -1)
  4280. );
  4281. } else {
  4282. result = Py_BuildValue("Os", path->object, "");
  4283. }
  4284. PyMem_Free(buffer);
  4285. return result;
  4286. }
  4287. #define PY_IFREG 1 // Regular file
  4288. #define PY_IFDIR 2 // Directory
  4289. #define PY_IFLNK 4 // Symlink
  4290. #define PY_IFMNT 8 // Mount Point (junction)
  4291. #define PY_IFLRP 16 // Link Reparse Point (name-surrogate, symlink, junction)
  4292. #define PY_IFRRP 32 // Regular Reparse Point
  4293. static inline BOOL
  4294. _testInfo(DWORD attributes, DWORD reparseTag, BOOL diskDevice, int testedType)
  4295. {
  4296. switch (testedType) {
  4297. case PY_IFREG:
  4298. return diskDevice && attributes &&
  4299. !(attributes & FILE_ATTRIBUTE_DIRECTORY);
  4300. case PY_IFDIR:
  4301. return attributes & FILE_ATTRIBUTE_DIRECTORY;
  4302. case PY_IFLNK:
  4303. return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
  4304. reparseTag == IO_REPARSE_TAG_SYMLINK;
  4305. case PY_IFMNT:
  4306. return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
  4307. reparseTag == IO_REPARSE_TAG_MOUNT_POINT;
  4308. case PY_IFLRP:
  4309. return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
  4310. IsReparseTagNameSurrogate(reparseTag);
  4311. case PY_IFRRP:
  4312. return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
  4313. reparseTag && !IsReparseTagNameSurrogate(reparseTag);
  4314. }
  4315. return FALSE;
  4316. }
  4317. static BOOL
  4318. _testFileTypeByHandle(HANDLE hfile, int testedType, BOOL diskOnly)
  4319. {
  4320. assert(testedType == PY_IFREG || testedType == PY_IFDIR ||
  4321. testedType == PY_IFLNK || testedType == PY_IFMNT ||
  4322. testedType == PY_IFLRP || testedType == PY_IFRRP);
  4323. BOOL diskDevice = GetFileType(hfile) == FILE_TYPE_DISK;
  4324. if (diskOnly && !diskDevice) {
  4325. return FALSE;
  4326. }
  4327. if (testedType != PY_IFREG && testedType != PY_IFDIR) {
  4328. FILE_ATTRIBUTE_TAG_INFO info;
  4329. return GetFileInformationByHandleEx(hfile, FileAttributeTagInfo, &info,
  4330. sizeof(info)) &&
  4331. _testInfo(info.FileAttributes, info.ReparseTag, diskDevice,
  4332. testedType);
  4333. }
  4334. FILE_BASIC_INFO info;
  4335. return GetFileInformationByHandleEx(hfile, FileBasicInfo, &info,
  4336. sizeof(info)) &&
  4337. _testInfo(info.FileAttributes, 0, diskDevice, testedType);
  4338. }
  4339. static BOOL
  4340. _testFileTypeByName(LPCWSTR path, int testedType)
  4341. {
  4342. assert(testedType == PY_IFREG || testedType == PY_IFDIR ||
  4343. testedType == PY_IFLNK || testedType == PY_IFMNT ||
  4344. testedType == PY_IFLRP || testedType == PY_IFRRP);
  4345. FILE_STAT_BASIC_INFORMATION info;
  4346. if (_Py_GetFileInformationByName(path, FileStatBasicByNameInfo, &info,
  4347. sizeof(info)))
  4348. {
  4349. BOOL diskDevice = info.DeviceType == FILE_DEVICE_DISK ||
  4350. info.DeviceType == FILE_DEVICE_VIRTUAL_DISK ||
  4351. info.DeviceType == FILE_DEVICE_CD_ROM;
  4352. BOOL result = _testInfo(info.FileAttributes, info.ReparseTag,
  4353. diskDevice, testedType);
  4354. if (!result || (testedType != PY_IFREG && testedType != PY_IFDIR) ||
  4355. !(info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
  4356. {
  4357. return result;
  4358. }
  4359. }
  4360. else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(
  4361. GetLastError()))
  4362. {
  4363. return FALSE;
  4364. }
  4365. DWORD flags = FILE_FLAG_BACKUP_SEMANTICS;
  4366. if (testedType != PY_IFREG && testedType != PY_IFDIR) {
  4367. flags |= FILE_FLAG_OPEN_REPARSE_POINT;
  4368. }
  4369. HANDLE hfile = CreateFileW(path, FILE_READ_ATTRIBUTES, 0, NULL,
  4370. OPEN_EXISTING, flags, NULL);
  4371. if (hfile != INVALID_HANDLE_VALUE) {
  4372. BOOL result = _testFileTypeByHandle(hfile, testedType, FALSE);
  4373. CloseHandle(hfile);
  4374. return result;
  4375. }
  4376. switch (GetLastError()) {
  4377. case ERROR_ACCESS_DENIED:
  4378. case ERROR_SHARING_VIOLATION:
  4379. case ERROR_CANT_ACCESS_FILE:
  4380. case ERROR_INVALID_PARAMETER:
  4381. int rc;
  4382. STRUCT_STAT st;
  4383. if (testedType == PY_IFREG || testedType == PY_IFDIR) {
  4384. rc = STAT(path, &st);
  4385. }
  4386. else {
  4387. // PY_IFRRP is not generally supported in this case, except for
  4388. // unhandled reparse points such as IO_REPARSE_TAG_APPEXECLINK.
  4389. rc = LSTAT(path, &st);
  4390. }
  4391. if (!rc) {
  4392. return _testInfo(st.st_file_attributes, st.st_reparse_tag,
  4393. st.st_mode & S_IFREG, testedType);
  4394. }
  4395. }
  4396. return FALSE;
  4397. }
  4398. static BOOL
  4399. _testFileExistsByName(LPCWSTR path, BOOL followLinks)
  4400. {
  4401. FILE_STAT_BASIC_INFORMATION info;
  4402. if (_Py_GetFileInformationByName(path, FileStatBasicByNameInfo, &info,
  4403. sizeof(info)))
  4404. {
  4405. if (!(info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ||
  4406. !followLinks && IsReparseTagNameSurrogate(info.ReparseTag))
  4407. {
  4408. return TRUE;
  4409. }
  4410. }
  4411. else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(
  4412. GetLastError()))
  4413. {
  4414. return FALSE;
  4415. }
  4416. DWORD flags = FILE_FLAG_BACKUP_SEMANTICS;
  4417. if (!followLinks) {
  4418. flags |= FILE_FLAG_OPEN_REPARSE_POINT;
  4419. }
  4420. HANDLE hfile = CreateFileW(path, FILE_READ_ATTRIBUTES, 0, NULL,
  4421. OPEN_EXISTING, flags, NULL);
  4422. if (hfile != INVALID_HANDLE_VALUE) {
  4423. if (followLinks) {
  4424. CloseHandle(hfile);
  4425. return TRUE;
  4426. }
  4427. // Regular Reparse Points (PY_IFRRP) have to be traversed.
  4428. BOOL result = _testFileTypeByHandle(hfile, PY_IFRRP, FALSE);
  4429. CloseHandle(hfile);
  4430. if (!result) {
  4431. return TRUE;
  4432. }
  4433. hfile = CreateFileW(path, FILE_READ_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
  4434. FILE_FLAG_BACKUP_SEMANTICS, NULL);
  4435. if (hfile != INVALID_HANDLE_VALUE) {
  4436. CloseHandle(hfile);
  4437. return TRUE;
  4438. }
  4439. }
  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. STRUCT_STAT _st;
  4446. return followLinks ? !STAT(path, &_st): !LSTAT(path, &_st);
  4447. }
  4448. return FALSE;
  4449. }
  4450. static BOOL
  4451. _testFileExists(path_t *path, BOOL followLinks)
  4452. {
  4453. BOOL result = FALSE;
  4454. if (path->value_error) {
  4455. return FALSE;
  4456. }
  4457. Py_BEGIN_ALLOW_THREADS
  4458. if (path->fd != -1) {
  4459. HANDLE hfile = _Py_get_osfhandle_noraise(path->fd);
  4460. if (hfile != INVALID_HANDLE_VALUE) {
  4461. if (GetFileType(hfile) != FILE_TYPE_UNKNOWN || !GetLastError()) {
  4462. result = TRUE;
  4463. }
  4464. }
  4465. }
  4466. else if (path->wide) {
  4467. result = _testFileExistsByName(path->wide, followLinks);
  4468. }
  4469. Py_END_ALLOW_THREADS
  4470. return result;
  4471. }
  4472. static BOOL
  4473. _testFileType(path_t *path, int testedType)
  4474. {
  4475. BOOL result = FALSE;
  4476. if (path->value_error) {
  4477. return FALSE;
  4478. }
  4479. Py_BEGIN_ALLOW_THREADS
  4480. if (path->fd != -1) {
  4481. HANDLE hfile = _Py_get_osfhandle_noraise(path->fd);
  4482. if (hfile != INVALID_HANDLE_VALUE) {
  4483. result = _testFileTypeByHandle(hfile, testedType, TRUE);
  4484. }
  4485. }
  4486. else if (path->wide) {
  4487. result = _testFileTypeByName(path->wide, testedType);
  4488. }
  4489. Py_END_ALLOW_THREADS
  4490. return result;
  4491. }
  4492. /*[clinic input]
  4493. os._path_exists -> bool
  4494. path: path_t(allow_fd=True, suppress_value_error=True)
  4495. Test whether a path exists. Returns False for broken symbolic links.
  4496. [clinic start generated code]*/
  4497. static int
  4498. os__path_exists_impl(PyObject *module, path_t *path)
  4499. /*[clinic end generated code: output=8da13acf666e16ba input=142beabfc66783eb]*/
  4500. {
  4501. return _testFileExists(path, TRUE);
  4502. }
  4503. /*[clinic input]
  4504. os._path_isdir -> bool
  4505. s as path: path_t(allow_fd=True, suppress_value_error=True)
  4506. Return true if the pathname refers to an existing directory.
  4507. [clinic start generated code]*/
  4508. static int
  4509. os__path_isdir_impl(PyObject *module, path_t *path)
  4510. /*[clinic end generated code: output=d5786196f9e2fa7a input=132a3b5301aecf79]*/
  4511. {
  4512. return _testFileType(path, PY_IFDIR);
  4513. }
  4514. /*[clinic input]
  4515. os._path_isfile -> bool
  4516. path: path_t(allow_fd=True, suppress_value_error=True)
  4517. Test whether a path is a regular file
  4518. [clinic start generated code]*/
  4519. static int
  4520. os__path_isfile_impl(PyObject *module, path_t *path)
  4521. /*[clinic end generated code: output=5c3073bc212b9863 input=4ac1fd350b30a39e]*/
  4522. {
  4523. return _testFileType(path, PY_IFREG);
  4524. }
  4525. /*[clinic input]
  4526. os._path_islink -> bool
  4527. path: path_t(allow_fd=True, suppress_value_error=True)
  4528. Test whether a path is a symbolic link
  4529. [clinic start generated code]*/
  4530. static int
  4531. os__path_islink_impl(PyObject *module, path_t *path)
  4532. /*[clinic end generated code: output=30da7bda8296adcc input=7510ce05b547debb]*/
  4533. {
  4534. return _testFileType(path, PY_IFLNK);
  4535. }
  4536. #undef PY_IFREG
  4537. #undef PY_IFDIR
  4538. #undef PY_IFLNK
  4539. #undef PY_IFMNT
  4540. #undef PY_IFLRP
  4541. #undef PY_IFRRP
  4542. #endif /* MS_WINDOWS */
  4543. /*[clinic input]
  4544. os._path_normpath
  4545. path: path_t(make_wide=True, nonstrict=True)
  4546. Normalize path, eliminating double slashes, etc.
  4547. [clinic start generated code]*/
  4548. static PyObject *
  4549. os__path_normpath_impl(PyObject *module, path_t *path)
  4550. /*[clinic end generated code: output=d353e7ed9410c044 input=3d4ac23b06332dcb]*/
  4551. {
  4552. PyObject *result;
  4553. Py_ssize_t norm_len;
  4554. wchar_t *norm_path = _Py_normpath_and_size((wchar_t *)path->wide,
  4555. path->length, &norm_len);
  4556. if (!norm_len) {
  4557. result = PyUnicode_FromOrdinal('.');
  4558. }
  4559. else {
  4560. result = PyUnicode_FromWideChar(norm_path, norm_len);
  4561. }
  4562. if (PyBytes_Check(path->object)) {
  4563. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  4564. }
  4565. return result;
  4566. }
  4567. /*[clinic input]
  4568. os.mkdir
  4569. path : path_t
  4570. mode: int = 0o777
  4571. *
  4572. dir_fd : dir_fd(requires='mkdirat') = None
  4573. # "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
  4574. Create a directory.
  4575. If dir_fd is not None, it should be a file descriptor open to a directory,
  4576. and path should be relative; path will then be relative to that directory.
  4577. dir_fd may not be implemented on your platform.
  4578. If it is unavailable, using it will raise a NotImplementedError.
  4579. The mode argument is ignored on Windows. Where it is used, the current umask
  4580. value is first masked out.
  4581. [clinic start generated code]*/
  4582. static PyObject *
  4583. os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
  4584. /*[clinic end generated code: output=a70446903abe821f input=a61722e1576fab03]*/
  4585. {
  4586. int result;
  4587. #ifdef MS_WINDOWS
  4588. int error = 0;
  4589. int pathError = 0;
  4590. SECURITY_ATTRIBUTES secAttr = { sizeof(secAttr) };
  4591. SECURITY_ATTRIBUTES *pSecAttr = NULL;
  4592. #endif
  4593. #ifdef HAVE_MKDIRAT
  4594. int mkdirat_unavailable = 0;
  4595. #endif
  4596. if (PySys_Audit("os.mkdir", "Oii", path->object, mode,
  4597. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4598. return NULL;
  4599. }
  4600. #ifdef MS_WINDOWS
  4601. Py_BEGIN_ALLOW_THREADS
  4602. if (mode == 0700 /* 0o700 */) {
  4603. ULONG sdSize;
  4604. pSecAttr = &secAttr;
  4605. // Set a discretionary ACL (D) that is protected (P) and includes
  4606. // inheritable (OICI) entries that allow (A) full control (FA) to
  4607. // SYSTEM (SY), Administrators (BA), and the owner (OW).
  4608. if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
  4609. L"D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;OW)",
  4610. SDDL_REVISION_1,
  4611. &secAttr.lpSecurityDescriptor,
  4612. &sdSize
  4613. )) {
  4614. error = GetLastError();
  4615. }
  4616. }
  4617. if (!error) {
  4618. result = CreateDirectoryW(path->wide, pSecAttr);
  4619. if (secAttr.lpSecurityDescriptor &&
  4620. // uncommonly, LocalFree returns non-zero on error, but still uses
  4621. // GetLastError() to see what the error code is
  4622. LocalFree(secAttr.lpSecurityDescriptor)) {
  4623. error = GetLastError();
  4624. }
  4625. }
  4626. Py_END_ALLOW_THREADS
  4627. if (error) {
  4628. return PyErr_SetFromWindowsErr(error);
  4629. }
  4630. if (!result) {
  4631. return path_error(path);
  4632. }
  4633. #else
  4634. Py_BEGIN_ALLOW_THREADS
  4635. #if HAVE_MKDIRAT
  4636. if (dir_fd != DEFAULT_DIR_FD) {
  4637. if (HAVE_MKDIRAT_RUNTIME) {
  4638. result = mkdirat(dir_fd, path->narrow, mode);
  4639. } else {
  4640. mkdirat_unavailable = 1;
  4641. }
  4642. } else
  4643. #endif
  4644. #if defined(__WATCOMC__) && !defined(__QNX__)
  4645. result = mkdir(path->narrow);
  4646. #else
  4647. result = mkdir(path->narrow, mode);
  4648. #endif
  4649. Py_END_ALLOW_THREADS
  4650. #if HAVE_MKDIRAT
  4651. if (mkdirat_unavailable) {
  4652. argument_unavailable_error(NULL, "dir_fd");
  4653. return NULL;
  4654. }
  4655. #endif
  4656. if (result < 0)
  4657. return path_error(path);
  4658. #endif /* MS_WINDOWS */
  4659. Py_RETURN_NONE;
  4660. }
  4661. /* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
  4662. #if defined(HAVE_SYS_RESOURCE_H)
  4663. #include <sys/resource.h>
  4664. #endif
  4665. #ifdef HAVE_NICE
  4666. /*[clinic input]
  4667. os.nice
  4668. increment: int
  4669. /
  4670. Add increment to the priority of process and return the new priority.
  4671. [clinic start generated code]*/
  4672. static PyObject *
  4673. os_nice_impl(PyObject *module, int increment)
  4674. /*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
  4675. {
  4676. int value;
  4677. /* There are two flavours of 'nice': one that returns the new
  4678. priority (as required by almost all standards out there) and the
  4679. Linux/FreeBSD one, which returns '0' on success and advices
  4680. the use of getpriority() to get the new priority.
  4681. If we are of the nice family that returns the new priority, we
  4682. need to clear errno before the call, and check if errno is filled
  4683. before calling posix_error() on a returnvalue of -1, because the
  4684. -1 may be the actual new priority! */
  4685. errno = 0;
  4686. value = nice(increment);
  4687. #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
  4688. if (value == 0)
  4689. value = getpriority(PRIO_PROCESS, 0);
  4690. #endif
  4691. if (value == -1 && errno != 0)
  4692. /* either nice() or getpriority() returned an error */
  4693. return posix_error();
  4694. return PyLong_FromLong((long) value);
  4695. }
  4696. #endif /* HAVE_NICE */
  4697. #ifdef HAVE_GETPRIORITY
  4698. /*[clinic input]
  4699. os.getpriority
  4700. which: int
  4701. who: int
  4702. Return program scheduling priority.
  4703. [clinic start generated code]*/
  4704. static PyObject *
  4705. os_getpriority_impl(PyObject *module, int which, int who)
  4706. /*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
  4707. {
  4708. int retval;
  4709. errno = 0;
  4710. retval = getpriority(which, who);
  4711. if (errno != 0)
  4712. return posix_error();
  4713. return PyLong_FromLong((long)retval);
  4714. }
  4715. #endif /* HAVE_GETPRIORITY */
  4716. #ifdef HAVE_SETPRIORITY
  4717. /*[clinic input]
  4718. os.setpriority
  4719. which: int
  4720. who: int
  4721. priority: int
  4722. Set program scheduling priority.
  4723. [clinic start generated code]*/
  4724. static PyObject *
  4725. os_setpriority_impl(PyObject *module, int which, int who, int priority)
  4726. /*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
  4727. {
  4728. int retval;
  4729. retval = setpriority(which, who, priority);
  4730. if (retval == -1)
  4731. return posix_error();
  4732. Py_RETURN_NONE;
  4733. }
  4734. #endif /* HAVE_SETPRIORITY */
  4735. static PyObject *
  4736. internal_rename(path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int is_replace)
  4737. {
  4738. const char *function_name = is_replace ? "replace" : "rename";
  4739. int dir_fd_specified;
  4740. #ifdef HAVE_RENAMEAT
  4741. int renameat_unavailable = 0;
  4742. #endif
  4743. #ifdef MS_WINDOWS
  4744. BOOL result;
  4745. int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
  4746. #else
  4747. int result;
  4748. #endif
  4749. dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
  4750. (dst_dir_fd != DEFAULT_DIR_FD);
  4751. #ifndef HAVE_RENAMEAT
  4752. if (dir_fd_specified) {
  4753. argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
  4754. return NULL;
  4755. }
  4756. #endif
  4757. if (PySys_Audit("os.rename", "OOii", src->object, dst->object,
  4758. src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
  4759. dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
  4760. return NULL;
  4761. }
  4762. #ifdef MS_WINDOWS
  4763. Py_BEGIN_ALLOW_THREADS
  4764. result = MoveFileExW(src->wide, dst->wide, flags);
  4765. Py_END_ALLOW_THREADS
  4766. if (!result)
  4767. return path_error2(src, dst);
  4768. #else
  4769. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  4770. PyErr_Format(PyExc_ValueError,
  4771. "%s: src and dst must be the same type", function_name);
  4772. return NULL;
  4773. }
  4774. Py_BEGIN_ALLOW_THREADS
  4775. #ifdef HAVE_RENAMEAT
  4776. if (dir_fd_specified) {
  4777. if (HAVE_RENAMEAT_RUNTIME) {
  4778. result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
  4779. } else {
  4780. renameat_unavailable = 1;
  4781. }
  4782. } else
  4783. #endif
  4784. result = rename(src->narrow, dst->narrow);
  4785. Py_END_ALLOW_THREADS
  4786. #ifdef HAVE_RENAMEAT
  4787. if (renameat_unavailable) {
  4788. argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
  4789. return NULL;
  4790. }
  4791. #endif
  4792. if (result)
  4793. return path_error2(src, dst);
  4794. #endif
  4795. Py_RETURN_NONE;
  4796. }
  4797. /*[clinic input]
  4798. os.rename
  4799. src : path_t
  4800. dst : path_t
  4801. *
  4802. src_dir_fd : dir_fd = None
  4803. dst_dir_fd : dir_fd = None
  4804. Rename a file or directory.
  4805. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  4806. descriptor open to a directory, and the respective path string (src or dst)
  4807. should be relative; the path will then be relative to that directory.
  4808. src_dir_fd and dst_dir_fd, may not be implemented on your platform.
  4809. If they are unavailable, using them will raise a NotImplementedError.
  4810. [clinic start generated code]*/
  4811. static PyObject *
  4812. os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  4813. int dst_dir_fd)
  4814. /*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
  4815. {
  4816. return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
  4817. }
  4818. /*[clinic input]
  4819. os.replace = os.rename
  4820. Rename a file or directory, overwriting the destination.
  4821. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  4822. descriptor open to a directory, and the respective path string (src or dst)
  4823. should be relative; the path will then be relative to that directory.
  4824. src_dir_fd and dst_dir_fd, may not be implemented on your platform.
  4825. If they are unavailable, using them will raise a NotImplementedError.
  4826. [clinic start generated code]*/
  4827. static PyObject *
  4828. os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  4829. int dst_dir_fd)
  4830. /*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
  4831. {
  4832. return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
  4833. }
  4834. /*[clinic input]
  4835. os.rmdir
  4836. path: path_t
  4837. *
  4838. dir_fd: dir_fd(requires='unlinkat') = None
  4839. Remove a directory.
  4840. If dir_fd is not None, it should be a file descriptor open to a directory,
  4841. and path should be relative; path will then be relative to that directory.
  4842. dir_fd may not be implemented on your platform.
  4843. If it is unavailable, using it will raise a NotImplementedError.
  4844. [clinic start generated code]*/
  4845. static PyObject *
  4846. os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
  4847. /*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
  4848. {
  4849. int result;
  4850. #ifdef HAVE_UNLINKAT
  4851. int unlinkat_unavailable = 0;
  4852. #endif
  4853. if (PySys_Audit("os.rmdir", "Oi", path->object,
  4854. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4855. return NULL;
  4856. }
  4857. Py_BEGIN_ALLOW_THREADS
  4858. #ifdef MS_WINDOWS
  4859. /* Windows, success=1, UNIX, success=0 */
  4860. result = !RemoveDirectoryW(path->wide);
  4861. #else
  4862. #ifdef HAVE_UNLINKAT
  4863. if (dir_fd != DEFAULT_DIR_FD) {
  4864. if (HAVE_UNLINKAT_RUNTIME) {
  4865. result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
  4866. } else {
  4867. unlinkat_unavailable = 1;
  4868. result = -1;
  4869. }
  4870. } else
  4871. #endif
  4872. result = rmdir(path->narrow);
  4873. #endif
  4874. Py_END_ALLOW_THREADS
  4875. #ifdef HAVE_UNLINKAT
  4876. if (unlinkat_unavailable) {
  4877. argument_unavailable_error("rmdir", "dir_fd");
  4878. return NULL;
  4879. }
  4880. #endif
  4881. if (result)
  4882. return path_error(path);
  4883. Py_RETURN_NONE;
  4884. }
  4885. #ifdef HAVE_SYSTEM
  4886. #ifdef MS_WINDOWS
  4887. /*[clinic input]
  4888. os.system -> long
  4889. command: Py_UNICODE
  4890. Execute the command in a subshell.
  4891. [clinic start generated code]*/
  4892. static long
  4893. os_system_impl(PyObject *module, const Py_UNICODE *command)
  4894. /*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
  4895. {
  4896. long result;
  4897. if (PySys_Audit("os.system", "(u)", command) < 0) {
  4898. return -1;
  4899. }
  4900. Py_BEGIN_ALLOW_THREADS
  4901. _Py_BEGIN_SUPPRESS_IPH
  4902. result = _wsystem(command);
  4903. _Py_END_SUPPRESS_IPH
  4904. Py_END_ALLOW_THREADS
  4905. return result;
  4906. }
  4907. #else /* MS_WINDOWS */
  4908. /*[clinic input]
  4909. os.system -> long
  4910. command: FSConverter
  4911. Execute the command in a subshell.
  4912. [clinic start generated code]*/
  4913. static long
  4914. os_system_impl(PyObject *module, PyObject *command)
  4915. /*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
  4916. {
  4917. long result;
  4918. const char *bytes = PyBytes_AsString(command);
  4919. if (PySys_Audit("os.system", "(O)", command) < 0) {
  4920. return -1;
  4921. }
  4922. Py_BEGIN_ALLOW_THREADS
  4923. result = system(bytes);
  4924. Py_END_ALLOW_THREADS
  4925. return result;
  4926. }
  4927. #endif
  4928. #endif /* HAVE_SYSTEM */
  4929. #ifdef HAVE_UMASK
  4930. /*[clinic input]
  4931. os.umask
  4932. mask: int
  4933. /
  4934. Set the current numeric umask and return the previous umask.
  4935. [clinic start generated code]*/
  4936. static PyObject *
  4937. os_umask_impl(PyObject *module, int mask)
  4938. /*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
  4939. {
  4940. int i = (int)umask(mask);
  4941. if (i < 0)
  4942. return posix_error();
  4943. return PyLong_FromLong((long)i);
  4944. }
  4945. #endif
  4946. #ifdef MS_WINDOWS
  4947. /* override the default DeleteFileW behavior so that directory
  4948. symlinks can be removed with this function, the same as with
  4949. Unix symlinks */
  4950. BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
  4951. {
  4952. WIN32_FILE_ATTRIBUTE_DATA info;
  4953. WIN32_FIND_DATAW find_data;
  4954. HANDLE find_data_handle;
  4955. int is_directory = 0;
  4956. int is_link = 0;
  4957. if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
  4958. is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4959. /* Get WIN32_FIND_DATA structure for the path to determine if
  4960. it is a symlink */
  4961. if(is_directory &&
  4962. info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
  4963. find_data_handle = FindFirstFileW(lpFileName, &find_data);
  4964. if(find_data_handle != INVALID_HANDLE_VALUE) {
  4965. /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
  4966. IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
  4967. is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
  4968. find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
  4969. FindClose(find_data_handle);
  4970. }
  4971. }
  4972. }
  4973. if (is_directory && is_link)
  4974. return RemoveDirectoryW(lpFileName);
  4975. return DeleteFileW(lpFileName);
  4976. }
  4977. #endif /* MS_WINDOWS */
  4978. /*[clinic input]
  4979. os.unlink
  4980. path: path_t
  4981. *
  4982. dir_fd: dir_fd(requires='unlinkat')=None
  4983. Remove a file (same as remove()).
  4984. If dir_fd is not None, it should be a file descriptor open to a directory,
  4985. and path should be relative; path will then be relative to that directory.
  4986. dir_fd may not be implemented on your platform.
  4987. If it is unavailable, using it will raise a NotImplementedError.
  4988. [clinic start generated code]*/
  4989. static PyObject *
  4990. os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
  4991. /*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
  4992. {
  4993. int result;
  4994. #ifdef HAVE_UNLINKAT
  4995. int unlinkat_unavailable = 0;
  4996. #endif
  4997. if (PySys_Audit("os.remove", "Oi", path->object,
  4998. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4999. return NULL;
  5000. }
  5001. Py_BEGIN_ALLOW_THREADS
  5002. _Py_BEGIN_SUPPRESS_IPH
  5003. #ifdef MS_WINDOWS
  5004. /* Windows, success=1, UNIX, success=0 */
  5005. result = !Py_DeleteFileW(path->wide);
  5006. #else
  5007. #ifdef HAVE_UNLINKAT
  5008. if (dir_fd != DEFAULT_DIR_FD) {
  5009. if (HAVE_UNLINKAT_RUNTIME) {
  5010. result = unlinkat(dir_fd, path->narrow, 0);
  5011. } else {
  5012. unlinkat_unavailable = 1;
  5013. }
  5014. } else
  5015. #endif /* HAVE_UNLINKAT */
  5016. result = unlink(path->narrow);
  5017. #endif
  5018. _Py_END_SUPPRESS_IPH
  5019. Py_END_ALLOW_THREADS
  5020. #ifdef HAVE_UNLINKAT
  5021. if (unlinkat_unavailable) {
  5022. argument_unavailable_error(NULL, "dir_fd");
  5023. return NULL;
  5024. }
  5025. #endif
  5026. if (result)
  5027. return path_error(path);
  5028. Py_RETURN_NONE;
  5029. }
  5030. /*[clinic input]
  5031. os.remove = os.unlink
  5032. Remove a file (same as unlink()).
  5033. If dir_fd is not None, it should be a file descriptor open to a directory,
  5034. and path should be relative; path will then be relative to that directory.
  5035. dir_fd may not be implemented on your platform.
  5036. If it is unavailable, using it will raise a NotImplementedError.
  5037. [clinic start generated code]*/
  5038. static PyObject *
  5039. os_remove_impl(PyObject *module, path_t *path, int dir_fd)
  5040. /*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
  5041. {
  5042. return os_unlink_impl(module, path, dir_fd);
  5043. }
  5044. static PyStructSequence_Field uname_result_fields[] = {
  5045. {"sysname", "operating system name"},
  5046. {"nodename", "name of machine on network (implementation-defined)"},
  5047. {"release", "operating system release"},
  5048. {"version", "operating system version"},
  5049. {"machine", "hardware identifier"},
  5050. {NULL}
  5051. };
  5052. PyDoc_STRVAR(uname_result__doc__,
  5053. "uname_result: Result from os.uname().\n\n\
  5054. This object may be accessed either as a tuple of\n\
  5055. (sysname, nodename, release, version, machine),\n\
  5056. or via the attributes sysname, nodename, release, version, and machine.\n\
  5057. \n\
  5058. See os.uname for more information.");
  5059. static PyStructSequence_Desc uname_result_desc = {
  5060. MODNAME ".uname_result", /* name */
  5061. uname_result__doc__, /* doc */
  5062. uname_result_fields,
  5063. 5
  5064. };
  5065. #ifdef HAVE_UNAME
  5066. /*[clinic input]
  5067. os.uname
  5068. Return an object identifying the current operating system.
  5069. The object behaves like a named tuple with the following fields:
  5070. (sysname, nodename, release, version, machine)
  5071. [clinic start generated code]*/
  5072. static PyObject *
  5073. os_uname_impl(PyObject *module)
  5074. /*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
  5075. {
  5076. struct utsname u;
  5077. int res;
  5078. PyObject *value;
  5079. Py_BEGIN_ALLOW_THREADS
  5080. res = uname(&u);
  5081. Py_END_ALLOW_THREADS
  5082. if (res < 0)
  5083. return posix_error();
  5084. PyObject *UnameResultType = get_posix_state(module)->UnameResultType;
  5085. value = PyStructSequence_New((PyTypeObject *)UnameResultType);
  5086. if (value == NULL)
  5087. return NULL;
  5088. #define SET(i, field) \
  5089. { \
  5090. PyObject *o = PyUnicode_DecodeFSDefault(field); \
  5091. if (!o) { \
  5092. Py_DECREF(value); \
  5093. return NULL; \
  5094. } \
  5095. PyStructSequence_SET_ITEM(value, i, o); \
  5096. } \
  5097. SET(0, u.sysname);
  5098. SET(1, u.nodename);
  5099. SET(2, u.release);
  5100. SET(3, u.version);
  5101. SET(4, u.machine);
  5102. #undef SET
  5103. return value;
  5104. }
  5105. #endif /* HAVE_UNAME */
  5106. typedef struct {
  5107. int now;
  5108. time_t atime_s;
  5109. long atime_ns;
  5110. time_t mtime_s;
  5111. long mtime_ns;
  5112. } utime_t;
  5113. /*
  5114. * these macros assume that "ut" is a pointer to a utime_t
  5115. * they also intentionally leak the declaration of a pointer named "time"
  5116. */
  5117. #define UTIME_TO_TIMESPEC \
  5118. struct timespec ts[2]; \
  5119. struct timespec *time; \
  5120. if (ut->now) \
  5121. time = NULL; \
  5122. else { \
  5123. ts[0].tv_sec = ut->atime_s; \
  5124. ts[0].tv_nsec = ut->atime_ns; \
  5125. ts[1].tv_sec = ut->mtime_s; \
  5126. ts[1].tv_nsec = ut->mtime_ns; \
  5127. time = ts; \
  5128. } \
  5129. #define UTIME_TO_TIMEVAL \
  5130. struct timeval tv[2]; \
  5131. struct timeval *time; \
  5132. if (ut->now) \
  5133. time = NULL; \
  5134. else { \
  5135. tv[0].tv_sec = ut->atime_s; \
  5136. tv[0].tv_usec = ut->atime_ns / 1000; \
  5137. tv[1].tv_sec = ut->mtime_s; \
  5138. tv[1].tv_usec = ut->mtime_ns / 1000; \
  5139. time = tv; \
  5140. } \
  5141. #define UTIME_TO_UTIMBUF \
  5142. struct utimbuf u; \
  5143. struct utimbuf *time; \
  5144. if (ut->now) \
  5145. time = NULL; \
  5146. else { \
  5147. u.actime = ut->atime_s; \
  5148. u.modtime = ut->mtime_s; \
  5149. time = &u; \
  5150. }
  5151. #define UTIME_TO_TIME_T \
  5152. time_t timet[2]; \
  5153. time_t *time; \
  5154. if (ut->now) \
  5155. time = NULL; \
  5156. else { \
  5157. timet[0] = ut->atime_s; \
  5158. timet[1] = ut->mtime_s; \
  5159. time = timet; \
  5160. } \
  5161. #if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
  5162. static int
  5163. utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
  5164. {
  5165. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5166. if (HAVE_UTIMENSAT_RUNTIME) {
  5167. int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
  5168. UTIME_TO_TIMESPEC;
  5169. return utimensat(dir_fd, path, time, flags);
  5170. } else {
  5171. errno = ENOSYS;
  5172. return -1;
  5173. }
  5174. #elif defined(HAVE_UTIMENSAT)
  5175. int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
  5176. UTIME_TO_TIMESPEC;
  5177. return utimensat(dir_fd, path, time, flags);
  5178. #elif defined(HAVE_FUTIMESAT)
  5179. UTIME_TO_TIMEVAL;
  5180. /*
  5181. * follow_symlinks will never be false here;
  5182. * we only allow !follow_symlinks and dir_fd together
  5183. * if we have utimensat()
  5184. */
  5185. assert(follow_symlinks);
  5186. return futimesat(dir_fd, path, time);
  5187. #endif
  5188. }
  5189. #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
  5190. #else
  5191. #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
  5192. #endif
  5193. #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
  5194. static int
  5195. utime_fd(utime_t *ut, int fd)
  5196. {
  5197. #ifdef HAVE_FUTIMENS
  5198. if (HAVE_FUTIMENS_RUNTIME) {
  5199. UTIME_TO_TIMESPEC;
  5200. return futimens(fd, time);
  5201. } else
  5202. #ifndef HAVE_FUTIMES
  5203. {
  5204. /* Not sure if this can happen */
  5205. PyErr_SetString(
  5206. PyExc_RuntimeError,
  5207. "neither futimens nor futimes are supported"
  5208. " on this system");
  5209. return -1;
  5210. }
  5211. #endif
  5212. #endif
  5213. #ifdef HAVE_FUTIMES
  5214. {
  5215. UTIME_TO_TIMEVAL;
  5216. return futimes(fd, time);
  5217. }
  5218. #endif
  5219. }
  5220. #define PATH_UTIME_HAVE_FD 1
  5221. #else
  5222. #define PATH_UTIME_HAVE_FD 0
  5223. #endif
  5224. #if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
  5225. # define UTIME_HAVE_NOFOLLOW_SYMLINKS
  5226. #endif
  5227. #ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
  5228. static int
  5229. utime_nofollow_symlinks(utime_t *ut, const char *path)
  5230. {
  5231. #ifdef HAVE_UTIMENSAT
  5232. if (HAVE_UTIMENSAT_RUNTIME) {
  5233. UTIME_TO_TIMESPEC;
  5234. return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
  5235. } else
  5236. #ifndef HAVE_LUTIMES
  5237. {
  5238. /* Not sure if this can happen */
  5239. PyErr_SetString(
  5240. PyExc_RuntimeError,
  5241. "neither utimensat nor lutimes are supported"
  5242. " on this system");
  5243. return -1;
  5244. }
  5245. #endif
  5246. #endif
  5247. #ifdef HAVE_LUTIMES
  5248. {
  5249. UTIME_TO_TIMEVAL;
  5250. return lutimes(path, time);
  5251. }
  5252. #endif
  5253. }
  5254. #endif
  5255. #ifndef MS_WINDOWS
  5256. static int
  5257. utime_default(utime_t *ut, const char *path)
  5258. {
  5259. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5260. if (HAVE_UTIMENSAT_RUNTIME) {
  5261. UTIME_TO_TIMESPEC;
  5262. return utimensat(DEFAULT_DIR_FD, path, time, 0);
  5263. } else {
  5264. UTIME_TO_TIMEVAL;
  5265. return utimes(path, time);
  5266. }
  5267. #elif defined(HAVE_UTIMENSAT)
  5268. UTIME_TO_TIMESPEC;
  5269. return utimensat(DEFAULT_DIR_FD, path, time, 0);
  5270. #elif defined(HAVE_UTIMES)
  5271. UTIME_TO_TIMEVAL;
  5272. return utimes(path, time);
  5273. #elif defined(HAVE_UTIME_H)
  5274. UTIME_TO_UTIMBUF;
  5275. return utime(path, time);
  5276. #else
  5277. UTIME_TO_TIME_T;
  5278. return utime(path, time);
  5279. #endif
  5280. }
  5281. #endif
  5282. static int
  5283. split_py_long_to_s_and_ns(PyObject *module, PyObject *py_long, time_t *s, long *ns)
  5284. {
  5285. int result = 0;
  5286. PyObject *divmod;
  5287. divmod = PyNumber_Divmod(py_long, get_posix_state(module)->billion);
  5288. if (!divmod)
  5289. goto exit;
  5290. if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
  5291. PyErr_Format(PyExc_TypeError,
  5292. "%.200s.__divmod__() must return a 2-tuple, not %.200s",
  5293. _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
  5294. goto exit;
  5295. }
  5296. *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
  5297. if ((*s == -1) && PyErr_Occurred())
  5298. goto exit;
  5299. *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
  5300. if ((*ns == -1) && PyErr_Occurred())
  5301. goto exit;
  5302. result = 1;
  5303. exit:
  5304. Py_XDECREF(divmod);
  5305. return result;
  5306. }
  5307. /*[clinic input]
  5308. os.utime
  5309. path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
  5310. times: object = None
  5311. *
  5312. ns: object = NULL
  5313. dir_fd: dir_fd(requires='futimensat') = None
  5314. follow_symlinks: bool=True
  5315. # "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
  5316. Set the access and modified time of path.
  5317. path may always be specified as a string.
  5318. On some platforms, path may also be specified as an open file descriptor.
  5319. If this functionality is unavailable, using it raises an exception.
  5320. If times is not None, it must be a tuple (atime, mtime);
  5321. atime and mtime should be expressed as float seconds since the epoch.
  5322. If ns is specified, it must be a tuple (atime_ns, mtime_ns);
  5323. atime_ns and mtime_ns should be expressed as integer nanoseconds
  5324. since the epoch.
  5325. If times is None and ns is unspecified, utime uses the current time.
  5326. Specifying tuples for both times and ns is an error.
  5327. If dir_fd is not None, it should be a file descriptor open to a directory,
  5328. and path should be relative; path will then be relative to that directory.
  5329. If follow_symlinks is False, and the last element of the path is a symbolic
  5330. link, utime will modify the symbolic link itself instead of the file the
  5331. link points to.
  5332. It is an error to use dir_fd or follow_symlinks when specifying path
  5333. as an open file descriptor.
  5334. dir_fd and follow_symlinks may not be available on your platform.
  5335. If they are unavailable, using them will raise a NotImplementedError.
  5336. [clinic start generated code]*/
  5337. static PyObject *
  5338. os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
  5339. int dir_fd, int follow_symlinks)
  5340. /*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
  5341. {
  5342. #ifdef MS_WINDOWS
  5343. HANDLE hFile;
  5344. FILETIME atime, mtime;
  5345. #else
  5346. int result;
  5347. #endif
  5348. utime_t utime;
  5349. memset(&utime, 0, sizeof(utime_t));
  5350. if (times != Py_None && ns) {
  5351. PyErr_SetString(PyExc_ValueError,
  5352. "utime: you may specify either 'times'"
  5353. " or 'ns' but not both");
  5354. return NULL;
  5355. }
  5356. if (times != Py_None) {
  5357. time_t a_sec, m_sec;
  5358. long a_nsec, m_nsec;
  5359. if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
  5360. PyErr_SetString(PyExc_TypeError,
  5361. "utime: 'times' must be either"
  5362. " a tuple of two ints or None");
  5363. return NULL;
  5364. }
  5365. utime.now = 0;
  5366. if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
  5367. &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
  5368. _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
  5369. &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
  5370. return NULL;
  5371. }
  5372. utime.atime_s = a_sec;
  5373. utime.atime_ns = a_nsec;
  5374. utime.mtime_s = m_sec;
  5375. utime.mtime_ns = m_nsec;
  5376. }
  5377. else if (ns) {
  5378. if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
  5379. PyErr_SetString(PyExc_TypeError,
  5380. "utime: 'ns' must be a tuple of two ints");
  5381. return NULL;
  5382. }
  5383. utime.now = 0;
  5384. if (!split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 0),
  5385. &utime.atime_s, &utime.atime_ns) ||
  5386. !split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 1),
  5387. &utime.mtime_s, &utime.mtime_ns)) {
  5388. return NULL;
  5389. }
  5390. }
  5391. else {
  5392. /* times and ns are both None/unspecified. use "now". */
  5393. utime.now = 1;
  5394. }
  5395. #if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
  5396. if (follow_symlinks_specified("utime", follow_symlinks))
  5397. return NULL;
  5398. #endif
  5399. if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
  5400. dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
  5401. fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
  5402. return NULL;
  5403. #if !defined(HAVE_UTIMENSAT)
  5404. if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
  5405. PyErr_SetString(PyExc_ValueError,
  5406. "utime: cannot use dir_fd and follow_symlinks "
  5407. "together on this platform");
  5408. return NULL;
  5409. }
  5410. #endif
  5411. if (PySys_Audit("os.utime", "OOOi", path->object, times, ns ? ns : Py_None,
  5412. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  5413. return NULL;
  5414. }
  5415. #ifdef MS_WINDOWS
  5416. Py_BEGIN_ALLOW_THREADS
  5417. hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
  5418. NULL, OPEN_EXISTING,
  5419. FILE_FLAG_BACKUP_SEMANTICS, NULL);
  5420. Py_END_ALLOW_THREADS
  5421. if (hFile == INVALID_HANDLE_VALUE) {
  5422. path_error(path);
  5423. return NULL;
  5424. }
  5425. if (utime.now) {
  5426. GetSystemTimeAsFileTime(&mtime);
  5427. atime = mtime;
  5428. }
  5429. else {
  5430. _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
  5431. _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
  5432. }
  5433. if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
  5434. /* Avoid putting the file name into the error here,
  5435. as that may confuse the user into believing that
  5436. something is wrong with the file, when it also
  5437. could be the time stamp that gives a problem. */
  5438. PyErr_SetFromWindowsErr(0);
  5439. CloseHandle(hFile);
  5440. return NULL;
  5441. }
  5442. CloseHandle(hFile);
  5443. #else /* MS_WINDOWS */
  5444. Py_BEGIN_ALLOW_THREADS
  5445. #ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
  5446. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  5447. result = utime_nofollow_symlinks(&utime, path->narrow);
  5448. else
  5449. #endif
  5450. #if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
  5451. if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks)) {
  5452. result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
  5453. } else
  5454. #endif
  5455. #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
  5456. if (path->fd != -1)
  5457. result = utime_fd(&utime, path->fd);
  5458. else
  5459. #endif
  5460. result = utime_default(&utime, path->narrow);
  5461. Py_END_ALLOW_THREADS
  5462. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5463. /* See utime_dir_fd implementation */
  5464. if (result == -1 && errno == ENOSYS) {
  5465. argument_unavailable_error(NULL, "dir_fd");
  5466. return NULL;
  5467. }
  5468. #endif
  5469. if (result < 0) {
  5470. /* see previous comment about not putting filename in error here */
  5471. posix_error();
  5472. return NULL;
  5473. }
  5474. #endif /* MS_WINDOWS */
  5475. Py_RETURN_NONE;
  5476. }
  5477. /* Process operations */
  5478. /*[clinic input]
  5479. os._exit
  5480. status: int
  5481. Exit to the system with specified status, without normal exit processing.
  5482. [clinic start generated code]*/
  5483. static PyObject *
  5484. os__exit_impl(PyObject *module, int status)
  5485. /*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
  5486. {
  5487. _exit(status);
  5488. return NULL; /* Make gcc -Wall happy */
  5489. }
  5490. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5491. #define EXECV_CHAR wchar_t
  5492. #else
  5493. #define EXECV_CHAR char
  5494. #endif
  5495. #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
  5496. static void
  5497. free_string_array(EXECV_CHAR **array, Py_ssize_t count)
  5498. {
  5499. Py_ssize_t i;
  5500. for (i = 0; i < count; i++)
  5501. PyMem_Free(array[i]);
  5502. PyMem_Free(array);
  5503. }
  5504. static int
  5505. fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
  5506. {
  5507. Py_ssize_t size;
  5508. PyObject *ub;
  5509. int result = 0;
  5510. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5511. if (!PyUnicode_FSDecoder(o, &ub))
  5512. return 0;
  5513. *out = PyUnicode_AsWideCharString(ub, &size);
  5514. if (*out)
  5515. result = 1;
  5516. #else
  5517. if (!PyUnicode_FSConverter(o, &ub))
  5518. return 0;
  5519. size = PyBytes_GET_SIZE(ub);
  5520. *out = PyMem_Malloc(size + 1);
  5521. if (*out) {
  5522. memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
  5523. result = 1;
  5524. } else
  5525. PyErr_NoMemory();
  5526. #endif
  5527. Py_DECREF(ub);
  5528. return result;
  5529. }
  5530. #endif
  5531. #if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
  5532. static EXECV_CHAR**
  5533. parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
  5534. {
  5535. Py_ssize_t i, pos, envc;
  5536. PyObject *keys=NULL, *vals=NULL;
  5537. PyObject *key2, *val2, *keyval;
  5538. EXECV_CHAR **envlist;
  5539. i = PyMapping_Size(env);
  5540. if (i < 0)
  5541. return NULL;
  5542. envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
  5543. if (envlist == NULL) {
  5544. PyErr_NoMemory();
  5545. return NULL;
  5546. }
  5547. envc = 0;
  5548. keys = PyMapping_Keys(env);
  5549. if (!keys)
  5550. goto error;
  5551. vals = PyMapping_Values(env);
  5552. if (!vals)
  5553. goto error;
  5554. if (!PyList_Check(keys) || !PyList_Check(vals)) {
  5555. PyErr_Format(PyExc_TypeError,
  5556. "env.keys() or env.values() is not a list");
  5557. goto error;
  5558. }
  5559. for (pos = 0; pos < i; pos++) {
  5560. PyObject *key = PyList_GetItem(keys, pos); // Borrowed ref.
  5561. if (key == NULL) {
  5562. goto error;
  5563. }
  5564. PyObject *val = PyList_GetItem(vals, pos); // Borrowed ref.
  5565. if (val == NULL) {
  5566. goto error;
  5567. }
  5568. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5569. if (!PyUnicode_FSDecoder(key, &key2))
  5570. goto error;
  5571. if (!PyUnicode_FSDecoder(val, &val2)) {
  5572. Py_DECREF(key2);
  5573. goto error;
  5574. }
  5575. /* Search from index 1 because on Windows starting '=' is allowed for
  5576. defining hidden environment variables. */
  5577. if (PyUnicode_GET_LENGTH(key2) == 0 ||
  5578. PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
  5579. {
  5580. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  5581. Py_DECREF(key2);
  5582. Py_DECREF(val2);
  5583. goto error;
  5584. }
  5585. keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
  5586. #else
  5587. if (!PyUnicode_FSConverter(key, &key2))
  5588. goto error;
  5589. if (!PyUnicode_FSConverter(val, &val2)) {
  5590. Py_DECREF(key2);
  5591. goto error;
  5592. }
  5593. if (PyBytes_GET_SIZE(key2) == 0 ||
  5594. strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
  5595. {
  5596. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  5597. Py_DECREF(key2);
  5598. Py_DECREF(val2);
  5599. goto error;
  5600. }
  5601. keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
  5602. PyBytes_AS_STRING(val2));
  5603. #endif
  5604. Py_DECREF(key2);
  5605. Py_DECREF(val2);
  5606. if (!keyval)
  5607. goto error;
  5608. if (!fsconvert_strdup(keyval, &envlist[envc++])) {
  5609. Py_DECREF(keyval);
  5610. goto error;
  5611. }
  5612. Py_DECREF(keyval);
  5613. }
  5614. Py_DECREF(vals);
  5615. Py_DECREF(keys);
  5616. envlist[envc] = 0;
  5617. *envc_ptr = envc;
  5618. return envlist;
  5619. error:
  5620. Py_XDECREF(keys);
  5621. Py_XDECREF(vals);
  5622. free_string_array(envlist, envc);
  5623. return NULL;
  5624. }
  5625. static EXECV_CHAR**
  5626. parse_arglist(PyObject* argv, Py_ssize_t *argc)
  5627. {
  5628. int i;
  5629. EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
  5630. if (argvlist == NULL) {
  5631. PyErr_NoMemory();
  5632. return NULL;
  5633. }
  5634. for (i = 0; i < *argc; i++) {
  5635. PyObject* item = PySequence_ITEM(argv, i);
  5636. if (item == NULL)
  5637. goto fail;
  5638. if (!fsconvert_strdup(item, &argvlist[i])) {
  5639. Py_DECREF(item);
  5640. goto fail;
  5641. }
  5642. Py_DECREF(item);
  5643. }
  5644. argvlist[*argc] = NULL;
  5645. return argvlist;
  5646. fail:
  5647. *argc = i;
  5648. free_string_array(argvlist, *argc);
  5649. return NULL;
  5650. }
  5651. #endif
  5652. #ifdef HAVE_EXECV
  5653. /*[clinic input]
  5654. os.execv
  5655. path: path_t
  5656. Path of executable file.
  5657. argv: object
  5658. Tuple or list of strings.
  5659. /
  5660. Execute an executable path with arguments, replacing current process.
  5661. [clinic start generated code]*/
  5662. static PyObject *
  5663. os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
  5664. /*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
  5665. {
  5666. EXECV_CHAR **argvlist;
  5667. Py_ssize_t argc;
  5668. PyInterpreterState *interp = _PyInterpreterState_GET();
  5669. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_EXEC)) {
  5670. PyErr_SetString(PyExc_RuntimeError,
  5671. "exec not supported for isolated subinterpreters");
  5672. return NULL;
  5673. }
  5674. /* execv has two arguments: (path, argv), where
  5675. argv is a list or tuple of strings. */
  5676. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  5677. PyErr_SetString(PyExc_TypeError,
  5678. "execv() arg 2 must be a tuple or list");
  5679. return NULL;
  5680. }
  5681. argc = PySequence_Size(argv);
  5682. if (argc < 1) {
  5683. PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
  5684. return NULL;
  5685. }
  5686. argvlist = parse_arglist(argv, &argc);
  5687. if (argvlist == NULL) {
  5688. return NULL;
  5689. }
  5690. if (!argvlist[0][0]) {
  5691. PyErr_SetString(PyExc_ValueError,
  5692. "execv() arg 2 first element cannot be empty");
  5693. free_string_array(argvlist, argc);
  5694. return NULL;
  5695. }
  5696. if (PySys_Audit("os.exec", "OOO", path->object, argv, Py_None) < 0) {
  5697. free_string_array(argvlist, argc);
  5698. return NULL;
  5699. }
  5700. _Py_BEGIN_SUPPRESS_IPH
  5701. #ifdef HAVE_WEXECV
  5702. _wexecv(path->wide, argvlist);
  5703. #else
  5704. execv(path->narrow, argvlist);
  5705. #endif
  5706. _Py_END_SUPPRESS_IPH
  5707. /* If we get here it's definitely an error */
  5708. posix_error();
  5709. free_string_array(argvlist, argc);
  5710. return NULL;
  5711. }
  5712. /*[clinic input]
  5713. os.execve
  5714. path: path_t(allow_fd='PATH_HAVE_FEXECVE')
  5715. Path of executable file.
  5716. argv: object
  5717. Tuple or list of strings.
  5718. env: object
  5719. Dictionary of strings mapping to strings.
  5720. Execute an executable path with arguments, replacing current process.
  5721. [clinic start generated code]*/
  5722. static PyObject *
  5723. os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
  5724. /*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
  5725. {
  5726. EXECV_CHAR **argvlist = NULL;
  5727. EXECV_CHAR **envlist;
  5728. Py_ssize_t argc, envc;
  5729. PyInterpreterState *interp = _PyInterpreterState_GET();
  5730. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_EXEC)) {
  5731. PyErr_SetString(PyExc_RuntimeError,
  5732. "exec not supported for isolated subinterpreters");
  5733. return NULL;
  5734. }
  5735. /* execve has three arguments: (path, argv, env), where
  5736. argv is a list or tuple of strings and env is a dictionary
  5737. like posix.environ. */
  5738. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  5739. PyErr_SetString(PyExc_TypeError,
  5740. "execve: argv must be a tuple or list");
  5741. goto fail_0;
  5742. }
  5743. argc = PySequence_Size(argv);
  5744. if (argc < 1) {
  5745. PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
  5746. return NULL;
  5747. }
  5748. if (!PyMapping_Check(env)) {
  5749. PyErr_SetString(PyExc_TypeError,
  5750. "execve: environment must be a mapping object");
  5751. goto fail_0;
  5752. }
  5753. argvlist = parse_arglist(argv, &argc);
  5754. if (argvlist == NULL) {
  5755. goto fail_0;
  5756. }
  5757. if (!argvlist[0][0]) {
  5758. PyErr_SetString(PyExc_ValueError,
  5759. "execve: argv first element cannot be empty");
  5760. goto fail_0;
  5761. }
  5762. envlist = parse_envlist(env, &envc);
  5763. if (envlist == NULL)
  5764. goto fail_0;
  5765. if (PySys_Audit("os.exec", "OOO", path->object, argv, env) < 0) {
  5766. goto fail_1;
  5767. }
  5768. _Py_BEGIN_SUPPRESS_IPH
  5769. #ifdef HAVE_FEXECVE
  5770. if (path->fd > -1)
  5771. fexecve(path->fd, argvlist, envlist);
  5772. else
  5773. #endif
  5774. #ifdef HAVE_WEXECV
  5775. _wexecve(path->wide, argvlist, envlist);
  5776. #else
  5777. execve(path->narrow, argvlist, envlist);
  5778. #endif
  5779. _Py_END_SUPPRESS_IPH
  5780. /* If we get here it's definitely an error */
  5781. posix_path_error(path);
  5782. fail_1:
  5783. free_string_array(envlist, envc);
  5784. fail_0:
  5785. if (argvlist)
  5786. free_string_array(argvlist, argc);
  5787. return NULL;
  5788. }
  5789. #endif /* HAVE_EXECV */
  5790. #ifdef HAVE_POSIX_SPAWN
  5791. enum posix_spawn_file_actions_identifier {
  5792. POSIX_SPAWN_OPEN,
  5793. POSIX_SPAWN_CLOSE,
  5794. POSIX_SPAWN_DUP2
  5795. };
  5796. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  5797. static int
  5798. convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res);
  5799. #endif
  5800. static int
  5801. parse_posix_spawn_flags(PyObject *module, const char *func_name, PyObject *setpgroup,
  5802. int resetids, int setsid, PyObject *setsigmask,
  5803. PyObject *setsigdef, PyObject *scheduler,
  5804. posix_spawnattr_t *attrp)
  5805. {
  5806. long all_flags = 0;
  5807. errno = posix_spawnattr_init(attrp);
  5808. if (errno) {
  5809. posix_error();
  5810. return -1;
  5811. }
  5812. if (setpgroup) {
  5813. pid_t pgid = PyLong_AsPid(setpgroup);
  5814. if (pgid == (pid_t)-1 && PyErr_Occurred()) {
  5815. goto fail;
  5816. }
  5817. errno = posix_spawnattr_setpgroup(attrp, pgid);
  5818. if (errno) {
  5819. posix_error();
  5820. goto fail;
  5821. }
  5822. all_flags |= POSIX_SPAWN_SETPGROUP;
  5823. }
  5824. if (resetids) {
  5825. all_flags |= POSIX_SPAWN_RESETIDS;
  5826. }
  5827. if (setsid) {
  5828. #ifdef HAVE_POSIX_SPAWN_SETSID_RUNTIME
  5829. if (HAVE_POSIX_SPAWN_SETSID_RUNTIME) {
  5830. #endif
  5831. #ifdef POSIX_SPAWN_SETSID
  5832. all_flags |= POSIX_SPAWN_SETSID;
  5833. #elif defined(POSIX_SPAWN_SETSID_NP)
  5834. all_flags |= POSIX_SPAWN_SETSID_NP;
  5835. #else
  5836. argument_unavailable_error(func_name, "setsid");
  5837. return -1;
  5838. #endif
  5839. #ifdef HAVE_POSIX_SPAWN_SETSID_RUNTIME
  5840. } else {
  5841. argument_unavailable_error(func_name, "setsid");
  5842. return -1;
  5843. }
  5844. #endif /* HAVE_POSIX_SPAWN_SETSID_RUNTIME */
  5845. }
  5846. #ifdef HAVE_SIGSET_T
  5847. if (setsigmask) {
  5848. sigset_t set;
  5849. if (!_Py_Sigset_Converter(setsigmask, &set)) {
  5850. goto fail;
  5851. }
  5852. errno = posix_spawnattr_setsigmask(attrp, &set);
  5853. if (errno) {
  5854. posix_error();
  5855. goto fail;
  5856. }
  5857. all_flags |= POSIX_SPAWN_SETSIGMASK;
  5858. }
  5859. if (setsigdef) {
  5860. sigset_t set;
  5861. if (!_Py_Sigset_Converter(setsigdef, &set)) {
  5862. goto fail;
  5863. }
  5864. errno = posix_spawnattr_setsigdefault(attrp, &set);
  5865. if (errno) {
  5866. posix_error();
  5867. goto fail;
  5868. }
  5869. all_flags |= POSIX_SPAWN_SETSIGDEF;
  5870. }
  5871. #else
  5872. if (setsigmask || setsigdef) {
  5873. PyErr_SetString(PyExc_NotImplementedError,
  5874. "sigset is not supported on this platform");
  5875. goto fail;
  5876. }
  5877. #endif
  5878. if (scheduler) {
  5879. #ifdef POSIX_SPAWN_SETSCHEDULER
  5880. PyObject *py_schedpolicy;
  5881. PyObject *schedparam_obj;
  5882. struct sched_param schedparam;
  5883. if (!PyArg_ParseTuple(scheduler, "OO"
  5884. ";A scheduler tuple must have two elements",
  5885. &py_schedpolicy, &schedparam_obj)) {
  5886. goto fail;
  5887. }
  5888. if (!convert_sched_param(module, schedparam_obj, &schedparam)) {
  5889. goto fail;
  5890. }
  5891. if (py_schedpolicy != Py_None) {
  5892. int schedpolicy = _PyLong_AsInt(py_schedpolicy);
  5893. if (schedpolicy == -1 && PyErr_Occurred()) {
  5894. goto fail;
  5895. }
  5896. errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
  5897. if (errno) {
  5898. posix_error();
  5899. goto fail;
  5900. }
  5901. all_flags |= POSIX_SPAWN_SETSCHEDULER;
  5902. }
  5903. errno = posix_spawnattr_setschedparam(attrp, &schedparam);
  5904. if (errno) {
  5905. posix_error();
  5906. goto fail;
  5907. }
  5908. all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
  5909. #else
  5910. PyErr_SetString(PyExc_NotImplementedError,
  5911. "The scheduler option is not supported in this system.");
  5912. goto fail;
  5913. #endif
  5914. }
  5915. errno = posix_spawnattr_setflags(attrp, all_flags);
  5916. if (errno) {
  5917. posix_error();
  5918. goto fail;
  5919. }
  5920. return 0;
  5921. fail:
  5922. (void)posix_spawnattr_destroy(attrp);
  5923. return -1;
  5924. }
  5925. static int
  5926. parse_file_actions(PyObject *file_actions,
  5927. posix_spawn_file_actions_t *file_actionsp,
  5928. PyObject *temp_buffer)
  5929. {
  5930. PyObject *seq;
  5931. PyObject *file_action = NULL;
  5932. PyObject *tag_obj;
  5933. seq = PySequence_Fast(file_actions,
  5934. "file_actions must be a sequence or None");
  5935. if (seq == NULL) {
  5936. return -1;
  5937. }
  5938. errno = posix_spawn_file_actions_init(file_actionsp);
  5939. if (errno) {
  5940. posix_error();
  5941. Py_DECREF(seq);
  5942. return -1;
  5943. }
  5944. for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
  5945. file_action = PySequence_Fast_GET_ITEM(seq, i);
  5946. Py_INCREF(file_action);
  5947. if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
  5948. PyErr_SetString(PyExc_TypeError,
  5949. "Each file_actions element must be a non-empty tuple");
  5950. goto fail;
  5951. }
  5952. long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
  5953. if (tag == -1 && PyErr_Occurred()) {
  5954. goto fail;
  5955. }
  5956. /* Populate the file_actions object */
  5957. switch (tag) {
  5958. case POSIX_SPAWN_OPEN: {
  5959. int fd, oflag;
  5960. PyObject *path;
  5961. unsigned long mode;
  5962. if (!PyArg_ParseTuple(file_action, "OiO&ik"
  5963. ";A open file_action tuple must have 5 elements",
  5964. &tag_obj, &fd, PyUnicode_FSConverter, &path,
  5965. &oflag, &mode))
  5966. {
  5967. goto fail;
  5968. }
  5969. if (PyList_Append(temp_buffer, path)) {
  5970. Py_DECREF(path);
  5971. goto fail;
  5972. }
  5973. errno = posix_spawn_file_actions_addopen(file_actionsp,
  5974. fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
  5975. if (errno) {
  5976. posix_error();
  5977. Py_DECREF(path);
  5978. goto fail;
  5979. }
  5980. Py_DECREF(path);
  5981. break;
  5982. }
  5983. case POSIX_SPAWN_CLOSE: {
  5984. int fd;
  5985. if (!PyArg_ParseTuple(file_action, "Oi"
  5986. ";A close file_action tuple must have 2 elements",
  5987. &tag_obj, &fd))
  5988. {
  5989. goto fail;
  5990. }
  5991. errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
  5992. if (errno) {
  5993. posix_error();
  5994. goto fail;
  5995. }
  5996. break;
  5997. }
  5998. case POSIX_SPAWN_DUP2: {
  5999. int fd1, fd2;
  6000. if (!PyArg_ParseTuple(file_action, "Oii"
  6001. ";A dup2 file_action tuple must have 3 elements",
  6002. &tag_obj, &fd1, &fd2))
  6003. {
  6004. goto fail;
  6005. }
  6006. errno = posix_spawn_file_actions_adddup2(file_actionsp,
  6007. fd1, fd2);
  6008. if (errno) {
  6009. posix_error();
  6010. goto fail;
  6011. }
  6012. break;
  6013. }
  6014. default: {
  6015. PyErr_SetString(PyExc_TypeError,
  6016. "Unknown file_actions identifier");
  6017. goto fail;
  6018. }
  6019. }
  6020. Py_DECREF(file_action);
  6021. }
  6022. Py_DECREF(seq);
  6023. return 0;
  6024. fail:
  6025. Py_DECREF(seq);
  6026. Py_DECREF(file_action);
  6027. (void)posix_spawn_file_actions_destroy(file_actionsp);
  6028. return -1;
  6029. }
  6030. static PyObject *
  6031. py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
  6032. PyObject *env, PyObject *file_actions,
  6033. PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
  6034. PyObject *setsigdef, PyObject *scheduler)
  6035. {
  6036. const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
  6037. EXECV_CHAR **argvlist = NULL;
  6038. EXECV_CHAR **envlist = NULL;
  6039. posix_spawn_file_actions_t file_actions_buf;
  6040. posix_spawn_file_actions_t *file_actionsp = NULL;
  6041. posix_spawnattr_t attr;
  6042. posix_spawnattr_t *attrp = NULL;
  6043. Py_ssize_t argc, envc;
  6044. PyObject *result = NULL;
  6045. PyObject *temp_buffer = NULL;
  6046. pid_t pid;
  6047. int err_code;
  6048. /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
  6049. argv is a list or tuple of strings and env is a dictionary
  6050. like posix.environ. */
  6051. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  6052. PyErr_Format(PyExc_TypeError,
  6053. "%s: argv must be a tuple or list", func_name);
  6054. goto exit;
  6055. }
  6056. argc = PySequence_Size(argv);
  6057. if (argc < 1) {
  6058. PyErr_Format(PyExc_ValueError,
  6059. "%s: argv must not be empty", func_name);
  6060. return NULL;
  6061. }
  6062. if (!PyMapping_Check(env)) {
  6063. PyErr_Format(PyExc_TypeError,
  6064. "%s: environment must be a mapping object", func_name);
  6065. goto exit;
  6066. }
  6067. argvlist = parse_arglist(argv, &argc);
  6068. if (argvlist == NULL) {
  6069. goto exit;
  6070. }
  6071. if (!argvlist[0][0]) {
  6072. PyErr_Format(PyExc_ValueError,
  6073. "%s: argv first element cannot be empty", func_name);
  6074. goto exit;
  6075. }
  6076. envlist = parse_envlist(env, &envc);
  6077. if (envlist == NULL) {
  6078. goto exit;
  6079. }
  6080. if (file_actions != NULL && file_actions != Py_None) {
  6081. /* There is a bug in old versions of glibc that makes some of the
  6082. * helper functions for manipulating file actions not copy the provided
  6083. * buffers. The problem is that posix_spawn_file_actions_addopen does not
  6084. * copy the value of path for some old versions of glibc (<2.20).
  6085. * The use of temp_buffer here is a workaround that keeps the
  6086. * python objects that own the buffers alive until posix_spawn gets called.
  6087. * Check https://bugs.python.org/issue33630 and
  6088. * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
  6089. temp_buffer = PyList_New(0);
  6090. if (!temp_buffer) {
  6091. goto exit;
  6092. }
  6093. if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
  6094. goto exit;
  6095. }
  6096. file_actionsp = &file_actions_buf;
  6097. }
  6098. if (parse_posix_spawn_flags(module, func_name, setpgroup, resetids, setsid,
  6099. setsigmask, setsigdef, scheduler, &attr)) {
  6100. goto exit;
  6101. }
  6102. attrp = &attr;
  6103. if (PySys_Audit("os.posix_spawn", "OOO", path->object, argv, env) < 0) {
  6104. goto exit;
  6105. }
  6106. _Py_BEGIN_SUPPRESS_IPH
  6107. #ifdef HAVE_POSIX_SPAWNP
  6108. if (use_posix_spawnp) {
  6109. err_code = posix_spawnp(&pid, path->narrow,
  6110. file_actionsp, attrp, argvlist, envlist);
  6111. }
  6112. else
  6113. #endif /* HAVE_POSIX_SPAWNP */
  6114. {
  6115. err_code = posix_spawn(&pid, path->narrow,
  6116. file_actionsp, attrp, argvlist, envlist);
  6117. }
  6118. _Py_END_SUPPRESS_IPH
  6119. if (err_code) {
  6120. errno = err_code;
  6121. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
  6122. goto exit;
  6123. }
  6124. #ifdef _Py_MEMORY_SANITIZER
  6125. __msan_unpoison(&pid, sizeof(pid));
  6126. #endif
  6127. result = PyLong_FromPid(pid);
  6128. exit:
  6129. if (file_actionsp) {
  6130. (void)posix_spawn_file_actions_destroy(file_actionsp);
  6131. }
  6132. if (attrp) {
  6133. (void)posix_spawnattr_destroy(attrp);
  6134. }
  6135. if (envlist) {
  6136. free_string_array(envlist, envc);
  6137. }
  6138. if (argvlist) {
  6139. free_string_array(argvlist, argc);
  6140. }
  6141. Py_XDECREF(temp_buffer);
  6142. return result;
  6143. }
  6144. /*[clinic input]
  6145. os.posix_spawn
  6146. path: path_t
  6147. Path of executable file.
  6148. argv: object
  6149. Tuple or list of strings.
  6150. env: object
  6151. Dictionary of strings mapping to strings.
  6152. /
  6153. *
  6154. file_actions: object(c_default='NULL') = ()
  6155. A sequence of file action tuples.
  6156. setpgroup: object = NULL
  6157. The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
  6158. resetids: bool = False
  6159. If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
  6160. setsid: bool = False
  6161. If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
  6162. setsigmask: object(c_default='NULL') = ()
  6163. The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
  6164. setsigdef: object(c_default='NULL') = ()
  6165. The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
  6166. scheduler: object = NULL
  6167. A tuple with the scheduler policy (optional) and parameters.
  6168. Execute the program specified by path in a new process.
  6169. [clinic start generated code]*/
  6170. static PyObject *
  6171. os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
  6172. PyObject *env, PyObject *file_actions,
  6173. PyObject *setpgroup, int resetids, int setsid,
  6174. PyObject *setsigmask, PyObject *setsigdef,
  6175. PyObject *scheduler)
  6176. /*[clinic end generated code: output=14a1098c566bc675 input=808aed1090d84e33]*/
  6177. {
  6178. return py_posix_spawn(0, module, path, argv, env, file_actions,
  6179. setpgroup, resetids, setsid, setsigmask, setsigdef,
  6180. scheduler);
  6181. }
  6182. #endif /* HAVE_POSIX_SPAWN */
  6183. #ifdef HAVE_POSIX_SPAWNP
  6184. /*[clinic input]
  6185. os.posix_spawnp
  6186. path: path_t
  6187. Path of executable file.
  6188. argv: object
  6189. Tuple or list of strings.
  6190. env: object
  6191. Dictionary of strings mapping to strings.
  6192. /
  6193. *
  6194. file_actions: object(c_default='NULL') = ()
  6195. A sequence of file action tuples.
  6196. setpgroup: object = NULL
  6197. The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
  6198. resetids: bool = False
  6199. If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
  6200. setsid: bool = False
  6201. If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
  6202. setsigmask: object(c_default='NULL') = ()
  6203. The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
  6204. setsigdef: object(c_default='NULL') = ()
  6205. The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
  6206. scheduler: object = NULL
  6207. A tuple with the scheduler policy (optional) and parameters.
  6208. Execute the program specified by path in a new process.
  6209. [clinic start generated code]*/
  6210. static PyObject *
  6211. os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
  6212. PyObject *env, PyObject *file_actions,
  6213. PyObject *setpgroup, int resetids, int setsid,
  6214. PyObject *setsigmask, PyObject *setsigdef,
  6215. PyObject *scheduler)
  6216. /*[clinic end generated code: output=7b9aaefe3031238d input=9e89e616116752a1]*/
  6217. {
  6218. return py_posix_spawn(1, module, path, argv, env, file_actions,
  6219. setpgroup, resetids, setsid, setsigmask, setsigdef,
  6220. scheduler);
  6221. }
  6222. #endif /* HAVE_POSIX_SPAWNP */
  6223. #ifdef HAVE_RTPSPAWN
  6224. static intptr_t
  6225. _rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
  6226. const char *envp[])
  6227. {
  6228. RTP_ID rtpid;
  6229. int status;
  6230. pid_t res;
  6231. int async_err = 0;
  6232. /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
  6233. uStackSize=0 cannot be used, the default stack size is too small for
  6234. Python. */
  6235. if (envp) {
  6236. rtpid = rtpSpawn(rtpFileName, argv, envp,
  6237. 100, 0x1000000, 0, VX_FP_TASK);
  6238. }
  6239. else {
  6240. rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
  6241. 100, 0x1000000, 0, VX_FP_TASK);
  6242. }
  6243. if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
  6244. do {
  6245. res = waitpid((pid_t)rtpid, &status, 0);
  6246. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  6247. if (res < 0)
  6248. return RTP_ID_ERROR;
  6249. return ((intptr_t)status);
  6250. }
  6251. return ((intptr_t)rtpid);
  6252. }
  6253. #endif
  6254. #if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
  6255. /*[clinic input]
  6256. os.spawnv
  6257. mode: int
  6258. Mode of process creation.
  6259. path: path_t
  6260. Path of executable file.
  6261. argv: object
  6262. Tuple or list of strings.
  6263. /
  6264. Execute the program specified by path in a new process.
  6265. [clinic start generated code]*/
  6266. static PyObject *
  6267. os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
  6268. /*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
  6269. {
  6270. EXECV_CHAR **argvlist;
  6271. int i;
  6272. Py_ssize_t argc;
  6273. intptr_t spawnval;
  6274. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  6275. /* spawnv has three arguments: (mode, path, argv), where
  6276. argv is a list or tuple of strings. */
  6277. if (PyList_Check(argv)) {
  6278. argc = PyList_Size(argv);
  6279. getitem = PyList_GetItem;
  6280. }
  6281. else if (PyTuple_Check(argv)) {
  6282. argc = PyTuple_Size(argv);
  6283. getitem = PyTuple_GetItem;
  6284. }
  6285. else {
  6286. PyErr_SetString(PyExc_TypeError,
  6287. "spawnv() arg 2 must be a tuple or list");
  6288. return NULL;
  6289. }
  6290. if (argc == 0) {
  6291. PyErr_SetString(PyExc_ValueError,
  6292. "spawnv() arg 2 cannot be empty");
  6293. return NULL;
  6294. }
  6295. argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
  6296. if (argvlist == NULL) {
  6297. return PyErr_NoMemory();
  6298. }
  6299. for (i = 0; i < argc; i++) {
  6300. if (!fsconvert_strdup((*getitem)(argv, i),
  6301. &argvlist[i])) {
  6302. free_string_array(argvlist, i);
  6303. PyErr_SetString(
  6304. PyExc_TypeError,
  6305. "spawnv() arg 2 must contain only strings");
  6306. return NULL;
  6307. }
  6308. if (i == 0 && !argvlist[0][0]) {
  6309. free_string_array(argvlist, i + 1);
  6310. PyErr_SetString(
  6311. PyExc_ValueError,
  6312. "spawnv() arg 2 first element cannot be empty");
  6313. return NULL;
  6314. }
  6315. }
  6316. argvlist[argc] = NULL;
  6317. #if !defined(HAVE_RTPSPAWN)
  6318. if (mode == _OLD_P_OVERLAY)
  6319. mode = _P_OVERLAY;
  6320. #endif
  6321. if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv,
  6322. Py_None) < 0) {
  6323. free_string_array(argvlist, argc);
  6324. return NULL;
  6325. }
  6326. Py_BEGIN_ALLOW_THREADS
  6327. _Py_BEGIN_SUPPRESS_IPH
  6328. #ifdef HAVE_WSPAWNV
  6329. spawnval = _wspawnv(mode, path->wide, argvlist);
  6330. #elif defined(HAVE_RTPSPAWN)
  6331. spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
  6332. #else
  6333. spawnval = _spawnv(mode, path->narrow, argvlist);
  6334. #endif
  6335. _Py_END_SUPPRESS_IPH
  6336. Py_END_ALLOW_THREADS
  6337. int saved_errno = errno;
  6338. free_string_array(argvlist, argc);
  6339. if (spawnval == -1) {
  6340. errno = saved_errno;
  6341. posix_error();
  6342. return NULL;
  6343. }
  6344. return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
  6345. }
  6346. /*[clinic input]
  6347. os.spawnve
  6348. mode: int
  6349. Mode of process creation.
  6350. path: path_t
  6351. Path of executable file.
  6352. argv: object
  6353. Tuple or list of strings.
  6354. env: object
  6355. Dictionary of strings mapping to strings.
  6356. /
  6357. Execute the program specified by path in a new process.
  6358. [clinic start generated code]*/
  6359. static PyObject *
  6360. os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
  6361. PyObject *env)
  6362. /*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
  6363. {
  6364. EXECV_CHAR **argvlist;
  6365. EXECV_CHAR **envlist;
  6366. PyObject *res = NULL;
  6367. Py_ssize_t argc, i, envc;
  6368. intptr_t spawnval;
  6369. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  6370. Py_ssize_t lastarg = 0;
  6371. /* spawnve has four arguments: (mode, path, argv, env), where
  6372. argv is a list or tuple of strings and env is a dictionary
  6373. like posix.environ. */
  6374. if (PyList_Check(argv)) {
  6375. argc = PyList_Size(argv);
  6376. getitem = PyList_GetItem;
  6377. }
  6378. else if (PyTuple_Check(argv)) {
  6379. argc = PyTuple_Size(argv);
  6380. getitem = PyTuple_GetItem;
  6381. }
  6382. else {
  6383. PyErr_SetString(PyExc_TypeError,
  6384. "spawnve() arg 2 must be a tuple or list");
  6385. goto fail_0;
  6386. }
  6387. if (argc == 0) {
  6388. PyErr_SetString(PyExc_ValueError,
  6389. "spawnve() arg 2 cannot be empty");
  6390. goto fail_0;
  6391. }
  6392. if (!PyMapping_Check(env)) {
  6393. PyErr_SetString(PyExc_TypeError,
  6394. "spawnve() arg 3 must be a mapping object");
  6395. goto fail_0;
  6396. }
  6397. argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
  6398. if (argvlist == NULL) {
  6399. PyErr_NoMemory();
  6400. goto fail_0;
  6401. }
  6402. for (i = 0; i < argc; i++) {
  6403. if (!fsconvert_strdup((*getitem)(argv, i),
  6404. &argvlist[i]))
  6405. {
  6406. lastarg = i;
  6407. goto fail_1;
  6408. }
  6409. if (i == 0 && !argvlist[0][0]) {
  6410. lastarg = i + 1;
  6411. PyErr_SetString(
  6412. PyExc_ValueError,
  6413. "spawnv() arg 2 first element cannot be empty");
  6414. goto fail_1;
  6415. }
  6416. }
  6417. lastarg = argc;
  6418. argvlist[argc] = NULL;
  6419. envlist = parse_envlist(env, &envc);
  6420. if (envlist == NULL)
  6421. goto fail_1;
  6422. #if !defined(HAVE_RTPSPAWN)
  6423. if (mode == _OLD_P_OVERLAY)
  6424. mode = _P_OVERLAY;
  6425. #endif
  6426. if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv, env) < 0) {
  6427. goto fail_2;
  6428. }
  6429. Py_BEGIN_ALLOW_THREADS
  6430. _Py_BEGIN_SUPPRESS_IPH
  6431. #ifdef HAVE_WSPAWNV
  6432. spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
  6433. #elif defined(HAVE_RTPSPAWN)
  6434. spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
  6435. (const char **)envlist);
  6436. #else
  6437. spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
  6438. #endif
  6439. _Py_END_SUPPRESS_IPH
  6440. Py_END_ALLOW_THREADS
  6441. if (spawnval == -1)
  6442. (void) posix_error();
  6443. else
  6444. res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
  6445. fail_2:
  6446. while (--envc >= 0) {
  6447. PyMem_Free(envlist[envc]);
  6448. }
  6449. PyMem_Free(envlist);
  6450. fail_1:
  6451. free_string_array(argvlist, lastarg);
  6452. fail_0:
  6453. return res;
  6454. }
  6455. #endif /* HAVE_SPAWNV */
  6456. #ifdef HAVE_FORK
  6457. /* Helper function to validate arguments.
  6458. Returns 0 on success. non-zero on failure with a TypeError raised.
  6459. If obj is non-NULL it must be callable. */
  6460. static int
  6461. check_null_or_callable(PyObject *obj, const char* obj_name)
  6462. {
  6463. if (obj && !PyCallable_Check(obj)) {
  6464. PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
  6465. obj_name, _PyType_Name(Py_TYPE(obj)));
  6466. return -1;
  6467. }
  6468. return 0;
  6469. }
  6470. /*[clinic input]
  6471. os.register_at_fork
  6472. *
  6473. before: object=NULL
  6474. A callable to be called in the parent before the fork() syscall.
  6475. after_in_child: object=NULL
  6476. A callable to be called in the child after fork().
  6477. after_in_parent: object=NULL
  6478. A callable to be called in the parent after fork().
  6479. Register callables to be called when forking a new process.
  6480. 'before' callbacks are called in reverse order.
  6481. 'after_in_child' and 'after_in_parent' callbacks are called in order.
  6482. [clinic start generated code]*/
  6483. static PyObject *
  6484. os_register_at_fork_impl(PyObject *module, PyObject *before,
  6485. PyObject *after_in_child, PyObject *after_in_parent)
  6486. /*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
  6487. {
  6488. PyInterpreterState *interp;
  6489. if (!before && !after_in_child && !after_in_parent) {
  6490. PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
  6491. return NULL;
  6492. }
  6493. if (check_null_or_callable(before, "before") ||
  6494. check_null_or_callable(after_in_child, "after_in_child") ||
  6495. check_null_or_callable(after_in_parent, "after_in_parent")) {
  6496. return NULL;
  6497. }
  6498. interp = _PyInterpreterState_GET();
  6499. if (register_at_forker(&interp->before_forkers, before)) {
  6500. return NULL;
  6501. }
  6502. if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
  6503. return NULL;
  6504. }
  6505. if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
  6506. return NULL;
  6507. }
  6508. Py_RETURN_NONE;
  6509. }
  6510. #endif /* HAVE_FORK */
  6511. #if defined(HAVE_FORK1) || defined(HAVE_FORKPTY) || defined(HAVE_FORK)
  6512. // Common code to raise a warning if we detect there is more than one thread
  6513. // running in the process. Best effort, silent if unable to count threads.
  6514. // Constraint: Quick. Never overcounts. Never leaves an error set.
  6515. //
  6516. // This code might do an import, thus acquiring the import lock, which
  6517. // PyOS_BeforeFork() also does. As this should only be called from
  6518. // the parent process, it is in the same thread so that works.
  6519. static void warn_about_fork_with_threads(const char* name) {
  6520. // TODO: Consider making an `os` module API to return the current number
  6521. // of threads in the process. That'd presumably use this platform code but
  6522. // raise an error rather than using the inaccurate fallback.
  6523. Py_ssize_t num_python_threads = 0;
  6524. #if defined(__APPLE__) && defined(HAVE_GETPID)
  6525. mach_port_t macos_self = mach_task_self();
  6526. mach_port_t macos_task;
  6527. if (task_for_pid(macos_self, getpid(), &macos_task) == KERN_SUCCESS) {
  6528. thread_array_t macos_threads;
  6529. mach_msg_type_number_t macos_n_threads;
  6530. if (task_threads(macos_task, &macos_threads,
  6531. &macos_n_threads) == KERN_SUCCESS) {
  6532. num_python_threads = macos_n_threads;
  6533. }
  6534. }
  6535. #elif defined(__linux__)
  6536. // Linux /proc/self/stat 20th field is the number of threads.
  6537. FILE* proc_stat = fopen("/proc/self/stat", "r");
  6538. if (proc_stat) {
  6539. size_t n;
  6540. // Size chosen arbitrarily. ~60% more bytes than a 20th column index
  6541. // observed on the author's workstation.
  6542. char stat_line[160];
  6543. n = fread(&stat_line, 1, 159, proc_stat);
  6544. stat_line[n] = '\0';
  6545. fclose(proc_stat);
  6546. char *saveptr = NULL;
  6547. char *field = strtok_r(stat_line, " ", &saveptr);
  6548. unsigned int idx;
  6549. for (idx = 19; idx && field; --idx) {
  6550. field = strtok_r(NULL, " ", &saveptr);
  6551. }
  6552. if (idx == 0 && field) { // found the 20th field
  6553. num_python_threads = atoi(field); // 0 on error
  6554. }
  6555. }
  6556. #endif
  6557. if (num_python_threads <= 0) {
  6558. // Fall back to just the number our threading module knows about.
  6559. // An incomplete view of the world, but better than nothing.
  6560. PyObject *threading = PyImport_GetModule(&_Py_ID(threading));
  6561. if (!threading) {
  6562. PyErr_Clear();
  6563. return;
  6564. }
  6565. PyObject *threading_active =
  6566. PyObject_GetAttr(threading, &_Py_ID(_active));
  6567. if (!threading_active) {
  6568. PyErr_Clear();
  6569. Py_DECREF(threading);
  6570. return;
  6571. }
  6572. PyObject *threading_limbo =
  6573. PyObject_GetAttr(threading, &_Py_ID(_limbo));
  6574. if (!threading_limbo) {
  6575. PyErr_Clear();
  6576. Py_DECREF(threading);
  6577. Py_DECREF(threading_active);
  6578. return;
  6579. }
  6580. Py_DECREF(threading);
  6581. // Duplicating what threading.active_count() does but without holding
  6582. // threading._active_limbo_lock so our count could be inaccurate if
  6583. // these dicts are mid-update from another thread. Not a big deal.
  6584. // Worst case if someone replaced threading._active or threading._limbo
  6585. // with non-dicts, we get -1 from *Length() below and undercount.
  6586. // Nobody should, but we're best effort so we clear errors and move on.
  6587. num_python_threads = (PyMapping_Length(threading_active)
  6588. + PyMapping_Length(threading_limbo));
  6589. PyErr_Clear();
  6590. Py_DECREF(threading_active);
  6591. Py_DECREF(threading_limbo);
  6592. }
  6593. if (num_python_threads > 1) {
  6594. PyErr_WarnFormat(
  6595. PyExc_DeprecationWarning, 1,
  6596. #ifdef HAVE_GETPID
  6597. "This process (pid=%d) is multi-threaded, "
  6598. #else
  6599. "This process is multi-threaded, "
  6600. #endif
  6601. "use of %s() may lead to deadlocks in the child.",
  6602. #ifdef HAVE_GETPID
  6603. getpid(),
  6604. #endif
  6605. name);
  6606. PyErr_Clear();
  6607. }
  6608. }
  6609. #endif // HAVE_FORK1 || HAVE_FORKPTY || HAVE_FORK
  6610. #ifdef HAVE_FORK1
  6611. /*[clinic input]
  6612. os.fork1
  6613. Fork a child process with a single multiplexed (i.e., not bound) thread.
  6614. Return 0 to child process and PID of child to parent process.
  6615. [clinic start generated code]*/
  6616. static PyObject *
  6617. os_fork1_impl(PyObject *module)
  6618. /*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
  6619. {
  6620. pid_t pid;
  6621. PyInterpreterState *interp = _PyInterpreterState_GET();
  6622. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  6623. PyErr_SetString(PyExc_RuntimeError,
  6624. "can't fork at interpreter shutdown");
  6625. return NULL;
  6626. }
  6627. if (!_Py_IsMainInterpreter(interp)) {
  6628. PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
  6629. return NULL;
  6630. }
  6631. PyOS_BeforeFork();
  6632. pid = fork1();
  6633. int saved_errno = errno;
  6634. if (pid == 0) {
  6635. /* child: this clobbers and resets the import lock. */
  6636. PyOS_AfterFork_Child();
  6637. } else {
  6638. warn_about_fork_with_threads("fork1");
  6639. /* parent: release the import lock. */
  6640. PyOS_AfterFork_Parent();
  6641. }
  6642. if (pid == -1) {
  6643. errno = saved_errno;
  6644. return posix_error();
  6645. }
  6646. return PyLong_FromPid(pid);
  6647. }
  6648. #endif /* HAVE_FORK1 */
  6649. #ifdef HAVE_FORK
  6650. /*[clinic input]
  6651. os.fork
  6652. Fork a child process.
  6653. Return 0 to child process and PID of child to parent process.
  6654. [clinic start generated code]*/
  6655. static PyObject *
  6656. os_fork_impl(PyObject *module)
  6657. /*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
  6658. {
  6659. pid_t pid;
  6660. PyInterpreterState *interp = _PyInterpreterState_GET();
  6661. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  6662. PyErr_SetString(PyExc_RuntimeError,
  6663. "can't fork at interpreter shutdown");
  6664. return NULL;
  6665. }
  6666. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_FORK)) {
  6667. PyErr_SetString(PyExc_RuntimeError,
  6668. "fork not supported for isolated subinterpreters");
  6669. return NULL;
  6670. }
  6671. if (PySys_Audit("os.fork", NULL) < 0) {
  6672. return NULL;
  6673. }
  6674. PyOS_BeforeFork();
  6675. pid = fork();
  6676. int saved_errno = errno;
  6677. if (pid == 0) {
  6678. /* child: this clobbers and resets the import lock. */
  6679. PyOS_AfterFork_Child();
  6680. } else {
  6681. warn_about_fork_with_threads("fork");
  6682. /* parent: release the import lock. */
  6683. PyOS_AfterFork_Parent();
  6684. }
  6685. if (pid == -1) {
  6686. errno = saved_errno;
  6687. return posix_error();
  6688. }
  6689. return PyLong_FromPid(pid);
  6690. }
  6691. #endif /* HAVE_FORK */
  6692. #ifdef HAVE_SCHED_H
  6693. #ifdef HAVE_SCHED_GET_PRIORITY_MAX
  6694. /*[clinic input]
  6695. os.sched_get_priority_max
  6696. policy: int
  6697. Get the maximum scheduling priority for policy.
  6698. [clinic start generated code]*/
  6699. static PyObject *
  6700. os_sched_get_priority_max_impl(PyObject *module, int policy)
  6701. /*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
  6702. {
  6703. int max;
  6704. max = sched_get_priority_max(policy);
  6705. if (max < 0)
  6706. return posix_error();
  6707. return PyLong_FromLong(max);
  6708. }
  6709. /*[clinic input]
  6710. os.sched_get_priority_min
  6711. policy: int
  6712. Get the minimum scheduling priority for policy.
  6713. [clinic start generated code]*/
  6714. static PyObject *
  6715. os_sched_get_priority_min_impl(PyObject *module, int policy)
  6716. /*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
  6717. {
  6718. int min = sched_get_priority_min(policy);
  6719. if (min < 0)
  6720. return posix_error();
  6721. return PyLong_FromLong(min);
  6722. }
  6723. #endif /* HAVE_SCHED_GET_PRIORITY_MAX */
  6724. #ifdef HAVE_SCHED_SETSCHEDULER
  6725. /*[clinic input]
  6726. os.sched_getscheduler
  6727. pid: pid_t
  6728. /
  6729. Get the scheduling policy for the process identified by pid.
  6730. Passing 0 for pid returns the scheduling policy for the calling process.
  6731. [clinic start generated code]*/
  6732. static PyObject *
  6733. os_sched_getscheduler_impl(PyObject *module, pid_t pid)
  6734. /*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
  6735. {
  6736. int policy;
  6737. policy = sched_getscheduler(pid);
  6738. if (policy < 0)
  6739. return posix_error();
  6740. return PyLong_FromLong(policy);
  6741. }
  6742. #endif /* HAVE_SCHED_SETSCHEDULER */
  6743. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  6744. /*[clinic input]
  6745. class os.sched_param "PyObject *" "SchedParamType"
  6746. @classmethod
  6747. os.sched_param.__new__
  6748. sched_priority: object
  6749. A scheduling parameter.
  6750. Currently has only one field: sched_priority
  6751. [clinic start generated code]*/
  6752. static PyObject *
  6753. os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
  6754. /*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
  6755. {
  6756. PyObject *res;
  6757. res = PyStructSequence_New(type);
  6758. if (!res)
  6759. return NULL;
  6760. PyStructSequence_SET_ITEM(res, 0, Py_NewRef(sched_priority));
  6761. return res;
  6762. }
  6763. static PyObject *
  6764. os_sched_param_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
  6765. {
  6766. return Py_BuildValue("(O(N))", Py_TYPE(self), PyStructSequence_GetItem(self, 0));
  6767. }
  6768. static PyMethodDef os_sched_param_reduce_method = {
  6769. "__reduce__", (PyCFunction)os_sched_param_reduce, METH_NOARGS|METH_COEXIST, NULL,
  6770. };
  6771. PyDoc_VAR(os_sched_param__doc__);
  6772. static PyStructSequence_Field sched_param_fields[] = {
  6773. {"sched_priority", "the scheduling priority"},
  6774. {0}
  6775. };
  6776. static PyStructSequence_Desc sched_param_desc = {
  6777. "sched_param", /* name */
  6778. os_sched_param__doc__, /* doc */
  6779. sched_param_fields,
  6780. 1
  6781. };
  6782. static int
  6783. convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res)
  6784. {
  6785. long priority;
  6786. if (!Py_IS_TYPE(param, (PyTypeObject *)get_posix_state(module)->SchedParamType)) {
  6787. PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
  6788. return 0;
  6789. }
  6790. priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
  6791. if (priority == -1 && PyErr_Occurred())
  6792. return 0;
  6793. if (priority > INT_MAX || priority < INT_MIN) {
  6794. PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
  6795. return 0;
  6796. }
  6797. res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
  6798. return 1;
  6799. }
  6800. #endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
  6801. #ifdef HAVE_SCHED_SETSCHEDULER
  6802. /*[clinic input]
  6803. os.sched_setscheduler
  6804. pid: pid_t
  6805. policy: int
  6806. param as param_obj: object
  6807. /
  6808. Set the scheduling policy for the process identified by pid.
  6809. If pid is 0, the calling process is changed.
  6810. param is an instance of sched_param.
  6811. [clinic start generated code]*/
  6812. static PyObject *
  6813. os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
  6814. PyObject *param_obj)
  6815. /*[clinic end generated code: output=cde27faa55dc993e input=73013d731bd8fbe9]*/
  6816. {
  6817. struct sched_param param;
  6818. if (!convert_sched_param(module, param_obj, &param)) {
  6819. return NULL;
  6820. }
  6821. /*
  6822. ** sched_setscheduler() returns 0 in Linux, but the previous
  6823. ** scheduling policy under Solaris/Illumos, and others.
  6824. ** On error, -1 is returned in all Operating Systems.
  6825. */
  6826. if (sched_setscheduler(pid, policy, &param) == -1)
  6827. return posix_error();
  6828. Py_RETURN_NONE;
  6829. }
  6830. #endif /* HAVE_SCHED_SETSCHEDULER*/
  6831. #ifdef HAVE_SCHED_SETPARAM
  6832. /*[clinic input]
  6833. os.sched_getparam
  6834. pid: pid_t
  6835. /
  6836. Returns scheduling parameters for the process identified by pid.
  6837. If pid is 0, returns parameters for the calling process.
  6838. Return value is an instance of sched_param.
  6839. [clinic start generated code]*/
  6840. static PyObject *
  6841. os_sched_getparam_impl(PyObject *module, pid_t pid)
  6842. /*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
  6843. {
  6844. struct sched_param param;
  6845. PyObject *result;
  6846. PyObject *priority;
  6847. if (sched_getparam(pid, &param))
  6848. return posix_error();
  6849. PyObject *SchedParamType = get_posix_state(module)->SchedParamType;
  6850. result = PyStructSequence_New((PyTypeObject *)SchedParamType);
  6851. if (!result)
  6852. return NULL;
  6853. priority = PyLong_FromLong(param.sched_priority);
  6854. if (!priority) {
  6855. Py_DECREF(result);
  6856. return NULL;
  6857. }
  6858. PyStructSequence_SET_ITEM(result, 0, priority);
  6859. return result;
  6860. }
  6861. /*[clinic input]
  6862. os.sched_setparam
  6863. pid: pid_t
  6864. param as param_obj: object
  6865. /
  6866. Set scheduling parameters for the process identified by pid.
  6867. If pid is 0, sets parameters for the calling process.
  6868. param should be an instance of sched_param.
  6869. [clinic start generated code]*/
  6870. static PyObject *
  6871. os_sched_setparam_impl(PyObject *module, pid_t pid, PyObject *param_obj)
  6872. /*[clinic end generated code: output=f19fe020a53741c1 input=27b98337c8b2dcc7]*/
  6873. {
  6874. struct sched_param param;
  6875. if (!convert_sched_param(module, param_obj, &param)) {
  6876. return NULL;
  6877. }
  6878. if (sched_setparam(pid, &param))
  6879. return posix_error();
  6880. Py_RETURN_NONE;
  6881. }
  6882. #endif /* HAVE_SCHED_SETPARAM */
  6883. #ifdef HAVE_SCHED_RR_GET_INTERVAL
  6884. /*[clinic input]
  6885. os.sched_rr_get_interval -> double
  6886. pid: pid_t
  6887. /
  6888. Return the round-robin quantum for the process identified by pid, in seconds.
  6889. Value returned is a float.
  6890. [clinic start generated code]*/
  6891. static double
  6892. os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
  6893. /*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
  6894. {
  6895. struct timespec interval;
  6896. if (sched_rr_get_interval(pid, &interval)) {
  6897. posix_error();
  6898. return -1.0;
  6899. }
  6900. #ifdef _Py_MEMORY_SANITIZER
  6901. __msan_unpoison(&interval, sizeof(interval));
  6902. #endif
  6903. return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
  6904. }
  6905. #endif /* HAVE_SCHED_RR_GET_INTERVAL */
  6906. /*[clinic input]
  6907. os.sched_yield
  6908. Voluntarily relinquish the CPU.
  6909. [clinic start generated code]*/
  6910. static PyObject *
  6911. os_sched_yield_impl(PyObject *module)
  6912. /*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
  6913. {
  6914. int result;
  6915. Py_BEGIN_ALLOW_THREADS
  6916. result = sched_yield();
  6917. Py_END_ALLOW_THREADS
  6918. if (result < 0) {
  6919. return posix_error();
  6920. }
  6921. Py_RETURN_NONE;
  6922. }
  6923. #ifdef HAVE_SCHED_SETAFFINITY
  6924. /* The minimum number of CPUs allocated in a cpu_set_t */
  6925. static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
  6926. /*[clinic input]
  6927. os.sched_setaffinity
  6928. pid: pid_t
  6929. mask : object
  6930. /
  6931. Set the CPU affinity of the process identified by pid to mask.
  6932. mask should be an iterable of integers identifying CPUs.
  6933. [clinic start generated code]*/
  6934. static PyObject *
  6935. os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
  6936. /*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
  6937. {
  6938. int ncpus;
  6939. size_t setsize;
  6940. cpu_set_t *cpu_set = NULL;
  6941. PyObject *iterator = NULL, *item;
  6942. iterator = PyObject_GetIter(mask);
  6943. if (iterator == NULL)
  6944. return NULL;
  6945. ncpus = NCPUS_START;
  6946. setsize = CPU_ALLOC_SIZE(ncpus);
  6947. cpu_set = CPU_ALLOC(ncpus);
  6948. if (cpu_set == NULL) {
  6949. PyErr_NoMemory();
  6950. goto error;
  6951. }
  6952. CPU_ZERO_S(setsize, cpu_set);
  6953. while ((item = PyIter_Next(iterator))) {
  6954. long cpu;
  6955. if (!PyLong_Check(item)) {
  6956. PyErr_Format(PyExc_TypeError,
  6957. "expected an iterator of ints, "
  6958. "but iterator yielded %R",
  6959. Py_TYPE(item));
  6960. Py_DECREF(item);
  6961. goto error;
  6962. }
  6963. cpu = PyLong_AsLong(item);
  6964. Py_DECREF(item);
  6965. if (cpu < 0) {
  6966. if (!PyErr_Occurred())
  6967. PyErr_SetString(PyExc_ValueError, "negative CPU number");
  6968. goto error;
  6969. }
  6970. if (cpu > INT_MAX - 1) {
  6971. PyErr_SetString(PyExc_OverflowError, "CPU number too large");
  6972. goto error;
  6973. }
  6974. if (cpu >= ncpus) {
  6975. /* Grow CPU mask to fit the CPU number */
  6976. int newncpus = ncpus;
  6977. cpu_set_t *newmask;
  6978. size_t newsetsize;
  6979. while (newncpus <= cpu) {
  6980. if (newncpus > INT_MAX / 2)
  6981. newncpus = cpu + 1;
  6982. else
  6983. newncpus = newncpus * 2;
  6984. }
  6985. newmask = CPU_ALLOC(newncpus);
  6986. if (newmask == NULL) {
  6987. PyErr_NoMemory();
  6988. goto error;
  6989. }
  6990. newsetsize = CPU_ALLOC_SIZE(newncpus);
  6991. CPU_ZERO_S(newsetsize, newmask);
  6992. memcpy(newmask, cpu_set, setsize);
  6993. CPU_FREE(cpu_set);
  6994. setsize = newsetsize;
  6995. cpu_set = newmask;
  6996. ncpus = newncpus;
  6997. }
  6998. CPU_SET_S(cpu, setsize, cpu_set);
  6999. }
  7000. if (PyErr_Occurred()) {
  7001. goto error;
  7002. }
  7003. Py_CLEAR(iterator);
  7004. if (sched_setaffinity(pid, setsize, cpu_set)) {
  7005. posix_error();
  7006. goto error;
  7007. }
  7008. CPU_FREE(cpu_set);
  7009. Py_RETURN_NONE;
  7010. error:
  7011. if (cpu_set)
  7012. CPU_FREE(cpu_set);
  7013. Py_XDECREF(iterator);
  7014. return NULL;
  7015. }
  7016. /*[clinic input]
  7017. os.sched_getaffinity
  7018. pid: pid_t
  7019. /
  7020. Return the affinity of the process identified by pid (or the current process if zero).
  7021. The affinity is returned as a set of CPU identifiers.
  7022. [clinic start generated code]*/
  7023. static PyObject *
  7024. os_sched_getaffinity_impl(PyObject *module, pid_t pid)
  7025. /*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
  7026. {
  7027. int cpu, ncpus, count;
  7028. size_t setsize;
  7029. cpu_set_t *mask = NULL;
  7030. PyObject *res = NULL;
  7031. ncpus = NCPUS_START;
  7032. while (1) {
  7033. setsize = CPU_ALLOC_SIZE(ncpus);
  7034. mask = CPU_ALLOC(ncpus);
  7035. if (mask == NULL)
  7036. return PyErr_NoMemory();
  7037. if (sched_getaffinity(pid, setsize, mask) == 0)
  7038. break;
  7039. CPU_FREE(mask);
  7040. if (errno != EINVAL)
  7041. return posix_error();
  7042. if (ncpus > INT_MAX / 2) {
  7043. PyErr_SetString(PyExc_OverflowError, "could not allocate "
  7044. "a large enough CPU set");
  7045. return NULL;
  7046. }
  7047. ncpus = ncpus * 2;
  7048. }
  7049. res = PySet_New(NULL);
  7050. if (res == NULL)
  7051. goto error;
  7052. for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
  7053. if (CPU_ISSET_S(cpu, setsize, mask)) {
  7054. PyObject *cpu_num = PyLong_FromLong(cpu);
  7055. --count;
  7056. if (cpu_num == NULL)
  7057. goto error;
  7058. if (PySet_Add(res, cpu_num)) {
  7059. Py_DECREF(cpu_num);
  7060. goto error;
  7061. }
  7062. Py_DECREF(cpu_num);
  7063. }
  7064. }
  7065. CPU_FREE(mask);
  7066. return res;
  7067. error:
  7068. if (mask)
  7069. CPU_FREE(mask);
  7070. Py_XDECREF(res);
  7071. return NULL;
  7072. }
  7073. #endif /* HAVE_SCHED_SETAFFINITY */
  7074. #endif /* HAVE_SCHED_H */
  7075. /* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
  7076. #if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
  7077. # define DEV_PTY_FILE "/dev/ptc"
  7078. # define HAVE_DEV_PTMX
  7079. #else
  7080. # define DEV_PTY_FILE "/dev/ptmx"
  7081. #endif
  7082. #if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX)
  7083. #ifdef HAVE_PTY_H
  7084. #include <pty.h>
  7085. #ifdef HAVE_UTMP_H
  7086. #include <utmp.h>
  7087. #endif /* HAVE_UTMP_H */
  7088. #elif defined(HAVE_LIBUTIL_H)
  7089. #include <libutil.h>
  7090. #elif defined(HAVE_UTIL_H)
  7091. #include <util.h>
  7092. #endif /* HAVE_PTY_H */
  7093. #ifdef HAVE_STROPTS_H
  7094. #include <stropts.h>
  7095. #else
  7096. #define __SID ('S' << 8)
  7097. #define I_PUSH (__SID | 2)
  7098. #endif
  7099. #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX) */
  7100. #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
  7101. /*[clinic input]
  7102. os.openpty
  7103. Open a pseudo-terminal.
  7104. Return a tuple of (master_fd, slave_fd) containing open file descriptors
  7105. for both the master and slave ends.
  7106. [clinic start generated code]*/
  7107. static PyObject *
  7108. os_openpty_impl(PyObject *module)
  7109. /*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
  7110. {
  7111. int master_fd = -1, slave_fd = -1;
  7112. #ifndef HAVE_OPENPTY
  7113. char * slave_name;
  7114. #endif
  7115. #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
  7116. PyOS_sighandler_t sig_saved;
  7117. #if defined(__sun) && defined(__SVR4)
  7118. extern char *ptsname(int fildes);
  7119. #endif
  7120. #endif
  7121. #ifdef HAVE_OPENPTY
  7122. if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
  7123. goto posix_error;
  7124. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7125. goto error;
  7126. if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
  7127. goto error;
  7128. #elif defined(HAVE__GETPTY)
  7129. slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
  7130. if (slave_name == NULL)
  7131. goto posix_error;
  7132. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7133. goto error;
  7134. slave_fd = _Py_open(slave_name, O_RDWR);
  7135. if (slave_fd < 0)
  7136. goto error;
  7137. #else
  7138. master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
  7139. if (master_fd < 0)
  7140. goto posix_error;
  7141. sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
  7142. /* change permission of slave */
  7143. if (grantpt(master_fd) < 0) {
  7144. int saved_errno = errno;
  7145. PyOS_setsig(SIGCHLD, sig_saved);
  7146. errno = saved_errno;
  7147. goto posix_error;
  7148. }
  7149. /* unlock slave */
  7150. if (unlockpt(master_fd) < 0) {
  7151. int saved_errno = errno;
  7152. PyOS_setsig(SIGCHLD, sig_saved);
  7153. errno = saved_errno;
  7154. goto posix_error;
  7155. }
  7156. PyOS_setsig(SIGCHLD, sig_saved);
  7157. slave_name = ptsname(master_fd); /* get name of slave */
  7158. if (slave_name == NULL)
  7159. goto posix_error;
  7160. slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
  7161. if (slave_fd == -1)
  7162. goto error;
  7163. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7164. goto posix_error;
  7165. #if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
  7166. ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
  7167. ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
  7168. #ifndef __hpux
  7169. ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
  7170. #endif /* __hpux */
  7171. #endif /* HAVE_CYGWIN */
  7172. #endif /* HAVE_OPENPTY */
  7173. return Py_BuildValue("(ii)", master_fd, slave_fd);
  7174. posix_error:
  7175. posix_error();
  7176. error:
  7177. if (master_fd != -1)
  7178. close(master_fd);
  7179. if (slave_fd != -1)
  7180. close(slave_fd);
  7181. return NULL;
  7182. }
  7183. #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
  7184. #if defined(HAVE_SETSID) && defined(TIOCSCTTY)
  7185. #define HAVE_FALLBACK_LOGIN_TTY 1
  7186. #endif /* defined(HAVE_SETSID) && defined(TIOCSCTTY) */
  7187. #if defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY)
  7188. /*[clinic input]
  7189. os.login_tty
  7190. fd: fildes
  7191. /
  7192. Prepare the tty of which fd is a file descriptor for a new login session.
  7193. Make the calling process a session leader; make the tty the
  7194. controlling tty, the stdin, the stdout, and the stderr of the
  7195. calling process; close fd.
  7196. [clinic start generated code]*/
  7197. static PyObject *
  7198. os_login_tty_impl(PyObject *module, int fd)
  7199. /*[clinic end generated code: output=495a79911b4cc1bc input=5f298565099903a2]*/
  7200. {
  7201. #ifdef HAVE_LOGIN_TTY
  7202. if (login_tty(fd) == -1) {
  7203. return posix_error();
  7204. }
  7205. #else /* defined(HAVE_FALLBACK_LOGIN_TTY) */
  7206. /* Establish a new session. */
  7207. if (setsid() == -1) {
  7208. return posix_error();
  7209. }
  7210. /* The tty becomes the controlling terminal. */
  7211. if (ioctl(fd, TIOCSCTTY, (char *)NULL) == -1) {
  7212. return posix_error();
  7213. }
  7214. /* The tty becomes stdin/stdout/stderr */
  7215. if (dup2(fd, 0) == -1 || dup2(fd, 1) == -1 || dup2(fd, 2) == -1) {
  7216. return posix_error();
  7217. }
  7218. if (fd > 2) {
  7219. close(fd);
  7220. }
  7221. #endif /* HAVE_LOGIN_TTY */
  7222. Py_RETURN_NONE;
  7223. }
  7224. #endif /* defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY) */
  7225. #ifdef HAVE_FORKPTY
  7226. /*[clinic input]
  7227. os.forkpty
  7228. Fork a new process with a new pseudo-terminal as controlling tty.
  7229. Returns a tuple of (pid, master_fd).
  7230. Like fork(), return pid of 0 to the child process,
  7231. and pid of child to the parent process.
  7232. To both, return fd of newly opened pseudo-terminal.
  7233. [clinic start generated code]*/
  7234. static PyObject *
  7235. os_forkpty_impl(PyObject *module)
  7236. /*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
  7237. {
  7238. int master_fd = -1;
  7239. pid_t pid;
  7240. PyInterpreterState *interp = _PyInterpreterState_GET();
  7241. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  7242. PyErr_SetString(PyExc_RuntimeError,
  7243. "can't fork at interpreter shutdown");
  7244. return NULL;
  7245. }
  7246. if (!_Py_IsMainInterpreter(interp)) {
  7247. PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
  7248. return NULL;
  7249. }
  7250. if (PySys_Audit("os.forkpty", NULL) < 0) {
  7251. return NULL;
  7252. }
  7253. PyOS_BeforeFork();
  7254. pid = forkpty(&master_fd, NULL, NULL, NULL);
  7255. if (pid == 0) {
  7256. /* child: this clobbers and resets the import lock. */
  7257. PyOS_AfterFork_Child();
  7258. } else {
  7259. warn_about_fork_with_threads("forkpty");
  7260. /* parent: release the import lock. */
  7261. PyOS_AfterFork_Parent();
  7262. }
  7263. if (pid == -1) {
  7264. return posix_error();
  7265. }
  7266. return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
  7267. }
  7268. #endif /* HAVE_FORKPTY */
  7269. #ifdef HAVE_GETEGID
  7270. /*[clinic input]
  7271. os.getegid
  7272. Return the current process's effective group id.
  7273. [clinic start generated code]*/
  7274. static PyObject *
  7275. os_getegid_impl(PyObject *module)
  7276. /*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
  7277. {
  7278. return _PyLong_FromGid(getegid());
  7279. }
  7280. #endif /* HAVE_GETEGID */
  7281. #ifdef HAVE_GETEUID
  7282. /*[clinic input]
  7283. os.geteuid
  7284. Return the current process's effective user id.
  7285. [clinic start generated code]*/
  7286. static PyObject *
  7287. os_geteuid_impl(PyObject *module)
  7288. /*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
  7289. {
  7290. return _PyLong_FromUid(geteuid());
  7291. }
  7292. #endif /* HAVE_GETEUID */
  7293. #ifdef HAVE_GETGID
  7294. /*[clinic input]
  7295. os.getgid
  7296. Return the current process's group id.
  7297. [clinic start generated code]*/
  7298. static PyObject *
  7299. os_getgid_impl(PyObject *module)
  7300. /*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
  7301. {
  7302. return _PyLong_FromGid(getgid());
  7303. }
  7304. #endif /* HAVE_GETGID */
  7305. #if defined(HAVE_GETPID)
  7306. /*[clinic input]
  7307. os.getpid
  7308. Return the current process id.
  7309. [clinic start generated code]*/
  7310. static PyObject *
  7311. os_getpid_impl(PyObject *module)
  7312. /*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
  7313. {
  7314. #if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  7315. return PyLong_FromPid(getpid());
  7316. #else
  7317. return PyLong_FromUnsignedLong(GetCurrentProcessId());
  7318. #endif
  7319. }
  7320. #endif /* defined(HAVE_GETPID) */
  7321. #ifdef NGROUPS_MAX
  7322. #define MAX_GROUPS NGROUPS_MAX
  7323. #else
  7324. /* defined to be 16 on Solaris7, so this should be a small number */
  7325. #define MAX_GROUPS 64
  7326. #endif
  7327. #ifdef HAVE_GETGROUPLIST
  7328. #ifdef __APPLE__
  7329. /*[clinic input]
  7330. os.getgrouplist
  7331. user: str
  7332. username to lookup
  7333. group as basegid: int
  7334. base group id of the user
  7335. /
  7336. Returns a list of groups to which a user belongs.
  7337. [clinic start generated code]*/
  7338. static PyObject *
  7339. os_getgrouplist_impl(PyObject *module, const char *user, int basegid)
  7340. /*[clinic end generated code: output=6e734697b8c26de0 input=f8d870374b09a490]*/
  7341. #else
  7342. /*[clinic input]
  7343. os.getgrouplist
  7344. user: str
  7345. username to lookup
  7346. group as basegid: gid_t
  7347. base group id of the user
  7348. /
  7349. Returns a list of groups to which a user belongs.
  7350. [clinic start generated code]*/
  7351. static PyObject *
  7352. os_getgrouplist_impl(PyObject *module, const char *user, gid_t basegid)
  7353. /*[clinic end generated code: output=0ebd7fb70115575b input=cc61d5c20b08958d]*/
  7354. #endif
  7355. {
  7356. int i, ngroups;
  7357. PyObject *list;
  7358. #ifdef __APPLE__
  7359. int *groups;
  7360. #else
  7361. gid_t *groups;
  7362. #endif
  7363. /*
  7364. * NGROUPS_MAX is defined by POSIX.1 as the maximum
  7365. * number of supplimental groups a users can belong to.
  7366. * We have to increment it by one because
  7367. * getgrouplist() returns both the supplemental groups
  7368. * and the primary group, i.e. all of the groups the
  7369. * user belongs to.
  7370. */
  7371. ngroups = 1 + MAX_GROUPS;
  7372. while (1) {
  7373. #ifdef __APPLE__
  7374. groups = PyMem_New(int, ngroups);
  7375. #else
  7376. groups = PyMem_New(gid_t, ngroups);
  7377. #endif
  7378. if (groups == NULL) {
  7379. return PyErr_NoMemory();
  7380. }
  7381. int old_ngroups = ngroups;
  7382. if (getgrouplist(user, basegid, groups, &ngroups) != -1) {
  7383. /* Success */
  7384. break;
  7385. }
  7386. /* getgrouplist() fails if the group list is too small */
  7387. PyMem_Free(groups);
  7388. if (ngroups > old_ngroups) {
  7389. /* If the group list is too small, the glibc implementation of
  7390. getgrouplist() sets ngroups to the total number of groups and
  7391. returns -1. */
  7392. }
  7393. else {
  7394. /* Double the group list size */
  7395. if (ngroups > INT_MAX / 2) {
  7396. return PyErr_NoMemory();
  7397. }
  7398. ngroups *= 2;
  7399. }
  7400. /* Retry getgrouplist() with a larger group list */
  7401. }
  7402. #ifdef _Py_MEMORY_SANITIZER
  7403. /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
  7404. __msan_unpoison(&ngroups, sizeof(ngroups));
  7405. __msan_unpoison(groups, ngroups*sizeof(*groups));
  7406. #endif
  7407. list = PyList_New(ngroups);
  7408. if (list == NULL) {
  7409. PyMem_Free(groups);
  7410. return NULL;
  7411. }
  7412. for (i = 0; i < ngroups; i++) {
  7413. #ifdef __APPLE__
  7414. PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
  7415. #else
  7416. PyObject *o = _PyLong_FromGid(groups[i]);
  7417. #endif
  7418. if (o == NULL) {
  7419. Py_DECREF(list);
  7420. PyMem_Free(groups);
  7421. return NULL;
  7422. }
  7423. PyList_SET_ITEM(list, i, o);
  7424. }
  7425. PyMem_Free(groups);
  7426. return list;
  7427. }
  7428. #endif /* HAVE_GETGROUPLIST */
  7429. #ifdef HAVE_GETGROUPS
  7430. /*[clinic input]
  7431. os.getgroups
  7432. Return list of supplemental group IDs for the process.
  7433. [clinic start generated code]*/
  7434. static PyObject *
  7435. os_getgroups_impl(PyObject *module)
  7436. /*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
  7437. {
  7438. // Call getgroups with length 0 to get the actual number of groups
  7439. int n = getgroups(0, NULL);
  7440. if (n < 0) {
  7441. return posix_error();
  7442. }
  7443. if (n == 0) {
  7444. return PyList_New(0);
  7445. }
  7446. gid_t *grouplist = PyMem_New(gid_t, n);
  7447. if (grouplist == NULL) {
  7448. return PyErr_NoMemory();
  7449. }
  7450. n = getgroups(n, grouplist);
  7451. if (n == -1) {
  7452. posix_error();
  7453. PyMem_Free(grouplist);
  7454. return NULL;
  7455. }
  7456. PyObject *result = PyList_New(n);
  7457. if (result == NULL) {
  7458. goto error;
  7459. }
  7460. for (int i = 0; i < n; ++i) {
  7461. PyObject *group = _PyLong_FromGid(grouplist[i]);
  7462. if (group == NULL) {
  7463. goto error;
  7464. }
  7465. PyList_SET_ITEM(result, i, group);
  7466. }
  7467. PyMem_Free(grouplist);
  7468. return result;
  7469. error:
  7470. PyMem_Free(grouplist);
  7471. Py_XDECREF(result);
  7472. return NULL;
  7473. }
  7474. #endif /* HAVE_GETGROUPS */
  7475. #ifdef HAVE_INITGROUPS
  7476. #ifdef __APPLE__
  7477. /*[clinic input]
  7478. os.initgroups
  7479. username as oname: FSConverter
  7480. gid: int
  7481. /
  7482. Initialize the group access list.
  7483. Call the system initgroups() to initialize the group access list with all of
  7484. the groups of which the specified username is a member, plus the specified
  7485. group id.
  7486. [clinic start generated code]*/
  7487. static PyObject *
  7488. os_initgroups_impl(PyObject *module, PyObject *oname, int gid)
  7489. /*[clinic end generated code: output=7f074d30a425fd3a input=df3d54331b0af204]*/
  7490. #else
  7491. /*[clinic input]
  7492. os.initgroups
  7493. username as oname: FSConverter
  7494. gid: gid_t
  7495. /
  7496. Initialize the group access list.
  7497. Call the system initgroups() to initialize the group access list with all of
  7498. the groups of which the specified username is a member, plus the specified
  7499. group id.
  7500. [clinic start generated code]*/
  7501. static PyObject *
  7502. os_initgroups_impl(PyObject *module, PyObject *oname, gid_t gid)
  7503. /*[clinic end generated code: output=59341244521a9e3f input=0cb91bdc59a4c564]*/
  7504. #endif
  7505. {
  7506. const char *username = PyBytes_AS_STRING(oname);
  7507. if (initgroups(username, gid) == -1)
  7508. return PyErr_SetFromErrno(PyExc_OSError);
  7509. Py_RETURN_NONE;
  7510. }
  7511. #endif /* HAVE_INITGROUPS */
  7512. #ifdef HAVE_GETPGID
  7513. /*[clinic input]
  7514. os.getpgid
  7515. pid: pid_t
  7516. Call the system call getpgid(), and return the result.
  7517. [clinic start generated code]*/
  7518. static PyObject *
  7519. os_getpgid_impl(PyObject *module, pid_t pid)
  7520. /*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
  7521. {
  7522. pid_t pgid = getpgid(pid);
  7523. if (pgid < 0)
  7524. return posix_error();
  7525. return PyLong_FromPid(pgid);
  7526. }
  7527. #endif /* HAVE_GETPGID */
  7528. #ifdef HAVE_GETPGRP
  7529. /*[clinic input]
  7530. os.getpgrp
  7531. Return the current process group id.
  7532. [clinic start generated code]*/
  7533. static PyObject *
  7534. os_getpgrp_impl(PyObject *module)
  7535. /*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
  7536. {
  7537. #ifdef GETPGRP_HAVE_ARG
  7538. return PyLong_FromPid(getpgrp(0));
  7539. #else /* GETPGRP_HAVE_ARG */
  7540. return PyLong_FromPid(getpgrp());
  7541. #endif /* GETPGRP_HAVE_ARG */
  7542. }
  7543. #endif /* HAVE_GETPGRP */
  7544. #ifdef HAVE_SETPGRP
  7545. /*[clinic input]
  7546. os.setpgrp
  7547. Make the current process the leader of its process group.
  7548. [clinic start generated code]*/
  7549. static PyObject *
  7550. os_setpgrp_impl(PyObject *module)
  7551. /*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
  7552. {
  7553. #ifdef SETPGRP_HAVE_ARG
  7554. if (setpgrp(0, 0) < 0)
  7555. #else /* SETPGRP_HAVE_ARG */
  7556. if (setpgrp() < 0)
  7557. #endif /* SETPGRP_HAVE_ARG */
  7558. return posix_error();
  7559. Py_RETURN_NONE;
  7560. }
  7561. #endif /* HAVE_SETPGRP */
  7562. #ifdef HAVE_GETPPID
  7563. #ifdef MS_WINDOWS
  7564. #include <processsnapshot.h>
  7565. static PyObject*
  7566. win32_getppid(void)
  7567. {
  7568. DWORD error;
  7569. PyObject* result = NULL;
  7570. HANDLE process = GetCurrentProcess();
  7571. HPSS snapshot = NULL;
  7572. error = PssCaptureSnapshot(process, PSS_CAPTURE_NONE, 0, &snapshot);
  7573. if (error != ERROR_SUCCESS) {
  7574. return PyErr_SetFromWindowsErr(error);
  7575. }
  7576. PSS_PROCESS_INFORMATION info;
  7577. error = PssQuerySnapshot(snapshot, PSS_QUERY_PROCESS_INFORMATION, &info,
  7578. sizeof(info));
  7579. if (error == ERROR_SUCCESS) {
  7580. result = PyLong_FromUnsignedLong(info.ParentProcessId);
  7581. }
  7582. else {
  7583. result = PyErr_SetFromWindowsErr(error);
  7584. }
  7585. PssFreeSnapshot(process, snapshot);
  7586. return result;
  7587. }
  7588. #endif /*MS_WINDOWS*/
  7589. /*[clinic input]
  7590. os.getppid
  7591. Return the parent's process id.
  7592. If the parent process has already exited, Windows machines will still
  7593. return its id; others systems will return the id of the 'init' process (1).
  7594. [clinic start generated code]*/
  7595. static PyObject *
  7596. os_getppid_impl(PyObject *module)
  7597. /*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
  7598. {
  7599. #ifdef MS_WINDOWS
  7600. return win32_getppid();
  7601. #else
  7602. return PyLong_FromPid(getppid());
  7603. #endif
  7604. }
  7605. #endif /* HAVE_GETPPID */
  7606. #ifdef HAVE_GETLOGIN
  7607. /*[clinic input]
  7608. os.getlogin
  7609. Return the actual login name.
  7610. [clinic start generated code]*/
  7611. static PyObject *
  7612. os_getlogin_impl(PyObject *module)
  7613. /*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
  7614. {
  7615. PyObject *result = NULL;
  7616. #ifdef MS_WINDOWS
  7617. wchar_t user_name[UNLEN + 1];
  7618. DWORD num_chars = Py_ARRAY_LENGTH(user_name);
  7619. if (GetUserNameW(user_name, &num_chars)) {
  7620. /* num_chars is the number of unicode chars plus null terminator */
  7621. result = PyUnicode_FromWideChar(user_name, num_chars - 1);
  7622. }
  7623. else
  7624. result = PyErr_SetFromWindowsErr(GetLastError());
  7625. #else
  7626. char *name;
  7627. int old_errno = errno;
  7628. errno = 0;
  7629. name = getlogin();
  7630. if (name == NULL) {
  7631. if (errno)
  7632. posix_error();
  7633. else
  7634. PyErr_SetString(PyExc_OSError, "unable to determine login name");
  7635. }
  7636. else
  7637. result = PyUnicode_DecodeFSDefault(name);
  7638. errno = old_errno;
  7639. #endif
  7640. return result;
  7641. }
  7642. #endif /* HAVE_GETLOGIN */
  7643. #ifdef HAVE_GETUID
  7644. /*[clinic input]
  7645. os.getuid
  7646. Return the current process's user id.
  7647. [clinic start generated code]*/
  7648. static PyObject *
  7649. os_getuid_impl(PyObject *module)
  7650. /*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
  7651. {
  7652. return _PyLong_FromUid(getuid());
  7653. }
  7654. #endif /* HAVE_GETUID */
  7655. #ifdef MS_WINDOWS
  7656. #define HAVE_KILL
  7657. #endif /* MS_WINDOWS */
  7658. #ifdef HAVE_KILL
  7659. /*[clinic input]
  7660. os.kill
  7661. pid: pid_t
  7662. signal: Py_ssize_t
  7663. /
  7664. Kill a process with a signal.
  7665. [clinic start generated code]*/
  7666. static PyObject *
  7667. os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
  7668. /*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
  7669. {
  7670. if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
  7671. return NULL;
  7672. }
  7673. #ifndef MS_WINDOWS
  7674. if (kill(pid, (int)signal) == -1) {
  7675. return posix_error();
  7676. }
  7677. // Check immediately if the signal was sent to the current process.
  7678. // Don't micro-optimize pid == getpid(), since PyErr_SetString() check
  7679. // is cheap.
  7680. if (PyErr_CheckSignals()) {
  7681. return NULL;
  7682. }
  7683. Py_RETURN_NONE;
  7684. #else /* !MS_WINDOWS */
  7685. DWORD sig = (DWORD)signal;
  7686. #ifdef HAVE_WINDOWS_CONSOLE_IO
  7687. /* Console processes which share a common console can be sent CTRL+C or
  7688. CTRL+BREAK events, provided they handle said events. */
  7689. if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
  7690. if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
  7691. return PyErr_SetFromWindowsErr(0);
  7692. }
  7693. Py_RETURN_NONE;
  7694. }
  7695. #endif /* HAVE_WINDOWS_CONSOLE_IO */
  7696. /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
  7697. attempt to open and terminate the process. */
  7698. HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
  7699. if (handle == NULL) {
  7700. return PyErr_SetFromWindowsErr(0);
  7701. }
  7702. BOOL res = TerminateProcess(handle, sig);
  7703. CloseHandle(handle);
  7704. if (res == 0) {
  7705. return PyErr_SetFromWindowsErr(0);
  7706. }
  7707. Py_RETURN_NONE;
  7708. #endif /* !MS_WINDOWS */
  7709. }
  7710. #endif /* HAVE_KILL */
  7711. #ifdef HAVE_KILLPG
  7712. /*[clinic input]
  7713. os.killpg
  7714. pgid: pid_t
  7715. signal: int
  7716. /
  7717. Kill a process group with a signal.
  7718. [clinic start generated code]*/
  7719. static PyObject *
  7720. os_killpg_impl(PyObject *module, pid_t pgid, int signal)
  7721. /*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
  7722. {
  7723. if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
  7724. return NULL;
  7725. }
  7726. /* XXX some man pages make the `pgid` parameter an int, others
  7727. a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
  7728. take the same type. Moreover, pid_t is always at least as wide as
  7729. int (else compilation of this module fails), which is safe. */
  7730. if (killpg(pgid, signal) == -1)
  7731. return posix_error();
  7732. Py_RETURN_NONE;
  7733. }
  7734. #endif /* HAVE_KILLPG */
  7735. #ifdef HAVE_PLOCK
  7736. #ifdef HAVE_SYS_LOCK_H
  7737. #include <sys/lock.h>
  7738. #endif
  7739. /*[clinic input]
  7740. os.plock
  7741. op: int
  7742. /
  7743. Lock program segments into memory.");
  7744. [clinic start generated code]*/
  7745. static PyObject *
  7746. os_plock_impl(PyObject *module, int op)
  7747. /*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
  7748. {
  7749. if (plock(op) == -1)
  7750. return posix_error();
  7751. Py_RETURN_NONE;
  7752. }
  7753. #endif /* HAVE_PLOCK */
  7754. #ifdef HAVE_SETUID
  7755. /*[clinic input]
  7756. os.setuid
  7757. uid: uid_t
  7758. /
  7759. Set the current process's user id.
  7760. [clinic start generated code]*/
  7761. static PyObject *
  7762. os_setuid_impl(PyObject *module, uid_t uid)
  7763. /*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
  7764. {
  7765. if (setuid(uid) < 0)
  7766. return posix_error();
  7767. Py_RETURN_NONE;
  7768. }
  7769. #endif /* HAVE_SETUID */
  7770. #ifdef HAVE_SETEUID
  7771. /*[clinic input]
  7772. os.seteuid
  7773. euid: uid_t
  7774. /
  7775. Set the current process's effective user id.
  7776. [clinic start generated code]*/
  7777. static PyObject *
  7778. os_seteuid_impl(PyObject *module, uid_t euid)
  7779. /*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
  7780. {
  7781. if (seteuid(euid) < 0)
  7782. return posix_error();
  7783. Py_RETURN_NONE;
  7784. }
  7785. #endif /* HAVE_SETEUID */
  7786. #ifdef HAVE_SETEGID
  7787. /*[clinic input]
  7788. os.setegid
  7789. egid: gid_t
  7790. /
  7791. Set the current process's effective group id.
  7792. [clinic start generated code]*/
  7793. static PyObject *
  7794. os_setegid_impl(PyObject *module, gid_t egid)
  7795. /*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
  7796. {
  7797. if (setegid(egid) < 0)
  7798. return posix_error();
  7799. Py_RETURN_NONE;
  7800. }
  7801. #endif /* HAVE_SETEGID */
  7802. #ifdef HAVE_SETREUID
  7803. /*[clinic input]
  7804. os.setreuid
  7805. ruid: uid_t
  7806. euid: uid_t
  7807. /
  7808. Set the current process's real and effective user ids.
  7809. [clinic start generated code]*/
  7810. static PyObject *
  7811. os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
  7812. /*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
  7813. {
  7814. if (setreuid(ruid, euid) < 0) {
  7815. return posix_error();
  7816. } else {
  7817. Py_RETURN_NONE;
  7818. }
  7819. }
  7820. #endif /* HAVE_SETREUID */
  7821. #ifdef HAVE_SETREGID
  7822. /*[clinic input]
  7823. os.setregid
  7824. rgid: gid_t
  7825. egid: gid_t
  7826. /
  7827. Set the current process's real and effective group ids.
  7828. [clinic start generated code]*/
  7829. static PyObject *
  7830. os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
  7831. /*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
  7832. {
  7833. if (setregid(rgid, egid) < 0)
  7834. return posix_error();
  7835. Py_RETURN_NONE;
  7836. }
  7837. #endif /* HAVE_SETREGID */
  7838. #ifdef HAVE_SETGID
  7839. /*[clinic input]
  7840. os.setgid
  7841. gid: gid_t
  7842. /
  7843. Set the current process's group id.
  7844. [clinic start generated code]*/
  7845. static PyObject *
  7846. os_setgid_impl(PyObject *module, gid_t gid)
  7847. /*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
  7848. {
  7849. if (setgid(gid) < 0)
  7850. return posix_error();
  7851. Py_RETURN_NONE;
  7852. }
  7853. #endif /* HAVE_SETGID */
  7854. #ifdef HAVE_SETGROUPS
  7855. /*[clinic input]
  7856. os.setgroups
  7857. groups: object
  7858. /
  7859. Set the groups of the current process to list.
  7860. [clinic start generated code]*/
  7861. static PyObject *
  7862. os_setgroups(PyObject *module, PyObject *groups)
  7863. /*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
  7864. {
  7865. if (!PySequence_Check(groups)) {
  7866. PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
  7867. return NULL;
  7868. }
  7869. Py_ssize_t len = PySequence_Size(groups);
  7870. if (len < 0) {
  7871. return NULL;
  7872. }
  7873. if (len > MAX_GROUPS) {
  7874. PyErr_SetString(PyExc_ValueError, "too many groups");
  7875. return NULL;
  7876. }
  7877. gid_t *grouplist = PyMem_New(gid_t, len);
  7878. for (Py_ssize_t i = 0; i < len; i++) {
  7879. PyObject *elem;
  7880. elem = PySequence_GetItem(groups, i);
  7881. if (!elem) {
  7882. PyMem_Free(grouplist);
  7883. return NULL;
  7884. }
  7885. if (!PyLong_Check(elem)) {
  7886. PyErr_SetString(PyExc_TypeError,
  7887. "groups must be integers");
  7888. Py_DECREF(elem);
  7889. PyMem_Free(grouplist);
  7890. return NULL;
  7891. } else {
  7892. if (!_Py_Gid_Converter(elem, &grouplist[i])) {
  7893. Py_DECREF(elem);
  7894. PyMem_Free(grouplist);
  7895. return NULL;
  7896. }
  7897. }
  7898. Py_DECREF(elem);
  7899. }
  7900. if (setgroups(len, grouplist) < 0) {
  7901. posix_error();
  7902. PyMem_Free(grouplist);
  7903. return NULL;
  7904. }
  7905. PyMem_Free(grouplist);
  7906. Py_RETURN_NONE;
  7907. }
  7908. #endif /* HAVE_SETGROUPS */
  7909. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  7910. static PyObject *
  7911. wait_helper(PyObject *module, pid_t pid, int status, struct rusage *ru)
  7912. {
  7913. PyObject *result;
  7914. PyObject *struct_rusage;
  7915. if (pid == -1)
  7916. return posix_error();
  7917. // If wait succeeded but no child was ready to report status, ru will not
  7918. // have been populated.
  7919. if (pid == 0) {
  7920. memset(ru, 0, sizeof(*ru));
  7921. }
  7922. struct_rusage = _PyImport_GetModuleAttrString("resource", "struct_rusage");
  7923. if (struct_rusage == NULL)
  7924. return NULL;
  7925. /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
  7926. result = PyStructSequence_New((PyTypeObject*) struct_rusage);
  7927. Py_DECREF(struct_rusage);
  7928. if (!result)
  7929. return NULL;
  7930. int pos = 0;
  7931. #ifndef doubletime
  7932. #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
  7933. #endif
  7934. #define SET_RESULT(CALL) \
  7935. do { \
  7936. PyObject *item = (CALL); \
  7937. if (item == NULL) { \
  7938. Py_DECREF(result); \
  7939. return NULL; \
  7940. } \
  7941. PyStructSequence_SET_ITEM(result, pos++, item); \
  7942. } while(0)
  7943. SET_RESULT(PyFloat_FromDouble(doubletime(ru->ru_utime)));
  7944. SET_RESULT(PyFloat_FromDouble(doubletime(ru->ru_stime)));
  7945. SET_RESULT(PyLong_FromLong(ru->ru_maxrss));
  7946. SET_RESULT(PyLong_FromLong(ru->ru_ixrss));
  7947. SET_RESULT(PyLong_FromLong(ru->ru_idrss));
  7948. SET_RESULT(PyLong_FromLong(ru->ru_isrss));
  7949. SET_RESULT(PyLong_FromLong(ru->ru_minflt));
  7950. SET_RESULT(PyLong_FromLong(ru->ru_majflt));
  7951. SET_RESULT(PyLong_FromLong(ru->ru_nswap));
  7952. SET_RESULT(PyLong_FromLong(ru->ru_inblock));
  7953. SET_RESULT(PyLong_FromLong(ru->ru_oublock));
  7954. SET_RESULT(PyLong_FromLong(ru->ru_msgsnd));
  7955. SET_RESULT(PyLong_FromLong(ru->ru_msgrcv));
  7956. SET_RESULT(PyLong_FromLong(ru->ru_nsignals));
  7957. SET_RESULT(PyLong_FromLong(ru->ru_nvcsw));
  7958. SET_RESULT(PyLong_FromLong(ru->ru_nivcsw));
  7959. #undef SET_RESULT
  7960. return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
  7961. }
  7962. #endif /* HAVE_WAIT3 || HAVE_WAIT4 */
  7963. #ifdef HAVE_WAIT3
  7964. /*[clinic input]
  7965. os.wait3
  7966. options: int
  7967. Wait for completion of a child process.
  7968. Returns a tuple of information about the child process:
  7969. (pid, status, rusage)
  7970. [clinic start generated code]*/
  7971. static PyObject *
  7972. os_wait3_impl(PyObject *module, int options)
  7973. /*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
  7974. {
  7975. pid_t pid;
  7976. struct rusage ru;
  7977. int async_err = 0;
  7978. WAIT_TYPE status;
  7979. WAIT_STATUS_INT(status) = 0;
  7980. do {
  7981. Py_BEGIN_ALLOW_THREADS
  7982. pid = wait3(&status, options, &ru);
  7983. Py_END_ALLOW_THREADS
  7984. } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  7985. if (pid < 0)
  7986. return (!async_err) ? posix_error() : NULL;
  7987. return wait_helper(module, pid, WAIT_STATUS_INT(status), &ru);
  7988. }
  7989. #endif /* HAVE_WAIT3 */
  7990. #ifdef HAVE_WAIT4
  7991. /*[clinic input]
  7992. os.wait4
  7993. pid: pid_t
  7994. options: int
  7995. Wait for completion of a specific child process.
  7996. Returns a tuple of information about the child process:
  7997. (pid, status, rusage)
  7998. [clinic start generated code]*/
  7999. static PyObject *
  8000. os_wait4_impl(PyObject *module, pid_t pid, int options)
  8001. /*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
  8002. {
  8003. pid_t res;
  8004. struct rusage ru;
  8005. int async_err = 0;
  8006. WAIT_TYPE status;
  8007. WAIT_STATUS_INT(status) = 0;
  8008. do {
  8009. Py_BEGIN_ALLOW_THREADS
  8010. res = wait4(pid, &status, options, &ru);
  8011. Py_END_ALLOW_THREADS
  8012. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8013. if (res < 0)
  8014. return (!async_err) ? posix_error() : NULL;
  8015. return wait_helper(module, res, WAIT_STATUS_INT(status), &ru);
  8016. }
  8017. #endif /* HAVE_WAIT4 */
  8018. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  8019. /*[clinic input]
  8020. os.waitid
  8021. idtype: idtype_t
  8022. Must be one of be P_PID, P_PGID or P_ALL.
  8023. id: id_t
  8024. The id to wait on.
  8025. options: int
  8026. Constructed from the ORing of one or more of WEXITED, WSTOPPED
  8027. or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
  8028. /
  8029. Returns the result of waiting for a process or processes.
  8030. Returns either waitid_result or None if WNOHANG is specified and there are
  8031. no children in a waitable state.
  8032. [clinic start generated code]*/
  8033. static PyObject *
  8034. os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
  8035. /*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
  8036. {
  8037. PyObject *result;
  8038. int res;
  8039. int async_err = 0;
  8040. siginfo_t si;
  8041. si.si_pid = 0;
  8042. do {
  8043. Py_BEGIN_ALLOW_THREADS
  8044. res = waitid(idtype, id, &si, options);
  8045. Py_END_ALLOW_THREADS
  8046. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8047. if (res < 0)
  8048. return (!async_err) ? posix_error() : NULL;
  8049. if (si.si_pid == 0)
  8050. Py_RETURN_NONE;
  8051. PyObject *WaitidResultType = get_posix_state(module)->WaitidResultType;
  8052. result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
  8053. if (!result)
  8054. return NULL;
  8055. int pos = 0;
  8056. #define SET_RESULT(CALL) \
  8057. do { \
  8058. PyObject *item = (CALL); \
  8059. if (item == NULL) { \
  8060. Py_DECREF(result); \
  8061. return NULL; \
  8062. } \
  8063. PyStructSequence_SET_ITEM(result, pos++, item); \
  8064. } while(0)
  8065. SET_RESULT(PyLong_FromPid(si.si_pid));
  8066. SET_RESULT(_PyLong_FromUid(si.si_uid));
  8067. SET_RESULT(PyLong_FromLong((long)(si.si_signo)));
  8068. SET_RESULT(PyLong_FromLong((long)(si.si_status)));
  8069. SET_RESULT(PyLong_FromLong((long)(si.si_code)));
  8070. #undef SET_RESULT
  8071. return result;
  8072. }
  8073. #endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
  8074. #if defined(HAVE_WAITPID)
  8075. /*[clinic input]
  8076. os.waitpid
  8077. pid: pid_t
  8078. options: int
  8079. /
  8080. Wait for completion of a given child process.
  8081. Returns a tuple of information regarding the child process:
  8082. (pid, status)
  8083. The options argument is ignored on Windows.
  8084. [clinic start generated code]*/
  8085. static PyObject *
  8086. os_waitpid_impl(PyObject *module, pid_t pid, int options)
  8087. /*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
  8088. {
  8089. pid_t res;
  8090. int async_err = 0;
  8091. WAIT_TYPE status;
  8092. WAIT_STATUS_INT(status) = 0;
  8093. do {
  8094. Py_BEGIN_ALLOW_THREADS
  8095. res = waitpid(pid, &status, options);
  8096. Py_END_ALLOW_THREADS
  8097. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8098. if (res < 0)
  8099. return (!async_err) ? posix_error() : NULL;
  8100. return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
  8101. }
  8102. #elif defined(HAVE_CWAIT)
  8103. /* MS C has a variant of waitpid() that's usable for most purposes. */
  8104. /*[clinic input]
  8105. os.waitpid
  8106. pid: intptr_t
  8107. options: int
  8108. /
  8109. Wait for completion of a given process.
  8110. Returns a tuple of information regarding the process:
  8111. (pid, status << 8)
  8112. The options argument is ignored on Windows.
  8113. [clinic start generated code]*/
  8114. static PyObject *
  8115. os_waitpid_impl(PyObject *module, intptr_t pid, int options)
  8116. /*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
  8117. {
  8118. int status;
  8119. intptr_t res;
  8120. int async_err = 0;
  8121. do {
  8122. Py_BEGIN_ALLOW_THREADS
  8123. _Py_BEGIN_SUPPRESS_IPH
  8124. res = _cwait(&status, pid, options);
  8125. _Py_END_SUPPRESS_IPH
  8126. Py_END_ALLOW_THREADS
  8127. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8128. if (res < 0)
  8129. return (!async_err) ? posix_error() : NULL;
  8130. unsigned long long ustatus = (unsigned int)status;
  8131. /* shift the status left a byte so this is more like the POSIX waitpid */
  8132. return Py_BuildValue(_Py_PARSE_INTPTR "K", res, ustatus << 8);
  8133. }
  8134. #endif
  8135. #ifdef HAVE_WAIT
  8136. /*[clinic input]
  8137. os.wait
  8138. Wait for completion of a child process.
  8139. Returns a tuple of information about the child process:
  8140. (pid, status)
  8141. [clinic start generated code]*/
  8142. static PyObject *
  8143. os_wait_impl(PyObject *module)
  8144. /*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
  8145. {
  8146. pid_t pid;
  8147. int async_err = 0;
  8148. WAIT_TYPE status;
  8149. WAIT_STATUS_INT(status) = 0;
  8150. do {
  8151. Py_BEGIN_ALLOW_THREADS
  8152. pid = wait(&status);
  8153. Py_END_ALLOW_THREADS
  8154. } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8155. if (pid < 0)
  8156. return (!async_err) ? posix_error() : NULL;
  8157. return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
  8158. }
  8159. #endif /* HAVE_WAIT */
  8160. #if defined(__linux__) && defined(__NR_pidfd_open)
  8161. /*[clinic input]
  8162. os.pidfd_open
  8163. pid: pid_t
  8164. flags: unsigned_int = 0
  8165. Return a file descriptor referring to the process *pid*.
  8166. The descriptor can be used to perform process management without races and
  8167. signals.
  8168. [clinic start generated code]*/
  8169. static PyObject *
  8170. os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
  8171. /*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
  8172. {
  8173. int fd = syscall(__NR_pidfd_open, pid, flags);
  8174. if (fd < 0) {
  8175. return posix_error();
  8176. }
  8177. return PyLong_FromLong(fd);
  8178. }
  8179. #endif
  8180. #ifdef HAVE_SETNS
  8181. /*[clinic input]
  8182. os.setns
  8183. fd: fildes
  8184. A file descriptor to a namespace.
  8185. nstype: int = 0
  8186. Type of namespace.
  8187. Move the calling thread into different namespaces.
  8188. [clinic start generated code]*/
  8189. static PyObject *
  8190. os_setns_impl(PyObject *module, int fd, int nstype)
  8191. /*[clinic end generated code: output=5dbd055bfb66ecd0 input=42787871226bf3ee]*/
  8192. {
  8193. int res;
  8194. Py_BEGIN_ALLOW_THREADS
  8195. res = setns(fd, nstype);
  8196. Py_END_ALLOW_THREADS
  8197. if (res != 0) {
  8198. return posix_error();
  8199. }
  8200. Py_RETURN_NONE;
  8201. }
  8202. #endif
  8203. #ifdef HAVE_UNSHARE
  8204. /*[clinic input]
  8205. os.unshare
  8206. flags: int
  8207. Namespaces to be unshared.
  8208. Disassociate parts of a process (or thread) execution context.
  8209. [clinic start generated code]*/
  8210. static PyObject *
  8211. os_unshare_impl(PyObject *module, int flags)
  8212. /*[clinic end generated code: output=1b3177906dd237ee input=9e065db3232b8b1b]*/
  8213. {
  8214. int res;
  8215. Py_BEGIN_ALLOW_THREADS
  8216. res = unshare(flags);
  8217. Py_END_ALLOW_THREADS
  8218. if (res != 0) {
  8219. return posix_error();
  8220. }
  8221. Py_RETURN_NONE;
  8222. }
  8223. #endif
  8224. #if defined(HAVE_READLINK) || defined(MS_WINDOWS)
  8225. /*[clinic input]
  8226. os.readlink
  8227. path: path_t
  8228. *
  8229. dir_fd: dir_fd(requires='readlinkat') = None
  8230. Return a string representing the path to which the symbolic link points.
  8231. If dir_fd is not None, it should be a file descriptor open to a directory,
  8232. and path should be relative; path will then be relative to that directory.
  8233. dir_fd may not be implemented on your platform. If it is unavailable,
  8234. using it will raise a NotImplementedError.
  8235. [clinic start generated code]*/
  8236. static PyObject *
  8237. os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
  8238. /*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
  8239. {
  8240. #if defined(HAVE_READLINK)
  8241. char buffer[MAXPATHLEN+1];
  8242. ssize_t length;
  8243. #ifdef HAVE_READLINKAT
  8244. int readlinkat_unavailable = 0;
  8245. #endif
  8246. Py_BEGIN_ALLOW_THREADS
  8247. #ifdef HAVE_READLINKAT
  8248. if (dir_fd != DEFAULT_DIR_FD) {
  8249. if (HAVE_READLINKAT_RUNTIME) {
  8250. length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
  8251. } else {
  8252. readlinkat_unavailable = 1;
  8253. }
  8254. } else
  8255. #endif
  8256. length = readlink(path->narrow, buffer, MAXPATHLEN);
  8257. Py_END_ALLOW_THREADS
  8258. #ifdef HAVE_READLINKAT
  8259. if (readlinkat_unavailable) {
  8260. argument_unavailable_error(NULL, "dir_fd");
  8261. return NULL;
  8262. }
  8263. #endif
  8264. if (length < 0) {
  8265. return path_error(path);
  8266. }
  8267. buffer[length] = '\0';
  8268. if (PyUnicode_Check(path->object))
  8269. return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
  8270. else
  8271. return PyBytes_FromStringAndSize(buffer, length);
  8272. #elif defined(MS_WINDOWS)
  8273. DWORD n_bytes_returned;
  8274. DWORD io_result = 0;
  8275. HANDLE reparse_point_handle;
  8276. char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
  8277. _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
  8278. PyObject *result = NULL;
  8279. /* First get a handle to the reparse point */
  8280. Py_BEGIN_ALLOW_THREADS
  8281. reparse_point_handle = CreateFileW(
  8282. path->wide,
  8283. 0,
  8284. 0,
  8285. 0,
  8286. OPEN_EXISTING,
  8287. FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
  8288. 0);
  8289. if (reparse_point_handle != INVALID_HANDLE_VALUE) {
  8290. /* New call DeviceIoControl to read the reparse point */
  8291. io_result = DeviceIoControl(
  8292. reparse_point_handle,
  8293. FSCTL_GET_REPARSE_POINT,
  8294. 0, 0, /* in buffer */
  8295. target_buffer, sizeof(target_buffer),
  8296. &n_bytes_returned,
  8297. 0 /* we're not using OVERLAPPED_IO */
  8298. );
  8299. CloseHandle(reparse_point_handle);
  8300. }
  8301. Py_END_ALLOW_THREADS
  8302. if (io_result == 0) {
  8303. return path_error(path);
  8304. }
  8305. wchar_t *name = NULL;
  8306. Py_ssize_t nameLen = 0;
  8307. if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
  8308. {
  8309. name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
  8310. rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
  8311. nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
  8312. }
  8313. else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
  8314. {
  8315. name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
  8316. rdb->MountPointReparseBuffer.SubstituteNameOffset);
  8317. nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
  8318. }
  8319. else
  8320. {
  8321. PyErr_SetString(PyExc_ValueError, "not a symbolic link");
  8322. }
  8323. if (name) {
  8324. if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
  8325. /* Our buffer is mutable, so this is okay */
  8326. name[1] = L'\\';
  8327. }
  8328. result = PyUnicode_FromWideChar(name, nameLen);
  8329. if (result && PyBytes_Check(path->object)) {
  8330. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  8331. }
  8332. }
  8333. return result;
  8334. #endif
  8335. }
  8336. #endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
  8337. #if defined(MS_WINDOWS)
  8338. /* Remove the last portion of the path - return 0 on success */
  8339. static int
  8340. _dirnameW(WCHAR *path)
  8341. {
  8342. WCHAR *ptr;
  8343. size_t length = wcsnlen_s(path, MAX_PATH);
  8344. if (length == MAX_PATH) {
  8345. return -1;
  8346. }
  8347. /* walk the path from the end until a backslash is encountered */
  8348. for(ptr = path + length; ptr != path; ptr--) {
  8349. if (*ptr == L'\\' || *ptr == L'/') {
  8350. break;
  8351. }
  8352. }
  8353. *ptr = 0;
  8354. return 0;
  8355. }
  8356. #endif
  8357. #ifdef HAVE_SYMLINK
  8358. #if defined(MS_WINDOWS)
  8359. /* Is this path absolute? */
  8360. static int
  8361. _is_absW(const WCHAR *path)
  8362. {
  8363. return path[0] == L'\\' || path[0] == L'/' ||
  8364. (path[0] && path[1] == L':');
  8365. }
  8366. /* join root and rest with a backslash - return 0 on success */
  8367. static int
  8368. _joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
  8369. {
  8370. if (_is_absW(rest)) {
  8371. return wcscpy_s(dest_path, MAX_PATH, rest);
  8372. }
  8373. if (wcscpy_s(dest_path, MAX_PATH, root)) {
  8374. return -1;
  8375. }
  8376. if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
  8377. return -1;
  8378. }
  8379. return wcscat_s(dest_path, MAX_PATH, rest);
  8380. }
  8381. /* Return True if the path at src relative to dest is a directory */
  8382. static int
  8383. _check_dirW(LPCWSTR src, LPCWSTR dest)
  8384. {
  8385. WIN32_FILE_ATTRIBUTE_DATA src_info;
  8386. WCHAR dest_parent[MAX_PATH];
  8387. WCHAR src_resolved[MAX_PATH] = L"";
  8388. /* dest_parent = os.path.dirname(dest) */
  8389. if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
  8390. _dirnameW(dest_parent)) {
  8391. return 0;
  8392. }
  8393. /* src_resolved = os.path.join(dest_parent, src) */
  8394. if (_joinW(src_resolved, dest_parent, src)) {
  8395. return 0;
  8396. }
  8397. return (
  8398. GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
  8399. && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
  8400. );
  8401. }
  8402. #endif
  8403. /*[clinic input]
  8404. os.symlink
  8405. src: path_t
  8406. dst: path_t
  8407. target_is_directory: bool = False
  8408. *
  8409. dir_fd: dir_fd(requires='symlinkat')=None
  8410. # "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
  8411. Create a symbolic link pointing to src named dst.
  8412. target_is_directory is required on Windows if the target is to be
  8413. interpreted as a directory. (On Windows, symlink requires
  8414. Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
  8415. target_is_directory is ignored on non-Windows platforms.
  8416. If dir_fd is not None, it should be a file descriptor open to a directory,
  8417. and path should be relative; path will then be relative to that directory.
  8418. dir_fd may not be implemented on your platform.
  8419. If it is unavailable, using it will raise a NotImplementedError.
  8420. [clinic start generated code]*/
  8421. static PyObject *
  8422. os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
  8423. int target_is_directory, int dir_fd)
  8424. /*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
  8425. {
  8426. #ifdef MS_WINDOWS
  8427. DWORD result;
  8428. DWORD flags = 0;
  8429. /* Assumed true, set to false if detected to not be available. */
  8430. static int windows_has_symlink_unprivileged_flag = TRUE;
  8431. #else
  8432. int result;
  8433. #ifdef HAVE_SYMLINKAT
  8434. int symlinkat_unavailable = 0;
  8435. #endif
  8436. #endif
  8437. if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
  8438. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  8439. return NULL;
  8440. }
  8441. #ifdef MS_WINDOWS
  8442. if (windows_has_symlink_unprivileged_flag) {
  8443. /* Allow non-admin symlinks if system allows it. */
  8444. flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
  8445. }
  8446. Py_BEGIN_ALLOW_THREADS
  8447. _Py_BEGIN_SUPPRESS_IPH
  8448. /* if src is a directory, ensure flags==1 (target_is_directory bit) */
  8449. if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
  8450. flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
  8451. }
  8452. result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
  8453. _Py_END_SUPPRESS_IPH
  8454. Py_END_ALLOW_THREADS
  8455. if (windows_has_symlink_unprivileged_flag && !result &&
  8456. ERROR_INVALID_PARAMETER == GetLastError()) {
  8457. Py_BEGIN_ALLOW_THREADS
  8458. _Py_BEGIN_SUPPRESS_IPH
  8459. /* This error might be caused by
  8460. SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
  8461. Try again, and update windows_has_symlink_unprivileged_flag if we
  8462. are successful this time.
  8463. NOTE: There is a risk of a race condition here if there are other
  8464. conditions than the flag causing ERROR_INVALID_PARAMETER, and
  8465. another process (or thread) changes that condition in between our
  8466. calls to CreateSymbolicLink.
  8467. */
  8468. flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
  8469. result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
  8470. _Py_END_SUPPRESS_IPH
  8471. Py_END_ALLOW_THREADS
  8472. if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
  8473. windows_has_symlink_unprivileged_flag = FALSE;
  8474. }
  8475. }
  8476. if (!result)
  8477. return path_error2(src, dst);
  8478. #else
  8479. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  8480. PyErr_SetString(PyExc_ValueError,
  8481. "symlink: src and dst must be the same type");
  8482. return NULL;
  8483. }
  8484. Py_BEGIN_ALLOW_THREADS
  8485. #ifdef HAVE_SYMLINKAT
  8486. if (dir_fd != DEFAULT_DIR_FD) {
  8487. if (HAVE_SYMLINKAT_RUNTIME) {
  8488. result = symlinkat(src->narrow, dir_fd, dst->narrow);
  8489. } else {
  8490. symlinkat_unavailable = 1;
  8491. }
  8492. } else
  8493. #endif
  8494. result = symlink(src->narrow, dst->narrow);
  8495. Py_END_ALLOW_THREADS
  8496. #ifdef HAVE_SYMLINKAT
  8497. if (symlinkat_unavailable) {
  8498. argument_unavailable_error(NULL, "dir_fd");
  8499. return NULL;
  8500. }
  8501. #endif
  8502. if (result)
  8503. return path_error2(src, dst);
  8504. #endif
  8505. Py_RETURN_NONE;
  8506. }
  8507. #endif /* HAVE_SYMLINK */
  8508. static PyStructSequence_Field times_result_fields[] = {
  8509. {"user", "user time"},
  8510. {"system", "system time"},
  8511. {"children_user", "user time of children"},
  8512. {"children_system", "system time of children"},
  8513. {"elapsed", "elapsed time since an arbitrary point in the past"},
  8514. {NULL}
  8515. };
  8516. PyDoc_STRVAR(times_result__doc__,
  8517. "times_result: Result from os.times().\n\n\
  8518. This object may be accessed either as a tuple of\n\
  8519. (user, system, children_user, children_system, elapsed),\n\
  8520. or via the attributes user, system, children_user, children_system,\n\
  8521. and elapsed.\n\
  8522. \n\
  8523. See os.times for more information.");
  8524. static PyStructSequence_Desc times_result_desc = {
  8525. "times_result", /* name */
  8526. times_result__doc__, /* doc */
  8527. times_result_fields,
  8528. 5
  8529. };
  8530. #ifdef MS_WINDOWS
  8531. #define HAVE_TIMES /* mandatory, for the method table */
  8532. #endif
  8533. #ifdef HAVE_TIMES
  8534. static PyObject *
  8535. build_times_result(PyObject *module, double user, double system,
  8536. double children_user, double children_system,
  8537. double elapsed)
  8538. {
  8539. PyObject *TimesResultType = get_posix_state(module)->TimesResultType;
  8540. PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
  8541. if (value == NULL)
  8542. return NULL;
  8543. #define SET(i, field) \
  8544. { \
  8545. PyObject *o = PyFloat_FromDouble(field); \
  8546. if (!o) { \
  8547. Py_DECREF(value); \
  8548. return NULL; \
  8549. } \
  8550. PyStructSequence_SET_ITEM(value, i, o); \
  8551. } \
  8552. SET(0, user);
  8553. SET(1, system);
  8554. SET(2, children_user);
  8555. SET(3, children_system);
  8556. SET(4, elapsed);
  8557. #undef SET
  8558. return value;
  8559. }
  8560. /*[clinic input]
  8561. os.times
  8562. Return a collection containing process timing information.
  8563. The object returned behaves like a named tuple with these fields:
  8564. (utime, stime, cutime, cstime, elapsed_time)
  8565. All fields are floating-point numbers.
  8566. [clinic start generated code]*/
  8567. static PyObject *
  8568. os_times_impl(PyObject *module)
  8569. /*[clinic end generated code: output=35f640503557d32a input=8dbfe33a2dcc3df3]*/
  8570. #ifdef MS_WINDOWS
  8571. {
  8572. FILETIME create, exit, kernel, user;
  8573. HANDLE hProc;
  8574. hProc = GetCurrentProcess();
  8575. GetProcessTimes(hProc, &create, &exit, &kernel, &user);
  8576. /* The fields of a FILETIME structure are the hi and lo part
  8577. of a 64-bit value expressed in 100 nanosecond units.
  8578. 1e7 is one second in such units; 1e-7 the inverse.
  8579. 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
  8580. */
  8581. return build_times_result(module,
  8582. (double)(user.dwHighDateTime*429.4967296 +
  8583. user.dwLowDateTime*1e-7),
  8584. (double)(kernel.dwHighDateTime*429.4967296 +
  8585. kernel.dwLowDateTime*1e-7),
  8586. (double)0,
  8587. (double)0,
  8588. (double)0);
  8589. }
  8590. #else /* MS_WINDOWS */
  8591. {
  8592. struct tms t;
  8593. clock_t c;
  8594. errno = 0;
  8595. c = times(&t);
  8596. if (c == (clock_t) -1) {
  8597. return posix_error();
  8598. }
  8599. assert(_PyRuntime.time.ticks_per_second_initialized);
  8600. #define ticks_per_second _PyRuntime.time.ticks_per_second
  8601. return build_times_result(module,
  8602. (double)t.tms_utime / ticks_per_second,
  8603. (double)t.tms_stime / ticks_per_second,
  8604. (double)t.tms_cutime / ticks_per_second,
  8605. (double)t.tms_cstime / ticks_per_second,
  8606. (double)c / ticks_per_second);
  8607. #undef ticks_per_second
  8608. }
  8609. #endif /* MS_WINDOWS */
  8610. #endif /* HAVE_TIMES */
  8611. #ifdef HAVE_GETSID
  8612. /*[clinic input]
  8613. os.getsid
  8614. pid: pid_t
  8615. /
  8616. Call the system call getsid(pid) and return the result.
  8617. [clinic start generated code]*/
  8618. static PyObject *
  8619. os_getsid_impl(PyObject *module, pid_t pid)
  8620. /*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
  8621. {
  8622. int sid;
  8623. sid = getsid(pid);
  8624. if (sid < 0)
  8625. return posix_error();
  8626. return PyLong_FromLong((long)sid);
  8627. }
  8628. #endif /* HAVE_GETSID */
  8629. #ifdef HAVE_SETSID
  8630. /*[clinic input]
  8631. os.setsid
  8632. Call the system call setsid().
  8633. [clinic start generated code]*/
  8634. static PyObject *
  8635. os_setsid_impl(PyObject *module)
  8636. /*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
  8637. {
  8638. if (setsid() < 0)
  8639. return posix_error();
  8640. Py_RETURN_NONE;
  8641. }
  8642. #endif /* HAVE_SETSID */
  8643. #ifdef HAVE_SETPGID
  8644. /*[clinic input]
  8645. os.setpgid
  8646. pid: pid_t
  8647. pgrp: pid_t
  8648. /
  8649. Call the system call setpgid(pid, pgrp).
  8650. [clinic start generated code]*/
  8651. static PyObject *
  8652. os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
  8653. /*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
  8654. {
  8655. if (setpgid(pid, pgrp) < 0)
  8656. return posix_error();
  8657. Py_RETURN_NONE;
  8658. }
  8659. #endif /* HAVE_SETPGID */
  8660. #ifdef HAVE_TCGETPGRP
  8661. /*[clinic input]
  8662. os.tcgetpgrp
  8663. fd: int
  8664. /
  8665. Return the process group associated with the terminal specified by fd.
  8666. [clinic start generated code]*/
  8667. static PyObject *
  8668. os_tcgetpgrp_impl(PyObject *module, int fd)
  8669. /*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
  8670. {
  8671. pid_t pgid = tcgetpgrp(fd);
  8672. if (pgid < 0)
  8673. return posix_error();
  8674. return PyLong_FromPid(pgid);
  8675. }
  8676. #endif /* HAVE_TCGETPGRP */
  8677. #ifdef HAVE_TCSETPGRP
  8678. /*[clinic input]
  8679. os.tcsetpgrp
  8680. fd: int
  8681. pgid: pid_t
  8682. /
  8683. Set the process group associated with the terminal specified by fd.
  8684. [clinic start generated code]*/
  8685. static PyObject *
  8686. os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
  8687. /*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
  8688. {
  8689. if (tcsetpgrp(fd, pgid) < 0)
  8690. return posix_error();
  8691. Py_RETURN_NONE;
  8692. }
  8693. #endif /* HAVE_TCSETPGRP */
  8694. /* Functions acting on file descriptors */
  8695. #ifdef O_CLOEXEC
  8696. extern int _Py_open_cloexec_works;
  8697. #endif
  8698. /*[clinic input]
  8699. os.open -> int
  8700. path: path_t
  8701. flags: int
  8702. mode: int = 0o777
  8703. *
  8704. dir_fd: dir_fd(requires='openat') = None
  8705. # "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
  8706. Open a file for low level IO. Returns a file descriptor (integer).
  8707. If dir_fd is not None, it should be a file descriptor open to a directory,
  8708. and path should be relative; path will then be relative to that directory.
  8709. dir_fd may not be implemented on your platform.
  8710. If it is unavailable, using it will raise a NotImplementedError.
  8711. [clinic start generated code]*/
  8712. static int
  8713. os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
  8714. /*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
  8715. {
  8716. int fd;
  8717. int async_err = 0;
  8718. #ifdef HAVE_OPENAT
  8719. int openat_unavailable = 0;
  8720. #endif
  8721. #ifdef O_CLOEXEC
  8722. int *atomic_flag_works = &_Py_open_cloexec_works;
  8723. #elif !defined(MS_WINDOWS)
  8724. int *atomic_flag_works = NULL;
  8725. #endif
  8726. #ifdef MS_WINDOWS
  8727. flags |= O_NOINHERIT;
  8728. #elif defined(O_CLOEXEC)
  8729. flags |= O_CLOEXEC;
  8730. #endif
  8731. if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
  8732. return -1;
  8733. }
  8734. _Py_BEGIN_SUPPRESS_IPH
  8735. do {
  8736. Py_BEGIN_ALLOW_THREADS
  8737. #ifdef MS_WINDOWS
  8738. fd = _wopen(path->wide, flags, mode);
  8739. #else
  8740. #ifdef HAVE_OPENAT
  8741. if (dir_fd != DEFAULT_DIR_FD) {
  8742. if (HAVE_OPENAT_RUNTIME) {
  8743. fd = openat(dir_fd, path->narrow, flags, mode);
  8744. } else {
  8745. openat_unavailable = 1;
  8746. fd = -1;
  8747. }
  8748. } else
  8749. #endif /* HAVE_OPENAT */
  8750. fd = open(path->narrow, flags, mode);
  8751. #endif /* !MS_WINDOWS */
  8752. Py_END_ALLOW_THREADS
  8753. } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8754. _Py_END_SUPPRESS_IPH
  8755. #ifdef HAVE_OPENAT
  8756. if (openat_unavailable) {
  8757. argument_unavailable_error(NULL, "dir_fd");
  8758. return -1;
  8759. }
  8760. #endif
  8761. if (fd < 0) {
  8762. if (!async_err)
  8763. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
  8764. return -1;
  8765. }
  8766. #ifndef MS_WINDOWS
  8767. if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
  8768. close(fd);
  8769. return -1;
  8770. }
  8771. #endif
  8772. return fd;
  8773. }
  8774. /*[clinic input]
  8775. os.close
  8776. fd: int
  8777. Close a file descriptor.
  8778. [clinic start generated code]*/
  8779. static PyObject *
  8780. os_close_impl(PyObject *module, int fd)
  8781. /*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
  8782. {
  8783. int res;
  8784. /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
  8785. * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
  8786. * for more details.
  8787. */
  8788. Py_BEGIN_ALLOW_THREADS
  8789. _Py_BEGIN_SUPPRESS_IPH
  8790. res = close(fd);
  8791. _Py_END_SUPPRESS_IPH
  8792. Py_END_ALLOW_THREADS
  8793. if (res < 0)
  8794. return posix_error();
  8795. Py_RETURN_NONE;
  8796. }
  8797. /*[clinic input]
  8798. os.closerange
  8799. fd_low: int
  8800. fd_high: int
  8801. /
  8802. Closes all file descriptors in [fd_low, fd_high), ignoring errors.
  8803. [clinic start generated code]*/
  8804. static PyObject *
  8805. os_closerange_impl(PyObject *module, int fd_low, int fd_high)
  8806. /*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
  8807. {
  8808. Py_BEGIN_ALLOW_THREADS
  8809. _Py_closerange(fd_low, fd_high - 1);
  8810. Py_END_ALLOW_THREADS
  8811. Py_RETURN_NONE;
  8812. }
  8813. /*[clinic input]
  8814. os.dup -> int
  8815. fd: int
  8816. /
  8817. Return a duplicate of a file descriptor.
  8818. [clinic start generated code]*/
  8819. static int
  8820. os_dup_impl(PyObject *module, int fd)
  8821. /*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
  8822. {
  8823. return _Py_dup(fd);
  8824. }
  8825. // dup2() is either provided by libc or dup2.c with AC_REPLACE_FUNCS().
  8826. // dup2.c provides working dup2() if and only if F_DUPFD is available.
  8827. #if (defined(HAVE_DUP3) || defined(F_DUPFD) || defined(MS_WINDOWS))
  8828. /*[clinic input]
  8829. os.dup2 -> int
  8830. fd: int
  8831. fd2: int
  8832. inheritable: bool=True
  8833. Duplicate file descriptor.
  8834. [clinic start generated code]*/
  8835. static int
  8836. os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
  8837. /*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
  8838. {
  8839. int res = 0;
  8840. #if defined(HAVE_DUP3) && \
  8841. !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
  8842. /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
  8843. static int dup3_works = -1;
  8844. #endif
  8845. /* dup2() can fail with EINTR if the target FD is already open, because it
  8846. * then has to be closed. See os_close_impl() for why we don't handle EINTR
  8847. * upon close(), and therefore below.
  8848. */
  8849. #ifdef MS_WINDOWS
  8850. Py_BEGIN_ALLOW_THREADS
  8851. _Py_BEGIN_SUPPRESS_IPH
  8852. res = dup2(fd, fd2);
  8853. _Py_END_SUPPRESS_IPH
  8854. Py_END_ALLOW_THREADS
  8855. if (res < 0) {
  8856. posix_error();
  8857. return -1;
  8858. }
  8859. res = fd2; // msvcrt dup2 returns 0 on success.
  8860. /* Character files like console cannot be make non-inheritable */
  8861. if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
  8862. close(fd2);
  8863. return -1;
  8864. }
  8865. #elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
  8866. Py_BEGIN_ALLOW_THREADS
  8867. if (!inheritable)
  8868. res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
  8869. else
  8870. res = dup2(fd, fd2);
  8871. Py_END_ALLOW_THREADS
  8872. if (res < 0) {
  8873. posix_error();
  8874. return -1;
  8875. }
  8876. #else
  8877. #ifdef HAVE_DUP3
  8878. if (!inheritable && dup3_works != 0) {
  8879. Py_BEGIN_ALLOW_THREADS
  8880. res = dup3(fd, fd2, O_CLOEXEC);
  8881. Py_END_ALLOW_THREADS
  8882. if (res < 0) {
  8883. if (dup3_works == -1)
  8884. dup3_works = (errno != ENOSYS);
  8885. if (dup3_works) {
  8886. posix_error();
  8887. return -1;
  8888. }
  8889. }
  8890. }
  8891. if (inheritable || dup3_works == 0)
  8892. {
  8893. #endif
  8894. Py_BEGIN_ALLOW_THREADS
  8895. res = dup2(fd, fd2);
  8896. Py_END_ALLOW_THREADS
  8897. if (res < 0) {
  8898. posix_error();
  8899. return -1;
  8900. }
  8901. if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
  8902. close(fd2);
  8903. return -1;
  8904. }
  8905. #ifdef HAVE_DUP3
  8906. }
  8907. #endif
  8908. #endif
  8909. return res;
  8910. }
  8911. #endif
  8912. #ifdef HAVE_LOCKF
  8913. /*[clinic input]
  8914. os.lockf
  8915. fd: int
  8916. An open file descriptor.
  8917. command: int
  8918. One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
  8919. length: Py_off_t
  8920. The number of bytes to lock, starting at the current position.
  8921. /
  8922. Apply, test or remove a POSIX lock on an open file descriptor.
  8923. [clinic start generated code]*/
  8924. static PyObject *
  8925. os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
  8926. /*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
  8927. {
  8928. int res;
  8929. if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
  8930. return NULL;
  8931. }
  8932. Py_BEGIN_ALLOW_THREADS
  8933. res = lockf(fd, command, length);
  8934. Py_END_ALLOW_THREADS
  8935. if (res < 0)
  8936. return posix_error();
  8937. Py_RETURN_NONE;
  8938. }
  8939. #endif /* HAVE_LOCKF */
  8940. /*[clinic input]
  8941. os.lseek -> Py_off_t
  8942. fd: int
  8943. An open file descriptor, as returned by os.open().
  8944. position: Py_off_t
  8945. Position, interpreted relative to 'whence'.
  8946. whence as how: int
  8947. The relative position to seek from. Valid values are:
  8948. - SEEK_SET: seek from the start of the file.
  8949. - SEEK_CUR: seek from the current file position.
  8950. - SEEK_END: seek from the end of the file.
  8951. /
  8952. Set the position of a file descriptor. Return the new position.
  8953. The return value is the number of bytes relative to the beginning of the file.
  8954. [clinic start generated code]*/
  8955. static Py_off_t
  8956. os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
  8957. /*[clinic end generated code: output=971e1efb6b30bd2f input=f096e754c5367504]*/
  8958. {
  8959. Py_off_t result;
  8960. #ifdef SEEK_SET
  8961. /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
  8962. switch (how) {
  8963. case 0: how = SEEK_SET; break;
  8964. case 1: how = SEEK_CUR; break;
  8965. case 2: how = SEEK_END; break;
  8966. }
  8967. #endif /* SEEK_END */
  8968. Py_BEGIN_ALLOW_THREADS
  8969. _Py_BEGIN_SUPPRESS_IPH
  8970. #ifdef MS_WINDOWS
  8971. result = _lseeki64(fd, position, how);
  8972. #else
  8973. result = lseek(fd, position, how);
  8974. #endif
  8975. _Py_END_SUPPRESS_IPH
  8976. Py_END_ALLOW_THREADS
  8977. if (result < 0)
  8978. posix_error();
  8979. return result;
  8980. }
  8981. /*[clinic input]
  8982. os.read
  8983. fd: int
  8984. length: Py_ssize_t
  8985. /
  8986. Read from a file descriptor. Returns a bytes object.
  8987. [clinic start generated code]*/
  8988. static PyObject *
  8989. os_read_impl(PyObject *module, int fd, Py_ssize_t length)
  8990. /*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
  8991. {
  8992. Py_ssize_t n;
  8993. PyObject *buffer;
  8994. if (length < 0) {
  8995. errno = EINVAL;
  8996. return posix_error();
  8997. }
  8998. length = Py_MIN(length, _PY_READ_MAX);
  8999. buffer = PyBytes_FromStringAndSize((char *)NULL, length);
  9000. if (buffer == NULL)
  9001. return NULL;
  9002. n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
  9003. if (n == -1) {
  9004. Py_DECREF(buffer);
  9005. return NULL;
  9006. }
  9007. if (n != length)
  9008. _PyBytes_Resize(&buffer, n);
  9009. return buffer;
  9010. }
  9011. #if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
  9012. || defined(__APPLE__))) \
  9013. || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
  9014. || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
  9015. static int
  9016. iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
  9017. {
  9018. Py_ssize_t i, j;
  9019. *iov = PyMem_New(struct iovec, cnt);
  9020. if (*iov == NULL) {
  9021. PyErr_NoMemory();
  9022. return -1;
  9023. }
  9024. *buf = PyMem_New(Py_buffer, cnt);
  9025. if (*buf == NULL) {
  9026. PyMem_Free(*iov);
  9027. PyErr_NoMemory();
  9028. return -1;
  9029. }
  9030. for (i = 0; i < cnt; i++) {
  9031. PyObject *item = PySequence_GetItem(seq, i);
  9032. if (item == NULL)
  9033. goto fail;
  9034. if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
  9035. Py_DECREF(item);
  9036. goto fail;
  9037. }
  9038. Py_DECREF(item);
  9039. (*iov)[i].iov_base = (*buf)[i].buf;
  9040. (*iov)[i].iov_len = (*buf)[i].len;
  9041. }
  9042. return 0;
  9043. fail:
  9044. PyMem_Free(*iov);
  9045. for (j = 0; j < i; j++) {
  9046. PyBuffer_Release(&(*buf)[j]);
  9047. }
  9048. PyMem_Free(*buf);
  9049. return -1;
  9050. }
  9051. static void
  9052. iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
  9053. {
  9054. int i;
  9055. PyMem_Free(iov);
  9056. for (i = 0; i < cnt; i++) {
  9057. PyBuffer_Release(&buf[i]);
  9058. }
  9059. PyMem_Free(buf);
  9060. }
  9061. #endif
  9062. #ifdef HAVE_READV
  9063. /*[clinic input]
  9064. os.readv -> Py_ssize_t
  9065. fd: int
  9066. buffers: object
  9067. /
  9068. Read from a file descriptor fd into an iterable of buffers.
  9069. The buffers should be mutable buffers accepting bytes.
  9070. readv will transfer data into each buffer until it is full
  9071. and then move on to the next buffer in the sequence to hold
  9072. the rest of the data.
  9073. readv returns the total number of bytes read,
  9074. which may be less than the total capacity of all the buffers.
  9075. [clinic start generated code]*/
  9076. static Py_ssize_t
  9077. os_readv_impl(PyObject *module, int fd, PyObject *buffers)
  9078. /*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
  9079. {
  9080. Py_ssize_t cnt, n;
  9081. int async_err = 0;
  9082. struct iovec *iov;
  9083. Py_buffer *buf;
  9084. if (!PySequence_Check(buffers)) {
  9085. PyErr_SetString(PyExc_TypeError,
  9086. "readv() arg 2 must be a sequence");
  9087. return -1;
  9088. }
  9089. cnt = PySequence_Size(buffers);
  9090. if (cnt < 0)
  9091. return -1;
  9092. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
  9093. return -1;
  9094. do {
  9095. Py_BEGIN_ALLOW_THREADS
  9096. n = readv(fd, iov, cnt);
  9097. Py_END_ALLOW_THREADS
  9098. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9099. int saved_errno = errno;
  9100. iov_cleanup(iov, buf, cnt);
  9101. if (n < 0) {
  9102. if (!async_err) {
  9103. errno = saved_errno;
  9104. posix_error();
  9105. }
  9106. return -1;
  9107. }
  9108. return n;
  9109. }
  9110. #endif /* HAVE_READV */
  9111. #ifdef HAVE_PREAD
  9112. /*[clinic input]
  9113. os.pread
  9114. fd: int
  9115. length: Py_ssize_t
  9116. offset: Py_off_t
  9117. /
  9118. Read a number of bytes from a file descriptor starting at a particular offset.
  9119. Read length bytes from file descriptor fd, starting at offset bytes from
  9120. the beginning of the file. The file offset remains unchanged.
  9121. [clinic start generated code]*/
  9122. static PyObject *
  9123. os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
  9124. /*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
  9125. {
  9126. Py_ssize_t n;
  9127. int async_err = 0;
  9128. PyObject *buffer;
  9129. if (length < 0) {
  9130. errno = EINVAL;
  9131. return posix_error();
  9132. }
  9133. buffer = PyBytes_FromStringAndSize((char *)NULL, length);
  9134. if (buffer == NULL)
  9135. return NULL;
  9136. do {
  9137. Py_BEGIN_ALLOW_THREADS
  9138. _Py_BEGIN_SUPPRESS_IPH
  9139. n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
  9140. _Py_END_SUPPRESS_IPH
  9141. Py_END_ALLOW_THREADS
  9142. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9143. if (n < 0) {
  9144. if (!async_err) {
  9145. posix_error();
  9146. }
  9147. Py_DECREF(buffer);
  9148. return NULL;
  9149. }
  9150. if (n != length)
  9151. _PyBytes_Resize(&buffer, n);
  9152. return buffer;
  9153. }
  9154. #endif /* HAVE_PREAD */
  9155. #if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
  9156. /*[clinic input]
  9157. os.preadv -> Py_ssize_t
  9158. fd: int
  9159. buffers: object
  9160. offset: Py_off_t
  9161. flags: int = 0
  9162. /
  9163. Reads from a file descriptor into a number of mutable bytes-like objects.
  9164. Combines the functionality of readv() and pread(). As readv(), it will
  9165. transfer data into each buffer until it is full and then move on to the next
  9166. buffer in the sequence to hold the rest of the data. Its fourth argument,
  9167. specifies the file offset at which the input operation is to be performed. It
  9168. will return the total number of bytes read (which can be less than the total
  9169. capacity of all the objects).
  9170. The flags argument contains a bitwise OR of zero or more of the following flags:
  9171. - RWF_HIPRI
  9172. - RWF_NOWAIT
  9173. Using non-zero flags requires Linux 4.6 or newer.
  9174. [clinic start generated code]*/
  9175. static Py_ssize_t
  9176. os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
  9177. int flags)
  9178. /*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
  9179. {
  9180. Py_ssize_t cnt, n;
  9181. int async_err = 0;
  9182. struct iovec *iov;
  9183. Py_buffer *buf;
  9184. if (!PySequence_Check(buffers)) {
  9185. PyErr_SetString(PyExc_TypeError,
  9186. "preadv2() arg 2 must be a sequence");
  9187. return -1;
  9188. }
  9189. cnt = PySequence_Size(buffers);
  9190. if (cnt < 0) {
  9191. return -1;
  9192. }
  9193. #ifndef HAVE_PREADV2
  9194. if(flags != 0) {
  9195. argument_unavailable_error("preadv2", "flags");
  9196. return -1;
  9197. }
  9198. #endif
  9199. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
  9200. return -1;
  9201. }
  9202. #ifdef HAVE_PREADV2
  9203. do {
  9204. Py_BEGIN_ALLOW_THREADS
  9205. _Py_BEGIN_SUPPRESS_IPH
  9206. n = preadv2(fd, iov, cnt, offset, flags);
  9207. _Py_END_SUPPRESS_IPH
  9208. Py_END_ALLOW_THREADS
  9209. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9210. #else
  9211. do {
  9212. #if defined(__APPLE__) && defined(__clang__)
  9213. /* This entire function will be removed from the module dict when the API
  9214. * is not available.
  9215. */
  9216. #pragma clang diagnostic push
  9217. #pragma clang diagnostic ignored "-Wunguarded-availability"
  9218. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  9219. #endif
  9220. Py_BEGIN_ALLOW_THREADS
  9221. _Py_BEGIN_SUPPRESS_IPH
  9222. n = preadv(fd, iov, cnt, offset);
  9223. _Py_END_SUPPRESS_IPH
  9224. Py_END_ALLOW_THREADS
  9225. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9226. #if defined(__APPLE__) && defined(__clang__)
  9227. #pragma clang diagnostic pop
  9228. #endif
  9229. #endif
  9230. int saved_errno = errno;
  9231. iov_cleanup(iov, buf, cnt);
  9232. if (n < 0) {
  9233. if (!async_err) {
  9234. errno = saved_errno;
  9235. posix_error();
  9236. }
  9237. return -1;
  9238. }
  9239. return n;
  9240. }
  9241. #endif /* HAVE_PREADV */
  9242. /*[clinic input]
  9243. os.write -> Py_ssize_t
  9244. fd: int
  9245. data: Py_buffer
  9246. /
  9247. Write a bytes object to a file descriptor.
  9248. [clinic start generated code]*/
  9249. static Py_ssize_t
  9250. os_write_impl(PyObject *module, int fd, Py_buffer *data)
  9251. /*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
  9252. {
  9253. return _Py_write(fd, data->buf, data->len);
  9254. }
  9255. #ifdef HAVE_SENDFILE
  9256. #ifdef __APPLE__
  9257. /*[clinic input]
  9258. os.sendfile
  9259. out_fd: int
  9260. in_fd: int
  9261. offset: Py_off_t
  9262. count as sbytes: Py_off_t
  9263. headers: object(c_default="NULL") = ()
  9264. trailers: object(c_default="NULL") = ()
  9265. flags: int = 0
  9266. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9267. [clinic start generated code]*/
  9268. static PyObject *
  9269. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
  9270. Py_off_t sbytes, PyObject *headers, PyObject *trailers,
  9271. int flags)
  9272. /*[clinic end generated code: output=81c4bcd143f5c82b input=b0d72579d4c69afa]*/
  9273. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  9274. /*[clinic input]
  9275. os.sendfile
  9276. out_fd: int
  9277. in_fd: int
  9278. offset: Py_off_t
  9279. count: Py_ssize_t
  9280. headers: object(c_default="NULL") = ()
  9281. trailers: object(c_default="NULL") = ()
  9282. flags: int = 0
  9283. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9284. [clinic start generated code]*/
  9285. static PyObject *
  9286. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
  9287. Py_ssize_t count, PyObject *headers, PyObject *trailers,
  9288. int flags)
  9289. /*[clinic end generated code: output=329ea009bdd55afc input=338adb8ff84ae8cd]*/
  9290. #else
  9291. /*[clinic input]
  9292. os.sendfile
  9293. out_fd: int
  9294. in_fd: int
  9295. offset as offobj: object
  9296. count: Py_ssize_t
  9297. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9298. [clinic start generated code]*/
  9299. static PyObject *
  9300. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, PyObject *offobj,
  9301. Py_ssize_t count)
  9302. /*[clinic end generated code: output=ae81216e40f167d8 input=76d64058c74477ba]*/
  9303. #endif
  9304. {
  9305. Py_ssize_t ret;
  9306. int async_err = 0;
  9307. #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
  9308. #ifndef __APPLE__
  9309. off_t sbytes;
  9310. #endif
  9311. Py_buffer *hbuf, *tbuf;
  9312. struct sf_hdtr sf;
  9313. sf.headers = NULL;
  9314. sf.trailers = NULL;
  9315. if (headers != NULL) {
  9316. if (!PySequence_Check(headers)) {
  9317. PyErr_SetString(PyExc_TypeError,
  9318. "sendfile() headers must be a sequence");
  9319. return NULL;
  9320. } else {
  9321. Py_ssize_t i = PySequence_Size(headers);
  9322. if (i < 0)
  9323. return NULL;
  9324. if (i > INT_MAX) {
  9325. PyErr_SetString(PyExc_OverflowError,
  9326. "sendfile() header is too large");
  9327. return NULL;
  9328. }
  9329. if (i > 0) {
  9330. sf.hdr_cnt = (int)i;
  9331. if (iov_setup(&(sf.headers), &hbuf,
  9332. headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
  9333. return NULL;
  9334. #ifdef __APPLE__
  9335. for (i = 0; i < sf.hdr_cnt; i++) {
  9336. Py_ssize_t blen = sf.headers[i].iov_len;
  9337. # define OFF_T_MAX 0x7fffffffffffffff
  9338. if (sbytes >= OFF_T_MAX - blen) {
  9339. PyErr_SetString(PyExc_OverflowError,
  9340. "sendfile() header is too large");
  9341. return NULL;
  9342. }
  9343. sbytes += blen;
  9344. }
  9345. #endif
  9346. }
  9347. }
  9348. }
  9349. if (trailers != NULL) {
  9350. if (!PySequence_Check(trailers)) {
  9351. PyErr_SetString(PyExc_TypeError,
  9352. "sendfile() trailers must be a sequence");
  9353. return NULL;
  9354. } else {
  9355. Py_ssize_t i = PySequence_Size(trailers);
  9356. if (i < 0)
  9357. return NULL;
  9358. if (i > INT_MAX) {
  9359. PyErr_SetString(PyExc_OverflowError,
  9360. "sendfile() trailer is too large");
  9361. return NULL;
  9362. }
  9363. if (i > 0) {
  9364. sf.trl_cnt = (int)i;
  9365. if (iov_setup(&(sf.trailers), &tbuf,
  9366. trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
  9367. return NULL;
  9368. }
  9369. }
  9370. }
  9371. _Py_BEGIN_SUPPRESS_IPH
  9372. do {
  9373. Py_BEGIN_ALLOW_THREADS
  9374. #ifdef __APPLE__
  9375. ret = sendfile(in_fd, out_fd, offset, &sbytes, &sf, flags);
  9376. #else
  9377. ret = sendfile(in_fd, out_fd, offset, count, &sf, &sbytes, flags);
  9378. #endif
  9379. Py_END_ALLOW_THREADS
  9380. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9381. _Py_END_SUPPRESS_IPH
  9382. int saved_errno = errno;
  9383. if (sf.headers != NULL)
  9384. iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
  9385. if (sf.trailers != NULL)
  9386. iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
  9387. if (ret < 0) {
  9388. if ((saved_errno == EAGAIN) || (saved_errno == EBUSY)) {
  9389. if (sbytes != 0) {
  9390. // some data has been sent
  9391. goto done;
  9392. }
  9393. // no data has been sent; upper application is supposed
  9394. // to retry on EAGAIN or EBUSY
  9395. }
  9396. if (!async_err) {
  9397. errno = saved_errno;
  9398. posix_error();
  9399. }
  9400. return NULL;
  9401. }
  9402. goto done;
  9403. done:
  9404. #if !defined(HAVE_LARGEFILE_SUPPORT)
  9405. return Py_BuildValue("l", sbytes);
  9406. #else
  9407. return Py_BuildValue("L", sbytes);
  9408. #endif
  9409. #else
  9410. #ifdef __linux__
  9411. if (offobj == Py_None) {
  9412. do {
  9413. Py_BEGIN_ALLOW_THREADS
  9414. ret = sendfile(out_fd, in_fd, NULL, count);
  9415. Py_END_ALLOW_THREADS
  9416. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9417. if (ret < 0)
  9418. return (!async_err) ? posix_error() : NULL;
  9419. return Py_BuildValue("n", ret);
  9420. }
  9421. #endif
  9422. off_t offset;
  9423. if (!Py_off_t_converter(offobj, &offset))
  9424. return NULL;
  9425. #if defined(__sun) && defined(__SVR4)
  9426. // On Solaris, sendfile raises EINVAL rather than returning 0
  9427. // when the offset is equal or bigger than the in_fd size.
  9428. struct stat st;
  9429. do {
  9430. Py_BEGIN_ALLOW_THREADS
  9431. ret = fstat(in_fd, &st);
  9432. Py_END_ALLOW_THREADS
  9433. } while (ret != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9434. if (ret < 0)
  9435. return (!async_err) ? posix_error() : NULL;
  9436. if (offset >= st.st_size) {
  9437. return Py_BuildValue("i", 0);
  9438. }
  9439. // On illumos specifically sendfile() may perform a partial write but
  9440. // return -1/an error (in one confirmed case the destination socket
  9441. // had a 5 second timeout set and errno was EAGAIN) and it's on the client
  9442. // code to check if the offset parameter was modified by sendfile().
  9443. //
  9444. // We need this variable to track said change.
  9445. off_t original_offset = offset;
  9446. #endif
  9447. do {
  9448. Py_BEGIN_ALLOW_THREADS
  9449. ret = sendfile(out_fd, in_fd, &offset, count);
  9450. #if defined(__sun) && defined(__SVR4)
  9451. // This handles illumos-specific sendfile() partial write behavior,
  9452. // see a comment above for more details.
  9453. if (ret < 0 && offset != original_offset) {
  9454. ret = offset - original_offset;
  9455. }
  9456. #endif
  9457. Py_END_ALLOW_THREADS
  9458. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9459. if (ret < 0)
  9460. return (!async_err) ? posix_error() : NULL;
  9461. return Py_BuildValue("n", ret);
  9462. #endif
  9463. }
  9464. #endif /* HAVE_SENDFILE */
  9465. #if defined(__APPLE__)
  9466. /*[clinic input]
  9467. os._fcopyfile
  9468. in_fd: int
  9469. out_fd: int
  9470. flags: int
  9471. /
  9472. Efficiently copy content or metadata of 2 regular file descriptors (macOS).
  9473. [clinic start generated code]*/
  9474. static PyObject *
  9475. os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
  9476. /*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
  9477. {
  9478. int ret;
  9479. Py_BEGIN_ALLOW_THREADS
  9480. ret = fcopyfile(in_fd, out_fd, NULL, flags);
  9481. Py_END_ALLOW_THREADS
  9482. if (ret < 0)
  9483. return posix_error();
  9484. Py_RETURN_NONE;
  9485. }
  9486. #endif
  9487. /*[clinic input]
  9488. os.fstat
  9489. fd : int
  9490. Perform a stat system call on the given file descriptor.
  9491. Like stat(), but for an open file descriptor.
  9492. Equivalent to os.stat(fd).
  9493. [clinic start generated code]*/
  9494. static PyObject *
  9495. os_fstat_impl(PyObject *module, int fd)
  9496. /*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
  9497. {
  9498. STRUCT_STAT st;
  9499. int res;
  9500. int async_err = 0;
  9501. do {
  9502. Py_BEGIN_ALLOW_THREADS
  9503. res = FSTAT(fd, &st);
  9504. Py_END_ALLOW_THREADS
  9505. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9506. if (res != 0) {
  9507. #ifdef MS_WINDOWS
  9508. return PyErr_SetFromWindowsErr(0);
  9509. #else
  9510. return (!async_err) ? posix_error() : NULL;
  9511. #endif
  9512. }
  9513. return _pystat_fromstructstat(module, &st);
  9514. }
  9515. /*[clinic input]
  9516. os.isatty -> bool
  9517. fd: int
  9518. /
  9519. Return True if the fd is connected to a terminal.
  9520. Return True if the file descriptor is an open file descriptor
  9521. connected to the slave end of a terminal.
  9522. [clinic start generated code]*/
  9523. static int
  9524. os_isatty_impl(PyObject *module, int fd)
  9525. /*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
  9526. {
  9527. int return_value;
  9528. Py_BEGIN_ALLOW_THREADS
  9529. _Py_BEGIN_SUPPRESS_IPH
  9530. return_value = isatty(fd);
  9531. _Py_END_SUPPRESS_IPH
  9532. Py_END_ALLOW_THREADS
  9533. return return_value;
  9534. }
  9535. #ifdef HAVE_PIPE
  9536. /*[clinic input]
  9537. os.pipe
  9538. Create a pipe.
  9539. Returns a tuple of two file descriptors:
  9540. (read_fd, write_fd)
  9541. [clinic start generated code]*/
  9542. static PyObject *
  9543. os_pipe_impl(PyObject *module)
  9544. /*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
  9545. {
  9546. int fds[2];
  9547. #ifdef MS_WINDOWS
  9548. HANDLE read, write;
  9549. SECURITY_ATTRIBUTES attr;
  9550. BOOL ok;
  9551. #else
  9552. int res;
  9553. #endif
  9554. #ifdef MS_WINDOWS
  9555. attr.nLength = sizeof(attr);
  9556. attr.lpSecurityDescriptor = NULL;
  9557. attr.bInheritHandle = FALSE;
  9558. Py_BEGIN_ALLOW_THREADS
  9559. ok = CreatePipe(&read, &write, &attr, 0);
  9560. if (ok) {
  9561. fds[0] = _Py_open_osfhandle_noraise(read, _O_RDONLY);
  9562. fds[1] = _Py_open_osfhandle_noraise(write, _O_WRONLY);
  9563. if (fds[0] == -1 || fds[1] == -1) {
  9564. CloseHandle(read);
  9565. CloseHandle(write);
  9566. ok = 0;
  9567. }
  9568. }
  9569. Py_END_ALLOW_THREADS
  9570. if (!ok)
  9571. return PyErr_SetFromWindowsErr(0);
  9572. #else
  9573. #ifdef HAVE_PIPE2
  9574. Py_BEGIN_ALLOW_THREADS
  9575. res = pipe2(fds, O_CLOEXEC);
  9576. Py_END_ALLOW_THREADS
  9577. if (res != 0 && errno == ENOSYS)
  9578. {
  9579. #endif
  9580. Py_BEGIN_ALLOW_THREADS
  9581. res = pipe(fds);
  9582. Py_END_ALLOW_THREADS
  9583. if (res == 0) {
  9584. if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
  9585. close(fds[0]);
  9586. close(fds[1]);
  9587. return NULL;
  9588. }
  9589. if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
  9590. close(fds[0]);
  9591. close(fds[1]);
  9592. return NULL;
  9593. }
  9594. }
  9595. #ifdef HAVE_PIPE2
  9596. }
  9597. #endif
  9598. if (res != 0)
  9599. return PyErr_SetFromErrno(PyExc_OSError);
  9600. #endif /* !MS_WINDOWS */
  9601. return Py_BuildValue("(ii)", fds[0], fds[1]);
  9602. }
  9603. #endif /* HAVE_PIPE */
  9604. #ifdef HAVE_PIPE2
  9605. /*[clinic input]
  9606. os.pipe2
  9607. flags: int
  9608. /
  9609. Create a pipe with flags set atomically.
  9610. Returns a tuple of two file descriptors:
  9611. (read_fd, write_fd)
  9612. flags can be constructed by ORing together one or more of these values:
  9613. O_NONBLOCK, O_CLOEXEC.
  9614. [clinic start generated code]*/
  9615. static PyObject *
  9616. os_pipe2_impl(PyObject *module, int flags)
  9617. /*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
  9618. {
  9619. int fds[2];
  9620. int res;
  9621. res = pipe2(fds, flags);
  9622. if (res != 0)
  9623. return posix_error();
  9624. return Py_BuildValue("(ii)", fds[0], fds[1]);
  9625. }
  9626. #endif /* HAVE_PIPE2 */
  9627. #ifdef HAVE_WRITEV
  9628. /*[clinic input]
  9629. os.writev -> Py_ssize_t
  9630. fd: int
  9631. buffers: object
  9632. /
  9633. Iterate over buffers, and write the contents of each to a file descriptor.
  9634. Returns the total number of bytes written.
  9635. buffers must be a sequence of bytes-like objects.
  9636. [clinic start generated code]*/
  9637. static Py_ssize_t
  9638. os_writev_impl(PyObject *module, int fd, PyObject *buffers)
  9639. /*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
  9640. {
  9641. Py_ssize_t cnt;
  9642. Py_ssize_t result;
  9643. int async_err = 0;
  9644. struct iovec *iov;
  9645. Py_buffer *buf;
  9646. if (!PySequence_Check(buffers)) {
  9647. PyErr_SetString(PyExc_TypeError,
  9648. "writev() arg 2 must be a sequence");
  9649. return -1;
  9650. }
  9651. cnt = PySequence_Size(buffers);
  9652. if (cnt < 0)
  9653. return -1;
  9654. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
  9655. return -1;
  9656. }
  9657. do {
  9658. Py_BEGIN_ALLOW_THREADS
  9659. result = writev(fd, iov, cnt);
  9660. Py_END_ALLOW_THREADS
  9661. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9662. if (result < 0 && !async_err)
  9663. posix_error();
  9664. iov_cleanup(iov, buf, cnt);
  9665. return result;
  9666. }
  9667. #endif /* HAVE_WRITEV */
  9668. #ifdef HAVE_PWRITE
  9669. /*[clinic input]
  9670. os.pwrite -> Py_ssize_t
  9671. fd: int
  9672. buffer: Py_buffer
  9673. offset: Py_off_t
  9674. /
  9675. Write bytes to a file descriptor starting at a particular offset.
  9676. Write buffer to fd, starting at offset bytes from the beginning of
  9677. the file. Returns the number of bytes writte. Does not change the
  9678. current file offset.
  9679. [clinic start generated code]*/
  9680. static Py_ssize_t
  9681. os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
  9682. /*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
  9683. {
  9684. Py_ssize_t size;
  9685. int async_err = 0;
  9686. do {
  9687. Py_BEGIN_ALLOW_THREADS
  9688. _Py_BEGIN_SUPPRESS_IPH
  9689. size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
  9690. _Py_END_SUPPRESS_IPH
  9691. Py_END_ALLOW_THREADS
  9692. } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9693. if (size < 0 && !async_err)
  9694. posix_error();
  9695. return size;
  9696. }
  9697. #endif /* HAVE_PWRITE */
  9698. #if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
  9699. /*[clinic input]
  9700. os.pwritev -> Py_ssize_t
  9701. fd: int
  9702. buffers: object
  9703. offset: Py_off_t
  9704. flags: int = 0
  9705. /
  9706. Writes the contents of bytes-like objects to a file descriptor at a given offset.
  9707. Combines the functionality of writev() and pwrite(). All buffers must be a sequence
  9708. of bytes-like objects. Buffers are processed in array order. Entire contents of first
  9709. buffer is written before proceeding to second, and so on. The operating system may
  9710. set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
  9711. This function writes the contents of each object to the file descriptor and returns
  9712. the total number of bytes written.
  9713. The flags argument contains a bitwise OR of zero or more of the following flags:
  9714. - RWF_DSYNC
  9715. - RWF_SYNC
  9716. - RWF_APPEND
  9717. Using non-zero flags requires Linux 4.7 or newer.
  9718. [clinic start generated code]*/
  9719. static Py_ssize_t
  9720. os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
  9721. int flags)
  9722. /*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=35358c327e1a2a8e]*/
  9723. {
  9724. Py_ssize_t cnt;
  9725. Py_ssize_t result;
  9726. int async_err = 0;
  9727. struct iovec *iov;
  9728. Py_buffer *buf;
  9729. if (!PySequence_Check(buffers)) {
  9730. PyErr_SetString(PyExc_TypeError,
  9731. "pwritev() arg 2 must be a sequence");
  9732. return -1;
  9733. }
  9734. cnt = PySequence_Size(buffers);
  9735. if (cnt < 0) {
  9736. return -1;
  9737. }
  9738. #ifndef HAVE_PWRITEV2
  9739. if(flags != 0) {
  9740. argument_unavailable_error("pwritev2", "flags");
  9741. return -1;
  9742. }
  9743. #endif
  9744. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
  9745. return -1;
  9746. }
  9747. #ifdef HAVE_PWRITEV2
  9748. do {
  9749. Py_BEGIN_ALLOW_THREADS
  9750. _Py_BEGIN_SUPPRESS_IPH
  9751. result = pwritev2(fd, iov, cnt, offset, flags);
  9752. _Py_END_SUPPRESS_IPH
  9753. Py_END_ALLOW_THREADS
  9754. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9755. #else
  9756. #if defined(__APPLE__) && defined(__clang__)
  9757. /* This entire function will be removed from the module dict when the API
  9758. * is not available.
  9759. */
  9760. #pragma clang diagnostic push
  9761. #pragma clang diagnostic ignored "-Wunguarded-availability"
  9762. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  9763. #endif
  9764. do {
  9765. Py_BEGIN_ALLOW_THREADS
  9766. _Py_BEGIN_SUPPRESS_IPH
  9767. result = pwritev(fd, iov, cnt, offset);
  9768. _Py_END_SUPPRESS_IPH
  9769. Py_END_ALLOW_THREADS
  9770. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9771. #if defined(__APPLE__) && defined(__clang__)
  9772. #pragma clang diagnostic pop
  9773. #endif
  9774. #endif
  9775. if (result < 0) {
  9776. if (!async_err) {
  9777. posix_error();
  9778. }
  9779. result = -1;
  9780. }
  9781. iov_cleanup(iov, buf, cnt);
  9782. return result;
  9783. }
  9784. #endif /* HAVE_PWRITEV */
  9785. #ifdef HAVE_COPY_FILE_RANGE
  9786. /*[clinic input]
  9787. os.copy_file_range
  9788. src: int
  9789. Source file descriptor.
  9790. dst: int
  9791. Destination file descriptor.
  9792. count: Py_ssize_t
  9793. Number of bytes to copy.
  9794. offset_src: object = None
  9795. Starting offset in src.
  9796. offset_dst: object = None
  9797. Starting offset in dst.
  9798. Copy count bytes from one file descriptor to another.
  9799. If offset_src is None, then src is read from the current position;
  9800. respectively for offset_dst.
  9801. [clinic start generated code]*/
  9802. static PyObject *
  9803. os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
  9804. PyObject *offset_src, PyObject *offset_dst)
  9805. /*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
  9806. {
  9807. off_t offset_src_val, offset_dst_val;
  9808. off_t *p_offset_src = NULL;
  9809. off_t *p_offset_dst = NULL;
  9810. Py_ssize_t ret;
  9811. int async_err = 0;
  9812. /* The flags argument is provided to allow
  9813. * for future extensions and currently must be to 0. */
  9814. int flags = 0;
  9815. if (count < 0) {
  9816. PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
  9817. return NULL;
  9818. }
  9819. if (offset_src != Py_None) {
  9820. if (!Py_off_t_converter(offset_src, &offset_src_val)) {
  9821. return NULL;
  9822. }
  9823. p_offset_src = &offset_src_val;
  9824. }
  9825. if (offset_dst != Py_None) {
  9826. if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
  9827. return NULL;
  9828. }
  9829. p_offset_dst = &offset_dst_val;
  9830. }
  9831. do {
  9832. Py_BEGIN_ALLOW_THREADS
  9833. ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
  9834. Py_END_ALLOW_THREADS
  9835. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9836. if (ret < 0) {
  9837. return (!async_err) ? posix_error() : NULL;
  9838. }
  9839. return PyLong_FromSsize_t(ret);
  9840. }
  9841. #endif /* HAVE_COPY_FILE_RANGE*/
  9842. #if (defined(HAVE_SPLICE) && !defined(_AIX))
  9843. /*[clinic input]
  9844. os.splice
  9845. src: int
  9846. Source file descriptor.
  9847. dst: int
  9848. Destination file descriptor.
  9849. count: Py_ssize_t
  9850. Number of bytes to copy.
  9851. offset_src: object = None
  9852. Starting offset in src.
  9853. offset_dst: object = None
  9854. Starting offset in dst.
  9855. flags: unsigned_int = 0
  9856. Flags to modify the semantics of the call.
  9857. Transfer count bytes from one pipe to a descriptor or vice versa.
  9858. If offset_src is None, then src is read from the current position;
  9859. respectively for offset_dst. The offset associated to the file
  9860. descriptor that refers to a pipe must be None.
  9861. [clinic start generated code]*/
  9862. static PyObject *
  9863. os_splice_impl(PyObject *module, int src, int dst, Py_ssize_t count,
  9864. PyObject *offset_src, PyObject *offset_dst,
  9865. unsigned int flags)
  9866. /*[clinic end generated code: output=d0386f25a8519dc5 input=047527c66c6d2e0a]*/
  9867. {
  9868. off_t offset_src_val, offset_dst_val;
  9869. off_t *p_offset_src = NULL;
  9870. off_t *p_offset_dst = NULL;
  9871. Py_ssize_t ret;
  9872. int async_err = 0;
  9873. if (count < 0) {
  9874. PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
  9875. return NULL;
  9876. }
  9877. if (offset_src != Py_None) {
  9878. if (!Py_off_t_converter(offset_src, &offset_src_val)) {
  9879. return NULL;
  9880. }
  9881. p_offset_src = &offset_src_val;
  9882. }
  9883. if (offset_dst != Py_None) {
  9884. if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
  9885. return NULL;
  9886. }
  9887. p_offset_dst = &offset_dst_val;
  9888. }
  9889. do {
  9890. Py_BEGIN_ALLOW_THREADS
  9891. ret = splice(src, p_offset_src, dst, p_offset_dst, count, flags);
  9892. Py_END_ALLOW_THREADS
  9893. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9894. if (ret < 0) {
  9895. return (!async_err) ? posix_error() : NULL;
  9896. }
  9897. return PyLong_FromSsize_t(ret);
  9898. }
  9899. #endif /* HAVE_SPLICE*/
  9900. #ifdef HAVE_MKFIFO
  9901. /*[clinic input]
  9902. os.mkfifo
  9903. path: path_t
  9904. mode: int=0o666
  9905. *
  9906. dir_fd: dir_fd(requires='mkfifoat')=None
  9907. Create a "fifo" (a POSIX named pipe).
  9908. If dir_fd is not None, it should be a file descriptor open to a directory,
  9909. and path should be relative; path will then be relative to that directory.
  9910. dir_fd may not be implemented on your platform.
  9911. If it is unavailable, using it will raise a NotImplementedError.
  9912. [clinic start generated code]*/
  9913. static PyObject *
  9914. os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
  9915. /*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
  9916. {
  9917. int result;
  9918. int async_err = 0;
  9919. #ifdef HAVE_MKFIFOAT
  9920. int mkfifoat_unavailable = 0;
  9921. #endif
  9922. do {
  9923. Py_BEGIN_ALLOW_THREADS
  9924. #ifdef HAVE_MKFIFOAT
  9925. if (dir_fd != DEFAULT_DIR_FD) {
  9926. if (HAVE_MKFIFOAT_RUNTIME) {
  9927. result = mkfifoat(dir_fd, path->narrow, mode);
  9928. } else {
  9929. mkfifoat_unavailable = 1;
  9930. result = 0;
  9931. }
  9932. } else
  9933. #endif
  9934. result = mkfifo(path->narrow, mode);
  9935. Py_END_ALLOW_THREADS
  9936. } while (result != 0 && errno == EINTR &&
  9937. !(async_err = PyErr_CheckSignals()));
  9938. #ifdef HAVE_MKFIFOAT
  9939. if (mkfifoat_unavailable) {
  9940. argument_unavailable_error(NULL, "dir_fd");
  9941. return NULL;
  9942. }
  9943. #endif
  9944. if (result != 0)
  9945. return (!async_err) ? posix_error() : NULL;
  9946. Py_RETURN_NONE;
  9947. }
  9948. #endif /* HAVE_MKFIFO */
  9949. #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
  9950. /*[clinic input]
  9951. os.mknod
  9952. path: path_t
  9953. mode: int=0o600
  9954. device: dev_t=0
  9955. *
  9956. dir_fd: dir_fd(requires='mknodat')=None
  9957. Create a node in the file system.
  9958. Create a node in the file system (file, device special file or named pipe)
  9959. at path. mode specifies both the permissions to use and the
  9960. type of node to be created, being combined (bitwise OR) with one of
  9961. S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
  9962. device defines the newly created device special file (probably using
  9963. os.makedev()). Otherwise device is ignored.
  9964. If dir_fd is not None, it should be a file descriptor open to a directory,
  9965. and path should be relative; path will then be relative to that directory.
  9966. dir_fd may not be implemented on your platform.
  9967. If it is unavailable, using it will raise a NotImplementedError.
  9968. [clinic start generated code]*/
  9969. static PyObject *
  9970. os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
  9971. int dir_fd)
  9972. /*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
  9973. {
  9974. int result;
  9975. int async_err = 0;
  9976. #ifdef HAVE_MKNODAT
  9977. int mknodat_unavailable = 0;
  9978. #endif
  9979. do {
  9980. Py_BEGIN_ALLOW_THREADS
  9981. #ifdef HAVE_MKNODAT
  9982. if (dir_fd != DEFAULT_DIR_FD) {
  9983. if (HAVE_MKNODAT_RUNTIME) {
  9984. result = mknodat(dir_fd, path->narrow, mode, device);
  9985. } else {
  9986. mknodat_unavailable = 1;
  9987. result = 0;
  9988. }
  9989. } else
  9990. #endif
  9991. result = mknod(path->narrow, mode, device);
  9992. Py_END_ALLOW_THREADS
  9993. } while (result != 0 && errno == EINTR &&
  9994. !(async_err = PyErr_CheckSignals()));
  9995. #ifdef HAVE_MKNODAT
  9996. if (mknodat_unavailable) {
  9997. argument_unavailable_error(NULL, "dir_fd");
  9998. return NULL;
  9999. }
  10000. #endif
  10001. if (result != 0)
  10002. return (!async_err) ? posix_error() : NULL;
  10003. Py_RETURN_NONE;
  10004. }
  10005. #endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
  10006. #ifdef HAVE_DEVICE_MACROS
  10007. static PyObject *
  10008. major_minor_conv(unsigned int value)
  10009. {
  10010. #ifdef NODEV
  10011. if (value == (unsigned int)NODEV) {
  10012. return PyLong_FromLong((int)NODEV);
  10013. }
  10014. #endif
  10015. return PyLong_FromUnsignedLong(value);
  10016. }
  10017. static int
  10018. major_minor_check(dev_t value)
  10019. {
  10020. #ifdef NODEV
  10021. if (value == NODEV) {
  10022. return 1;
  10023. }
  10024. #endif
  10025. return (dev_t)(unsigned int)value == value;
  10026. }
  10027. /*[clinic input]
  10028. os.major
  10029. device: dev_t
  10030. /
  10031. Extracts a device major number from a raw device number.
  10032. [clinic start generated code]*/
  10033. static PyObject *
  10034. os_major_impl(PyObject *module, dev_t device)
  10035. /*[clinic end generated code: output=4071ffee17647891 input=b1a0a14ec9448229]*/
  10036. {
  10037. return major_minor_conv(major(device));
  10038. }
  10039. /*[clinic input]
  10040. os.minor
  10041. device: dev_t
  10042. /
  10043. Extracts a device minor number from a raw device number.
  10044. [clinic start generated code]*/
  10045. static PyObject *
  10046. os_minor_impl(PyObject *module, dev_t device)
  10047. /*[clinic end generated code: output=306cb78e3bc5004f input=2f686e463682a9da]*/
  10048. {
  10049. return major_minor_conv(minor(device));
  10050. }
  10051. /*[clinic input]
  10052. os.makedev -> dev_t
  10053. major: dev_t
  10054. minor: dev_t
  10055. /
  10056. Composes a raw device number from the major and minor device numbers.
  10057. [clinic start generated code]*/
  10058. static dev_t
  10059. os_makedev_impl(PyObject *module, dev_t major, dev_t minor)
  10060. /*[clinic end generated code: output=cad6125c51f5af80 input=2146126ec02e55c1]*/
  10061. {
  10062. if (!major_minor_check(major) || !major_minor_check(minor)) {
  10063. PyErr_SetString(PyExc_OverflowError,
  10064. "Python int too large to convert to C unsigned int");
  10065. return (dev_t)-1;
  10066. }
  10067. return makedev(major, minor);
  10068. }
  10069. #endif /* HAVE_DEVICE_MACROS */
  10070. #if defined HAVE_FTRUNCATE || defined MS_WINDOWS
  10071. /*[clinic input]
  10072. os.ftruncate
  10073. fd: int
  10074. length: Py_off_t
  10075. /
  10076. Truncate a file, specified by file descriptor, to a specific length.
  10077. [clinic start generated code]*/
  10078. static PyObject *
  10079. os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
  10080. /*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
  10081. {
  10082. int result;
  10083. int async_err = 0;
  10084. if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
  10085. return NULL;
  10086. }
  10087. do {
  10088. Py_BEGIN_ALLOW_THREADS
  10089. _Py_BEGIN_SUPPRESS_IPH
  10090. #ifdef MS_WINDOWS
  10091. result = _chsize_s(fd, length);
  10092. #else
  10093. result = ftruncate(fd, length);
  10094. #endif
  10095. _Py_END_SUPPRESS_IPH
  10096. Py_END_ALLOW_THREADS
  10097. } while (result != 0 && errno == EINTR &&
  10098. !(async_err = PyErr_CheckSignals()));
  10099. if (result != 0)
  10100. return (!async_err) ? posix_error() : NULL;
  10101. Py_RETURN_NONE;
  10102. }
  10103. #endif /* HAVE_FTRUNCATE || MS_WINDOWS */
  10104. #if defined HAVE_TRUNCATE || defined MS_WINDOWS
  10105. /*[clinic input]
  10106. os.truncate
  10107. path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
  10108. length: Py_off_t
  10109. Truncate a file, specified by path, to a specific length.
  10110. On some platforms, path may also be specified as an open file descriptor.
  10111. If this functionality is unavailable, using it raises an exception.
  10112. [clinic start generated code]*/
  10113. static PyObject *
  10114. os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
  10115. /*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
  10116. {
  10117. int result;
  10118. #ifdef MS_WINDOWS
  10119. int fd;
  10120. #endif
  10121. if (path->fd != -1)
  10122. return os_ftruncate_impl(module, path->fd, length);
  10123. if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
  10124. return NULL;
  10125. }
  10126. Py_BEGIN_ALLOW_THREADS
  10127. _Py_BEGIN_SUPPRESS_IPH
  10128. #ifdef MS_WINDOWS
  10129. fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
  10130. if (fd < 0)
  10131. result = -1;
  10132. else {
  10133. result = _chsize_s(fd, length);
  10134. close(fd);
  10135. if (result < 0)
  10136. errno = result;
  10137. }
  10138. #else
  10139. result = truncate(path->narrow, length);
  10140. #endif
  10141. _Py_END_SUPPRESS_IPH
  10142. Py_END_ALLOW_THREADS
  10143. if (result < 0)
  10144. return posix_path_error(path);
  10145. Py_RETURN_NONE;
  10146. }
  10147. #endif /* HAVE_TRUNCATE || MS_WINDOWS */
  10148. /* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
  10149. and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
  10150. defined, which is the case in Python on AIX. AIX bug report:
  10151. http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
  10152. #if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
  10153. # define POSIX_FADVISE_AIX_BUG
  10154. #endif
  10155. /* GH-111804: Due to posix_fallocate() not having consistent semantics across
  10156. OSs, support was dropped in WASI preview2. */
  10157. #if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG) && \
  10158. !defined(__wasi__)
  10159. /*[clinic input]
  10160. os.posix_fallocate
  10161. fd: int
  10162. offset: Py_off_t
  10163. length: Py_off_t
  10164. /
  10165. Ensure a file has allocated at least a particular number of bytes on disk.
  10166. Ensure that the file specified by fd encompasses a range of bytes
  10167. starting at offset bytes from the beginning and continuing for length bytes.
  10168. [clinic start generated code]*/
  10169. static PyObject *
  10170. os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
  10171. Py_off_t length)
  10172. /*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
  10173. {
  10174. int result;
  10175. int async_err = 0;
  10176. do {
  10177. Py_BEGIN_ALLOW_THREADS
  10178. result = posix_fallocate(fd, offset, length);
  10179. Py_END_ALLOW_THREADS
  10180. } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
  10181. if (result == 0)
  10182. Py_RETURN_NONE;
  10183. if (async_err)
  10184. return NULL;
  10185. errno = result;
  10186. return posix_error();
  10187. }
  10188. #endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG && !defined(__wasi__) */
  10189. #if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
  10190. /*[clinic input]
  10191. os.posix_fadvise
  10192. fd: int
  10193. offset: Py_off_t
  10194. length: Py_off_t
  10195. advice: int
  10196. /
  10197. Announce an intention to access data in a specific pattern.
  10198. Announce an intention to access data in a specific pattern, thus allowing
  10199. the kernel to make optimizations.
  10200. The advice applies to the region of the file specified by fd starting at
  10201. offset and continuing for length bytes.
  10202. advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
  10203. POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
  10204. POSIX_FADV_DONTNEED.
  10205. [clinic start generated code]*/
  10206. static PyObject *
  10207. os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
  10208. Py_off_t length, int advice)
  10209. /*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
  10210. {
  10211. int result;
  10212. int async_err = 0;
  10213. do {
  10214. Py_BEGIN_ALLOW_THREADS
  10215. result = posix_fadvise(fd, offset, length, advice);
  10216. Py_END_ALLOW_THREADS
  10217. } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
  10218. if (result == 0)
  10219. Py_RETURN_NONE;
  10220. if (async_err)
  10221. return NULL;
  10222. errno = result;
  10223. return posix_error();
  10224. }
  10225. #endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
  10226. #ifdef MS_WINDOWS
  10227. static PyObject*
  10228. win32_putenv(PyObject *name, PyObject *value)
  10229. {
  10230. /* Search from index 1 because on Windows starting '=' is allowed for
  10231. defining hidden environment variables. */
  10232. if (PyUnicode_GET_LENGTH(name) == 0 ||
  10233. PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
  10234. {
  10235. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  10236. return NULL;
  10237. }
  10238. PyObject *unicode;
  10239. if (value != NULL) {
  10240. unicode = PyUnicode_FromFormat("%U=%U", name, value);
  10241. }
  10242. else {
  10243. unicode = PyUnicode_FromFormat("%U=", name);
  10244. }
  10245. if (unicode == NULL) {
  10246. return NULL;
  10247. }
  10248. Py_ssize_t size;
  10249. wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
  10250. Py_DECREF(unicode);
  10251. if (env == NULL) {
  10252. return NULL;
  10253. }
  10254. if (size > _MAX_ENV) {
  10255. PyErr_Format(PyExc_ValueError,
  10256. "the environment variable is longer than %u characters",
  10257. _MAX_ENV);
  10258. PyMem_Free(env);
  10259. return NULL;
  10260. }
  10261. if (wcslen(env) != (size_t)size) {
  10262. PyErr_SetString(PyExc_ValueError,
  10263. "embedded null character");
  10264. PyMem_Free(env);
  10265. return NULL;
  10266. }
  10267. /* _wputenv() and SetEnvironmentVariableW() update the environment in the
  10268. Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
  10269. and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
  10270. Prefer _wputenv() to be compatible with C libraries using CRT
  10271. variables and CRT functions using these variables (ex: getenv()). */
  10272. int err = _wputenv(env);
  10273. if (err) {
  10274. posix_error();
  10275. PyMem_Free(env);
  10276. return NULL;
  10277. }
  10278. PyMem_Free(env);
  10279. Py_RETURN_NONE;
  10280. }
  10281. #endif
  10282. #ifdef MS_WINDOWS
  10283. /*[clinic input]
  10284. os.putenv
  10285. name: unicode
  10286. value: unicode
  10287. /
  10288. Change or add an environment variable.
  10289. [clinic start generated code]*/
  10290. static PyObject *
  10291. os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
  10292. /*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
  10293. {
  10294. if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
  10295. return NULL;
  10296. }
  10297. return win32_putenv(name, value);
  10298. }
  10299. #else
  10300. /*[clinic input]
  10301. os.putenv
  10302. name: FSConverter
  10303. value: FSConverter
  10304. /
  10305. Change or add an environment variable.
  10306. [clinic start generated code]*/
  10307. static PyObject *
  10308. os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
  10309. /*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
  10310. {
  10311. const char *name_string = PyBytes_AS_STRING(name);
  10312. const char *value_string = PyBytes_AS_STRING(value);
  10313. if (strchr(name_string, '=') != NULL) {
  10314. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  10315. return NULL;
  10316. }
  10317. if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
  10318. return NULL;
  10319. }
  10320. if (setenv(name_string, value_string, 1)) {
  10321. return posix_error();
  10322. }
  10323. Py_RETURN_NONE;
  10324. }
  10325. #endif /* !defined(MS_WINDOWS) */
  10326. #ifdef MS_WINDOWS
  10327. /*[clinic input]
  10328. os.unsetenv
  10329. name: unicode
  10330. /
  10331. Delete an environment variable.
  10332. [clinic start generated code]*/
  10333. static PyObject *
  10334. os_unsetenv_impl(PyObject *module, PyObject *name)
  10335. /*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
  10336. {
  10337. if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
  10338. return NULL;
  10339. }
  10340. return win32_putenv(name, NULL);
  10341. }
  10342. #else
  10343. /*[clinic input]
  10344. os.unsetenv
  10345. name: FSConverter
  10346. /
  10347. Delete an environment variable.
  10348. [clinic start generated code]*/
  10349. static PyObject *
  10350. os_unsetenv_impl(PyObject *module, PyObject *name)
  10351. /*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
  10352. {
  10353. if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
  10354. return NULL;
  10355. }
  10356. #ifdef HAVE_BROKEN_UNSETENV
  10357. unsetenv(PyBytes_AS_STRING(name));
  10358. #else
  10359. int err = unsetenv(PyBytes_AS_STRING(name));
  10360. if (err) {
  10361. return posix_error();
  10362. }
  10363. #endif
  10364. Py_RETURN_NONE;
  10365. }
  10366. #endif /* !MS_WINDOWS */
  10367. /*[clinic input]
  10368. os.strerror
  10369. code: int
  10370. /
  10371. Translate an error code to a message string.
  10372. [clinic start generated code]*/
  10373. static PyObject *
  10374. os_strerror_impl(PyObject *module, int code)
  10375. /*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
  10376. {
  10377. char *message = strerror(code);
  10378. if (message == NULL) {
  10379. PyErr_SetString(PyExc_ValueError,
  10380. "strerror() argument out of range");
  10381. return NULL;
  10382. }
  10383. return PyUnicode_DecodeLocale(message, "surrogateescape");
  10384. }
  10385. #ifdef HAVE_SYS_WAIT_H
  10386. #ifdef WCOREDUMP
  10387. /*[clinic input]
  10388. os.WCOREDUMP -> bool
  10389. status: int
  10390. /
  10391. Return True if the process returning status was dumped to a core file.
  10392. [clinic start generated code]*/
  10393. static int
  10394. os_WCOREDUMP_impl(PyObject *module, int status)
  10395. /*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
  10396. {
  10397. WAIT_TYPE wait_status;
  10398. WAIT_STATUS_INT(wait_status) = status;
  10399. return WCOREDUMP(wait_status);
  10400. }
  10401. #endif /* WCOREDUMP */
  10402. #ifdef WIFCONTINUED
  10403. /*[clinic input]
  10404. os.WIFCONTINUED -> bool
  10405. status: int
  10406. Return True if a particular process was continued from a job control stop.
  10407. Return True if the process returning status was continued from a
  10408. job control stop.
  10409. [clinic start generated code]*/
  10410. static int
  10411. os_WIFCONTINUED_impl(PyObject *module, int status)
  10412. /*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
  10413. {
  10414. WAIT_TYPE wait_status;
  10415. WAIT_STATUS_INT(wait_status) = status;
  10416. return WIFCONTINUED(wait_status);
  10417. }
  10418. #endif /* WIFCONTINUED */
  10419. #ifdef WIFSTOPPED
  10420. /*[clinic input]
  10421. os.WIFSTOPPED -> bool
  10422. status: int
  10423. Return True if the process returning status was stopped.
  10424. [clinic start generated code]*/
  10425. static int
  10426. os_WIFSTOPPED_impl(PyObject *module, int status)
  10427. /*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
  10428. {
  10429. WAIT_TYPE wait_status;
  10430. WAIT_STATUS_INT(wait_status) = status;
  10431. return WIFSTOPPED(wait_status);
  10432. }
  10433. #endif /* WIFSTOPPED */
  10434. #ifdef WIFSIGNALED
  10435. /*[clinic input]
  10436. os.WIFSIGNALED -> bool
  10437. status: int
  10438. Return True if the process returning status was terminated by a signal.
  10439. [clinic start generated code]*/
  10440. static int
  10441. os_WIFSIGNALED_impl(PyObject *module, int status)
  10442. /*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
  10443. {
  10444. WAIT_TYPE wait_status;
  10445. WAIT_STATUS_INT(wait_status) = status;
  10446. return WIFSIGNALED(wait_status);
  10447. }
  10448. #endif /* WIFSIGNALED */
  10449. #ifdef WIFEXITED
  10450. /*[clinic input]
  10451. os.WIFEXITED -> bool
  10452. status: int
  10453. Return True if the process returning status exited via the exit() system call.
  10454. [clinic start generated code]*/
  10455. static int
  10456. os_WIFEXITED_impl(PyObject *module, int status)
  10457. /*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
  10458. {
  10459. WAIT_TYPE wait_status;
  10460. WAIT_STATUS_INT(wait_status) = status;
  10461. return WIFEXITED(wait_status);
  10462. }
  10463. #endif /* WIFEXITED */
  10464. #ifdef WEXITSTATUS
  10465. /*[clinic input]
  10466. os.WEXITSTATUS -> int
  10467. status: int
  10468. Return the process return code from status.
  10469. [clinic start generated code]*/
  10470. static int
  10471. os_WEXITSTATUS_impl(PyObject *module, int status)
  10472. /*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
  10473. {
  10474. WAIT_TYPE wait_status;
  10475. WAIT_STATUS_INT(wait_status) = status;
  10476. return WEXITSTATUS(wait_status);
  10477. }
  10478. #endif /* WEXITSTATUS */
  10479. #ifdef WTERMSIG
  10480. /*[clinic input]
  10481. os.WTERMSIG -> int
  10482. status: int
  10483. Return the signal that terminated the process that provided the status value.
  10484. [clinic start generated code]*/
  10485. static int
  10486. os_WTERMSIG_impl(PyObject *module, int status)
  10487. /*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
  10488. {
  10489. WAIT_TYPE wait_status;
  10490. WAIT_STATUS_INT(wait_status) = status;
  10491. return WTERMSIG(wait_status);
  10492. }
  10493. #endif /* WTERMSIG */
  10494. #ifdef WSTOPSIG
  10495. /*[clinic input]
  10496. os.WSTOPSIG -> int
  10497. status: int
  10498. Return the signal that stopped the process that provided the status value.
  10499. [clinic start generated code]*/
  10500. static int
  10501. os_WSTOPSIG_impl(PyObject *module, int status)
  10502. /*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
  10503. {
  10504. WAIT_TYPE wait_status;
  10505. WAIT_STATUS_INT(wait_status) = status;
  10506. return WSTOPSIG(wait_status);
  10507. }
  10508. #endif /* WSTOPSIG */
  10509. #endif /* HAVE_SYS_WAIT_H */
  10510. #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
  10511. #ifdef _SCO_DS
  10512. /* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
  10513. needed definitions in sys/statvfs.h */
  10514. #define _SVID3
  10515. #endif
  10516. #include <sys/statvfs.h>
  10517. static PyObject*
  10518. _pystatvfs_fromstructstatvfs(PyObject *module, struct statvfs st) {
  10519. PyObject *StatVFSResultType = get_posix_state(module)->StatVFSResultType;
  10520. PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
  10521. if (v == NULL)
  10522. return NULL;
  10523. int pos = 0;
  10524. #define SET_RESULT(CALL) \
  10525. do { \
  10526. PyObject *item = (CALL); \
  10527. if (item == NULL) { \
  10528. Py_DECREF(v); \
  10529. return NULL; \
  10530. } \
  10531. PyStructSequence_SET_ITEM(v, pos++, item); \
  10532. } while(0)
  10533. #if !defined(HAVE_LARGEFILE_SUPPORT)
  10534. SET_RESULT(PyLong_FromLong((long) st.f_bsize));
  10535. SET_RESULT(PyLong_FromLong((long) st.f_frsize));
  10536. SET_RESULT(PyLong_FromLong((long) st.f_blocks));
  10537. SET_RESULT(PyLong_FromLong((long) st.f_bfree));
  10538. SET_RESULT(PyLong_FromLong((long) st.f_bavail));
  10539. SET_RESULT(PyLong_FromLong((long) st.f_files));
  10540. SET_RESULT(PyLong_FromLong((long) st.f_ffree));
  10541. SET_RESULT(PyLong_FromLong((long) st.f_favail));
  10542. SET_RESULT(PyLong_FromLong((long) st.f_flag));
  10543. SET_RESULT(PyLong_FromLong((long) st.f_namemax));
  10544. #else
  10545. SET_RESULT(PyLong_FromLong((long) st.f_bsize));
  10546. SET_RESULT(PyLong_FromLong((long) st.f_frsize));
  10547. SET_RESULT(PyLong_FromLongLong((long long) st.f_blocks));
  10548. SET_RESULT(PyLong_FromLongLong((long long) st.f_bfree));
  10549. SET_RESULT(PyLong_FromLongLong((long long) st.f_bavail));
  10550. SET_RESULT(PyLong_FromLongLong((long long) st.f_files));
  10551. SET_RESULT(PyLong_FromLongLong((long long) st.f_ffree));
  10552. SET_RESULT(PyLong_FromLongLong((long long) st.f_favail));
  10553. SET_RESULT(PyLong_FromLong((long) st.f_flag));
  10554. SET_RESULT(PyLong_FromLong((long) st.f_namemax));
  10555. #endif
  10556. /* The _ALL_SOURCE feature test macro defines f_fsid as a structure
  10557. * (issue #32390). */
  10558. #if defined(_AIX) && defined(_ALL_SOURCE)
  10559. SET_RESULT(PyLong_FromUnsignedLong(st.f_fsid.val[0]));
  10560. #else
  10561. SET_RESULT(PyLong_FromUnsignedLong(st.f_fsid));
  10562. #endif
  10563. #undef SET_RESULT
  10564. return v;
  10565. }
  10566. /*[clinic input]
  10567. os.fstatvfs
  10568. fd: int
  10569. /
  10570. Perform an fstatvfs system call on the given fd.
  10571. Equivalent to statvfs(fd).
  10572. [clinic start generated code]*/
  10573. static PyObject *
  10574. os_fstatvfs_impl(PyObject *module, int fd)
  10575. /*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
  10576. {
  10577. int result;
  10578. int async_err = 0;
  10579. struct statvfs st;
  10580. do {
  10581. Py_BEGIN_ALLOW_THREADS
  10582. result = fstatvfs(fd, &st);
  10583. Py_END_ALLOW_THREADS
  10584. } while (result != 0 && errno == EINTR &&
  10585. !(async_err = PyErr_CheckSignals()));
  10586. if (result != 0)
  10587. return (!async_err) ? posix_error() : NULL;
  10588. return _pystatvfs_fromstructstatvfs(module, st);
  10589. }
  10590. #endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
  10591. #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
  10592. #include <sys/statvfs.h>
  10593. /*[clinic input]
  10594. os.statvfs
  10595. path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
  10596. Perform a statvfs system call on the given path.
  10597. path may always be specified as a string.
  10598. On some platforms, path may also be specified as an open file descriptor.
  10599. If this functionality is unavailable, using it raises an exception.
  10600. [clinic start generated code]*/
  10601. static PyObject *
  10602. os_statvfs_impl(PyObject *module, path_t *path)
  10603. /*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
  10604. {
  10605. int result;
  10606. struct statvfs st;
  10607. Py_BEGIN_ALLOW_THREADS
  10608. #ifdef HAVE_FSTATVFS
  10609. if (path->fd != -1) {
  10610. result = fstatvfs(path->fd, &st);
  10611. }
  10612. else
  10613. #endif
  10614. result = statvfs(path->narrow, &st);
  10615. Py_END_ALLOW_THREADS
  10616. if (result) {
  10617. return path_error(path);
  10618. }
  10619. return _pystatvfs_fromstructstatvfs(module, st);
  10620. }
  10621. #endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
  10622. #ifdef MS_WINDOWS
  10623. /*[clinic input]
  10624. os._getdiskusage
  10625. path: path_t
  10626. Return disk usage statistics about the given path as a (total, free) tuple.
  10627. [clinic start generated code]*/
  10628. static PyObject *
  10629. os__getdiskusage_impl(PyObject *module, path_t *path)
  10630. /*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
  10631. {
  10632. BOOL retval;
  10633. ULARGE_INTEGER _, total, free;
  10634. DWORD err = 0;
  10635. Py_BEGIN_ALLOW_THREADS
  10636. retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
  10637. Py_END_ALLOW_THREADS
  10638. if (retval == 0) {
  10639. if (GetLastError() == ERROR_DIRECTORY) {
  10640. wchar_t *dir_path = NULL;
  10641. dir_path = PyMem_New(wchar_t, path->length + 1);
  10642. if (dir_path == NULL) {
  10643. return PyErr_NoMemory();
  10644. }
  10645. wcscpy_s(dir_path, path->length + 1, path->wide);
  10646. if (_dirnameW(dir_path) != -1) {
  10647. Py_BEGIN_ALLOW_THREADS
  10648. retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
  10649. Py_END_ALLOW_THREADS
  10650. }
  10651. /* Record the last error in case it's modified by PyMem_Free. */
  10652. err = GetLastError();
  10653. PyMem_Free(dir_path);
  10654. if (retval) {
  10655. goto success;
  10656. }
  10657. }
  10658. return PyErr_SetFromWindowsErr(err);
  10659. }
  10660. success:
  10661. return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
  10662. }
  10663. #endif /* MS_WINDOWS */
  10664. /* This is used for fpathconf(), pathconf(), confstr() and sysconf().
  10665. * It maps strings representing configuration variable names to
  10666. * integer values, allowing those functions to be called with the
  10667. * magic names instead of polluting the module's namespace with tons of
  10668. * rarely-used constants. There are three separate tables that use
  10669. * these definitions.
  10670. *
  10671. * This code is always included, even if none of the interfaces that
  10672. * need it are included. The #if hackery needed to avoid it would be
  10673. * sufficiently pervasive that it's not worth the loss of readability.
  10674. */
  10675. struct constdef {
  10676. const char *name;
  10677. int value;
  10678. };
  10679. static int
  10680. conv_confname(PyObject *arg, int *valuep, struct constdef *table,
  10681. size_t tablesize)
  10682. {
  10683. if (PyLong_Check(arg)) {
  10684. int value = _PyLong_AsInt(arg);
  10685. if (value == -1 && PyErr_Occurred())
  10686. return 0;
  10687. *valuep = value;
  10688. return 1;
  10689. }
  10690. else {
  10691. /* look up the value in the table using a binary search */
  10692. size_t lo = 0;
  10693. size_t mid;
  10694. size_t hi = tablesize;
  10695. int cmp;
  10696. const char *confname;
  10697. if (!PyUnicode_Check(arg)) {
  10698. PyErr_SetString(PyExc_TypeError,
  10699. "configuration names must be strings or integers");
  10700. return 0;
  10701. }
  10702. confname = PyUnicode_AsUTF8(arg);
  10703. if (confname == NULL)
  10704. return 0;
  10705. while (lo < hi) {
  10706. mid = (lo + hi) / 2;
  10707. cmp = strcmp(confname, table[mid].name);
  10708. if (cmp < 0)
  10709. hi = mid;
  10710. else if (cmp > 0)
  10711. lo = mid + 1;
  10712. else {
  10713. *valuep = table[mid].value;
  10714. return 1;
  10715. }
  10716. }
  10717. PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
  10718. return 0;
  10719. }
  10720. }
  10721. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  10722. static struct constdef posix_constants_pathconf[] = {
  10723. #ifdef _PC_ABI_AIO_XFER_MAX
  10724. {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
  10725. #endif
  10726. #ifdef _PC_ABI_ASYNC_IO
  10727. {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
  10728. #endif
  10729. #ifdef _PC_ASYNC_IO
  10730. {"PC_ASYNC_IO", _PC_ASYNC_IO},
  10731. #endif
  10732. #ifdef _PC_CHOWN_RESTRICTED
  10733. {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
  10734. #endif
  10735. #ifdef _PC_FILESIZEBITS
  10736. {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
  10737. #endif
  10738. #ifdef _PC_LAST
  10739. {"PC_LAST", _PC_LAST},
  10740. #endif
  10741. #ifdef _PC_LINK_MAX
  10742. {"PC_LINK_MAX", _PC_LINK_MAX},
  10743. #endif
  10744. #ifdef _PC_MAX_CANON
  10745. {"PC_MAX_CANON", _PC_MAX_CANON},
  10746. #endif
  10747. #ifdef _PC_MAX_INPUT
  10748. {"PC_MAX_INPUT", _PC_MAX_INPUT},
  10749. #endif
  10750. #ifdef _PC_NAME_MAX
  10751. {"PC_NAME_MAX", _PC_NAME_MAX},
  10752. #endif
  10753. #ifdef _PC_NO_TRUNC
  10754. {"PC_NO_TRUNC", _PC_NO_TRUNC},
  10755. #endif
  10756. #ifdef _PC_PATH_MAX
  10757. {"PC_PATH_MAX", _PC_PATH_MAX},
  10758. #endif
  10759. #ifdef _PC_PIPE_BUF
  10760. {"PC_PIPE_BUF", _PC_PIPE_BUF},
  10761. #endif
  10762. #ifdef _PC_PRIO_IO
  10763. {"PC_PRIO_IO", _PC_PRIO_IO},
  10764. #endif
  10765. #ifdef _PC_SOCK_MAXBUF
  10766. {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
  10767. #endif
  10768. #ifdef _PC_SYNC_IO
  10769. {"PC_SYNC_IO", _PC_SYNC_IO},
  10770. #endif
  10771. #ifdef _PC_VDISABLE
  10772. {"PC_VDISABLE", _PC_VDISABLE},
  10773. #endif
  10774. #ifdef _PC_ACL_ENABLED
  10775. {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
  10776. #endif
  10777. #ifdef _PC_MIN_HOLE_SIZE
  10778. {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
  10779. #endif
  10780. #ifdef _PC_ALLOC_SIZE_MIN
  10781. {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
  10782. #endif
  10783. #ifdef _PC_REC_INCR_XFER_SIZE
  10784. {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
  10785. #endif
  10786. #ifdef _PC_REC_MAX_XFER_SIZE
  10787. {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
  10788. #endif
  10789. #ifdef _PC_REC_MIN_XFER_SIZE
  10790. {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
  10791. #endif
  10792. #ifdef _PC_REC_XFER_ALIGN
  10793. {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
  10794. #endif
  10795. #ifdef _PC_SYMLINK_MAX
  10796. {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
  10797. #endif
  10798. #ifdef _PC_XATTR_ENABLED
  10799. {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
  10800. #endif
  10801. #ifdef _PC_XATTR_EXISTS
  10802. {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
  10803. #endif
  10804. #ifdef _PC_TIMESTAMP_RESOLUTION
  10805. {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
  10806. #endif
  10807. };
  10808. static int
  10809. conv_path_confname(PyObject *arg, int *valuep)
  10810. {
  10811. return conv_confname(arg, valuep, posix_constants_pathconf,
  10812. sizeof(posix_constants_pathconf)
  10813. / sizeof(struct constdef));
  10814. }
  10815. #endif
  10816. #ifdef HAVE_FPATHCONF
  10817. /*[clinic input]
  10818. os.fpathconf -> long
  10819. fd: fildes
  10820. name: path_confname
  10821. /
  10822. Return the configuration limit name for the file descriptor fd.
  10823. If there is no limit, return -1.
  10824. [clinic start generated code]*/
  10825. static long
  10826. os_fpathconf_impl(PyObject *module, int fd, int name)
  10827. /*[clinic end generated code: output=d5b7042425fc3e21 input=5b8d2471cfaae186]*/
  10828. {
  10829. long limit;
  10830. errno = 0;
  10831. limit = fpathconf(fd, name);
  10832. if (limit == -1 && errno != 0)
  10833. posix_error();
  10834. return limit;
  10835. }
  10836. #endif /* HAVE_FPATHCONF */
  10837. #ifdef HAVE_PATHCONF
  10838. /*[clinic input]
  10839. os.pathconf -> long
  10840. path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
  10841. name: path_confname
  10842. Return the configuration limit name for the file or directory path.
  10843. If there is no limit, return -1.
  10844. On some platforms, path may also be specified as an open file descriptor.
  10845. If this functionality is unavailable, using it raises an exception.
  10846. [clinic start generated code]*/
  10847. static long
  10848. os_pathconf_impl(PyObject *module, path_t *path, int name)
  10849. /*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
  10850. {
  10851. long limit;
  10852. errno = 0;
  10853. #ifdef HAVE_FPATHCONF
  10854. if (path->fd != -1)
  10855. limit = fpathconf(path->fd, name);
  10856. else
  10857. #endif
  10858. limit = pathconf(path->narrow, name);
  10859. if (limit == -1 && errno != 0) {
  10860. if (errno == EINVAL)
  10861. /* could be a path or name problem */
  10862. posix_error();
  10863. else
  10864. path_error(path);
  10865. }
  10866. return limit;
  10867. }
  10868. #endif /* HAVE_PATHCONF */
  10869. #ifdef HAVE_CONFSTR
  10870. static struct constdef posix_constants_confstr[] = {
  10871. #ifdef _CS_ARCHITECTURE
  10872. {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
  10873. #endif
  10874. #ifdef _CS_GNU_LIBC_VERSION
  10875. {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
  10876. #endif
  10877. #ifdef _CS_GNU_LIBPTHREAD_VERSION
  10878. {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
  10879. #endif
  10880. #ifdef _CS_HOSTNAME
  10881. {"CS_HOSTNAME", _CS_HOSTNAME},
  10882. #endif
  10883. #ifdef _CS_HW_PROVIDER
  10884. {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
  10885. #endif
  10886. #ifdef _CS_HW_SERIAL
  10887. {"CS_HW_SERIAL", _CS_HW_SERIAL},
  10888. #endif
  10889. #ifdef _CS_INITTAB_NAME
  10890. {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
  10891. #endif
  10892. #ifdef _CS_LFS64_CFLAGS
  10893. {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
  10894. #endif
  10895. #ifdef _CS_LFS64_LDFLAGS
  10896. {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
  10897. #endif
  10898. #ifdef _CS_LFS64_LIBS
  10899. {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
  10900. #endif
  10901. #ifdef _CS_LFS64_LINTFLAGS
  10902. {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
  10903. #endif
  10904. #ifdef _CS_LFS_CFLAGS
  10905. {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
  10906. #endif
  10907. #ifdef _CS_LFS_LDFLAGS
  10908. {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
  10909. #endif
  10910. #ifdef _CS_LFS_LIBS
  10911. {"CS_LFS_LIBS", _CS_LFS_LIBS},
  10912. #endif
  10913. #ifdef _CS_LFS_LINTFLAGS
  10914. {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
  10915. #endif
  10916. #ifdef _CS_MACHINE
  10917. {"CS_MACHINE", _CS_MACHINE},
  10918. #endif
  10919. #ifdef _CS_PATH
  10920. {"CS_PATH", _CS_PATH},
  10921. #endif
  10922. #ifdef _CS_RELEASE
  10923. {"CS_RELEASE", _CS_RELEASE},
  10924. #endif
  10925. #ifdef _CS_SRPC_DOMAIN
  10926. {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
  10927. #endif
  10928. #ifdef _CS_SYSNAME
  10929. {"CS_SYSNAME", _CS_SYSNAME},
  10930. #endif
  10931. #ifdef _CS_VERSION
  10932. {"CS_VERSION", _CS_VERSION},
  10933. #endif
  10934. #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
  10935. {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
  10936. #endif
  10937. #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
  10938. {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
  10939. #endif
  10940. #ifdef _CS_XBS5_ILP32_OFF32_LIBS
  10941. {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
  10942. #endif
  10943. #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
  10944. {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
  10945. #endif
  10946. #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
  10947. {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
  10948. #endif
  10949. #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
  10950. {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
  10951. #endif
  10952. #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
  10953. {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
  10954. #endif
  10955. #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
  10956. {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
  10957. #endif
  10958. #ifdef _CS_XBS5_LP64_OFF64_CFLAGS
  10959. {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
  10960. #endif
  10961. #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
  10962. {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
  10963. #endif
  10964. #ifdef _CS_XBS5_LP64_OFF64_LIBS
  10965. {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
  10966. #endif
  10967. #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
  10968. {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
  10969. #endif
  10970. #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
  10971. {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
  10972. #endif
  10973. #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
  10974. {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
  10975. #endif
  10976. #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
  10977. {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
  10978. #endif
  10979. #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
  10980. {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
  10981. #endif
  10982. #ifdef _MIPS_CS_AVAIL_PROCESSORS
  10983. {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
  10984. #endif
  10985. #ifdef _MIPS_CS_BASE
  10986. {"MIPS_CS_BASE", _MIPS_CS_BASE},
  10987. #endif
  10988. #ifdef _MIPS_CS_HOSTID
  10989. {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
  10990. #endif
  10991. #ifdef _MIPS_CS_HW_NAME
  10992. {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
  10993. #endif
  10994. #ifdef _MIPS_CS_NUM_PROCESSORS
  10995. {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
  10996. #endif
  10997. #ifdef _MIPS_CS_OSREL_MAJ
  10998. {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
  10999. #endif
  11000. #ifdef _MIPS_CS_OSREL_MIN
  11001. {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
  11002. #endif
  11003. #ifdef _MIPS_CS_OSREL_PATCH
  11004. {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
  11005. #endif
  11006. #ifdef _MIPS_CS_OS_NAME
  11007. {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
  11008. #endif
  11009. #ifdef _MIPS_CS_OS_PROVIDER
  11010. {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
  11011. #endif
  11012. #ifdef _MIPS_CS_PROCESSORS
  11013. {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
  11014. #endif
  11015. #ifdef _MIPS_CS_SERIAL
  11016. {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
  11017. #endif
  11018. #ifdef _MIPS_CS_VENDOR
  11019. {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
  11020. #endif
  11021. };
  11022. static int
  11023. conv_confstr_confname(PyObject *arg, int *valuep)
  11024. {
  11025. return conv_confname(arg, valuep, posix_constants_confstr,
  11026. sizeof(posix_constants_confstr)
  11027. / sizeof(struct constdef));
  11028. }
  11029. /*[clinic input]
  11030. os.confstr
  11031. name: confstr_confname
  11032. /
  11033. Return a string-valued system configuration variable.
  11034. [clinic start generated code]*/
  11035. static PyObject *
  11036. os_confstr_impl(PyObject *module, int name)
  11037. /*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
  11038. {
  11039. PyObject *result = NULL;
  11040. char buffer[255];
  11041. size_t len;
  11042. errno = 0;
  11043. len = confstr(name, buffer, sizeof(buffer));
  11044. if (len == 0) {
  11045. if (errno) {
  11046. posix_error();
  11047. return NULL;
  11048. }
  11049. else {
  11050. Py_RETURN_NONE;
  11051. }
  11052. }
  11053. if (len >= sizeof(buffer)) {
  11054. size_t len2;
  11055. char *buf = PyMem_Malloc(len);
  11056. if (buf == NULL)
  11057. return PyErr_NoMemory();
  11058. len2 = confstr(name, buf, len);
  11059. assert(len == len2);
  11060. result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
  11061. PyMem_Free(buf);
  11062. }
  11063. else
  11064. result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
  11065. return result;
  11066. }
  11067. #endif /* HAVE_CONFSTR */
  11068. #ifdef HAVE_SYSCONF
  11069. static struct constdef posix_constants_sysconf[] = {
  11070. #ifdef _SC_2_CHAR_TERM
  11071. {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
  11072. #endif
  11073. #ifdef _SC_2_C_BIND
  11074. {"SC_2_C_BIND", _SC_2_C_BIND},
  11075. #endif
  11076. #ifdef _SC_2_C_DEV
  11077. {"SC_2_C_DEV", _SC_2_C_DEV},
  11078. #endif
  11079. #ifdef _SC_2_C_VERSION
  11080. {"SC_2_C_VERSION", _SC_2_C_VERSION},
  11081. #endif
  11082. #ifdef _SC_2_FORT_DEV
  11083. {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
  11084. #endif
  11085. #ifdef _SC_2_FORT_RUN
  11086. {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
  11087. #endif
  11088. #ifdef _SC_2_LOCALEDEF
  11089. {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
  11090. #endif
  11091. #ifdef _SC_2_SW_DEV
  11092. {"SC_2_SW_DEV", _SC_2_SW_DEV},
  11093. #endif
  11094. #ifdef _SC_2_UPE
  11095. {"SC_2_UPE", _SC_2_UPE},
  11096. #endif
  11097. #ifdef _SC_2_VERSION
  11098. {"SC_2_VERSION", _SC_2_VERSION},
  11099. #endif
  11100. #ifdef _SC_ABI_ASYNCHRONOUS_IO
  11101. {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
  11102. #endif
  11103. #ifdef _SC_ACL
  11104. {"SC_ACL", _SC_ACL},
  11105. #endif
  11106. #ifdef _SC_AIO_LISTIO_MAX
  11107. {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
  11108. #endif
  11109. #ifdef _SC_AIO_MAX
  11110. {"SC_AIO_MAX", _SC_AIO_MAX},
  11111. #endif
  11112. #ifdef _SC_AIO_PRIO_DELTA_MAX
  11113. {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
  11114. #endif
  11115. #ifdef _SC_ARG_MAX
  11116. {"SC_ARG_MAX", _SC_ARG_MAX},
  11117. #endif
  11118. #ifdef _SC_ASYNCHRONOUS_IO
  11119. {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
  11120. #endif
  11121. #ifdef _SC_ATEXIT_MAX
  11122. {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
  11123. #endif
  11124. #ifdef _SC_AUDIT
  11125. {"SC_AUDIT", _SC_AUDIT},
  11126. #endif
  11127. #ifdef _SC_AVPHYS_PAGES
  11128. {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
  11129. #endif
  11130. #ifdef _SC_BC_BASE_MAX
  11131. {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
  11132. #endif
  11133. #ifdef _SC_BC_DIM_MAX
  11134. {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
  11135. #endif
  11136. #ifdef _SC_BC_SCALE_MAX
  11137. {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
  11138. #endif
  11139. #ifdef _SC_BC_STRING_MAX
  11140. {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
  11141. #endif
  11142. #ifdef _SC_CAP
  11143. {"SC_CAP", _SC_CAP},
  11144. #endif
  11145. #ifdef _SC_CHARCLASS_NAME_MAX
  11146. {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
  11147. #endif
  11148. #ifdef _SC_CHAR_BIT
  11149. {"SC_CHAR_BIT", _SC_CHAR_BIT},
  11150. #endif
  11151. #ifdef _SC_CHAR_MAX
  11152. {"SC_CHAR_MAX", _SC_CHAR_MAX},
  11153. #endif
  11154. #ifdef _SC_CHAR_MIN
  11155. {"SC_CHAR_MIN", _SC_CHAR_MIN},
  11156. #endif
  11157. #ifdef _SC_CHILD_MAX
  11158. {"SC_CHILD_MAX", _SC_CHILD_MAX},
  11159. #endif
  11160. #ifdef _SC_CLK_TCK
  11161. {"SC_CLK_TCK", _SC_CLK_TCK},
  11162. #endif
  11163. #ifdef _SC_COHER_BLKSZ
  11164. {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
  11165. #endif
  11166. #ifdef _SC_COLL_WEIGHTS_MAX
  11167. {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
  11168. #endif
  11169. #ifdef _SC_DCACHE_ASSOC
  11170. {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
  11171. #endif
  11172. #ifdef _SC_DCACHE_BLKSZ
  11173. {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
  11174. #endif
  11175. #ifdef _SC_DCACHE_LINESZ
  11176. {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
  11177. #endif
  11178. #ifdef _SC_DCACHE_SZ
  11179. {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
  11180. #endif
  11181. #ifdef _SC_DCACHE_TBLKSZ
  11182. {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
  11183. #endif
  11184. #ifdef _SC_DELAYTIMER_MAX
  11185. {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
  11186. #endif
  11187. #ifdef _SC_EQUIV_CLASS_MAX
  11188. {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
  11189. #endif
  11190. #ifdef _SC_EXPR_NEST_MAX
  11191. {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
  11192. #endif
  11193. #ifdef _SC_FSYNC
  11194. {"SC_FSYNC", _SC_FSYNC},
  11195. #endif
  11196. #ifdef _SC_GETGR_R_SIZE_MAX
  11197. {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
  11198. #endif
  11199. #ifdef _SC_GETPW_R_SIZE_MAX
  11200. {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
  11201. #endif
  11202. #ifdef _SC_ICACHE_ASSOC
  11203. {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
  11204. #endif
  11205. #ifdef _SC_ICACHE_BLKSZ
  11206. {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
  11207. #endif
  11208. #ifdef _SC_ICACHE_LINESZ
  11209. {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
  11210. #endif
  11211. #ifdef _SC_ICACHE_SZ
  11212. {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
  11213. #endif
  11214. #ifdef _SC_INF
  11215. {"SC_INF", _SC_INF},
  11216. #endif
  11217. #ifdef _SC_INT_MAX
  11218. {"SC_INT_MAX", _SC_INT_MAX},
  11219. #endif
  11220. #ifdef _SC_INT_MIN
  11221. {"SC_INT_MIN", _SC_INT_MIN},
  11222. #endif
  11223. #ifdef _SC_IOV_MAX
  11224. {"SC_IOV_MAX", _SC_IOV_MAX},
  11225. #endif
  11226. #ifdef _SC_IP_SECOPTS
  11227. {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
  11228. #endif
  11229. #ifdef _SC_JOB_CONTROL
  11230. {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
  11231. #endif
  11232. #ifdef _SC_KERN_POINTERS
  11233. {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
  11234. #endif
  11235. #ifdef _SC_KERN_SIM
  11236. {"SC_KERN_SIM", _SC_KERN_SIM},
  11237. #endif
  11238. #ifdef _SC_LINE_MAX
  11239. {"SC_LINE_MAX", _SC_LINE_MAX},
  11240. #endif
  11241. #ifdef _SC_LOGIN_NAME_MAX
  11242. {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
  11243. #endif
  11244. #ifdef _SC_LOGNAME_MAX
  11245. {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
  11246. #endif
  11247. #ifdef _SC_LONG_BIT
  11248. {"SC_LONG_BIT", _SC_LONG_BIT},
  11249. #endif
  11250. #ifdef _SC_MAC
  11251. {"SC_MAC", _SC_MAC},
  11252. #endif
  11253. #ifdef _SC_MAPPED_FILES
  11254. {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
  11255. #endif
  11256. #ifdef _SC_MAXPID
  11257. {"SC_MAXPID", _SC_MAXPID},
  11258. #endif
  11259. #ifdef _SC_MB_LEN_MAX
  11260. {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
  11261. #endif
  11262. #ifdef _SC_MEMLOCK
  11263. {"SC_MEMLOCK", _SC_MEMLOCK},
  11264. #endif
  11265. #ifdef _SC_MEMLOCK_RANGE
  11266. {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
  11267. #endif
  11268. #ifdef _SC_MEMORY_PROTECTION
  11269. {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
  11270. #endif
  11271. #ifdef _SC_MESSAGE_PASSING
  11272. {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
  11273. #endif
  11274. #ifdef _SC_MMAP_FIXED_ALIGNMENT
  11275. {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
  11276. #endif
  11277. #ifdef _SC_MQ_OPEN_MAX
  11278. {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
  11279. #endif
  11280. #ifdef _SC_MQ_PRIO_MAX
  11281. {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
  11282. #endif
  11283. #ifdef _SC_NACLS_MAX
  11284. {"SC_NACLS_MAX", _SC_NACLS_MAX},
  11285. #endif
  11286. #ifdef _SC_NGROUPS_MAX
  11287. {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
  11288. #endif
  11289. #ifdef _SC_NL_ARGMAX
  11290. {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
  11291. #endif
  11292. #ifdef _SC_NL_LANGMAX
  11293. {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
  11294. #endif
  11295. #ifdef _SC_NL_MSGMAX
  11296. {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
  11297. #endif
  11298. #ifdef _SC_NL_NMAX
  11299. {"SC_NL_NMAX", _SC_NL_NMAX},
  11300. #endif
  11301. #ifdef _SC_NL_SETMAX
  11302. {"SC_NL_SETMAX", _SC_NL_SETMAX},
  11303. #endif
  11304. #ifdef _SC_NL_TEXTMAX
  11305. {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
  11306. #endif
  11307. #ifdef _SC_NPROCESSORS_CONF
  11308. {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
  11309. #endif
  11310. #ifdef _SC_NPROCESSORS_ONLN
  11311. {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
  11312. #endif
  11313. #ifdef _SC_NPROC_CONF
  11314. {"SC_NPROC_CONF", _SC_NPROC_CONF},
  11315. #endif
  11316. #ifdef _SC_NPROC_ONLN
  11317. {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
  11318. #endif
  11319. #ifdef _SC_NZERO
  11320. {"SC_NZERO", _SC_NZERO},
  11321. #endif
  11322. #ifdef _SC_OPEN_MAX
  11323. {"SC_OPEN_MAX", _SC_OPEN_MAX},
  11324. #endif
  11325. #ifdef _SC_PAGESIZE
  11326. {"SC_PAGESIZE", _SC_PAGESIZE},
  11327. #endif
  11328. #ifdef _SC_PAGE_SIZE
  11329. {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
  11330. #endif
  11331. #ifdef _SC_AIX_REALMEM
  11332. {"SC_AIX_REALMEM", _SC_AIX_REALMEM},
  11333. #endif
  11334. #ifdef _SC_PASS_MAX
  11335. {"SC_PASS_MAX", _SC_PASS_MAX},
  11336. #endif
  11337. #ifdef _SC_PHYS_PAGES
  11338. {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
  11339. #endif
  11340. #ifdef _SC_PII
  11341. {"SC_PII", _SC_PII},
  11342. #endif
  11343. #ifdef _SC_PII_INTERNET
  11344. {"SC_PII_INTERNET", _SC_PII_INTERNET},
  11345. #endif
  11346. #ifdef _SC_PII_INTERNET_DGRAM
  11347. {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
  11348. #endif
  11349. #ifdef _SC_PII_INTERNET_STREAM
  11350. {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
  11351. #endif
  11352. #ifdef _SC_PII_OSI
  11353. {"SC_PII_OSI", _SC_PII_OSI},
  11354. #endif
  11355. #ifdef _SC_PII_OSI_CLTS
  11356. {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
  11357. #endif
  11358. #ifdef _SC_PII_OSI_COTS
  11359. {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
  11360. #endif
  11361. #ifdef _SC_PII_OSI_M
  11362. {"SC_PII_OSI_M", _SC_PII_OSI_M},
  11363. #endif
  11364. #ifdef _SC_PII_SOCKET
  11365. {"SC_PII_SOCKET", _SC_PII_SOCKET},
  11366. #endif
  11367. #ifdef _SC_PII_XTI
  11368. {"SC_PII_XTI", _SC_PII_XTI},
  11369. #endif
  11370. #ifdef _SC_POLL
  11371. {"SC_POLL", _SC_POLL},
  11372. #endif
  11373. #ifdef _SC_PRIORITIZED_IO
  11374. {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
  11375. #endif
  11376. #ifdef _SC_PRIORITY_SCHEDULING
  11377. {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
  11378. #endif
  11379. #ifdef _SC_REALTIME_SIGNALS
  11380. {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
  11381. #endif
  11382. #ifdef _SC_RE_DUP_MAX
  11383. {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
  11384. #endif
  11385. #ifdef _SC_RTSIG_MAX
  11386. {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
  11387. #endif
  11388. #ifdef _SC_SAVED_IDS
  11389. {"SC_SAVED_IDS", _SC_SAVED_IDS},
  11390. #endif
  11391. #ifdef _SC_SCHAR_MAX
  11392. {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
  11393. #endif
  11394. #ifdef _SC_SCHAR_MIN
  11395. {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
  11396. #endif
  11397. #ifdef _SC_SELECT
  11398. {"SC_SELECT", _SC_SELECT},
  11399. #endif
  11400. #ifdef _SC_SEMAPHORES
  11401. {"SC_SEMAPHORES", _SC_SEMAPHORES},
  11402. #endif
  11403. #ifdef _SC_SEM_NSEMS_MAX
  11404. {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
  11405. #endif
  11406. #ifdef _SC_SEM_VALUE_MAX
  11407. {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
  11408. #endif
  11409. #ifdef _SC_SHARED_MEMORY_OBJECTS
  11410. {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
  11411. #endif
  11412. #ifdef _SC_SHRT_MAX
  11413. {"SC_SHRT_MAX", _SC_SHRT_MAX},
  11414. #endif
  11415. #ifdef _SC_SHRT_MIN
  11416. {"SC_SHRT_MIN", _SC_SHRT_MIN},
  11417. #endif
  11418. #ifdef _SC_SIGQUEUE_MAX
  11419. {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
  11420. #endif
  11421. #ifdef _SC_SIGRT_MAX
  11422. {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
  11423. #endif
  11424. #ifdef _SC_SIGRT_MIN
  11425. {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
  11426. #endif
  11427. #ifdef _SC_SOFTPOWER
  11428. {"SC_SOFTPOWER", _SC_SOFTPOWER},
  11429. #endif
  11430. #ifdef _SC_SPLIT_CACHE
  11431. {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
  11432. #endif
  11433. #ifdef _SC_SSIZE_MAX
  11434. {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
  11435. #endif
  11436. #ifdef _SC_STACK_PROT
  11437. {"SC_STACK_PROT", _SC_STACK_PROT},
  11438. #endif
  11439. #ifdef _SC_STREAM_MAX
  11440. {"SC_STREAM_MAX", _SC_STREAM_MAX},
  11441. #endif
  11442. #ifdef _SC_SYNCHRONIZED_IO
  11443. {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
  11444. #endif
  11445. #ifdef _SC_THREADS
  11446. {"SC_THREADS", _SC_THREADS},
  11447. #endif
  11448. #ifdef _SC_THREAD_ATTR_STACKADDR
  11449. {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
  11450. #endif
  11451. #ifdef _SC_THREAD_ATTR_STACKSIZE
  11452. {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
  11453. #endif
  11454. #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
  11455. {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
  11456. #endif
  11457. #ifdef _SC_THREAD_KEYS_MAX
  11458. {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
  11459. #endif
  11460. #ifdef _SC_THREAD_PRIORITY_SCHEDULING
  11461. {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
  11462. #endif
  11463. #ifdef _SC_THREAD_PRIO_INHERIT
  11464. {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
  11465. #endif
  11466. #ifdef _SC_THREAD_PRIO_PROTECT
  11467. {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
  11468. #endif
  11469. #ifdef _SC_THREAD_PROCESS_SHARED
  11470. {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
  11471. #endif
  11472. #ifdef _SC_THREAD_SAFE_FUNCTIONS
  11473. {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
  11474. #endif
  11475. #ifdef _SC_THREAD_STACK_MIN
  11476. {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
  11477. #endif
  11478. #ifdef _SC_THREAD_THREADS_MAX
  11479. {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
  11480. #endif
  11481. #ifdef _SC_TIMERS
  11482. {"SC_TIMERS", _SC_TIMERS},
  11483. #endif
  11484. #ifdef _SC_TIMER_MAX
  11485. {"SC_TIMER_MAX", _SC_TIMER_MAX},
  11486. #endif
  11487. #ifdef _SC_TTY_NAME_MAX
  11488. {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
  11489. #endif
  11490. #ifdef _SC_TZNAME_MAX
  11491. {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
  11492. #endif
  11493. #ifdef _SC_T_IOV_MAX
  11494. {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
  11495. #endif
  11496. #ifdef _SC_UCHAR_MAX
  11497. {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
  11498. #endif
  11499. #ifdef _SC_UINT_MAX
  11500. {"SC_UINT_MAX", _SC_UINT_MAX},
  11501. #endif
  11502. #ifdef _SC_UIO_MAXIOV
  11503. {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
  11504. #endif
  11505. #ifdef _SC_ULONG_MAX
  11506. {"SC_ULONG_MAX", _SC_ULONG_MAX},
  11507. #endif
  11508. #ifdef _SC_USHRT_MAX
  11509. {"SC_USHRT_MAX", _SC_USHRT_MAX},
  11510. #endif
  11511. #ifdef _SC_VERSION
  11512. {"SC_VERSION", _SC_VERSION},
  11513. #endif
  11514. #ifdef _SC_WORD_BIT
  11515. {"SC_WORD_BIT", _SC_WORD_BIT},
  11516. #endif
  11517. #ifdef _SC_XBS5_ILP32_OFF32
  11518. {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
  11519. #endif
  11520. #ifdef _SC_XBS5_ILP32_OFFBIG
  11521. {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
  11522. #endif
  11523. #ifdef _SC_XBS5_LP64_OFF64
  11524. {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
  11525. #endif
  11526. #ifdef _SC_XBS5_LPBIG_OFFBIG
  11527. {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
  11528. #endif
  11529. #ifdef _SC_XOPEN_CRYPT
  11530. {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
  11531. #endif
  11532. #ifdef _SC_XOPEN_ENH_I18N
  11533. {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
  11534. #endif
  11535. #ifdef _SC_XOPEN_LEGACY
  11536. {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
  11537. #endif
  11538. #ifdef _SC_XOPEN_REALTIME
  11539. {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
  11540. #endif
  11541. #ifdef _SC_XOPEN_REALTIME_THREADS
  11542. {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
  11543. #endif
  11544. #ifdef _SC_XOPEN_SHM
  11545. {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
  11546. #endif
  11547. #ifdef _SC_XOPEN_UNIX
  11548. {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
  11549. #endif
  11550. #ifdef _SC_XOPEN_VERSION
  11551. {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
  11552. #endif
  11553. #ifdef _SC_XOPEN_XCU_VERSION
  11554. {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
  11555. #endif
  11556. #ifdef _SC_XOPEN_XPG2
  11557. {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
  11558. #endif
  11559. #ifdef _SC_XOPEN_XPG3
  11560. {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
  11561. #endif
  11562. #ifdef _SC_XOPEN_XPG4
  11563. {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
  11564. #endif
  11565. #ifdef _SC_MINSIGSTKSZ
  11566. {"SC_MINSIGSTKSZ", _SC_MINSIGSTKSZ},
  11567. #endif
  11568. };
  11569. static int
  11570. conv_sysconf_confname(PyObject *arg, int *valuep)
  11571. {
  11572. return conv_confname(arg, valuep, posix_constants_sysconf,
  11573. sizeof(posix_constants_sysconf)
  11574. / sizeof(struct constdef));
  11575. }
  11576. /*[clinic input]
  11577. os.sysconf -> long
  11578. name: sysconf_confname
  11579. /
  11580. Return an integer-valued system configuration variable.
  11581. [clinic start generated code]*/
  11582. static long
  11583. os_sysconf_impl(PyObject *module, int name)
  11584. /*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
  11585. {
  11586. long value;
  11587. errno = 0;
  11588. value = sysconf(name);
  11589. if (value == -1 && errno != 0)
  11590. posix_error();
  11591. return value;
  11592. }
  11593. #endif /* HAVE_SYSCONF */
  11594. /* This code is used to ensure that the tables of configuration value names
  11595. * are in sorted order as required by conv_confname(), and also to build
  11596. * the exported dictionaries that are used to publish information about the
  11597. * names available on the host platform.
  11598. *
  11599. * Sorting the table at runtime ensures that the table is properly ordered
  11600. * when used, even for platforms we're not able to test on. It also makes
  11601. * it easier to add additional entries to the tables.
  11602. */
  11603. static int
  11604. cmp_constdefs(const void *v1, const void *v2)
  11605. {
  11606. const struct constdef *c1 =
  11607. (const struct constdef *) v1;
  11608. const struct constdef *c2 =
  11609. (const struct constdef *) v2;
  11610. return strcmp(c1->name, c2->name);
  11611. }
  11612. static int
  11613. setup_confname_table(struct constdef *table, size_t tablesize,
  11614. const char *tablename, PyObject *module)
  11615. {
  11616. PyObject *d = NULL;
  11617. size_t i;
  11618. qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
  11619. d = PyDict_New();
  11620. if (d == NULL)
  11621. return -1;
  11622. for (i=0; i < tablesize; ++i) {
  11623. PyObject *o = PyLong_FromLong(table[i].value);
  11624. if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
  11625. Py_XDECREF(o);
  11626. Py_DECREF(d);
  11627. return -1;
  11628. }
  11629. Py_DECREF(o);
  11630. }
  11631. return _PyModule_Add(module, tablename, d);
  11632. }
  11633. /* Return -1 on failure, 0 on success. */
  11634. static int
  11635. setup_confname_tables(PyObject *module)
  11636. {
  11637. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  11638. if (setup_confname_table(posix_constants_pathconf,
  11639. sizeof(posix_constants_pathconf)
  11640. / sizeof(struct constdef),
  11641. "pathconf_names", module))
  11642. return -1;
  11643. #endif
  11644. #ifdef HAVE_CONFSTR
  11645. if (setup_confname_table(posix_constants_confstr,
  11646. sizeof(posix_constants_confstr)
  11647. / sizeof(struct constdef),
  11648. "confstr_names", module))
  11649. return -1;
  11650. #endif
  11651. #ifdef HAVE_SYSCONF
  11652. if (setup_confname_table(posix_constants_sysconf,
  11653. sizeof(posix_constants_sysconf)
  11654. / sizeof(struct constdef),
  11655. "sysconf_names", module))
  11656. return -1;
  11657. #endif
  11658. return 0;
  11659. }
  11660. /*[clinic input]
  11661. os.abort
  11662. Abort the interpreter immediately.
  11663. This function 'dumps core' or otherwise fails in the hardest way possible
  11664. on the hosting operating system. This function never returns.
  11665. [clinic start generated code]*/
  11666. static PyObject *
  11667. os_abort_impl(PyObject *module)
  11668. /*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
  11669. {
  11670. abort();
  11671. /*NOTREACHED*/
  11672. #ifndef __clang__
  11673. /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
  11674. GCC emits a warning without "return NULL;" (compiler bug?), but Clang
  11675. is smarter and emits a warning on the return. */
  11676. Py_FatalError("abort() called from Python code didn't abort!");
  11677. return NULL;
  11678. #endif
  11679. }
  11680. #ifdef MS_WINDOWS
  11681. /* Grab ShellExecute dynamically from shell32 */
  11682. static int has_ShellExecute = -1;
  11683. static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
  11684. LPCWSTR, INT);
  11685. static int
  11686. check_ShellExecute(void)
  11687. {
  11688. HINSTANCE hShell32;
  11689. /* only recheck */
  11690. if (-1 == has_ShellExecute) {
  11691. Py_BEGIN_ALLOW_THREADS
  11692. /* Security note: this call is not vulnerable to "DLL hijacking".
  11693. SHELL32 is part of "KnownDLLs" and so Windows always load
  11694. the system SHELL32.DLL, even if there is another SHELL32.DLL
  11695. in the DLL search path. */
  11696. hShell32 = LoadLibraryW(L"SHELL32");
  11697. if (hShell32) {
  11698. *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
  11699. "ShellExecuteW");
  11700. has_ShellExecute = Py_ShellExecuteW != NULL;
  11701. } else {
  11702. has_ShellExecute = 0;
  11703. }
  11704. Py_END_ALLOW_THREADS
  11705. }
  11706. return has_ShellExecute;
  11707. }
  11708. /*[clinic input]
  11709. os.startfile
  11710. filepath: path_t
  11711. operation: Py_UNICODE = NULL
  11712. arguments: Py_UNICODE = NULL
  11713. cwd: path_t(nullable=True) = None
  11714. show_cmd: int = 1
  11715. Start a file with its associated application.
  11716. When "operation" is not specified or "open", this acts like
  11717. double-clicking the file in Explorer, or giving the file name as an
  11718. argument to the DOS "start" command: the file is opened with whatever
  11719. application (if any) its extension is associated.
  11720. When another "operation" is given, it specifies what should be done with
  11721. the file. A typical operation is "print".
  11722. "arguments" is passed to the application, but should be omitted if the
  11723. file is a document.
  11724. "cwd" is the working directory for the operation. If "filepath" is
  11725. relative, it will be resolved against this directory. This argument
  11726. should usually be an absolute path.
  11727. "show_cmd" can be used to override the recommended visibility option.
  11728. See the Windows ShellExecute documentation for values.
  11729. startfile returns as soon as the associated application is launched.
  11730. There is no option to wait for the application to close, and no way
  11731. to retrieve the application's exit status.
  11732. The filepath is relative to the current directory. If you want to use
  11733. an absolute path, make sure the first character is not a slash ("/");
  11734. the underlying Win32 ShellExecute function doesn't work if it is.
  11735. [clinic start generated code]*/
  11736. static PyObject *
  11737. os_startfile_impl(PyObject *module, path_t *filepath,
  11738. const Py_UNICODE *operation, const Py_UNICODE *arguments,
  11739. path_t *cwd, int show_cmd)
  11740. /*[clinic end generated code: output=3baa4f9795841880 input=8248997b80669622]*/
  11741. {
  11742. HINSTANCE rc;
  11743. if(!check_ShellExecute()) {
  11744. /* If the OS doesn't have ShellExecute, return a
  11745. NotImplementedError. */
  11746. return PyErr_Format(PyExc_NotImplementedError,
  11747. "startfile not available on this platform");
  11748. }
  11749. if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
  11750. return NULL;
  11751. }
  11752. if (PySys_Audit("os.startfile/2", "OuuOi", filepath->object, operation,
  11753. arguments, cwd->object ? cwd->object : Py_None,
  11754. show_cmd) < 0) {
  11755. return NULL;
  11756. }
  11757. Py_BEGIN_ALLOW_THREADS
  11758. rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
  11759. arguments, cwd->wide, show_cmd);
  11760. Py_END_ALLOW_THREADS
  11761. if (rc <= (HINSTANCE)32) {
  11762. win32_error_object("startfile", filepath->object);
  11763. return NULL;
  11764. }
  11765. Py_RETURN_NONE;
  11766. }
  11767. #endif /* MS_WINDOWS */
  11768. #ifdef HAVE_GETLOADAVG
  11769. /*[clinic input]
  11770. os.getloadavg
  11771. Return average recent system load information.
  11772. Return the number of processes in the system run queue averaged over
  11773. the last 1, 5, and 15 minutes as a tuple of three floats.
  11774. Raises OSError if the load average was unobtainable.
  11775. [clinic start generated code]*/
  11776. static PyObject *
  11777. os_getloadavg_impl(PyObject *module)
  11778. /*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
  11779. {
  11780. double loadavg[3];
  11781. if (getloadavg(loadavg, 3)!=3) {
  11782. PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
  11783. return NULL;
  11784. } else
  11785. return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
  11786. }
  11787. #endif /* HAVE_GETLOADAVG */
  11788. /*[clinic input]
  11789. os.device_encoding
  11790. fd: int
  11791. Return a string describing the encoding of a terminal's file descriptor.
  11792. The file descriptor must be attached to a terminal.
  11793. If the device is not a terminal, return None.
  11794. [clinic start generated code]*/
  11795. static PyObject *
  11796. os_device_encoding_impl(PyObject *module, int fd)
  11797. /*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
  11798. {
  11799. return _Py_device_encoding(fd);
  11800. }
  11801. #ifdef HAVE_SETRESUID
  11802. /*[clinic input]
  11803. os.setresuid
  11804. ruid: uid_t
  11805. euid: uid_t
  11806. suid: uid_t
  11807. /
  11808. Set the current process's real, effective, and saved user ids.
  11809. [clinic start generated code]*/
  11810. static PyObject *
  11811. os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
  11812. /*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
  11813. {
  11814. if (setresuid(ruid, euid, suid) < 0)
  11815. return posix_error();
  11816. Py_RETURN_NONE;
  11817. }
  11818. #endif /* HAVE_SETRESUID */
  11819. #ifdef HAVE_SETRESGID
  11820. /*[clinic input]
  11821. os.setresgid
  11822. rgid: gid_t
  11823. egid: gid_t
  11824. sgid: gid_t
  11825. /
  11826. Set the current process's real, effective, and saved group ids.
  11827. [clinic start generated code]*/
  11828. static PyObject *
  11829. os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
  11830. /*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
  11831. {
  11832. if (setresgid(rgid, egid, sgid) < 0)
  11833. return posix_error();
  11834. Py_RETURN_NONE;
  11835. }
  11836. #endif /* HAVE_SETRESGID */
  11837. #ifdef HAVE_GETRESUID
  11838. /*[clinic input]
  11839. os.getresuid
  11840. Return a tuple of the current process's real, effective, and saved user ids.
  11841. [clinic start generated code]*/
  11842. static PyObject *
  11843. os_getresuid_impl(PyObject *module)
  11844. /*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
  11845. {
  11846. uid_t ruid, euid, suid;
  11847. if (getresuid(&ruid, &euid, &suid) < 0)
  11848. return posix_error();
  11849. return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
  11850. _PyLong_FromUid(euid),
  11851. _PyLong_FromUid(suid));
  11852. }
  11853. #endif /* HAVE_GETRESUID */
  11854. #ifdef HAVE_GETRESGID
  11855. /*[clinic input]
  11856. os.getresgid
  11857. Return a tuple of the current process's real, effective, and saved group ids.
  11858. [clinic start generated code]*/
  11859. static PyObject *
  11860. os_getresgid_impl(PyObject *module)
  11861. /*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
  11862. {
  11863. gid_t rgid, egid, sgid;
  11864. if (getresgid(&rgid, &egid, &sgid) < 0)
  11865. return posix_error();
  11866. return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
  11867. _PyLong_FromGid(egid),
  11868. _PyLong_FromGid(sgid));
  11869. }
  11870. #endif /* HAVE_GETRESGID */
  11871. #ifdef USE_XATTRS
  11872. /*[clinic input]
  11873. os.getxattr
  11874. path: path_t(allow_fd=True)
  11875. attribute: path_t
  11876. *
  11877. follow_symlinks: bool = True
  11878. Return the value of extended attribute attribute on path.
  11879. path may be either a string, a path-like object, or an open file descriptor.
  11880. If follow_symlinks is False, and the last element of the path is a symbolic
  11881. link, getxattr will examine the symbolic link itself instead of the file
  11882. the link points to.
  11883. [clinic start generated code]*/
  11884. static PyObject *
  11885. os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11886. int follow_symlinks)
  11887. /*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
  11888. {
  11889. Py_ssize_t i;
  11890. PyObject *buffer = NULL;
  11891. if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
  11892. return NULL;
  11893. if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
  11894. return NULL;
  11895. }
  11896. for (i = 0; ; i++) {
  11897. void *ptr;
  11898. ssize_t result;
  11899. static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
  11900. Py_ssize_t buffer_size = buffer_sizes[i];
  11901. if (!buffer_size) {
  11902. path_error(path);
  11903. return NULL;
  11904. }
  11905. buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
  11906. if (!buffer)
  11907. return NULL;
  11908. ptr = PyBytes_AS_STRING(buffer);
  11909. Py_BEGIN_ALLOW_THREADS;
  11910. if (path->fd >= 0)
  11911. result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
  11912. else if (follow_symlinks)
  11913. result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
  11914. else
  11915. result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
  11916. Py_END_ALLOW_THREADS;
  11917. if (result < 0) {
  11918. if (errno == ERANGE) {
  11919. Py_DECREF(buffer);
  11920. continue;
  11921. }
  11922. path_error(path);
  11923. Py_DECREF(buffer);
  11924. return NULL;
  11925. }
  11926. if (result != buffer_size) {
  11927. /* Can only shrink. */
  11928. _PyBytes_Resize(&buffer, result);
  11929. }
  11930. break;
  11931. }
  11932. return buffer;
  11933. }
  11934. /*[clinic input]
  11935. os.setxattr
  11936. path: path_t(allow_fd=True)
  11937. attribute: path_t
  11938. value: Py_buffer
  11939. flags: int = 0
  11940. *
  11941. follow_symlinks: bool = True
  11942. Set extended attribute attribute on path to value.
  11943. path may be either a string, a path-like object, or an open file descriptor.
  11944. If follow_symlinks is False, and the last element of the path is a symbolic
  11945. link, setxattr will modify the symbolic link itself instead of the file
  11946. the link points to.
  11947. [clinic start generated code]*/
  11948. static PyObject *
  11949. os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11950. Py_buffer *value, int flags, int follow_symlinks)
  11951. /*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
  11952. {
  11953. ssize_t result;
  11954. if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
  11955. return NULL;
  11956. if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
  11957. value->buf, value->len, flags) < 0) {
  11958. return NULL;
  11959. }
  11960. Py_BEGIN_ALLOW_THREADS;
  11961. if (path->fd > -1)
  11962. result = fsetxattr(path->fd, attribute->narrow,
  11963. value->buf, value->len, flags);
  11964. else if (follow_symlinks)
  11965. result = setxattr(path->narrow, attribute->narrow,
  11966. value->buf, value->len, flags);
  11967. else
  11968. result = lsetxattr(path->narrow, attribute->narrow,
  11969. value->buf, value->len, flags);
  11970. Py_END_ALLOW_THREADS;
  11971. if (result) {
  11972. path_error(path);
  11973. return NULL;
  11974. }
  11975. Py_RETURN_NONE;
  11976. }
  11977. /*[clinic input]
  11978. os.removexattr
  11979. path: path_t(allow_fd=True)
  11980. attribute: path_t
  11981. *
  11982. follow_symlinks: bool = True
  11983. Remove extended attribute attribute on path.
  11984. path may be either a string, a path-like object, or an open file descriptor.
  11985. If follow_symlinks is False, and the last element of the path is a symbolic
  11986. link, removexattr will modify the symbolic link itself instead of the file
  11987. the link points to.
  11988. [clinic start generated code]*/
  11989. static PyObject *
  11990. os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11991. int follow_symlinks)
  11992. /*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
  11993. {
  11994. ssize_t result;
  11995. if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
  11996. return NULL;
  11997. if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
  11998. return NULL;
  11999. }
  12000. Py_BEGIN_ALLOW_THREADS;
  12001. if (path->fd > -1)
  12002. result = fremovexattr(path->fd, attribute->narrow);
  12003. else if (follow_symlinks)
  12004. result = removexattr(path->narrow, attribute->narrow);
  12005. else
  12006. result = lremovexattr(path->narrow, attribute->narrow);
  12007. Py_END_ALLOW_THREADS;
  12008. if (result) {
  12009. return path_error(path);
  12010. }
  12011. Py_RETURN_NONE;
  12012. }
  12013. /*[clinic input]
  12014. os.listxattr
  12015. path: path_t(allow_fd=True, nullable=True) = None
  12016. *
  12017. follow_symlinks: bool = True
  12018. Return a list of extended attributes on path.
  12019. path may be either None, a string, a path-like object, or an open file descriptor.
  12020. if path is None, listxattr will examine the current directory.
  12021. If follow_symlinks is False, and the last element of the path is a symbolic
  12022. link, listxattr will examine the symbolic link itself instead of the file
  12023. the link points to.
  12024. [clinic start generated code]*/
  12025. static PyObject *
  12026. os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
  12027. /*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
  12028. {
  12029. Py_ssize_t i;
  12030. PyObject *result = NULL;
  12031. const char *name;
  12032. char *buffer = NULL;
  12033. if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
  12034. goto exit;
  12035. if (PySys_Audit("os.listxattr", "(O)",
  12036. path->object ? path->object : Py_None) < 0) {
  12037. return NULL;
  12038. }
  12039. name = path->narrow ? path->narrow : ".";
  12040. for (i = 0; ; i++) {
  12041. const char *start, *trace, *end;
  12042. ssize_t length;
  12043. static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
  12044. Py_ssize_t buffer_size = buffer_sizes[i];
  12045. if (!buffer_size) {
  12046. /* ERANGE */
  12047. path_error(path);
  12048. break;
  12049. }
  12050. buffer = PyMem_Malloc(buffer_size);
  12051. if (!buffer) {
  12052. PyErr_NoMemory();
  12053. break;
  12054. }
  12055. Py_BEGIN_ALLOW_THREADS;
  12056. if (path->fd > -1)
  12057. length = flistxattr(path->fd, buffer, buffer_size);
  12058. else if (follow_symlinks)
  12059. length = listxattr(name, buffer, buffer_size);
  12060. else
  12061. length = llistxattr(name, buffer, buffer_size);
  12062. Py_END_ALLOW_THREADS;
  12063. if (length < 0) {
  12064. if (errno == ERANGE) {
  12065. PyMem_Free(buffer);
  12066. buffer = NULL;
  12067. continue;
  12068. }
  12069. path_error(path);
  12070. break;
  12071. }
  12072. result = PyList_New(0);
  12073. if (!result) {
  12074. goto exit;
  12075. }
  12076. end = buffer + length;
  12077. for (trace = start = buffer; trace != end; trace++) {
  12078. if (!*trace) {
  12079. int error;
  12080. PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
  12081. trace - start);
  12082. if (!attribute) {
  12083. Py_SETREF(result, NULL);
  12084. goto exit;
  12085. }
  12086. error = PyList_Append(result, attribute);
  12087. Py_DECREF(attribute);
  12088. if (error) {
  12089. Py_SETREF(result, NULL);
  12090. goto exit;
  12091. }
  12092. start = trace + 1;
  12093. }
  12094. }
  12095. break;
  12096. }
  12097. exit:
  12098. if (buffer)
  12099. PyMem_Free(buffer);
  12100. return result;
  12101. }
  12102. #endif /* USE_XATTRS */
  12103. /*[clinic input]
  12104. os.urandom
  12105. size: Py_ssize_t
  12106. /
  12107. Return a bytes object containing random bytes suitable for cryptographic use.
  12108. [clinic start generated code]*/
  12109. static PyObject *
  12110. os_urandom_impl(PyObject *module, Py_ssize_t size)
  12111. /*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
  12112. {
  12113. PyObject *bytes;
  12114. int result;
  12115. if (size < 0)
  12116. return PyErr_Format(PyExc_ValueError,
  12117. "negative argument not allowed");
  12118. bytes = PyBytes_FromStringAndSize(NULL, size);
  12119. if (bytes == NULL)
  12120. return NULL;
  12121. result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
  12122. if (result == -1) {
  12123. Py_DECREF(bytes);
  12124. return NULL;
  12125. }
  12126. return bytes;
  12127. }
  12128. #ifdef HAVE_MEMFD_CREATE
  12129. /*[clinic input]
  12130. os.memfd_create
  12131. name: FSConverter
  12132. flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
  12133. [clinic start generated code]*/
  12134. static PyObject *
  12135. os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
  12136. /*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
  12137. {
  12138. int fd;
  12139. const char *bytes = PyBytes_AS_STRING(name);
  12140. Py_BEGIN_ALLOW_THREADS
  12141. fd = memfd_create(bytes, flags);
  12142. Py_END_ALLOW_THREADS
  12143. if (fd == -1) {
  12144. return PyErr_SetFromErrno(PyExc_OSError);
  12145. }
  12146. return PyLong_FromLong(fd);
  12147. }
  12148. #endif
  12149. #if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
  12150. /*[clinic input]
  12151. os.eventfd
  12152. initval: unsigned_int
  12153. flags: int(c_default="EFD_CLOEXEC") = EFD_CLOEXEC
  12154. Creates and returns an event notification file descriptor.
  12155. [clinic start generated code]*/
  12156. static PyObject *
  12157. os_eventfd_impl(PyObject *module, unsigned int initval, int flags)
  12158. /*[clinic end generated code: output=ce9c9bbd1446f2de input=66203e3c50c4028b]*/
  12159. {
  12160. /* initval is limited to uint32_t, internal counter is uint64_t */
  12161. int fd;
  12162. Py_BEGIN_ALLOW_THREADS
  12163. fd = eventfd(initval, flags);
  12164. Py_END_ALLOW_THREADS
  12165. if (fd == -1) {
  12166. return PyErr_SetFromErrno(PyExc_OSError);
  12167. }
  12168. return PyLong_FromLong(fd);
  12169. }
  12170. /*[clinic input]
  12171. os.eventfd_read
  12172. fd: fildes
  12173. Read eventfd value
  12174. [clinic start generated code]*/
  12175. static PyObject *
  12176. os_eventfd_read_impl(PyObject *module, int fd)
  12177. /*[clinic end generated code: output=8f2c7b59a3521fd1 input=110f8b57fa596afe]*/
  12178. {
  12179. eventfd_t value;
  12180. int result;
  12181. Py_BEGIN_ALLOW_THREADS
  12182. result = eventfd_read(fd, &value);
  12183. Py_END_ALLOW_THREADS
  12184. if (result == -1) {
  12185. return PyErr_SetFromErrno(PyExc_OSError);
  12186. }
  12187. return PyLong_FromUnsignedLongLong(value);
  12188. }
  12189. /*[clinic input]
  12190. os.eventfd_write
  12191. fd: fildes
  12192. value: unsigned_long_long
  12193. Write eventfd value.
  12194. [clinic start generated code]*/
  12195. static PyObject *
  12196. os_eventfd_write_impl(PyObject *module, int fd, unsigned long long value)
  12197. /*[clinic end generated code: output=bebd9040bbf987f5 input=156de8555be5a949]*/
  12198. {
  12199. int result;
  12200. Py_BEGIN_ALLOW_THREADS
  12201. result = eventfd_write(fd, value);
  12202. Py_END_ALLOW_THREADS
  12203. if (result == -1) {
  12204. return PyErr_SetFromErrno(PyExc_OSError);
  12205. }
  12206. Py_RETURN_NONE;
  12207. }
  12208. #endif /* HAVE_EVENTFD && EFD_CLOEXEC */
  12209. /* Terminal size querying */
  12210. PyDoc_STRVAR(TerminalSize_docstring,
  12211. "A tuple of (columns, lines) for holding terminal window size");
  12212. static PyStructSequence_Field TerminalSize_fields[] = {
  12213. {"columns", "width of the terminal window in characters"},
  12214. {"lines", "height of the terminal window in characters"},
  12215. {NULL, NULL}
  12216. };
  12217. static PyStructSequence_Desc TerminalSize_desc = {
  12218. "os.terminal_size",
  12219. TerminalSize_docstring,
  12220. TerminalSize_fields,
  12221. 2,
  12222. };
  12223. #if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
  12224. /*[clinic input]
  12225. os.get_terminal_size
  12226. fd: int(c_default="fileno(stdout)", py_default="<unrepresentable>") = -1
  12227. /
  12228. Return the size of the terminal window as (columns, lines).
  12229. The optional argument fd (default standard output) specifies
  12230. which file descriptor should be queried.
  12231. If the file descriptor is not connected to a terminal, an OSError
  12232. is thrown.
  12233. This function will only be defined if an implementation is
  12234. available for this system.
  12235. shutil.get_terminal_size is the high-level function which should
  12236. normally be used, os.get_terminal_size is the low-level implementation.
  12237. [clinic start generated code]*/
  12238. static PyObject *
  12239. os_get_terminal_size_impl(PyObject *module, int fd)
  12240. /*[clinic end generated code: output=fbab93acef980508 input=ead5679b82ddb920]*/
  12241. {
  12242. int columns, lines;
  12243. PyObject *termsize;
  12244. /* Under some conditions stdout may not be connected and
  12245. * fileno(stdout) may point to an invalid file descriptor. For example
  12246. * GUI apps don't have valid standard streams by default.
  12247. *
  12248. * If this happens, and the optional fd argument is not present,
  12249. * the ioctl below will fail returning EBADF. This is what we want.
  12250. */
  12251. #ifdef TERMSIZE_USE_IOCTL
  12252. {
  12253. struct winsize w;
  12254. if (ioctl(fd, TIOCGWINSZ, &w))
  12255. return PyErr_SetFromErrno(PyExc_OSError);
  12256. columns = w.ws_col;
  12257. lines = w.ws_row;
  12258. }
  12259. #endif /* TERMSIZE_USE_IOCTL */
  12260. #ifdef TERMSIZE_USE_CONIO
  12261. {
  12262. HANDLE handle;
  12263. CONSOLE_SCREEN_BUFFER_INFO csbi;
  12264. handle = _Py_get_osfhandle(fd);
  12265. if (handle == INVALID_HANDLE_VALUE)
  12266. return NULL;
  12267. if (!GetConsoleScreenBufferInfo(handle, &csbi))
  12268. return PyErr_SetFromWindowsErr(0);
  12269. columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
  12270. lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
  12271. }
  12272. #endif /* TERMSIZE_USE_CONIO */
  12273. PyObject *TerminalSizeType = get_posix_state(module)->TerminalSizeType;
  12274. termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
  12275. if (termsize == NULL)
  12276. return NULL;
  12277. int pos = 0;
  12278. #define SET_TERMSIZE(CALL) \
  12279. do { \
  12280. PyObject *item = (CALL); \
  12281. if (item == NULL) { \
  12282. Py_DECREF(termsize); \
  12283. return NULL; \
  12284. } \
  12285. PyStructSequence_SET_ITEM(termsize, pos++, item); \
  12286. } while(0)
  12287. SET_TERMSIZE(PyLong_FromLong(columns));
  12288. SET_TERMSIZE(PyLong_FromLong(lines));
  12289. #undef SET_TERMSIZE
  12290. return termsize;
  12291. }
  12292. #endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
  12293. /*[clinic input]
  12294. os.cpu_count
  12295. Return the number of CPUs in the system; return None if indeterminable.
  12296. This number is not equivalent to the number of CPUs the current process can
  12297. use. The number of usable CPUs can be obtained with
  12298. ``len(os.sched_getaffinity(0))``
  12299. [clinic start generated code]*/
  12300. static PyObject *
  12301. os_cpu_count_impl(PyObject *module)
  12302. /*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
  12303. {
  12304. int ncpu = 0;
  12305. #ifdef MS_WINDOWS
  12306. #ifdef MS_WINDOWS_DESKTOP
  12307. ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
  12308. #endif
  12309. #elif defined(__hpux)
  12310. ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
  12311. #elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
  12312. ncpu = sysconf(_SC_NPROCESSORS_ONLN);
  12313. #elif defined(__VXWORKS__)
  12314. ncpu = _Py_popcount32(vxCpuEnabledGet());
  12315. #elif defined(__DragonFly__) || \
  12316. defined(__OpenBSD__) || \
  12317. defined(__FreeBSD__) || \
  12318. defined(__NetBSD__) || \
  12319. defined(__APPLE__)
  12320. int mib[2];
  12321. size_t len = sizeof(ncpu);
  12322. mib[0] = CTL_HW;
  12323. mib[1] = HW_NCPU;
  12324. if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
  12325. ncpu = 0;
  12326. #endif
  12327. if (ncpu >= 1)
  12328. return PyLong_FromLong(ncpu);
  12329. else
  12330. Py_RETURN_NONE;
  12331. }
  12332. /*[clinic input]
  12333. os.get_inheritable -> bool
  12334. fd: int
  12335. /
  12336. Get the close-on-exe flag of the specified file descriptor.
  12337. [clinic start generated code]*/
  12338. static int
  12339. os_get_inheritable_impl(PyObject *module, int fd)
  12340. /*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
  12341. {
  12342. int return_value;
  12343. _Py_BEGIN_SUPPRESS_IPH
  12344. return_value = _Py_get_inheritable(fd);
  12345. _Py_END_SUPPRESS_IPH
  12346. return return_value;
  12347. }
  12348. /*[clinic input]
  12349. os.set_inheritable
  12350. fd: int
  12351. inheritable: int
  12352. /
  12353. Set the inheritable flag of the specified file descriptor.
  12354. [clinic start generated code]*/
  12355. static PyObject *
  12356. os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
  12357. /*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
  12358. {
  12359. int result;
  12360. _Py_BEGIN_SUPPRESS_IPH
  12361. result = _Py_set_inheritable(fd, inheritable, NULL);
  12362. _Py_END_SUPPRESS_IPH
  12363. if (result < 0)
  12364. return NULL;
  12365. Py_RETURN_NONE;
  12366. }
  12367. #ifdef MS_WINDOWS
  12368. #ifndef HANDLE_FLAG_INHERIT
  12369. #define HANDLE_FLAG_INHERIT 0x00000001
  12370. #endif
  12371. /*[clinic input]
  12372. os.get_handle_inheritable -> bool
  12373. handle: intptr_t
  12374. /
  12375. Get the close-on-exe flag of the specified file descriptor.
  12376. [clinic start generated code]*/
  12377. static int
  12378. os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
  12379. /*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
  12380. {
  12381. DWORD flags;
  12382. if (!GetHandleInformation((HANDLE)handle, &flags)) {
  12383. PyErr_SetFromWindowsErr(0);
  12384. return -1;
  12385. }
  12386. return flags & HANDLE_FLAG_INHERIT;
  12387. }
  12388. /*[clinic input]
  12389. os.set_handle_inheritable
  12390. handle: intptr_t
  12391. inheritable: bool
  12392. /
  12393. Set the inheritable flag of the specified handle.
  12394. [clinic start generated code]*/
  12395. static PyObject *
  12396. os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
  12397. int inheritable)
  12398. /*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
  12399. {
  12400. DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
  12401. if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
  12402. PyErr_SetFromWindowsErr(0);
  12403. return NULL;
  12404. }
  12405. Py_RETURN_NONE;
  12406. }
  12407. #endif /* MS_WINDOWS */
  12408. /*[clinic input]
  12409. os.get_blocking -> bool
  12410. fd: int
  12411. /
  12412. Get the blocking mode of the file descriptor.
  12413. Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
  12414. [clinic start generated code]*/
  12415. static int
  12416. os_get_blocking_impl(PyObject *module, int fd)
  12417. /*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
  12418. {
  12419. int blocking;
  12420. _Py_BEGIN_SUPPRESS_IPH
  12421. blocking = _Py_get_blocking(fd);
  12422. _Py_END_SUPPRESS_IPH
  12423. return blocking;
  12424. }
  12425. /*[clinic input]
  12426. os.set_blocking
  12427. fd: int
  12428. blocking: bool
  12429. /
  12430. Set the blocking mode of the specified file descriptor.
  12431. Set the O_NONBLOCK flag if blocking is False,
  12432. clear the O_NONBLOCK flag otherwise.
  12433. [clinic start generated code]*/
  12434. static PyObject *
  12435. os_set_blocking_impl(PyObject *module, int fd, int blocking)
  12436. /*[clinic end generated code: output=384eb43aa0762a9d input=7e9dfc9b14804dd4]*/
  12437. {
  12438. int result;
  12439. _Py_BEGIN_SUPPRESS_IPH
  12440. result = _Py_set_blocking(fd, blocking);
  12441. _Py_END_SUPPRESS_IPH
  12442. if (result < 0)
  12443. return NULL;
  12444. Py_RETURN_NONE;
  12445. }
  12446. /*[clinic input]
  12447. class os.DirEntry "DirEntry *" "DirEntryType"
  12448. [clinic start generated code]*/
  12449. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
  12450. typedef struct {
  12451. PyObject_HEAD
  12452. PyObject *name;
  12453. PyObject *path;
  12454. PyObject *stat;
  12455. PyObject *lstat;
  12456. #ifdef MS_WINDOWS
  12457. struct _Py_stat_struct win32_lstat;
  12458. uint64_t win32_file_index;
  12459. uint64_t win32_file_index_high;
  12460. int got_file_index;
  12461. #else /* POSIX */
  12462. #ifdef HAVE_DIRENT_D_TYPE
  12463. unsigned char d_type;
  12464. #endif
  12465. ino_t d_ino;
  12466. int dir_fd;
  12467. #endif
  12468. } DirEntry;
  12469. static void
  12470. DirEntry_dealloc(DirEntry *entry)
  12471. {
  12472. PyTypeObject *tp = Py_TYPE(entry);
  12473. Py_XDECREF(entry->name);
  12474. Py_XDECREF(entry->path);
  12475. Py_XDECREF(entry->stat);
  12476. Py_XDECREF(entry->lstat);
  12477. freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
  12478. free_func(entry);
  12479. Py_DECREF(tp);
  12480. }
  12481. /* Forward reference */
  12482. static int
  12483. DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
  12484. int follow_symlinks, unsigned short mode_bits);
  12485. /*[clinic input]
  12486. os.DirEntry.is_symlink -> bool
  12487. defining_class: defining_class
  12488. /
  12489. Return True if the entry is a symbolic link; cached per entry.
  12490. [clinic start generated code]*/
  12491. static int
  12492. os_DirEntry_is_symlink_impl(DirEntry *self, PyTypeObject *defining_class)
  12493. /*[clinic end generated code: output=293096d589b6d47c input=e9acc5ee4d511113]*/
  12494. {
  12495. #ifdef MS_WINDOWS
  12496. return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
  12497. #elif defined(HAVE_DIRENT_D_TYPE)
  12498. /* POSIX */
  12499. if (self->d_type != DT_UNKNOWN)
  12500. return self->d_type == DT_LNK;
  12501. else
  12502. return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
  12503. #else
  12504. /* POSIX without d_type */
  12505. return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
  12506. #endif
  12507. }
  12508. /*[clinic input]
  12509. os.DirEntry.is_junction -> bool
  12510. defining_class: defining_class
  12511. /
  12512. Return True if the entry is a junction; cached per entry.
  12513. [clinic start generated code]*/
  12514. static int
  12515. os_DirEntry_is_junction_impl(DirEntry *self, PyTypeObject *defining_class)
  12516. /*[clinic end generated code: output=7061a07b0ef2cd1f input=475cd36fb7d4723f]*/
  12517. {
  12518. #ifdef MS_WINDOWS
  12519. return self->win32_lstat.st_reparse_tag == IO_REPARSE_TAG_MOUNT_POINT;
  12520. #else
  12521. return 0;
  12522. #endif
  12523. }
  12524. static PyObject *
  12525. DirEntry_fetch_stat(PyObject *module, DirEntry *self, int follow_symlinks)
  12526. {
  12527. int result;
  12528. STRUCT_STAT st;
  12529. PyObject *ub;
  12530. #ifdef MS_WINDOWS
  12531. if (!PyUnicode_FSDecoder(self->path, &ub))
  12532. return NULL;
  12533. wchar_t *path = PyUnicode_AsWideCharString(ub, NULL);
  12534. Py_DECREF(ub);
  12535. #else /* POSIX */
  12536. if (!PyUnicode_FSConverter(self->path, &ub))
  12537. return NULL;
  12538. const char *path = PyBytes_AS_STRING(ub);
  12539. if (self->dir_fd != DEFAULT_DIR_FD) {
  12540. #ifdef HAVE_FSTATAT
  12541. if (HAVE_FSTATAT_RUNTIME) {
  12542. Py_BEGIN_ALLOW_THREADS
  12543. result = fstatat(self->dir_fd, path, &st,
  12544. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  12545. Py_END_ALLOW_THREADS
  12546. } else
  12547. #endif /* HAVE_FSTATAT */
  12548. {
  12549. Py_DECREF(ub);
  12550. PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
  12551. return NULL;
  12552. }
  12553. }
  12554. else
  12555. #endif
  12556. {
  12557. Py_BEGIN_ALLOW_THREADS
  12558. if (follow_symlinks) {
  12559. result = STAT(path, &st);
  12560. }
  12561. else {
  12562. result = LSTAT(path, &st);
  12563. }
  12564. Py_END_ALLOW_THREADS
  12565. }
  12566. int saved_errno = errno;
  12567. #if defined(MS_WINDOWS)
  12568. PyMem_Free(path);
  12569. #else
  12570. Py_DECREF(ub);
  12571. #endif
  12572. if (result != 0) {
  12573. errno = saved_errno;
  12574. path_object_error(self->path);
  12575. return NULL;
  12576. }
  12577. return _pystat_fromstructstat(module, &st);
  12578. }
  12579. static PyObject *
  12580. DirEntry_get_lstat(PyTypeObject *defining_class, DirEntry *self)
  12581. {
  12582. if (!self->lstat) {
  12583. PyObject *module = PyType_GetModule(defining_class);
  12584. #ifdef MS_WINDOWS
  12585. self->lstat = _pystat_fromstructstat(module, &self->win32_lstat);
  12586. #else /* POSIX */
  12587. self->lstat = DirEntry_fetch_stat(module, self, 0);
  12588. #endif
  12589. }
  12590. return Py_XNewRef(self->lstat);
  12591. }
  12592. /*[clinic input]
  12593. os.DirEntry.stat
  12594. defining_class: defining_class
  12595. /
  12596. *
  12597. follow_symlinks: bool = True
  12598. Return stat_result object for the entry; cached per entry.
  12599. [clinic start generated code]*/
  12600. static PyObject *
  12601. os_DirEntry_stat_impl(DirEntry *self, PyTypeObject *defining_class,
  12602. int follow_symlinks)
  12603. /*[clinic end generated code: output=23f803e19c3e780e input=e816273c4e67ee98]*/
  12604. {
  12605. if (!follow_symlinks) {
  12606. return DirEntry_get_lstat(defining_class, self);
  12607. }
  12608. if (!self->stat) {
  12609. int result = os_DirEntry_is_symlink_impl(self, defining_class);
  12610. if (result == -1) {
  12611. return NULL;
  12612. }
  12613. if (result) {
  12614. PyObject *module = PyType_GetModule(defining_class);
  12615. self->stat = DirEntry_fetch_stat(module, self, 1);
  12616. }
  12617. else {
  12618. self->stat = DirEntry_get_lstat(defining_class, self);
  12619. }
  12620. }
  12621. return Py_XNewRef(self->stat);
  12622. }
  12623. /* Set exception and return -1 on error, 0 for False, 1 for True */
  12624. static int
  12625. DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
  12626. int follow_symlinks, unsigned short mode_bits)
  12627. {
  12628. PyObject *stat = NULL;
  12629. PyObject *st_mode = NULL;
  12630. long mode;
  12631. int result;
  12632. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12633. int is_symlink;
  12634. int need_stat;
  12635. #endif
  12636. #ifdef MS_WINDOWS
  12637. unsigned long dir_bits;
  12638. #endif
  12639. #ifdef MS_WINDOWS
  12640. is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
  12641. need_stat = follow_symlinks && is_symlink;
  12642. #elif defined(HAVE_DIRENT_D_TYPE)
  12643. is_symlink = self->d_type == DT_LNK;
  12644. need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
  12645. #endif
  12646. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12647. if (need_stat) {
  12648. #endif
  12649. stat = os_DirEntry_stat_impl(self, defining_class, follow_symlinks);
  12650. if (!stat) {
  12651. if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
  12652. /* If file doesn't exist (anymore), then return False
  12653. (i.e., say it's not a file/directory) */
  12654. PyErr_Clear();
  12655. return 0;
  12656. }
  12657. goto error;
  12658. }
  12659. _posixstate* state = get_posix_state(PyType_GetModule(defining_class));
  12660. st_mode = PyObject_GetAttr(stat, state->st_mode);
  12661. if (!st_mode)
  12662. goto error;
  12663. mode = PyLong_AsLong(st_mode);
  12664. if (mode == -1 && PyErr_Occurred())
  12665. goto error;
  12666. Py_CLEAR(st_mode);
  12667. Py_CLEAR(stat);
  12668. result = (mode & S_IFMT) == mode_bits;
  12669. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12670. }
  12671. else if (is_symlink) {
  12672. assert(mode_bits != S_IFLNK);
  12673. result = 0;
  12674. }
  12675. else {
  12676. assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
  12677. #ifdef MS_WINDOWS
  12678. dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
  12679. if (mode_bits == S_IFDIR)
  12680. result = dir_bits != 0;
  12681. else
  12682. result = dir_bits == 0;
  12683. #else /* POSIX */
  12684. if (mode_bits == S_IFDIR)
  12685. result = self->d_type == DT_DIR;
  12686. else
  12687. result = self->d_type == DT_REG;
  12688. #endif
  12689. }
  12690. #endif
  12691. return result;
  12692. error:
  12693. Py_XDECREF(st_mode);
  12694. Py_XDECREF(stat);
  12695. return -1;
  12696. }
  12697. /*[clinic input]
  12698. os.DirEntry.is_dir -> bool
  12699. defining_class: defining_class
  12700. /
  12701. *
  12702. follow_symlinks: bool = True
  12703. Return True if the entry is a directory; cached per entry.
  12704. [clinic start generated code]*/
  12705. static int
  12706. os_DirEntry_is_dir_impl(DirEntry *self, PyTypeObject *defining_class,
  12707. int follow_symlinks)
  12708. /*[clinic end generated code: output=0cd453b9c0987fdf input=1a4ffd6dec9920cb]*/
  12709. {
  12710. return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFDIR);
  12711. }
  12712. /*[clinic input]
  12713. os.DirEntry.is_file -> bool
  12714. defining_class: defining_class
  12715. /
  12716. *
  12717. follow_symlinks: bool = True
  12718. Return True if the entry is a file; cached per entry.
  12719. [clinic start generated code]*/
  12720. static int
  12721. os_DirEntry_is_file_impl(DirEntry *self, PyTypeObject *defining_class,
  12722. int follow_symlinks)
  12723. /*[clinic end generated code: output=f7c277ab5ba80908 input=0a64c5a12e802e3b]*/
  12724. {
  12725. return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFREG);
  12726. }
  12727. /*[clinic input]
  12728. os.DirEntry.inode
  12729. Return inode of the entry; cached per entry.
  12730. [clinic start generated code]*/
  12731. static PyObject *
  12732. os_DirEntry_inode_impl(DirEntry *self)
  12733. /*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
  12734. {
  12735. #ifdef MS_WINDOWS
  12736. if (!self->got_file_index) {
  12737. PyObject *unicode;
  12738. STRUCT_STAT stat;
  12739. int result;
  12740. if (!PyUnicode_FSDecoder(self->path, &unicode))
  12741. return NULL;
  12742. wchar_t *path = PyUnicode_AsWideCharString(unicode, NULL);
  12743. Py_DECREF(unicode);
  12744. result = LSTAT(path, &stat);
  12745. int saved_errno = errno;
  12746. PyMem_Free(path);
  12747. if (result != 0) {
  12748. errno = saved_errno;
  12749. return path_object_error(self->path);
  12750. }
  12751. self->win32_file_index = stat.st_ino;
  12752. self->win32_file_index_high = stat.st_ino_high;
  12753. self->got_file_index = 1;
  12754. }
  12755. return _pystat_l128_from_l64_l64(self->win32_file_index, self->win32_file_index_high);
  12756. #else /* POSIX */
  12757. static_assert(sizeof(unsigned long long) >= sizeof(self->d_ino),
  12758. "DirEntry.d_ino is larger than unsigned long long");
  12759. return PyLong_FromUnsignedLongLong(self->d_ino);
  12760. #endif
  12761. }
  12762. static PyObject *
  12763. DirEntry_repr(DirEntry *self)
  12764. {
  12765. return PyUnicode_FromFormat("<DirEntry %R>", self->name);
  12766. }
  12767. /*[clinic input]
  12768. os.DirEntry.__fspath__
  12769. Returns the path for the entry.
  12770. [clinic start generated code]*/
  12771. static PyObject *
  12772. os_DirEntry___fspath___impl(DirEntry *self)
  12773. /*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
  12774. {
  12775. return Py_NewRef(self->path);
  12776. }
  12777. static PyMemberDef DirEntry_members[] = {
  12778. {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
  12779. "the entry's base filename, relative to scandir() \"path\" argument"},
  12780. {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
  12781. "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
  12782. {NULL}
  12783. };
  12784. #include "clinic/posixmodule.c.h"
  12785. static PyMethodDef DirEntry_methods[] = {
  12786. OS_DIRENTRY_IS_DIR_METHODDEF
  12787. OS_DIRENTRY_IS_FILE_METHODDEF
  12788. OS_DIRENTRY_IS_SYMLINK_METHODDEF
  12789. OS_DIRENTRY_IS_JUNCTION_METHODDEF
  12790. OS_DIRENTRY_STAT_METHODDEF
  12791. OS_DIRENTRY_INODE_METHODDEF
  12792. OS_DIRENTRY___FSPATH___METHODDEF
  12793. {"__class_getitem__", Py_GenericAlias,
  12794. METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  12795. {NULL}
  12796. };
  12797. static PyType_Slot DirEntryType_slots[] = {
  12798. {Py_tp_dealloc, DirEntry_dealloc},
  12799. {Py_tp_repr, DirEntry_repr},
  12800. {Py_tp_methods, DirEntry_methods},
  12801. {Py_tp_members, DirEntry_members},
  12802. {0, 0},
  12803. };
  12804. static PyType_Spec DirEntryType_spec = {
  12805. MODNAME ".DirEntry",
  12806. sizeof(DirEntry),
  12807. 0,
  12808. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
  12809. DirEntryType_slots
  12810. };
  12811. #ifdef MS_WINDOWS
  12812. static wchar_t *
  12813. join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
  12814. {
  12815. Py_ssize_t path_len;
  12816. Py_ssize_t size;
  12817. wchar_t *result;
  12818. wchar_t ch;
  12819. if (!path_wide) { /* Default arg: "." */
  12820. path_wide = L".";
  12821. path_len = 1;
  12822. }
  12823. else {
  12824. path_len = wcslen(path_wide);
  12825. }
  12826. /* The +1's are for the path separator and the NUL */
  12827. size = path_len + 1 + wcslen(filename) + 1;
  12828. result = PyMem_New(wchar_t, size);
  12829. if (!result) {
  12830. PyErr_NoMemory();
  12831. return NULL;
  12832. }
  12833. wcscpy(result, path_wide);
  12834. if (path_len > 0) {
  12835. ch = result[path_len - 1];
  12836. if (ch != SEP && ch != ALTSEP && ch != L':')
  12837. result[path_len++] = SEP;
  12838. wcscpy(result + path_len, filename);
  12839. }
  12840. return result;
  12841. }
  12842. static PyObject *
  12843. DirEntry_from_find_data(PyObject *module, path_t *path, WIN32_FIND_DATAW *dataW)
  12844. {
  12845. DirEntry *entry;
  12846. BY_HANDLE_FILE_INFORMATION file_info;
  12847. ULONG reparse_tag;
  12848. wchar_t *joined_path;
  12849. PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
  12850. entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
  12851. if (!entry)
  12852. return NULL;
  12853. entry->name = NULL;
  12854. entry->path = NULL;
  12855. entry->stat = NULL;
  12856. entry->lstat = NULL;
  12857. entry->got_file_index = 0;
  12858. entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
  12859. if (!entry->name)
  12860. goto error;
  12861. int return_bytes = path->wide && PyBytes_Check(path->object);
  12862. if (return_bytes) {
  12863. Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
  12864. if (!entry->name)
  12865. goto error;
  12866. }
  12867. joined_path = join_path_filenameW(path->wide, dataW->cFileName);
  12868. if (!joined_path)
  12869. goto error;
  12870. entry->path = PyUnicode_FromWideChar(joined_path, -1);
  12871. PyMem_Free(joined_path);
  12872. if (!entry->path)
  12873. goto error;
  12874. if (return_bytes) {
  12875. Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
  12876. if (!entry->path)
  12877. goto error;
  12878. }
  12879. find_data_to_file_info(dataW, &file_info, &reparse_tag);
  12880. _Py_attribute_data_to_stat(&file_info, reparse_tag, NULL, NULL, &entry->win32_lstat);
  12881. /* ctime is only deprecated from 3.12, so we copy birthtime across */
  12882. entry->win32_lstat.st_ctime = entry->win32_lstat.st_birthtime;
  12883. entry->win32_lstat.st_ctime_nsec = entry->win32_lstat.st_birthtime_nsec;
  12884. return (PyObject *)entry;
  12885. error:
  12886. Py_DECREF(entry);
  12887. return NULL;
  12888. }
  12889. #else /* POSIX */
  12890. static char *
  12891. join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
  12892. {
  12893. Py_ssize_t path_len;
  12894. Py_ssize_t size;
  12895. char *result;
  12896. if (!path_narrow) { /* Default arg: "." */
  12897. path_narrow = ".";
  12898. path_len = 1;
  12899. }
  12900. else {
  12901. path_len = strlen(path_narrow);
  12902. }
  12903. if (filename_len == -1)
  12904. filename_len = strlen(filename);
  12905. /* The +1's are for the path separator and the NUL */
  12906. size = path_len + 1 + filename_len + 1;
  12907. result = PyMem_New(char, size);
  12908. if (!result) {
  12909. PyErr_NoMemory();
  12910. return NULL;
  12911. }
  12912. strcpy(result, path_narrow);
  12913. if (path_len > 0 && result[path_len - 1] != '/')
  12914. result[path_len++] = '/';
  12915. strcpy(result + path_len, filename);
  12916. return result;
  12917. }
  12918. static PyObject *
  12919. DirEntry_from_posix_info(PyObject *module, path_t *path, const char *name,
  12920. Py_ssize_t name_len, ino_t d_ino
  12921. #ifdef HAVE_DIRENT_D_TYPE
  12922. , unsigned char d_type
  12923. #endif
  12924. )
  12925. {
  12926. DirEntry *entry;
  12927. char *joined_path;
  12928. PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
  12929. entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
  12930. if (!entry)
  12931. return NULL;
  12932. entry->name = NULL;
  12933. entry->path = NULL;
  12934. entry->stat = NULL;
  12935. entry->lstat = NULL;
  12936. if (path->fd != -1) {
  12937. entry->dir_fd = path->fd;
  12938. joined_path = NULL;
  12939. }
  12940. else {
  12941. entry->dir_fd = DEFAULT_DIR_FD;
  12942. joined_path = join_path_filename(path->narrow, name, name_len);
  12943. if (!joined_path)
  12944. goto error;
  12945. }
  12946. if (!path->narrow || !PyBytes_Check(path->object)) {
  12947. entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
  12948. if (joined_path)
  12949. entry->path = PyUnicode_DecodeFSDefault(joined_path);
  12950. }
  12951. else {
  12952. entry->name = PyBytes_FromStringAndSize(name, name_len);
  12953. if (joined_path)
  12954. entry->path = PyBytes_FromString(joined_path);
  12955. }
  12956. PyMem_Free(joined_path);
  12957. if (!entry->name)
  12958. goto error;
  12959. if (path->fd != -1) {
  12960. entry->path = Py_NewRef(entry->name);
  12961. }
  12962. else if (!entry->path)
  12963. goto error;
  12964. #ifdef HAVE_DIRENT_D_TYPE
  12965. entry->d_type = d_type;
  12966. #endif
  12967. entry->d_ino = d_ino;
  12968. return (PyObject *)entry;
  12969. error:
  12970. Py_XDECREF(entry);
  12971. return NULL;
  12972. }
  12973. #endif
  12974. typedef struct {
  12975. PyObject_HEAD
  12976. path_t path;
  12977. #ifdef MS_WINDOWS
  12978. HANDLE handle;
  12979. WIN32_FIND_DATAW file_data;
  12980. int first_time;
  12981. #else /* POSIX */
  12982. DIR *dirp;
  12983. #endif
  12984. #ifdef HAVE_FDOPENDIR
  12985. int fd;
  12986. #endif
  12987. } ScandirIterator;
  12988. #ifdef MS_WINDOWS
  12989. static int
  12990. ScandirIterator_is_closed(ScandirIterator *iterator)
  12991. {
  12992. return iterator->handle == INVALID_HANDLE_VALUE;
  12993. }
  12994. static void
  12995. ScandirIterator_closedir(ScandirIterator *iterator)
  12996. {
  12997. HANDLE handle = iterator->handle;
  12998. if (handle == INVALID_HANDLE_VALUE)
  12999. return;
  13000. iterator->handle = INVALID_HANDLE_VALUE;
  13001. Py_BEGIN_ALLOW_THREADS
  13002. FindClose(handle);
  13003. Py_END_ALLOW_THREADS
  13004. }
  13005. static PyObject *
  13006. ScandirIterator_iternext(ScandirIterator *iterator)
  13007. {
  13008. WIN32_FIND_DATAW *file_data = &iterator->file_data;
  13009. BOOL success;
  13010. PyObject *entry;
  13011. /* Happens if the iterator is iterated twice, or closed explicitly */
  13012. if (iterator->handle == INVALID_HANDLE_VALUE)
  13013. return NULL;
  13014. while (1) {
  13015. if (!iterator->first_time) {
  13016. Py_BEGIN_ALLOW_THREADS
  13017. success = FindNextFileW(iterator->handle, file_data);
  13018. Py_END_ALLOW_THREADS
  13019. if (!success) {
  13020. /* Error or no more files */
  13021. if (GetLastError() != ERROR_NO_MORE_FILES)
  13022. path_error(&iterator->path);
  13023. break;
  13024. }
  13025. }
  13026. iterator->first_time = 0;
  13027. /* Skip over . and .. */
  13028. if (wcscmp(file_data->cFileName, L".") != 0 &&
  13029. wcscmp(file_data->cFileName, L"..") != 0)
  13030. {
  13031. PyObject *module = PyType_GetModule(Py_TYPE(iterator));
  13032. entry = DirEntry_from_find_data(module, &iterator->path, file_data);
  13033. if (!entry)
  13034. break;
  13035. return entry;
  13036. }
  13037. /* Loop till we get a non-dot directory or finish iterating */
  13038. }
  13039. /* Error or no more files */
  13040. ScandirIterator_closedir(iterator);
  13041. return NULL;
  13042. }
  13043. #else /* POSIX */
  13044. static int
  13045. ScandirIterator_is_closed(ScandirIterator *iterator)
  13046. {
  13047. return !iterator->dirp;
  13048. }
  13049. static void
  13050. ScandirIterator_closedir(ScandirIterator *iterator)
  13051. {
  13052. DIR *dirp = iterator->dirp;
  13053. if (!dirp)
  13054. return;
  13055. iterator->dirp = NULL;
  13056. Py_BEGIN_ALLOW_THREADS
  13057. #ifdef HAVE_FDOPENDIR
  13058. if (iterator->path.fd != -1)
  13059. rewinddir(dirp);
  13060. #endif
  13061. closedir(dirp);
  13062. Py_END_ALLOW_THREADS
  13063. return;
  13064. }
  13065. static PyObject *
  13066. ScandirIterator_iternext(ScandirIterator *iterator)
  13067. {
  13068. struct dirent *direntp;
  13069. Py_ssize_t name_len;
  13070. int is_dot;
  13071. PyObject *entry;
  13072. /* Happens if the iterator is iterated twice, or closed explicitly */
  13073. if (!iterator->dirp)
  13074. return NULL;
  13075. while (1) {
  13076. errno = 0;
  13077. Py_BEGIN_ALLOW_THREADS
  13078. direntp = readdir(iterator->dirp);
  13079. Py_END_ALLOW_THREADS
  13080. if (!direntp) {
  13081. /* Error or no more files */
  13082. if (errno != 0)
  13083. path_error(&iterator->path);
  13084. break;
  13085. }
  13086. /* Skip over . and .. */
  13087. name_len = NAMLEN(direntp);
  13088. is_dot = direntp->d_name[0] == '.' &&
  13089. (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
  13090. if (!is_dot) {
  13091. PyObject *module = PyType_GetModule(Py_TYPE(iterator));
  13092. entry = DirEntry_from_posix_info(module,
  13093. &iterator->path, direntp->d_name,
  13094. name_len, direntp->d_ino
  13095. #ifdef HAVE_DIRENT_D_TYPE
  13096. , direntp->d_type
  13097. #endif
  13098. );
  13099. if (!entry)
  13100. break;
  13101. return entry;
  13102. }
  13103. /* Loop till we get a non-dot directory or finish iterating */
  13104. }
  13105. /* Error or no more files */
  13106. ScandirIterator_closedir(iterator);
  13107. return NULL;
  13108. }
  13109. #endif
  13110. static PyObject *
  13111. ScandirIterator_close(ScandirIterator *self, PyObject *args)
  13112. {
  13113. ScandirIterator_closedir(self);
  13114. Py_RETURN_NONE;
  13115. }
  13116. static PyObject *
  13117. ScandirIterator_enter(PyObject *self, PyObject *args)
  13118. {
  13119. return Py_NewRef(self);
  13120. }
  13121. static PyObject *
  13122. ScandirIterator_exit(ScandirIterator *self, PyObject *args)
  13123. {
  13124. ScandirIterator_closedir(self);
  13125. Py_RETURN_NONE;
  13126. }
  13127. static void
  13128. ScandirIterator_finalize(ScandirIterator *iterator)
  13129. {
  13130. /* Save the current exception, if any. */
  13131. PyObject *exc = PyErr_GetRaisedException();
  13132. if (!ScandirIterator_is_closed(iterator)) {
  13133. ScandirIterator_closedir(iterator);
  13134. if (PyErr_ResourceWarning((PyObject *)iterator, 1,
  13135. "unclosed scandir iterator %R", iterator)) {
  13136. /* Spurious errors can appear at shutdown */
  13137. if (PyErr_ExceptionMatches(PyExc_Warning)) {
  13138. PyErr_WriteUnraisable((PyObject *) iterator);
  13139. }
  13140. }
  13141. }
  13142. path_cleanup(&iterator->path);
  13143. /* Restore the saved exception. */
  13144. PyErr_SetRaisedException(exc);
  13145. }
  13146. static void
  13147. ScandirIterator_dealloc(ScandirIterator *iterator)
  13148. {
  13149. PyTypeObject *tp = Py_TYPE(iterator);
  13150. if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
  13151. return;
  13152. freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
  13153. free_func(iterator);
  13154. Py_DECREF(tp);
  13155. }
  13156. static PyMethodDef ScandirIterator_methods[] = {
  13157. {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
  13158. {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
  13159. {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
  13160. {NULL}
  13161. };
  13162. static PyType_Slot ScandirIteratorType_slots[] = {
  13163. {Py_tp_dealloc, ScandirIterator_dealloc},
  13164. {Py_tp_finalize, ScandirIterator_finalize},
  13165. {Py_tp_iter, PyObject_SelfIter},
  13166. {Py_tp_iternext, ScandirIterator_iternext},
  13167. {Py_tp_methods, ScandirIterator_methods},
  13168. {0, 0},
  13169. };
  13170. static PyType_Spec ScandirIteratorType_spec = {
  13171. MODNAME ".ScandirIterator",
  13172. sizeof(ScandirIterator),
  13173. 0,
  13174. // bpo-40549: Py_TPFLAGS_BASETYPE should not be used, since
  13175. // PyType_GetModule(Py_TYPE(self)) doesn't work on a subclass instance.
  13176. (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE
  13177. | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  13178. ScandirIteratorType_slots
  13179. };
  13180. /*[clinic input]
  13181. os.scandir
  13182. path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
  13183. Return an iterator of DirEntry objects for given path.
  13184. path can be specified as either str, bytes, or a path-like object. If path
  13185. is bytes, the names of yielded DirEntry objects will also be bytes; in
  13186. all other circumstances they will be str.
  13187. If path is None, uses the path='.'.
  13188. [clinic start generated code]*/
  13189. static PyObject *
  13190. os_scandir_impl(PyObject *module, path_t *path)
  13191. /*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
  13192. {
  13193. ScandirIterator *iterator;
  13194. #ifdef MS_WINDOWS
  13195. wchar_t *path_strW;
  13196. #else
  13197. const char *path_str;
  13198. #ifdef HAVE_FDOPENDIR
  13199. int fd = -1;
  13200. #endif
  13201. #endif
  13202. if (PySys_Audit("os.scandir", "O",
  13203. path->object ? path->object : Py_None) < 0) {
  13204. return NULL;
  13205. }
  13206. PyObject *ScandirIteratorType = get_posix_state(module)->ScandirIteratorType;
  13207. iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
  13208. if (!iterator)
  13209. return NULL;
  13210. #ifdef MS_WINDOWS
  13211. iterator->handle = INVALID_HANDLE_VALUE;
  13212. #else
  13213. iterator->dirp = NULL;
  13214. #endif
  13215. /* Move the ownership to iterator->path */
  13216. memcpy(&iterator->path, path, sizeof(path_t));
  13217. memset(path, 0, sizeof(path_t));
  13218. #ifdef MS_WINDOWS
  13219. iterator->first_time = 1;
  13220. path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
  13221. if (!path_strW)
  13222. goto error;
  13223. Py_BEGIN_ALLOW_THREADS
  13224. iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
  13225. Py_END_ALLOW_THREADS
  13226. if (iterator->handle == INVALID_HANDLE_VALUE) {
  13227. path_error(&iterator->path);
  13228. PyMem_Free(path_strW);
  13229. goto error;
  13230. }
  13231. PyMem_Free(path_strW);
  13232. #else /* POSIX */
  13233. errno = 0;
  13234. #ifdef HAVE_FDOPENDIR
  13235. if (iterator->path.fd != -1) {
  13236. if (HAVE_FDOPENDIR_RUNTIME) {
  13237. /* closedir() closes the FD, so we duplicate it */
  13238. fd = _Py_dup(iterator->path.fd);
  13239. if (fd == -1)
  13240. goto error;
  13241. Py_BEGIN_ALLOW_THREADS
  13242. iterator->dirp = fdopendir(fd);
  13243. Py_END_ALLOW_THREADS
  13244. } else {
  13245. PyErr_SetString(PyExc_TypeError,
  13246. "scandir: path should be string, bytes, os.PathLike or None, not int");
  13247. return NULL;
  13248. }
  13249. }
  13250. else
  13251. #endif
  13252. {
  13253. if (iterator->path.narrow)
  13254. path_str = iterator->path.narrow;
  13255. else
  13256. path_str = ".";
  13257. Py_BEGIN_ALLOW_THREADS
  13258. iterator->dirp = opendir(path_str);
  13259. Py_END_ALLOW_THREADS
  13260. }
  13261. if (!iterator->dirp) {
  13262. path_error(&iterator->path);
  13263. #ifdef HAVE_FDOPENDIR
  13264. if (fd != -1) {
  13265. Py_BEGIN_ALLOW_THREADS
  13266. close(fd);
  13267. Py_END_ALLOW_THREADS
  13268. }
  13269. #endif
  13270. goto error;
  13271. }
  13272. #endif
  13273. return (PyObject *)iterator;
  13274. error:
  13275. Py_DECREF(iterator);
  13276. return NULL;
  13277. }
  13278. /*
  13279. Return the file system path representation of the object.
  13280. If the object is str or bytes, then allow it to pass through with
  13281. an incremented refcount. If the object defines __fspath__(), then
  13282. return the result of that method. All other types raise a TypeError.
  13283. */
  13284. PyObject *
  13285. PyOS_FSPath(PyObject *path)
  13286. {
  13287. /* For error message reasons, this function is manually inlined in
  13288. path_converter(). */
  13289. PyObject *func = NULL;
  13290. PyObject *path_repr = NULL;
  13291. if (PyUnicode_Check(path) || PyBytes_Check(path)) {
  13292. return Py_NewRef(path);
  13293. }
  13294. func = _PyObject_LookupSpecial(path, &_Py_ID(__fspath__));
  13295. if (NULL == func) {
  13296. return PyErr_Format(PyExc_TypeError,
  13297. "expected str, bytes or os.PathLike object, "
  13298. "not %.200s",
  13299. _PyType_Name(Py_TYPE(path)));
  13300. }
  13301. path_repr = _PyObject_CallNoArgs(func);
  13302. Py_DECREF(func);
  13303. if (NULL == path_repr) {
  13304. return NULL;
  13305. }
  13306. if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
  13307. PyErr_Format(PyExc_TypeError,
  13308. "expected %.200s.__fspath__() to return str or bytes, "
  13309. "not %.200s", _PyType_Name(Py_TYPE(path)),
  13310. _PyType_Name(Py_TYPE(path_repr)));
  13311. Py_DECREF(path_repr);
  13312. return NULL;
  13313. }
  13314. return path_repr;
  13315. }
  13316. /*[clinic input]
  13317. os.fspath
  13318. path: object
  13319. Return the file system path representation of the object.
  13320. If the object is str or bytes, then allow it to pass through as-is. If the
  13321. object defines __fspath__(), then return the result of that method. All other
  13322. types raise a TypeError.
  13323. [clinic start generated code]*/
  13324. static PyObject *
  13325. os_fspath_impl(PyObject *module, PyObject *path)
  13326. /*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
  13327. {
  13328. return PyOS_FSPath(path);
  13329. }
  13330. #ifdef HAVE_GETRANDOM_SYSCALL
  13331. /*[clinic input]
  13332. os.getrandom
  13333. size: Py_ssize_t
  13334. flags: int=0
  13335. Obtain a series of random bytes.
  13336. [clinic start generated code]*/
  13337. static PyObject *
  13338. os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
  13339. /*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
  13340. {
  13341. PyObject *bytes;
  13342. Py_ssize_t n;
  13343. if (size < 0) {
  13344. errno = EINVAL;
  13345. return posix_error();
  13346. }
  13347. bytes = PyBytes_FromStringAndSize(NULL, size);
  13348. if (bytes == NULL) {
  13349. PyErr_NoMemory();
  13350. return NULL;
  13351. }
  13352. while (1) {
  13353. n = syscall(SYS_getrandom,
  13354. PyBytes_AS_STRING(bytes),
  13355. PyBytes_GET_SIZE(bytes),
  13356. flags);
  13357. if (n < 0 && errno == EINTR) {
  13358. if (PyErr_CheckSignals() < 0) {
  13359. goto error;
  13360. }
  13361. /* getrandom() was interrupted by a signal: retry */
  13362. continue;
  13363. }
  13364. break;
  13365. }
  13366. if (n < 0) {
  13367. PyErr_SetFromErrno(PyExc_OSError);
  13368. goto error;
  13369. }
  13370. if (n != size) {
  13371. _PyBytes_Resize(&bytes, n);
  13372. }
  13373. return bytes;
  13374. error:
  13375. Py_DECREF(bytes);
  13376. return NULL;
  13377. }
  13378. #endif /* HAVE_GETRANDOM_SYSCALL */
  13379. #if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
  13380. /* bpo-36085: Helper functions for managing DLL search directories
  13381. * on win32
  13382. */
  13383. /*[clinic input]
  13384. os._add_dll_directory
  13385. path: path_t
  13386. Add a path to the DLL search path.
  13387. This search path is used when resolving dependencies for imported
  13388. extension modules (the module itself is resolved through sys.path),
  13389. and also by ctypes.
  13390. Returns an opaque value that may be passed to os.remove_dll_directory
  13391. to remove this directory from the search path.
  13392. [clinic start generated code]*/
  13393. static PyObject *
  13394. os__add_dll_directory_impl(PyObject *module, path_t *path)
  13395. /*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
  13396. {
  13397. DLL_DIRECTORY_COOKIE cookie = 0;
  13398. DWORD err = 0;
  13399. if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
  13400. return NULL;
  13401. }
  13402. Py_BEGIN_ALLOW_THREADS
  13403. if (!(cookie = AddDllDirectory(path->wide))) {
  13404. err = GetLastError();
  13405. }
  13406. Py_END_ALLOW_THREADS
  13407. if (err) {
  13408. return win32_error_object_err("add_dll_directory",
  13409. path->object, err);
  13410. }
  13411. return PyCapsule_New(cookie, "DLL directory cookie", NULL);
  13412. }
  13413. /*[clinic input]
  13414. os._remove_dll_directory
  13415. cookie: object
  13416. Removes a path from the DLL search path.
  13417. The parameter is an opaque value that was returned from
  13418. os.add_dll_directory. You can only remove directories that you added
  13419. yourself.
  13420. [clinic start generated code]*/
  13421. static PyObject *
  13422. os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
  13423. /*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
  13424. {
  13425. DLL_DIRECTORY_COOKIE cookieValue;
  13426. DWORD err = 0;
  13427. if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
  13428. PyErr_SetString(PyExc_TypeError,
  13429. "Provided cookie was not returned from os.add_dll_directory");
  13430. return NULL;
  13431. }
  13432. cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
  13433. cookie, "DLL directory cookie");
  13434. Py_BEGIN_ALLOW_THREADS
  13435. if (!RemoveDllDirectory(cookieValue)) {
  13436. err = GetLastError();
  13437. }
  13438. Py_END_ALLOW_THREADS
  13439. if (err) {
  13440. return win32_error_object_err("remove_dll_directory",
  13441. NULL, err);
  13442. }
  13443. if (PyCapsule_SetName(cookie, NULL)) {
  13444. return NULL;
  13445. }
  13446. Py_RETURN_NONE;
  13447. }
  13448. #endif /* MS_WINDOWS_APP || MS_WINDOWS_SYSTEM */
  13449. /* Only check if WIFEXITED is available: expect that it comes
  13450. with WEXITSTATUS, WIFSIGNALED, etc.
  13451. os.waitstatus_to_exitcode() is implemented in C and not in Python, so
  13452. subprocess can safely call it during late Python finalization without
  13453. risking that used os attributes were set to None by finalize_modules(). */
  13454. #if defined(WIFEXITED) || defined(MS_WINDOWS)
  13455. /*[clinic input]
  13456. os.waitstatus_to_exitcode
  13457. status as status_obj: object
  13458. Convert a wait status to an exit code.
  13459. On Unix:
  13460. * If WIFEXITED(status) is true, return WEXITSTATUS(status).
  13461. * If WIFSIGNALED(status) is true, return -WTERMSIG(status).
  13462. * Otherwise, raise a ValueError.
  13463. On Windows, return status shifted right by 8 bits.
  13464. On Unix, if the process is being traced or if waitpid() was called with
  13465. WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true.
  13466. This function must not be called if WIFSTOPPED(status) is true.
  13467. [clinic start generated code]*/
  13468. static PyObject *
  13469. os_waitstatus_to_exitcode_impl(PyObject *module, PyObject *status_obj)
  13470. /*[clinic end generated code: output=db50b1b0ba3c7153 input=7fe2d7fdaea3db42]*/
  13471. {
  13472. #ifndef MS_WINDOWS
  13473. int status = _PyLong_AsInt(status_obj);
  13474. if (status == -1 && PyErr_Occurred()) {
  13475. return NULL;
  13476. }
  13477. WAIT_TYPE wait_status;
  13478. WAIT_STATUS_INT(wait_status) = status;
  13479. int exitcode;
  13480. if (WIFEXITED(wait_status)) {
  13481. exitcode = WEXITSTATUS(wait_status);
  13482. /* Sanity check to provide warranty on the function behavior.
  13483. It should not occur in practice */
  13484. if (exitcode < 0) {
  13485. PyErr_Format(PyExc_ValueError, "invalid WEXITSTATUS: %i", exitcode);
  13486. return NULL;
  13487. }
  13488. }
  13489. else if (WIFSIGNALED(wait_status)) {
  13490. int signum = WTERMSIG(wait_status);
  13491. /* Sanity check to provide warranty on the function behavior.
  13492. It should not occurs in practice */
  13493. if (signum <= 0) {
  13494. PyErr_Format(PyExc_ValueError, "invalid WTERMSIG: %i", signum);
  13495. return NULL;
  13496. }
  13497. exitcode = -signum;
  13498. } else if (WIFSTOPPED(wait_status)) {
  13499. /* Status only received if the process is being traced
  13500. or if waitpid() was called with WUNTRACED option. */
  13501. int signum = WSTOPSIG(wait_status);
  13502. PyErr_Format(PyExc_ValueError,
  13503. "process stopped by delivery of signal %i",
  13504. signum);
  13505. return NULL;
  13506. }
  13507. else {
  13508. PyErr_Format(PyExc_ValueError, "invalid wait status: %i", status);
  13509. return NULL;
  13510. }
  13511. return PyLong_FromLong(exitcode);
  13512. #else
  13513. /* Windows implementation: see os.waitpid() implementation
  13514. which uses _cwait(). */
  13515. unsigned long long status = PyLong_AsUnsignedLongLong(status_obj);
  13516. if (status == (unsigned long long)-1 && PyErr_Occurred()) {
  13517. return NULL;
  13518. }
  13519. unsigned long long exitcode = (status >> 8);
  13520. /* ExitProcess() accepts an UINT type:
  13521. reject exit code which doesn't fit in an UINT */
  13522. if (exitcode > UINT_MAX) {
  13523. PyErr_Format(PyExc_ValueError, "invalid exit code: %llu", exitcode);
  13524. return NULL;
  13525. }
  13526. return PyLong_FromUnsignedLong((unsigned long)exitcode);
  13527. #endif
  13528. }
  13529. #endif
  13530. static PyMethodDef posix_methods[] = {
  13531. OS_STAT_METHODDEF
  13532. OS_ACCESS_METHODDEF
  13533. OS_TTYNAME_METHODDEF
  13534. OS_CHDIR_METHODDEF
  13535. OS_CHFLAGS_METHODDEF
  13536. OS_CHMOD_METHODDEF
  13537. OS_FCHMOD_METHODDEF
  13538. OS_LCHMOD_METHODDEF
  13539. OS_CHOWN_METHODDEF
  13540. OS_FCHOWN_METHODDEF
  13541. OS_LCHOWN_METHODDEF
  13542. OS_LCHFLAGS_METHODDEF
  13543. OS_CHROOT_METHODDEF
  13544. OS_CTERMID_METHODDEF
  13545. OS_GETCWD_METHODDEF
  13546. OS_GETCWDB_METHODDEF
  13547. OS_LINK_METHODDEF
  13548. OS_LISTDIR_METHODDEF
  13549. OS_LISTDRIVES_METHODDEF
  13550. OS_LISTMOUNTS_METHODDEF
  13551. OS_LISTVOLUMES_METHODDEF
  13552. OS_LSTAT_METHODDEF
  13553. OS_MKDIR_METHODDEF
  13554. OS_NICE_METHODDEF
  13555. OS_GETPRIORITY_METHODDEF
  13556. OS_SETPRIORITY_METHODDEF
  13557. OS_POSIX_SPAWN_METHODDEF
  13558. OS_POSIX_SPAWNP_METHODDEF
  13559. OS_READLINK_METHODDEF
  13560. OS_COPY_FILE_RANGE_METHODDEF
  13561. OS_SPLICE_METHODDEF
  13562. OS_RENAME_METHODDEF
  13563. OS_REPLACE_METHODDEF
  13564. OS_RMDIR_METHODDEF
  13565. OS_SYMLINK_METHODDEF
  13566. OS_SYSTEM_METHODDEF
  13567. OS_UMASK_METHODDEF
  13568. OS_UNAME_METHODDEF
  13569. OS_UNLINK_METHODDEF
  13570. OS_REMOVE_METHODDEF
  13571. OS_UTIME_METHODDEF
  13572. OS_TIMES_METHODDEF
  13573. OS__EXIT_METHODDEF
  13574. OS__FCOPYFILE_METHODDEF
  13575. OS_EXECV_METHODDEF
  13576. OS_EXECVE_METHODDEF
  13577. OS_SPAWNV_METHODDEF
  13578. OS_SPAWNVE_METHODDEF
  13579. OS_FORK1_METHODDEF
  13580. OS_FORK_METHODDEF
  13581. OS_REGISTER_AT_FORK_METHODDEF
  13582. OS_SCHED_GET_PRIORITY_MAX_METHODDEF
  13583. OS_SCHED_GET_PRIORITY_MIN_METHODDEF
  13584. OS_SCHED_GETPARAM_METHODDEF
  13585. OS_SCHED_GETSCHEDULER_METHODDEF
  13586. OS_SCHED_RR_GET_INTERVAL_METHODDEF
  13587. OS_SCHED_SETPARAM_METHODDEF
  13588. OS_SCHED_SETSCHEDULER_METHODDEF
  13589. OS_SCHED_YIELD_METHODDEF
  13590. OS_SCHED_SETAFFINITY_METHODDEF
  13591. OS_SCHED_GETAFFINITY_METHODDEF
  13592. OS_OPENPTY_METHODDEF
  13593. OS_LOGIN_TTY_METHODDEF
  13594. OS_FORKPTY_METHODDEF
  13595. OS_GETEGID_METHODDEF
  13596. OS_GETEUID_METHODDEF
  13597. OS_GETGID_METHODDEF
  13598. OS_GETGROUPLIST_METHODDEF
  13599. OS_GETGROUPS_METHODDEF
  13600. OS_GETPID_METHODDEF
  13601. OS_GETPGRP_METHODDEF
  13602. OS_GETPPID_METHODDEF
  13603. OS_GETUID_METHODDEF
  13604. OS_GETLOGIN_METHODDEF
  13605. OS_KILL_METHODDEF
  13606. OS_KILLPG_METHODDEF
  13607. OS_PLOCK_METHODDEF
  13608. OS_STARTFILE_METHODDEF
  13609. OS_SETUID_METHODDEF
  13610. OS_SETEUID_METHODDEF
  13611. OS_SETREUID_METHODDEF
  13612. OS_SETGID_METHODDEF
  13613. OS_SETEGID_METHODDEF
  13614. OS_SETREGID_METHODDEF
  13615. OS_SETGROUPS_METHODDEF
  13616. OS_INITGROUPS_METHODDEF
  13617. OS_GETPGID_METHODDEF
  13618. OS_SETPGRP_METHODDEF
  13619. OS_WAIT_METHODDEF
  13620. OS_WAIT3_METHODDEF
  13621. OS_WAIT4_METHODDEF
  13622. OS_WAITID_METHODDEF
  13623. OS_WAITPID_METHODDEF
  13624. OS_PIDFD_OPEN_METHODDEF
  13625. OS_GETSID_METHODDEF
  13626. OS_SETSID_METHODDEF
  13627. OS_SETPGID_METHODDEF
  13628. OS_TCGETPGRP_METHODDEF
  13629. OS_TCSETPGRP_METHODDEF
  13630. OS_OPEN_METHODDEF
  13631. OS_CLOSE_METHODDEF
  13632. OS_CLOSERANGE_METHODDEF
  13633. OS_DEVICE_ENCODING_METHODDEF
  13634. OS_DUP_METHODDEF
  13635. OS_DUP2_METHODDEF
  13636. OS_LOCKF_METHODDEF
  13637. OS_LSEEK_METHODDEF
  13638. OS_READ_METHODDEF
  13639. OS_READV_METHODDEF
  13640. OS_PREAD_METHODDEF
  13641. OS_PREADV_METHODDEF
  13642. OS_WRITE_METHODDEF
  13643. OS_WRITEV_METHODDEF
  13644. OS_PWRITE_METHODDEF
  13645. OS_PWRITEV_METHODDEF
  13646. OS_SENDFILE_METHODDEF
  13647. OS_FSTAT_METHODDEF
  13648. OS_ISATTY_METHODDEF
  13649. OS_PIPE_METHODDEF
  13650. OS_PIPE2_METHODDEF
  13651. OS_MKFIFO_METHODDEF
  13652. OS_MKNOD_METHODDEF
  13653. OS_MAJOR_METHODDEF
  13654. OS_MINOR_METHODDEF
  13655. OS_MAKEDEV_METHODDEF
  13656. OS_FTRUNCATE_METHODDEF
  13657. OS_TRUNCATE_METHODDEF
  13658. OS_POSIX_FALLOCATE_METHODDEF
  13659. OS_POSIX_FADVISE_METHODDEF
  13660. OS_PUTENV_METHODDEF
  13661. OS_UNSETENV_METHODDEF
  13662. OS_STRERROR_METHODDEF
  13663. OS_FCHDIR_METHODDEF
  13664. OS_FSYNC_METHODDEF
  13665. OS_SYNC_METHODDEF
  13666. OS_FDATASYNC_METHODDEF
  13667. OS_WCOREDUMP_METHODDEF
  13668. OS_WIFCONTINUED_METHODDEF
  13669. OS_WIFSTOPPED_METHODDEF
  13670. OS_WIFSIGNALED_METHODDEF
  13671. OS_WIFEXITED_METHODDEF
  13672. OS_WEXITSTATUS_METHODDEF
  13673. OS_WTERMSIG_METHODDEF
  13674. OS_WSTOPSIG_METHODDEF
  13675. OS_FSTATVFS_METHODDEF
  13676. OS_STATVFS_METHODDEF
  13677. OS_CONFSTR_METHODDEF
  13678. OS_SYSCONF_METHODDEF
  13679. OS_FPATHCONF_METHODDEF
  13680. OS_PATHCONF_METHODDEF
  13681. OS_ABORT_METHODDEF
  13682. OS__GETFULLPATHNAME_METHODDEF
  13683. OS__GETDISKUSAGE_METHODDEF
  13684. OS__GETFINALPATHNAME_METHODDEF
  13685. OS__GETVOLUMEPATHNAME_METHODDEF
  13686. OS__PATH_SPLITROOT_METHODDEF
  13687. OS__PATH_NORMPATH_METHODDEF
  13688. OS_GETLOADAVG_METHODDEF
  13689. OS_URANDOM_METHODDEF
  13690. OS_SETRESUID_METHODDEF
  13691. OS_SETRESGID_METHODDEF
  13692. OS_GETRESUID_METHODDEF
  13693. OS_GETRESGID_METHODDEF
  13694. OS_GETXATTR_METHODDEF
  13695. OS_SETXATTR_METHODDEF
  13696. OS_REMOVEXATTR_METHODDEF
  13697. OS_LISTXATTR_METHODDEF
  13698. OS_GET_TERMINAL_SIZE_METHODDEF
  13699. OS_CPU_COUNT_METHODDEF
  13700. OS_GET_INHERITABLE_METHODDEF
  13701. OS_SET_INHERITABLE_METHODDEF
  13702. OS_GET_HANDLE_INHERITABLE_METHODDEF
  13703. OS_SET_HANDLE_INHERITABLE_METHODDEF
  13704. OS_GET_BLOCKING_METHODDEF
  13705. OS_SET_BLOCKING_METHODDEF
  13706. OS_SCANDIR_METHODDEF
  13707. OS_FSPATH_METHODDEF
  13708. OS_GETRANDOM_METHODDEF
  13709. OS_MEMFD_CREATE_METHODDEF
  13710. OS_EVENTFD_METHODDEF
  13711. OS_EVENTFD_READ_METHODDEF
  13712. OS_EVENTFD_WRITE_METHODDEF
  13713. OS__ADD_DLL_DIRECTORY_METHODDEF
  13714. OS__REMOVE_DLL_DIRECTORY_METHODDEF
  13715. OS_WAITSTATUS_TO_EXITCODE_METHODDEF
  13716. OS_SETNS_METHODDEF
  13717. OS_UNSHARE_METHODDEF
  13718. OS__PATH_ISDEVDRIVE_METHODDEF
  13719. OS__PATH_ISDIR_METHODDEF
  13720. OS__PATH_ISFILE_METHODDEF
  13721. OS__PATH_ISLINK_METHODDEF
  13722. OS__PATH_EXISTS_METHODDEF
  13723. {NULL, NULL} /* Sentinel */
  13724. };
  13725. static int
  13726. all_ins(PyObject *m)
  13727. {
  13728. #ifdef F_OK
  13729. if (PyModule_AddIntMacro(m, F_OK)) return -1;
  13730. #endif
  13731. #ifdef R_OK
  13732. if (PyModule_AddIntMacro(m, R_OK)) return -1;
  13733. #endif
  13734. #ifdef W_OK
  13735. if (PyModule_AddIntMacro(m, W_OK)) return -1;
  13736. #endif
  13737. #ifdef X_OK
  13738. if (PyModule_AddIntMacro(m, X_OK)) return -1;
  13739. #endif
  13740. #ifdef NGROUPS_MAX
  13741. if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
  13742. #endif
  13743. #ifdef TMP_MAX
  13744. if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
  13745. #endif
  13746. #ifdef WCONTINUED
  13747. if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
  13748. #endif
  13749. #ifdef WNOHANG
  13750. if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
  13751. #endif
  13752. #ifdef WUNTRACED
  13753. if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
  13754. #endif
  13755. #ifdef O_RDONLY
  13756. if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
  13757. #endif
  13758. #ifdef O_WRONLY
  13759. if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
  13760. #endif
  13761. #ifdef O_RDWR
  13762. if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
  13763. #endif
  13764. #ifdef O_NDELAY
  13765. if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
  13766. #endif
  13767. #ifdef O_NONBLOCK
  13768. if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
  13769. #endif
  13770. #ifdef O_APPEND
  13771. if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
  13772. #endif
  13773. #ifdef O_DSYNC
  13774. if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
  13775. #endif
  13776. #ifdef O_RSYNC
  13777. if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
  13778. #endif
  13779. #ifdef O_SYNC
  13780. if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
  13781. #endif
  13782. #ifdef O_NOCTTY
  13783. if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
  13784. #endif
  13785. #ifdef O_CREAT
  13786. if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
  13787. #endif
  13788. #ifdef O_EXCL
  13789. if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
  13790. #endif
  13791. #ifdef O_TRUNC
  13792. if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
  13793. #endif
  13794. #ifdef O_BINARY
  13795. if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
  13796. #endif
  13797. #ifdef O_TEXT
  13798. if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
  13799. #endif
  13800. #ifdef O_XATTR
  13801. if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
  13802. #endif
  13803. #ifdef O_LARGEFILE
  13804. if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
  13805. #endif
  13806. #ifndef __GNU__
  13807. #ifdef O_SHLOCK
  13808. if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
  13809. #endif
  13810. #ifdef O_EXLOCK
  13811. if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
  13812. #endif
  13813. #endif
  13814. #ifdef O_EXEC
  13815. if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
  13816. #endif
  13817. #ifdef O_SEARCH
  13818. if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
  13819. #endif
  13820. #ifdef O_PATH
  13821. if (PyModule_AddIntMacro(m, O_PATH)) return -1;
  13822. #endif
  13823. #ifdef O_TTY_INIT
  13824. if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
  13825. #endif
  13826. #ifdef O_TMPFILE
  13827. if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
  13828. #endif
  13829. #ifdef PRIO_PROCESS
  13830. if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
  13831. #endif
  13832. #ifdef PRIO_PGRP
  13833. if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
  13834. #endif
  13835. #ifdef PRIO_USER
  13836. if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
  13837. #endif
  13838. #ifdef PRIO_DARWIN_THREAD
  13839. if (PyModule_AddIntMacro(m, PRIO_DARWIN_THREAD)) return -1;
  13840. #endif
  13841. #ifdef PRIO_DARWIN_PROCESS
  13842. if (PyModule_AddIntMacro(m, PRIO_DARWIN_PROCESS)) return -1;
  13843. #endif
  13844. #ifdef PRIO_DARWIN_BG
  13845. if (PyModule_AddIntMacro(m, PRIO_DARWIN_BG)) return -1;
  13846. #endif
  13847. #ifdef PRIO_DARWIN_NONUI
  13848. if (PyModule_AddIntMacro(m, PRIO_DARWIN_NONUI)) return -1;
  13849. #endif
  13850. #ifdef O_CLOEXEC
  13851. if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
  13852. #endif
  13853. #ifdef O_ACCMODE
  13854. if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
  13855. #endif
  13856. #ifdef O_EVTONLY
  13857. if (PyModule_AddIntMacro(m, O_EVTONLY)) return -1;
  13858. #endif
  13859. #ifdef O_FSYNC
  13860. if (PyModule_AddIntMacro(m, O_FSYNC)) return -1;
  13861. #endif
  13862. #ifdef O_SYMLINK
  13863. if (PyModule_AddIntMacro(m, O_SYMLINK)) return -1;
  13864. #endif
  13865. #ifdef SEEK_HOLE
  13866. if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
  13867. #endif
  13868. #ifdef SEEK_DATA
  13869. if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
  13870. #endif
  13871. /* MS Windows */
  13872. #ifdef O_NOINHERIT
  13873. /* Don't inherit in child processes. */
  13874. if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
  13875. #endif
  13876. #ifdef _O_SHORT_LIVED
  13877. /* Optimize for short life (keep in memory). */
  13878. /* MS forgot to define this one with a non-underscore form too. */
  13879. if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
  13880. #endif
  13881. #ifdef O_TEMPORARY
  13882. /* Automatically delete when last handle is closed. */
  13883. if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
  13884. #endif
  13885. #ifdef O_RANDOM
  13886. /* Optimize for random access. */
  13887. if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
  13888. #endif
  13889. #ifdef O_SEQUENTIAL
  13890. /* Optimize for sequential access. */
  13891. if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
  13892. #endif
  13893. /* GNU extensions. */
  13894. #ifdef O_ASYNC
  13895. /* Send a SIGIO signal whenever input or output
  13896. becomes available on file descriptor */
  13897. if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
  13898. #endif
  13899. #ifdef O_DIRECT
  13900. /* Direct disk access. */
  13901. if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
  13902. #endif
  13903. #ifdef O_DIRECTORY
  13904. /* Must be a directory. */
  13905. if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
  13906. #endif
  13907. #ifdef O_NOFOLLOW
  13908. /* Do not follow links. */
  13909. if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
  13910. #endif
  13911. #ifdef O_NOFOLLOW_ANY
  13912. if (PyModule_AddIntMacro(m, O_NOFOLLOW_ANY)) return -1;
  13913. #endif
  13914. #ifdef O_NOLINKS
  13915. /* Fails if link count of the named file is greater than 1 */
  13916. if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
  13917. #endif
  13918. #ifdef O_NOATIME
  13919. /* Do not update the access time. */
  13920. if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
  13921. #endif
  13922. /* These come from sysexits.h */
  13923. #ifdef EX_OK
  13924. if (PyModule_AddIntMacro(m, EX_OK)) return -1;
  13925. #endif /* EX_OK */
  13926. #ifdef EX_USAGE
  13927. if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
  13928. #endif /* EX_USAGE */
  13929. #ifdef EX_DATAERR
  13930. if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
  13931. #endif /* EX_DATAERR */
  13932. #ifdef EX_NOINPUT
  13933. if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
  13934. #endif /* EX_NOINPUT */
  13935. #ifdef EX_NOUSER
  13936. if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
  13937. #endif /* EX_NOUSER */
  13938. #ifdef EX_NOHOST
  13939. if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
  13940. #endif /* EX_NOHOST */
  13941. #ifdef EX_UNAVAILABLE
  13942. if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
  13943. #endif /* EX_UNAVAILABLE */
  13944. #ifdef EX_SOFTWARE
  13945. if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
  13946. #endif /* EX_SOFTWARE */
  13947. #ifdef EX_OSERR
  13948. if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
  13949. #endif /* EX_OSERR */
  13950. #ifdef EX_OSFILE
  13951. if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
  13952. #endif /* EX_OSFILE */
  13953. #ifdef EX_CANTCREAT
  13954. if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
  13955. #endif /* EX_CANTCREAT */
  13956. #ifdef EX_IOERR
  13957. if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
  13958. #endif /* EX_IOERR */
  13959. #ifdef EX_TEMPFAIL
  13960. if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
  13961. #endif /* EX_TEMPFAIL */
  13962. #ifdef EX_PROTOCOL
  13963. if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
  13964. #endif /* EX_PROTOCOL */
  13965. #ifdef EX_NOPERM
  13966. if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
  13967. #endif /* EX_NOPERM */
  13968. #ifdef EX_CONFIG
  13969. if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
  13970. #endif /* EX_CONFIG */
  13971. #ifdef EX_NOTFOUND
  13972. if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
  13973. #endif /* EX_NOTFOUND */
  13974. /* statvfs */
  13975. #ifdef ST_RDONLY
  13976. if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
  13977. #endif /* ST_RDONLY */
  13978. #ifdef ST_NOSUID
  13979. if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
  13980. #endif /* ST_NOSUID */
  13981. /* GNU extensions */
  13982. #ifdef ST_NODEV
  13983. if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
  13984. #endif /* ST_NODEV */
  13985. #ifdef ST_NOEXEC
  13986. if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
  13987. #endif /* ST_NOEXEC */
  13988. #ifdef ST_SYNCHRONOUS
  13989. if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
  13990. #endif /* ST_SYNCHRONOUS */
  13991. #ifdef ST_MANDLOCK
  13992. if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
  13993. #endif /* ST_MANDLOCK */
  13994. #ifdef ST_WRITE
  13995. if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
  13996. #endif /* ST_WRITE */
  13997. #ifdef ST_APPEND
  13998. if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
  13999. #endif /* ST_APPEND */
  14000. #ifdef ST_NOATIME
  14001. if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
  14002. #endif /* ST_NOATIME */
  14003. #ifdef ST_NODIRATIME
  14004. if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
  14005. #endif /* ST_NODIRATIME */
  14006. #ifdef ST_RELATIME
  14007. if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
  14008. #endif /* ST_RELATIME */
  14009. /* FreeBSD sendfile() constants */
  14010. #ifdef SF_NODISKIO
  14011. if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
  14012. #endif
  14013. /* is obsolete since the 11.x release */
  14014. #ifdef SF_MNOWAIT
  14015. if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
  14016. #endif
  14017. #ifdef SF_SYNC
  14018. if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
  14019. #endif
  14020. #ifdef SF_NOCACHE
  14021. if (PyModule_AddIntMacro(m, SF_NOCACHE)) return -1;
  14022. #endif
  14023. /* constants for posix_fadvise */
  14024. #ifdef POSIX_FADV_NORMAL
  14025. if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
  14026. #endif
  14027. #ifdef POSIX_FADV_SEQUENTIAL
  14028. if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
  14029. #endif
  14030. #ifdef POSIX_FADV_RANDOM
  14031. if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
  14032. #endif
  14033. #ifdef POSIX_FADV_NOREUSE
  14034. if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
  14035. #endif
  14036. #ifdef POSIX_FADV_WILLNEED
  14037. if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
  14038. #endif
  14039. #ifdef POSIX_FADV_DONTNEED
  14040. if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
  14041. #endif
  14042. /* constants for waitid */
  14043. #if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
  14044. if (PyModule_AddIntMacro(m, P_PID)) return -1;
  14045. if (PyModule_AddIntMacro(m, P_PGID)) return -1;
  14046. if (PyModule_AddIntMacro(m, P_ALL)) return -1;
  14047. #ifdef P_PIDFD
  14048. if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
  14049. #endif
  14050. #ifdef PIDFD_NONBLOCK
  14051. if (PyModule_AddIntMacro(m, PIDFD_NONBLOCK)) return -1;
  14052. #endif
  14053. #endif
  14054. #ifdef WEXITED
  14055. if (PyModule_AddIntMacro(m, WEXITED)) return -1;
  14056. #endif
  14057. #ifdef WNOWAIT
  14058. if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
  14059. #endif
  14060. #ifdef WSTOPPED
  14061. if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
  14062. #endif
  14063. #ifdef CLD_EXITED
  14064. if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
  14065. #endif
  14066. #ifdef CLD_KILLED
  14067. if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
  14068. #endif
  14069. #ifdef CLD_DUMPED
  14070. if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
  14071. #endif
  14072. #ifdef CLD_TRAPPED
  14073. if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
  14074. #endif
  14075. #ifdef CLD_STOPPED
  14076. if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
  14077. #endif
  14078. #ifdef CLD_CONTINUED
  14079. if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
  14080. #endif
  14081. /* constants for lockf */
  14082. #ifdef F_LOCK
  14083. if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
  14084. #endif
  14085. #ifdef F_TLOCK
  14086. if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
  14087. #endif
  14088. #ifdef F_ULOCK
  14089. if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
  14090. #endif
  14091. #ifdef F_TEST
  14092. if (PyModule_AddIntMacro(m, F_TEST)) return -1;
  14093. #endif
  14094. #ifdef RWF_DSYNC
  14095. if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
  14096. #endif
  14097. #ifdef RWF_HIPRI
  14098. if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
  14099. #endif
  14100. #ifdef RWF_SYNC
  14101. if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
  14102. #endif
  14103. #ifdef RWF_NOWAIT
  14104. if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
  14105. #endif
  14106. #ifdef RWF_APPEND
  14107. if (PyModule_AddIntConstant(m, "RWF_APPEND", RWF_APPEND)) return -1;
  14108. #endif
  14109. /* constants for splice */
  14110. #if defined(HAVE_SPLICE) && defined(__linux__)
  14111. if (PyModule_AddIntConstant(m, "SPLICE_F_MOVE", SPLICE_F_MOVE)) return -1;
  14112. if (PyModule_AddIntConstant(m, "SPLICE_F_NONBLOCK", SPLICE_F_NONBLOCK)) return -1;
  14113. if (PyModule_AddIntConstant(m, "SPLICE_F_MORE", SPLICE_F_MORE)) return -1;
  14114. #endif
  14115. /* constants for posix_spawn */
  14116. #ifdef HAVE_POSIX_SPAWN
  14117. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
  14118. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
  14119. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
  14120. #endif
  14121. #if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
  14122. if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
  14123. if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
  14124. if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
  14125. #endif
  14126. #ifdef HAVE_SPAWNV
  14127. if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
  14128. if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
  14129. #endif
  14130. #ifdef HAVE_SCHED_H
  14131. #ifdef SCHED_OTHER
  14132. if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
  14133. #endif
  14134. #ifdef SCHED_FIFO
  14135. if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
  14136. #endif
  14137. #ifdef SCHED_RR
  14138. if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
  14139. #endif
  14140. #ifdef SCHED_SPORADIC
  14141. if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
  14142. #endif
  14143. #ifdef SCHED_BATCH
  14144. if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
  14145. #endif
  14146. #ifdef SCHED_IDLE
  14147. if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
  14148. #endif
  14149. #ifdef SCHED_RESET_ON_FORK
  14150. if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
  14151. #endif
  14152. #ifdef SCHED_SYS
  14153. if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
  14154. #endif
  14155. #ifdef SCHED_IA
  14156. if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
  14157. #endif
  14158. #ifdef SCHED_FSS
  14159. if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
  14160. #endif
  14161. #ifdef SCHED_FX
  14162. if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
  14163. #endif
  14164. /* constants for namespaces */
  14165. #if defined(HAVE_SETNS) || defined(HAVE_UNSHARE)
  14166. #ifdef CLONE_FS
  14167. if (PyModule_AddIntMacro(m, CLONE_FS)) return -1;
  14168. #endif
  14169. #ifdef CLONE_FILES
  14170. if (PyModule_AddIntMacro(m, CLONE_FILES)) return -1;
  14171. #endif
  14172. #ifdef CLONE_NEWNS
  14173. if (PyModule_AddIntMacro(m, CLONE_NEWNS)) return -1;
  14174. #endif
  14175. #ifdef CLONE_NEWCGROUP
  14176. if (PyModule_AddIntMacro(m, CLONE_NEWCGROUP)) return -1;
  14177. #endif
  14178. #ifdef CLONE_NEWUTS
  14179. if (PyModule_AddIntMacro(m, CLONE_NEWUTS)) return -1;
  14180. #endif
  14181. #ifdef CLONE_NEWIPC
  14182. if (PyModule_AddIntMacro(m, CLONE_NEWIPC)) return -1;
  14183. #endif
  14184. #ifdef CLONE_NEWUSER
  14185. if (PyModule_AddIntMacro(m, CLONE_NEWUSER)) return -1;
  14186. #endif
  14187. #ifdef CLONE_NEWPID
  14188. if (PyModule_AddIntMacro(m, CLONE_NEWPID)) return -1;
  14189. #endif
  14190. #ifdef CLONE_NEWNET
  14191. if (PyModule_AddIntMacro(m, CLONE_NEWNET)) return -1;
  14192. #endif
  14193. #ifdef CLONE_NEWTIME
  14194. if (PyModule_AddIntMacro(m, CLONE_NEWTIME)) return -1;
  14195. #endif
  14196. #ifdef CLONE_SYSVSEM
  14197. if (PyModule_AddIntMacro(m, CLONE_SYSVSEM)) return -1;
  14198. #endif
  14199. #ifdef CLONE_THREAD
  14200. if (PyModule_AddIntMacro(m, CLONE_THREAD)) return -1;
  14201. #endif
  14202. #ifdef CLONE_SIGHAND
  14203. if (PyModule_AddIntMacro(m, CLONE_SIGHAND)) return -1;
  14204. #endif
  14205. #ifdef CLONE_VM
  14206. if (PyModule_AddIntMacro(m, CLONE_VM)) return -1;
  14207. #endif
  14208. #endif
  14209. #endif
  14210. #ifdef USE_XATTRS
  14211. if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
  14212. if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
  14213. if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
  14214. #endif
  14215. #if HAVE_DECL_RTLD_LAZY
  14216. if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
  14217. #endif
  14218. #if HAVE_DECL_RTLD_NOW
  14219. if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
  14220. #endif
  14221. #if HAVE_DECL_RTLD_GLOBAL
  14222. if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
  14223. #endif
  14224. #if HAVE_DECL_RTLD_LOCAL
  14225. if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
  14226. #endif
  14227. #if HAVE_DECL_RTLD_NODELETE
  14228. if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
  14229. #endif
  14230. #if HAVE_DECL_RTLD_NOLOAD
  14231. if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
  14232. #endif
  14233. #if HAVE_DECL_RTLD_DEEPBIND
  14234. if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
  14235. #endif
  14236. #if HAVE_DECL_RTLD_MEMBER
  14237. if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
  14238. #endif
  14239. #ifdef HAVE_GETRANDOM_SYSCALL
  14240. if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
  14241. if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
  14242. #endif
  14243. #ifdef HAVE_MEMFD_CREATE
  14244. if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
  14245. if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
  14246. #ifdef MFD_HUGETLB
  14247. if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
  14248. #endif
  14249. #ifdef MFD_HUGE_SHIFT
  14250. if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
  14251. #endif
  14252. #ifdef MFD_HUGE_MASK
  14253. if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
  14254. #endif
  14255. #ifdef MFD_HUGE_64KB
  14256. if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
  14257. #endif
  14258. #ifdef MFD_HUGE_512KB
  14259. if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
  14260. #endif
  14261. #ifdef MFD_HUGE_1MB
  14262. if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
  14263. #endif
  14264. #ifdef MFD_HUGE_2MB
  14265. if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
  14266. #endif
  14267. #ifdef MFD_HUGE_8MB
  14268. if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
  14269. #endif
  14270. #ifdef MFD_HUGE_16MB
  14271. if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
  14272. #endif
  14273. #ifdef MFD_HUGE_32MB
  14274. if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
  14275. #endif
  14276. #ifdef MFD_HUGE_256MB
  14277. if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
  14278. #endif
  14279. #ifdef MFD_HUGE_512MB
  14280. if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
  14281. #endif
  14282. #ifdef MFD_HUGE_1GB
  14283. if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
  14284. #endif
  14285. #ifdef MFD_HUGE_2GB
  14286. if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
  14287. #endif
  14288. #ifdef MFD_HUGE_16GB
  14289. if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
  14290. #endif
  14291. #endif /* HAVE_MEMFD_CREATE */
  14292. #if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
  14293. if (PyModule_AddIntMacro(m, EFD_CLOEXEC)) return -1;
  14294. #ifdef EFD_NONBLOCK
  14295. if (PyModule_AddIntMacro(m, EFD_NONBLOCK)) return -1;
  14296. #endif
  14297. #ifdef EFD_SEMAPHORE
  14298. if (PyModule_AddIntMacro(m, EFD_SEMAPHORE)) return -1;
  14299. #endif
  14300. #endif /* HAVE_EVENTFD && EFD_CLOEXEC */
  14301. #if defined(__APPLE__)
  14302. if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
  14303. if (PyModule_AddIntConstant(m, "_COPYFILE_STAT", COPYFILE_STAT)) return -1;
  14304. if (PyModule_AddIntConstant(m, "_COPYFILE_ACL", COPYFILE_ACL)) return -1;
  14305. if (PyModule_AddIntConstant(m, "_COPYFILE_XATTR", COPYFILE_XATTR)) return -1;
  14306. #endif
  14307. #ifdef MS_WINDOWS
  14308. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
  14309. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
  14310. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
  14311. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
  14312. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
  14313. #endif
  14314. return 0;
  14315. }
  14316. #define PROBE(name, test) \
  14317. static int name(void) \
  14318. { \
  14319. if (test) { \
  14320. return 1; \
  14321. } else { \
  14322. return 0; \
  14323. } \
  14324. }
  14325. #ifdef HAVE_FSTATAT
  14326. PROBE(probe_fstatat, HAVE_FSTATAT_RUNTIME)
  14327. #endif
  14328. #ifdef HAVE_FACCESSAT
  14329. PROBE(probe_faccessat, HAVE_FACCESSAT_RUNTIME)
  14330. #endif
  14331. #ifdef HAVE_FCHMODAT
  14332. PROBE(probe_fchmodat, HAVE_FCHMODAT_RUNTIME)
  14333. #endif
  14334. #ifdef HAVE_FCHOWNAT
  14335. PROBE(probe_fchownat, HAVE_FCHOWNAT_RUNTIME)
  14336. #endif
  14337. #ifdef HAVE_LINKAT
  14338. PROBE(probe_linkat, HAVE_LINKAT_RUNTIME)
  14339. #endif
  14340. #ifdef HAVE_FDOPENDIR
  14341. PROBE(probe_fdopendir, HAVE_FDOPENDIR_RUNTIME)
  14342. #endif
  14343. #ifdef HAVE_MKDIRAT
  14344. PROBE(probe_mkdirat, HAVE_MKDIRAT_RUNTIME)
  14345. #endif
  14346. #ifdef HAVE_MKFIFOAT
  14347. PROBE(probe_mkfifoat, HAVE_MKFIFOAT_RUNTIME)
  14348. #endif
  14349. #ifdef HAVE_MKNODAT
  14350. PROBE(probe_mknodat, HAVE_MKNODAT_RUNTIME)
  14351. #endif
  14352. #ifdef HAVE_RENAMEAT
  14353. PROBE(probe_renameat, HAVE_RENAMEAT_RUNTIME)
  14354. #endif
  14355. #ifdef HAVE_UNLINKAT
  14356. PROBE(probe_unlinkat, HAVE_UNLINKAT_RUNTIME)
  14357. #endif
  14358. #ifdef HAVE_OPENAT
  14359. PROBE(probe_openat, HAVE_OPENAT_RUNTIME)
  14360. #endif
  14361. #ifdef HAVE_READLINKAT
  14362. PROBE(probe_readlinkat, HAVE_READLINKAT_RUNTIME)
  14363. #endif
  14364. #ifdef HAVE_SYMLINKAT
  14365. PROBE(probe_symlinkat, HAVE_SYMLINKAT_RUNTIME)
  14366. #endif
  14367. #ifdef HAVE_FUTIMENS
  14368. PROBE(probe_futimens, HAVE_FUTIMENS_RUNTIME)
  14369. #endif
  14370. #ifdef HAVE_UTIMENSAT
  14371. PROBE(probe_utimensat, HAVE_UTIMENSAT_RUNTIME)
  14372. #endif
  14373. static const struct have_function {
  14374. const char * const label;
  14375. int (*probe)(void);
  14376. } have_functions[] = {
  14377. #ifdef HAVE_EVENTFD
  14378. {"HAVE_EVENTFD", NULL},
  14379. #endif
  14380. #ifdef HAVE_FACCESSAT
  14381. { "HAVE_FACCESSAT", probe_faccessat },
  14382. #endif
  14383. #ifdef HAVE_FCHDIR
  14384. { "HAVE_FCHDIR", NULL },
  14385. #endif
  14386. #ifdef HAVE_FCHMOD
  14387. { "HAVE_FCHMOD", NULL },
  14388. #endif
  14389. #ifdef HAVE_FCHMODAT
  14390. { "HAVE_FCHMODAT", probe_fchmodat },
  14391. #endif
  14392. #ifdef HAVE_FCHOWN
  14393. { "HAVE_FCHOWN", NULL },
  14394. #endif
  14395. #ifdef HAVE_FCHOWNAT
  14396. { "HAVE_FCHOWNAT", probe_fchownat },
  14397. #endif
  14398. #ifdef HAVE_FEXECVE
  14399. { "HAVE_FEXECVE", NULL },
  14400. #endif
  14401. #ifdef HAVE_FDOPENDIR
  14402. { "HAVE_FDOPENDIR", probe_fdopendir },
  14403. #endif
  14404. #ifdef HAVE_FPATHCONF
  14405. { "HAVE_FPATHCONF", NULL },
  14406. #endif
  14407. #ifdef HAVE_FSTATAT
  14408. { "HAVE_FSTATAT", probe_fstatat },
  14409. #endif
  14410. #ifdef HAVE_FSTATVFS
  14411. { "HAVE_FSTATVFS", NULL },
  14412. #endif
  14413. #if defined HAVE_FTRUNCATE || defined MS_WINDOWS
  14414. { "HAVE_FTRUNCATE", NULL },
  14415. #endif
  14416. #ifdef HAVE_FUTIMENS
  14417. { "HAVE_FUTIMENS", probe_futimens },
  14418. #endif
  14419. #ifdef HAVE_FUTIMES
  14420. { "HAVE_FUTIMES", NULL },
  14421. #endif
  14422. #ifdef HAVE_FUTIMESAT
  14423. { "HAVE_FUTIMESAT", NULL },
  14424. #endif
  14425. #ifdef HAVE_LINKAT
  14426. { "HAVE_LINKAT", probe_linkat },
  14427. #endif
  14428. #ifdef HAVE_LCHFLAGS
  14429. { "HAVE_LCHFLAGS", NULL },
  14430. #endif
  14431. #ifdef HAVE_LCHMOD
  14432. { "HAVE_LCHMOD", NULL },
  14433. #endif
  14434. #ifdef HAVE_LCHOWN
  14435. { "HAVE_LCHOWN", NULL },
  14436. #endif
  14437. #ifdef HAVE_LSTAT
  14438. { "HAVE_LSTAT", NULL },
  14439. #endif
  14440. #ifdef HAVE_LUTIMES
  14441. { "HAVE_LUTIMES", NULL },
  14442. #endif
  14443. #ifdef HAVE_MEMFD_CREATE
  14444. { "HAVE_MEMFD_CREATE", NULL },
  14445. #endif
  14446. #ifdef HAVE_MKDIRAT
  14447. { "HAVE_MKDIRAT", probe_mkdirat },
  14448. #endif
  14449. #ifdef HAVE_MKFIFOAT
  14450. { "HAVE_MKFIFOAT", probe_mkfifoat },
  14451. #endif
  14452. #ifdef HAVE_MKNODAT
  14453. { "HAVE_MKNODAT", probe_mknodat },
  14454. #endif
  14455. #ifdef HAVE_OPENAT
  14456. { "HAVE_OPENAT", probe_openat },
  14457. #endif
  14458. #ifdef HAVE_READLINKAT
  14459. { "HAVE_READLINKAT", probe_readlinkat },
  14460. #endif
  14461. #ifdef HAVE_RENAMEAT
  14462. { "HAVE_RENAMEAT", probe_renameat },
  14463. #endif
  14464. #ifdef HAVE_SYMLINKAT
  14465. { "HAVE_SYMLINKAT", probe_symlinkat },
  14466. #endif
  14467. #ifdef HAVE_UNLINKAT
  14468. { "HAVE_UNLINKAT", probe_unlinkat },
  14469. #endif
  14470. #ifdef HAVE_UTIMENSAT
  14471. { "HAVE_UTIMENSAT", probe_utimensat },
  14472. #endif
  14473. #ifdef MS_WINDOWS
  14474. { "MS_WINDOWS", NULL },
  14475. #endif
  14476. { NULL, NULL }
  14477. };
  14478. static int
  14479. posixmodule_exec(PyObject *m)
  14480. {
  14481. _posixstate *state = get_posix_state(m);
  14482. #if defined(HAVE_PWRITEV)
  14483. if (HAVE_PWRITEV_RUNTIME) {} else {
  14484. PyObject* dct = PyModule_GetDict(m);
  14485. if (dct == NULL) {
  14486. return -1;
  14487. }
  14488. if (PyDict_DelItemString(dct, "pwritev") == -1) {
  14489. PyErr_Clear();
  14490. }
  14491. if (PyDict_DelItemString(dct, "preadv") == -1) {
  14492. PyErr_Clear();
  14493. }
  14494. }
  14495. #endif
  14496. /* Initialize environ dictionary */
  14497. if (_PyModule_Add(m, "environ", convertenviron()) != 0) {
  14498. return -1;
  14499. }
  14500. if (all_ins(m))
  14501. return -1;
  14502. if (setup_confname_tables(m))
  14503. return -1;
  14504. if (PyModule_AddObjectRef(m, "error", PyExc_OSError) < 0) {
  14505. return -1;
  14506. }
  14507. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  14508. waitid_result_desc.name = MODNAME ".waitid_result";
  14509. state->WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
  14510. if (PyModule_AddObjectRef(m, "waitid_result", state->WaitidResultType) < 0) {
  14511. return -1;
  14512. }
  14513. #endif
  14514. stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
  14515. stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
  14516. stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
  14517. stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
  14518. state->StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
  14519. if (PyModule_AddObjectRef(m, "stat_result", state->StatResultType) < 0) {
  14520. return -1;
  14521. }
  14522. state->statresult_new_orig = ((PyTypeObject *)state->StatResultType)->tp_new;
  14523. ((PyTypeObject *)state->StatResultType)->tp_new = statresult_new;
  14524. statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
  14525. state->StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
  14526. if (PyModule_AddObjectRef(m, "statvfs_result", state->StatVFSResultType) < 0) {
  14527. return -1;
  14528. }
  14529. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  14530. sched_param_desc.name = MODNAME ".sched_param";
  14531. state->SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
  14532. if (PyModule_AddObjectRef(m, "sched_param", state->SchedParamType) < 0) {
  14533. return -1;
  14534. }
  14535. ((PyTypeObject *)state->SchedParamType)->tp_new = os_sched_param;
  14536. if (_PyType_AddMethod((PyTypeObject *)state->SchedParamType,
  14537. &os_sched_param_reduce_method) < 0)
  14538. {
  14539. return -1;
  14540. }
  14541. PyType_Modified((PyTypeObject *)state->SchedParamType);
  14542. #endif
  14543. /* initialize TerminalSize_info */
  14544. state->TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
  14545. if (PyModule_AddObjectRef(m, "terminal_size", state->TerminalSizeType) < 0) {
  14546. return -1;
  14547. }
  14548. /* initialize scandir types */
  14549. PyObject *ScandirIteratorType = PyType_FromModuleAndSpec(m, &ScandirIteratorType_spec, NULL);
  14550. if (ScandirIteratorType == NULL) {
  14551. return -1;
  14552. }
  14553. state->ScandirIteratorType = ScandirIteratorType;
  14554. state->DirEntryType = PyType_FromModuleAndSpec(m, &DirEntryType_spec, NULL);
  14555. if (PyModule_AddObjectRef(m, "DirEntry", state->DirEntryType) < 0) {
  14556. return -1;
  14557. }
  14558. times_result_desc.name = MODNAME ".times_result";
  14559. state->TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
  14560. if (PyModule_AddObjectRef(m, "times_result", state->TimesResultType) < 0) {
  14561. return -1;
  14562. }
  14563. state->UnameResultType = (PyObject *)PyStructSequence_NewType(&uname_result_desc);
  14564. if (PyModule_AddObjectRef(m, "uname_result", state->UnameResultType) < 0) {
  14565. return -1;
  14566. }
  14567. if ((state->billion = PyLong_FromLong(1000000000)) == NULL)
  14568. return -1;
  14569. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  14570. state->struct_rusage = PyUnicode_InternFromString("struct_rusage");
  14571. if (state->struct_rusage == NULL)
  14572. return -1;
  14573. #endif
  14574. state->st_mode = PyUnicode_InternFromString("st_mode");
  14575. if (state->st_mode == NULL)
  14576. return -1;
  14577. /* suppress "function not used" warnings */
  14578. {
  14579. int ignored;
  14580. fd_specified("", -1);
  14581. follow_symlinks_specified("", 1);
  14582. dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
  14583. dir_fd_converter(Py_None, &ignored);
  14584. dir_fd_unavailable(Py_None, &ignored);
  14585. }
  14586. /*
  14587. * provide list of locally available functions
  14588. * so os.py can populate support_* lists
  14589. */
  14590. PyObject *list = PyList_New(0);
  14591. if (!list) {
  14592. return -1;
  14593. }
  14594. for (const struct have_function *trace = have_functions; trace->label; trace++) {
  14595. PyObject *unicode;
  14596. if (trace->probe && !trace->probe()) continue;
  14597. unicode = PyUnicode_DecodeASCII(trace->label, strlen(trace->label), NULL);
  14598. if (!unicode)
  14599. return -1;
  14600. if (PyList_Append(list, unicode))
  14601. return -1;
  14602. Py_DECREF(unicode);
  14603. }
  14604. return _PyModule_Add(m, "_have_functions", list);
  14605. }
  14606. static PyModuleDef_Slot posixmodile_slots[] = {
  14607. {Py_mod_exec, posixmodule_exec},
  14608. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  14609. {0, NULL}
  14610. };
  14611. static struct PyModuleDef posixmodule = {
  14612. PyModuleDef_HEAD_INIT,
  14613. .m_name = MODNAME,
  14614. .m_doc = posix__doc__,
  14615. .m_size = sizeof(_posixstate),
  14616. .m_methods = posix_methods,
  14617. .m_slots = posixmodile_slots,
  14618. .m_traverse = _posix_traverse,
  14619. .m_clear = _posix_clear,
  14620. .m_free = _posix_free,
  14621. };
  14622. PyMODINIT_FUNC
  14623. INITFUNC(void)
  14624. {
  14625. return PyModuleDef_Init(&posixmodule);
  14626. }
  14627. #ifdef __cplusplus
  14628. }
  14629. #endif