posixmodule.c 445 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017
  1. /* POSIX module implementation */
  2. /* This file is also used for Windows NT/MS-Win. In that case the
  3. module actually calls itself 'nt', not 'posix', and a few
  4. functions are either unimplemented or implemented differently. The source
  5. assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
  6. of the compiler used. Different compilers define their own feature
  7. test macro, e.g. '_MSC_VER'. */
  8. #define PY_SSIZE_T_CLEAN
  9. #include "Python.h"
  10. #ifdef __VXWORKS__
  11. # include "pycore_bitutils.h" // _Py_popcount32()
  12. #endif
  13. #include "pycore_call.h" // _PyObject_CallNoArgs()
  14. #include "pycore_ceval.h" // _PyEval_ReInitThreads()
  15. #include "pycore_fileutils.h" // _Py_closerange()
  16. #include "pycore_import.h" // _PyImport_ReInitLock()
  17. #include "pycore_initconfig.h" // _PyStatus_EXCEPTION()
  18. #include "pycore_moduleobject.h" // _PyModule_GetState()
  19. #include "pycore_object.h" // _PyObject_LookupSpecial()
  20. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  21. #include "pycore_signal.h" // Py_NSIG
  22. #ifdef MS_WINDOWS
  23. # include <windows.h>
  24. # if !defined(MS_WINDOWS_GAMES) || defined(MS_WINDOWS_DESKTOP)
  25. # include <pathcch.h>
  26. # endif
  27. # include <winioctl.h>
  28. # include <lmcons.h> // UNLEN
  29. # include "osdefs.h" // SEP
  30. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  31. # define HAVE_SYMLINK
  32. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_SYSTEM */
  33. #endif
  34. #include "structmember.h" // PyMemberDef
  35. #ifndef MS_WINDOWS
  36. # include "posixmodule.h"
  37. #else
  38. # include "pycore_fileutils_windows.h"
  39. # include "winreparse.h"
  40. #endif
  41. #if !defined(EX_OK) && defined(EXIT_SUCCESS)
  42. # define EX_OK EXIT_SUCCESS
  43. #endif
  44. /* On android API level 21, 'AT_EACCESS' is not declared although
  45. * HAVE_FACCESSAT is defined. */
  46. #ifdef __ANDROID__
  47. # undef HAVE_FACCESSAT
  48. #endif
  49. #include <stdio.h> // ctermid()
  50. #include <stdlib.h> // system()
  51. /*
  52. * A number of APIs are available on macOS from a certain macOS version.
  53. * To support building with a new SDK while deploying to older versions
  54. * the availability test is split into two:
  55. * - HAVE_<FUNCTION>: The configure check for compile time availability
  56. * - HAVE_<FUNCTION>_RUNTIME: Runtime check for availability
  57. *
  58. * The latter is always true when not on macOS, or when using a compiler
  59. * that does not support __has_builtin (older versions of Xcode).
  60. *
  61. * Due to compiler restrictions there is one valid use of HAVE_<FUNCTION>_RUNTIME:
  62. * if (HAVE_<FUNCTION>_RUNTIME) { ... }
  63. *
  64. * In mixing the test with other tests or using negations will result in compile
  65. * errors.
  66. */
  67. #if defined(__APPLE__)
  68. #include <mach/mach.h>
  69. #if defined(__has_builtin)
  70. #if __has_builtin(__builtin_available)
  71. #define HAVE_BUILTIN_AVAILABLE 1
  72. #endif
  73. #endif
  74. #ifdef HAVE_BUILTIN_AVAILABLE
  75. # define HAVE_FSTATAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  76. # define HAVE_FACCESSAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  77. # define HAVE_FCHMODAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  78. # define HAVE_FCHOWNAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  79. # define HAVE_LINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  80. # define HAVE_FDOPENDIR_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  81. # define HAVE_MKDIRAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  82. # define HAVE_RENAMEAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  83. # define HAVE_UNLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  84. # define HAVE_OPENAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  85. # define HAVE_READLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  86. # define HAVE_SYMLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
  87. # define HAVE_FUTIMENS_RUNTIME __builtin_available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  88. # define HAVE_UTIMENSAT_RUNTIME __builtin_available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  89. # define HAVE_PWRITEV_RUNTIME __builtin_available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
  90. # define HAVE_MKFIFOAT_RUNTIME __builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
  91. # define HAVE_MKNODAT_RUNTIME __builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
  92. # define HAVE_POSIX_SPAWN_SETSID_RUNTIME __builtin_available(macOS 10.15, *)
  93. #else /* Xcode 8 or earlier */
  94. /* __builtin_available is not present in these compilers, but
  95. * some of the symbols might be weak linked (10.10 SDK or later
  96. * deploying on 10.9.
  97. *
  98. * Fall back to the older style of availability checking for
  99. * symbols introduced in macOS 10.10.
  100. */
  101. # ifdef HAVE_FSTATAT
  102. # define HAVE_FSTATAT_RUNTIME (fstatat != NULL)
  103. # endif
  104. # ifdef HAVE_FACCESSAT
  105. # define HAVE_FACCESSAT_RUNTIME (faccessat != NULL)
  106. # endif
  107. # ifdef HAVE_FCHMODAT
  108. # define HAVE_FCHMODAT_RUNTIME (fchmodat != NULL)
  109. # endif
  110. # ifdef HAVE_FCHOWNAT
  111. # define HAVE_FCHOWNAT_RUNTIME (fchownat != NULL)
  112. # endif
  113. # ifdef HAVE_LINKAT
  114. # define HAVE_LINKAT_RUNTIME (linkat != NULL)
  115. # endif
  116. # ifdef HAVE_FDOPENDIR
  117. # define HAVE_FDOPENDIR_RUNTIME (fdopendir != NULL)
  118. # endif
  119. # ifdef HAVE_MKDIRAT
  120. # define HAVE_MKDIRAT_RUNTIME (mkdirat != NULL)
  121. # endif
  122. # ifdef HAVE_RENAMEAT
  123. # define HAVE_RENAMEAT_RUNTIME (renameat != NULL)
  124. # endif
  125. # ifdef HAVE_UNLINKAT
  126. # define HAVE_UNLINKAT_RUNTIME (unlinkat != NULL)
  127. # endif
  128. # ifdef HAVE_OPENAT
  129. # define HAVE_OPENAT_RUNTIME (openat != NULL)
  130. # endif
  131. # ifdef HAVE_READLINKAT
  132. # define HAVE_READLINKAT_RUNTIME (readlinkat != NULL)
  133. # endif
  134. # ifdef HAVE_SYMLINKAT
  135. # define HAVE_SYMLINKAT_RUNTIME (symlinkat != NULL)
  136. # endif
  137. # ifdef HAVE_UTIMENSAT
  138. # define HAVE_UTIMENSAT_RUNTIME (utimensat != NULL)
  139. # endif
  140. # ifdef HAVE_FUTIMENS
  141. # define HAVE_FUTIMENS_RUNTIME (futimens != NULL)
  142. # endif
  143. # ifdef HAVE_PWRITEV
  144. # define HAVE_PWRITEV_RUNTIME (pwritev != NULL)
  145. # endif
  146. # ifdef HAVE_MKFIFOAT
  147. # define HAVE_MKFIFOAT_RUNTIME (mkfifoat != NULL)
  148. # endif
  149. # ifdef HAVE_MKNODAT
  150. # define HAVE_MKNODAT_RUNTIME (mknodat != NULL)
  151. # endif
  152. #endif
  153. #ifdef HAVE_FUTIMESAT
  154. /* Some of the logic for weak linking depends on this assertion */
  155. # error "HAVE_FUTIMESAT unexpectedly defined"
  156. #endif
  157. #else
  158. # define HAVE_FSTATAT_RUNTIME 1
  159. # define HAVE_FACCESSAT_RUNTIME 1
  160. # define HAVE_FCHMODAT_RUNTIME 1
  161. # define HAVE_FCHOWNAT_RUNTIME 1
  162. # define HAVE_LINKAT_RUNTIME 1
  163. # define HAVE_FDOPENDIR_RUNTIME 1
  164. # define HAVE_MKDIRAT_RUNTIME 1
  165. # define HAVE_RENAMEAT_RUNTIME 1
  166. # define HAVE_UNLINKAT_RUNTIME 1
  167. # define HAVE_OPENAT_RUNTIME 1
  168. # define HAVE_READLINKAT_RUNTIME 1
  169. # define HAVE_SYMLINKAT_RUNTIME 1
  170. # define HAVE_FUTIMENS_RUNTIME 1
  171. # define HAVE_UTIMENSAT_RUNTIME 1
  172. # define HAVE_PWRITEV_RUNTIME 1
  173. # define HAVE_MKFIFOAT_RUNTIME 1
  174. # define HAVE_MKNODAT_RUNTIME 1
  175. #endif
  176. #ifdef __cplusplus
  177. extern "C" {
  178. #endif
  179. PyDoc_STRVAR(posix__doc__,
  180. "This module provides access to operating system functionality that is\n\
  181. standardized by the C Standard and the POSIX standard (a thinly\n\
  182. disguised Unix interface). Refer to the library manual and\n\
  183. corresponding Unix manual entries for more information on calls.");
  184. #ifdef HAVE_SYS_UIO_H
  185. # include <sys/uio.h>
  186. #endif
  187. #ifdef HAVE_SYS_TYPES_H
  188. /* Should be included before <sys/sysmacros.h> on HP-UX v3 */
  189. # include <sys/types.h>
  190. #endif /* HAVE_SYS_TYPES_H */
  191. #ifdef HAVE_SYS_SYSMACROS_H
  192. /* GNU C Library: major(), minor(), makedev() */
  193. # include <sys/sysmacros.h>
  194. #endif
  195. #ifdef HAVE_SYS_STAT_H
  196. # include <sys/stat.h>
  197. #endif /* HAVE_SYS_STAT_H */
  198. #ifdef HAVE_SYS_WAIT_H
  199. # include <sys/wait.h> // WNOHANG
  200. #endif
  201. #ifdef HAVE_LINUX_WAIT_H
  202. # include <linux/wait.h> // P_PIDFD
  203. #endif
  204. #ifdef HAVE_SIGNAL_H
  205. # include <signal.h>
  206. #endif
  207. #ifdef HAVE_FCNTL_H
  208. # include <fcntl.h>
  209. #endif
  210. #ifdef HAVE_GRP_H
  211. # include <grp.h>
  212. #endif
  213. #ifdef HAVE_SYSEXITS_H
  214. # include <sysexits.h>
  215. #endif
  216. #ifdef HAVE_SYS_LOADAVG_H
  217. # include <sys/loadavg.h>
  218. #endif
  219. #ifdef HAVE_SYS_SENDFILE_H
  220. # include <sys/sendfile.h>
  221. #endif
  222. #if defined(__APPLE__)
  223. # include <copyfile.h>
  224. #endif
  225. #ifdef HAVE_SCHED_H
  226. # include <sched.h>
  227. #endif
  228. #ifdef HAVE_COPY_FILE_RANGE
  229. # include <unistd.h>
  230. #endif
  231. #if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
  232. # undef HAVE_SCHED_SETAFFINITY
  233. #endif
  234. #if defined(HAVE_SYS_XATTR_H) && defined(HAVE_LINUX_LIMITS_H) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
  235. # define USE_XATTRS
  236. # include <linux/limits.h> // Needed for XATTR_SIZE_MAX on musl libc.
  237. #endif
  238. #ifdef USE_XATTRS
  239. # include <sys/xattr.h>
  240. #endif
  241. #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
  242. # ifdef HAVE_SYS_SOCKET_H
  243. # include <sys/socket.h>
  244. # endif
  245. #endif
  246. #ifdef HAVE_DLFCN_H
  247. # include <dlfcn.h>
  248. #endif
  249. #ifdef __hpux
  250. # include <sys/mpctl.h>
  251. #endif
  252. #if defined(__DragonFly__) || \
  253. defined(__OpenBSD__) || \
  254. defined(__FreeBSD__) || \
  255. defined(__NetBSD__) || \
  256. defined(__APPLE__)
  257. # include <sys/sysctl.h>
  258. #endif
  259. #ifdef HAVE_LINUX_RANDOM_H
  260. # include <linux/random.h>
  261. #endif
  262. #ifdef HAVE_GETRANDOM_SYSCALL
  263. # include <sys/syscall.h>
  264. # include <sys/random.h>
  265. #endif
  266. #ifdef HAVE_WINDOWS_CONSOLE_IO
  267. # define TERMSIZE_USE_CONIO
  268. #elif defined(HAVE_SYS_IOCTL_H)
  269. # include <sys/ioctl.h>
  270. # if defined(HAVE_TERMIOS_H)
  271. # include <termios.h>
  272. # endif
  273. # if defined(TIOCGWINSZ)
  274. # define TERMSIZE_USE_IOCTL
  275. # endif
  276. #endif /* HAVE_WINDOWS_CONSOLE_IO */
  277. /* Various compilers have only certain posix functions */
  278. /* XXX Gosh I wish these were all moved into pyconfig.h */
  279. #if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
  280. # define HAVE_OPENDIR 1
  281. # define HAVE_SYSTEM 1
  282. # include <process.h>
  283. #elif defined( _MSC_VER)
  284. /* Microsoft compiler */
  285. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
  286. # define HAVE_GETPPID 1
  287. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_APP | MS_WINDOWS_SYSTEM */
  288. # if defined(MS_WINDOWS_DESKTOP)
  289. # define HAVE_GETLOGIN 1
  290. # endif /* MS_WINDOWS_DESKTOP */
  291. # if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  292. # define HAVE_SPAWNV 1
  293. # define HAVE_EXECV 1
  294. # define HAVE_WSPAWNV 1
  295. # define HAVE_WEXECV 1
  296. # define HAVE_SYSTEM 1
  297. # define HAVE_CWAIT 1
  298. # endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_SYSTEM */
  299. # define HAVE_PIPE 1
  300. # define HAVE_FSYNC 1
  301. # define fsync _commit
  302. #endif /* ! __WATCOMC__ || __QNX__ */
  303. /*[clinic input]
  304. # one of the few times we lie about this name!
  305. module os
  306. [clinic start generated code]*/
  307. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
  308. #ifndef _MSC_VER
  309. #if defined(__sgi)&&_COMPILER_VERSION>=700
  310. /* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
  311. (default) */
  312. extern char *ctermid_r(char *);
  313. #endif
  314. #endif /* !_MSC_VER */
  315. #if defined(__VXWORKS__)
  316. # error #include <vxCpuLib.h>
  317. # error #include <rtpLib.h>
  318. # include <wait.h>
  319. # error #include <taskLib.h>
  320. # ifndef _P_WAIT
  321. # define _P_WAIT 0
  322. # define _P_NOWAIT 1
  323. # define _P_NOWAITO 1
  324. # endif
  325. #endif /* __VXWORKS__ */
  326. #ifdef HAVE_POSIX_SPAWN
  327. # include <spawn.h>
  328. #endif
  329. #ifdef HAVE_UTIME_H
  330. # include <utime.h>
  331. #endif /* HAVE_UTIME_H */
  332. #ifdef HAVE_SYS_UTIME_H
  333. # include <sys/utime.h>
  334. # define HAVE_UTIME_H /* pretend we do for the rest of this file */
  335. #endif /* HAVE_SYS_UTIME_H */
  336. #ifdef HAVE_SYS_TIMES_H
  337. # include <sys/times.h>
  338. #endif /* HAVE_SYS_TIMES_H */
  339. #ifdef HAVE_SYS_PARAM_H
  340. # include <sys/param.h>
  341. #endif /* HAVE_SYS_PARAM_H */
  342. #ifdef HAVE_SYS_UTSNAME_H
  343. # include <sys/utsname.h>
  344. #endif /* HAVE_SYS_UTSNAME_H */
  345. #ifdef HAVE_DIRENT_H
  346. # include <dirent.h>
  347. # define NAMLEN(dirent) strlen((dirent)->d_name)
  348. #else
  349. # if defined(__WATCOMC__) && !defined(__QNX__)
  350. # include <direct.h>
  351. # define NAMLEN(dirent) strlen((dirent)->d_name)
  352. # else
  353. # define dirent direct
  354. # define NAMLEN(dirent) (dirent)->d_namlen
  355. # endif
  356. # ifdef HAVE_SYS_NDIR_H
  357. # include <sys/ndir.h>
  358. # endif
  359. # ifdef HAVE_SYS_DIR_H
  360. # include <sys/dir.h>
  361. # endif
  362. # ifdef HAVE_NDIR_H
  363. # include <ndir.h>
  364. # endif
  365. #endif
  366. #ifdef _MSC_VER
  367. # ifdef HAVE_DIRECT_H
  368. # include <direct.h>
  369. # endif
  370. # ifdef HAVE_IO_H
  371. # include <io.h>
  372. # endif
  373. # ifdef HAVE_PROCESS_H
  374. # include <process.h>
  375. # endif
  376. # include <malloc.h>
  377. #endif /* _MSC_VER */
  378. #ifndef MAXPATHLEN
  379. # if defined(PATH_MAX) && PATH_MAX > 1024
  380. # define MAXPATHLEN PATH_MAX
  381. # else
  382. # define MAXPATHLEN 1024
  383. # endif
  384. #endif /* MAXPATHLEN */
  385. #ifdef UNION_WAIT
  386. /* Emulate some macros on systems that have a union instead of macros */
  387. # ifndef WIFEXITED
  388. # define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
  389. # endif
  390. # ifndef WEXITSTATUS
  391. # define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
  392. # endif
  393. # ifndef WTERMSIG
  394. # define WTERMSIG(u_wait) ((u_wait).w_termsig)
  395. # endif
  396. # define WAIT_TYPE union wait
  397. # define WAIT_STATUS_INT(s) (s.w_status)
  398. #else
  399. /* !UNION_WAIT */
  400. # define WAIT_TYPE int
  401. # define WAIT_STATUS_INT(s) (s)
  402. #endif /* UNION_WAIT */
  403. /* Don't use the "_r" form if we don't need it (also, won't have a
  404. prototype for it, at least on Solaris -- maybe others as well?). */
  405. #if defined(HAVE_CTERMID_R)
  406. # define USE_CTERMID_R
  407. #endif
  408. /* choose the appropriate stat and fstat functions and return structs */
  409. #undef STAT
  410. #undef FSTAT
  411. #undef STRUCT_STAT
  412. #ifdef MS_WINDOWS
  413. # define STAT win32_stat
  414. # define LSTAT win32_lstat
  415. # define FSTAT _Py_fstat_noraise
  416. # define STRUCT_STAT struct _Py_stat_struct
  417. #else
  418. # define STAT stat
  419. # define LSTAT lstat
  420. # define FSTAT fstat
  421. # define STRUCT_STAT struct stat
  422. #endif
  423. #if defined(MAJOR_IN_MKDEV)
  424. # include <sys/mkdev.h>
  425. #else
  426. # if defined(MAJOR_IN_SYSMACROS)
  427. # include <sys/sysmacros.h>
  428. # endif
  429. # if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
  430. # include <sys/mkdev.h>
  431. # endif
  432. #endif
  433. #ifdef MS_WINDOWS
  434. # define INITFUNC PyInit_nt
  435. # define MODNAME "nt"
  436. # define MODNAME_OBJ &_Py_ID(nt)
  437. #else
  438. # define INITFUNC PyInit_posix
  439. # define MODNAME "posix"
  440. # define MODNAME_OBJ &_Py_ID(posix)
  441. #endif
  442. #if defined(__sun)
  443. /* Something to implement in autoconf, not present in autoconf 2.69 */
  444. # define HAVE_STRUCT_STAT_ST_FSTYPE 1
  445. #endif
  446. /* memfd_create is either defined in sys/mman.h or sys/memfd.h
  447. * linux/memfd.h defines additional flags
  448. */
  449. #ifdef HAVE_SYS_MMAN_H
  450. # include <sys/mman.h>
  451. #endif
  452. #ifdef HAVE_SYS_MEMFD_H
  453. # include <sys/memfd.h>
  454. #endif
  455. #ifdef HAVE_LINUX_MEMFD_H
  456. # include <linux/memfd.h>
  457. #endif
  458. /* eventfd() */
  459. #ifdef HAVE_SYS_EVENTFD_H
  460. # include <sys/eventfd.h>
  461. #endif
  462. #ifdef _Py_MEMORY_SANITIZER
  463. # include <sanitizer/msan_interface.h>
  464. #endif
  465. #ifdef HAVE_FORK
  466. static void
  467. run_at_forkers(PyObject *lst, int reverse)
  468. {
  469. Py_ssize_t i;
  470. PyObject *cpy;
  471. if (lst != NULL) {
  472. assert(PyList_CheckExact(lst));
  473. /* Use a list copy in case register_at_fork() is called from
  474. * one of the callbacks.
  475. */
  476. cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
  477. if (cpy == NULL)
  478. PyErr_WriteUnraisable(lst);
  479. else {
  480. if (reverse)
  481. PyList_Reverse(cpy);
  482. for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
  483. PyObject *func, *res;
  484. func = PyList_GET_ITEM(cpy, i);
  485. res = _PyObject_CallNoArgs(func);
  486. if (res == NULL)
  487. PyErr_WriteUnraisable(func);
  488. else
  489. Py_DECREF(res);
  490. }
  491. Py_DECREF(cpy);
  492. }
  493. }
  494. }
  495. void
  496. PyOS_BeforeFork(void)
  497. {
  498. PyInterpreterState *interp = _PyInterpreterState_GET();
  499. run_at_forkers(interp->before_forkers, 1);
  500. _PyImport_AcquireLock(interp);
  501. }
  502. void
  503. PyOS_AfterFork_Parent(void)
  504. {
  505. PyInterpreterState *interp = _PyInterpreterState_GET();
  506. if (_PyImport_ReleaseLock(interp) <= 0) {
  507. Py_FatalError("failed releasing import lock after fork");
  508. }
  509. run_at_forkers(interp->after_forkers_parent, 0);
  510. }
  511. void
  512. PyOS_AfterFork_Child(void)
  513. {
  514. PyStatus status;
  515. _PyRuntimeState *runtime = &_PyRuntime;
  516. status = _PyRuntimeState_ReInitThreads(runtime);
  517. if (_PyStatus_EXCEPTION(status)) {
  518. goto fatal_error;
  519. }
  520. PyThreadState *tstate = _PyThreadState_GET();
  521. _Py_EnsureTstateNotNULL(tstate);
  522. #ifdef PY_HAVE_THREAD_NATIVE_ID
  523. tstate->native_thread_id = PyThread_get_thread_native_id();
  524. #endif
  525. status = _PyEval_ReInitThreads(tstate);
  526. if (_PyStatus_EXCEPTION(status)) {
  527. goto fatal_error;
  528. }
  529. status = _PyImport_ReInitLock(tstate->interp);
  530. if (_PyStatus_EXCEPTION(status)) {
  531. goto fatal_error;
  532. }
  533. _PySignal_AfterFork();
  534. status = _PyInterpreterState_DeleteExceptMain(runtime);
  535. if (_PyStatus_EXCEPTION(status)) {
  536. goto fatal_error;
  537. }
  538. assert(_PyThreadState_GET() == tstate);
  539. status = _PyPerfTrampoline_AfterFork_Child();
  540. if (_PyStatus_EXCEPTION(status)) {
  541. goto fatal_error;
  542. }
  543. run_at_forkers(tstate->interp->after_forkers_child, 0);
  544. return;
  545. fatal_error:
  546. Py_ExitStatusException(status);
  547. }
  548. static int
  549. register_at_forker(PyObject **lst, PyObject *func)
  550. {
  551. if (func == NULL) /* nothing to register? do nothing. */
  552. return 0;
  553. if (*lst == NULL) {
  554. *lst = PyList_New(0);
  555. if (*lst == NULL)
  556. return -1;
  557. }
  558. return PyList_Append(*lst, func);
  559. }
  560. #endif /* HAVE_FORK */
  561. /* Legacy wrapper */
  562. void
  563. PyOS_AfterFork(void)
  564. {
  565. #ifdef HAVE_FORK
  566. PyOS_AfterFork_Child();
  567. #endif
  568. }
  569. #ifdef MS_WINDOWS
  570. /* defined in fileutils.c */
  571. void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
  572. void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *, ULONG,
  573. FILE_BASIC_INFO *, FILE_ID_INFO *,
  574. struct _Py_stat_struct *);
  575. void _Py_stat_basic_info_to_stat(FILE_STAT_BASIC_INFORMATION *,
  576. struct _Py_stat_struct *);
  577. #endif
  578. #ifndef MS_WINDOWS
  579. PyObject *
  580. _PyLong_FromUid(uid_t uid)
  581. {
  582. if (uid == (uid_t)-1)
  583. return PyLong_FromLong(-1);
  584. return PyLong_FromUnsignedLong(uid);
  585. }
  586. PyObject *
  587. _PyLong_FromGid(gid_t gid)
  588. {
  589. if (gid == (gid_t)-1)
  590. return PyLong_FromLong(-1);
  591. return PyLong_FromUnsignedLong(gid);
  592. }
  593. int
  594. _Py_Uid_Converter(PyObject *obj, uid_t *p)
  595. {
  596. uid_t uid;
  597. PyObject *index;
  598. int overflow;
  599. long result;
  600. unsigned long uresult;
  601. index = _PyNumber_Index(obj);
  602. if (index == NULL) {
  603. PyErr_Format(PyExc_TypeError,
  604. "uid should be integer, not %.200s",
  605. _PyType_Name(Py_TYPE(obj)));
  606. return 0;
  607. }
  608. /*
  609. * Handling uid_t is complicated for two reasons:
  610. * * Although uid_t is (always?) unsigned, it still
  611. * accepts -1.
  612. * * We don't know its size in advance--it may be
  613. * bigger than an int, or it may be smaller than
  614. * a long.
  615. *
  616. * So a bit of defensive programming is in order.
  617. * Start with interpreting the value passed
  618. * in as a signed long and see if it works.
  619. */
  620. result = PyLong_AsLongAndOverflow(index, &overflow);
  621. if (!overflow) {
  622. uid = (uid_t)result;
  623. if (result == -1) {
  624. if (PyErr_Occurred())
  625. goto fail;
  626. /* It's a legitimate -1, we're done. */
  627. goto success;
  628. }
  629. /* Any other negative number is disallowed. */
  630. if (result < 0)
  631. goto underflow;
  632. /* Ensure the value wasn't truncated. */
  633. if (sizeof(uid_t) < sizeof(long) &&
  634. (long)uid != result)
  635. goto underflow;
  636. goto success;
  637. }
  638. if (overflow < 0)
  639. goto underflow;
  640. /*
  641. * Okay, the value overflowed a signed long. If it
  642. * fits in an *unsigned* long, it may still be okay,
  643. * as uid_t may be unsigned long on this platform.
  644. */
  645. uresult = PyLong_AsUnsignedLong(index);
  646. if (PyErr_Occurred()) {
  647. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  648. goto overflow;
  649. goto fail;
  650. }
  651. uid = (uid_t)uresult;
  652. /*
  653. * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
  654. * but this value would get interpreted as (uid_t)-1 by chown
  655. * and its siblings. That's not what the user meant! So we
  656. * throw an overflow exception instead. (We already
  657. * handled a real -1 with PyLong_AsLongAndOverflow() above.)
  658. */
  659. if (uid == (uid_t)-1)
  660. goto overflow;
  661. /* Ensure the value wasn't truncated. */
  662. if (sizeof(uid_t) < sizeof(long) &&
  663. (unsigned long)uid != uresult)
  664. goto overflow;
  665. /* fallthrough */
  666. success:
  667. Py_DECREF(index);
  668. *p = uid;
  669. return 1;
  670. underflow:
  671. PyErr_SetString(PyExc_OverflowError,
  672. "uid is less than minimum");
  673. goto fail;
  674. overflow:
  675. PyErr_SetString(PyExc_OverflowError,
  676. "uid is greater than maximum");
  677. /* fallthrough */
  678. fail:
  679. Py_DECREF(index);
  680. return 0;
  681. }
  682. int
  683. _Py_Gid_Converter(PyObject *obj, gid_t *p)
  684. {
  685. gid_t gid;
  686. PyObject *index;
  687. int overflow;
  688. long result;
  689. unsigned long uresult;
  690. index = _PyNumber_Index(obj);
  691. if (index == NULL) {
  692. PyErr_Format(PyExc_TypeError,
  693. "gid should be integer, not %.200s",
  694. _PyType_Name(Py_TYPE(obj)));
  695. return 0;
  696. }
  697. /*
  698. * Handling gid_t is complicated for two reasons:
  699. * * Although gid_t is (always?) unsigned, it still
  700. * accepts -1.
  701. * * We don't know its size in advance--it may be
  702. * bigger than an int, or it may be smaller than
  703. * a long.
  704. *
  705. * So a bit of defensive programming is in order.
  706. * Start with interpreting the value passed
  707. * in as a signed long and see if it works.
  708. */
  709. result = PyLong_AsLongAndOverflow(index, &overflow);
  710. if (!overflow) {
  711. gid = (gid_t)result;
  712. if (result == -1) {
  713. if (PyErr_Occurred())
  714. goto fail;
  715. /* It's a legitimate -1, we're done. */
  716. goto success;
  717. }
  718. /* Any other negative number is disallowed. */
  719. if (result < 0) {
  720. goto underflow;
  721. }
  722. /* Ensure the value wasn't truncated. */
  723. if (sizeof(gid_t) < sizeof(long) &&
  724. (long)gid != result)
  725. goto underflow;
  726. goto success;
  727. }
  728. if (overflow < 0)
  729. goto underflow;
  730. /*
  731. * Okay, the value overflowed a signed long. If it
  732. * fits in an *unsigned* long, it may still be okay,
  733. * as gid_t may be unsigned long on this platform.
  734. */
  735. uresult = PyLong_AsUnsignedLong(index);
  736. if (PyErr_Occurred()) {
  737. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  738. goto overflow;
  739. goto fail;
  740. }
  741. gid = (gid_t)uresult;
  742. /*
  743. * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
  744. * but this value would get interpreted as (gid_t)-1 by chown
  745. * and its siblings. That's not what the user meant! So we
  746. * throw an overflow exception instead. (We already
  747. * handled a real -1 with PyLong_AsLongAndOverflow() above.)
  748. */
  749. if (gid == (gid_t)-1)
  750. goto overflow;
  751. /* Ensure the value wasn't truncated. */
  752. if (sizeof(gid_t) < sizeof(long) &&
  753. (unsigned long)gid != uresult)
  754. goto overflow;
  755. /* fallthrough */
  756. success:
  757. Py_DECREF(index);
  758. *p = gid;
  759. return 1;
  760. underflow:
  761. PyErr_SetString(PyExc_OverflowError,
  762. "gid is less than minimum");
  763. goto fail;
  764. overflow:
  765. PyErr_SetString(PyExc_OverflowError,
  766. "gid is greater than maximum");
  767. /* fallthrough */
  768. fail:
  769. Py_DECREF(index);
  770. return 0;
  771. }
  772. #endif /* MS_WINDOWS */
  773. #define _PyLong_FromDev PyLong_FromLongLong
  774. #if (defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)) || defined(HAVE_DEVICE_MACROS)
  775. static int
  776. _Py_Dev_Converter(PyObject *obj, void *p)
  777. {
  778. *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
  779. if (PyErr_Occurred())
  780. return 0;
  781. return 1;
  782. }
  783. #endif /* (HAVE_MKNOD && HAVE_MAKEDEV) || HAVE_DEVICE_MACROS */
  784. #ifdef AT_FDCWD
  785. /*
  786. * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
  787. * without the int cast, the value gets interpreted as uint (4291925331),
  788. * which doesn't play nicely with all the initializer lines in this file that
  789. * look like this:
  790. * int dir_fd = DEFAULT_DIR_FD;
  791. */
  792. #define DEFAULT_DIR_FD (int)AT_FDCWD
  793. #else
  794. #define DEFAULT_DIR_FD (-100)
  795. #endif
  796. static int
  797. _fd_converter(PyObject *o, int *p)
  798. {
  799. int overflow;
  800. long long_value;
  801. PyObject *index = _PyNumber_Index(o);
  802. if (index == NULL) {
  803. return 0;
  804. }
  805. assert(PyLong_Check(index));
  806. long_value = PyLong_AsLongAndOverflow(index, &overflow);
  807. Py_DECREF(index);
  808. assert(!PyErr_Occurred());
  809. if (overflow > 0 || long_value > INT_MAX) {
  810. PyErr_SetString(PyExc_OverflowError,
  811. "fd is greater than maximum");
  812. return 0;
  813. }
  814. if (overflow < 0 || long_value < INT_MIN) {
  815. PyErr_SetString(PyExc_OverflowError,
  816. "fd is less than minimum");
  817. return 0;
  818. }
  819. *p = (int)long_value;
  820. return 1;
  821. }
  822. static int
  823. dir_fd_converter(PyObject *o, void *p)
  824. {
  825. if (o == Py_None) {
  826. *(int *)p = DEFAULT_DIR_FD;
  827. return 1;
  828. }
  829. else if (PyIndex_Check(o)) {
  830. return _fd_converter(o, (int *)p);
  831. }
  832. else {
  833. PyErr_Format(PyExc_TypeError,
  834. "argument should be integer or None, not %.200s",
  835. _PyType_Name(Py_TYPE(o)));
  836. return 0;
  837. }
  838. }
  839. typedef struct {
  840. PyObject *billion;
  841. PyObject *DirEntryType;
  842. PyObject *ScandirIteratorType;
  843. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  844. PyObject *SchedParamType;
  845. #endif
  846. newfunc statresult_new_orig;
  847. PyObject *StatResultType;
  848. PyObject *StatVFSResultType;
  849. PyObject *TerminalSizeType;
  850. PyObject *TimesResultType;
  851. PyObject *UnameResultType;
  852. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  853. PyObject *WaitidResultType;
  854. #endif
  855. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  856. PyObject *struct_rusage;
  857. #endif
  858. PyObject *st_mode;
  859. } _posixstate;
  860. static inline _posixstate*
  861. get_posix_state(PyObject *module)
  862. {
  863. void *state = _PyModule_GetState(module);
  864. assert(state != NULL);
  865. return (_posixstate *)state;
  866. }
  867. /*
  868. * A PyArg_ParseTuple "converter" function
  869. * that handles filesystem paths in the manner
  870. * preferred by the os module.
  871. *
  872. * path_converter accepts (Unicode) strings and their
  873. * subclasses, and bytes and their subclasses. What
  874. * it does with the argument depends on the platform:
  875. *
  876. * * On Windows, if we get a (Unicode) string we
  877. * extract the wchar_t * and return it; if we get
  878. * bytes we decode to wchar_t * and return that.
  879. *
  880. * * On all other platforms, strings are encoded
  881. * to bytes using PyUnicode_FSConverter, then we
  882. * extract the char * from the bytes object and
  883. * return that.
  884. *
  885. * path_converter also optionally accepts signed
  886. * integers (representing open file descriptors) instead
  887. * of path strings.
  888. *
  889. * Input fields:
  890. * path.nullable
  891. * If nonzero, the path is permitted to be None.
  892. * path.allow_fd
  893. * If nonzero, the path is permitted to be a file handle
  894. * (a signed int) instead of a string.
  895. * path.function_name
  896. * If non-NULL, path_converter will use that as the name
  897. * of the function in error messages.
  898. * (If path.function_name is NULL it omits the function name.)
  899. * path.argument_name
  900. * If non-NULL, path_converter will use that as the name
  901. * of the parameter in error messages.
  902. * (If path.argument_name is NULL it uses "path".)
  903. *
  904. * Output fields:
  905. * path.wide
  906. * Points to the path if it was expressed as Unicode
  907. * and was not encoded. (Only used on Windows.)
  908. * path.narrow
  909. * Points to the path if it was expressed as bytes,
  910. * or it was Unicode and was encoded to bytes. (On Windows,
  911. * is a non-zero integer if the path was expressed as bytes.
  912. * The type is deliberately incompatible to prevent misuse.)
  913. * path.fd
  914. * Contains a file descriptor if path.accept_fd was true
  915. * and the caller provided a signed integer instead of any
  916. * sort of string.
  917. *
  918. * WARNING: if your "path" parameter is optional, and is
  919. * unspecified, path_converter will never get called.
  920. * So if you set allow_fd, you *MUST* initialize path.fd = -1
  921. * yourself!
  922. * path.length
  923. * The length of the path in characters, if specified as
  924. * a string.
  925. * path.object
  926. * The original object passed in (if get a PathLike object,
  927. * the result of PyOS_FSPath() is treated as the original object).
  928. * Own a reference to the object.
  929. * path.cleanup
  930. * For internal use only. May point to a temporary object.
  931. * (Pay no attention to the man behind the curtain.)
  932. *
  933. * At most one of path.wide or path.narrow will be non-NULL.
  934. * If path was None and path.nullable was set,
  935. * or if path was an integer and path.allow_fd was set,
  936. * both path.wide and path.narrow will be NULL
  937. * and path.length will be 0.
  938. *
  939. * path_converter takes care to not write to the path_t
  940. * unless it's successful. However it must reset the
  941. * "cleanup" field each time it's called.
  942. *
  943. * Use as follows:
  944. * path_t path;
  945. * memset(&path, 0, sizeof(path));
  946. * PyArg_ParseTuple(args, "O&", path_converter, &path);
  947. * // ... use values from path ...
  948. * path_cleanup(&path);
  949. *
  950. * (Note that if PyArg_Parse fails you don't need to call
  951. * path_cleanup(). However it is safe to do so.)
  952. */
  953. typedef struct {
  954. const char *function_name;
  955. const char *argument_name;
  956. int nullable;
  957. int allow_fd;
  958. const wchar_t *wide;
  959. #ifdef MS_WINDOWS
  960. BOOL narrow;
  961. #else
  962. const char *narrow;
  963. #endif
  964. int fd;
  965. Py_ssize_t length;
  966. PyObject *object;
  967. PyObject *cleanup;
  968. } path_t;
  969. #ifdef MS_WINDOWS
  970. #define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
  971. {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
  972. #else
  973. #define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
  974. {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
  975. #endif
  976. static void
  977. path_cleanup(path_t *path)
  978. {
  979. wchar_t *wide = (wchar_t *)path->wide;
  980. path->wide = NULL;
  981. PyMem_Free(wide);
  982. Py_CLEAR(path->object);
  983. Py_CLEAR(path->cleanup);
  984. }
  985. static int
  986. path_converter(PyObject *o, void *p)
  987. {
  988. path_t *path = (path_t *)p;
  989. PyObject *bytes = NULL;
  990. Py_ssize_t length = 0;
  991. int is_index, is_bytes, is_unicode;
  992. const char *narrow;
  993. #ifdef MS_WINDOWS
  994. PyObject *wo = NULL;
  995. wchar_t *wide = NULL;
  996. #endif
  997. #define FORMAT_EXCEPTION(exc, fmt) \
  998. PyErr_Format(exc, "%s%s" fmt, \
  999. path->function_name ? path->function_name : "", \
  1000. path->function_name ? ": " : "", \
  1001. path->argument_name ? path->argument_name : "path")
  1002. /* Py_CLEANUP_SUPPORTED support */
  1003. if (o == NULL) {
  1004. path_cleanup(path);
  1005. return 1;
  1006. }
  1007. /* Ensure it's always safe to call path_cleanup(). */
  1008. path->object = path->cleanup = NULL;
  1009. /* path->object owns a reference to the original object */
  1010. Py_INCREF(o);
  1011. if ((o == Py_None) && path->nullable) {
  1012. path->wide = NULL;
  1013. #ifdef MS_WINDOWS
  1014. path->narrow = FALSE;
  1015. #else
  1016. path->narrow = NULL;
  1017. #endif
  1018. path->fd = -1;
  1019. goto success_exit;
  1020. }
  1021. /* Only call this here so that we don't treat the return value of
  1022. os.fspath() as an fd or buffer. */
  1023. is_index = path->allow_fd && PyIndex_Check(o);
  1024. is_bytes = PyBytes_Check(o);
  1025. is_unicode = PyUnicode_Check(o);
  1026. if (!is_index && !is_unicode && !is_bytes) {
  1027. /* Inline PyOS_FSPath() for better error messages. */
  1028. PyObject *func, *res;
  1029. func = _PyObject_LookupSpecial(o, &_Py_ID(__fspath__));
  1030. if (NULL == func) {
  1031. goto error_format;
  1032. }
  1033. res = _PyObject_CallNoArgs(func);
  1034. Py_DECREF(func);
  1035. if (NULL == res) {
  1036. goto error_exit;
  1037. }
  1038. else if (PyUnicode_Check(res)) {
  1039. is_unicode = 1;
  1040. }
  1041. else if (PyBytes_Check(res)) {
  1042. is_bytes = 1;
  1043. }
  1044. else {
  1045. PyErr_Format(PyExc_TypeError,
  1046. "expected %.200s.__fspath__() to return str or bytes, "
  1047. "not %.200s", _PyType_Name(Py_TYPE(o)),
  1048. _PyType_Name(Py_TYPE(res)));
  1049. Py_DECREF(res);
  1050. goto error_exit;
  1051. }
  1052. /* still owns a reference to the original object */
  1053. Py_SETREF(o, res);
  1054. }
  1055. if (is_unicode) {
  1056. #ifdef MS_WINDOWS
  1057. wide = PyUnicode_AsWideCharString(o, &length);
  1058. if (!wide) {
  1059. goto error_exit;
  1060. }
  1061. if (length > 32767) {
  1062. FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
  1063. goto error_exit;
  1064. }
  1065. if (wcslen(wide) != length) {
  1066. FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
  1067. goto error_exit;
  1068. }
  1069. path->wide = wide;
  1070. path->narrow = FALSE;
  1071. path->fd = -1;
  1072. wide = NULL;
  1073. goto success_exit;
  1074. #else
  1075. if (!PyUnicode_FSConverter(o, &bytes)) {
  1076. goto error_exit;
  1077. }
  1078. #endif
  1079. }
  1080. else if (is_bytes) {
  1081. bytes = Py_NewRef(o);
  1082. }
  1083. else if (is_index) {
  1084. if (!_fd_converter(o, &path->fd)) {
  1085. goto error_exit;
  1086. }
  1087. path->wide = NULL;
  1088. #ifdef MS_WINDOWS
  1089. path->narrow = FALSE;
  1090. #else
  1091. path->narrow = NULL;
  1092. #endif
  1093. goto success_exit;
  1094. }
  1095. else {
  1096. error_format:
  1097. PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
  1098. path->function_name ? path->function_name : "",
  1099. path->function_name ? ": " : "",
  1100. path->argument_name ? path->argument_name : "path",
  1101. path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
  1102. "integer or None" :
  1103. path->allow_fd ? "string, bytes, os.PathLike or integer" :
  1104. path->nullable ? "string, bytes, os.PathLike or None" :
  1105. "string, bytes or os.PathLike",
  1106. _PyType_Name(Py_TYPE(o)));
  1107. goto error_exit;
  1108. }
  1109. length = PyBytes_GET_SIZE(bytes);
  1110. narrow = PyBytes_AS_STRING(bytes);
  1111. if ((size_t)length != strlen(narrow)) {
  1112. FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
  1113. goto error_exit;
  1114. }
  1115. #ifdef MS_WINDOWS
  1116. wo = PyUnicode_DecodeFSDefaultAndSize(
  1117. narrow,
  1118. length
  1119. );
  1120. if (!wo) {
  1121. goto error_exit;
  1122. }
  1123. wide = PyUnicode_AsWideCharString(wo, &length);
  1124. Py_DECREF(wo);
  1125. if (!wide) {
  1126. goto error_exit;
  1127. }
  1128. if (length > 32767) {
  1129. FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
  1130. goto error_exit;
  1131. }
  1132. if (wcslen(wide) != length) {
  1133. FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
  1134. goto error_exit;
  1135. }
  1136. path->wide = wide;
  1137. path->narrow = TRUE;
  1138. Py_DECREF(bytes);
  1139. wide = NULL;
  1140. #else
  1141. path->wide = NULL;
  1142. path->narrow = narrow;
  1143. if (bytes == o) {
  1144. /* Still a reference owned by path->object, don't have to
  1145. worry about path->narrow is used after free. */
  1146. Py_DECREF(bytes);
  1147. }
  1148. else {
  1149. path->cleanup = bytes;
  1150. }
  1151. #endif
  1152. path->fd = -1;
  1153. success_exit:
  1154. path->length = length;
  1155. path->object = o;
  1156. return Py_CLEANUP_SUPPORTED;
  1157. error_exit:
  1158. Py_XDECREF(o);
  1159. Py_XDECREF(bytes);
  1160. #ifdef MS_WINDOWS
  1161. PyMem_Free(wide);
  1162. #endif
  1163. return 0;
  1164. }
  1165. static void
  1166. argument_unavailable_error(const char *function_name, const char *argument_name)
  1167. {
  1168. PyErr_Format(PyExc_NotImplementedError,
  1169. "%s%s%s unavailable on this platform",
  1170. (function_name != NULL) ? function_name : "",
  1171. (function_name != NULL) ? ": ": "",
  1172. argument_name);
  1173. }
  1174. static int
  1175. dir_fd_unavailable(PyObject *o, void *p)
  1176. {
  1177. int dir_fd;
  1178. if (!dir_fd_converter(o, &dir_fd))
  1179. return 0;
  1180. if (dir_fd != DEFAULT_DIR_FD) {
  1181. argument_unavailable_error(NULL, "dir_fd");
  1182. return 0;
  1183. }
  1184. *(int *)p = dir_fd;
  1185. return 1;
  1186. }
  1187. static int
  1188. fd_specified(const char *function_name, int fd)
  1189. {
  1190. if (fd == -1)
  1191. return 0;
  1192. argument_unavailable_error(function_name, "fd");
  1193. return 1;
  1194. }
  1195. static int
  1196. follow_symlinks_specified(const char *function_name, int follow_symlinks)
  1197. {
  1198. if (follow_symlinks)
  1199. return 0;
  1200. argument_unavailable_error(function_name, "follow_symlinks");
  1201. return 1;
  1202. }
  1203. static int
  1204. path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
  1205. {
  1206. if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
  1207. #ifndef MS_WINDOWS
  1208. && !path->narrow
  1209. #endif
  1210. ) {
  1211. PyErr_Format(PyExc_ValueError,
  1212. "%s: can't specify dir_fd without matching path",
  1213. function_name);
  1214. return 1;
  1215. }
  1216. return 0;
  1217. }
  1218. static int
  1219. dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
  1220. {
  1221. if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
  1222. PyErr_Format(PyExc_ValueError,
  1223. "%s: can't specify both dir_fd and fd",
  1224. function_name);
  1225. return 1;
  1226. }
  1227. return 0;
  1228. }
  1229. static int
  1230. fd_and_follow_symlinks_invalid(const char *function_name, int fd,
  1231. int follow_symlinks)
  1232. {
  1233. if ((fd > 0) && (!follow_symlinks)) {
  1234. PyErr_Format(PyExc_ValueError,
  1235. "%s: cannot use fd and follow_symlinks together",
  1236. function_name);
  1237. return 1;
  1238. }
  1239. return 0;
  1240. }
  1241. static int
  1242. dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
  1243. int follow_symlinks)
  1244. {
  1245. if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
  1246. PyErr_Format(PyExc_ValueError,
  1247. "%s: cannot use dir_fd and follow_symlinks together",
  1248. function_name);
  1249. return 1;
  1250. }
  1251. return 0;
  1252. }
  1253. #ifdef MS_WINDOWS
  1254. typedef long long Py_off_t;
  1255. #else
  1256. typedef off_t Py_off_t;
  1257. #endif
  1258. static int
  1259. Py_off_t_converter(PyObject *arg, void *addr)
  1260. {
  1261. #ifdef HAVE_LARGEFILE_SUPPORT
  1262. *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
  1263. #else
  1264. *((Py_off_t *)addr) = PyLong_AsLong(arg);
  1265. #endif
  1266. if (PyErr_Occurred())
  1267. return 0;
  1268. return 1;
  1269. }
  1270. static PyObject *
  1271. PyLong_FromPy_off_t(Py_off_t offset)
  1272. {
  1273. #ifdef HAVE_LARGEFILE_SUPPORT
  1274. return PyLong_FromLongLong(offset);
  1275. #else
  1276. return PyLong_FromLong(offset);
  1277. #endif
  1278. }
  1279. #ifdef HAVE_SIGSET_T
  1280. /* Convert an iterable of integers to a sigset.
  1281. Return 1 on success, return 0 and raise an exception on error. */
  1282. int
  1283. _Py_Sigset_Converter(PyObject *obj, void *addr)
  1284. {
  1285. sigset_t *mask = (sigset_t *)addr;
  1286. PyObject *iterator, *item;
  1287. long signum;
  1288. int overflow;
  1289. // The extra parens suppress the unreachable-code warning with clang on MacOS
  1290. if (sigemptyset(mask) < (0)) {
  1291. /* Probably only if mask == NULL. */
  1292. PyErr_SetFromErrno(PyExc_OSError);
  1293. return 0;
  1294. }
  1295. iterator = PyObject_GetIter(obj);
  1296. if (iterator == NULL) {
  1297. return 0;
  1298. }
  1299. while ((item = PyIter_Next(iterator)) != NULL) {
  1300. signum = PyLong_AsLongAndOverflow(item, &overflow);
  1301. Py_DECREF(item);
  1302. if (signum <= 0 || signum >= Py_NSIG) {
  1303. if (overflow || signum != -1 || !PyErr_Occurred()) {
  1304. PyErr_Format(PyExc_ValueError,
  1305. "signal number %ld out of range [1; %i]",
  1306. signum, Py_NSIG - 1);
  1307. }
  1308. goto error;
  1309. }
  1310. if (sigaddset(mask, (int)signum)) {
  1311. if (errno != EINVAL) {
  1312. /* Probably impossible */
  1313. PyErr_SetFromErrno(PyExc_OSError);
  1314. goto error;
  1315. }
  1316. /* For backwards compatibility, allow idioms such as
  1317. * `range(1, NSIG)` but warn about invalid signal numbers
  1318. */
  1319. const char msg[] =
  1320. "invalid signal number %ld, please use valid_signals()";
  1321. if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
  1322. goto error;
  1323. }
  1324. }
  1325. }
  1326. if (!PyErr_Occurred()) {
  1327. Py_DECREF(iterator);
  1328. return 1;
  1329. }
  1330. error:
  1331. Py_DECREF(iterator);
  1332. return 0;
  1333. }
  1334. #endif /* HAVE_SIGSET_T */
  1335. /* Return a dictionary corresponding to the POSIX environment table */
  1336. #if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
  1337. /* On Darwin/MacOSX a shared library or framework has no access to
  1338. ** environ directly, we must obtain it with _NSGetEnviron(). See also
  1339. ** man environ(7).
  1340. */
  1341. #include <crt_externs.h>
  1342. #elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
  1343. extern char **environ;
  1344. #endif /* !_MSC_VER */
  1345. static PyObject *
  1346. convertenviron(void)
  1347. {
  1348. PyObject *d;
  1349. #ifdef MS_WINDOWS
  1350. wchar_t **e;
  1351. #else
  1352. char **e;
  1353. #endif
  1354. d = PyDict_New();
  1355. if (d == NULL)
  1356. return NULL;
  1357. #ifdef MS_WINDOWS
  1358. /* _wenviron must be initialized in this way if the program is started
  1359. through main() instead of wmain(). */
  1360. (void)_wgetenv(L"");
  1361. e = _wenviron;
  1362. #elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
  1363. /* environ is not accessible as an extern in a shared object on OSX; use
  1364. _NSGetEnviron to resolve it. The value changes if you add environment
  1365. variables between calls to Py_Initialize, so don't cache the value. */
  1366. e = *_NSGetEnviron();
  1367. #else
  1368. e = environ;
  1369. #endif
  1370. if (e == NULL)
  1371. return d;
  1372. for (; *e != NULL; e++) {
  1373. PyObject *k;
  1374. PyObject *v;
  1375. #ifdef MS_WINDOWS
  1376. const wchar_t *p = wcschr(*e, L'=');
  1377. #else
  1378. const char *p = strchr(*e, '=');
  1379. #endif
  1380. if (p == NULL)
  1381. continue;
  1382. #ifdef MS_WINDOWS
  1383. k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
  1384. #else
  1385. k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
  1386. #endif
  1387. if (k == NULL) {
  1388. Py_DECREF(d);
  1389. return NULL;
  1390. }
  1391. #ifdef MS_WINDOWS
  1392. v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
  1393. #else
  1394. v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
  1395. #endif
  1396. if (v == NULL) {
  1397. Py_DECREF(k);
  1398. Py_DECREF(d);
  1399. return NULL;
  1400. }
  1401. if (PyDict_SetDefault(d, k, v) == NULL) {
  1402. Py_DECREF(v);
  1403. Py_DECREF(k);
  1404. Py_DECREF(d);
  1405. return NULL;
  1406. }
  1407. Py_DECREF(k);
  1408. Py_DECREF(v);
  1409. }
  1410. return d;
  1411. }
  1412. /* Set a POSIX-specific error from errno, and return NULL */
  1413. static PyObject *
  1414. posix_error(void)
  1415. {
  1416. return PyErr_SetFromErrno(PyExc_OSError);
  1417. }
  1418. #ifdef MS_WINDOWS
  1419. static PyObject *
  1420. win32_error(const char* function, const char* filename)
  1421. {
  1422. /* XXX We should pass the function name along in the future.
  1423. (winreg.c also wants to pass the function name.)
  1424. This would however require an additional param to the
  1425. Windows error object, which is non-trivial.
  1426. */
  1427. errno = GetLastError();
  1428. if (filename)
  1429. return PyErr_SetFromWindowsErrWithFilename(errno, filename);
  1430. else
  1431. return PyErr_SetFromWindowsErr(errno);
  1432. }
  1433. static PyObject *
  1434. win32_error_object_err(const char* function, PyObject* filename, DWORD err)
  1435. {
  1436. /* XXX - see win32_error for comments on 'function' */
  1437. if (filename)
  1438. return PyErr_SetExcFromWindowsErrWithFilenameObject(
  1439. PyExc_OSError,
  1440. err,
  1441. filename);
  1442. else
  1443. return PyErr_SetFromWindowsErr(err);
  1444. }
  1445. static PyObject *
  1446. win32_error_object(const char* function, PyObject* filename)
  1447. {
  1448. errno = GetLastError();
  1449. return win32_error_object_err(function, filename, errno);
  1450. }
  1451. #endif /* MS_WINDOWS */
  1452. static PyObject *
  1453. posix_path_object_error(PyObject *path)
  1454. {
  1455. return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
  1456. }
  1457. static PyObject *
  1458. path_object_error(PyObject *path)
  1459. {
  1460. #ifdef MS_WINDOWS
  1461. return PyErr_SetExcFromWindowsErrWithFilenameObject(
  1462. PyExc_OSError, 0, path);
  1463. #else
  1464. return posix_path_object_error(path);
  1465. #endif
  1466. }
  1467. static PyObject *
  1468. path_object_error2(PyObject *path, PyObject *path2)
  1469. {
  1470. #ifdef MS_WINDOWS
  1471. return PyErr_SetExcFromWindowsErrWithFilenameObjects(
  1472. PyExc_OSError, 0, path, path2);
  1473. #else
  1474. return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
  1475. #endif
  1476. }
  1477. static PyObject *
  1478. path_error(path_t *path)
  1479. {
  1480. return path_object_error(path->object);
  1481. }
  1482. static PyObject *
  1483. posix_path_error(path_t *path)
  1484. {
  1485. return posix_path_object_error(path->object);
  1486. }
  1487. static PyObject *
  1488. path_error2(path_t *path, path_t *path2)
  1489. {
  1490. return path_object_error2(path->object, path2->object);
  1491. }
  1492. /* POSIX generic methods */
  1493. static PyObject *
  1494. posix_fildes_fd(int fd, int (*func)(int))
  1495. {
  1496. int res;
  1497. int async_err = 0;
  1498. do {
  1499. Py_BEGIN_ALLOW_THREADS
  1500. _Py_BEGIN_SUPPRESS_IPH
  1501. res = (*func)(fd);
  1502. _Py_END_SUPPRESS_IPH
  1503. Py_END_ALLOW_THREADS
  1504. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1505. if (res != 0)
  1506. return (!async_err) ? posix_error() : NULL;
  1507. Py_RETURN_NONE;
  1508. }
  1509. #ifdef MS_WINDOWS
  1510. /* This is a reimplementation of the C library's chdir function,
  1511. but one that produces Win32 errors instead of DOS error codes.
  1512. chdir is essentially a wrapper around SetCurrentDirectory; however,
  1513. it also needs to set "magic" environment variables indicating
  1514. the per-drive current directory, which are of the form =<drive>: */
  1515. static BOOL __stdcall
  1516. win32_wchdir(LPCWSTR path)
  1517. {
  1518. wchar_t path_buf[MAX_PATH], *new_path = path_buf;
  1519. int result;
  1520. wchar_t env[4] = L"=x:";
  1521. if(!SetCurrentDirectoryW(path))
  1522. return FALSE;
  1523. result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
  1524. if (!result)
  1525. return FALSE;
  1526. if (result > Py_ARRAY_LENGTH(path_buf)) {
  1527. new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
  1528. if (!new_path) {
  1529. SetLastError(ERROR_OUTOFMEMORY);
  1530. return FALSE;
  1531. }
  1532. result = GetCurrentDirectoryW(result, new_path);
  1533. if (!result) {
  1534. PyMem_RawFree(new_path);
  1535. return FALSE;
  1536. }
  1537. }
  1538. int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
  1539. wcsncmp(new_path, L"//", 2) == 0);
  1540. if (!is_unc_like_path) {
  1541. env[1] = new_path[0];
  1542. result = SetEnvironmentVariableW(env, new_path);
  1543. }
  1544. if (new_path != path_buf)
  1545. PyMem_RawFree(new_path);
  1546. return result ? TRUE : FALSE;
  1547. }
  1548. #endif
  1549. #ifdef MS_WINDOWS
  1550. /* The CRT of Windows has a number of flaws wrt. its stat() implementation:
  1551. - time stamps are restricted to second resolution
  1552. - file modification times suffer from forth-and-back conversions between
  1553. UTC and local time
  1554. Therefore, we implement our own stat, based on the Win32 API directly.
  1555. */
  1556. #define HAVE_STAT_NSEC 1
  1557. #define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
  1558. #define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
  1559. static void
  1560. find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
  1561. BY_HANDLE_FILE_INFORMATION *info,
  1562. ULONG *reparse_tag)
  1563. {
  1564. memset(info, 0, sizeof(*info));
  1565. info->dwFileAttributes = pFileData->dwFileAttributes;
  1566. info->ftCreationTime = pFileData->ftCreationTime;
  1567. info->ftLastAccessTime = pFileData->ftLastAccessTime;
  1568. info->ftLastWriteTime = pFileData->ftLastWriteTime;
  1569. info->nFileSizeHigh = pFileData->nFileSizeHigh;
  1570. info->nFileSizeLow = pFileData->nFileSizeLow;
  1571. /* info->nNumberOfLinks = 1; */
  1572. if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
  1573. *reparse_tag = pFileData->dwReserved0;
  1574. else
  1575. *reparse_tag = 0;
  1576. }
  1577. static BOOL
  1578. attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
  1579. {
  1580. HANDLE hFindFile;
  1581. WIN32_FIND_DATAW FileData;
  1582. LPCWSTR filename = pszFile;
  1583. size_t n = wcslen(pszFile);
  1584. if (n && (pszFile[n - 1] == L'\\' || pszFile[n - 1] == L'/')) {
  1585. // cannot use PyMem_Malloc here because we do not hold the GIL
  1586. filename = (LPCWSTR)malloc((n + 1) * sizeof(filename[0]));
  1587. if(!filename) {
  1588. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1589. return FALSE;
  1590. }
  1591. wcsncpy_s((LPWSTR)filename, n + 1, pszFile, n);
  1592. while (--n > 0 && (filename[n] == L'\\' || filename[n] == L'/')) {
  1593. ((LPWSTR)filename)[n] = L'\0';
  1594. }
  1595. if (!n || (n == 1 && filename[1] == L':')) {
  1596. // Nothing left to query
  1597. free((void *)filename);
  1598. return FALSE;
  1599. }
  1600. }
  1601. hFindFile = FindFirstFileW(filename, &FileData);
  1602. if (pszFile != filename) {
  1603. free((void *)filename);
  1604. }
  1605. if (hFindFile == INVALID_HANDLE_VALUE) {
  1606. return FALSE;
  1607. }
  1608. FindClose(hFindFile);
  1609. find_data_to_file_info(&FileData, info, reparse_tag);
  1610. return TRUE;
  1611. }
  1612. static void
  1613. update_st_mode_from_path(const wchar_t *path, DWORD attr,
  1614. struct _Py_stat_struct *result)
  1615. {
  1616. if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) {
  1617. /* Fix the file execute permissions. This hack sets S_IEXEC if
  1618. the filename has an extension that is commonly used by files
  1619. that CreateProcessW can execute. A real implementation calls
  1620. GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
  1621. AccessCheck to check for generic read, write, and execute
  1622. access. */
  1623. const wchar_t *fileExtension = wcsrchr(path, '.');
  1624. if (fileExtension) {
  1625. if (_wcsicmp(fileExtension, L".exe") == 0 ||
  1626. _wcsicmp(fileExtension, L".bat") == 0 ||
  1627. _wcsicmp(fileExtension, L".cmd") == 0 ||
  1628. _wcsicmp(fileExtension, L".com") == 0) {
  1629. result->st_mode |= 0111;
  1630. }
  1631. }
  1632. }
  1633. }
  1634. static int
  1635. win32_xstat_slow_impl(const wchar_t *path, struct _Py_stat_struct *result,
  1636. BOOL traverse)
  1637. {
  1638. HANDLE hFile;
  1639. BY_HANDLE_FILE_INFORMATION fileInfo;
  1640. FILE_BASIC_INFO basicInfo;
  1641. FILE_BASIC_INFO *pBasicInfo = NULL;
  1642. FILE_ID_INFO idInfo;
  1643. FILE_ID_INFO *pIdInfo = NULL;
  1644. FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
  1645. DWORD fileType, error;
  1646. BOOL isUnhandledTag = FALSE;
  1647. int retval = 0;
  1648. DWORD access = FILE_READ_ATTRIBUTES;
  1649. DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
  1650. if (!traverse) {
  1651. flags |= FILE_FLAG_OPEN_REPARSE_POINT;
  1652. }
  1653. hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
  1654. if (hFile == INVALID_HANDLE_VALUE) {
  1655. /* Either the path doesn't exist, or the caller lacks access. */
  1656. error = GetLastError();
  1657. switch (error) {
  1658. case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
  1659. case ERROR_SHARING_VIOLATION: /* It's a paging file. */
  1660. /* Try reading the parent directory. */
  1661. if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
  1662. /* Cannot read the parent directory. */
  1663. switch (GetLastError()) {
  1664. case ERROR_FILE_NOT_FOUND: /* File cannot be found */
  1665. case ERROR_PATH_NOT_FOUND: /* File parent directory cannot be found */
  1666. case ERROR_NOT_READY: /* Drive exists but unavailable */
  1667. case ERROR_BAD_NET_NAME: /* Remote drive unavailable */
  1668. break;
  1669. /* Restore the error from CreateFileW(). */
  1670. default:
  1671. SetLastError(error);
  1672. }
  1673. return -1;
  1674. }
  1675. if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
  1676. if (traverse ||
  1677. !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
  1678. /* The stat call has to traverse but cannot, so fail. */
  1679. SetLastError(error);
  1680. return -1;
  1681. }
  1682. }
  1683. break;
  1684. case ERROR_INVALID_PARAMETER:
  1685. /* \\.\con requires read or write access. */
  1686. hFile = CreateFileW(path, access | GENERIC_READ,
  1687. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
  1688. OPEN_EXISTING, flags, NULL);
  1689. if (hFile == INVALID_HANDLE_VALUE) {
  1690. SetLastError(error);
  1691. return -1;
  1692. }
  1693. break;
  1694. case ERROR_CANT_ACCESS_FILE:
  1695. /* bpo37834: open unhandled reparse points if traverse fails. */
  1696. if (traverse) {
  1697. traverse = FALSE;
  1698. isUnhandledTag = TRUE;
  1699. hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
  1700. flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
  1701. }
  1702. if (hFile == INVALID_HANDLE_VALUE) {
  1703. SetLastError(error);
  1704. return -1;
  1705. }
  1706. break;
  1707. default:
  1708. return -1;
  1709. }
  1710. }
  1711. if (hFile != INVALID_HANDLE_VALUE) {
  1712. /* Handle types other than files on disk. */
  1713. fileType = GetFileType(hFile);
  1714. if (fileType != FILE_TYPE_DISK) {
  1715. if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
  1716. retval = -1;
  1717. goto cleanup;
  1718. }
  1719. DWORD fileAttributes = GetFileAttributesW(path);
  1720. memset(result, 0, sizeof(*result));
  1721. if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
  1722. fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  1723. /* \\.\pipe\ or \\.\mailslot\ */
  1724. result->st_mode = _S_IFDIR;
  1725. } else if (fileType == FILE_TYPE_CHAR) {
  1726. /* \\.\nul */
  1727. result->st_mode = _S_IFCHR;
  1728. } else if (fileType == FILE_TYPE_PIPE) {
  1729. /* \\.\pipe\spam */
  1730. result->st_mode = _S_IFIFO;
  1731. }
  1732. /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
  1733. goto cleanup;
  1734. }
  1735. /* Query the reparse tag, and traverse a non-link. */
  1736. if (!traverse) {
  1737. if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
  1738. &tagInfo, sizeof(tagInfo))) {
  1739. /* Allow devices that do not support FileAttributeTagInfo. */
  1740. switch (GetLastError()) {
  1741. case ERROR_INVALID_PARAMETER:
  1742. case ERROR_INVALID_FUNCTION:
  1743. case ERROR_NOT_SUPPORTED:
  1744. tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
  1745. tagInfo.ReparseTag = 0;
  1746. break;
  1747. default:
  1748. retval = -1;
  1749. goto cleanup;
  1750. }
  1751. } else if (tagInfo.FileAttributes &
  1752. FILE_ATTRIBUTE_REPARSE_POINT) {
  1753. if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
  1754. if (isUnhandledTag) {
  1755. /* Traversing previously failed for either this link
  1756. or its target. */
  1757. SetLastError(ERROR_CANT_ACCESS_FILE);
  1758. retval = -1;
  1759. goto cleanup;
  1760. }
  1761. /* Traverse a non-link, but not if traversing already failed
  1762. for an unhandled tag. */
  1763. } else if (!isUnhandledTag) {
  1764. CloseHandle(hFile);
  1765. return win32_xstat_slow_impl(path, result, TRUE);
  1766. }
  1767. }
  1768. }
  1769. if (!GetFileInformationByHandle(hFile, &fileInfo) ||
  1770. !GetFileInformationByHandleEx(hFile, FileBasicInfo,
  1771. &basicInfo, sizeof(basicInfo))) {
  1772. switch (GetLastError()) {
  1773. case ERROR_INVALID_PARAMETER:
  1774. case ERROR_INVALID_FUNCTION:
  1775. case ERROR_NOT_SUPPORTED:
  1776. /* Volumes and physical disks are block devices, e.g.
  1777. \\.\C: and \\.\PhysicalDrive0. */
  1778. memset(result, 0, sizeof(*result));
  1779. result->st_mode = 0x6000; /* S_IFBLK */
  1780. goto cleanup;
  1781. }
  1782. retval = -1;
  1783. goto cleanup;
  1784. }
  1785. /* Successfully got FileBasicInfo, so we'll pass it along */
  1786. pBasicInfo = &basicInfo;
  1787. if (GetFileInformationByHandleEx(hFile, FileIdInfo, &idInfo, sizeof(idInfo))) {
  1788. /* Successfully got FileIdInfo, so pass it along */
  1789. pIdInfo = &idInfo;
  1790. }
  1791. }
  1792. _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, pBasicInfo, pIdInfo, result);
  1793. update_st_mode_from_path(path, fileInfo.dwFileAttributes, result);
  1794. cleanup:
  1795. if (hFile != INVALID_HANDLE_VALUE) {
  1796. /* Preserve last error if we are failing */
  1797. error = retval ? GetLastError() : 0;
  1798. if (!CloseHandle(hFile)) {
  1799. retval = -1;
  1800. } else if (retval) {
  1801. /* Restore last error */
  1802. SetLastError(error);
  1803. }
  1804. }
  1805. return retval;
  1806. }
  1807. static int
  1808. win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
  1809. BOOL traverse)
  1810. {
  1811. FILE_STAT_BASIC_INFORMATION statInfo;
  1812. if (_Py_GetFileInformationByName(path, FileStatBasicByNameInfo,
  1813. &statInfo, sizeof(statInfo))) {
  1814. if (// Cannot use fast path for reparse points ...
  1815. !(statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
  1816. // ... unless it's a name surrogate (symlink) and we're not following
  1817. || (!traverse && IsReparseTagNameSurrogate(statInfo.ReparseTag))
  1818. ) {
  1819. _Py_stat_basic_info_to_stat(&statInfo, result);
  1820. update_st_mode_from_path(path, statInfo.FileAttributes, result);
  1821. return 0;
  1822. }
  1823. } else {
  1824. switch(GetLastError()) {
  1825. case ERROR_FILE_NOT_FOUND:
  1826. case ERROR_PATH_NOT_FOUND:
  1827. case ERROR_NOT_READY:
  1828. case ERROR_BAD_NET_NAME:
  1829. /* These errors aren't worth retrying with the slow path */
  1830. return -1;
  1831. case ERROR_NOT_SUPPORTED:
  1832. /* indicates the API couldn't be loaded */
  1833. break;
  1834. }
  1835. }
  1836. return win32_xstat_slow_impl(path, result, traverse);
  1837. }
  1838. static int
  1839. win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
  1840. {
  1841. /* Protocol violation: we explicitly clear errno, instead of
  1842. setting it to a POSIX error. Callers should use GetLastError. */
  1843. int code = win32_xstat_impl(path, result, traverse);
  1844. errno = 0;
  1845. /* ctime is only deprecated from 3.12, so we copy birthtime across */
  1846. result->st_ctime = result->st_birthtime;
  1847. result->st_ctime_nsec = result->st_birthtime_nsec;
  1848. return code;
  1849. }
  1850. /* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
  1851. In Posix, stat automatically traverses symlinks and returns the stat
  1852. structure for the target. In Windows, the equivalent GetFileAttributes by
  1853. default does not traverse symlinks and instead returns attributes for
  1854. the symlink.
  1855. Instead, we will open the file (which *does* traverse symlinks by default)
  1856. and GetFileInformationByHandle(). */
  1857. static int
  1858. win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
  1859. {
  1860. return win32_xstat(path, result, FALSE);
  1861. }
  1862. static int
  1863. win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
  1864. {
  1865. return win32_xstat(path, result, TRUE);
  1866. }
  1867. #endif /* MS_WINDOWS */
  1868. PyDoc_STRVAR(stat_result__doc__,
  1869. "stat_result: Result from stat, fstat, or lstat.\n\n\
  1870. This object may be accessed either as a tuple of\n\
  1871. (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
  1872. or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
  1873. \n\
  1874. Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
  1875. or st_flags, they are available as attributes only.\n\
  1876. \n\
  1877. See os.stat for more information.");
  1878. static PyStructSequence_Field stat_result_fields[] = {
  1879. {"st_mode", "protection bits"},
  1880. {"st_ino", "inode"},
  1881. {"st_dev", "device"},
  1882. {"st_nlink", "number of hard links"},
  1883. {"st_uid", "user ID of owner"},
  1884. {"st_gid", "group ID of owner"},
  1885. {"st_size", "total size, in bytes"},
  1886. /* The NULL is replaced with PyStructSequence_UnnamedField later. */
  1887. {NULL, "integer time of last access"},
  1888. {NULL, "integer time of last modification"},
  1889. {NULL, "integer time of last change"},
  1890. {"st_atime", "time of last access"},
  1891. {"st_mtime", "time of last modification"},
  1892. {"st_ctime", "time of last change"},
  1893. {"st_atime_ns", "time of last access in nanoseconds"},
  1894. {"st_mtime_ns", "time of last modification in nanoseconds"},
  1895. {"st_ctime_ns", "time of last change in nanoseconds"},
  1896. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1897. {"st_blksize", "blocksize for filesystem I/O"},
  1898. #endif
  1899. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1900. {"st_blocks", "number of blocks allocated"},
  1901. #endif
  1902. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1903. {"st_rdev", "device type (if inode device)"},
  1904. #endif
  1905. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1906. {"st_flags", "user defined flags for file"},
  1907. #endif
  1908. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1909. {"st_gen", "generation number"},
  1910. #endif
  1911. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) || defined(MS_WINDOWS)
  1912. {"st_birthtime", "time of creation"},
  1913. #endif
  1914. #ifdef MS_WINDOWS
  1915. {"st_birthtime_ns", "time of creation in nanoseconds"},
  1916. #endif
  1917. #ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
  1918. {"st_file_attributes", "Windows file attribute bits"},
  1919. #endif
  1920. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  1921. {"st_fstype", "Type of filesystem"},
  1922. #endif
  1923. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  1924. {"st_reparse_tag", "Windows reparse tag"},
  1925. #endif
  1926. {0}
  1927. };
  1928. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1929. #define ST_BLKSIZE_IDX 16
  1930. #else
  1931. #define ST_BLKSIZE_IDX 15
  1932. #endif
  1933. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1934. #define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
  1935. #else
  1936. #define ST_BLOCKS_IDX ST_BLKSIZE_IDX
  1937. #endif
  1938. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1939. #define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
  1940. #else
  1941. #define ST_RDEV_IDX ST_BLOCKS_IDX
  1942. #endif
  1943. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1944. #define ST_FLAGS_IDX (ST_RDEV_IDX+1)
  1945. #else
  1946. #define ST_FLAGS_IDX ST_RDEV_IDX
  1947. #endif
  1948. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1949. #define ST_GEN_IDX (ST_FLAGS_IDX+1)
  1950. #else
  1951. #define ST_GEN_IDX ST_FLAGS_IDX
  1952. #endif
  1953. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) || defined(MS_WINDOWS)
  1954. #define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
  1955. #else
  1956. #define ST_BIRTHTIME_IDX ST_GEN_IDX
  1957. #endif
  1958. #ifdef MS_WINDOWS
  1959. #define ST_BIRTHTIME_NS_IDX (ST_BIRTHTIME_IDX+1)
  1960. #else
  1961. #define ST_BIRTHTIME_NS_IDX ST_BIRTHTIME_IDX
  1962. #endif
  1963. #if defined(HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES) || defined(MS_WINDOWS)
  1964. #define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_NS_IDX+1)
  1965. #else
  1966. #define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_NS_IDX
  1967. #endif
  1968. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  1969. #define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
  1970. #else
  1971. #define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
  1972. #endif
  1973. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  1974. #define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
  1975. #else
  1976. #define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
  1977. #endif
  1978. static PyStructSequence_Desc stat_result_desc = {
  1979. "stat_result", /* name */
  1980. stat_result__doc__, /* doc */
  1981. stat_result_fields,
  1982. 10
  1983. };
  1984. PyDoc_STRVAR(statvfs_result__doc__,
  1985. "statvfs_result: Result from statvfs or fstatvfs.\n\n\
  1986. This object may be accessed either as a tuple of\n\
  1987. (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
  1988. or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
  1989. \n\
  1990. See os.statvfs for more information.");
  1991. static PyStructSequence_Field statvfs_result_fields[] = {
  1992. {"f_bsize", },
  1993. {"f_frsize", },
  1994. {"f_blocks", },
  1995. {"f_bfree", },
  1996. {"f_bavail", },
  1997. {"f_files", },
  1998. {"f_ffree", },
  1999. {"f_favail", },
  2000. {"f_flag", },
  2001. {"f_namemax",},
  2002. {"f_fsid", },
  2003. {0}
  2004. };
  2005. static PyStructSequence_Desc statvfs_result_desc = {
  2006. "statvfs_result", /* name */
  2007. statvfs_result__doc__, /* doc */
  2008. statvfs_result_fields,
  2009. 10
  2010. };
  2011. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2012. PyDoc_STRVAR(waitid_result__doc__,
  2013. "waitid_result: Result from waitid.\n\n\
  2014. This object may be accessed either as a tuple of\n\
  2015. (si_pid, si_uid, si_signo, si_status, si_code),\n\
  2016. or via the attributes si_pid, si_uid, and so on.\n\
  2017. \n\
  2018. See os.waitid for more information.");
  2019. static PyStructSequence_Field waitid_result_fields[] = {
  2020. {"si_pid", },
  2021. {"si_uid", },
  2022. {"si_signo", },
  2023. {"si_status", },
  2024. {"si_code", },
  2025. {0}
  2026. };
  2027. static PyStructSequence_Desc waitid_result_desc = {
  2028. "waitid_result", /* name */
  2029. waitid_result__doc__, /* doc */
  2030. waitid_result_fields,
  2031. 5
  2032. };
  2033. #endif
  2034. static PyObject *
  2035. statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2036. {
  2037. PyStructSequence *result;
  2038. int i;
  2039. // ht_module doesn't get set in PyStructSequence_NewType(),
  2040. // so we can't use PyType_GetModule().
  2041. PyObject *mod = PyImport_GetModule(MODNAME_OBJ);
  2042. if (mod == NULL) {
  2043. return NULL;
  2044. }
  2045. _posixstate *state = get_posix_state(mod);
  2046. Py_DECREF(mod);
  2047. if (state == NULL) {
  2048. return NULL;
  2049. }
  2050. #define structseq_new state->statresult_new_orig
  2051. result = (PyStructSequence*)structseq_new(type, args, kwds);
  2052. if (!result)
  2053. return NULL;
  2054. /* If we have been initialized from a tuple,
  2055. st_?time might be set to None. Initialize it
  2056. from the int slots. */
  2057. for (i = 7; i <= 9; i++) {
  2058. if (result->ob_item[i+3] == Py_None) {
  2059. Py_DECREF(Py_None);
  2060. result->ob_item[i+3] = Py_NewRef(result->ob_item[i]);
  2061. }
  2062. }
  2063. return (PyObject*)result;
  2064. }
  2065. static int
  2066. _posix_clear(PyObject *module)
  2067. {
  2068. _posixstate *state = get_posix_state(module);
  2069. Py_CLEAR(state->billion);
  2070. Py_CLEAR(state->DirEntryType);
  2071. Py_CLEAR(state->ScandirIteratorType);
  2072. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  2073. Py_CLEAR(state->SchedParamType);
  2074. #endif
  2075. Py_CLEAR(state->StatResultType);
  2076. Py_CLEAR(state->StatVFSResultType);
  2077. Py_CLEAR(state->TerminalSizeType);
  2078. Py_CLEAR(state->TimesResultType);
  2079. Py_CLEAR(state->UnameResultType);
  2080. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2081. Py_CLEAR(state->WaitidResultType);
  2082. #endif
  2083. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  2084. Py_CLEAR(state->struct_rusage);
  2085. #endif
  2086. Py_CLEAR(state->st_mode);
  2087. return 0;
  2088. }
  2089. static int
  2090. _posix_traverse(PyObject *module, visitproc visit, void *arg)
  2091. {
  2092. _posixstate *state = get_posix_state(module);
  2093. Py_VISIT(state->billion);
  2094. Py_VISIT(state->DirEntryType);
  2095. Py_VISIT(state->ScandirIteratorType);
  2096. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  2097. Py_VISIT(state->SchedParamType);
  2098. #endif
  2099. Py_VISIT(state->StatResultType);
  2100. Py_VISIT(state->StatVFSResultType);
  2101. Py_VISIT(state->TerminalSizeType);
  2102. Py_VISIT(state->TimesResultType);
  2103. Py_VISIT(state->UnameResultType);
  2104. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  2105. Py_VISIT(state->WaitidResultType);
  2106. #endif
  2107. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  2108. Py_VISIT(state->struct_rusage);
  2109. #endif
  2110. Py_VISIT(state->st_mode);
  2111. return 0;
  2112. }
  2113. static void
  2114. _posix_free(void *module)
  2115. {
  2116. _posix_clear((PyObject *)module);
  2117. }
  2118. static int
  2119. fill_time(PyObject *module, PyObject *v, int s_index, int f_index, int ns_index, time_t sec, unsigned long nsec)
  2120. {
  2121. assert(!PyErr_Occurred());
  2122. int res = -1;
  2123. PyObject *s_in_ns = NULL;
  2124. PyObject *ns_total = NULL;
  2125. PyObject *float_s = NULL;
  2126. PyObject *s = _PyLong_FromTime_t(sec);
  2127. PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
  2128. if (!(s && ns_fractional)) {
  2129. goto exit;
  2130. }
  2131. s_in_ns = PyNumber_Multiply(s, get_posix_state(module)->billion);
  2132. if (!s_in_ns) {
  2133. goto exit;
  2134. }
  2135. ns_total = PyNumber_Add(s_in_ns, ns_fractional);
  2136. if (!ns_total)
  2137. goto exit;
  2138. float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
  2139. if (!float_s) {
  2140. goto exit;
  2141. }
  2142. if (s_index >= 0) {
  2143. PyStructSequence_SET_ITEM(v, s_index, s);
  2144. s = NULL;
  2145. }
  2146. if (f_index >= 0) {
  2147. PyStructSequence_SET_ITEM(v, f_index, float_s);
  2148. float_s = NULL;
  2149. }
  2150. if (ns_index >= 0) {
  2151. PyStructSequence_SET_ITEM(v, ns_index, ns_total);
  2152. ns_total = NULL;
  2153. }
  2154. assert(!PyErr_Occurred());
  2155. res = 0;
  2156. exit:
  2157. Py_XDECREF(s);
  2158. Py_XDECREF(ns_fractional);
  2159. Py_XDECREF(s_in_ns);
  2160. Py_XDECREF(ns_total);
  2161. Py_XDECREF(float_s);
  2162. return res;
  2163. }
  2164. #ifdef MS_WINDOWS
  2165. static PyObject*
  2166. _pystat_l128_from_l64_l64(uint64_t low, uint64_t high)
  2167. {
  2168. PyObject *o_low = PyLong_FromUnsignedLongLong(low);
  2169. if (!o_low || !high) {
  2170. return o_low;
  2171. }
  2172. PyObject *o_high = PyLong_FromUnsignedLongLong(high);
  2173. PyObject *l64 = o_high ? PyLong_FromLong(64) : NULL;
  2174. if (!l64) {
  2175. Py_XDECREF(o_high);
  2176. Py_DECREF(o_low);
  2177. return NULL;
  2178. }
  2179. Py_SETREF(o_high, PyNumber_Lshift(o_high, l64));
  2180. Py_DECREF(l64);
  2181. if (!o_high) {
  2182. Py_DECREF(o_low);
  2183. return NULL;
  2184. }
  2185. Py_SETREF(o_low, PyNumber_Add(o_low, o_high));
  2186. Py_DECREF(o_high);
  2187. return o_low;
  2188. }
  2189. #endif
  2190. /* pack a system stat C structure into the Python stat tuple
  2191. (used by posix_stat() and posix_fstat()) */
  2192. static PyObject*
  2193. _pystat_fromstructstat(PyObject *module, STRUCT_STAT *st)
  2194. {
  2195. assert(!PyErr_Occurred());
  2196. PyObject *StatResultType = get_posix_state(module)->StatResultType;
  2197. PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
  2198. if (v == NULL) {
  2199. return NULL;
  2200. }
  2201. #define SET_ITEM(pos, expr) \
  2202. do { \
  2203. PyObject *obj = (expr); \
  2204. if (obj == NULL) { \
  2205. goto error; \
  2206. } \
  2207. PyStructSequence_SET_ITEM(v, (pos), obj); \
  2208. } while (0)
  2209. SET_ITEM(0, PyLong_FromLong((long)st->st_mode));
  2210. #ifdef MS_WINDOWS
  2211. SET_ITEM(1, _pystat_l128_from_l64_l64(st->st_ino, st->st_ino_high));
  2212. SET_ITEM(2, PyLong_FromUnsignedLongLong(st->st_dev));
  2213. #else
  2214. static_assert(sizeof(unsigned long long) >= sizeof(st->st_ino),
  2215. "stat.st_ino is larger than unsigned long long");
  2216. SET_ITEM(1, PyLong_FromUnsignedLongLong(st->st_ino));
  2217. SET_ITEM(2, _PyLong_FromDev(st->st_dev));
  2218. #endif
  2219. SET_ITEM(3, PyLong_FromLong((long)st->st_nlink));
  2220. #if defined(MS_WINDOWS)
  2221. SET_ITEM(4, PyLong_FromLong(0));
  2222. SET_ITEM(5, PyLong_FromLong(0));
  2223. #else
  2224. SET_ITEM(4, _PyLong_FromUid(st->st_uid));
  2225. SET_ITEM(5, _PyLong_FromGid(st->st_gid));
  2226. #endif
  2227. static_assert(sizeof(long long) >= sizeof(st->st_size),
  2228. "stat.st_size is larger than long long");
  2229. SET_ITEM(6, PyLong_FromLongLong(st->st_size));
  2230. // Set st_atime, st_mtime and st_ctime
  2231. unsigned long ansec, mnsec, cnsec;
  2232. #if defined(HAVE_STAT_TV_NSEC)
  2233. ansec = st->st_atim.tv_nsec;
  2234. mnsec = st->st_mtim.tv_nsec;
  2235. cnsec = st->st_ctim.tv_nsec;
  2236. #elif defined(HAVE_STAT_TV_NSEC2)
  2237. ansec = st->st_atimespec.tv_nsec;
  2238. mnsec = st->st_mtimespec.tv_nsec;
  2239. cnsec = st->st_ctimespec.tv_nsec;
  2240. #elif defined(HAVE_STAT_NSEC)
  2241. ansec = st->st_atime_nsec;
  2242. mnsec = st->st_mtime_nsec;
  2243. cnsec = st->st_ctime_nsec;
  2244. #else
  2245. ansec = mnsec = cnsec = 0;
  2246. #endif
  2247. if (fill_time(module, v, 7, 10, 13, st->st_atime, ansec) < 0) {
  2248. goto error;
  2249. }
  2250. if (fill_time(module, v, 8, 11, 14, st->st_mtime, mnsec) < 0) {
  2251. goto error;
  2252. }
  2253. if (fill_time(module, v, 9, 12, 15, st->st_ctime, cnsec) < 0) {
  2254. goto error;
  2255. }
  2256. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  2257. SET_ITEM(ST_BLKSIZE_IDX, PyLong_FromLong((long)st->st_blksize));
  2258. #endif
  2259. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  2260. SET_ITEM(ST_BLOCKS_IDX, PyLong_FromLong((long)st->st_blocks));
  2261. #endif
  2262. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  2263. SET_ITEM(ST_RDEV_IDX, PyLong_FromLong((long)st->st_rdev));
  2264. #endif
  2265. #ifdef HAVE_STRUCT_STAT_ST_GEN
  2266. SET_ITEM(ST_GEN_IDX, PyLong_FromLong((long)st->st_gen));
  2267. #endif
  2268. #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME)
  2269. {
  2270. unsigned long bsec, bnsec;
  2271. bsec = (long)st->st_birthtime;
  2272. #ifdef HAVE_STAT_TV_NSEC2
  2273. bnsec = st->st_birthtimespec.tv_nsec;
  2274. #else
  2275. bnsec = 0;
  2276. #endif
  2277. SET_ITEM(ST_BIRTHTIME_IDX, PyFloat_FromDouble(bsec + bnsec * 1e-9));
  2278. }
  2279. #elif defined(MS_WINDOWS)
  2280. if (fill_time(module, v, -1, ST_BIRTHTIME_IDX, ST_BIRTHTIME_NS_IDX,
  2281. st->st_birthtime, st->st_birthtime_nsec) < 0) {
  2282. goto error;
  2283. }
  2284. #endif
  2285. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  2286. SET_ITEM(ST_FLAGS_IDX, PyLong_FromLong((long)st->st_flags));
  2287. #endif
  2288. #ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
  2289. SET_ITEM(ST_FILE_ATTRIBUTES_IDX,
  2290. PyLong_FromUnsignedLong(st->st_file_attributes));
  2291. #endif
  2292. #ifdef HAVE_STRUCT_STAT_ST_FSTYPE
  2293. SET_ITEM(ST_FSTYPE_IDX, PyUnicode_FromString(st->st_fstype));
  2294. #endif
  2295. #ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
  2296. SET_ITEM(ST_REPARSE_TAG_IDX, PyLong_FromUnsignedLong(st->st_reparse_tag));
  2297. #endif
  2298. assert(!PyErr_Occurred());
  2299. return v;
  2300. error:
  2301. Py_DECREF(v);
  2302. return NULL;
  2303. #undef SET_ITEM
  2304. }
  2305. /* POSIX methods */
  2306. static PyObject *
  2307. posix_do_stat(PyObject *module, const char *function_name, path_t *path,
  2308. int dir_fd, int follow_symlinks)
  2309. {
  2310. STRUCT_STAT st;
  2311. int result;
  2312. #ifdef HAVE_FSTATAT
  2313. int fstatat_unavailable = 0;
  2314. #endif
  2315. #if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
  2316. if (follow_symlinks_specified(function_name, follow_symlinks))
  2317. return NULL;
  2318. #endif
  2319. if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
  2320. dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
  2321. fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
  2322. return NULL;
  2323. Py_BEGIN_ALLOW_THREADS
  2324. if (path->fd != -1)
  2325. result = FSTAT(path->fd, &st);
  2326. #ifdef MS_WINDOWS
  2327. else if (follow_symlinks)
  2328. result = win32_stat(path->wide, &st);
  2329. else
  2330. result = win32_lstat(path->wide, &st);
  2331. #else
  2332. else
  2333. #if defined(HAVE_LSTAT)
  2334. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  2335. result = LSTAT(path->narrow, &st);
  2336. else
  2337. #endif /* HAVE_LSTAT */
  2338. #ifdef HAVE_FSTATAT
  2339. if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
  2340. if (HAVE_FSTATAT_RUNTIME) {
  2341. result = fstatat(dir_fd, path->narrow, &st,
  2342. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  2343. } else {
  2344. fstatat_unavailable = 1;
  2345. }
  2346. } else
  2347. #endif /* HAVE_FSTATAT */
  2348. result = STAT(path->narrow, &st);
  2349. #endif /* MS_WINDOWS */
  2350. Py_END_ALLOW_THREADS
  2351. #ifdef HAVE_FSTATAT
  2352. if (fstatat_unavailable) {
  2353. argument_unavailable_error("stat", "dir_fd");
  2354. return NULL;
  2355. }
  2356. #endif
  2357. if (result != 0) {
  2358. return path_error(path);
  2359. }
  2360. return _pystat_fromstructstat(module, &st);
  2361. }
  2362. /*[python input]
  2363. for s in """
  2364. FACCESSAT
  2365. FCHMODAT
  2366. FCHOWNAT
  2367. FSTATAT
  2368. LINKAT
  2369. MKDIRAT
  2370. MKFIFOAT
  2371. MKNODAT
  2372. OPENAT
  2373. READLINKAT
  2374. SYMLINKAT
  2375. UNLINKAT
  2376. """.strip().split():
  2377. s = s.strip()
  2378. print("""
  2379. #ifdef HAVE_{s}
  2380. #define {s}_DIR_FD_CONVERTER dir_fd_converter
  2381. #else
  2382. #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
  2383. #endif
  2384. """.rstrip().format(s=s))
  2385. for s in """
  2386. FCHDIR
  2387. FCHMOD
  2388. FCHOWN
  2389. FDOPENDIR
  2390. FEXECVE
  2391. FPATHCONF
  2392. FSTATVFS
  2393. FTRUNCATE
  2394. """.strip().split():
  2395. s = s.strip()
  2396. print("""
  2397. #ifdef HAVE_{s}
  2398. #define PATH_HAVE_{s} 1
  2399. #else
  2400. #define PATH_HAVE_{s} 0
  2401. #endif
  2402. """.rstrip().format(s=s))
  2403. [python start generated code]*/
  2404. #ifdef HAVE_FACCESSAT
  2405. #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
  2406. #else
  2407. #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
  2408. #endif
  2409. #ifdef HAVE_FCHMODAT
  2410. #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
  2411. #else
  2412. #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
  2413. #endif
  2414. #ifdef HAVE_FCHOWNAT
  2415. #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
  2416. #else
  2417. #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
  2418. #endif
  2419. #ifdef HAVE_FSTATAT
  2420. #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
  2421. #else
  2422. #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
  2423. #endif
  2424. #ifdef HAVE_LINKAT
  2425. #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
  2426. #else
  2427. #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2428. #endif
  2429. #ifdef HAVE_MKDIRAT
  2430. #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
  2431. #else
  2432. #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
  2433. #endif
  2434. #ifdef HAVE_MKFIFOAT
  2435. #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
  2436. #else
  2437. #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
  2438. #endif
  2439. #ifdef HAVE_MKNODAT
  2440. #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
  2441. #else
  2442. #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
  2443. #endif
  2444. #ifdef HAVE_OPENAT
  2445. #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
  2446. #else
  2447. #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
  2448. #endif
  2449. #ifdef HAVE_READLINKAT
  2450. #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2451. #else
  2452. #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2453. #endif
  2454. #ifdef HAVE_SYMLINKAT
  2455. #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2456. #else
  2457. #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2458. #endif
  2459. #ifdef HAVE_UNLINKAT
  2460. #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
  2461. #else
  2462. #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
  2463. #endif
  2464. #ifdef HAVE_FCHDIR
  2465. #define PATH_HAVE_FCHDIR 1
  2466. #else
  2467. #define PATH_HAVE_FCHDIR 0
  2468. #endif
  2469. #ifdef HAVE_FCHMOD
  2470. #define PATH_HAVE_FCHMOD 1
  2471. #else
  2472. #define PATH_HAVE_FCHMOD 0
  2473. #endif
  2474. #ifdef HAVE_FCHOWN
  2475. #define PATH_HAVE_FCHOWN 1
  2476. #else
  2477. #define PATH_HAVE_FCHOWN 0
  2478. #endif
  2479. #ifdef HAVE_FDOPENDIR
  2480. #define PATH_HAVE_FDOPENDIR 1
  2481. #else
  2482. #define PATH_HAVE_FDOPENDIR 0
  2483. #endif
  2484. #ifdef HAVE_FEXECVE
  2485. #define PATH_HAVE_FEXECVE 1
  2486. #else
  2487. #define PATH_HAVE_FEXECVE 0
  2488. #endif
  2489. #ifdef HAVE_FPATHCONF
  2490. #define PATH_HAVE_FPATHCONF 1
  2491. #else
  2492. #define PATH_HAVE_FPATHCONF 0
  2493. #endif
  2494. #ifdef HAVE_FSTATVFS
  2495. #define PATH_HAVE_FSTATVFS 1
  2496. #else
  2497. #define PATH_HAVE_FSTATVFS 0
  2498. #endif
  2499. #ifdef HAVE_FTRUNCATE
  2500. #define PATH_HAVE_FTRUNCATE 1
  2501. #else
  2502. #define PATH_HAVE_FTRUNCATE 0
  2503. #endif
  2504. /*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
  2505. #ifdef MS_WINDOWS
  2506. #undef PATH_HAVE_FTRUNCATE
  2507. #define PATH_HAVE_FTRUNCATE 1
  2508. #endif
  2509. /*[python input]
  2510. class path_t_converter(CConverter):
  2511. type = "path_t"
  2512. impl_by_reference = True
  2513. parse_by_reference = True
  2514. converter = 'path_converter'
  2515. def converter_init(self, *, allow_fd=False, nullable=False):
  2516. # right now path_t doesn't support default values.
  2517. # to support a default value, you'll need to override initialize().
  2518. if self.default not in (unspecified, None):
  2519. fail("Can't specify a default to the path_t converter!")
  2520. if self.c_default not in (None, 'Py_None'):
  2521. raise RuntimeError("Can't specify a c_default to the path_t converter!")
  2522. self.nullable = nullable
  2523. self.allow_fd = allow_fd
  2524. def pre_render(self):
  2525. def strify(value):
  2526. if isinstance(value, str):
  2527. return value
  2528. return str(int(bool(value)))
  2529. # add self.py_name here when merging with posixmodule conversion
  2530. self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
  2531. self.function.name,
  2532. self.name,
  2533. strify(self.nullable),
  2534. strify(self.allow_fd),
  2535. )
  2536. def cleanup(self):
  2537. return "path_cleanup(&" + self.name + ");\n"
  2538. class dir_fd_converter(CConverter):
  2539. type = 'int'
  2540. def converter_init(self, requires=None):
  2541. if self.default in (unspecified, None):
  2542. self.c_default = 'DEFAULT_DIR_FD'
  2543. if isinstance(requires, str):
  2544. self.converter = requires.upper() + '_DIR_FD_CONVERTER'
  2545. else:
  2546. self.converter = 'dir_fd_converter'
  2547. class uid_t_converter(CConverter):
  2548. type = "uid_t"
  2549. converter = '_Py_Uid_Converter'
  2550. class gid_t_converter(CConverter):
  2551. type = "gid_t"
  2552. converter = '_Py_Gid_Converter'
  2553. class dev_t_converter(CConverter):
  2554. type = 'dev_t'
  2555. converter = '_Py_Dev_Converter'
  2556. class dev_t_return_converter(unsigned_long_return_converter):
  2557. type = 'dev_t'
  2558. conversion_fn = '_PyLong_FromDev'
  2559. unsigned_cast = '(dev_t)'
  2560. class FSConverter_converter(CConverter):
  2561. type = 'PyObject *'
  2562. converter = 'PyUnicode_FSConverter'
  2563. def converter_init(self):
  2564. if self.default is not unspecified:
  2565. fail("FSConverter_converter does not support default values")
  2566. self.c_default = 'NULL'
  2567. def cleanup(self):
  2568. return "Py_XDECREF(" + self.name + ");\n"
  2569. class pid_t_converter(CConverter):
  2570. type = 'pid_t'
  2571. format_unit = '" _Py_PARSE_PID "'
  2572. class idtype_t_converter(int_converter):
  2573. type = 'idtype_t'
  2574. class id_t_converter(CConverter):
  2575. type = 'id_t'
  2576. format_unit = '" _Py_PARSE_PID "'
  2577. class intptr_t_converter(CConverter):
  2578. type = 'intptr_t'
  2579. format_unit = '" _Py_PARSE_INTPTR "'
  2580. class Py_off_t_converter(CConverter):
  2581. type = 'Py_off_t'
  2582. converter = 'Py_off_t_converter'
  2583. class Py_off_t_return_converter(long_return_converter):
  2584. type = 'Py_off_t'
  2585. conversion_fn = 'PyLong_FromPy_off_t'
  2586. class path_confname_converter(CConverter):
  2587. type="int"
  2588. converter="conv_path_confname"
  2589. class confstr_confname_converter(path_confname_converter):
  2590. converter='conv_confstr_confname'
  2591. class sysconf_confname_converter(path_confname_converter):
  2592. converter="conv_sysconf_confname"
  2593. [python start generated code]*/
  2594. /*[python end generated code: output=da39a3ee5e6b4b0d input=3338733161aa7879]*/
  2595. /*[clinic input]
  2596. os.stat
  2597. path : path_t(allow_fd=True)
  2598. Path to be examined; can be string, bytes, a path-like object or
  2599. open-file-descriptor int.
  2600. *
  2601. dir_fd : dir_fd(requires='fstatat') = None
  2602. If not None, it should be a file descriptor open to a directory,
  2603. and path should be a relative string; path will then be relative to
  2604. that directory.
  2605. follow_symlinks: bool = True
  2606. If False, and the last element of the path is a symbolic link,
  2607. stat will examine the symbolic link itself instead of the file
  2608. the link points to.
  2609. Perform a stat system call on the given path.
  2610. dir_fd and follow_symlinks may not be implemented
  2611. on your platform. If they are unavailable, using them will raise a
  2612. NotImplementedError.
  2613. It's an error to use dir_fd or follow_symlinks when specifying path as
  2614. an open file descriptor.
  2615. [clinic start generated code]*/
  2616. static PyObject *
  2617. os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
  2618. /*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
  2619. {
  2620. return posix_do_stat(module, "stat", path, dir_fd, follow_symlinks);
  2621. }
  2622. /*[clinic input]
  2623. os.lstat
  2624. path : path_t
  2625. *
  2626. dir_fd : dir_fd(requires='fstatat') = None
  2627. Perform a stat system call on the given path, without following symbolic links.
  2628. Like stat(), but do not follow symbolic links.
  2629. Equivalent to stat(path, follow_symlinks=False).
  2630. [clinic start generated code]*/
  2631. static PyObject *
  2632. os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
  2633. /*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
  2634. {
  2635. int follow_symlinks = 0;
  2636. return posix_do_stat(module, "lstat", path, dir_fd, follow_symlinks);
  2637. }
  2638. /*[clinic input]
  2639. os.access -> bool
  2640. path: path_t
  2641. Path to be tested; can be string, bytes, or a path-like object.
  2642. mode: int
  2643. Operating-system mode bitfield. Can be F_OK to test existence,
  2644. or the inclusive-OR of R_OK, W_OK, and X_OK.
  2645. *
  2646. dir_fd : dir_fd(requires='faccessat') = None
  2647. If not None, it should be a file descriptor open to a directory,
  2648. and path should be relative; path will then be relative to that
  2649. directory.
  2650. effective_ids: bool = False
  2651. If True, access will use the effective uid/gid instead of
  2652. the real uid/gid.
  2653. follow_symlinks: bool = True
  2654. If False, and the last element of the path is a symbolic link,
  2655. access will examine the symbolic link itself instead of the file
  2656. the link points to.
  2657. Use the real uid/gid to test for access to a path.
  2658. {parameters}
  2659. dir_fd, effective_ids, and follow_symlinks may not be implemented
  2660. on your platform. If they are unavailable, using them will raise a
  2661. NotImplementedError.
  2662. Note that most operations will use the effective uid/gid, therefore this
  2663. routine can be used in a suid/sgid environment to test if the invoking user
  2664. has the specified access to the path.
  2665. [clinic start generated code]*/
  2666. static int
  2667. os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
  2668. int effective_ids, int follow_symlinks)
  2669. /*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
  2670. {
  2671. int return_value;
  2672. #ifdef MS_WINDOWS
  2673. DWORD attr;
  2674. #else
  2675. int result;
  2676. #endif
  2677. #ifdef HAVE_FACCESSAT
  2678. int faccessat_unavailable = 0;
  2679. #endif
  2680. #ifndef HAVE_FACCESSAT
  2681. if (follow_symlinks_specified("access", follow_symlinks))
  2682. return -1;
  2683. if (effective_ids) {
  2684. argument_unavailable_error("access", "effective_ids");
  2685. return -1;
  2686. }
  2687. #endif
  2688. #ifdef MS_WINDOWS
  2689. Py_BEGIN_ALLOW_THREADS
  2690. attr = GetFileAttributesW(path->wide);
  2691. Py_END_ALLOW_THREADS
  2692. /*
  2693. * Access is possible if
  2694. * * we didn't get a -1, and
  2695. * * write access wasn't requested,
  2696. * * or the file isn't read-only,
  2697. * * or it's a directory.
  2698. * (Directories cannot be read-only on Windows.)
  2699. */
  2700. return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
  2701. (!(mode & 2) ||
  2702. !(attr & FILE_ATTRIBUTE_READONLY) ||
  2703. (attr & FILE_ATTRIBUTE_DIRECTORY));
  2704. #else
  2705. Py_BEGIN_ALLOW_THREADS
  2706. #ifdef HAVE_FACCESSAT
  2707. if ((dir_fd != DEFAULT_DIR_FD) ||
  2708. effective_ids ||
  2709. !follow_symlinks) {
  2710. if (HAVE_FACCESSAT_RUNTIME) {
  2711. int flags = 0;
  2712. if (!follow_symlinks)
  2713. flags |= AT_SYMLINK_NOFOLLOW;
  2714. if (effective_ids)
  2715. flags |= AT_EACCESS;
  2716. result = faccessat(dir_fd, path->narrow, mode, flags);
  2717. } else {
  2718. faccessat_unavailable = 1;
  2719. }
  2720. }
  2721. else
  2722. #endif
  2723. result = access(path->narrow, mode);
  2724. Py_END_ALLOW_THREADS
  2725. #ifdef HAVE_FACCESSAT
  2726. if (faccessat_unavailable) {
  2727. if (dir_fd != DEFAULT_DIR_FD) {
  2728. argument_unavailable_error("access", "dir_fd");
  2729. return -1;
  2730. }
  2731. if (follow_symlinks_specified("access", follow_symlinks))
  2732. return -1;
  2733. if (effective_ids) {
  2734. argument_unavailable_error("access", "effective_ids");
  2735. return -1;
  2736. }
  2737. /* should be unreachable */
  2738. return -1;
  2739. }
  2740. #endif
  2741. return_value = !result;
  2742. #endif
  2743. return return_value;
  2744. }
  2745. #ifndef F_OK
  2746. #define F_OK 0
  2747. #endif
  2748. #ifndef R_OK
  2749. #define R_OK 4
  2750. #endif
  2751. #ifndef W_OK
  2752. #define W_OK 2
  2753. #endif
  2754. #ifndef X_OK
  2755. #define X_OK 1
  2756. #endif
  2757. #ifdef HAVE_TTYNAME
  2758. /*[clinic input]
  2759. os.ttyname
  2760. fd: int
  2761. Integer file descriptor handle.
  2762. /
  2763. Return the name of the terminal device connected to 'fd'.
  2764. [clinic start generated code]*/
  2765. static PyObject *
  2766. os_ttyname_impl(PyObject *module, int fd)
  2767. /*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
  2768. {
  2769. long size = sysconf(_SC_TTY_NAME_MAX);
  2770. if (size == -1) {
  2771. return posix_error();
  2772. }
  2773. char *buffer = (char *)PyMem_RawMalloc(size);
  2774. if (buffer == NULL) {
  2775. return PyErr_NoMemory();
  2776. }
  2777. int ret = ttyname_r(fd, buffer, size);
  2778. if (ret != 0) {
  2779. PyMem_RawFree(buffer);
  2780. errno = ret;
  2781. return posix_error();
  2782. }
  2783. PyObject *res = PyUnicode_DecodeFSDefault(buffer);
  2784. PyMem_RawFree(buffer);
  2785. return res;
  2786. }
  2787. #endif
  2788. #ifdef HAVE_CTERMID
  2789. /*[clinic input]
  2790. os.ctermid
  2791. Return the name of the controlling terminal for this process.
  2792. [clinic start generated code]*/
  2793. static PyObject *
  2794. os_ctermid_impl(PyObject *module)
  2795. /*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
  2796. {
  2797. char *ret;
  2798. char buffer[L_ctermid];
  2799. #ifdef USE_CTERMID_R
  2800. ret = ctermid_r(buffer);
  2801. #else
  2802. ret = ctermid(buffer);
  2803. #endif
  2804. if (ret == NULL)
  2805. return posix_error();
  2806. return PyUnicode_DecodeFSDefault(buffer);
  2807. }
  2808. #endif /* HAVE_CTERMID */
  2809. /*[clinic input]
  2810. os.chdir
  2811. path: path_t(allow_fd='PATH_HAVE_FCHDIR')
  2812. Change the current working directory to the specified path.
  2813. path may always be specified as a string.
  2814. On some platforms, path may also be specified as an open file descriptor.
  2815. If this functionality is unavailable, using it raises an exception.
  2816. [clinic start generated code]*/
  2817. static PyObject *
  2818. os_chdir_impl(PyObject *module, path_t *path)
  2819. /*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
  2820. {
  2821. int result;
  2822. if (PySys_Audit("os.chdir", "(O)", path->object) < 0) {
  2823. return NULL;
  2824. }
  2825. Py_BEGIN_ALLOW_THREADS
  2826. #ifdef MS_WINDOWS
  2827. /* on unix, success = 0, on windows, success = !0 */
  2828. result = !win32_wchdir(path->wide);
  2829. #else
  2830. #ifdef HAVE_FCHDIR
  2831. if (path->fd != -1)
  2832. result = fchdir(path->fd);
  2833. else
  2834. #endif
  2835. result = chdir(path->narrow);
  2836. #endif
  2837. Py_END_ALLOW_THREADS
  2838. if (result) {
  2839. return path_error(path);
  2840. }
  2841. Py_RETURN_NONE;
  2842. }
  2843. #ifdef HAVE_FCHDIR
  2844. /*[clinic input]
  2845. os.fchdir
  2846. fd: fildes
  2847. Change to the directory of the given file descriptor.
  2848. fd must be opened on a directory, not a file.
  2849. Equivalent to os.chdir(fd).
  2850. [clinic start generated code]*/
  2851. static PyObject *
  2852. os_fchdir_impl(PyObject *module, int fd)
  2853. /*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
  2854. {
  2855. if (PySys_Audit("os.chdir", "(i)", fd) < 0) {
  2856. return NULL;
  2857. }
  2858. return posix_fildes_fd(fd, fchdir);
  2859. }
  2860. #endif /* HAVE_FCHDIR */
  2861. /*[clinic input]
  2862. os.chmod
  2863. path: path_t(allow_fd='PATH_HAVE_FCHMOD')
  2864. Path to be modified. May always be specified as a str, bytes, or a path-like object.
  2865. On some platforms, path may also be specified as an open file descriptor.
  2866. If this functionality is unavailable, using it raises an exception.
  2867. mode: int
  2868. Operating-system mode bitfield.
  2869. Be careful when using number literals for *mode*. The conventional UNIX notation for
  2870. numeric modes uses an octal base, which needs to be indicated with a ``0o`` prefix in
  2871. Python.
  2872. *
  2873. dir_fd : dir_fd(requires='fchmodat') = None
  2874. If not None, it should be a file descriptor open to a directory,
  2875. and path should be relative; path will then be relative to that
  2876. directory.
  2877. follow_symlinks: bool = True
  2878. If False, and the last element of the path is a symbolic link,
  2879. chmod will modify the symbolic link itself instead of the file
  2880. the link points to.
  2881. Change the access permissions of a file.
  2882. It is an error to use dir_fd or follow_symlinks when specifying path as
  2883. an open file descriptor.
  2884. dir_fd and follow_symlinks may not be implemented on your platform.
  2885. If they are unavailable, using them will raise a NotImplementedError.
  2886. [clinic start generated code]*/
  2887. static PyObject *
  2888. os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
  2889. int follow_symlinks)
  2890. /*[clinic end generated code: output=5cf6a94915cc7bff input=674a14bc998de09d]*/
  2891. {
  2892. int result;
  2893. #ifdef MS_WINDOWS
  2894. DWORD attr;
  2895. #endif
  2896. #ifdef HAVE_FCHMODAT
  2897. int fchmodat_nofollow_unsupported = 0;
  2898. int fchmodat_unsupported = 0;
  2899. #endif
  2900. #if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
  2901. if (follow_symlinks_specified("chmod", follow_symlinks))
  2902. return NULL;
  2903. #endif
  2904. if (PySys_Audit("os.chmod", "Oii", path->object, mode,
  2905. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  2906. return NULL;
  2907. }
  2908. #ifdef MS_WINDOWS
  2909. Py_BEGIN_ALLOW_THREADS
  2910. attr = GetFileAttributesW(path->wide);
  2911. if (attr == INVALID_FILE_ATTRIBUTES)
  2912. result = 0;
  2913. else {
  2914. if (mode & _S_IWRITE)
  2915. attr &= ~FILE_ATTRIBUTE_READONLY;
  2916. else
  2917. attr |= FILE_ATTRIBUTE_READONLY;
  2918. result = SetFileAttributesW(path->wide, attr);
  2919. }
  2920. Py_END_ALLOW_THREADS
  2921. if (!result) {
  2922. return path_error(path);
  2923. }
  2924. #else /* MS_WINDOWS */
  2925. Py_BEGIN_ALLOW_THREADS
  2926. #ifdef HAVE_FCHMOD
  2927. if (path->fd != -1)
  2928. result = fchmod(path->fd, mode);
  2929. else
  2930. #endif /* HAVE_CHMOD */
  2931. #ifdef HAVE_LCHMOD
  2932. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  2933. result = lchmod(path->narrow, mode);
  2934. else
  2935. #endif /* HAVE_LCHMOD */
  2936. #ifdef HAVE_FCHMODAT
  2937. if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
  2938. if (HAVE_FCHMODAT_RUNTIME) {
  2939. /*
  2940. * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
  2941. * The documentation specifically shows how to use it,
  2942. * and then says it isn't implemented yet.
  2943. * (true on linux with glibc 2.15, and openindiana 3.x)
  2944. *
  2945. * Once it is supported, os.chmod will automatically
  2946. * support dir_fd and follow_symlinks=False. (Hopefully.)
  2947. * Until then, we need to be careful what exception we raise.
  2948. */
  2949. result = fchmodat(dir_fd, path->narrow, mode,
  2950. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  2951. /*
  2952. * But wait! We can't throw the exception without allowing threads,
  2953. * and we can't do that in this nested scope. (Macro trickery, sigh.)
  2954. */
  2955. fchmodat_nofollow_unsupported =
  2956. result &&
  2957. ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
  2958. !follow_symlinks;
  2959. } else {
  2960. fchmodat_unsupported = 1;
  2961. fchmodat_nofollow_unsupported = 1;
  2962. result = -1;
  2963. }
  2964. }
  2965. else
  2966. #endif /* HAVE_FHCMODAT */
  2967. {
  2968. #ifdef HAVE_CHMOD
  2969. result = chmod(path->narrow, mode);
  2970. #elif defined(__wasi__)
  2971. // WASI SDK 15.0 does not support chmod.
  2972. // Ignore missing syscall for now.
  2973. result = 0;
  2974. #else
  2975. result = -1;
  2976. errno = ENOSYS;
  2977. #endif
  2978. }
  2979. Py_END_ALLOW_THREADS
  2980. if (result) {
  2981. #ifdef HAVE_FCHMODAT
  2982. if (fchmodat_unsupported) {
  2983. if (dir_fd != DEFAULT_DIR_FD) {
  2984. argument_unavailable_error("chmod", "dir_fd");
  2985. return NULL;
  2986. }
  2987. }
  2988. if (fchmodat_nofollow_unsupported) {
  2989. if (dir_fd != DEFAULT_DIR_FD)
  2990. dir_fd_and_follow_symlinks_invalid("chmod",
  2991. dir_fd, follow_symlinks);
  2992. else
  2993. follow_symlinks_specified("chmod", follow_symlinks);
  2994. return NULL;
  2995. }
  2996. else
  2997. #endif /* HAVE_FCHMODAT */
  2998. return path_error(path);
  2999. }
  3000. #endif /* MS_WINDOWS */
  3001. Py_RETURN_NONE;
  3002. }
  3003. #ifdef HAVE_FCHMOD
  3004. /*[clinic input]
  3005. os.fchmod
  3006. fd: int
  3007. The file descriptor of the file to be modified.
  3008. mode: int
  3009. Operating-system mode bitfield.
  3010. Be careful when using number literals for *mode*. The conventional UNIX notation for
  3011. numeric modes uses an octal base, which needs to be indicated with a ``0o`` prefix in
  3012. Python.
  3013. Change the access permissions of the file given by file descriptor fd.
  3014. Equivalent to os.chmod(fd, mode).
  3015. [clinic start generated code]*/
  3016. static PyObject *
  3017. os_fchmod_impl(PyObject *module, int fd, int mode)
  3018. /*[clinic end generated code: output=afd9bc05b4e426b3 input=b5594618bbbc22df]*/
  3019. {
  3020. int res;
  3021. int async_err = 0;
  3022. if (PySys_Audit("os.chmod", "iii", fd, mode, -1) < 0) {
  3023. return NULL;
  3024. }
  3025. do {
  3026. Py_BEGIN_ALLOW_THREADS
  3027. res = fchmod(fd, mode);
  3028. Py_END_ALLOW_THREADS
  3029. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  3030. if (res != 0)
  3031. return (!async_err) ? posix_error() : NULL;
  3032. Py_RETURN_NONE;
  3033. }
  3034. #endif /* HAVE_FCHMOD */
  3035. #ifdef HAVE_LCHMOD
  3036. /*[clinic input]
  3037. os.lchmod
  3038. path: path_t
  3039. mode: int
  3040. Change the access permissions of a file, without following symbolic links.
  3041. If path is a symlink, this affects the link itself rather than the target.
  3042. Equivalent to chmod(path, mode, follow_symlinks=False)."
  3043. [clinic start generated code]*/
  3044. static PyObject *
  3045. os_lchmod_impl(PyObject *module, path_t *path, int mode)
  3046. /*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
  3047. {
  3048. int res;
  3049. if (PySys_Audit("os.chmod", "Oii", path->object, mode, -1) < 0) {
  3050. return NULL;
  3051. }
  3052. Py_BEGIN_ALLOW_THREADS
  3053. res = lchmod(path->narrow, mode);
  3054. Py_END_ALLOW_THREADS
  3055. if (res < 0) {
  3056. path_error(path);
  3057. return NULL;
  3058. }
  3059. Py_RETURN_NONE;
  3060. }
  3061. #endif /* HAVE_LCHMOD */
  3062. #ifdef HAVE_CHFLAGS
  3063. /*[clinic input]
  3064. os.chflags
  3065. path: path_t
  3066. flags: unsigned_long(bitwise=True)
  3067. follow_symlinks: bool=True
  3068. Set file flags.
  3069. If follow_symlinks is False, and the last element of the path is a symbolic
  3070. link, chflags will change flags on the symbolic link itself instead of the
  3071. file the link points to.
  3072. follow_symlinks may not be implemented on your platform. If it is
  3073. unavailable, using it will raise a NotImplementedError.
  3074. [clinic start generated code]*/
  3075. static PyObject *
  3076. os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
  3077. int follow_symlinks)
  3078. /*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
  3079. {
  3080. int result;
  3081. #ifndef HAVE_LCHFLAGS
  3082. if (follow_symlinks_specified("chflags", follow_symlinks))
  3083. return NULL;
  3084. #endif
  3085. if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
  3086. return NULL;
  3087. }
  3088. Py_BEGIN_ALLOW_THREADS
  3089. #ifdef HAVE_LCHFLAGS
  3090. if (!follow_symlinks)
  3091. result = lchflags(path->narrow, flags);
  3092. else
  3093. #endif
  3094. result = chflags(path->narrow, flags);
  3095. Py_END_ALLOW_THREADS
  3096. if (result)
  3097. return path_error(path);
  3098. Py_RETURN_NONE;
  3099. }
  3100. #endif /* HAVE_CHFLAGS */
  3101. #ifdef HAVE_LCHFLAGS
  3102. /*[clinic input]
  3103. os.lchflags
  3104. path: path_t
  3105. flags: unsigned_long(bitwise=True)
  3106. Set file flags.
  3107. This function will not follow symbolic links.
  3108. Equivalent to chflags(path, flags, follow_symlinks=False).
  3109. [clinic start generated code]*/
  3110. static PyObject *
  3111. os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
  3112. /*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
  3113. {
  3114. int res;
  3115. if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
  3116. return NULL;
  3117. }
  3118. Py_BEGIN_ALLOW_THREADS
  3119. res = lchflags(path->narrow, flags);
  3120. Py_END_ALLOW_THREADS
  3121. if (res < 0) {
  3122. return path_error(path);
  3123. }
  3124. Py_RETURN_NONE;
  3125. }
  3126. #endif /* HAVE_LCHFLAGS */
  3127. #ifdef HAVE_CHROOT
  3128. /*[clinic input]
  3129. os.chroot
  3130. path: path_t
  3131. Change root directory to path.
  3132. [clinic start generated code]*/
  3133. static PyObject *
  3134. os_chroot_impl(PyObject *module, path_t *path)
  3135. /*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
  3136. {
  3137. int res;
  3138. Py_BEGIN_ALLOW_THREADS
  3139. res = chroot(path->narrow);
  3140. Py_END_ALLOW_THREADS
  3141. if (res < 0)
  3142. return path_error(path);
  3143. Py_RETURN_NONE;
  3144. }
  3145. #endif /* HAVE_CHROOT */
  3146. #ifdef HAVE_FSYNC
  3147. /*[clinic input]
  3148. os.fsync
  3149. fd: fildes
  3150. Force write of fd to disk.
  3151. [clinic start generated code]*/
  3152. static PyObject *
  3153. os_fsync_impl(PyObject *module, int fd)
  3154. /*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
  3155. {
  3156. return posix_fildes_fd(fd, fsync);
  3157. }
  3158. #endif /* HAVE_FSYNC */
  3159. #ifdef HAVE_SYNC
  3160. /*[clinic input]
  3161. os.sync
  3162. Force write of everything to disk.
  3163. [clinic start generated code]*/
  3164. static PyObject *
  3165. os_sync_impl(PyObject *module)
  3166. /*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
  3167. {
  3168. Py_BEGIN_ALLOW_THREADS
  3169. sync();
  3170. Py_END_ALLOW_THREADS
  3171. Py_RETURN_NONE;
  3172. }
  3173. #endif /* HAVE_SYNC */
  3174. #ifdef HAVE_FDATASYNC
  3175. #ifdef __hpux
  3176. extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
  3177. #endif
  3178. /*[clinic input]
  3179. os.fdatasync
  3180. fd: fildes
  3181. Force write of fd to disk without forcing update of metadata.
  3182. [clinic start generated code]*/
  3183. static PyObject *
  3184. os_fdatasync_impl(PyObject *module, int fd)
  3185. /*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
  3186. {
  3187. return posix_fildes_fd(fd, fdatasync);
  3188. }
  3189. #endif /* HAVE_FDATASYNC */
  3190. #ifdef HAVE_CHOWN
  3191. /*[clinic input]
  3192. os.chown
  3193. path : path_t(allow_fd='PATH_HAVE_FCHOWN')
  3194. Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
  3195. uid: uid_t
  3196. gid: gid_t
  3197. *
  3198. dir_fd : dir_fd(requires='fchownat') = None
  3199. If not None, it should be a file descriptor open to a directory,
  3200. and path should be relative; path will then be relative to that
  3201. directory.
  3202. follow_symlinks: bool = True
  3203. If False, and the last element of the path is a symbolic link,
  3204. stat will examine the symbolic link itself instead of the file
  3205. the link points to.
  3206. Change the owner and group id of path to the numeric uid and gid.\
  3207. path may always be specified as a string.
  3208. On some platforms, path may also be specified as an open file descriptor.
  3209. If this functionality is unavailable, using it raises an exception.
  3210. If dir_fd is not None, it should be a file descriptor open to a directory,
  3211. and path should be relative; path will then be relative to that directory.
  3212. If follow_symlinks is False, and the last element of the path is a symbolic
  3213. link, chown will modify the symbolic link itself instead of the file the
  3214. link points to.
  3215. It is an error to use dir_fd or follow_symlinks when specifying path as
  3216. an open file descriptor.
  3217. dir_fd and follow_symlinks may not be implemented on your platform.
  3218. If they are unavailable, using them will raise a NotImplementedError.
  3219. [clinic start generated code]*/
  3220. static PyObject *
  3221. os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
  3222. int dir_fd, int follow_symlinks)
  3223. /*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
  3224. {
  3225. int result;
  3226. #if defined(HAVE_FCHOWNAT)
  3227. int fchownat_unsupported = 0;
  3228. #endif
  3229. #if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
  3230. if (follow_symlinks_specified("chown", follow_symlinks))
  3231. return NULL;
  3232. #endif
  3233. if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
  3234. fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
  3235. return NULL;
  3236. if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid,
  3237. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  3238. return NULL;
  3239. }
  3240. Py_BEGIN_ALLOW_THREADS
  3241. #ifdef HAVE_FCHOWN
  3242. if (path->fd != -1)
  3243. result = fchown(path->fd, uid, gid);
  3244. else
  3245. #endif
  3246. #ifdef HAVE_LCHOWN
  3247. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  3248. result = lchown(path->narrow, uid, gid);
  3249. else
  3250. #endif
  3251. #ifdef HAVE_FCHOWNAT
  3252. if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks)) {
  3253. if (HAVE_FCHOWNAT_RUNTIME) {
  3254. result = fchownat(dir_fd, path->narrow, uid, gid,
  3255. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  3256. } else {
  3257. fchownat_unsupported = 1;
  3258. }
  3259. } else
  3260. #endif
  3261. result = chown(path->narrow, uid, gid);
  3262. Py_END_ALLOW_THREADS
  3263. #ifdef HAVE_FCHOWNAT
  3264. if (fchownat_unsupported) {
  3265. /* This would be incorrect if the current platform
  3266. * doesn't support lchown.
  3267. */
  3268. argument_unavailable_error(NULL, "dir_fd");
  3269. return NULL;
  3270. }
  3271. #endif
  3272. if (result)
  3273. return path_error(path);
  3274. Py_RETURN_NONE;
  3275. }
  3276. #endif /* HAVE_CHOWN */
  3277. #ifdef HAVE_FCHOWN
  3278. /*[clinic input]
  3279. os.fchown
  3280. fd: int
  3281. uid: uid_t
  3282. gid: gid_t
  3283. Change the owner and group id of the file specified by file descriptor.
  3284. Equivalent to os.chown(fd, uid, gid).
  3285. [clinic start generated code]*/
  3286. static PyObject *
  3287. os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
  3288. /*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
  3289. {
  3290. int res;
  3291. int async_err = 0;
  3292. if (PySys_Audit("os.chown", "iIIi", fd, uid, gid, -1) < 0) {
  3293. return NULL;
  3294. }
  3295. do {
  3296. Py_BEGIN_ALLOW_THREADS
  3297. res = fchown(fd, uid, gid);
  3298. Py_END_ALLOW_THREADS
  3299. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  3300. if (res != 0)
  3301. return (!async_err) ? posix_error() : NULL;
  3302. Py_RETURN_NONE;
  3303. }
  3304. #endif /* HAVE_FCHOWN */
  3305. #ifdef HAVE_LCHOWN
  3306. /*[clinic input]
  3307. os.lchown
  3308. path : path_t
  3309. uid: uid_t
  3310. gid: gid_t
  3311. Change the owner and group id of path to the numeric uid and gid.
  3312. This function will not follow symbolic links.
  3313. Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
  3314. [clinic start generated code]*/
  3315. static PyObject *
  3316. os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
  3317. /*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
  3318. {
  3319. int res;
  3320. if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid, -1) < 0) {
  3321. return NULL;
  3322. }
  3323. Py_BEGIN_ALLOW_THREADS
  3324. res = lchown(path->narrow, uid, gid);
  3325. Py_END_ALLOW_THREADS
  3326. if (res < 0) {
  3327. return path_error(path);
  3328. }
  3329. Py_RETURN_NONE;
  3330. }
  3331. #endif /* HAVE_LCHOWN */
  3332. static PyObject *
  3333. posix_getcwd(int use_bytes)
  3334. {
  3335. #ifdef MS_WINDOWS
  3336. wchar_t wbuf[MAXPATHLEN];
  3337. wchar_t *wbuf2 = wbuf;
  3338. DWORD len;
  3339. Py_BEGIN_ALLOW_THREADS
  3340. len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
  3341. /* If the buffer is large enough, len does not include the
  3342. terminating \0. If the buffer is too small, len includes
  3343. the space needed for the terminator. */
  3344. if (len >= Py_ARRAY_LENGTH(wbuf)) {
  3345. if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  3346. wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
  3347. }
  3348. else {
  3349. wbuf2 = NULL;
  3350. }
  3351. if (wbuf2) {
  3352. len = GetCurrentDirectoryW(len, wbuf2);
  3353. }
  3354. }
  3355. Py_END_ALLOW_THREADS
  3356. if (!wbuf2) {
  3357. PyErr_NoMemory();
  3358. return NULL;
  3359. }
  3360. if (!len) {
  3361. PyErr_SetFromWindowsErr(0);
  3362. if (wbuf2 != wbuf)
  3363. PyMem_RawFree(wbuf2);
  3364. return NULL;
  3365. }
  3366. PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
  3367. if (wbuf2 != wbuf) {
  3368. PyMem_RawFree(wbuf2);
  3369. }
  3370. if (use_bytes) {
  3371. if (resobj == NULL) {
  3372. return NULL;
  3373. }
  3374. Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
  3375. }
  3376. return resobj;
  3377. #else
  3378. const size_t chunk = 1024;
  3379. char *buf = NULL;
  3380. char *cwd = NULL;
  3381. size_t buflen = 0;
  3382. Py_BEGIN_ALLOW_THREADS
  3383. do {
  3384. char *newbuf;
  3385. if (buflen <= PY_SSIZE_T_MAX - chunk) {
  3386. buflen += chunk;
  3387. newbuf = PyMem_RawRealloc(buf, buflen);
  3388. }
  3389. else {
  3390. newbuf = NULL;
  3391. }
  3392. if (newbuf == NULL) {
  3393. PyMem_RawFree(buf);
  3394. buf = NULL;
  3395. break;
  3396. }
  3397. buf = newbuf;
  3398. cwd = getcwd(buf, buflen);
  3399. } while (cwd == NULL && errno == ERANGE);
  3400. Py_END_ALLOW_THREADS
  3401. if (buf == NULL) {
  3402. return PyErr_NoMemory();
  3403. }
  3404. if (cwd == NULL) {
  3405. posix_error();
  3406. PyMem_RawFree(buf);
  3407. return NULL;
  3408. }
  3409. PyObject *obj;
  3410. if (use_bytes) {
  3411. obj = PyBytes_FromStringAndSize(buf, strlen(buf));
  3412. }
  3413. else {
  3414. obj = PyUnicode_DecodeFSDefault(buf);
  3415. }
  3416. PyMem_RawFree(buf);
  3417. return obj;
  3418. #endif /* !MS_WINDOWS */
  3419. }
  3420. /*[clinic input]
  3421. os.getcwd
  3422. Return a unicode string representing the current working directory.
  3423. [clinic start generated code]*/
  3424. static PyObject *
  3425. os_getcwd_impl(PyObject *module)
  3426. /*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
  3427. {
  3428. return posix_getcwd(0);
  3429. }
  3430. /*[clinic input]
  3431. os.getcwdb
  3432. Return a bytes string representing the current working directory.
  3433. [clinic start generated code]*/
  3434. static PyObject *
  3435. os_getcwdb_impl(PyObject *module)
  3436. /*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
  3437. {
  3438. return posix_getcwd(1);
  3439. }
  3440. #if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
  3441. #define HAVE_LINK 1
  3442. #endif
  3443. #ifdef HAVE_LINK
  3444. /*[clinic input]
  3445. os.link
  3446. src : path_t
  3447. dst : path_t
  3448. *
  3449. src_dir_fd : dir_fd = None
  3450. dst_dir_fd : dir_fd = None
  3451. follow_symlinks: bool = True
  3452. Create a hard link to a file.
  3453. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  3454. descriptor open to a directory, and the respective path string (src or dst)
  3455. should be relative; the path will then be relative to that directory.
  3456. If follow_symlinks is False, and the last element of src is a symbolic
  3457. link, link will create a link to the symbolic link itself instead of the
  3458. file the link points to.
  3459. src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
  3460. platform. If they are unavailable, using them will raise a
  3461. NotImplementedError.
  3462. [clinic start generated code]*/
  3463. static PyObject *
  3464. os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  3465. int dst_dir_fd, int follow_symlinks)
  3466. /*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
  3467. {
  3468. #ifdef MS_WINDOWS
  3469. BOOL result = FALSE;
  3470. #else
  3471. int result;
  3472. #endif
  3473. #if defined(HAVE_LINKAT)
  3474. int linkat_unavailable = 0;
  3475. #endif
  3476. #ifndef HAVE_LINKAT
  3477. if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
  3478. argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
  3479. return NULL;
  3480. }
  3481. #endif
  3482. #ifndef MS_WINDOWS
  3483. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  3484. PyErr_SetString(PyExc_NotImplementedError,
  3485. "link: src and dst must be the same type");
  3486. return NULL;
  3487. }
  3488. #endif
  3489. if (PySys_Audit("os.link", "OOii", src->object, dst->object,
  3490. src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
  3491. dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
  3492. return NULL;
  3493. }
  3494. #ifdef MS_WINDOWS
  3495. Py_BEGIN_ALLOW_THREADS
  3496. result = CreateHardLinkW(dst->wide, src->wide, NULL);
  3497. Py_END_ALLOW_THREADS
  3498. if (!result)
  3499. return path_error2(src, dst);
  3500. #else
  3501. Py_BEGIN_ALLOW_THREADS
  3502. #ifdef HAVE_LINKAT
  3503. if ((src_dir_fd != DEFAULT_DIR_FD) ||
  3504. (dst_dir_fd != DEFAULT_DIR_FD) ||
  3505. (!follow_symlinks)) {
  3506. if (HAVE_LINKAT_RUNTIME) {
  3507. result = linkat(src_dir_fd, src->narrow,
  3508. dst_dir_fd, dst->narrow,
  3509. follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
  3510. }
  3511. #ifdef __APPLE__
  3512. else {
  3513. if (src_dir_fd == DEFAULT_DIR_FD && dst_dir_fd == DEFAULT_DIR_FD) {
  3514. /* See issue 41355: This matches the behaviour of !HAVE_LINKAT */
  3515. result = link(src->narrow, dst->narrow);
  3516. } else {
  3517. linkat_unavailable = 1;
  3518. }
  3519. }
  3520. #endif
  3521. }
  3522. else
  3523. #endif /* HAVE_LINKAT */
  3524. result = link(src->narrow, dst->narrow);
  3525. Py_END_ALLOW_THREADS
  3526. #ifdef HAVE_LINKAT
  3527. if (linkat_unavailable) {
  3528. /* Either or both dir_fd arguments were specified */
  3529. if (src_dir_fd != DEFAULT_DIR_FD) {
  3530. argument_unavailable_error("link", "src_dir_fd");
  3531. } else {
  3532. argument_unavailable_error("link", "dst_dir_fd");
  3533. }
  3534. return NULL;
  3535. }
  3536. #endif
  3537. if (result)
  3538. return path_error2(src, dst);
  3539. #endif /* MS_WINDOWS */
  3540. Py_RETURN_NONE;
  3541. }
  3542. #endif
  3543. #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
  3544. static PyObject *
  3545. _listdir_windows_no_opendir(path_t *path, PyObject *list)
  3546. {
  3547. PyObject *v;
  3548. HANDLE hFindFile = INVALID_HANDLE_VALUE;
  3549. BOOL result;
  3550. wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
  3551. /* only claim to have space for MAX_PATH */
  3552. Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
  3553. wchar_t *wnamebuf = NULL;
  3554. WIN32_FIND_DATAW wFileData;
  3555. const wchar_t *po_wchars;
  3556. if (!path->wide) { /* Default arg: "." */
  3557. po_wchars = L".";
  3558. len = 1;
  3559. } else {
  3560. po_wchars = path->wide;
  3561. len = wcslen(path->wide);
  3562. }
  3563. /* The +5 is so we can append "\\*.*\0" */
  3564. wnamebuf = PyMem_New(wchar_t, len + 5);
  3565. if (!wnamebuf) {
  3566. PyErr_NoMemory();
  3567. goto exit;
  3568. }
  3569. wcscpy(wnamebuf, po_wchars);
  3570. if (len > 0) {
  3571. wchar_t wch = wnamebuf[len-1];
  3572. if (wch != SEP && wch != ALTSEP && wch != L':')
  3573. wnamebuf[len++] = SEP;
  3574. wcscpy(wnamebuf + len, L"*.*");
  3575. }
  3576. if ((list = PyList_New(0)) == NULL) {
  3577. goto exit;
  3578. }
  3579. Py_BEGIN_ALLOW_THREADS
  3580. hFindFile = FindFirstFileW(wnamebuf, &wFileData);
  3581. Py_END_ALLOW_THREADS
  3582. if (hFindFile == INVALID_HANDLE_VALUE) {
  3583. int error = GetLastError();
  3584. if (error == ERROR_FILE_NOT_FOUND)
  3585. goto exit;
  3586. path_error(path);
  3587. Py_CLEAR(list);
  3588. goto exit;
  3589. }
  3590. do {
  3591. /* Skip over . and .. */
  3592. if (wcscmp(wFileData.cFileName, L".") != 0 &&
  3593. wcscmp(wFileData.cFileName, L"..") != 0) {
  3594. v = PyUnicode_FromWideChar(wFileData.cFileName,
  3595. wcslen(wFileData.cFileName));
  3596. if (path->narrow && v) {
  3597. Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
  3598. }
  3599. if (v == NULL) {
  3600. Py_CLEAR(list);
  3601. break;
  3602. }
  3603. if (PyList_Append(list, v) != 0) {
  3604. Py_DECREF(v);
  3605. Py_CLEAR(list);
  3606. break;
  3607. }
  3608. Py_DECREF(v);
  3609. }
  3610. Py_BEGIN_ALLOW_THREADS
  3611. result = FindNextFileW(hFindFile, &wFileData);
  3612. Py_END_ALLOW_THREADS
  3613. /* FindNextFile sets error to ERROR_NO_MORE_FILES if
  3614. it got to the end of the directory. */
  3615. if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
  3616. path_error(path);
  3617. Py_CLEAR(list);
  3618. goto exit;
  3619. }
  3620. } while (result == TRUE);
  3621. exit:
  3622. if (hFindFile != INVALID_HANDLE_VALUE) {
  3623. if (FindClose(hFindFile) == FALSE) {
  3624. if (list != NULL) {
  3625. path_error(path);
  3626. Py_CLEAR(list);
  3627. }
  3628. }
  3629. }
  3630. PyMem_Free(wnamebuf);
  3631. return list;
  3632. } /* end of _listdir_windows_no_opendir */
  3633. #else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
  3634. static PyObject *
  3635. _posix_listdir(path_t *path, PyObject *list)
  3636. {
  3637. PyObject *v;
  3638. DIR *dirp = NULL;
  3639. struct dirent *ep;
  3640. int return_str; /* if false, return bytes */
  3641. #ifdef HAVE_FDOPENDIR
  3642. int fd = -1;
  3643. #endif
  3644. errno = 0;
  3645. #ifdef HAVE_FDOPENDIR
  3646. if (path->fd != -1) {
  3647. if (HAVE_FDOPENDIR_RUNTIME) {
  3648. /* closedir() closes the FD, so we duplicate it */
  3649. fd = _Py_dup(path->fd);
  3650. if (fd == -1)
  3651. return NULL;
  3652. return_str = 1;
  3653. Py_BEGIN_ALLOW_THREADS
  3654. dirp = fdopendir(fd);
  3655. Py_END_ALLOW_THREADS
  3656. } else {
  3657. PyErr_SetString(PyExc_TypeError,
  3658. "listdir: path should be string, bytes, os.PathLike or None, not int");
  3659. return NULL;
  3660. }
  3661. }
  3662. else
  3663. #endif
  3664. {
  3665. const char *name;
  3666. if (path->narrow) {
  3667. name = path->narrow;
  3668. /* only return bytes if they specified a bytes object */
  3669. return_str = !PyBytes_Check(path->object);
  3670. }
  3671. else {
  3672. name = ".";
  3673. return_str = 1;
  3674. }
  3675. Py_BEGIN_ALLOW_THREADS
  3676. dirp = opendir(name);
  3677. Py_END_ALLOW_THREADS
  3678. }
  3679. if (dirp == NULL) {
  3680. path_error(path);
  3681. list = NULL;
  3682. #ifdef HAVE_FDOPENDIR
  3683. if (fd != -1) {
  3684. Py_BEGIN_ALLOW_THREADS
  3685. close(fd);
  3686. Py_END_ALLOW_THREADS
  3687. }
  3688. #endif
  3689. goto exit;
  3690. }
  3691. if ((list = PyList_New(0)) == NULL) {
  3692. goto exit;
  3693. }
  3694. for (;;) {
  3695. errno = 0;
  3696. Py_BEGIN_ALLOW_THREADS
  3697. ep = readdir(dirp);
  3698. Py_END_ALLOW_THREADS
  3699. if (ep == NULL) {
  3700. if (errno == 0) {
  3701. break;
  3702. } else {
  3703. path_error(path);
  3704. Py_CLEAR(list);
  3705. goto exit;
  3706. }
  3707. }
  3708. if (ep->d_name[0] == '.' &&
  3709. (NAMLEN(ep) == 1 ||
  3710. (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
  3711. continue;
  3712. if (return_str)
  3713. v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
  3714. else
  3715. v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
  3716. if (v == NULL) {
  3717. Py_CLEAR(list);
  3718. break;
  3719. }
  3720. if (PyList_Append(list, v) != 0) {
  3721. Py_DECREF(v);
  3722. Py_CLEAR(list);
  3723. break;
  3724. }
  3725. Py_DECREF(v);
  3726. }
  3727. exit:
  3728. if (dirp != NULL) {
  3729. Py_BEGIN_ALLOW_THREADS
  3730. #ifdef HAVE_FDOPENDIR
  3731. if (fd > -1)
  3732. rewinddir(dirp);
  3733. #endif
  3734. closedir(dirp);
  3735. Py_END_ALLOW_THREADS
  3736. }
  3737. return list;
  3738. } /* end of _posix_listdir */
  3739. #endif /* which OS */
  3740. /*[clinic input]
  3741. os.listdir
  3742. path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
  3743. Return a list containing the names of the files in the directory.
  3744. path can be specified as either str, bytes, or a path-like object. If path is bytes,
  3745. the filenames returned will also be bytes; in all other circumstances
  3746. the filenames returned will be str.
  3747. If path is None, uses the path='.'.
  3748. On some platforms, path may also be specified as an open file descriptor;\
  3749. the file descriptor must refer to a directory.
  3750. If this functionality is unavailable, using it raises NotImplementedError.
  3751. The list is in arbitrary order. It does not include the special
  3752. entries '.' and '..' even if they are present in the directory.
  3753. [clinic start generated code]*/
  3754. static PyObject *
  3755. os_listdir_impl(PyObject *module, path_t *path)
  3756. /*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
  3757. {
  3758. if (PySys_Audit("os.listdir", "O",
  3759. path->object ? path->object : Py_None) < 0) {
  3760. return NULL;
  3761. }
  3762. #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
  3763. return _listdir_windows_no_opendir(path, NULL);
  3764. #else
  3765. return _posix_listdir(path, NULL);
  3766. #endif
  3767. }
  3768. #ifdef MS_WINDOWS
  3769. /*[clinic input]
  3770. os.listdrives
  3771. Return a list containing the names of drives in the system.
  3772. A drive name typically looks like 'C:\\'.
  3773. [clinic start generated code]*/
  3774. static PyObject *
  3775. os_listdrives_impl(PyObject *module)
  3776. /*[clinic end generated code: output=aaece9dacdf682b5 input=1af9ccc9e583798e]*/
  3777. {
  3778. /* Number of possible drives is limited, so 256 should always be enough.
  3779. On the day when it is not, listmounts() will have to be used. */
  3780. wchar_t buffer[256];
  3781. DWORD buflen = Py_ARRAY_LENGTH(buffer);
  3782. PyObject *result = NULL;
  3783. if (PySys_Audit("os.listdrives", NULL) < 0) {
  3784. return NULL;
  3785. }
  3786. Py_BEGIN_ALLOW_THREADS;
  3787. buflen = GetLogicalDriveStringsW(buflen, buffer);
  3788. Py_END_ALLOW_THREADS;
  3789. if (!buflen) {
  3790. PyErr_SetFromWindowsErr(0);
  3791. return NULL;
  3792. } else if (buflen >= Py_ARRAY_LENGTH(buffer)) {
  3793. PyErr_SetFromWindowsErr(ERROR_MORE_DATA);
  3794. return NULL;
  3795. }
  3796. /* buflen includes a null terminator, so remove it */
  3797. PyObject *str = PyUnicode_FromWideChar(buffer, buflen - 1);
  3798. if (str) {
  3799. PyObject *nullchar = PyUnicode_FromStringAndSize("\0", 1);
  3800. if (nullchar) {
  3801. result = PyUnicode_Split(str, nullchar, -1);
  3802. Py_DECREF(nullchar);
  3803. }
  3804. Py_DECREF(str);
  3805. }
  3806. return result;
  3807. }
  3808. /*[clinic input]
  3809. os.listvolumes
  3810. Return a list containing the volumes in the system.
  3811. Volumes are typically represented as a GUID path.
  3812. [clinic start generated code]*/
  3813. static PyObject *
  3814. os_listvolumes_impl(PyObject *module)
  3815. /*[clinic end generated code: output=534e10ea2bf9d386 input=f6e4e70371f11e99]*/
  3816. {
  3817. PyObject *result = PyList_New(0);
  3818. HANDLE find = INVALID_HANDLE_VALUE;
  3819. wchar_t buffer[MAX_PATH + 1];
  3820. if (!result) {
  3821. return NULL;
  3822. }
  3823. if (PySys_Audit("os.listvolumes", NULL) < 0) {
  3824. Py_DECREF(result);
  3825. return NULL;
  3826. }
  3827. int err = 0;
  3828. Py_BEGIN_ALLOW_THREADS;
  3829. find = FindFirstVolumeW(buffer, Py_ARRAY_LENGTH(buffer));
  3830. if (find == INVALID_HANDLE_VALUE) {
  3831. err = GetLastError();
  3832. }
  3833. Py_END_ALLOW_THREADS;
  3834. while (!err) {
  3835. PyObject *s = PyUnicode_FromWideChar(buffer, -1);
  3836. if (!s || PyList_Append(result, s) < 0) {
  3837. Py_XDECREF(s);
  3838. Py_CLEAR(result);
  3839. break;
  3840. }
  3841. Py_DECREF(s);
  3842. Py_BEGIN_ALLOW_THREADS;
  3843. if (!FindNextVolumeW(find, buffer, Py_ARRAY_LENGTH(buffer))) {
  3844. err = GetLastError();
  3845. }
  3846. Py_END_ALLOW_THREADS;
  3847. }
  3848. if (find != INVALID_HANDLE_VALUE) {
  3849. Py_BEGIN_ALLOW_THREADS;
  3850. FindVolumeClose(find);
  3851. Py_END_ALLOW_THREADS;
  3852. }
  3853. if (err && err != ERROR_NO_MORE_FILES) {
  3854. PyErr_SetFromWindowsErr(err);
  3855. Py_XDECREF(result);
  3856. result = NULL;
  3857. }
  3858. return result;
  3859. }
  3860. /*[clinic input]
  3861. os.listmounts
  3862. volume: path_t
  3863. Return a list containing mount points for a particular volume.
  3864. 'volume' should be a GUID path as returned from os.listvolumes.
  3865. [clinic start generated code]*/
  3866. static PyObject *
  3867. os_listmounts_impl(PyObject *module, path_t *volume)
  3868. /*[clinic end generated code: output=06da49679de4512e input=a8a27178e3f67845]*/
  3869. {
  3870. wchar_t default_buffer[MAX_PATH + 1];
  3871. DWORD buflen = Py_ARRAY_LENGTH(default_buffer);
  3872. LPWSTR buffer = default_buffer;
  3873. DWORD attributes;
  3874. PyObject *str = NULL;
  3875. PyObject *nullchar = NULL;
  3876. PyObject *result = NULL;
  3877. /* Ensure we have a valid volume path before continuing */
  3878. Py_BEGIN_ALLOW_THREADS
  3879. attributes = GetFileAttributesW(volume->wide);
  3880. Py_END_ALLOW_THREADS
  3881. if (attributes == INVALID_FILE_ATTRIBUTES &&
  3882. GetLastError() == ERROR_UNRECOGNIZED_VOLUME)
  3883. {
  3884. return PyErr_SetFromWindowsErr(ERROR_UNRECOGNIZED_VOLUME);
  3885. }
  3886. if (PySys_Audit("os.listmounts", "O", volume->object) < 0) {
  3887. return NULL;
  3888. }
  3889. while (1) {
  3890. BOOL success;
  3891. Py_BEGIN_ALLOW_THREADS
  3892. success = GetVolumePathNamesForVolumeNameW(volume->wide, buffer,
  3893. buflen, &buflen);
  3894. Py_END_ALLOW_THREADS
  3895. if (success) {
  3896. break;
  3897. }
  3898. if (GetLastError() != ERROR_MORE_DATA) {
  3899. PyErr_SetFromWindowsErr(0);
  3900. goto exit;
  3901. }
  3902. if (buffer != default_buffer) {
  3903. PyMem_Free((void *)buffer);
  3904. }
  3905. buffer = (wchar_t*)PyMem_Malloc(sizeof(wchar_t) * buflen);
  3906. if (!buffer) {
  3907. PyErr_NoMemory();
  3908. goto exit;
  3909. }
  3910. }
  3911. if (buflen < 2) {
  3912. result = PyList_New(0);
  3913. goto exit;
  3914. }
  3915. // buflen includes two null terminators, one for the last string
  3916. // and one for the array of strings.
  3917. str = PyUnicode_FromWideChar(buffer, buflen - 2);
  3918. nullchar = PyUnicode_FromStringAndSize("\0", 1);
  3919. if (str && nullchar) {
  3920. result = PyUnicode_Split(str, nullchar, -1);
  3921. }
  3922. exit:
  3923. if (buffer != default_buffer) {
  3924. PyMem_Free(buffer);
  3925. }
  3926. Py_XDECREF(nullchar);
  3927. Py_XDECREF(str);
  3928. return result;
  3929. }
  3930. /*[clinic input]
  3931. os._path_isdevdrive
  3932. path: path_t
  3933. Determines whether the specified path is on a Windows Dev Drive.
  3934. [clinic start generated code]*/
  3935. static PyObject *
  3936. os__path_isdevdrive_impl(PyObject *module, path_t *path)
  3937. /*[clinic end generated code: output=1f437ea6677433a2 input=ee83e4996a48e23d]*/
  3938. {
  3939. #ifndef PERSISTENT_VOLUME_STATE_DEV_VOLUME
  3940. /* This flag will be documented at
  3941. https://learn.microsoft.com/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_fs_persistent_volume_information
  3942. after release, and will be available in the latest WinSDK.
  3943. We include the flag to avoid a specific version dependency
  3944. on the latest WinSDK. */
  3945. const int PERSISTENT_VOLUME_STATE_DEV_VOLUME = 0x00002000;
  3946. #endif
  3947. int err = 0;
  3948. PyObject *r = NULL;
  3949. wchar_t volume[MAX_PATH];
  3950. Py_BEGIN_ALLOW_THREADS
  3951. if (!GetVolumePathNameW(path->wide, volume, MAX_PATH)) {
  3952. /* invalid path of some kind */
  3953. /* Note that this also includes the case where a volume is mounted
  3954. in a path longer than 260 characters. This is likely to be rare
  3955. and problematic for other reasons, so a (soft) failure in this
  3956. check seems okay. */
  3957. err = GetLastError();
  3958. } else if (GetDriveTypeW(volume) != DRIVE_FIXED) {
  3959. /* only care about local dev drives */
  3960. r = Py_False;
  3961. } else {
  3962. HANDLE hVolume = CreateFileW(
  3963. volume,
  3964. FILE_READ_ATTRIBUTES,
  3965. FILE_SHARE_READ | FILE_SHARE_WRITE,
  3966. NULL,
  3967. OPEN_EXISTING,
  3968. FILE_FLAG_BACKUP_SEMANTICS,
  3969. NULL
  3970. );
  3971. if (hVolume == INVALID_HANDLE_VALUE) {
  3972. err = GetLastError();
  3973. } else {
  3974. FILE_FS_PERSISTENT_VOLUME_INFORMATION volumeState = {0};
  3975. volumeState.Version = 1;
  3976. volumeState.FlagMask = PERSISTENT_VOLUME_STATE_DEV_VOLUME;
  3977. if (!DeviceIoControl(
  3978. hVolume,
  3979. FSCTL_QUERY_PERSISTENT_VOLUME_STATE,
  3980. &volumeState,
  3981. sizeof(volumeState),
  3982. &volumeState,
  3983. sizeof(volumeState),
  3984. NULL,
  3985. NULL
  3986. )) {
  3987. err = GetLastError();
  3988. }
  3989. CloseHandle(hVolume);
  3990. if (err == ERROR_INVALID_PARAMETER) {
  3991. /* not supported on this platform */
  3992. r = Py_False;
  3993. } else if (!err) {
  3994. r = (volumeState.VolumeFlags & PERSISTENT_VOLUME_STATE_DEV_VOLUME)
  3995. ? Py_True : Py_False;
  3996. }
  3997. }
  3998. }
  3999. Py_END_ALLOW_THREADS
  4000. if (err) {
  4001. PyErr_SetFromWindowsErr(err);
  4002. return NULL;
  4003. }
  4004. if (r) {
  4005. return Py_NewRef(r);
  4006. }
  4007. return NULL;
  4008. }
  4009. int
  4010. _PyOS_getfullpathname(const wchar_t *path, wchar_t **abspath_p)
  4011. {
  4012. wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
  4013. DWORD result;
  4014. result = GetFullPathNameW(path,
  4015. Py_ARRAY_LENGTH(woutbuf), woutbuf,
  4016. NULL);
  4017. if (!result) {
  4018. return -1;
  4019. }
  4020. if (result >= Py_ARRAY_LENGTH(woutbuf)) {
  4021. if ((size_t)result <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  4022. woutbufp = PyMem_RawMalloc((size_t)result * sizeof(wchar_t));
  4023. }
  4024. else {
  4025. woutbufp = NULL;
  4026. }
  4027. if (!woutbufp) {
  4028. *abspath_p = NULL;
  4029. return 0;
  4030. }
  4031. result = GetFullPathNameW(path, result, woutbufp, NULL);
  4032. if (!result) {
  4033. PyMem_RawFree(woutbufp);
  4034. return -1;
  4035. }
  4036. }
  4037. if (woutbufp != woutbuf) {
  4038. *abspath_p = woutbufp;
  4039. return 0;
  4040. }
  4041. *abspath_p = _PyMem_RawWcsdup(woutbufp);
  4042. return 0;
  4043. }
  4044. /* A helper function for abspath on win32 */
  4045. /*[clinic input]
  4046. os._getfullpathname
  4047. path: path_t
  4048. /
  4049. [clinic start generated code]*/
  4050. static PyObject *
  4051. os__getfullpathname_impl(PyObject *module, path_t *path)
  4052. /*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
  4053. {
  4054. wchar_t *abspath;
  4055. if (_PyOS_getfullpathname(path->wide, &abspath) < 0) {
  4056. return win32_error_object("GetFullPathNameW", path->object);
  4057. }
  4058. if (abspath == NULL) {
  4059. return PyErr_NoMemory();
  4060. }
  4061. PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
  4062. PyMem_RawFree(abspath);
  4063. if (str == NULL) {
  4064. return NULL;
  4065. }
  4066. if (path->narrow) {
  4067. Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
  4068. }
  4069. return str;
  4070. }
  4071. /*[clinic input]
  4072. os._getfinalpathname
  4073. path: path_t
  4074. /
  4075. A helper function for samepath on windows.
  4076. [clinic start generated code]*/
  4077. static PyObject *
  4078. os__getfinalpathname_impl(PyObject *module, path_t *path)
  4079. /*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
  4080. {
  4081. HANDLE hFile;
  4082. wchar_t buf[MAXPATHLEN], *target_path = buf;
  4083. int buf_size = Py_ARRAY_LENGTH(buf);
  4084. int result_length;
  4085. PyObject *result;
  4086. Py_BEGIN_ALLOW_THREADS
  4087. hFile = CreateFileW(
  4088. path->wide,
  4089. 0, /* desired access */
  4090. 0, /* share mode */
  4091. NULL, /* security attributes */
  4092. OPEN_EXISTING,
  4093. /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
  4094. FILE_FLAG_BACKUP_SEMANTICS,
  4095. NULL);
  4096. Py_END_ALLOW_THREADS
  4097. if (hFile == INVALID_HANDLE_VALUE) {
  4098. return win32_error_object("CreateFileW", path->object);
  4099. }
  4100. /* We have a good handle to the target, use it to determine the
  4101. target path name. */
  4102. while (1) {
  4103. Py_BEGIN_ALLOW_THREADS
  4104. result_length = GetFinalPathNameByHandleW(hFile, target_path,
  4105. buf_size, VOLUME_NAME_DOS);
  4106. Py_END_ALLOW_THREADS
  4107. if (!result_length) {
  4108. result = win32_error_object("GetFinalPathNameByHandleW",
  4109. path->object);
  4110. goto cleanup;
  4111. }
  4112. if (result_length < buf_size) {
  4113. break;
  4114. }
  4115. wchar_t *tmp;
  4116. tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
  4117. result_length * sizeof(*tmp));
  4118. if (!tmp) {
  4119. result = PyErr_NoMemory();
  4120. goto cleanup;
  4121. }
  4122. buf_size = result_length;
  4123. target_path = tmp;
  4124. }
  4125. result = PyUnicode_FromWideChar(target_path, result_length);
  4126. if (result && path->narrow) {
  4127. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  4128. }
  4129. cleanup:
  4130. if (target_path != buf) {
  4131. PyMem_Free(target_path);
  4132. }
  4133. CloseHandle(hFile);
  4134. return result;
  4135. }
  4136. /*[clinic input]
  4137. os._getvolumepathname
  4138. path: path_t
  4139. A helper function for ismount on Win32.
  4140. [clinic start generated code]*/
  4141. static PyObject *
  4142. os__getvolumepathname_impl(PyObject *module, path_t *path)
  4143. /*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
  4144. {
  4145. PyObject *result;
  4146. wchar_t *mountpath=NULL;
  4147. size_t buflen;
  4148. BOOL ret;
  4149. /* Volume path should be shorter than entire path */
  4150. buflen = Py_MAX(path->length, MAX_PATH);
  4151. if (buflen > PY_DWORD_MAX) {
  4152. PyErr_SetString(PyExc_OverflowError, "path too long");
  4153. return NULL;
  4154. }
  4155. mountpath = PyMem_New(wchar_t, buflen);
  4156. if (mountpath == NULL)
  4157. return PyErr_NoMemory();
  4158. Py_BEGIN_ALLOW_THREADS
  4159. ret = GetVolumePathNameW(path->wide, mountpath,
  4160. Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
  4161. Py_END_ALLOW_THREADS
  4162. if (!ret) {
  4163. result = win32_error_object("_getvolumepathname", path->object);
  4164. goto exit;
  4165. }
  4166. result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
  4167. if (path->narrow)
  4168. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  4169. exit:
  4170. PyMem_Free(mountpath);
  4171. return result;
  4172. }
  4173. /*[clinic input]
  4174. os._path_splitroot
  4175. path: path_t
  4176. Removes everything after the root on Win32.
  4177. [clinic start generated code]*/
  4178. static PyObject *
  4179. os__path_splitroot_impl(PyObject *module, path_t *path)
  4180. /*[clinic end generated code: output=ab7f1a88b654581c input=dc93b1d3984cffb6]*/
  4181. {
  4182. wchar_t *buffer;
  4183. wchar_t *end;
  4184. PyObject *result = NULL;
  4185. HRESULT ret;
  4186. buffer = (wchar_t*)PyMem_Malloc(sizeof(wchar_t) * (wcslen(path->wide) + 1));
  4187. if (!buffer) {
  4188. return NULL;
  4189. }
  4190. wcscpy(buffer, path->wide);
  4191. for (wchar_t *p = wcschr(buffer, L'/'); p; p = wcschr(p, L'/')) {
  4192. *p = L'\\';
  4193. }
  4194. Py_BEGIN_ALLOW_THREADS
  4195. ret = PathCchSkipRoot(buffer, &end);
  4196. Py_END_ALLOW_THREADS
  4197. if (FAILED(ret)) {
  4198. result = Py_BuildValue("sO", "", path->object);
  4199. } else if (end != buffer) {
  4200. size_t rootLen = (size_t)(end - buffer);
  4201. result = Py_BuildValue("NN",
  4202. PyUnicode_FromWideChar(path->wide, rootLen),
  4203. PyUnicode_FromWideChar(path->wide + rootLen, -1)
  4204. );
  4205. } else {
  4206. result = Py_BuildValue("Os", path->object, "");
  4207. }
  4208. PyMem_Free(buffer);
  4209. return result;
  4210. }
  4211. /*[clinic input]
  4212. os._path_isdir
  4213. s: 'O'
  4214. Return true if the pathname refers to an existing directory.
  4215. [clinic start generated code]*/
  4216. static PyObject *
  4217. os__path_isdir_impl(PyObject *module, PyObject *s)
  4218. /*[clinic end generated code: output=9d87ab3c8b8a4e61 input=c17f7ef21d22d64e]*/
  4219. {
  4220. HANDLE hfile;
  4221. BOOL close_file = TRUE;
  4222. FILE_BASIC_INFO info;
  4223. path_t _path = PATH_T_INITIALIZE("isdir", "s", 0, 1);
  4224. int result;
  4225. BOOL slow_path = TRUE;
  4226. FILE_STAT_BASIC_INFORMATION statInfo;
  4227. if (!path_converter(s, &_path)) {
  4228. path_cleanup(&_path);
  4229. if (PyErr_ExceptionMatches(PyExc_ValueError)) {
  4230. PyErr_Clear();
  4231. Py_RETURN_FALSE;
  4232. }
  4233. return NULL;
  4234. }
  4235. Py_BEGIN_ALLOW_THREADS
  4236. if (_path.wide) {
  4237. if (_Py_GetFileInformationByName(_path.wide, FileStatBasicByNameInfo,
  4238. &statInfo, sizeof(statInfo))) {
  4239. if (!(statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
  4240. slow_path = FALSE;
  4241. result = statInfo.FileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4242. } else if (!(statInfo.FileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
  4243. slow_path = FALSE;
  4244. result = 0;
  4245. }
  4246. } else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(GetLastError())) {
  4247. slow_path = FALSE;
  4248. result = 0;
  4249. }
  4250. }
  4251. if (slow_path) {
  4252. if (_path.fd != -1) {
  4253. hfile = _Py_get_osfhandle_noraise(_path.fd);
  4254. close_file = FALSE;
  4255. }
  4256. else {
  4257. hfile = CreateFileW(_path.wide, FILE_READ_ATTRIBUTES, 0, NULL,
  4258. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  4259. }
  4260. if (hfile != INVALID_HANDLE_VALUE) {
  4261. if (GetFileInformationByHandleEx(hfile, FileBasicInfo, &info,
  4262. sizeof(info)))
  4263. {
  4264. result = info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4265. }
  4266. else {
  4267. result = 0;
  4268. }
  4269. if (close_file) {
  4270. CloseHandle(hfile);
  4271. }
  4272. }
  4273. else {
  4274. STRUCT_STAT st;
  4275. switch (GetLastError()) {
  4276. case ERROR_ACCESS_DENIED:
  4277. case ERROR_SHARING_VIOLATION:
  4278. case ERROR_CANT_ACCESS_FILE:
  4279. case ERROR_INVALID_PARAMETER:
  4280. if (STAT(_path.wide, &st)) {
  4281. result = 0;
  4282. }
  4283. else {
  4284. result = S_ISDIR(st.st_mode);
  4285. }
  4286. break;
  4287. default:
  4288. result = 0;
  4289. }
  4290. }
  4291. }
  4292. Py_END_ALLOW_THREADS
  4293. path_cleanup(&_path);
  4294. if (result) {
  4295. Py_RETURN_TRUE;
  4296. }
  4297. Py_RETURN_FALSE;
  4298. }
  4299. /*[clinic input]
  4300. os._path_isfile
  4301. path: 'O'
  4302. Test whether a path is a regular file
  4303. [clinic start generated code]*/
  4304. static PyObject *
  4305. os__path_isfile_impl(PyObject *module, PyObject *path)
  4306. /*[clinic end generated code: output=2394ed7c4b5cfd85 input=de22d74960ade365]*/
  4307. {
  4308. HANDLE hfile;
  4309. BOOL close_file = TRUE;
  4310. FILE_BASIC_INFO info;
  4311. path_t _path = PATH_T_INITIALIZE("isfile", "path", 0, 1);
  4312. int result;
  4313. BOOL slow_path = TRUE;
  4314. FILE_STAT_BASIC_INFORMATION statInfo;
  4315. if (!path_converter(path, &_path)) {
  4316. path_cleanup(&_path);
  4317. if (PyErr_ExceptionMatches(PyExc_ValueError)) {
  4318. PyErr_Clear();
  4319. Py_RETURN_FALSE;
  4320. }
  4321. return NULL;
  4322. }
  4323. Py_BEGIN_ALLOW_THREADS
  4324. if (_path.wide) {
  4325. if (_Py_GetFileInformationByName(_path.wide, FileStatBasicByNameInfo,
  4326. &statInfo, sizeof(statInfo))) {
  4327. if (!(statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
  4328. slow_path = FALSE;
  4329. result = !(statInfo.FileAttributes & FILE_ATTRIBUTE_DIRECTORY);
  4330. } else if (statInfo.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  4331. slow_path = FALSE;
  4332. result = 0;
  4333. }
  4334. } else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(GetLastError())) {
  4335. slow_path = FALSE;
  4336. result = 0;
  4337. }
  4338. }
  4339. if (slow_path) {
  4340. if (_path.fd != -1) {
  4341. hfile = _Py_get_osfhandle_noraise(_path.fd);
  4342. close_file = FALSE;
  4343. }
  4344. else {
  4345. hfile = CreateFileW(_path.wide, FILE_READ_ATTRIBUTES, 0, NULL,
  4346. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  4347. }
  4348. if (hfile != INVALID_HANDLE_VALUE) {
  4349. if (GetFileInformationByHandleEx(hfile, FileBasicInfo, &info,
  4350. sizeof(info)))
  4351. {
  4352. result = !(info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY);
  4353. }
  4354. else {
  4355. result = 0;
  4356. }
  4357. if (close_file) {
  4358. CloseHandle(hfile);
  4359. }
  4360. }
  4361. else {
  4362. STRUCT_STAT st;
  4363. switch (GetLastError()) {
  4364. case ERROR_ACCESS_DENIED:
  4365. case ERROR_SHARING_VIOLATION:
  4366. case ERROR_CANT_ACCESS_FILE:
  4367. case ERROR_INVALID_PARAMETER:
  4368. if (STAT(_path.wide, &st)) {
  4369. result = 0;
  4370. }
  4371. else {
  4372. result = S_ISREG(st.st_mode);
  4373. }
  4374. break;
  4375. default:
  4376. result = 0;
  4377. }
  4378. }
  4379. }
  4380. Py_END_ALLOW_THREADS
  4381. path_cleanup(&_path);
  4382. if (result) {
  4383. Py_RETURN_TRUE;
  4384. }
  4385. Py_RETURN_FALSE;
  4386. }
  4387. /*[clinic input]
  4388. os._path_exists
  4389. path: 'O'
  4390. Test whether a path exists. Returns False for broken symbolic links
  4391. [clinic start generated code]*/
  4392. static PyObject *
  4393. os__path_exists_impl(PyObject *module, PyObject *path)
  4394. /*[clinic end generated code: output=f508c3b35e13a249 input=380f77cdfa0f7ae8]*/
  4395. {
  4396. HANDLE hfile;
  4397. BOOL close_file = TRUE;
  4398. path_t _path = PATH_T_INITIALIZE("exists", "path", 0, 1);
  4399. int result;
  4400. BOOL slow_path = TRUE;
  4401. FILE_STAT_BASIC_INFORMATION statInfo;
  4402. if (!path_converter(path, &_path)) {
  4403. path_cleanup(&_path);
  4404. if (PyErr_ExceptionMatches(PyExc_ValueError)) {
  4405. PyErr_Clear();
  4406. Py_RETURN_FALSE;
  4407. }
  4408. return NULL;
  4409. }
  4410. Py_BEGIN_ALLOW_THREADS
  4411. if (_path.wide) {
  4412. if (_Py_GetFileInformationByName(_path.wide, FileStatBasicByNameInfo,
  4413. &statInfo, sizeof(statInfo))) {
  4414. if (!(statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
  4415. slow_path = FALSE;
  4416. result = 1;
  4417. }
  4418. } else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(GetLastError())) {
  4419. slow_path = FALSE;
  4420. result = 0;
  4421. }
  4422. }
  4423. if (slow_path) {
  4424. if (_path.fd != -1) {
  4425. hfile = _Py_get_osfhandle_noraise(_path.fd);
  4426. close_file = FALSE;
  4427. }
  4428. else {
  4429. hfile = CreateFileW(_path.wide, FILE_READ_ATTRIBUTES, 0, NULL,
  4430. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  4431. }
  4432. if (hfile != INVALID_HANDLE_VALUE) {
  4433. result = 1;
  4434. if (close_file) {
  4435. CloseHandle(hfile);
  4436. }
  4437. }
  4438. else {
  4439. STRUCT_STAT st;
  4440. switch (GetLastError()) {
  4441. case ERROR_ACCESS_DENIED:
  4442. case ERROR_SHARING_VIOLATION:
  4443. case ERROR_CANT_ACCESS_FILE:
  4444. case ERROR_INVALID_PARAMETER:
  4445. if (STAT(_path.wide, &st)) {
  4446. result = 0;
  4447. }
  4448. else {
  4449. result = 1;
  4450. }
  4451. break;
  4452. default:
  4453. result = 0;
  4454. }
  4455. }
  4456. }
  4457. Py_END_ALLOW_THREADS
  4458. path_cleanup(&_path);
  4459. if (result) {
  4460. Py_RETURN_TRUE;
  4461. }
  4462. Py_RETURN_FALSE;
  4463. }
  4464. /*[clinic input]
  4465. os._path_islink
  4466. path: 'O'
  4467. Test whether a path is a symbolic link
  4468. [clinic start generated code]*/
  4469. static PyObject *
  4470. os__path_islink_impl(PyObject *module, PyObject *path)
  4471. /*[clinic end generated code: output=6d8640b1a390c054 input=38a3cb937ccf59bf]*/
  4472. {
  4473. HANDLE hfile;
  4474. BOOL close_file = TRUE;
  4475. FILE_ATTRIBUTE_TAG_INFO info;
  4476. path_t _path = PATH_T_INITIALIZE("islink", "path", 0, 1);
  4477. int result;
  4478. BOOL slow_path = TRUE;
  4479. FILE_STAT_BASIC_INFORMATION statInfo;
  4480. if (!path_converter(path, &_path)) {
  4481. path_cleanup(&_path);
  4482. if (PyErr_ExceptionMatches(PyExc_ValueError)) {
  4483. PyErr_Clear();
  4484. Py_RETURN_FALSE;
  4485. }
  4486. return NULL;
  4487. }
  4488. Py_BEGIN_ALLOW_THREADS
  4489. if (_path.wide) {
  4490. if (_Py_GetFileInformationByName(_path.wide, FileStatBasicByNameInfo,
  4491. &statInfo, sizeof(statInfo))) {
  4492. slow_path = FALSE;
  4493. if (statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
  4494. result = (statInfo.ReparseTag == IO_REPARSE_TAG_SYMLINK);
  4495. }
  4496. else {
  4497. result = 0;
  4498. }
  4499. } else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(GetLastError())) {
  4500. slow_path = FALSE;
  4501. result = 0;
  4502. }
  4503. }
  4504. if (slow_path) {
  4505. if (_path.fd != -1) {
  4506. hfile = _Py_get_osfhandle_noraise(_path.fd);
  4507. close_file = FALSE;
  4508. }
  4509. else {
  4510. hfile = CreateFileW(_path.wide, FILE_READ_ATTRIBUTES, 0, NULL,
  4511. OPEN_EXISTING,
  4512. FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
  4513. NULL);
  4514. }
  4515. if (hfile != INVALID_HANDLE_VALUE) {
  4516. if (GetFileInformationByHandleEx(hfile, FileAttributeTagInfo, &info,
  4517. sizeof(info)))
  4518. {
  4519. result = (info.ReparseTag == IO_REPARSE_TAG_SYMLINK);
  4520. }
  4521. else {
  4522. result = 0;
  4523. }
  4524. if (close_file) {
  4525. CloseHandle(hfile);
  4526. }
  4527. }
  4528. else {
  4529. STRUCT_STAT st;
  4530. switch (GetLastError()) {
  4531. case ERROR_ACCESS_DENIED:
  4532. case ERROR_SHARING_VIOLATION:
  4533. case ERROR_CANT_ACCESS_FILE:
  4534. case ERROR_INVALID_PARAMETER:
  4535. if (LSTAT(_path.wide, &st)) {
  4536. result = 0;
  4537. }
  4538. else {
  4539. result = S_ISLNK(st.st_mode);
  4540. }
  4541. break;
  4542. default:
  4543. result = 0;
  4544. }
  4545. }
  4546. }
  4547. Py_END_ALLOW_THREADS
  4548. path_cleanup(&_path);
  4549. if (result) {
  4550. Py_RETURN_TRUE;
  4551. }
  4552. Py_RETURN_FALSE;
  4553. }
  4554. #endif /* MS_WINDOWS */
  4555. /*[clinic input]
  4556. os._path_normpath
  4557. path: object
  4558. Basic path normalization.
  4559. [clinic start generated code]*/
  4560. static PyObject *
  4561. os__path_normpath_impl(PyObject *module, PyObject *path)
  4562. /*[clinic end generated code: output=b94d696d828019da input=5e90c39e12549dc0]*/
  4563. {
  4564. if (!PyUnicode_Check(path)) {
  4565. PyErr_Format(PyExc_TypeError, "expected 'str', not '%.200s'",
  4566. Py_TYPE(path)->tp_name);
  4567. return NULL;
  4568. }
  4569. Py_ssize_t len;
  4570. wchar_t *buffer = PyUnicode_AsWideCharString(path, &len);
  4571. if (!buffer) {
  4572. return NULL;
  4573. }
  4574. Py_ssize_t norm_len;
  4575. wchar_t *norm_path = _Py_normpath_and_size(buffer, len, &norm_len);
  4576. PyObject *result = PyUnicode_FromWideChar(norm_path, norm_len);
  4577. PyMem_Free(buffer);
  4578. return result;
  4579. }
  4580. /*[clinic input]
  4581. os.mkdir
  4582. path : path_t
  4583. mode: int = 0o777
  4584. *
  4585. dir_fd : dir_fd(requires='mkdirat') = None
  4586. # "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
  4587. Create a directory.
  4588. If dir_fd is not None, it should be a file descriptor open to a directory,
  4589. and path should be relative; path will then be relative to that directory.
  4590. dir_fd may not be implemented on your platform.
  4591. If it is unavailable, using it will raise a NotImplementedError.
  4592. The mode argument is ignored on Windows. Where it is used, the current umask
  4593. value is first masked out.
  4594. [clinic start generated code]*/
  4595. static PyObject *
  4596. os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
  4597. /*[clinic end generated code: output=a70446903abe821f input=a61722e1576fab03]*/
  4598. {
  4599. int result;
  4600. #ifdef HAVE_MKDIRAT
  4601. int mkdirat_unavailable = 0;
  4602. #endif
  4603. if (PySys_Audit("os.mkdir", "Oii", path->object, mode,
  4604. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4605. return NULL;
  4606. }
  4607. #ifdef MS_WINDOWS
  4608. Py_BEGIN_ALLOW_THREADS
  4609. result = CreateDirectoryW(path->wide, NULL);
  4610. Py_END_ALLOW_THREADS
  4611. if (!result)
  4612. return path_error(path);
  4613. #else
  4614. Py_BEGIN_ALLOW_THREADS
  4615. #if HAVE_MKDIRAT
  4616. if (dir_fd != DEFAULT_DIR_FD) {
  4617. if (HAVE_MKDIRAT_RUNTIME) {
  4618. result = mkdirat(dir_fd, path->narrow, mode);
  4619. } else {
  4620. mkdirat_unavailable = 1;
  4621. }
  4622. } else
  4623. #endif
  4624. #if defined(__WATCOMC__) && !defined(__QNX__)
  4625. result = mkdir(path->narrow);
  4626. #else
  4627. result = mkdir(path->narrow, mode);
  4628. #endif
  4629. Py_END_ALLOW_THREADS
  4630. #if HAVE_MKDIRAT
  4631. if (mkdirat_unavailable) {
  4632. argument_unavailable_error(NULL, "dir_fd");
  4633. return NULL;
  4634. }
  4635. #endif
  4636. if (result < 0)
  4637. return path_error(path);
  4638. #endif /* MS_WINDOWS */
  4639. Py_RETURN_NONE;
  4640. }
  4641. /* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
  4642. #if defined(HAVE_SYS_RESOURCE_H)
  4643. #include <sys/resource.h>
  4644. #endif
  4645. #ifdef HAVE_NICE
  4646. /*[clinic input]
  4647. os.nice
  4648. increment: int
  4649. /
  4650. Add increment to the priority of process and return the new priority.
  4651. [clinic start generated code]*/
  4652. static PyObject *
  4653. os_nice_impl(PyObject *module, int increment)
  4654. /*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
  4655. {
  4656. int value;
  4657. /* There are two flavours of 'nice': one that returns the new
  4658. priority (as required by almost all standards out there) and the
  4659. Linux/FreeBSD one, which returns '0' on success and advices
  4660. the use of getpriority() to get the new priority.
  4661. If we are of the nice family that returns the new priority, we
  4662. need to clear errno before the call, and check if errno is filled
  4663. before calling posix_error() on a returnvalue of -1, because the
  4664. -1 may be the actual new priority! */
  4665. errno = 0;
  4666. value = nice(increment);
  4667. #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
  4668. if (value == 0)
  4669. value = getpriority(PRIO_PROCESS, 0);
  4670. #endif
  4671. if (value == -1 && errno != 0)
  4672. /* either nice() or getpriority() returned an error */
  4673. return posix_error();
  4674. return PyLong_FromLong((long) value);
  4675. }
  4676. #endif /* HAVE_NICE */
  4677. #ifdef HAVE_GETPRIORITY
  4678. /*[clinic input]
  4679. os.getpriority
  4680. which: int
  4681. who: int
  4682. Return program scheduling priority.
  4683. [clinic start generated code]*/
  4684. static PyObject *
  4685. os_getpriority_impl(PyObject *module, int which, int who)
  4686. /*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
  4687. {
  4688. int retval;
  4689. errno = 0;
  4690. retval = getpriority(which, who);
  4691. if (errno != 0)
  4692. return posix_error();
  4693. return PyLong_FromLong((long)retval);
  4694. }
  4695. #endif /* HAVE_GETPRIORITY */
  4696. #ifdef HAVE_SETPRIORITY
  4697. /*[clinic input]
  4698. os.setpriority
  4699. which: int
  4700. who: int
  4701. priority: int
  4702. Set program scheduling priority.
  4703. [clinic start generated code]*/
  4704. static PyObject *
  4705. os_setpriority_impl(PyObject *module, int which, int who, int priority)
  4706. /*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
  4707. {
  4708. int retval;
  4709. retval = setpriority(which, who, priority);
  4710. if (retval == -1)
  4711. return posix_error();
  4712. Py_RETURN_NONE;
  4713. }
  4714. #endif /* HAVE_SETPRIORITY */
  4715. static PyObject *
  4716. internal_rename(path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int is_replace)
  4717. {
  4718. const char *function_name = is_replace ? "replace" : "rename";
  4719. int dir_fd_specified;
  4720. #ifdef HAVE_RENAMEAT
  4721. int renameat_unavailable = 0;
  4722. #endif
  4723. #ifdef MS_WINDOWS
  4724. BOOL result;
  4725. int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
  4726. #else
  4727. int result;
  4728. #endif
  4729. dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
  4730. (dst_dir_fd != DEFAULT_DIR_FD);
  4731. #ifndef HAVE_RENAMEAT
  4732. if (dir_fd_specified) {
  4733. argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
  4734. return NULL;
  4735. }
  4736. #endif
  4737. if (PySys_Audit("os.rename", "OOii", src->object, dst->object,
  4738. src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
  4739. dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
  4740. return NULL;
  4741. }
  4742. #ifdef MS_WINDOWS
  4743. Py_BEGIN_ALLOW_THREADS
  4744. result = MoveFileExW(src->wide, dst->wide, flags);
  4745. Py_END_ALLOW_THREADS
  4746. if (!result)
  4747. return path_error2(src, dst);
  4748. #else
  4749. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  4750. PyErr_Format(PyExc_ValueError,
  4751. "%s: src and dst must be the same type", function_name);
  4752. return NULL;
  4753. }
  4754. Py_BEGIN_ALLOW_THREADS
  4755. #ifdef HAVE_RENAMEAT
  4756. if (dir_fd_specified) {
  4757. if (HAVE_RENAMEAT_RUNTIME) {
  4758. result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
  4759. } else {
  4760. renameat_unavailable = 1;
  4761. }
  4762. } else
  4763. #endif
  4764. result = rename(src->narrow, dst->narrow);
  4765. Py_END_ALLOW_THREADS
  4766. #ifdef HAVE_RENAMEAT
  4767. if (renameat_unavailable) {
  4768. argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
  4769. return NULL;
  4770. }
  4771. #endif
  4772. if (result)
  4773. return path_error2(src, dst);
  4774. #endif
  4775. Py_RETURN_NONE;
  4776. }
  4777. /*[clinic input]
  4778. os.rename
  4779. src : path_t
  4780. dst : path_t
  4781. *
  4782. src_dir_fd : dir_fd = None
  4783. dst_dir_fd : dir_fd = None
  4784. Rename a file or directory.
  4785. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  4786. descriptor open to a directory, and the respective path string (src or dst)
  4787. should be relative; the path will then be relative to that directory.
  4788. src_dir_fd and dst_dir_fd, may not be implemented on your platform.
  4789. If they are unavailable, using them will raise a NotImplementedError.
  4790. [clinic start generated code]*/
  4791. static PyObject *
  4792. os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  4793. int dst_dir_fd)
  4794. /*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
  4795. {
  4796. return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
  4797. }
  4798. /*[clinic input]
  4799. os.replace = os.rename
  4800. Rename a file or directory, overwriting the destination.
  4801. If either src_dir_fd or dst_dir_fd is not None, it should be a file
  4802. descriptor open to a directory, and the respective path string (src or dst)
  4803. should be relative; the path will then be relative to that directory.
  4804. src_dir_fd and dst_dir_fd, may not be implemented on your platform.
  4805. If they are unavailable, using them will raise a NotImplementedError.
  4806. [clinic start generated code]*/
  4807. static PyObject *
  4808. os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
  4809. int dst_dir_fd)
  4810. /*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
  4811. {
  4812. return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
  4813. }
  4814. /*[clinic input]
  4815. os.rmdir
  4816. path: path_t
  4817. *
  4818. dir_fd: dir_fd(requires='unlinkat') = None
  4819. Remove a directory.
  4820. If dir_fd is not None, it should be a file descriptor open to a directory,
  4821. and path should be relative; path will then be relative to that directory.
  4822. dir_fd may not be implemented on your platform.
  4823. If it is unavailable, using it will raise a NotImplementedError.
  4824. [clinic start generated code]*/
  4825. static PyObject *
  4826. os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
  4827. /*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
  4828. {
  4829. int result;
  4830. #ifdef HAVE_UNLINKAT
  4831. int unlinkat_unavailable = 0;
  4832. #endif
  4833. if (PySys_Audit("os.rmdir", "Oi", path->object,
  4834. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4835. return NULL;
  4836. }
  4837. Py_BEGIN_ALLOW_THREADS
  4838. #ifdef MS_WINDOWS
  4839. /* Windows, success=1, UNIX, success=0 */
  4840. result = !RemoveDirectoryW(path->wide);
  4841. #else
  4842. #ifdef HAVE_UNLINKAT
  4843. if (dir_fd != DEFAULT_DIR_FD) {
  4844. if (HAVE_UNLINKAT_RUNTIME) {
  4845. result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
  4846. } else {
  4847. unlinkat_unavailable = 1;
  4848. result = -1;
  4849. }
  4850. } else
  4851. #endif
  4852. result = rmdir(path->narrow);
  4853. #endif
  4854. Py_END_ALLOW_THREADS
  4855. #ifdef HAVE_UNLINKAT
  4856. if (unlinkat_unavailable) {
  4857. argument_unavailable_error("rmdir", "dir_fd");
  4858. return NULL;
  4859. }
  4860. #endif
  4861. if (result)
  4862. return path_error(path);
  4863. Py_RETURN_NONE;
  4864. }
  4865. #ifdef HAVE_SYSTEM
  4866. #ifdef MS_WINDOWS
  4867. /*[clinic input]
  4868. os.system -> long
  4869. command: Py_UNICODE
  4870. Execute the command in a subshell.
  4871. [clinic start generated code]*/
  4872. static long
  4873. os_system_impl(PyObject *module, const Py_UNICODE *command)
  4874. /*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
  4875. {
  4876. long result;
  4877. if (PySys_Audit("os.system", "(u)", command) < 0) {
  4878. return -1;
  4879. }
  4880. Py_BEGIN_ALLOW_THREADS
  4881. _Py_BEGIN_SUPPRESS_IPH
  4882. result = _wsystem(command);
  4883. _Py_END_SUPPRESS_IPH
  4884. Py_END_ALLOW_THREADS
  4885. return result;
  4886. }
  4887. #else /* MS_WINDOWS */
  4888. /*[clinic input]
  4889. os.system -> long
  4890. command: FSConverter
  4891. Execute the command in a subshell.
  4892. [clinic start generated code]*/
  4893. static long
  4894. os_system_impl(PyObject *module, PyObject *command)
  4895. /*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
  4896. {
  4897. long result;
  4898. const char *bytes = PyBytes_AsString(command);
  4899. if (PySys_Audit("os.system", "(O)", command) < 0) {
  4900. return -1;
  4901. }
  4902. Py_BEGIN_ALLOW_THREADS
  4903. result = system(bytes);
  4904. Py_END_ALLOW_THREADS
  4905. return result;
  4906. }
  4907. #endif
  4908. #endif /* HAVE_SYSTEM */
  4909. #ifdef HAVE_UMASK
  4910. /*[clinic input]
  4911. os.umask
  4912. mask: int
  4913. /
  4914. Set the current numeric umask and return the previous umask.
  4915. [clinic start generated code]*/
  4916. static PyObject *
  4917. os_umask_impl(PyObject *module, int mask)
  4918. /*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
  4919. {
  4920. int i = (int)umask(mask);
  4921. if (i < 0)
  4922. return posix_error();
  4923. return PyLong_FromLong((long)i);
  4924. }
  4925. #endif
  4926. #ifdef MS_WINDOWS
  4927. /* override the default DeleteFileW behavior so that directory
  4928. symlinks can be removed with this function, the same as with
  4929. Unix symlinks */
  4930. BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
  4931. {
  4932. WIN32_FILE_ATTRIBUTE_DATA info;
  4933. WIN32_FIND_DATAW find_data;
  4934. HANDLE find_data_handle;
  4935. int is_directory = 0;
  4936. int is_link = 0;
  4937. if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
  4938. is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4939. /* Get WIN32_FIND_DATA structure for the path to determine if
  4940. it is a symlink */
  4941. if(is_directory &&
  4942. info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
  4943. find_data_handle = FindFirstFileW(lpFileName, &find_data);
  4944. if(find_data_handle != INVALID_HANDLE_VALUE) {
  4945. /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
  4946. IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
  4947. is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
  4948. find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
  4949. FindClose(find_data_handle);
  4950. }
  4951. }
  4952. }
  4953. if (is_directory && is_link)
  4954. return RemoveDirectoryW(lpFileName);
  4955. return DeleteFileW(lpFileName);
  4956. }
  4957. #endif /* MS_WINDOWS */
  4958. /*[clinic input]
  4959. os.unlink
  4960. path: path_t
  4961. *
  4962. dir_fd: dir_fd(requires='unlinkat')=None
  4963. Remove a file (same as remove()).
  4964. If dir_fd is not None, it should be a file descriptor open to a directory,
  4965. and path should be relative; path will then be relative to that directory.
  4966. dir_fd may not be implemented on your platform.
  4967. If it is unavailable, using it will raise a NotImplementedError.
  4968. [clinic start generated code]*/
  4969. static PyObject *
  4970. os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
  4971. /*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
  4972. {
  4973. int result;
  4974. #ifdef HAVE_UNLINKAT
  4975. int unlinkat_unavailable = 0;
  4976. #endif
  4977. if (PySys_Audit("os.remove", "Oi", path->object,
  4978. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  4979. return NULL;
  4980. }
  4981. Py_BEGIN_ALLOW_THREADS
  4982. _Py_BEGIN_SUPPRESS_IPH
  4983. #ifdef MS_WINDOWS
  4984. /* Windows, success=1, UNIX, success=0 */
  4985. result = !Py_DeleteFileW(path->wide);
  4986. #else
  4987. #ifdef HAVE_UNLINKAT
  4988. if (dir_fd != DEFAULT_DIR_FD) {
  4989. if (HAVE_UNLINKAT_RUNTIME) {
  4990. result = unlinkat(dir_fd, path->narrow, 0);
  4991. } else {
  4992. unlinkat_unavailable = 1;
  4993. }
  4994. } else
  4995. #endif /* HAVE_UNLINKAT */
  4996. result = unlink(path->narrow);
  4997. #endif
  4998. _Py_END_SUPPRESS_IPH
  4999. Py_END_ALLOW_THREADS
  5000. #ifdef HAVE_UNLINKAT
  5001. if (unlinkat_unavailable) {
  5002. argument_unavailable_error(NULL, "dir_fd");
  5003. return NULL;
  5004. }
  5005. #endif
  5006. if (result)
  5007. return path_error(path);
  5008. Py_RETURN_NONE;
  5009. }
  5010. /*[clinic input]
  5011. os.remove = os.unlink
  5012. Remove a file (same as unlink()).
  5013. If dir_fd is not None, it should be a file descriptor open to a directory,
  5014. and path should be relative; path will then be relative to that directory.
  5015. dir_fd may not be implemented on your platform.
  5016. If it is unavailable, using it will raise a NotImplementedError.
  5017. [clinic start generated code]*/
  5018. static PyObject *
  5019. os_remove_impl(PyObject *module, path_t *path, int dir_fd)
  5020. /*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
  5021. {
  5022. return os_unlink_impl(module, path, dir_fd);
  5023. }
  5024. static PyStructSequence_Field uname_result_fields[] = {
  5025. {"sysname", "operating system name"},
  5026. {"nodename", "name of machine on network (implementation-defined)"},
  5027. {"release", "operating system release"},
  5028. {"version", "operating system version"},
  5029. {"machine", "hardware identifier"},
  5030. {NULL}
  5031. };
  5032. PyDoc_STRVAR(uname_result__doc__,
  5033. "uname_result: Result from os.uname().\n\n\
  5034. This object may be accessed either as a tuple of\n\
  5035. (sysname, nodename, release, version, machine),\n\
  5036. or via the attributes sysname, nodename, release, version, and machine.\n\
  5037. \n\
  5038. See os.uname for more information.");
  5039. static PyStructSequence_Desc uname_result_desc = {
  5040. MODNAME ".uname_result", /* name */
  5041. uname_result__doc__, /* doc */
  5042. uname_result_fields,
  5043. 5
  5044. };
  5045. #ifdef HAVE_UNAME
  5046. /*[clinic input]
  5047. os.uname
  5048. Return an object identifying the current operating system.
  5049. The object behaves like a named tuple with the following fields:
  5050. (sysname, nodename, release, version, machine)
  5051. [clinic start generated code]*/
  5052. static PyObject *
  5053. os_uname_impl(PyObject *module)
  5054. /*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
  5055. {
  5056. struct utsname u;
  5057. int res;
  5058. PyObject *value;
  5059. Py_BEGIN_ALLOW_THREADS
  5060. res = uname(&u);
  5061. Py_END_ALLOW_THREADS
  5062. if (res < 0)
  5063. return posix_error();
  5064. PyObject *UnameResultType = get_posix_state(module)->UnameResultType;
  5065. value = PyStructSequence_New((PyTypeObject *)UnameResultType);
  5066. if (value == NULL)
  5067. return NULL;
  5068. #define SET(i, field) \
  5069. { \
  5070. PyObject *o = PyUnicode_DecodeFSDefault(field); \
  5071. if (!o) { \
  5072. Py_DECREF(value); \
  5073. return NULL; \
  5074. } \
  5075. PyStructSequence_SET_ITEM(value, i, o); \
  5076. } \
  5077. SET(0, u.sysname);
  5078. SET(1, u.nodename);
  5079. SET(2, u.release);
  5080. SET(3, u.version);
  5081. SET(4, u.machine);
  5082. #undef SET
  5083. return value;
  5084. }
  5085. #endif /* HAVE_UNAME */
  5086. typedef struct {
  5087. int now;
  5088. time_t atime_s;
  5089. long atime_ns;
  5090. time_t mtime_s;
  5091. long mtime_ns;
  5092. } utime_t;
  5093. /*
  5094. * these macros assume that "ut" is a pointer to a utime_t
  5095. * they also intentionally leak the declaration of a pointer named "time"
  5096. */
  5097. #define UTIME_TO_TIMESPEC \
  5098. struct timespec ts[2]; \
  5099. struct timespec *time; \
  5100. if (ut->now) \
  5101. time = NULL; \
  5102. else { \
  5103. ts[0].tv_sec = ut->atime_s; \
  5104. ts[0].tv_nsec = ut->atime_ns; \
  5105. ts[1].tv_sec = ut->mtime_s; \
  5106. ts[1].tv_nsec = ut->mtime_ns; \
  5107. time = ts; \
  5108. } \
  5109. #define UTIME_TO_TIMEVAL \
  5110. struct timeval tv[2]; \
  5111. struct timeval *time; \
  5112. if (ut->now) \
  5113. time = NULL; \
  5114. else { \
  5115. tv[0].tv_sec = ut->atime_s; \
  5116. tv[0].tv_usec = ut->atime_ns / 1000; \
  5117. tv[1].tv_sec = ut->mtime_s; \
  5118. tv[1].tv_usec = ut->mtime_ns / 1000; \
  5119. time = tv; \
  5120. } \
  5121. #define UTIME_TO_UTIMBUF \
  5122. struct utimbuf u; \
  5123. struct utimbuf *time; \
  5124. if (ut->now) \
  5125. time = NULL; \
  5126. else { \
  5127. u.actime = ut->atime_s; \
  5128. u.modtime = ut->mtime_s; \
  5129. time = &u; \
  5130. }
  5131. #define UTIME_TO_TIME_T \
  5132. time_t timet[2]; \
  5133. time_t *time; \
  5134. if (ut->now) \
  5135. time = NULL; \
  5136. else { \
  5137. timet[0] = ut->atime_s; \
  5138. timet[1] = ut->mtime_s; \
  5139. time = timet; \
  5140. } \
  5141. #if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
  5142. static int
  5143. utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
  5144. {
  5145. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5146. if (HAVE_UTIMENSAT_RUNTIME) {
  5147. int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
  5148. UTIME_TO_TIMESPEC;
  5149. return utimensat(dir_fd, path, time, flags);
  5150. } else {
  5151. errno = ENOSYS;
  5152. return -1;
  5153. }
  5154. #elif defined(HAVE_UTIMENSAT)
  5155. int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
  5156. UTIME_TO_TIMESPEC;
  5157. return utimensat(dir_fd, path, time, flags);
  5158. #elif defined(HAVE_FUTIMESAT)
  5159. UTIME_TO_TIMEVAL;
  5160. /*
  5161. * follow_symlinks will never be false here;
  5162. * we only allow !follow_symlinks and dir_fd together
  5163. * if we have utimensat()
  5164. */
  5165. assert(follow_symlinks);
  5166. return futimesat(dir_fd, path, time);
  5167. #endif
  5168. }
  5169. #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
  5170. #else
  5171. #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
  5172. #endif
  5173. #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
  5174. static int
  5175. utime_fd(utime_t *ut, int fd)
  5176. {
  5177. #ifdef HAVE_FUTIMENS
  5178. if (HAVE_FUTIMENS_RUNTIME) {
  5179. UTIME_TO_TIMESPEC;
  5180. return futimens(fd, time);
  5181. } else
  5182. #ifndef HAVE_FUTIMES
  5183. {
  5184. /* Not sure if this can happen */
  5185. PyErr_SetString(
  5186. PyExc_RuntimeError,
  5187. "neither futimens nor futimes are supported"
  5188. " on this system");
  5189. return -1;
  5190. }
  5191. #endif
  5192. #endif
  5193. #ifdef HAVE_FUTIMES
  5194. {
  5195. UTIME_TO_TIMEVAL;
  5196. return futimes(fd, time);
  5197. }
  5198. #endif
  5199. }
  5200. #define PATH_UTIME_HAVE_FD 1
  5201. #else
  5202. #define PATH_UTIME_HAVE_FD 0
  5203. #endif
  5204. #if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
  5205. # define UTIME_HAVE_NOFOLLOW_SYMLINKS
  5206. #endif
  5207. #ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
  5208. static int
  5209. utime_nofollow_symlinks(utime_t *ut, const char *path)
  5210. {
  5211. #ifdef HAVE_UTIMENSAT
  5212. if (HAVE_UTIMENSAT_RUNTIME) {
  5213. UTIME_TO_TIMESPEC;
  5214. return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
  5215. } else
  5216. #ifndef HAVE_LUTIMES
  5217. {
  5218. /* Not sure if this can happen */
  5219. PyErr_SetString(
  5220. PyExc_RuntimeError,
  5221. "neither utimensat nor lutimes are supported"
  5222. " on this system");
  5223. return -1;
  5224. }
  5225. #endif
  5226. #endif
  5227. #ifdef HAVE_LUTIMES
  5228. {
  5229. UTIME_TO_TIMEVAL;
  5230. return lutimes(path, time);
  5231. }
  5232. #endif
  5233. }
  5234. #endif
  5235. #ifndef MS_WINDOWS
  5236. static int
  5237. utime_default(utime_t *ut, const char *path)
  5238. {
  5239. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5240. if (HAVE_UTIMENSAT_RUNTIME) {
  5241. UTIME_TO_TIMESPEC;
  5242. return utimensat(DEFAULT_DIR_FD, path, time, 0);
  5243. } else {
  5244. UTIME_TO_TIMEVAL;
  5245. return utimes(path, time);
  5246. }
  5247. #elif defined(HAVE_UTIMENSAT)
  5248. UTIME_TO_TIMESPEC;
  5249. return utimensat(DEFAULT_DIR_FD, path, time, 0);
  5250. #elif defined(HAVE_UTIMES)
  5251. UTIME_TO_TIMEVAL;
  5252. return utimes(path, time);
  5253. #elif defined(HAVE_UTIME_H)
  5254. UTIME_TO_UTIMBUF;
  5255. return utime(path, time);
  5256. #else
  5257. UTIME_TO_TIME_T;
  5258. return utime(path, time);
  5259. #endif
  5260. }
  5261. #endif
  5262. static int
  5263. split_py_long_to_s_and_ns(PyObject *module, PyObject *py_long, time_t *s, long *ns)
  5264. {
  5265. int result = 0;
  5266. PyObject *divmod;
  5267. divmod = PyNumber_Divmod(py_long, get_posix_state(module)->billion);
  5268. if (!divmod)
  5269. goto exit;
  5270. if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
  5271. PyErr_Format(PyExc_TypeError,
  5272. "%.200s.__divmod__() must return a 2-tuple, not %.200s",
  5273. _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
  5274. goto exit;
  5275. }
  5276. *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
  5277. if ((*s == -1) && PyErr_Occurred())
  5278. goto exit;
  5279. *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
  5280. if ((*ns == -1) && PyErr_Occurred())
  5281. goto exit;
  5282. result = 1;
  5283. exit:
  5284. Py_XDECREF(divmod);
  5285. return result;
  5286. }
  5287. /*[clinic input]
  5288. os.utime
  5289. path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
  5290. times: object = None
  5291. *
  5292. ns: object = NULL
  5293. dir_fd: dir_fd(requires='futimensat') = None
  5294. follow_symlinks: bool=True
  5295. # "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
  5296. Set the access and modified time of path.
  5297. path may always be specified as a string.
  5298. On some platforms, path may also be specified as an open file descriptor.
  5299. If this functionality is unavailable, using it raises an exception.
  5300. If times is not None, it must be a tuple (atime, mtime);
  5301. atime and mtime should be expressed as float seconds since the epoch.
  5302. If ns is specified, it must be a tuple (atime_ns, mtime_ns);
  5303. atime_ns and mtime_ns should be expressed as integer nanoseconds
  5304. since the epoch.
  5305. If times is None and ns is unspecified, utime uses the current time.
  5306. Specifying tuples for both times and ns is an error.
  5307. If dir_fd is not None, it should be a file descriptor open to a directory,
  5308. and path should be relative; path will then be relative to that directory.
  5309. If follow_symlinks is False, and the last element of the path is a symbolic
  5310. link, utime will modify the symbolic link itself instead of the file the
  5311. link points to.
  5312. It is an error to use dir_fd or follow_symlinks when specifying path
  5313. as an open file descriptor.
  5314. dir_fd and follow_symlinks may not be available on your platform.
  5315. If they are unavailable, using them will raise a NotImplementedError.
  5316. [clinic start generated code]*/
  5317. static PyObject *
  5318. os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
  5319. int dir_fd, int follow_symlinks)
  5320. /*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
  5321. {
  5322. #ifdef MS_WINDOWS
  5323. HANDLE hFile;
  5324. FILETIME atime, mtime;
  5325. #else
  5326. int result;
  5327. #endif
  5328. utime_t utime;
  5329. memset(&utime, 0, sizeof(utime_t));
  5330. if (times != Py_None && ns) {
  5331. PyErr_SetString(PyExc_ValueError,
  5332. "utime: you may specify either 'times'"
  5333. " or 'ns' but not both");
  5334. return NULL;
  5335. }
  5336. if (times != Py_None) {
  5337. time_t a_sec, m_sec;
  5338. long a_nsec, m_nsec;
  5339. if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
  5340. PyErr_SetString(PyExc_TypeError,
  5341. "utime: 'times' must be either"
  5342. " a tuple of two ints or None");
  5343. return NULL;
  5344. }
  5345. utime.now = 0;
  5346. if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
  5347. &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
  5348. _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
  5349. &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
  5350. return NULL;
  5351. }
  5352. utime.atime_s = a_sec;
  5353. utime.atime_ns = a_nsec;
  5354. utime.mtime_s = m_sec;
  5355. utime.mtime_ns = m_nsec;
  5356. }
  5357. else if (ns) {
  5358. if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
  5359. PyErr_SetString(PyExc_TypeError,
  5360. "utime: 'ns' must be a tuple of two ints");
  5361. return NULL;
  5362. }
  5363. utime.now = 0;
  5364. if (!split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 0),
  5365. &utime.atime_s, &utime.atime_ns) ||
  5366. !split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 1),
  5367. &utime.mtime_s, &utime.mtime_ns)) {
  5368. return NULL;
  5369. }
  5370. }
  5371. else {
  5372. /* times and ns are both None/unspecified. use "now". */
  5373. utime.now = 1;
  5374. }
  5375. #if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
  5376. if (follow_symlinks_specified("utime", follow_symlinks))
  5377. return NULL;
  5378. #endif
  5379. if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
  5380. dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
  5381. fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
  5382. return NULL;
  5383. #if !defined(HAVE_UTIMENSAT)
  5384. if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
  5385. PyErr_SetString(PyExc_ValueError,
  5386. "utime: cannot use dir_fd and follow_symlinks "
  5387. "together on this platform");
  5388. return NULL;
  5389. }
  5390. #endif
  5391. if (PySys_Audit("os.utime", "OOOi", path->object, times, ns ? ns : Py_None,
  5392. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  5393. return NULL;
  5394. }
  5395. #ifdef MS_WINDOWS
  5396. Py_BEGIN_ALLOW_THREADS
  5397. hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
  5398. NULL, OPEN_EXISTING,
  5399. FILE_FLAG_BACKUP_SEMANTICS, NULL);
  5400. Py_END_ALLOW_THREADS
  5401. if (hFile == INVALID_HANDLE_VALUE) {
  5402. path_error(path);
  5403. return NULL;
  5404. }
  5405. if (utime.now) {
  5406. GetSystemTimeAsFileTime(&mtime);
  5407. atime = mtime;
  5408. }
  5409. else {
  5410. _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
  5411. _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
  5412. }
  5413. if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
  5414. /* Avoid putting the file name into the error here,
  5415. as that may confuse the user into believing that
  5416. something is wrong with the file, when it also
  5417. could be the time stamp that gives a problem. */
  5418. PyErr_SetFromWindowsErr(0);
  5419. CloseHandle(hFile);
  5420. return NULL;
  5421. }
  5422. CloseHandle(hFile);
  5423. #else /* MS_WINDOWS */
  5424. Py_BEGIN_ALLOW_THREADS
  5425. #ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
  5426. if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
  5427. result = utime_nofollow_symlinks(&utime, path->narrow);
  5428. else
  5429. #endif
  5430. #if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
  5431. if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks)) {
  5432. result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
  5433. } else
  5434. #endif
  5435. #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
  5436. if (path->fd != -1)
  5437. result = utime_fd(&utime, path->fd);
  5438. else
  5439. #endif
  5440. result = utime_default(&utime, path->narrow);
  5441. Py_END_ALLOW_THREADS
  5442. #if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
  5443. /* See utime_dir_fd implementation */
  5444. if (result == -1 && errno == ENOSYS) {
  5445. argument_unavailable_error(NULL, "dir_fd");
  5446. return NULL;
  5447. }
  5448. #endif
  5449. if (result < 0) {
  5450. /* see previous comment about not putting filename in error here */
  5451. posix_error();
  5452. return NULL;
  5453. }
  5454. #endif /* MS_WINDOWS */
  5455. Py_RETURN_NONE;
  5456. }
  5457. /* Process operations */
  5458. /*[clinic input]
  5459. os._exit
  5460. status: int
  5461. Exit to the system with specified status, without normal exit processing.
  5462. [clinic start generated code]*/
  5463. static PyObject *
  5464. os__exit_impl(PyObject *module, int status)
  5465. /*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
  5466. {
  5467. _exit(status);
  5468. return NULL; /* Make gcc -Wall happy */
  5469. }
  5470. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5471. #define EXECV_CHAR wchar_t
  5472. #else
  5473. #define EXECV_CHAR char
  5474. #endif
  5475. #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
  5476. static void
  5477. free_string_array(EXECV_CHAR **array, Py_ssize_t count)
  5478. {
  5479. Py_ssize_t i;
  5480. for (i = 0; i < count; i++)
  5481. PyMem_Free(array[i]);
  5482. PyMem_Free(array);
  5483. }
  5484. static int
  5485. fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
  5486. {
  5487. Py_ssize_t size;
  5488. PyObject *ub;
  5489. int result = 0;
  5490. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5491. if (!PyUnicode_FSDecoder(o, &ub))
  5492. return 0;
  5493. *out = PyUnicode_AsWideCharString(ub, &size);
  5494. if (*out)
  5495. result = 1;
  5496. #else
  5497. if (!PyUnicode_FSConverter(o, &ub))
  5498. return 0;
  5499. size = PyBytes_GET_SIZE(ub);
  5500. *out = PyMem_Malloc(size + 1);
  5501. if (*out) {
  5502. memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
  5503. result = 1;
  5504. } else
  5505. PyErr_NoMemory();
  5506. #endif
  5507. Py_DECREF(ub);
  5508. return result;
  5509. }
  5510. #endif
  5511. #if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
  5512. static EXECV_CHAR**
  5513. parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
  5514. {
  5515. Py_ssize_t i, pos, envc;
  5516. PyObject *keys=NULL, *vals=NULL;
  5517. PyObject *key2, *val2, *keyval;
  5518. EXECV_CHAR **envlist;
  5519. i = PyMapping_Size(env);
  5520. if (i < 0)
  5521. return NULL;
  5522. envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
  5523. if (envlist == NULL) {
  5524. PyErr_NoMemory();
  5525. return NULL;
  5526. }
  5527. envc = 0;
  5528. keys = PyMapping_Keys(env);
  5529. if (!keys)
  5530. goto error;
  5531. vals = PyMapping_Values(env);
  5532. if (!vals)
  5533. goto error;
  5534. if (!PyList_Check(keys) || !PyList_Check(vals)) {
  5535. PyErr_Format(PyExc_TypeError,
  5536. "env.keys() or env.values() is not a list");
  5537. goto error;
  5538. }
  5539. for (pos = 0; pos < i; pos++) {
  5540. PyObject *key = PyList_GetItem(keys, pos); // Borrowed ref.
  5541. if (key == NULL) {
  5542. goto error;
  5543. }
  5544. PyObject *val = PyList_GetItem(vals, pos); // Borrowed ref.
  5545. if (val == NULL) {
  5546. goto error;
  5547. }
  5548. #if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
  5549. if (!PyUnicode_FSDecoder(key, &key2))
  5550. goto error;
  5551. if (!PyUnicode_FSDecoder(val, &val2)) {
  5552. Py_DECREF(key2);
  5553. goto error;
  5554. }
  5555. /* Search from index 1 because on Windows starting '=' is allowed for
  5556. defining hidden environment variables. */
  5557. if (PyUnicode_GET_LENGTH(key2) == 0 ||
  5558. PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
  5559. {
  5560. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  5561. Py_DECREF(key2);
  5562. Py_DECREF(val2);
  5563. goto error;
  5564. }
  5565. keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
  5566. #else
  5567. if (!PyUnicode_FSConverter(key, &key2))
  5568. goto error;
  5569. if (!PyUnicode_FSConverter(val, &val2)) {
  5570. Py_DECREF(key2);
  5571. goto error;
  5572. }
  5573. if (PyBytes_GET_SIZE(key2) == 0 ||
  5574. strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
  5575. {
  5576. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  5577. Py_DECREF(key2);
  5578. Py_DECREF(val2);
  5579. goto error;
  5580. }
  5581. keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
  5582. PyBytes_AS_STRING(val2));
  5583. #endif
  5584. Py_DECREF(key2);
  5585. Py_DECREF(val2);
  5586. if (!keyval)
  5587. goto error;
  5588. if (!fsconvert_strdup(keyval, &envlist[envc++])) {
  5589. Py_DECREF(keyval);
  5590. goto error;
  5591. }
  5592. Py_DECREF(keyval);
  5593. }
  5594. Py_DECREF(vals);
  5595. Py_DECREF(keys);
  5596. envlist[envc] = 0;
  5597. *envc_ptr = envc;
  5598. return envlist;
  5599. error:
  5600. Py_XDECREF(keys);
  5601. Py_XDECREF(vals);
  5602. free_string_array(envlist, envc);
  5603. return NULL;
  5604. }
  5605. static EXECV_CHAR**
  5606. parse_arglist(PyObject* argv, Py_ssize_t *argc)
  5607. {
  5608. int i;
  5609. EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
  5610. if (argvlist == NULL) {
  5611. PyErr_NoMemory();
  5612. return NULL;
  5613. }
  5614. for (i = 0; i < *argc; i++) {
  5615. PyObject* item = PySequence_ITEM(argv, i);
  5616. if (item == NULL)
  5617. goto fail;
  5618. if (!fsconvert_strdup(item, &argvlist[i])) {
  5619. Py_DECREF(item);
  5620. goto fail;
  5621. }
  5622. Py_DECREF(item);
  5623. }
  5624. argvlist[*argc] = NULL;
  5625. return argvlist;
  5626. fail:
  5627. *argc = i;
  5628. free_string_array(argvlist, *argc);
  5629. return NULL;
  5630. }
  5631. #endif
  5632. #ifdef HAVE_EXECV
  5633. /*[clinic input]
  5634. os.execv
  5635. path: path_t
  5636. Path of executable file.
  5637. argv: object
  5638. Tuple or list of strings.
  5639. /
  5640. Execute an executable path with arguments, replacing current process.
  5641. [clinic start generated code]*/
  5642. static PyObject *
  5643. os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
  5644. /*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
  5645. {
  5646. EXECV_CHAR **argvlist;
  5647. Py_ssize_t argc;
  5648. PyInterpreterState *interp = _PyInterpreterState_GET();
  5649. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_EXEC)) {
  5650. PyErr_SetString(PyExc_RuntimeError,
  5651. "exec not supported for isolated subinterpreters");
  5652. return NULL;
  5653. }
  5654. /* execv has two arguments: (path, argv), where
  5655. argv is a list or tuple of strings. */
  5656. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  5657. PyErr_SetString(PyExc_TypeError,
  5658. "execv() arg 2 must be a tuple or list");
  5659. return NULL;
  5660. }
  5661. argc = PySequence_Size(argv);
  5662. if (argc < 1) {
  5663. PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
  5664. return NULL;
  5665. }
  5666. argvlist = parse_arglist(argv, &argc);
  5667. if (argvlist == NULL) {
  5668. return NULL;
  5669. }
  5670. if (!argvlist[0][0]) {
  5671. PyErr_SetString(PyExc_ValueError,
  5672. "execv() arg 2 first element cannot be empty");
  5673. free_string_array(argvlist, argc);
  5674. return NULL;
  5675. }
  5676. if (PySys_Audit("os.exec", "OOO", path->object, argv, Py_None) < 0) {
  5677. free_string_array(argvlist, argc);
  5678. return NULL;
  5679. }
  5680. _Py_BEGIN_SUPPRESS_IPH
  5681. #ifdef HAVE_WEXECV
  5682. _wexecv(path->wide, argvlist);
  5683. #else
  5684. execv(path->narrow, argvlist);
  5685. #endif
  5686. _Py_END_SUPPRESS_IPH
  5687. /* If we get here it's definitely an error */
  5688. posix_error();
  5689. free_string_array(argvlist, argc);
  5690. return NULL;
  5691. }
  5692. /*[clinic input]
  5693. os.execve
  5694. path: path_t(allow_fd='PATH_HAVE_FEXECVE')
  5695. Path of executable file.
  5696. argv: object
  5697. Tuple or list of strings.
  5698. env: object
  5699. Dictionary of strings mapping to strings.
  5700. Execute an executable path with arguments, replacing current process.
  5701. [clinic start generated code]*/
  5702. static PyObject *
  5703. os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
  5704. /*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
  5705. {
  5706. EXECV_CHAR **argvlist = NULL;
  5707. EXECV_CHAR **envlist;
  5708. Py_ssize_t argc, envc;
  5709. PyInterpreterState *interp = _PyInterpreterState_GET();
  5710. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_EXEC)) {
  5711. PyErr_SetString(PyExc_RuntimeError,
  5712. "exec not supported for isolated subinterpreters");
  5713. return NULL;
  5714. }
  5715. /* execve has three arguments: (path, argv, env), where
  5716. argv is a list or tuple of strings and env is a dictionary
  5717. like posix.environ. */
  5718. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  5719. PyErr_SetString(PyExc_TypeError,
  5720. "execve: argv must be a tuple or list");
  5721. goto fail_0;
  5722. }
  5723. argc = PySequence_Size(argv);
  5724. if (argc < 1) {
  5725. PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
  5726. return NULL;
  5727. }
  5728. if (!PyMapping_Check(env)) {
  5729. PyErr_SetString(PyExc_TypeError,
  5730. "execve: environment must be a mapping object");
  5731. goto fail_0;
  5732. }
  5733. argvlist = parse_arglist(argv, &argc);
  5734. if (argvlist == NULL) {
  5735. goto fail_0;
  5736. }
  5737. if (!argvlist[0][0]) {
  5738. PyErr_SetString(PyExc_ValueError,
  5739. "execve: argv first element cannot be empty");
  5740. goto fail_0;
  5741. }
  5742. envlist = parse_envlist(env, &envc);
  5743. if (envlist == NULL)
  5744. goto fail_0;
  5745. if (PySys_Audit("os.exec", "OOO", path->object, argv, env) < 0) {
  5746. goto fail_1;
  5747. }
  5748. _Py_BEGIN_SUPPRESS_IPH
  5749. #ifdef HAVE_FEXECVE
  5750. if (path->fd > -1)
  5751. fexecve(path->fd, argvlist, envlist);
  5752. else
  5753. #endif
  5754. #ifdef HAVE_WEXECV
  5755. _wexecve(path->wide, argvlist, envlist);
  5756. #else
  5757. execve(path->narrow, argvlist, envlist);
  5758. #endif
  5759. _Py_END_SUPPRESS_IPH
  5760. /* If we get here it's definitely an error */
  5761. posix_path_error(path);
  5762. fail_1:
  5763. free_string_array(envlist, envc);
  5764. fail_0:
  5765. if (argvlist)
  5766. free_string_array(argvlist, argc);
  5767. return NULL;
  5768. }
  5769. #endif /* HAVE_EXECV */
  5770. #ifdef HAVE_POSIX_SPAWN
  5771. enum posix_spawn_file_actions_identifier {
  5772. POSIX_SPAWN_OPEN,
  5773. POSIX_SPAWN_CLOSE,
  5774. POSIX_SPAWN_DUP2
  5775. };
  5776. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  5777. static int
  5778. convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res);
  5779. #endif
  5780. static int
  5781. parse_posix_spawn_flags(PyObject *module, const char *func_name, PyObject *setpgroup,
  5782. int resetids, int setsid, PyObject *setsigmask,
  5783. PyObject *setsigdef, PyObject *scheduler,
  5784. posix_spawnattr_t *attrp)
  5785. {
  5786. long all_flags = 0;
  5787. errno = posix_spawnattr_init(attrp);
  5788. if (errno) {
  5789. posix_error();
  5790. return -1;
  5791. }
  5792. if (setpgroup) {
  5793. pid_t pgid = PyLong_AsPid(setpgroup);
  5794. if (pgid == (pid_t)-1 && PyErr_Occurred()) {
  5795. goto fail;
  5796. }
  5797. errno = posix_spawnattr_setpgroup(attrp, pgid);
  5798. if (errno) {
  5799. posix_error();
  5800. goto fail;
  5801. }
  5802. all_flags |= POSIX_SPAWN_SETPGROUP;
  5803. }
  5804. if (resetids) {
  5805. all_flags |= POSIX_SPAWN_RESETIDS;
  5806. }
  5807. if (setsid) {
  5808. #ifdef HAVE_POSIX_SPAWN_SETSID_RUNTIME
  5809. if (HAVE_POSIX_SPAWN_SETSID_RUNTIME) {
  5810. #endif
  5811. #ifdef POSIX_SPAWN_SETSID
  5812. all_flags |= POSIX_SPAWN_SETSID;
  5813. #elif defined(POSIX_SPAWN_SETSID_NP)
  5814. all_flags |= POSIX_SPAWN_SETSID_NP;
  5815. #else
  5816. argument_unavailable_error(func_name, "setsid");
  5817. return -1;
  5818. #endif
  5819. #ifdef HAVE_POSIX_SPAWN_SETSID_RUNTIME
  5820. } else {
  5821. argument_unavailable_error(func_name, "setsid");
  5822. return -1;
  5823. }
  5824. #endif /* HAVE_POSIX_SPAWN_SETSID_RUNTIME */
  5825. }
  5826. #ifdef HAVE_SIGSET_T
  5827. if (setsigmask) {
  5828. sigset_t set;
  5829. if (!_Py_Sigset_Converter(setsigmask, &set)) {
  5830. goto fail;
  5831. }
  5832. errno = posix_spawnattr_setsigmask(attrp, &set);
  5833. if (errno) {
  5834. posix_error();
  5835. goto fail;
  5836. }
  5837. all_flags |= POSIX_SPAWN_SETSIGMASK;
  5838. }
  5839. if (setsigdef) {
  5840. sigset_t set;
  5841. if (!_Py_Sigset_Converter(setsigdef, &set)) {
  5842. goto fail;
  5843. }
  5844. errno = posix_spawnattr_setsigdefault(attrp, &set);
  5845. if (errno) {
  5846. posix_error();
  5847. goto fail;
  5848. }
  5849. all_flags |= POSIX_SPAWN_SETSIGDEF;
  5850. }
  5851. #else
  5852. if (setsigmask || setsigdef) {
  5853. PyErr_SetString(PyExc_NotImplementedError,
  5854. "sigset is not supported on this platform");
  5855. goto fail;
  5856. }
  5857. #endif
  5858. if (scheduler) {
  5859. #ifdef POSIX_SPAWN_SETSCHEDULER
  5860. PyObject *py_schedpolicy;
  5861. PyObject *schedparam_obj;
  5862. struct sched_param schedparam;
  5863. if (!PyArg_ParseTuple(scheduler, "OO"
  5864. ";A scheduler tuple must have two elements",
  5865. &py_schedpolicy, &schedparam_obj)) {
  5866. goto fail;
  5867. }
  5868. if (!convert_sched_param(module, schedparam_obj, &schedparam)) {
  5869. goto fail;
  5870. }
  5871. if (py_schedpolicy != Py_None) {
  5872. int schedpolicy = _PyLong_AsInt(py_schedpolicy);
  5873. if (schedpolicy == -1 && PyErr_Occurred()) {
  5874. goto fail;
  5875. }
  5876. errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
  5877. if (errno) {
  5878. posix_error();
  5879. goto fail;
  5880. }
  5881. all_flags |= POSIX_SPAWN_SETSCHEDULER;
  5882. }
  5883. errno = posix_spawnattr_setschedparam(attrp, &schedparam);
  5884. if (errno) {
  5885. posix_error();
  5886. goto fail;
  5887. }
  5888. all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
  5889. #else
  5890. PyErr_SetString(PyExc_NotImplementedError,
  5891. "The scheduler option is not supported in this system.");
  5892. goto fail;
  5893. #endif
  5894. }
  5895. errno = posix_spawnattr_setflags(attrp, all_flags);
  5896. if (errno) {
  5897. posix_error();
  5898. goto fail;
  5899. }
  5900. return 0;
  5901. fail:
  5902. (void)posix_spawnattr_destroy(attrp);
  5903. return -1;
  5904. }
  5905. static int
  5906. parse_file_actions(PyObject *file_actions,
  5907. posix_spawn_file_actions_t *file_actionsp,
  5908. PyObject *temp_buffer)
  5909. {
  5910. PyObject *seq;
  5911. PyObject *file_action = NULL;
  5912. PyObject *tag_obj;
  5913. seq = PySequence_Fast(file_actions,
  5914. "file_actions must be a sequence or None");
  5915. if (seq == NULL) {
  5916. return -1;
  5917. }
  5918. errno = posix_spawn_file_actions_init(file_actionsp);
  5919. if (errno) {
  5920. posix_error();
  5921. Py_DECREF(seq);
  5922. return -1;
  5923. }
  5924. for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
  5925. file_action = PySequence_Fast_GET_ITEM(seq, i);
  5926. Py_INCREF(file_action);
  5927. if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
  5928. PyErr_SetString(PyExc_TypeError,
  5929. "Each file_actions element must be a non-empty tuple");
  5930. goto fail;
  5931. }
  5932. long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
  5933. if (tag == -1 && PyErr_Occurred()) {
  5934. goto fail;
  5935. }
  5936. /* Populate the file_actions object */
  5937. switch (tag) {
  5938. case POSIX_SPAWN_OPEN: {
  5939. int fd, oflag;
  5940. PyObject *path;
  5941. unsigned long mode;
  5942. if (!PyArg_ParseTuple(file_action, "OiO&ik"
  5943. ";A open file_action tuple must have 5 elements",
  5944. &tag_obj, &fd, PyUnicode_FSConverter, &path,
  5945. &oflag, &mode))
  5946. {
  5947. goto fail;
  5948. }
  5949. if (PyList_Append(temp_buffer, path)) {
  5950. Py_DECREF(path);
  5951. goto fail;
  5952. }
  5953. errno = posix_spawn_file_actions_addopen(file_actionsp,
  5954. fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
  5955. if (errno) {
  5956. posix_error();
  5957. Py_DECREF(path);
  5958. goto fail;
  5959. }
  5960. Py_DECREF(path);
  5961. break;
  5962. }
  5963. case POSIX_SPAWN_CLOSE: {
  5964. int fd;
  5965. if (!PyArg_ParseTuple(file_action, "Oi"
  5966. ";A close file_action tuple must have 2 elements",
  5967. &tag_obj, &fd))
  5968. {
  5969. goto fail;
  5970. }
  5971. errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
  5972. if (errno) {
  5973. posix_error();
  5974. goto fail;
  5975. }
  5976. break;
  5977. }
  5978. case POSIX_SPAWN_DUP2: {
  5979. int fd1, fd2;
  5980. if (!PyArg_ParseTuple(file_action, "Oii"
  5981. ";A dup2 file_action tuple must have 3 elements",
  5982. &tag_obj, &fd1, &fd2))
  5983. {
  5984. goto fail;
  5985. }
  5986. errno = posix_spawn_file_actions_adddup2(file_actionsp,
  5987. fd1, fd2);
  5988. if (errno) {
  5989. posix_error();
  5990. goto fail;
  5991. }
  5992. break;
  5993. }
  5994. default: {
  5995. PyErr_SetString(PyExc_TypeError,
  5996. "Unknown file_actions identifier");
  5997. goto fail;
  5998. }
  5999. }
  6000. Py_DECREF(file_action);
  6001. }
  6002. Py_DECREF(seq);
  6003. return 0;
  6004. fail:
  6005. Py_DECREF(seq);
  6006. Py_DECREF(file_action);
  6007. (void)posix_spawn_file_actions_destroy(file_actionsp);
  6008. return -1;
  6009. }
  6010. static PyObject *
  6011. py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
  6012. PyObject *env, PyObject *file_actions,
  6013. PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
  6014. PyObject *setsigdef, PyObject *scheduler)
  6015. {
  6016. const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
  6017. EXECV_CHAR **argvlist = NULL;
  6018. EXECV_CHAR **envlist = NULL;
  6019. posix_spawn_file_actions_t file_actions_buf;
  6020. posix_spawn_file_actions_t *file_actionsp = NULL;
  6021. posix_spawnattr_t attr;
  6022. posix_spawnattr_t *attrp = NULL;
  6023. Py_ssize_t argc, envc;
  6024. PyObject *result = NULL;
  6025. PyObject *temp_buffer = NULL;
  6026. pid_t pid;
  6027. int err_code;
  6028. /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
  6029. argv is a list or tuple of strings and env is a dictionary
  6030. like posix.environ. */
  6031. if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
  6032. PyErr_Format(PyExc_TypeError,
  6033. "%s: argv must be a tuple or list", func_name);
  6034. goto exit;
  6035. }
  6036. argc = PySequence_Size(argv);
  6037. if (argc < 1) {
  6038. PyErr_Format(PyExc_ValueError,
  6039. "%s: argv must not be empty", func_name);
  6040. return NULL;
  6041. }
  6042. if (!PyMapping_Check(env)) {
  6043. PyErr_Format(PyExc_TypeError,
  6044. "%s: environment must be a mapping object", func_name);
  6045. goto exit;
  6046. }
  6047. argvlist = parse_arglist(argv, &argc);
  6048. if (argvlist == NULL) {
  6049. goto exit;
  6050. }
  6051. if (!argvlist[0][0]) {
  6052. PyErr_Format(PyExc_ValueError,
  6053. "%s: argv first element cannot be empty", func_name);
  6054. goto exit;
  6055. }
  6056. envlist = parse_envlist(env, &envc);
  6057. if (envlist == NULL) {
  6058. goto exit;
  6059. }
  6060. if (file_actions != NULL && file_actions != Py_None) {
  6061. /* There is a bug in old versions of glibc that makes some of the
  6062. * helper functions for manipulating file actions not copy the provided
  6063. * buffers. The problem is that posix_spawn_file_actions_addopen does not
  6064. * copy the value of path for some old versions of glibc (<2.20).
  6065. * The use of temp_buffer here is a workaround that keeps the
  6066. * python objects that own the buffers alive until posix_spawn gets called.
  6067. * Check https://bugs.python.org/issue33630 and
  6068. * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
  6069. temp_buffer = PyList_New(0);
  6070. if (!temp_buffer) {
  6071. goto exit;
  6072. }
  6073. if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
  6074. goto exit;
  6075. }
  6076. file_actionsp = &file_actions_buf;
  6077. }
  6078. if (parse_posix_spawn_flags(module, func_name, setpgroup, resetids, setsid,
  6079. setsigmask, setsigdef, scheduler, &attr)) {
  6080. goto exit;
  6081. }
  6082. attrp = &attr;
  6083. if (PySys_Audit("os.posix_spawn", "OOO", path->object, argv, env) < 0) {
  6084. goto exit;
  6085. }
  6086. _Py_BEGIN_SUPPRESS_IPH
  6087. #ifdef HAVE_POSIX_SPAWNP
  6088. if (use_posix_spawnp) {
  6089. err_code = posix_spawnp(&pid, path->narrow,
  6090. file_actionsp, attrp, argvlist, envlist);
  6091. }
  6092. else
  6093. #endif /* HAVE_POSIX_SPAWNP */
  6094. {
  6095. err_code = posix_spawn(&pid, path->narrow,
  6096. file_actionsp, attrp, argvlist, envlist);
  6097. }
  6098. _Py_END_SUPPRESS_IPH
  6099. if (err_code) {
  6100. errno = err_code;
  6101. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
  6102. goto exit;
  6103. }
  6104. #ifdef _Py_MEMORY_SANITIZER
  6105. __msan_unpoison(&pid, sizeof(pid));
  6106. #endif
  6107. result = PyLong_FromPid(pid);
  6108. exit:
  6109. if (file_actionsp) {
  6110. (void)posix_spawn_file_actions_destroy(file_actionsp);
  6111. }
  6112. if (attrp) {
  6113. (void)posix_spawnattr_destroy(attrp);
  6114. }
  6115. if (envlist) {
  6116. free_string_array(envlist, envc);
  6117. }
  6118. if (argvlist) {
  6119. free_string_array(argvlist, argc);
  6120. }
  6121. Py_XDECREF(temp_buffer);
  6122. return result;
  6123. }
  6124. /*[clinic input]
  6125. os.posix_spawn
  6126. path: path_t
  6127. Path of executable file.
  6128. argv: object
  6129. Tuple or list of strings.
  6130. env: object
  6131. Dictionary of strings mapping to strings.
  6132. /
  6133. *
  6134. file_actions: object(c_default='NULL') = ()
  6135. A sequence of file action tuples.
  6136. setpgroup: object = NULL
  6137. The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
  6138. resetids: bool = False
  6139. If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
  6140. setsid: bool = False
  6141. If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
  6142. setsigmask: object(c_default='NULL') = ()
  6143. The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
  6144. setsigdef: object(c_default='NULL') = ()
  6145. The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
  6146. scheduler: object = NULL
  6147. A tuple with the scheduler policy (optional) and parameters.
  6148. Execute the program specified by path in a new process.
  6149. [clinic start generated code]*/
  6150. static PyObject *
  6151. os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
  6152. PyObject *env, PyObject *file_actions,
  6153. PyObject *setpgroup, int resetids, int setsid,
  6154. PyObject *setsigmask, PyObject *setsigdef,
  6155. PyObject *scheduler)
  6156. /*[clinic end generated code: output=14a1098c566bc675 input=808aed1090d84e33]*/
  6157. {
  6158. return py_posix_spawn(0, module, path, argv, env, file_actions,
  6159. setpgroup, resetids, setsid, setsigmask, setsigdef,
  6160. scheduler);
  6161. }
  6162. #endif /* HAVE_POSIX_SPAWN */
  6163. #ifdef HAVE_POSIX_SPAWNP
  6164. /*[clinic input]
  6165. os.posix_spawnp
  6166. path: path_t
  6167. Path of executable file.
  6168. argv: object
  6169. Tuple or list of strings.
  6170. env: object
  6171. Dictionary of strings mapping to strings.
  6172. /
  6173. *
  6174. file_actions: object(c_default='NULL') = ()
  6175. A sequence of file action tuples.
  6176. setpgroup: object = NULL
  6177. The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
  6178. resetids: bool = False
  6179. If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
  6180. setsid: bool = False
  6181. If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
  6182. setsigmask: object(c_default='NULL') = ()
  6183. The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
  6184. setsigdef: object(c_default='NULL') = ()
  6185. The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
  6186. scheduler: object = NULL
  6187. A tuple with the scheduler policy (optional) and parameters.
  6188. Execute the program specified by path in a new process.
  6189. [clinic start generated code]*/
  6190. static PyObject *
  6191. os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
  6192. PyObject *env, PyObject *file_actions,
  6193. PyObject *setpgroup, int resetids, int setsid,
  6194. PyObject *setsigmask, PyObject *setsigdef,
  6195. PyObject *scheduler)
  6196. /*[clinic end generated code: output=7b9aaefe3031238d input=9e89e616116752a1]*/
  6197. {
  6198. return py_posix_spawn(1, module, path, argv, env, file_actions,
  6199. setpgroup, resetids, setsid, setsigmask, setsigdef,
  6200. scheduler);
  6201. }
  6202. #endif /* HAVE_POSIX_SPAWNP */
  6203. #ifdef HAVE_RTPSPAWN
  6204. static intptr_t
  6205. _rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
  6206. const char *envp[])
  6207. {
  6208. RTP_ID rtpid;
  6209. int status;
  6210. pid_t res;
  6211. int async_err = 0;
  6212. /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
  6213. uStackSize=0 cannot be used, the default stack size is too small for
  6214. Python. */
  6215. if (envp) {
  6216. rtpid = rtpSpawn(rtpFileName, argv, envp,
  6217. 100, 0x1000000, 0, VX_FP_TASK);
  6218. }
  6219. else {
  6220. rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
  6221. 100, 0x1000000, 0, VX_FP_TASK);
  6222. }
  6223. if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
  6224. do {
  6225. res = waitpid((pid_t)rtpid, &status, 0);
  6226. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  6227. if (res < 0)
  6228. return RTP_ID_ERROR;
  6229. return ((intptr_t)status);
  6230. }
  6231. return ((intptr_t)rtpid);
  6232. }
  6233. #endif
  6234. #if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
  6235. /*[clinic input]
  6236. os.spawnv
  6237. mode: int
  6238. Mode of process creation.
  6239. path: path_t
  6240. Path of executable file.
  6241. argv: object
  6242. Tuple or list of strings.
  6243. /
  6244. Execute the program specified by path in a new process.
  6245. [clinic start generated code]*/
  6246. static PyObject *
  6247. os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
  6248. /*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
  6249. {
  6250. EXECV_CHAR **argvlist;
  6251. int i;
  6252. Py_ssize_t argc;
  6253. intptr_t spawnval;
  6254. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  6255. /* spawnv has three arguments: (mode, path, argv), where
  6256. argv is a list or tuple of strings. */
  6257. if (PyList_Check(argv)) {
  6258. argc = PyList_Size(argv);
  6259. getitem = PyList_GetItem;
  6260. }
  6261. else if (PyTuple_Check(argv)) {
  6262. argc = PyTuple_Size(argv);
  6263. getitem = PyTuple_GetItem;
  6264. }
  6265. else {
  6266. PyErr_SetString(PyExc_TypeError,
  6267. "spawnv() arg 2 must be a tuple or list");
  6268. return NULL;
  6269. }
  6270. if (argc == 0) {
  6271. PyErr_SetString(PyExc_ValueError,
  6272. "spawnv() arg 2 cannot be empty");
  6273. return NULL;
  6274. }
  6275. argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
  6276. if (argvlist == NULL) {
  6277. return PyErr_NoMemory();
  6278. }
  6279. for (i = 0; i < argc; i++) {
  6280. if (!fsconvert_strdup((*getitem)(argv, i),
  6281. &argvlist[i])) {
  6282. free_string_array(argvlist, i);
  6283. PyErr_SetString(
  6284. PyExc_TypeError,
  6285. "spawnv() arg 2 must contain only strings");
  6286. return NULL;
  6287. }
  6288. if (i == 0 && !argvlist[0][0]) {
  6289. free_string_array(argvlist, i + 1);
  6290. PyErr_SetString(
  6291. PyExc_ValueError,
  6292. "spawnv() arg 2 first element cannot be empty");
  6293. return NULL;
  6294. }
  6295. }
  6296. argvlist[argc] = NULL;
  6297. #if !defined(HAVE_RTPSPAWN)
  6298. if (mode == _OLD_P_OVERLAY)
  6299. mode = _P_OVERLAY;
  6300. #endif
  6301. if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv,
  6302. Py_None) < 0) {
  6303. free_string_array(argvlist, argc);
  6304. return NULL;
  6305. }
  6306. Py_BEGIN_ALLOW_THREADS
  6307. _Py_BEGIN_SUPPRESS_IPH
  6308. #ifdef HAVE_WSPAWNV
  6309. spawnval = _wspawnv(mode, path->wide, argvlist);
  6310. #elif defined(HAVE_RTPSPAWN)
  6311. spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
  6312. #else
  6313. spawnval = _spawnv(mode, path->narrow, argvlist);
  6314. #endif
  6315. _Py_END_SUPPRESS_IPH
  6316. Py_END_ALLOW_THREADS
  6317. int saved_errno = errno;
  6318. free_string_array(argvlist, argc);
  6319. if (spawnval == -1) {
  6320. errno = saved_errno;
  6321. posix_error();
  6322. return NULL;
  6323. }
  6324. return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
  6325. }
  6326. /*[clinic input]
  6327. os.spawnve
  6328. mode: int
  6329. Mode of process creation.
  6330. path: path_t
  6331. Path of executable file.
  6332. argv: object
  6333. Tuple or list of strings.
  6334. env: object
  6335. Dictionary of strings mapping to strings.
  6336. /
  6337. Execute the program specified by path in a new process.
  6338. [clinic start generated code]*/
  6339. static PyObject *
  6340. os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
  6341. PyObject *env)
  6342. /*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
  6343. {
  6344. EXECV_CHAR **argvlist;
  6345. EXECV_CHAR **envlist;
  6346. PyObject *res = NULL;
  6347. Py_ssize_t argc, i, envc;
  6348. intptr_t spawnval;
  6349. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  6350. Py_ssize_t lastarg = 0;
  6351. /* spawnve has four arguments: (mode, path, argv, env), where
  6352. argv is a list or tuple of strings and env is a dictionary
  6353. like posix.environ. */
  6354. if (PyList_Check(argv)) {
  6355. argc = PyList_Size(argv);
  6356. getitem = PyList_GetItem;
  6357. }
  6358. else if (PyTuple_Check(argv)) {
  6359. argc = PyTuple_Size(argv);
  6360. getitem = PyTuple_GetItem;
  6361. }
  6362. else {
  6363. PyErr_SetString(PyExc_TypeError,
  6364. "spawnve() arg 2 must be a tuple or list");
  6365. goto fail_0;
  6366. }
  6367. if (argc == 0) {
  6368. PyErr_SetString(PyExc_ValueError,
  6369. "spawnve() arg 2 cannot be empty");
  6370. goto fail_0;
  6371. }
  6372. if (!PyMapping_Check(env)) {
  6373. PyErr_SetString(PyExc_TypeError,
  6374. "spawnve() arg 3 must be a mapping object");
  6375. goto fail_0;
  6376. }
  6377. argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
  6378. if (argvlist == NULL) {
  6379. PyErr_NoMemory();
  6380. goto fail_0;
  6381. }
  6382. for (i = 0; i < argc; i++) {
  6383. if (!fsconvert_strdup((*getitem)(argv, i),
  6384. &argvlist[i]))
  6385. {
  6386. lastarg = i;
  6387. goto fail_1;
  6388. }
  6389. if (i == 0 && !argvlist[0][0]) {
  6390. lastarg = i + 1;
  6391. PyErr_SetString(
  6392. PyExc_ValueError,
  6393. "spawnv() arg 2 first element cannot be empty");
  6394. goto fail_1;
  6395. }
  6396. }
  6397. lastarg = argc;
  6398. argvlist[argc] = NULL;
  6399. envlist = parse_envlist(env, &envc);
  6400. if (envlist == NULL)
  6401. goto fail_1;
  6402. #if !defined(HAVE_RTPSPAWN)
  6403. if (mode == _OLD_P_OVERLAY)
  6404. mode = _P_OVERLAY;
  6405. #endif
  6406. if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv, env) < 0) {
  6407. goto fail_2;
  6408. }
  6409. Py_BEGIN_ALLOW_THREADS
  6410. _Py_BEGIN_SUPPRESS_IPH
  6411. #ifdef HAVE_WSPAWNV
  6412. spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
  6413. #elif defined(HAVE_RTPSPAWN)
  6414. spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
  6415. (const char **)envlist);
  6416. #else
  6417. spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
  6418. #endif
  6419. _Py_END_SUPPRESS_IPH
  6420. Py_END_ALLOW_THREADS
  6421. if (spawnval == -1)
  6422. (void) posix_error();
  6423. else
  6424. res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
  6425. fail_2:
  6426. while (--envc >= 0) {
  6427. PyMem_Free(envlist[envc]);
  6428. }
  6429. PyMem_Free(envlist);
  6430. fail_1:
  6431. free_string_array(argvlist, lastarg);
  6432. fail_0:
  6433. return res;
  6434. }
  6435. #endif /* HAVE_SPAWNV */
  6436. #ifdef HAVE_FORK
  6437. /* Helper function to validate arguments.
  6438. Returns 0 on success. non-zero on failure with a TypeError raised.
  6439. If obj is non-NULL it must be callable. */
  6440. static int
  6441. check_null_or_callable(PyObject *obj, const char* obj_name)
  6442. {
  6443. if (obj && !PyCallable_Check(obj)) {
  6444. PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
  6445. obj_name, _PyType_Name(Py_TYPE(obj)));
  6446. return -1;
  6447. }
  6448. return 0;
  6449. }
  6450. /*[clinic input]
  6451. os.register_at_fork
  6452. *
  6453. before: object=NULL
  6454. A callable to be called in the parent before the fork() syscall.
  6455. after_in_child: object=NULL
  6456. A callable to be called in the child after fork().
  6457. after_in_parent: object=NULL
  6458. A callable to be called in the parent after fork().
  6459. Register callables to be called when forking a new process.
  6460. 'before' callbacks are called in reverse order.
  6461. 'after_in_child' and 'after_in_parent' callbacks are called in order.
  6462. [clinic start generated code]*/
  6463. static PyObject *
  6464. os_register_at_fork_impl(PyObject *module, PyObject *before,
  6465. PyObject *after_in_child, PyObject *after_in_parent)
  6466. /*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
  6467. {
  6468. PyInterpreterState *interp;
  6469. if (!before && !after_in_child && !after_in_parent) {
  6470. PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
  6471. return NULL;
  6472. }
  6473. if (check_null_or_callable(before, "before") ||
  6474. check_null_or_callable(after_in_child, "after_in_child") ||
  6475. check_null_or_callable(after_in_parent, "after_in_parent")) {
  6476. return NULL;
  6477. }
  6478. interp = _PyInterpreterState_GET();
  6479. if (register_at_forker(&interp->before_forkers, before)) {
  6480. return NULL;
  6481. }
  6482. if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
  6483. return NULL;
  6484. }
  6485. if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
  6486. return NULL;
  6487. }
  6488. Py_RETURN_NONE;
  6489. }
  6490. #endif /* HAVE_FORK */
  6491. // Common code to raise a warning if we detect there is more than one thread
  6492. // running in the process. Best effort, silent if unable to count threads.
  6493. // Constraint: Quick. Never overcounts. Never leaves an error set.
  6494. //
  6495. // This code might do an import, thus acquiring the import lock, which
  6496. // PyOS_BeforeFork() also does. As this should only be called from
  6497. // the parent process, it is in the same thread so that works.
  6498. static void warn_about_fork_with_threads(const char* name) {
  6499. // TODO: Consider making an `os` module API to return the current number
  6500. // of threads in the process. That'd presumably use this platform code but
  6501. // raise an error rather than using the inaccurate fallback.
  6502. Py_ssize_t num_python_threads = 0;
  6503. #if defined(__APPLE__) && defined(HAVE_GETPID)
  6504. mach_port_t macos_self = mach_task_self();
  6505. mach_port_t macos_task;
  6506. if (task_for_pid(macos_self, getpid(), &macos_task) == KERN_SUCCESS) {
  6507. thread_array_t macos_threads;
  6508. mach_msg_type_number_t macos_n_threads;
  6509. if (task_threads(macos_task, &macos_threads,
  6510. &macos_n_threads) == KERN_SUCCESS) {
  6511. num_python_threads = macos_n_threads;
  6512. }
  6513. }
  6514. #elif defined(__linux__)
  6515. // Linux /proc/self/stat 20th field is the number of threads.
  6516. FILE* proc_stat = fopen("/proc/self/stat", "r");
  6517. if (proc_stat) {
  6518. size_t n;
  6519. // Size chosen arbitrarily. ~60% more bytes than a 20th column index
  6520. // observed on the author's workstation.
  6521. char stat_line[160];
  6522. n = fread(&stat_line, 1, 159, proc_stat);
  6523. stat_line[n] = '\0';
  6524. fclose(proc_stat);
  6525. char *saveptr = NULL;
  6526. char *field = strtok_r(stat_line, " ", &saveptr);
  6527. unsigned int idx;
  6528. for (idx = 19; idx && field; --idx) {
  6529. field = strtok_r(NULL, " ", &saveptr);
  6530. }
  6531. if (idx == 0 && field) { // found the 20th field
  6532. num_python_threads = atoi(field); // 0 on error
  6533. }
  6534. }
  6535. #endif
  6536. if (num_python_threads <= 0) {
  6537. // Fall back to just the number our threading module knows about.
  6538. // An incomplete view of the world, but better than nothing.
  6539. PyObject *threading = PyImport_GetModule(&_Py_ID(threading));
  6540. if (!threading) {
  6541. PyErr_Clear();
  6542. return;
  6543. }
  6544. PyObject *threading_active =
  6545. PyObject_GetAttr(threading, &_Py_ID(_active));
  6546. if (!threading_active) {
  6547. PyErr_Clear();
  6548. Py_DECREF(threading);
  6549. return;
  6550. }
  6551. PyObject *threading_limbo =
  6552. PyObject_GetAttr(threading, &_Py_ID(_limbo));
  6553. if (!threading_limbo) {
  6554. PyErr_Clear();
  6555. Py_DECREF(threading);
  6556. Py_DECREF(threading_active);
  6557. return;
  6558. }
  6559. Py_DECREF(threading);
  6560. // Duplicating what threading.active_count() does but without holding
  6561. // threading._active_limbo_lock so our count could be inaccurate if
  6562. // these dicts are mid-update from another thread. Not a big deal.
  6563. // Worst case if someone replaced threading._active or threading._limbo
  6564. // with non-dicts, we get -1 from *Length() below and undercount.
  6565. // Nobody should, but we're best effort so we clear errors and move on.
  6566. num_python_threads = (PyMapping_Length(threading_active)
  6567. + PyMapping_Length(threading_limbo));
  6568. PyErr_Clear();
  6569. Py_DECREF(threading_active);
  6570. Py_DECREF(threading_limbo);
  6571. }
  6572. if (num_python_threads > 1) {
  6573. PyErr_WarnFormat(
  6574. PyExc_DeprecationWarning, 1,
  6575. #ifdef HAVE_GETPID
  6576. "This process (pid=%d) is multi-threaded, "
  6577. #else
  6578. "This process is multi-threaded, "
  6579. #endif
  6580. "use of %s() may lead to deadlocks in the child.",
  6581. #ifdef HAVE_GETPID
  6582. getpid(),
  6583. #endif
  6584. name);
  6585. PyErr_Clear();
  6586. }
  6587. }
  6588. #ifdef HAVE_FORK1
  6589. /*[clinic input]
  6590. os.fork1
  6591. Fork a child process with a single multiplexed (i.e., not bound) thread.
  6592. Return 0 to child process and PID of child to parent process.
  6593. [clinic start generated code]*/
  6594. static PyObject *
  6595. os_fork1_impl(PyObject *module)
  6596. /*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
  6597. {
  6598. pid_t pid;
  6599. PyInterpreterState *interp = _PyInterpreterState_GET();
  6600. if (interp->finalizing) {
  6601. PyErr_SetString(PyExc_RuntimeError,
  6602. "can't fork at interpreter shutdown");
  6603. return NULL;
  6604. }
  6605. if (!_Py_IsMainInterpreter(interp)) {
  6606. PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
  6607. return NULL;
  6608. }
  6609. PyOS_BeforeFork();
  6610. pid = fork1();
  6611. int saved_errno = errno;
  6612. if (pid == 0) {
  6613. /* child: this clobbers and resets the import lock. */
  6614. PyOS_AfterFork_Child();
  6615. } else {
  6616. warn_about_fork_with_threads("fork1");
  6617. /* parent: release the import lock. */
  6618. PyOS_AfterFork_Parent();
  6619. }
  6620. if (pid == -1) {
  6621. errno = saved_errno;
  6622. return posix_error();
  6623. }
  6624. return PyLong_FromPid(pid);
  6625. }
  6626. #endif /* HAVE_FORK1 */
  6627. #ifdef HAVE_FORK
  6628. /*[clinic input]
  6629. os.fork
  6630. Fork a child process.
  6631. Return 0 to child process and PID of child to parent process.
  6632. [clinic start generated code]*/
  6633. static PyObject *
  6634. os_fork_impl(PyObject *module)
  6635. /*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
  6636. {
  6637. pid_t pid;
  6638. PyInterpreterState *interp = _PyInterpreterState_GET();
  6639. if (interp->finalizing) {
  6640. PyErr_SetString(PyExc_RuntimeError,
  6641. "can't fork at interpreter shutdown");
  6642. return NULL;
  6643. }
  6644. if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_FORK)) {
  6645. PyErr_SetString(PyExc_RuntimeError,
  6646. "fork not supported for isolated subinterpreters");
  6647. return NULL;
  6648. }
  6649. if (PySys_Audit("os.fork", NULL) < 0) {
  6650. return NULL;
  6651. }
  6652. PyOS_BeforeFork();
  6653. pid = fork();
  6654. int saved_errno = errno;
  6655. if (pid == 0) {
  6656. /* child: this clobbers and resets the import lock. */
  6657. PyOS_AfterFork_Child();
  6658. } else {
  6659. warn_about_fork_with_threads("fork");
  6660. /* parent: release the import lock. */
  6661. PyOS_AfterFork_Parent();
  6662. }
  6663. if (pid == -1) {
  6664. errno = saved_errno;
  6665. return posix_error();
  6666. }
  6667. return PyLong_FromPid(pid);
  6668. }
  6669. #endif /* HAVE_FORK */
  6670. #ifdef HAVE_SCHED_H
  6671. #ifdef HAVE_SCHED_GET_PRIORITY_MAX
  6672. /*[clinic input]
  6673. os.sched_get_priority_max
  6674. policy: int
  6675. Get the maximum scheduling priority for policy.
  6676. [clinic start generated code]*/
  6677. static PyObject *
  6678. os_sched_get_priority_max_impl(PyObject *module, int policy)
  6679. /*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
  6680. {
  6681. int max;
  6682. max = sched_get_priority_max(policy);
  6683. if (max < 0)
  6684. return posix_error();
  6685. return PyLong_FromLong(max);
  6686. }
  6687. /*[clinic input]
  6688. os.sched_get_priority_min
  6689. policy: int
  6690. Get the minimum scheduling priority for policy.
  6691. [clinic start generated code]*/
  6692. static PyObject *
  6693. os_sched_get_priority_min_impl(PyObject *module, int policy)
  6694. /*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
  6695. {
  6696. int min = sched_get_priority_min(policy);
  6697. if (min < 0)
  6698. return posix_error();
  6699. return PyLong_FromLong(min);
  6700. }
  6701. #endif /* HAVE_SCHED_GET_PRIORITY_MAX */
  6702. #ifdef HAVE_SCHED_SETSCHEDULER
  6703. /*[clinic input]
  6704. os.sched_getscheduler
  6705. pid: pid_t
  6706. /
  6707. Get the scheduling policy for the process identified by pid.
  6708. Passing 0 for pid returns the scheduling policy for the calling process.
  6709. [clinic start generated code]*/
  6710. static PyObject *
  6711. os_sched_getscheduler_impl(PyObject *module, pid_t pid)
  6712. /*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
  6713. {
  6714. int policy;
  6715. policy = sched_getscheduler(pid);
  6716. if (policy < 0)
  6717. return posix_error();
  6718. return PyLong_FromLong(policy);
  6719. }
  6720. #endif /* HAVE_SCHED_SETSCHEDULER */
  6721. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  6722. /*[clinic input]
  6723. class os.sched_param "PyObject *" "SchedParamType"
  6724. @classmethod
  6725. os.sched_param.__new__
  6726. sched_priority: object
  6727. A scheduling parameter.
  6728. Currently has only one field: sched_priority
  6729. [clinic start generated code]*/
  6730. static PyObject *
  6731. os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
  6732. /*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
  6733. {
  6734. PyObject *res;
  6735. res = PyStructSequence_New(type);
  6736. if (!res)
  6737. return NULL;
  6738. PyStructSequence_SET_ITEM(res, 0, Py_NewRef(sched_priority));
  6739. return res;
  6740. }
  6741. PyDoc_VAR(os_sched_param__doc__);
  6742. static PyStructSequence_Field sched_param_fields[] = {
  6743. {"sched_priority", "the scheduling priority"},
  6744. {0}
  6745. };
  6746. static PyStructSequence_Desc sched_param_desc = {
  6747. "sched_param", /* name */
  6748. os_sched_param__doc__, /* doc */
  6749. sched_param_fields,
  6750. 1
  6751. };
  6752. static int
  6753. convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res)
  6754. {
  6755. long priority;
  6756. if (!Py_IS_TYPE(param, (PyTypeObject *)get_posix_state(module)->SchedParamType)) {
  6757. PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
  6758. return 0;
  6759. }
  6760. priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
  6761. if (priority == -1 && PyErr_Occurred())
  6762. return 0;
  6763. if (priority > INT_MAX || priority < INT_MIN) {
  6764. PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
  6765. return 0;
  6766. }
  6767. res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
  6768. return 1;
  6769. }
  6770. #endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
  6771. #ifdef HAVE_SCHED_SETSCHEDULER
  6772. /*[clinic input]
  6773. os.sched_setscheduler
  6774. pid: pid_t
  6775. policy: int
  6776. param as param_obj: object
  6777. /
  6778. Set the scheduling policy for the process identified by pid.
  6779. If pid is 0, the calling process is changed.
  6780. param is an instance of sched_param.
  6781. [clinic start generated code]*/
  6782. static PyObject *
  6783. os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
  6784. PyObject *param_obj)
  6785. /*[clinic end generated code: output=cde27faa55dc993e input=73013d731bd8fbe9]*/
  6786. {
  6787. struct sched_param param;
  6788. if (!convert_sched_param(module, param_obj, &param)) {
  6789. return NULL;
  6790. }
  6791. /*
  6792. ** sched_setscheduler() returns 0 in Linux, but the previous
  6793. ** scheduling policy under Solaris/Illumos, and others.
  6794. ** On error, -1 is returned in all Operating Systems.
  6795. */
  6796. if (sched_setscheduler(pid, policy, &param) == -1)
  6797. return posix_error();
  6798. Py_RETURN_NONE;
  6799. }
  6800. #endif /* HAVE_SCHED_SETSCHEDULER*/
  6801. #ifdef HAVE_SCHED_SETPARAM
  6802. /*[clinic input]
  6803. os.sched_getparam
  6804. pid: pid_t
  6805. /
  6806. Returns scheduling parameters for the process identified by pid.
  6807. If pid is 0, returns parameters for the calling process.
  6808. Return value is an instance of sched_param.
  6809. [clinic start generated code]*/
  6810. static PyObject *
  6811. os_sched_getparam_impl(PyObject *module, pid_t pid)
  6812. /*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
  6813. {
  6814. struct sched_param param;
  6815. PyObject *result;
  6816. PyObject *priority;
  6817. if (sched_getparam(pid, &param))
  6818. return posix_error();
  6819. PyObject *SchedParamType = get_posix_state(module)->SchedParamType;
  6820. result = PyStructSequence_New((PyTypeObject *)SchedParamType);
  6821. if (!result)
  6822. return NULL;
  6823. priority = PyLong_FromLong(param.sched_priority);
  6824. if (!priority) {
  6825. Py_DECREF(result);
  6826. return NULL;
  6827. }
  6828. PyStructSequence_SET_ITEM(result, 0, priority);
  6829. return result;
  6830. }
  6831. /*[clinic input]
  6832. os.sched_setparam
  6833. pid: pid_t
  6834. param as param_obj: object
  6835. /
  6836. Set scheduling parameters for the process identified by pid.
  6837. If pid is 0, sets parameters for the calling process.
  6838. param should be an instance of sched_param.
  6839. [clinic start generated code]*/
  6840. static PyObject *
  6841. os_sched_setparam_impl(PyObject *module, pid_t pid, PyObject *param_obj)
  6842. /*[clinic end generated code: output=f19fe020a53741c1 input=27b98337c8b2dcc7]*/
  6843. {
  6844. struct sched_param param;
  6845. if (!convert_sched_param(module, param_obj, &param)) {
  6846. return NULL;
  6847. }
  6848. if (sched_setparam(pid, &param))
  6849. return posix_error();
  6850. Py_RETURN_NONE;
  6851. }
  6852. #endif /* HAVE_SCHED_SETPARAM */
  6853. #ifdef HAVE_SCHED_RR_GET_INTERVAL
  6854. /*[clinic input]
  6855. os.sched_rr_get_interval -> double
  6856. pid: pid_t
  6857. /
  6858. Return the round-robin quantum for the process identified by pid, in seconds.
  6859. Value returned is a float.
  6860. [clinic start generated code]*/
  6861. static double
  6862. os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
  6863. /*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
  6864. {
  6865. struct timespec interval;
  6866. if (sched_rr_get_interval(pid, &interval)) {
  6867. posix_error();
  6868. return -1.0;
  6869. }
  6870. #ifdef _Py_MEMORY_SANITIZER
  6871. __msan_unpoison(&interval, sizeof(interval));
  6872. #endif
  6873. return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
  6874. }
  6875. #endif /* HAVE_SCHED_RR_GET_INTERVAL */
  6876. /*[clinic input]
  6877. os.sched_yield
  6878. Voluntarily relinquish the CPU.
  6879. [clinic start generated code]*/
  6880. static PyObject *
  6881. os_sched_yield_impl(PyObject *module)
  6882. /*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
  6883. {
  6884. int result;
  6885. Py_BEGIN_ALLOW_THREADS
  6886. result = sched_yield();
  6887. Py_END_ALLOW_THREADS
  6888. if (result < 0) {
  6889. return posix_error();
  6890. }
  6891. Py_RETURN_NONE;
  6892. }
  6893. #ifdef HAVE_SCHED_SETAFFINITY
  6894. /* The minimum number of CPUs allocated in a cpu_set_t */
  6895. static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
  6896. /*[clinic input]
  6897. os.sched_setaffinity
  6898. pid: pid_t
  6899. mask : object
  6900. /
  6901. Set the CPU affinity of the process identified by pid to mask.
  6902. mask should be an iterable of integers identifying CPUs.
  6903. [clinic start generated code]*/
  6904. static PyObject *
  6905. os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
  6906. /*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
  6907. {
  6908. int ncpus;
  6909. size_t setsize;
  6910. cpu_set_t *cpu_set = NULL;
  6911. PyObject *iterator = NULL, *item;
  6912. iterator = PyObject_GetIter(mask);
  6913. if (iterator == NULL)
  6914. return NULL;
  6915. ncpus = NCPUS_START;
  6916. setsize = CPU_ALLOC_SIZE(ncpus);
  6917. cpu_set = CPU_ALLOC(ncpus);
  6918. if (cpu_set == NULL) {
  6919. PyErr_NoMemory();
  6920. goto error;
  6921. }
  6922. CPU_ZERO_S(setsize, cpu_set);
  6923. while ((item = PyIter_Next(iterator))) {
  6924. long cpu;
  6925. if (!PyLong_Check(item)) {
  6926. PyErr_Format(PyExc_TypeError,
  6927. "expected an iterator of ints, "
  6928. "but iterator yielded %R",
  6929. Py_TYPE(item));
  6930. Py_DECREF(item);
  6931. goto error;
  6932. }
  6933. cpu = PyLong_AsLong(item);
  6934. Py_DECREF(item);
  6935. if (cpu < 0) {
  6936. if (!PyErr_Occurred())
  6937. PyErr_SetString(PyExc_ValueError, "negative CPU number");
  6938. goto error;
  6939. }
  6940. if (cpu > INT_MAX - 1) {
  6941. PyErr_SetString(PyExc_OverflowError, "CPU number too large");
  6942. goto error;
  6943. }
  6944. if (cpu >= ncpus) {
  6945. /* Grow CPU mask to fit the CPU number */
  6946. int newncpus = ncpus;
  6947. cpu_set_t *newmask;
  6948. size_t newsetsize;
  6949. while (newncpus <= cpu) {
  6950. if (newncpus > INT_MAX / 2)
  6951. newncpus = cpu + 1;
  6952. else
  6953. newncpus = newncpus * 2;
  6954. }
  6955. newmask = CPU_ALLOC(newncpus);
  6956. if (newmask == NULL) {
  6957. PyErr_NoMemory();
  6958. goto error;
  6959. }
  6960. newsetsize = CPU_ALLOC_SIZE(newncpus);
  6961. CPU_ZERO_S(newsetsize, newmask);
  6962. memcpy(newmask, cpu_set, setsize);
  6963. CPU_FREE(cpu_set);
  6964. setsize = newsetsize;
  6965. cpu_set = newmask;
  6966. ncpus = newncpus;
  6967. }
  6968. CPU_SET_S(cpu, setsize, cpu_set);
  6969. }
  6970. if (PyErr_Occurred()) {
  6971. goto error;
  6972. }
  6973. Py_CLEAR(iterator);
  6974. if (sched_setaffinity(pid, setsize, cpu_set)) {
  6975. posix_error();
  6976. goto error;
  6977. }
  6978. CPU_FREE(cpu_set);
  6979. Py_RETURN_NONE;
  6980. error:
  6981. if (cpu_set)
  6982. CPU_FREE(cpu_set);
  6983. Py_XDECREF(iterator);
  6984. return NULL;
  6985. }
  6986. /*[clinic input]
  6987. os.sched_getaffinity
  6988. pid: pid_t
  6989. /
  6990. Return the affinity of the process identified by pid (or the current process if zero).
  6991. The affinity is returned as a set of CPU identifiers.
  6992. [clinic start generated code]*/
  6993. static PyObject *
  6994. os_sched_getaffinity_impl(PyObject *module, pid_t pid)
  6995. /*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
  6996. {
  6997. int cpu, ncpus, count;
  6998. size_t setsize;
  6999. cpu_set_t *mask = NULL;
  7000. PyObject *res = NULL;
  7001. ncpus = NCPUS_START;
  7002. while (1) {
  7003. setsize = CPU_ALLOC_SIZE(ncpus);
  7004. mask = CPU_ALLOC(ncpus);
  7005. if (mask == NULL)
  7006. return PyErr_NoMemory();
  7007. if (sched_getaffinity(pid, setsize, mask) == 0)
  7008. break;
  7009. CPU_FREE(mask);
  7010. if (errno != EINVAL)
  7011. return posix_error();
  7012. if (ncpus > INT_MAX / 2) {
  7013. PyErr_SetString(PyExc_OverflowError, "could not allocate "
  7014. "a large enough CPU set");
  7015. return NULL;
  7016. }
  7017. ncpus = ncpus * 2;
  7018. }
  7019. res = PySet_New(NULL);
  7020. if (res == NULL)
  7021. goto error;
  7022. for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
  7023. if (CPU_ISSET_S(cpu, setsize, mask)) {
  7024. PyObject *cpu_num = PyLong_FromLong(cpu);
  7025. --count;
  7026. if (cpu_num == NULL)
  7027. goto error;
  7028. if (PySet_Add(res, cpu_num)) {
  7029. Py_DECREF(cpu_num);
  7030. goto error;
  7031. }
  7032. Py_DECREF(cpu_num);
  7033. }
  7034. }
  7035. CPU_FREE(mask);
  7036. return res;
  7037. error:
  7038. if (mask)
  7039. CPU_FREE(mask);
  7040. Py_XDECREF(res);
  7041. return NULL;
  7042. }
  7043. #endif /* HAVE_SCHED_SETAFFINITY */
  7044. #endif /* HAVE_SCHED_H */
  7045. /* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
  7046. #if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
  7047. # define DEV_PTY_FILE "/dev/ptc"
  7048. # define HAVE_DEV_PTMX
  7049. #else
  7050. # define DEV_PTY_FILE "/dev/ptmx"
  7051. #endif
  7052. #if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX)
  7053. #ifdef HAVE_PTY_H
  7054. #include <pty.h>
  7055. #ifdef HAVE_UTMP_H
  7056. #include <utmp.h>
  7057. #endif /* HAVE_UTMP_H */
  7058. #elif defined(HAVE_LIBUTIL_H)
  7059. #include <libutil.h>
  7060. #elif defined(HAVE_UTIL_H)
  7061. #include <util.h>
  7062. #endif /* HAVE_PTY_H */
  7063. #ifdef HAVE_STROPTS_H
  7064. #include <stropts.h>
  7065. #else
  7066. #define __SID ('S' << 8)
  7067. #define I_PUSH (__SID | 2)
  7068. #endif
  7069. #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX) */
  7070. #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
  7071. /*[clinic input]
  7072. os.openpty
  7073. Open a pseudo-terminal.
  7074. Return a tuple of (master_fd, slave_fd) containing open file descriptors
  7075. for both the master and slave ends.
  7076. [clinic start generated code]*/
  7077. static PyObject *
  7078. os_openpty_impl(PyObject *module)
  7079. /*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
  7080. {
  7081. int master_fd = -1, slave_fd = -1;
  7082. #ifndef HAVE_OPENPTY
  7083. char * slave_name;
  7084. #endif
  7085. #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
  7086. PyOS_sighandler_t sig_saved;
  7087. #if defined(__sun) && defined(__SVR4)
  7088. extern char *ptsname(int fildes);
  7089. #endif
  7090. #endif
  7091. #ifdef HAVE_OPENPTY
  7092. if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
  7093. goto posix_error;
  7094. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7095. goto error;
  7096. if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
  7097. goto error;
  7098. #elif defined(HAVE__GETPTY)
  7099. slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
  7100. if (slave_name == NULL)
  7101. goto posix_error;
  7102. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7103. goto error;
  7104. slave_fd = _Py_open(slave_name, O_RDWR);
  7105. if (slave_fd < 0)
  7106. goto error;
  7107. #else
  7108. master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
  7109. if (master_fd < 0)
  7110. goto posix_error;
  7111. sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
  7112. /* change permission of slave */
  7113. if (grantpt(master_fd) < 0) {
  7114. int saved_errno = errno;
  7115. PyOS_setsig(SIGCHLD, sig_saved);
  7116. errno = saved_errno;
  7117. goto posix_error;
  7118. }
  7119. /* unlock slave */
  7120. if (unlockpt(master_fd) < 0) {
  7121. int saved_errno = errno;
  7122. PyOS_setsig(SIGCHLD, sig_saved);
  7123. errno = saved_errno;
  7124. goto posix_error;
  7125. }
  7126. PyOS_setsig(SIGCHLD, sig_saved);
  7127. slave_name = ptsname(master_fd); /* get name of slave */
  7128. if (slave_name == NULL)
  7129. goto posix_error;
  7130. slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
  7131. if (slave_fd == -1)
  7132. goto error;
  7133. if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
  7134. goto posix_error;
  7135. #if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
  7136. ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
  7137. ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
  7138. #ifndef __hpux
  7139. ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
  7140. #endif /* __hpux */
  7141. #endif /* HAVE_CYGWIN */
  7142. #endif /* HAVE_OPENPTY */
  7143. return Py_BuildValue("(ii)", master_fd, slave_fd);
  7144. posix_error:
  7145. posix_error();
  7146. error:
  7147. if (master_fd != -1)
  7148. close(master_fd);
  7149. if (slave_fd != -1)
  7150. close(slave_fd);
  7151. return NULL;
  7152. }
  7153. #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
  7154. #if defined(HAVE_SETSID) && defined(TIOCSCTTY)
  7155. #define HAVE_FALLBACK_LOGIN_TTY 1
  7156. #endif /* defined(HAVE_SETSID) && defined(TIOCSCTTY) */
  7157. #if defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY)
  7158. /*[clinic input]
  7159. os.login_tty
  7160. fd: fildes
  7161. /
  7162. Prepare the tty of which fd is a file descriptor for a new login session.
  7163. Make the calling process a session leader; make the tty the
  7164. controlling tty, the stdin, the stdout, and the stderr of the
  7165. calling process; close fd.
  7166. [clinic start generated code]*/
  7167. static PyObject *
  7168. os_login_tty_impl(PyObject *module, int fd)
  7169. /*[clinic end generated code: output=495a79911b4cc1bc input=5f298565099903a2]*/
  7170. {
  7171. #ifdef HAVE_LOGIN_TTY
  7172. if (login_tty(fd) == -1) {
  7173. return posix_error();
  7174. }
  7175. #else /* defined(HAVE_FALLBACK_LOGIN_TTY) */
  7176. /* Establish a new session. */
  7177. if (setsid() == -1) {
  7178. return posix_error();
  7179. }
  7180. /* The tty becomes the controlling terminal. */
  7181. if (ioctl(fd, TIOCSCTTY, (char *)NULL) == -1) {
  7182. return posix_error();
  7183. }
  7184. /* The tty becomes stdin/stdout/stderr */
  7185. if (dup2(fd, 0) == -1 || dup2(fd, 1) == -1 || dup2(fd, 2) == -1) {
  7186. return posix_error();
  7187. }
  7188. if (fd > 2) {
  7189. close(fd);
  7190. }
  7191. #endif /* HAVE_LOGIN_TTY */
  7192. Py_RETURN_NONE;
  7193. }
  7194. #endif /* defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY) */
  7195. #ifdef HAVE_FORKPTY
  7196. /*[clinic input]
  7197. os.forkpty
  7198. Fork a new process with a new pseudo-terminal as controlling tty.
  7199. Returns a tuple of (pid, master_fd).
  7200. Like fork(), return pid of 0 to the child process,
  7201. and pid of child to the parent process.
  7202. To both, return fd of newly opened pseudo-terminal.
  7203. [clinic start generated code]*/
  7204. static PyObject *
  7205. os_forkpty_impl(PyObject *module)
  7206. /*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
  7207. {
  7208. int master_fd = -1;
  7209. pid_t pid;
  7210. PyInterpreterState *interp = _PyInterpreterState_GET();
  7211. if (interp->finalizing) {
  7212. PyErr_SetString(PyExc_RuntimeError,
  7213. "can't fork at interpreter shutdown");
  7214. return NULL;
  7215. }
  7216. if (!_Py_IsMainInterpreter(interp)) {
  7217. PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
  7218. return NULL;
  7219. }
  7220. if (PySys_Audit("os.forkpty", NULL) < 0) {
  7221. return NULL;
  7222. }
  7223. PyOS_BeforeFork();
  7224. pid = forkpty(&master_fd, NULL, NULL, NULL);
  7225. if (pid == 0) {
  7226. /* child: this clobbers and resets the import lock. */
  7227. PyOS_AfterFork_Child();
  7228. } else {
  7229. warn_about_fork_with_threads("forkpty");
  7230. /* parent: release the import lock. */
  7231. PyOS_AfterFork_Parent();
  7232. }
  7233. if (pid == -1) {
  7234. return posix_error();
  7235. }
  7236. return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
  7237. }
  7238. #endif /* HAVE_FORKPTY */
  7239. #ifdef HAVE_GETEGID
  7240. /*[clinic input]
  7241. os.getegid
  7242. Return the current process's effective group id.
  7243. [clinic start generated code]*/
  7244. static PyObject *
  7245. os_getegid_impl(PyObject *module)
  7246. /*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
  7247. {
  7248. return _PyLong_FromGid(getegid());
  7249. }
  7250. #endif /* HAVE_GETEGID */
  7251. #ifdef HAVE_GETEUID
  7252. /*[clinic input]
  7253. os.geteuid
  7254. Return the current process's effective user id.
  7255. [clinic start generated code]*/
  7256. static PyObject *
  7257. os_geteuid_impl(PyObject *module)
  7258. /*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
  7259. {
  7260. return _PyLong_FromUid(geteuid());
  7261. }
  7262. #endif /* HAVE_GETEUID */
  7263. #ifdef HAVE_GETGID
  7264. /*[clinic input]
  7265. os.getgid
  7266. Return the current process's group id.
  7267. [clinic start generated code]*/
  7268. static PyObject *
  7269. os_getgid_impl(PyObject *module)
  7270. /*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
  7271. {
  7272. return _PyLong_FromGid(getgid());
  7273. }
  7274. #endif /* HAVE_GETGID */
  7275. #if defined(HAVE_GETPID)
  7276. /*[clinic input]
  7277. os.getpid
  7278. Return the current process id.
  7279. [clinic start generated code]*/
  7280. static PyObject *
  7281. os_getpid_impl(PyObject *module)
  7282. /*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
  7283. {
  7284. #if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  7285. return PyLong_FromPid(getpid());
  7286. #else
  7287. return PyLong_FromUnsignedLong(GetCurrentProcessId());
  7288. #endif
  7289. }
  7290. #endif /* defined(HAVE_GETPID) */
  7291. #ifdef NGROUPS_MAX
  7292. #define MAX_GROUPS NGROUPS_MAX
  7293. #else
  7294. /* defined to be 16 on Solaris7, so this should be a small number */
  7295. #define MAX_GROUPS 64
  7296. #endif
  7297. #ifdef HAVE_GETGROUPLIST
  7298. #ifdef __APPLE__
  7299. /*[clinic input]
  7300. os.getgrouplist
  7301. user: str
  7302. username to lookup
  7303. group as basegid: int
  7304. base group id of the user
  7305. /
  7306. Returns a list of groups to which a user belongs.
  7307. [clinic start generated code]*/
  7308. static PyObject *
  7309. os_getgrouplist_impl(PyObject *module, const char *user, int basegid)
  7310. /*[clinic end generated code: output=6e734697b8c26de0 input=f8d870374b09a490]*/
  7311. #else
  7312. /*[clinic input]
  7313. os.getgrouplist
  7314. user: str
  7315. username to lookup
  7316. group as basegid: gid_t
  7317. base group id of the user
  7318. /
  7319. Returns a list of groups to which a user belongs.
  7320. [clinic start generated code]*/
  7321. static PyObject *
  7322. os_getgrouplist_impl(PyObject *module, const char *user, gid_t basegid)
  7323. /*[clinic end generated code: output=0ebd7fb70115575b input=cc61d5c20b08958d]*/
  7324. #endif
  7325. {
  7326. int i, ngroups;
  7327. PyObject *list;
  7328. #ifdef __APPLE__
  7329. int *groups;
  7330. #else
  7331. gid_t *groups;
  7332. #endif
  7333. /*
  7334. * NGROUPS_MAX is defined by POSIX.1 as the maximum
  7335. * number of supplimental groups a users can belong to.
  7336. * We have to increment it by one because
  7337. * getgrouplist() returns both the supplemental groups
  7338. * and the primary group, i.e. all of the groups the
  7339. * user belongs to.
  7340. */
  7341. ngroups = 1 + MAX_GROUPS;
  7342. while (1) {
  7343. #ifdef __APPLE__
  7344. groups = PyMem_New(int, ngroups);
  7345. #else
  7346. groups = PyMem_New(gid_t, ngroups);
  7347. #endif
  7348. if (groups == NULL) {
  7349. return PyErr_NoMemory();
  7350. }
  7351. int old_ngroups = ngroups;
  7352. if (getgrouplist(user, basegid, groups, &ngroups) != -1) {
  7353. /* Success */
  7354. break;
  7355. }
  7356. /* getgrouplist() fails if the group list is too small */
  7357. PyMem_Free(groups);
  7358. if (ngroups > old_ngroups) {
  7359. /* If the group list is too small, the glibc implementation of
  7360. getgrouplist() sets ngroups to the total number of groups and
  7361. returns -1. */
  7362. }
  7363. else {
  7364. /* Double the group list size */
  7365. if (ngroups > INT_MAX / 2) {
  7366. return PyErr_NoMemory();
  7367. }
  7368. ngroups *= 2;
  7369. }
  7370. /* Retry getgrouplist() with a larger group list */
  7371. }
  7372. #ifdef _Py_MEMORY_SANITIZER
  7373. /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
  7374. __msan_unpoison(&ngroups, sizeof(ngroups));
  7375. __msan_unpoison(groups, ngroups*sizeof(*groups));
  7376. #endif
  7377. list = PyList_New(ngroups);
  7378. if (list == NULL) {
  7379. PyMem_Free(groups);
  7380. return NULL;
  7381. }
  7382. for (i = 0; i < ngroups; i++) {
  7383. #ifdef __APPLE__
  7384. PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
  7385. #else
  7386. PyObject *o = _PyLong_FromGid(groups[i]);
  7387. #endif
  7388. if (o == NULL) {
  7389. Py_DECREF(list);
  7390. PyMem_Free(groups);
  7391. return NULL;
  7392. }
  7393. PyList_SET_ITEM(list, i, o);
  7394. }
  7395. PyMem_Free(groups);
  7396. return list;
  7397. }
  7398. #endif /* HAVE_GETGROUPLIST */
  7399. #ifdef HAVE_GETGROUPS
  7400. /*[clinic input]
  7401. os.getgroups
  7402. Return list of supplemental group IDs for the process.
  7403. [clinic start generated code]*/
  7404. static PyObject *
  7405. os_getgroups_impl(PyObject *module)
  7406. /*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
  7407. {
  7408. // Call getgroups with length 0 to get the actual number of groups
  7409. int n = getgroups(0, NULL);
  7410. if (n < 0) {
  7411. return posix_error();
  7412. }
  7413. if (n == 0) {
  7414. return PyList_New(0);
  7415. }
  7416. gid_t *grouplist = PyMem_New(gid_t, n);
  7417. if (grouplist == NULL) {
  7418. return PyErr_NoMemory();
  7419. }
  7420. n = getgroups(n, grouplist);
  7421. if (n == -1) {
  7422. posix_error();
  7423. PyMem_Free(grouplist);
  7424. return NULL;
  7425. }
  7426. PyObject *result = PyList_New(n);
  7427. if (result == NULL) {
  7428. goto error;
  7429. }
  7430. for (int i = 0; i < n; ++i) {
  7431. PyObject *group = _PyLong_FromGid(grouplist[i]);
  7432. if (group == NULL) {
  7433. goto error;
  7434. }
  7435. PyList_SET_ITEM(result, i, group);
  7436. }
  7437. PyMem_Free(grouplist);
  7438. return result;
  7439. error:
  7440. PyMem_Free(grouplist);
  7441. Py_XDECREF(result);
  7442. return NULL;
  7443. }
  7444. #endif /* HAVE_GETGROUPS */
  7445. #ifdef HAVE_INITGROUPS
  7446. #ifdef __APPLE__
  7447. /*[clinic input]
  7448. os.initgroups
  7449. username as oname: FSConverter
  7450. gid: int
  7451. /
  7452. Initialize the group access list.
  7453. Call the system initgroups() to initialize the group access list with all of
  7454. the groups of which the specified username is a member, plus the specified
  7455. group id.
  7456. [clinic start generated code]*/
  7457. static PyObject *
  7458. os_initgroups_impl(PyObject *module, PyObject *oname, int gid)
  7459. /*[clinic end generated code: output=7f074d30a425fd3a input=df3d54331b0af204]*/
  7460. #else
  7461. /*[clinic input]
  7462. os.initgroups
  7463. username as oname: FSConverter
  7464. gid: gid_t
  7465. /
  7466. Initialize the group access list.
  7467. Call the system initgroups() to initialize the group access list with all of
  7468. the groups of which the specified username is a member, plus the specified
  7469. group id.
  7470. [clinic start generated code]*/
  7471. static PyObject *
  7472. os_initgroups_impl(PyObject *module, PyObject *oname, gid_t gid)
  7473. /*[clinic end generated code: output=59341244521a9e3f input=0cb91bdc59a4c564]*/
  7474. #endif
  7475. {
  7476. const char *username = PyBytes_AS_STRING(oname);
  7477. if (initgroups(username, gid) == -1)
  7478. return PyErr_SetFromErrno(PyExc_OSError);
  7479. Py_RETURN_NONE;
  7480. }
  7481. #endif /* HAVE_INITGROUPS */
  7482. #ifdef HAVE_GETPGID
  7483. /*[clinic input]
  7484. os.getpgid
  7485. pid: pid_t
  7486. Call the system call getpgid(), and return the result.
  7487. [clinic start generated code]*/
  7488. static PyObject *
  7489. os_getpgid_impl(PyObject *module, pid_t pid)
  7490. /*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
  7491. {
  7492. pid_t pgid = getpgid(pid);
  7493. if (pgid < 0)
  7494. return posix_error();
  7495. return PyLong_FromPid(pgid);
  7496. }
  7497. #endif /* HAVE_GETPGID */
  7498. #ifdef HAVE_GETPGRP
  7499. /*[clinic input]
  7500. os.getpgrp
  7501. Return the current process group id.
  7502. [clinic start generated code]*/
  7503. static PyObject *
  7504. os_getpgrp_impl(PyObject *module)
  7505. /*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
  7506. {
  7507. #ifdef GETPGRP_HAVE_ARG
  7508. return PyLong_FromPid(getpgrp(0));
  7509. #else /* GETPGRP_HAVE_ARG */
  7510. return PyLong_FromPid(getpgrp());
  7511. #endif /* GETPGRP_HAVE_ARG */
  7512. }
  7513. #endif /* HAVE_GETPGRP */
  7514. #ifdef HAVE_SETPGRP
  7515. /*[clinic input]
  7516. os.setpgrp
  7517. Make the current process the leader of its process group.
  7518. [clinic start generated code]*/
  7519. static PyObject *
  7520. os_setpgrp_impl(PyObject *module)
  7521. /*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
  7522. {
  7523. #ifdef SETPGRP_HAVE_ARG
  7524. if (setpgrp(0, 0) < 0)
  7525. #else /* SETPGRP_HAVE_ARG */
  7526. if (setpgrp() < 0)
  7527. #endif /* SETPGRP_HAVE_ARG */
  7528. return posix_error();
  7529. Py_RETURN_NONE;
  7530. }
  7531. #endif /* HAVE_SETPGRP */
  7532. #ifdef HAVE_GETPPID
  7533. #ifdef MS_WINDOWS
  7534. #include <processsnapshot.h>
  7535. static PyObject*
  7536. win32_getppid(void)
  7537. {
  7538. DWORD error;
  7539. PyObject* result = NULL;
  7540. HANDLE process = GetCurrentProcess();
  7541. HPSS snapshot = NULL;
  7542. error = PssCaptureSnapshot(process, PSS_CAPTURE_NONE, 0, &snapshot);
  7543. if (error != ERROR_SUCCESS) {
  7544. return PyErr_SetFromWindowsErr(error);
  7545. }
  7546. PSS_PROCESS_INFORMATION info;
  7547. error = PssQuerySnapshot(snapshot, PSS_QUERY_PROCESS_INFORMATION, &info,
  7548. sizeof(info));
  7549. if (error == ERROR_SUCCESS) {
  7550. result = PyLong_FromUnsignedLong(info.ParentProcessId);
  7551. }
  7552. else {
  7553. result = PyErr_SetFromWindowsErr(error);
  7554. }
  7555. PssFreeSnapshot(process, snapshot);
  7556. return result;
  7557. }
  7558. #endif /*MS_WINDOWS*/
  7559. /*[clinic input]
  7560. os.getppid
  7561. Return the parent's process id.
  7562. If the parent process has already exited, Windows machines will still
  7563. return its id; others systems will return the id of the 'init' process (1).
  7564. [clinic start generated code]*/
  7565. static PyObject *
  7566. os_getppid_impl(PyObject *module)
  7567. /*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
  7568. {
  7569. #ifdef MS_WINDOWS
  7570. return win32_getppid();
  7571. #else
  7572. return PyLong_FromPid(getppid());
  7573. #endif
  7574. }
  7575. #endif /* HAVE_GETPPID */
  7576. #ifdef HAVE_GETLOGIN
  7577. /*[clinic input]
  7578. os.getlogin
  7579. Return the actual login name.
  7580. [clinic start generated code]*/
  7581. static PyObject *
  7582. os_getlogin_impl(PyObject *module)
  7583. /*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
  7584. {
  7585. PyObject *result = NULL;
  7586. #ifdef MS_WINDOWS
  7587. wchar_t user_name[UNLEN + 1];
  7588. DWORD num_chars = Py_ARRAY_LENGTH(user_name);
  7589. if (GetUserNameW(user_name, &num_chars)) {
  7590. /* num_chars is the number of unicode chars plus null terminator */
  7591. result = PyUnicode_FromWideChar(user_name, num_chars - 1);
  7592. }
  7593. else
  7594. result = PyErr_SetFromWindowsErr(GetLastError());
  7595. #else
  7596. char *name;
  7597. int old_errno = errno;
  7598. errno = 0;
  7599. name = getlogin();
  7600. if (name == NULL) {
  7601. if (errno)
  7602. posix_error();
  7603. else
  7604. PyErr_SetString(PyExc_OSError, "unable to determine login name");
  7605. }
  7606. else
  7607. result = PyUnicode_DecodeFSDefault(name);
  7608. errno = old_errno;
  7609. #endif
  7610. return result;
  7611. }
  7612. #endif /* HAVE_GETLOGIN */
  7613. #ifdef HAVE_GETUID
  7614. /*[clinic input]
  7615. os.getuid
  7616. Return the current process's user id.
  7617. [clinic start generated code]*/
  7618. static PyObject *
  7619. os_getuid_impl(PyObject *module)
  7620. /*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
  7621. {
  7622. return _PyLong_FromUid(getuid());
  7623. }
  7624. #endif /* HAVE_GETUID */
  7625. #ifdef MS_WINDOWS
  7626. #define HAVE_KILL
  7627. #endif /* MS_WINDOWS */
  7628. #ifdef HAVE_KILL
  7629. /*[clinic input]
  7630. os.kill
  7631. pid: pid_t
  7632. signal: Py_ssize_t
  7633. /
  7634. Kill a process with a signal.
  7635. [clinic start generated code]*/
  7636. static PyObject *
  7637. os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
  7638. /*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
  7639. {
  7640. if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
  7641. return NULL;
  7642. }
  7643. #ifndef MS_WINDOWS
  7644. if (kill(pid, (int)signal) == -1) {
  7645. return posix_error();
  7646. }
  7647. // Check immediately if the signal was sent to the current process.
  7648. // Don't micro-optimize pid == getpid(), since PyErr_SetString() check
  7649. // is cheap.
  7650. if (PyErr_CheckSignals()) {
  7651. return NULL;
  7652. }
  7653. Py_RETURN_NONE;
  7654. #else /* !MS_WINDOWS */
  7655. PyObject *result;
  7656. DWORD sig = (DWORD)signal;
  7657. DWORD err;
  7658. HANDLE handle;
  7659. #ifdef HAVE_WINDOWS_CONSOLE_IO
  7660. /* Console processes which share a common console can be sent CTRL+C or
  7661. CTRL+BREAK events, provided they handle said events. */
  7662. if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
  7663. if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
  7664. err = GetLastError();
  7665. PyErr_SetFromWindowsErr(err);
  7666. }
  7667. else {
  7668. Py_RETURN_NONE;
  7669. }
  7670. }
  7671. #endif /* HAVE_WINDOWS_CONSOLE_IO */
  7672. /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
  7673. attempt to open and terminate the process. */
  7674. handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
  7675. if (handle == NULL) {
  7676. err = GetLastError();
  7677. return PyErr_SetFromWindowsErr(err);
  7678. }
  7679. if (TerminateProcess(handle, sig) == 0) {
  7680. err = GetLastError();
  7681. result = PyErr_SetFromWindowsErr(err);
  7682. } else {
  7683. result = Py_NewRef(Py_None);
  7684. }
  7685. CloseHandle(handle);
  7686. return result;
  7687. #endif /* !MS_WINDOWS */
  7688. }
  7689. #endif /* HAVE_KILL */
  7690. #ifdef HAVE_KILLPG
  7691. /*[clinic input]
  7692. os.killpg
  7693. pgid: pid_t
  7694. signal: int
  7695. /
  7696. Kill a process group with a signal.
  7697. [clinic start generated code]*/
  7698. static PyObject *
  7699. os_killpg_impl(PyObject *module, pid_t pgid, int signal)
  7700. /*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
  7701. {
  7702. if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
  7703. return NULL;
  7704. }
  7705. /* XXX some man pages make the `pgid` parameter an int, others
  7706. a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
  7707. take the same type. Moreover, pid_t is always at least as wide as
  7708. int (else compilation of this module fails), which is safe. */
  7709. if (killpg(pgid, signal) == -1)
  7710. return posix_error();
  7711. Py_RETURN_NONE;
  7712. }
  7713. #endif /* HAVE_KILLPG */
  7714. #ifdef HAVE_PLOCK
  7715. #ifdef HAVE_SYS_LOCK_H
  7716. #include <sys/lock.h>
  7717. #endif
  7718. /*[clinic input]
  7719. os.plock
  7720. op: int
  7721. /
  7722. Lock program segments into memory.");
  7723. [clinic start generated code]*/
  7724. static PyObject *
  7725. os_plock_impl(PyObject *module, int op)
  7726. /*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
  7727. {
  7728. if (plock(op) == -1)
  7729. return posix_error();
  7730. Py_RETURN_NONE;
  7731. }
  7732. #endif /* HAVE_PLOCK */
  7733. #ifdef HAVE_SETUID
  7734. /*[clinic input]
  7735. os.setuid
  7736. uid: uid_t
  7737. /
  7738. Set the current process's user id.
  7739. [clinic start generated code]*/
  7740. static PyObject *
  7741. os_setuid_impl(PyObject *module, uid_t uid)
  7742. /*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
  7743. {
  7744. if (setuid(uid) < 0)
  7745. return posix_error();
  7746. Py_RETURN_NONE;
  7747. }
  7748. #endif /* HAVE_SETUID */
  7749. #ifdef HAVE_SETEUID
  7750. /*[clinic input]
  7751. os.seteuid
  7752. euid: uid_t
  7753. /
  7754. Set the current process's effective user id.
  7755. [clinic start generated code]*/
  7756. static PyObject *
  7757. os_seteuid_impl(PyObject *module, uid_t euid)
  7758. /*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
  7759. {
  7760. if (seteuid(euid) < 0)
  7761. return posix_error();
  7762. Py_RETURN_NONE;
  7763. }
  7764. #endif /* HAVE_SETEUID */
  7765. #ifdef HAVE_SETEGID
  7766. /*[clinic input]
  7767. os.setegid
  7768. egid: gid_t
  7769. /
  7770. Set the current process's effective group id.
  7771. [clinic start generated code]*/
  7772. static PyObject *
  7773. os_setegid_impl(PyObject *module, gid_t egid)
  7774. /*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
  7775. {
  7776. if (setegid(egid) < 0)
  7777. return posix_error();
  7778. Py_RETURN_NONE;
  7779. }
  7780. #endif /* HAVE_SETEGID */
  7781. #ifdef HAVE_SETREUID
  7782. /*[clinic input]
  7783. os.setreuid
  7784. ruid: uid_t
  7785. euid: uid_t
  7786. /
  7787. Set the current process's real and effective user ids.
  7788. [clinic start generated code]*/
  7789. static PyObject *
  7790. os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
  7791. /*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
  7792. {
  7793. if (setreuid(ruid, euid) < 0) {
  7794. return posix_error();
  7795. } else {
  7796. Py_RETURN_NONE;
  7797. }
  7798. }
  7799. #endif /* HAVE_SETREUID */
  7800. #ifdef HAVE_SETREGID
  7801. /*[clinic input]
  7802. os.setregid
  7803. rgid: gid_t
  7804. egid: gid_t
  7805. /
  7806. Set the current process's real and effective group ids.
  7807. [clinic start generated code]*/
  7808. static PyObject *
  7809. os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
  7810. /*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
  7811. {
  7812. if (setregid(rgid, egid) < 0)
  7813. return posix_error();
  7814. Py_RETURN_NONE;
  7815. }
  7816. #endif /* HAVE_SETREGID */
  7817. #ifdef HAVE_SETGID
  7818. /*[clinic input]
  7819. os.setgid
  7820. gid: gid_t
  7821. /
  7822. Set the current process's group id.
  7823. [clinic start generated code]*/
  7824. static PyObject *
  7825. os_setgid_impl(PyObject *module, gid_t gid)
  7826. /*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
  7827. {
  7828. if (setgid(gid) < 0)
  7829. return posix_error();
  7830. Py_RETURN_NONE;
  7831. }
  7832. #endif /* HAVE_SETGID */
  7833. #ifdef HAVE_SETGROUPS
  7834. /*[clinic input]
  7835. os.setgroups
  7836. groups: object
  7837. /
  7838. Set the groups of the current process to list.
  7839. [clinic start generated code]*/
  7840. static PyObject *
  7841. os_setgroups(PyObject *module, PyObject *groups)
  7842. /*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
  7843. {
  7844. if (!PySequence_Check(groups)) {
  7845. PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
  7846. return NULL;
  7847. }
  7848. Py_ssize_t len = PySequence_Size(groups);
  7849. if (len < 0) {
  7850. return NULL;
  7851. }
  7852. if (len > MAX_GROUPS) {
  7853. PyErr_SetString(PyExc_ValueError, "too many groups");
  7854. return NULL;
  7855. }
  7856. gid_t *grouplist = PyMem_New(gid_t, len);
  7857. for (Py_ssize_t i = 0; i < len; i++) {
  7858. PyObject *elem;
  7859. elem = PySequence_GetItem(groups, i);
  7860. if (!elem) {
  7861. PyMem_Free(grouplist);
  7862. return NULL;
  7863. }
  7864. if (!PyLong_Check(elem)) {
  7865. PyErr_SetString(PyExc_TypeError,
  7866. "groups must be integers");
  7867. Py_DECREF(elem);
  7868. PyMem_Free(grouplist);
  7869. return NULL;
  7870. } else {
  7871. if (!_Py_Gid_Converter(elem, &grouplist[i])) {
  7872. Py_DECREF(elem);
  7873. PyMem_Free(grouplist);
  7874. return NULL;
  7875. }
  7876. }
  7877. Py_DECREF(elem);
  7878. }
  7879. if (setgroups(len, grouplist) < 0) {
  7880. posix_error();
  7881. PyMem_Free(grouplist);
  7882. return NULL;
  7883. }
  7884. PyMem_Free(grouplist);
  7885. Py_RETURN_NONE;
  7886. }
  7887. #endif /* HAVE_SETGROUPS */
  7888. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  7889. static PyObject *
  7890. wait_helper(PyObject *module, pid_t pid, int status, struct rusage *ru)
  7891. {
  7892. PyObject *result;
  7893. PyObject *struct_rusage;
  7894. if (pid == -1)
  7895. return posix_error();
  7896. // If wait succeeded but no child was ready to report status, ru will not
  7897. // have been populated.
  7898. if (pid == 0) {
  7899. memset(ru, 0, sizeof(*ru));
  7900. }
  7901. struct_rusage = _PyImport_GetModuleAttrString("resource", "struct_rusage");
  7902. if (struct_rusage == NULL)
  7903. return NULL;
  7904. /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
  7905. result = PyStructSequence_New((PyTypeObject*) struct_rusage);
  7906. Py_DECREF(struct_rusage);
  7907. if (!result)
  7908. return NULL;
  7909. #ifndef doubletime
  7910. #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
  7911. #endif
  7912. PyStructSequence_SET_ITEM(result, 0,
  7913. PyFloat_FromDouble(doubletime(ru->ru_utime)));
  7914. PyStructSequence_SET_ITEM(result, 1,
  7915. PyFloat_FromDouble(doubletime(ru->ru_stime)));
  7916. #define SET_INT(result, index, value)\
  7917. PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
  7918. SET_INT(result, 2, ru->ru_maxrss);
  7919. SET_INT(result, 3, ru->ru_ixrss);
  7920. SET_INT(result, 4, ru->ru_idrss);
  7921. SET_INT(result, 5, ru->ru_isrss);
  7922. SET_INT(result, 6, ru->ru_minflt);
  7923. SET_INT(result, 7, ru->ru_majflt);
  7924. SET_INT(result, 8, ru->ru_nswap);
  7925. SET_INT(result, 9, ru->ru_inblock);
  7926. SET_INT(result, 10, ru->ru_oublock);
  7927. SET_INT(result, 11, ru->ru_msgsnd);
  7928. SET_INT(result, 12, ru->ru_msgrcv);
  7929. SET_INT(result, 13, ru->ru_nsignals);
  7930. SET_INT(result, 14, ru->ru_nvcsw);
  7931. SET_INT(result, 15, ru->ru_nivcsw);
  7932. #undef SET_INT
  7933. if (PyErr_Occurred()) {
  7934. Py_DECREF(result);
  7935. return NULL;
  7936. }
  7937. return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
  7938. }
  7939. #endif /* HAVE_WAIT3 || HAVE_WAIT4 */
  7940. #ifdef HAVE_WAIT3
  7941. /*[clinic input]
  7942. os.wait3
  7943. options: int
  7944. Wait for completion of a child process.
  7945. Returns a tuple of information about the child process:
  7946. (pid, status, rusage)
  7947. [clinic start generated code]*/
  7948. static PyObject *
  7949. os_wait3_impl(PyObject *module, int options)
  7950. /*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
  7951. {
  7952. pid_t pid;
  7953. struct rusage ru;
  7954. int async_err = 0;
  7955. WAIT_TYPE status;
  7956. WAIT_STATUS_INT(status) = 0;
  7957. do {
  7958. Py_BEGIN_ALLOW_THREADS
  7959. pid = wait3(&status, options, &ru);
  7960. Py_END_ALLOW_THREADS
  7961. } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  7962. if (pid < 0)
  7963. return (!async_err) ? posix_error() : NULL;
  7964. return wait_helper(module, pid, WAIT_STATUS_INT(status), &ru);
  7965. }
  7966. #endif /* HAVE_WAIT3 */
  7967. #ifdef HAVE_WAIT4
  7968. /*[clinic input]
  7969. os.wait4
  7970. pid: pid_t
  7971. options: int
  7972. Wait for completion of a specific child process.
  7973. Returns a tuple of information about the child process:
  7974. (pid, status, rusage)
  7975. [clinic start generated code]*/
  7976. static PyObject *
  7977. os_wait4_impl(PyObject *module, pid_t pid, int options)
  7978. /*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
  7979. {
  7980. pid_t res;
  7981. struct rusage ru;
  7982. int async_err = 0;
  7983. WAIT_TYPE status;
  7984. WAIT_STATUS_INT(status) = 0;
  7985. do {
  7986. Py_BEGIN_ALLOW_THREADS
  7987. res = wait4(pid, &status, options, &ru);
  7988. Py_END_ALLOW_THREADS
  7989. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  7990. if (res < 0)
  7991. return (!async_err) ? posix_error() : NULL;
  7992. return wait_helper(module, res, WAIT_STATUS_INT(status), &ru);
  7993. }
  7994. #endif /* HAVE_WAIT4 */
  7995. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  7996. /*[clinic input]
  7997. os.waitid
  7998. idtype: idtype_t
  7999. Must be one of be P_PID, P_PGID or P_ALL.
  8000. id: id_t
  8001. The id to wait on.
  8002. options: int
  8003. Constructed from the ORing of one or more of WEXITED, WSTOPPED
  8004. or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
  8005. /
  8006. Returns the result of waiting for a process or processes.
  8007. Returns either waitid_result or None if WNOHANG is specified and there are
  8008. no children in a waitable state.
  8009. [clinic start generated code]*/
  8010. static PyObject *
  8011. os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
  8012. /*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
  8013. {
  8014. PyObject *result;
  8015. int res;
  8016. int async_err = 0;
  8017. siginfo_t si;
  8018. si.si_pid = 0;
  8019. do {
  8020. Py_BEGIN_ALLOW_THREADS
  8021. res = waitid(idtype, id, &si, options);
  8022. Py_END_ALLOW_THREADS
  8023. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8024. if (res < 0)
  8025. return (!async_err) ? posix_error() : NULL;
  8026. if (si.si_pid == 0)
  8027. Py_RETURN_NONE;
  8028. PyObject *WaitidResultType = get_posix_state(module)->WaitidResultType;
  8029. result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
  8030. if (!result)
  8031. return NULL;
  8032. PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
  8033. PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
  8034. PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
  8035. PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
  8036. PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
  8037. if (PyErr_Occurred()) {
  8038. Py_DECREF(result);
  8039. return NULL;
  8040. }
  8041. return result;
  8042. }
  8043. #endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
  8044. #if defined(HAVE_WAITPID)
  8045. /*[clinic input]
  8046. os.waitpid
  8047. pid: pid_t
  8048. options: int
  8049. /
  8050. Wait for completion of a given child process.
  8051. Returns a tuple of information regarding the child process:
  8052. (pid, status)
  8053. The options argument is ignored on Windows.
  8054. [clinic start generated code]*/
  8055. static PyObject *
  8056. os_waitpid_impl(PyObject *module, pid_t pid, int options)
  8057. /*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
  8058. {
  8059. pid_t res;
  8060. int async_err = 0;
  8061. WAIT_TYPE status;
  8062. WAIT_STATUS_INT(status) = 0;
  8063. do {
  8064. Py_BEGIN_ALLOW_THREADS
  8065. res = waitpid(pid, &status, options);
  8066. Py_END_ALLOW_THREADS
  8067. } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8068. if (res < 0)
  8069. return (!async_err) ? posix_error() : NULL;
  8070. return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
  8071. }
  8072. #elif defined(HAVE_CWAIT)
  8073. /* MS C has a variant of waitpid() that's usable for most purposes. */
  8074. /*[clinic input]
  8075. os.waitpid
  8076. pid: intptr_t
  8077. options: int
  8078. /
  8079. Wait for completion of a given process.
  8080. Returns a tuple of information regarding the process:
  8081. (pid, status << 8)
  8082. The options argument is ignored on Windows.
  8083. [clinic start generated code]*/
  8084. static PyObject *
  8085. os_waitpid_impl(PyObject *module, intptr_t pid, int options)
  8086. /*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
  8087. {
  8088. int status;
  8089. intptr_t res;
  8090. int async_err = 0;
  8091. do {
  8092. Py_BEGIN_ALLOW_THREADS
  8093. _Py_BEGIN_SUPPRESS_IPH
  8094. res = _cwait(&status, pid, options);
  8095. _Py_END_SUPPRESS_IPH
  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. unsigned long long ustatus = (unsigned int)status;
  8101. /* shift the status left a byte so this is more like the POSIX waitpid */
  8102. return Py_BuildValue(_Py_PARSE_INTPTR "K", res, ustatus << 8);
  8103. }
  8104. #endif
  8105. #ifdef HAVE_WAIT
  8106. /*[clinic input]
  8107. os.wait
  8108. Wait for completion of a child process.
  8109. Returns a tuple of information about the child process:
  8110. (pid, status)
  8111. [clinic start generated code]*/
  8112. static PyObject *
  8113. os_wait_impl(PyObject *module)
  8114. /*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
  8115. {
  8116. pid_t pid;
  8117. int async_err = 0;
  8118. WAIT_TYPE status;
  8119. WAIT_STATUS_INT(status) = 0;
  8120. do {
  8121. Py_BEGIN_ALLOW_THREADS
  8122. pid = wait(&status);
  8123. Py_END_ALLOW_THREADS
  8124. } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8125. if (pid < 0)
  8126. return (!async_err) ? posix_error() : NULL;
  8127. return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
  8128. }
  8129. #endif /* HAVE_WAIT */
  8130. #if defined(__linux__) && defined(__NR_pidfd_open)
  8131. /*[clinic input]
  8132. os.pidfd_open
  8133. pid: pid_t
  8134. flags: unsigned_int = 0
  8135. Return a file descriptor referring to the process *pid*.
  8136. The descriptor can be used to perform process management without races and
  8137. signals.
  8138. [clinic start generated code]*/
  8139. static PyObject *
  8140. os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
  8141. /*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
  8142. {
  8143. int fd = syscall(__NR_pidfd_open, pid, flags);
  8144. if (fd < 0) {
  8145. return posix_error();
  8146. }
  8147. return PyLong_FromLong(fd);
  8148. }
  8149. #endif
  8150. #ifdef HAVE_SETNS
  8151. /*[clinic input]
  8152. os.setns
  8153. fd: fildes
  8154. A file descriptor to a namespace.
  8155. nstype: int = 0
  8156. Type of namespace.
  8157. Move the calling thread into different namespaces.
  8158. [clinic start generated code]*/
  8159. static PyObject *
  8160. os_setns_impl(PyObject *module, int fd, int nstype)
  8161. /*[clinic end generated code: output=5dbd055bfb66ecd0 input=42787871226bf3ee]*/
  8162. {
  8163. int res;
  8164. Py_BEGIN_ALLOW_THREADS
  8165. res = setns(fd, nstype);
  8166. Py_END_ALLOW_THREADS
  8167. if (res != 0) {
  8168. return posix_error();
  8169. }
  8170. Py_RETURN_NONE;
  8171. }
  8172. #endif
  8173. #ifdef HAVE_UNSHARE
  8174. /*[clinic input]
  8175. os.unshare
  8176. flags: int
  8177. Namespaces to be unshared.
  8178. Disassociate parts of a process (or thread) execution context.
  8179. [clinic start generated code]*/
  8180. static PyObject *
  8181. os_unshare_impl(PyObject *module, int flags)
  8182. /*[clinic end generated code: output=1b3177906dd237ee input=9e065db3232b8b1b]*/
  8183. {
  8184. int res;
  8185. Py_BEGIN_ALLOW_THREADS
  8186. res = unshare(flags);
  8187. Py_END_ALLOW_THREADS
  8188. if (res != 0) {
  8189. return posix_error();
  8190. }
  8191. Py_RETURN_NONE;
  8192. }
  8193. #endif
  8194. #if defined(HAVE_READLINK) || defined(MS_WINDOWS)
  8195. /*[clinic input]
  8196. os.readlink
  8197. path: path_t
  8198. *
  8199. dir_fd: dir_fd(requires='readlinkat') = None
  8200. Return a string representing the path to which the symbolic link points.
  8201. If dir_fd is not None, it should be a file descriptor open to a directory,
  8202. and path should be relative; path will then be relative to that directory.
  8203. dir_fd may not be implemented on your platform. If it is unavailable,
  8204. using it will raise a NotImplementedError.
  8205. [clinic start generated code]*/
  8206. static PyObject *
  8207. os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
  8208. /*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
  8209. {
  8210. #if defined(HAVE_READLINK)
  8211. char buffer[MAXPATHLEN+1];
  8212. ssize_t length;
  8213. #ifdef HAVE_READLINKAT
  8214. int readlinkat_unavailable = 0;
  8215. #endif
  8216. Py_BEGIN_ALLOW_THREADS
  8217. #ifdef HAVE_READLINKAT
  8218. if (dir_fd != DEFAULT_DIR_FD) {
  8219. if (HAVE_READLINKAT_RUNTIME) {
  8220. length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
  8221. } else {
  8222. readlinkat_unavailable = 1;
  8223. }
  8224. } else
  8225. #endif
  8226. length = readlink(path->narrow, buffer, MAXPATHLEN);
  8227. Py_END_ALLOW_THREADS
  8228. #ifdef HAVE_READLINKAT
  8229. if (readlinkat_unavailable) {
  8230. argument_unavailable_error(NULL, "dir_fd");
  8231. return NULL;
  8232. }
  8233. #endif
  8234. if (length < 0) {
  8235. return path_error(path);
  8236. }
  8237. buffer[length] = '\0';
  8238. if (PyUnicode_Check(path->object))
  8239. return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
  8240. else
  8241. return PyBytes_FromStringAndSize(buffer, length);
  8242. #elif defined(MS_WINDOWS)
  8243. DWORD n_bytes_returned;
  8244. DWORD io_result = 0;
  8245. HANDLE reparse_point_handle;
  8246. char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
  8247. _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
  8248. PyObject *result = NULL;
  8249. /* First get a handle to the reparse point */
  8250. Py_BEGIN_ALLOW_THREADS
  8251. reparse_point_handle = CreateFileW(
  8252. path->wide,
  8253. 0,
  8254. 0,
  8255. 0,
  8256. OPEN_EXISTING,
  8257. FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
  8258. 0);
  8259. if (reparse_point_handle != INVALID_HANDLE_VALUE) {
  8260. /* New call DeviceIoControl to read the reparse point */
  8261. io_result = DeviceIoControl(
  8262. reparse_point_handle,
  8263. FSCTL_GET_REPARSE_POINT,
  8264. 0, 0, /* in buffer */
  8265. target_buffer, sizeof(target_buffer),
  8266. &n_bytes_returned,
  8267. 0 /* we're not using OVERLAPPED_IO */
  8268. );
  8269. CloseHandle(reparse_point_handle);
  8270. }
  8271. Py_END_ALLOW_THREADS
  8272. if (io_result == 0) {
  8273. return path_error(path);
  8274. }
  8275. wchar_t *name = NULL;
  8276. Py_ssize_t nameLen = 0;
  8277. if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
  8278. {
  8279. name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
  8280. rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
  8281. nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
  8282. }
  8283. else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
  8284. {
  8285. name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
  8286. rdb->MountPointReparseBuffer.SubstituteNameOffset);
  8287. nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
  8288. }
  8289. else
  8290. {
  8291. PyErr_SetString(PyExc_ValueError, "not a symbolic link");
  8292. }
  8293. if (name) {
  8294. if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
  8295. /* Our buffer is mutable, so this is okay */
  8296. name[1] = L'\\';
  8297. }
  8298. result = PyUnicode_FromWideChar(name, nameLen);
  8299. if (result && path->narrow) {
  8300. Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
  8301. }
  8302. }
  8303. return result;
  8304. #endif
  8305. }
  8306. #endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
  8307. #if defined(MS_WINDOWS)
  8308. /* Remove the last portion of the path - return 0 on success */
  8309. static int
  8310. _dirnameW(WCHAR *path)
  8311. {
  8312. WCHAR *ptr;
  8313. size_t length = wcsnlen_s(path, MAX_PATH);
  8314. if (length == MAX_PATH) {
  8315. return -1;
  8316. }
  8317. /* walk the path from the end until a backslash is encountered */
  8318. for(ptr = path + length; ptr != path; ptr--) {
  8319. if (*ptr == L'\\' || *ptr == L'/') {
  8320. break;
  8321. }
  8322. }
  8323. *ptr = 0;
  8324. return 0;
  8325. }
  8326. #endif
  8327. #ifdef HAVE_SYMLINK
  8328. #if defined(MS_WINDOWS)
  8329. /* Is this path absolute? */
  8330. static int
  8331. _is_absW(const WCHAR *path)
  8332. {
  8333. return path[0] == L'\\' || path[0] == L'/' ||
  8334. (path[0] && path[1] == L':');
  8335. }
  8336. /* join root and rest with a backslash - return 0 on success */
  8337. static int
  8338. _joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
  8339. {
  8340. if (_is_absW(rest)) {
  8341. return wcscpy_s(dest_path, MAX_PATH, rest);
  8342. }
  8343. if (wcscpy_s(dest_path, MAX_PATH, root)) {
  8344. return -1;
  8345. }
  8346. if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
  8347. return -1;
  8348. }
  8349. return wcscat_s(dest_path, MAX_PATH, rest);
  8350. }
  8351. /* Return True if the path at src relative to dest is a directory */
  8352. static int
  8353. _check_dirW(LPCWSTR src, LPCWSTR dest)
  8354. {
  8355. WIN32_FILE_ATTRIBUTE_DATA src_info;
  8356. WCHAR dest_parent[MAX_PATH];
  8357. WCHAR src_resolved[MAX_PATH] = L"";
  8358. /* dest_parent = os.path.dirname(dest) */
  8359. if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
  8360. _dirnameW(dest_parent)) {
  8361. return 0;
  8362. }
  8363. /* src_resolved = os.path.join(dest_parent, src) */
  8364. if (_joinW(src_resolved, dest_parent, src)) {
  8365. return 0;
  8366. }
  8367. return (
  8368. GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
  8369. && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
  8370. );
  8371. }
  8372. #endif
  8373. /*[clinic input]
  8374. os.symlink
  8375. src: path_t
  8376. dst: path_t
  8377. target_is_directory: bool = False
  8378. *
  8379. dir_fd: dir_fd(requires='symlinkat')=None
  8380. # "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
  8381. Create a symbolic link pointing to src named dst.
  8382. target_is_directory is required on Windows if the target is to be
  8383. interpreted as a directory. (On Windows, symlink requires
  8384. Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
  8385. target_is_directory is ignored on non-Windows platforms.
  8386. If dir_fd is not None, it should be a file descriptor open to a directory,
  8387. and path should be relative; path will then be relative to that directory.
  8388. dir_fd may not be implemented on your platform.
  8389. If it is unavailable, using it will raise a NotImplementedError.
  8390. [clinic start generated code]*/
  8391. static PyObject *
  8392. os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
  8393. int target_is_directory, int dir_fd)
  8394. /*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
  8395. {
  8396. #ifdef MS_WINDOWS
  8397. DWORD result;
  8398. DWORD flags = 0;
  8399. /* Assumed true, set to false if detected to not be available. */
  8400. static int windows_has_symlink_unprivileged_flag = TRUE;
  8401. #else
  8402. int result;
  8403. #ifdef HAVE_SYMLINKAT
  8404. int symlinkat_unavailable = 0;
  8405. #endif
  8406. #endif
  8407. if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
  8408. dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
  8409. return NULL;
  8410. }
  8411. #ifdef MS_WINDOWS
  8412. if (windows_has_symlink_unprivileged_flag) {
  8413. /* Allow non-admin symlinks if system allows it. */
  8414. flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
  8415. }
  8416. Py_BEGIN_ALLOW_THREADS
  8417. _Py_BEGIN_SUPPRESS_IPH
  8418. /* if src is a directory, ensure flags==1 (target_is_directory bit) */
  8419. if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
  8420. flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
  8421. }
  8422. result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
  8423. _Py_END_SUPPRESS_IPH
  8424. Py_END_ALLOW_THREADS
  8425. if (windows_has_symlink_unprivileged_flag && !result &&
  8426. ERROR_INVALID_PARAMETER == GetLastError()) {
  8427. Py_BEGIN_ALLOW_THREADS
  8428. _Py_BEGIN_SUPPRESS_IPH
  8429. /* This error might be caused by
  8430. SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
  8431. Try again, and update windows_has_symlink_unprivileged_flag if we
  8432. are successful this time.
  8433. NOTE: There is a risk of a race condition here if there are other
  8434. conditions than the flag causing ERROR_INVALID_PARAMETER, and
  8435. another process (or thread) changes that condition in between our
  8436. calls to CreateSymbolicLink.
  8437. */
  8438. flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
  8439. result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
  8440. _Py_END_SUPPRESS_IPH
  8441. Py_END_ALLOW_THREADS
  8442. if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
  8443. windows_has_symlink_unprivileged_flag = FALSE;
  8444. }
  8445. }
  8446. if (!result)
  8447. return path_error2(src, dst);
  8448. #else
  8449. if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
  8450. PyErr_SetString(PyExc_ValueError,
  8451. "symlink: src and dst must be the same type");
  8452. return NULL;
  8453. }
  8454. Py_BEGIN_ALLOW_THREADS
  8455. #ifdef HAVE_SYMLINKAT
  8456. if (dir_fd != DEFAULT_DIR_FD) {
  8457. if (HAVE_SYMLINKAT_RUNTIME) {
  8458. result = symlinkat(src->narrow, dir_fd, dst->narrow);
  8459. } else {
  8460. symlinkat_unavailable = 1;
  8461. }
  8462. } else
  8463. #endif
  8464. result = symlink(src->narrow, dst->narrow);
  8465. Py_END_ALLOW_THREADS
  8466. #ifdef HAVE_SYMLINKAT
  8467. if (symlinkat_unavailable) {
  8468. argument_unavailable_error(NULL, "dir_fd");
  8469. return NULL;
  8470. }
  8471. #endif
  8472. if (result)
  8473. return path_error2(src, dst);
  8474. #endif
  8475. Py_RETURN_NONE;
  8476. }
  8477. #endif /* HAVE_SYMLINK */
  8478. static PyStructSequence_Field times_result_fields[] = {
  8479. {"user", "user time"},
  8480. {"system", "system time"},
  8481. {"children_user", "user time of children"},
  8482. {"children_system", "system time of children"},
  8483. {"elapsed", "elapsed time since an arbitrary point in the past"},
  8484. {NULL}
  8485. };
  8486. PyDoc_STRVAR(times_result__doc__,
  8487. "times_result: Result from os.times().\n\n\
  8488. This object may be accessed either as a tuple of\n\
  8489. (user, system, children_user, children_system, elapsed),\n\
  8490. or via the attributes user, system, children_user, children_system,\n\
  8491. and elapsed.\n\
  8492. \n\
  8493. See os.times for more information.");
  8494. static PyStructSequence_Desc times_result_desc = {
  8495. "times_result", /* name */
  8496. times_result__doc__, /* doc */
  8497. times_result_fields,
  8498. 5
  8499. };
  8500. #ifdef MS_WINDOWS
  8501. #define HAVE_TIMES /* mandatory, for the method table */
  8502. #endif
  8503. #ifdef HAVE_TIMES
  8504. static PyObject *
  8505. build_times_result(PyObject *module, double user, double system,
  8506. double children_user, double children_system,
  8507. double elapsed)
  8508. {
  8509. PyObject *TimesResultType = get_posix_state(module)->TimesResultType;
  8510. PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
  8511. if (value == NULL)
  8512. return NULL;
  8513. #define SET(i, field) \
  8514. { \
  8515. PyObject *o = PyFloat_FromDouble(field); \
  8516. if (!o) { \
  8517. Py_DECREF(value); \
  8518. return NULL; \
  8519. } \
  8520. PyStructSequence_SET_ITEM(value, i, o); \
  8521. } \
  8522. SET(0, user);
  8523. SET(1, system);
  8524. SET(2, children_user);
  8525. SET(3, children_system);
  8526. SET(4, elapsed);
  8527. #undef SET
  8528. return value;
  8529. }
  8530. /*[clinic input]
  8531. os.times
  8532. Return a collection containing process timing information.
  8533. The object returned behaves like a named tuple with these fields:
  8534. (utime, stime, cutime, cstime, elapsed_time)
  8535. All fields are floating point numbers.
  8536. [clinic start generated code]*/
  8537. static PyObject *
  8538. os_times_impl(PyObject *module)
  8539. /*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
  8540. #ifdef MS_WINDOWS
  8541. {
  8542. FILETIME create, exit, kernel, user;
  8543. HANDLE hProc;
  8544. hProc = GetCurrentProcess();
  8545. GetProcessTimes(hProc, &create, &exit, &kernel, &user);
  8546. /* The fields of a FILETIME structure are the hi and lo part
  8547. of a 64-bit value expressed in 100 nanosecond units.
  8548. 1e7 is one second in such units; 1e-7 the inverse.
  8549. 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
  8550. */
  8551. return build_times_result(module,
  8552. (double)(user.dwHighDateTime*429.4967296 +
  8553. user.dwLowDateTime*1e-7),
  8554. (double)(kernel.dwHighDateTime*429.4967296 +
  8555. kernel.dwLowDateTime*1e-7),
  8556. (double)0,
  8557. (double)0,
  8558. (double)0);
  8559. }
  8560. #else /* MS_WINDOWS */
  8561. {
  8562. struct tms t;
  8563. clock_t c;
  8564. errno = 0;
  8565. c = times(&t);
  8566. if (c == (clock_t) -1) {
  8567. return posix_error();
  8568. }
  8569. assert(_PyRuntime.time.ticks_per_second_initialized);
  8570. #define ticks_per_second _PyRuntime.time.ticks_per_second
  8571. return build_times_result(module,
  8572. (double)t.tms_utime / ticks_per_second,
  8573. (double)t.tms_stime / ticks_per_second,
  8574. (double)t.tms_cutime / ticks_per_second,
  8575. (double)t.tms_cstime / ticks_per_second,
  8576. (double)c / ticks_per_second);
  8577. #undef ticks_per_second
  8578. }
  8579. #endif /* MS_WINDOWS */
  8580. #endif /* HAVE_TIMES */
  8581. #ifdef HAVE_GETSID
  8582. /*[clinic input]
  8583. os.getsid
  8584. pid: pid_t
  8585. /
  8586. Call the system call getsid(pid) and return the result.
  8587. [clinic start generated code]*/
  8588. static PyObject *
  8589. os_getsid_impl(PyObject *module, pid_t pid)
  8590. /*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
  8591. {
  8592. int sid;
  8593. sid = getsid(pid);
  8594. if (sid < 0)
  8595. return posix_error();
  8596. return PyLong_FromLong((long)sid);
  8597. }
  8598. #endif /* HAVE_GETSID */
  8599. #ifdef HAVE_SETSID
  8600. /*[clinic input]
  8601. os.setsid
  8602. Call the system call setsid().
  8603. [clinic start generated code]*/
  8604. static PyObject *
  8605. os_setsid_impl(PyObject *module)
  8606. /*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
  8607. {
  8608. if (setsid() < 0)
  8609. return posix_error();
  8610. Py_RETURN_NONE;
  8611. }
  8612. #endif /* HAVE_SETSID */
  8613. #ifdef HAVE_SETPGID
  8614. /*[clinic input]
  8615. os.setpgid
  8616. pid: pid_t
  8617. pgrp: pid_t
  8618. /
  8619. Call the system call setpgid(pid, pgrp).
  8620. [clinic start generated code]*/
  8621. static PyObject *
  8622. os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
  8623. /*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
  8624. {
  8625. if (setpgid(pid, pgrp) < 0)
  8626. return posix_error();
  8627. Py_RETURN_NONE;
  8628. }
  8629. #endif /* HAVE_SETPGID */
  8630. #ifdef HAVE_TCGETPGRP
  8631. /*[clinic input]
  8632. os.tcgetpgrp
  8633. fd: int
  8634. /
  8635. Return the process group associated with the terminal specified by fd.
  8636. [clinic start generated code]*/
  8637. static PyObject *
  8638. os_tcgetpgrp_impl(PyObject *module, int fd)
  8639. /*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
  8640. {
  8641. pid_t pgid = tcgetpgrp(fd);
  8642. if (pgid < 0)
  8643. return posix_error();
  8644. return PyLong_FromPid(pgid);
  8645. }
  8646. #endif /* HAVE_TCGETPGRP */
  8647. #ifdef HAVE_TCSETPGRP
  8648. /*[clinic input]
  8649. os.tcsetpgrp
  8650. fd: int
  8651. pgid: pid_t
  8652. /
  8653. Set the process group associated with the terminal specified by fd.
  8654. [clinic start generated code]*/
  8655. static PyObject *
  8656. os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
  8657. /*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
  8658. {
  8659. if (tcsetpgrp(fd, pgid) < 0)
  8660. return posix_error();
  8661. Py_RETURN_NONE;
  8662. }
  8663. #endif /* HAVE_TCSETPGRP */
  8664. /* Functions acting on file descriptors */
  8665. #ifdef O_CLOEXEC
  8666. extern int _Py_open_cloexec_works;
  8667. #endif
  8668. /*[clinic input]
  8669. os.open -> int
  8670. path: path_t
  8671. flags: int
  8672. mode: int = 0o777
  8673. *
  8674. dir_fd: dir_fd(requires='openat') = None
  8675. # "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
  8676. Open a file for low level IO. Returns a file descriptor (integer).
  8677. If dir_fd is not None, it should be a file descriptor open to a directory,
  8678. and path should be relative; path will then be relative to that directory.
  8679. dir_fd may not be implemented on your platform.
  8680. If it is unavailable, using it will raise a NotImplementedError.
  8681. [clinic start generated code]*/
  8682. static int
  8683. os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
  8684. /*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
  8685. {
  8686. int fd;
  8687. int async_err = 0;
  8688. #ifdef HAVE_OPENAT
  8689. int openat_unavailable = 0;
  8690. #endif
  8691. #ifdef O_CLOEXEC
  8692. int *atomic_flag_works = &_Py_open_cloexec_works;
  8693. #elif !defined(MS_WINDOWS)
  8694. int *atomic_flag_works = NULL;
  8695. #endif
  8696. #ifdef MS_WINDOWS
  8697. flags |= O_NOINHERIT;
  8698. #elif defined(O_CLOEXEC)
  8699. flags |= O_CLOEXEC;
  8700. #endif
  8701. if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
  8702. return -1;
  8703. }
  8704. _Py_BEGIN_SUPPRESS_IPH
  8705. do {
  8706. Py_BEGIN_ALLOW_THREADS
  8707. #ifdef MS_WINDOWS
  8708. fd = _wopen(path->wide, flags, mode);
  8709. #else
  8710. #ifdef HAVE_OPENAT
  8711. if (dir_fd != DEFAULT_DIR_FD) {
  8712. if (HAVE_OPENAT_RUNTIME) {
  8713. fd = openat(dir_fd, path->narrow, flags, mode);
  8714. } else {
  8715. openat_unavailable = 1;
  8716. fd = -1;
  8717. }
  8718. } else
  8719. #endif /* HAVE_OPENAT */
  8720. fd = open(path->narrow, flags, mode);
  8721. #endif /* !MS_WINDOWS */
  8722. Py_END_ALLOW_THREADS
  8723. } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  8724. _Py_END_SUPPRESS_IPH
  8725. #ifdef HAVE_OPENAT
  8726. if (openat_unavailable) {
  8727. argument_unavailable_error(NULL, "dir_fd");
  8728. return -1;
  8729. }
  8730. #endif
  8731. if (fd < 0) {
  8732. if (!async_err)
  8733. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
  8734. return -1;
  8735. }
  8736. #ifndef MS_WINDOWS
  8737. if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
  8738. close(fd);
  8739. return -1;
  8740. }
  8741. #endif
  8742. return fd;
  8743. }
  8744. /*[clinic input]
  8745. os.close
  8746. fd: int
  8747. Close a file descriptor.
  8748. [clinic start generated code]*/
  8749. static PyObject *
  8750. os_close_impl(PyObject *module, int fd)
  8751. /*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
  8752. {
  8753. int res;
  8754. /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
  8755. * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
  8756. * for more details.
  8757. */
  8758. Py_BEGIN_ALLOW_THREADS
  8759. _Py_BEGIN_SUPPRESS_IPH
  8760. res = close(fd);
  8761. _Py_END_SUPPRESS_IPH
  8762. Py_END_ALLOW_THREADS
  8763. if (res < 0)
  8764. return posix_error();
  8765. Py_RETURN_NONE;
  8766. }
  8767. /*[clinic input]
  8768. os.closerange
  8769. fd_low: int
  8770. fd_high: int
  8771. /
  8772. Closes all file descriptors in [fd_low, fd_high), ignoring errors.
  8773. [clinic start generated code]*/
  8774. static PyObject *
  8775. os_closerange_impl(PyObject *module, int fd_low, int fd_high)
  8776. /*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
  8777. {
  8778. Py_BEGIN_ALLOW_THREADS
  8779. _Py_closerange(fd_low, fd_high - 1);
  8780. Py_END_ALLOW_THREADS
  8781. Py_RETURN_NONE;
  8782. }
  8783. /*[clinic input]
  8784. os.dup -> int
  8785. fd: int
  8786. /
  8787. Return a duplicate of a file descriptor.
  8788. [clinic start generated code]*/
  8789. static int
  8790. os_dup_impl(PyObject *module, int fd)
  8791. /*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
  8792. {
  8793. return _Py_dup(fd);
  8794. }
  8795. // dup2() is either provided by libc or dup2.c with AC_REPLACE_FUNCS().
  8796. // dup2.c provides working dup2() if and only if F_DUPFD is available.
  8797. #if (defined(HAVE_DUP3) || defined(F_DUPFD) || defined(MS_WINDOWS))
  8798. /*[clinic input]
  8799. os.dup2 -> int
  8800. fd: int
  8801. fd2: int
  8802. inheritable: bool=True
  8803. Duplicate file descriptor.
  8804. [clinic start generated code]*/
  8805. static int
  8806. os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
  8807. /*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
  8808. {
  8809. int res = 0;
  8810. #if defined(HAVE_DUP3) && \
  8811. !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
  8812. /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
  8813. static int dup3_works = -1;
  8814. #endif
  8815. /* dup2() can fail with EINTR if the target FD is already open, because it
  8816. * then has to be closed. See os_close_impl() for why we don't handle EINTR
  8817. * upon close(), and therefore below.
  8818. */
  8819. #ifdef MS_WINDOWS
  8820. Py_BEGIN_ALLOW_THREADS
  8821. _Py_BEGIN_SUPPRESS_IPH
  8822. res = dup2(fd, fd2);
  8823. _Py_END_SUPPRESS_IPH
  8824. Py_END_ALLOW_THREADS
  8825. if (res < 0) {
  8826. posix_error();
  8827. return -1;
  8828. }
  8829. res = fd2; // msvcrt dup2 returns 0 on success.
  8830. /* Character files like console cannot be make non-inheritable */
  8831. if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
  8832. close(fd2);
  8833. return -1;
  8834. }
  8835. #elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
  8836. Py_BEGIN_ALLOW_THREADS
  8837. if (!inheritable)
  8838. res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
  8839. else
  8840. res = dup2(fd, fd2);
  8841. Py_END_ALLOW_THREADS
  8842. if (res < 0) {
  8843. posix_error();
  8844. return -1;
  8845. }
  8846. #else
  8847. #ifdef HAVE_DUP3
  8848. if (!inheritable && dup3_works != 0) {
  8849. Py_BEGIN_ALLOW_THREADS
  8850. res = dup3(fd, fd2, O_CLOEXEC);
  8851. Py_END_ALLOW_THREADS
  8852. if (res < 0) {
  8853. if (dup3_works == -1)
  8854. dup3_works = (errno != ENOSYS);
  8855. if (dup3_works) {
  8856. posix_error();
  8857. return -1;
  8858. }
  8859. }
  8860. }
  8861. if (inheritable || dup3_works == 0)
  8862. {
  8863. #endif
  8864. Py_BEGIN_ALLOW_THREADS
  8865. res = dup2(fd, fd2);
  8866. Py_END_ALLOW_THREADS
  8867. if (res < 0) {
  8868. posix_error();
  8869. return -1;
  8870. }
  8871. if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
  8872. close(fd2);
  8873. return -1;
  8874. }
  8875. #ifdef HAVE_DUP3
  8876. }
  8877. #endif
  8878. #endif
  8879. return res;
  8880. }
  8881. #endif
  8882. #ifdef HAVE_LOCKF
  8883. /*[clinic input]
  8884. os.lockf
  8885. fd: int
  8886. An open file descriptor.
  8887. command: int
  8888. One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
  8889. length: Py_off_t
  8890. The number of bytes to lock, starting at the current position.
  8891. /
  8892. Apply, test or remove a POSIX lock on an open file descriptor.
  8893. [clinic start generated code]*/
  8894. static PyObject *
  8895. os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
  8896. /*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
  8897. {
  8898. int res;
  8899. if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
  8900. return NULL;
  8901. }
  8902. Py_BEGIN_ALLOW_THREADS
  8903. res = lockf(fd, command, length);
  8904. Py_END_ALLOW_THREADS
  8905. if (res < 0)
  8906. return posix_error();
  8907. Py_RETURN_NONE;
  8908. }
  8909. #endif /* HAVE_LOCKF */
  8910. /*[clinic input]
  8911. os.lseek -> Py_off_t
  8912. fd: int
  8913. An open file descriptor, as returned by os.open().
  8914. position: Py_off_t
  8915. Position, interpreted relative to 'whence'.
  8916. whence as how: int
  8917. The relative position to seek from. Valid values are:
  8918. - SEEK_SET: seek from the start of the file.
  8919. - SEEK_CUR: seek from the current file position.
  8920. - SEEK_END: seek from the end of the file.
  8921. /
  8922. Set the position of a file descriptor. Return the new position.
  8923. The return value is the number of bytes relative to the beginning of the file.
  8924. [clinic start generated code]*/
  8925. static Py_off_t
  8926. os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
  8927. /*[clinic end generated code: output=971e1efb6b30bd2f input=f096e754c5367504]*/
  8928. {
  8929. Py_off_t result;
  8930. #ifdef SEEK_SET
  8931. /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
  8932. switch (how) {
  8933. case 0: how = SEEK_SET; break;
  8934. case 1: how = SEEK_CUR; break;
  8935. case 2: how = SEEK_END; break;
  8936. }
  8937. #endif /* SEEK_END */
  8938. Py_BEGIN_ALLOW_THREADS
  8939. _Py_BEGIN_SUPPRESS_IPH
  8940. #ifdef MS_WINDOWS
  8941. result = _lseeki64(fd, position, how);
  8942. #else
  8943. result = lseek(fd, position, how);
  8944. #endif
  8945. _Py_END_SUPPRESS_IPH
  8946. Py_END_ALLOW_THREADS
  8947. if (result < 0)
  8948. posix_error();
  8949. return result;
  8950. }
  8951. /*[clinic input]
  8952. os.read
  8953. fd: int
  8954. length: Py_ssize_t
  8955. /
  8956. Read from a file descriptor. Returns a bytes object.
  8957. [clinic start generated code]*/
  8958. static PyObject *
  8959. os_read_impl(PyObject *module, int fd, Py_ssize_t length)
  8960. /*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
  8961. {
  8962. Py_ssize_t n;
  8963. PyObject *buffer;
  8964. if (length < 0) {
  8965. errno = EINVAL;
  8966. return posix_error();
  8967. }
  8968. length = Py_MIN(length, _PY_READ_MAX);
  8969. buffer = PyBytes_FromStringAndSize((char *)NULL, length);
  8970. if (buffer == NULL)
  8971. return NULL;
  8972. n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
  8973. if (n == -1) {
  8974. Py_DECREF(buffer);
  8975. return NULL;
  8976. }
  8977. if (n != length)
  8978. _PyBytes_Resize(&buffer, n);
  8979. return buffer;
  8980. }
  8981. #if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
  8982. || defined(__APPLE__))) \
  8983. || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
  8984. || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
  8985. static int
  8986. iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
  8987. {
  8988. Py_ssize_t i, j;
  8989. *iov = PyMem_New(struct iovec, cnt);
  8990. if (*iov == NULL) {
  8991. PyErr_NoMemory();
  8992. return -1;
  8993. }
  8994. *buf = PyMem_New(Py_buffer, cnt);
  8995. if (*buf == NULL) {
  8996. PyMem_Free(*iov);
  8997. PyErr_NoMemory();
  8998. return -1;
  8999. }
  9000. for (i = 0; i < cnt; i++) {
  9001. PyObject *item = PySequence_GetItem(seq, i);
  9002. if (item == NULL)
  9003. goto fail;
  9004. if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
  9005. Py_DECREF(item);
  9006. goto fail;
  9007. }
  9008. Py_DECREF(item);
  9009. (*iov)[i].iov_base = (*buf)[i].buf;
  9010. (*iov)[i].iov_len = (*buf)[i].len;
  9011. }
  9012. return 0;
  9013. fail:
  9014. PyMem_Free(*iov);
  9015. for (j = 0; j < i; j++) {
  9016. PyBuffer_Release(&(*buf)[j]);
  9017. }
  9018. PyMem_Free(*buf);
  9019. return -1;
  9020. }
  9021. static void
  9022. iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
  9023. {
  9024. int i;
  9025. PyMem_Free(iov);
  9026. for (i = 0; i < cnt; i++) {
  9027. PyBuffer_Release(&buf[i]);
  9028. }
  9029. PyMem_Free(buf);
  9030. }
  9031. #endif
  9032. #ifdef HAVE_READV
  9033. /*[clinic input]
  9034. os.readv -> Py_ssize_t
  9035. fd: int
  9036. buffers: object
  9037. /
  9038. Read from a file descriptor fd into an iterable of buffers.
  9039. The buffers should be mutable buffers accepting bytes.
  9040. readv will transfer data into each buffer until it is full
  9041. and then move on to the next buffer in the sequence to hold
  9042. the rest of the data.
  9043. readv returns the total number of bytes read,
  9044. which may be less than the total capacity of all the buffers.
  9045. [clinic start generated code]*/
  9046. static Py_ssize_t
  9047. os_readv_impl(PyObject *module, int fd, PyObject *buffers)
  9048. /*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
  9049. {
  9050. Py_ssize_t cnt, n;
  9051. int async_err = 0;
  9052. struct iovec *iov;
  9053. Py_buffer *buf;
  9054. if (!PySequence_Check(buffers)) {
  9055. PyErr_SetString(PyExc_TypeError,
  9056. "readv() arg 2 must be a sequence");
  9057. return -1;
  9058. }
  9059. cnt = PySequence_Size(buffers);
  9060. if (cnt < 0)
  9061. return -1;
  9062. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
  9063. return -1;
  9064. do {
  9065. Py_BEGIN_ALLOW_THREADS
  9066. n = readv(fd, iov, cnt);
  9067. Py_END_ALLOW_THREADS
  9068. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9069. int saved_errno = errno;
  9070. iov_cleanup(iov, buf, cnt);
  9071. if (n < 0) {
  9072. if (!async_err) {
  9073. errno = saved_errno;
  9074. posix_error();
  9075. }
  9076. return -1;
  9077. }
  9078. return n;
  9079. }
  9080. #endif /* HAVE_READV */
  9081. #ifdef HAVE_PREAD
  9082. /*[clinic input]
  9083. os.pread
  9084. fd: int
  9085. length: Py_ssize_t
  9086. offset: Py_off_t
  9087. /
  9088. Read a number of bytes from a file descriptor starting at a particular offset.
  9089. Read length bytes from file descriptor fd, starting at offset bytes from
  9090. the beginning of the file. The file offset remains unchanged.
  9091. [clinic start generated code]*/
  9092. static PyObject *
  9093. os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
  9094. /*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
  9095. {
  9096. Py_ssize_t n;
  9097. int async_err = 0;
  9098. PyObject *buffer;
  9099. if (length < 0) {
  9100. errno = EINVAL;
  9101. return posix_error();
  9102. }
  9103. buffer = PyBytes_FromStringAndSize((char *)NULL, length);
  9104. if (buffer == NULL)
  9105. return NULL;
  9106. do {
  9107. Py_BEGIN_ALLOW_THREADS
  9108. _Py_BEGIN_SUPPRESS_IPH
  9109. n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
  9110. _Py_END_SUPPRESS_IPH
  9111. Py_END_ALLOW_THREADS
  9112. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9113. if (n < 0) {
  9114. if (!async_err) {
  9115. posix_error();
  9116. }
  9117. Py_DECREF(buffer);
  9118. return NULL;
  9119. }
  9120. if (n != length)
  9121. _PyBytes_Resize(&buffer, n);
  9122. return buffer;
  9123. }
  9124. #endif /* HAVE_PREAD */
  9125. #if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
  9126. /*[clinic input]
  9127. os.preadv -> Py_ssize_t
  9128. fd: int
  9129. buffers: object
  9130. offset: Py_off_t
  9131. flags: int = 0
  9132. /
  9133. Reads from a file descriptor into a number of mutable bytes-like objects.
  9134. Combines the functionality of readv() and pread(). As readv(), it will
  9135. transfer data into each buffer until it is full and then move on to the next
  9136. buffer in the sequence to hold the rest of the data. Its fourth argument,
  9137. specifies the file offset at which the input operation is to be performed. It
  9138. will return the total number of bytes read (which can be less than the total
  9139. capacity of all the objects).
  9140. The flags argument contains a bitwise OR of zero or more of the following flags:
  9141. - RWF_HIPRI
  9142. - RWF_NOWAIT
  9143. Using non-zero flags requires Linux 4.6 or newer.
  9144. [clinic start generated code]*/
  9145. static Py_ssize_t
  9146. os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
  9147. int flags)
  9148. /*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
  9149. {
  9150. Py_ssize_t cnt, n;
  9151. int async_err = 0;
  9152. struct iovec *iov;
  9153. Py_buffer *buf;
  9154. if (!PySequence_Check(buffers)) {
  9155. PyErr_SetString(PyExc_TypeError,
  9156. "preadv2() arg 2 must be a sequence");
  9157. return -1;
  9158. }
  9159. cnt = PySequence_Size(buffers);
  9160. if (cnt < 0) {
  9161. return -1;
  9162. }
  9163. #ifndef HAVE_PREADV2
  9164. if(flags != 0) {
  9165. argument_unavailable_error("preadv2", "flags");
  9166. return -1;
  9167. }
  9168. #endif
  9169. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
  9170. return -1;
  9171. }
  9172. #ifdef HAVE_PREADV2
  9173. do {
  9174. Py_BEGIN_ALLOW_THREADS
  9175. _Py_BEGIN_SUPPRESS_IPH
  9176. n = preadv2(fd, iov, cnt, offset, flags);
  9177. _Py_END_SUPPRESS_IPH
  9178. Py_END_ALLOW_THREADS
  9179. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9180. #else
  9181. do {
  9182. #if defined(__APPLE__) && defined(__clang__)
  9183. /* This entire function will be removed from the module dict when the API
  9184. * is not available.
  9185. */
  9186. #pragma clang diagnostic push
  9187. #pragma clang diagnostic ignored "-Wunguarded-availability"
  9188. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  9189. #endif
  9190. Py_BEGIN_ALLOW_THREADS
  9191. _Py_BEGIN_SUPPRESS_IPH
  9192. n = preadv(fd, iov, cnt, offset);
  9193. _Py_END_SUPPRESS_IPH
  9194. Py_END_ALLOW_THREADS
  9195. } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9196. #if defined(__APPLE__) && defined(__clang__)
  9197. #pragma clang diagnostic pop
  9198. #endif
  9199. #endif
  9200. int saved_errno = errno;
  9201. iov_cleanup(iov, buf, cnt);
  9202. if (n < 0) {
  9203. if (!async_err) {
  9204. errno = saved_errno;
  9205. posix_error();
  9206. }
  9207. return -1;
  9208. }
  9209. return n;
  9210. }
  9211. #endif /* HAVE_PREADV */
  9212. /*[clinic input]
  9213. os.write -> Py_ssize_t
  9214. fd: int
  9215. data: Py_buffer
  9216. /
  9217. Write a bytes object to a file descriptor.
  9218. [clinic start generated code]*/
  9219. static Py_ssize_t
  9220. os_write_impl(PyObject *module, int fd, Py_buffer *data)
  9221. /*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
  9222. {
  9223. return _Py_write(fd, data->buf, data->len);
  9224. }
  9225. #ifdef HAVE_SENDFILE
  9226. #ifdef __APPLE__
  9227. /*[clinic input]
  9228. os.sendfile
  9229. out_fd: int
  9230. in_fd: int
  9231. offset: Py_off_t
  9232. count as sbytes: Py_off_t
  9233. headers: object(c_default="NULL") = ()
  9234. trailers: object(c_default="NULL") = ()
  9235. flags: int = 0
  9236. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9237. [clinic start generated code]*/
  9238. static PyObject *
  9239. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
  9240. Py_off_t sbytes, PyObject *headers, PyObject *trailers,
  9241. int flags)
  9242. /*[clinic end generated code: output=81c4bcd143f5c82b input=b0d72579d4c69afa]*/
  9243. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  9244. /*[clinic input]
  9245. os.sendfile
  9246. out_fd: int
  9247. in_fd: int
  9248. offset: Py_off_t
  9249. count: Py_ssize_t
  9250. headers: object(c_default="NULL") = ()
  9251. trailers: object(c_default="NULL") = ()
  9252. flags: int = 0
  9253. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9254. [clinic start generated code]*/
  9255. static PyObject *
  9256. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
  9257. Py_ssize_t count, PyObject *headers, PyObject *trailers,
  9258. int flags)
  9259. /*[clinic end generated code: output=329ea009bdd55afc input=338adb8ff84ae8cd]*/
  9260. #else
  9261. /*[clinic input]
  9262. os.sendfile
  9263. out_fd: int
  9264. in_fd: int
  9265. offset as offobj: object
  9266. count: Py_ssize_t
  9267. Copy count bytes from file descriptor in_fd to file descriptor out_fd.
  9268. [clinic start generated code]*/
  9269. static PyObject *
  9270. os_sendfile_impl(PyObject *module, int out_fd, int in_fd, PyObject *offobj,
  9271. Py_ssize_t count)
  9272. /*[clinic end generated code: output=ae81216e40f167d8 input=76d64058c74477ba]*/
  9273. #endif
  9274. {
  9275. Py_ssize_t ret;
  9276. int async_err = 0;
  9277. #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
  9278. #ifndef __APPLE__
  9279. off_t sbytes;
  9280. #endif
  9281. Py_buffer *hbuf, *tbuf;
  9282. struct sf_hdtr sf;
  9283. sf.headers = NULL;
  9284. sf.trailers = NULL;
  9285. if (headers != NULL) {
  9286. if (!PySequence_Check(headers)) {
  9287. PyErr_SetString(PyExc_TypeError,
  9288. "sendfile() headers must be a sequence");
  9289. return NULL;
  9290. } else {
  9291. Py_ssize_t i = PySequence_Size(headers);
  9292. if (i < 0)
  9293. return NULL;
  9294. if (i > INT_MAX) {
  9295. PyErr_SetString(PyExc_OverflowError,
  9296. "sendfile() header is too large");
  9297. return NULL;
  9298. }
  9299. if (i > 0) {
  9300. sf.hdr_cnt = (int)i;
  9301. if (iov_setup(&(sf.headers), &hbuf,
  9302. headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
  9303. return NULL;
  9304. #ifdef __APPLE__
  9305. for (i = 0; i < sf.hdr_cnt; i++) {
  9306. Py_ssize_t blen = sf.headers[i].iov_len;
  9307. # define OFF_T_MAX 0x7fffffffffffffff
  9308. if (sbytes >= OFF_T_MAX - blen) {
  9309. PyErr_SetString(PyExc_OverflowError,
  9310. "sendfile() header is too large");
  9311. return NULL;
  9312. }
  9313. sbytes += blen;
  9314. }
  9315. #endif
  9316. }
  9317. }
  9318. }
  9319. if (trailers != NULL) {
  9320. if (!PySequence_Check(trailers)) {
  9321. PyErr_SetString(PyExc_TypeError,
  9322. "sendfile() trailers must be a sequence");
  9323. return NULL;
  9324. } else {
  9325. Py_ssize_t i = PySequence_Size(trailers);
  9326. if (i < 0)
  9327. return NULL;
  9328. if (i > INT_MAX) {
  9329. PyErr_SetString(PyExc_OverflowError,
  9330. "sendfile() trailer is too large");
  9331. return NULL;
  9332. }
  9333. if (i > 0) {
  9334. sf.trl_cnt = (int)i;
  9335. if (iov_setup(&(sf.trailers), &tbuf,
  9336. trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
  9337. return NULL;
  9338. }
  9339. }
  9340. }
  9341. _Py_BEGIN_SUPPRESS_IPH
  9342. do {
  9343. Py_BEGIN_ALLOW_THREADS
  9344. #ifdef __APPLE__
  9345. ret = sendfile(in_fd, out_fd, offset, &sbytes, &sf, flags);
  9346. #else
  9347. ret = sendfile(in_fd, out_fd, offset, count, &sf, &sbytes, flags);
  9348. #endif
  9349. Py_END_ALLOW_THREADS
  9350. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9351. _Py_END_SUPPRESS_IPH
  9352. int saved_errno = errno;
  9353. if (sf.headers != NULL)
  9354. iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
  9355. if (sf.trailers != NULL)
  9356. iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
  9357. if (ret < 0) {
  9358. if ((saved_errno == EAGAIN) || (saved_errno == EBUSY)) {
  9359. if (sbytes != 0) {
  9360. // some data has been sent
  9361. goto done;
  9362. }
  9363. // no data has been sent; upper application is supposed
  9364. // to retry on EAGAIN or EBUSY
  9365. }
  9366. if (!async_err) {
  9367. errno = saved_errno;
  9368. posix_error();
  9369. }
  9370. return NULL;
  9371. }
  9372. goto done;
  9373. done:
  9374. #if !defined(HAVE_LARGEFILE_SUPPORT)
  9375. return Py_BuildValue("l", sbytes);
  9376. #else
  9377. return Py_BuildValue("L", sbytes);
  9378. #endif
  9379. #else
  9380. #ifdef __linux__
  9381. if (offobj == Py_None) {
  9382. do {
  9383. Py_BEGIN_ALLOW_THREADS
  9384. ret = sendfile(out_fd, in_fd, NULL, count);
  9385. Py_END_ALLOW_THREADS
  9386. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9387. if (ret < 0)
  9388. return (!async_err) ? posix_error() : NULL;
  9389. return Py_BuildValue("n", ret);
  9390. }
  9391. #endif
  9392. off_t offset;
  9393. if (!Py_off_t_converter(offobj, &offset))
  9394. return NULL;
  9395. #if defined(__sun) && defined(__SVR4)
  9396. // On Solaris, sendfile raises EINVAL rather than returning 0
  9397. // when the offset is equal or bigger than the in_fd size.
  9398. struct stat st;
  9399. do {
  9400. Py_BEGIN_ALLOW_THREADS
  9401. ret = fstat(in_fd, &st);
  9402. Py_END_ALLOW_THREADS
  9403. } while (ret != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9404. if (ret < 0)
  9405. return (!async_err) ? posix_error() : NULL;
  9406. if (offset >= st.st_size) {
  9407. return Py_BuildValue("i", 0);
  9408. }
  9409. // On illumos specifically sendfile() may perform a partial write but
  9410. // return -1/an error (in one confirmed case the destination socket
  9411. // had a 5 second timeout set and errno was EAGAIN) and it's on the client
  9412. // code to check if the offset parameter was modified by sendfile().
  9413. //
  9414. // We need this variable to track said change.
  9415. off_t original_offset = offset;
  9416. #endif
  9417. do {
  9418. Py_BEGIN_ALLOW_THREADS
  9419. ret = sendfile(out_fd, in_fd, &offset, count);
  9420. #if defined(__sun) && defined(__SVR4)
  9421. // This handles illumos-specific sendfile() partial write behavior,
  9422. // see a comment above for more details.
  9423. if (ret < 0 && offset != original_offset) {
  9424. ret = offset - original_offset;
  9425. }
  9426. #endif
  9427. Py_END_ALLOW_THREADS
  9428. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9429. if (ret < 0)
  9430. return (!async_err) ? posix_error() : NULL;
  9431. return Py_BuildValue("n", ret);
  9432. #endif
  9433. }
  9434. #endif /* HAVE_SENDFILE */
  9435. #if defined(__APPLE__)
  9436. /*[clinic input]
  9437. os._fcopyfile
  9438. in_fd: int
  9439. out_fd: int
  9440. flags: int
  9441. /
  9442. Efficiently copy content or metadata of 2 regular file descriptors (macOS).
  9443. [clinic start generated code]*/
  9444. static PyObject *
  9445. os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
  9446. /*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
  9447. {
  9448. int ret;
  9449. Py_BEGIN_ALLOW_THREADS
  9450. ret = fcopyfile(in_fd, out_fd, NULL, flags);
  9451. Py_END_ALLOW_THREADS
  9452. if (ret < 0)
  9453. return posix_error();
  9454. Py_RETURN_NONE;
  9455. }
  9456. #endif
  9457. /*[clinic input]
  9458. os.fstat
  9459. fd : int
  9460. Perform a stat system call on the given file descriptor.
  9461. Like stat(), but for an open file descriptor.
  9462. Equivalent to os.stat(fd).
  9463. [clinic start generated code]*/
  9464. static PyObject *
  9465. os_fstat_impl(PyObject *module, int fd)
  9466. /*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
  9467. {
  9468. STRUCT_STAT st;
  9469. int res;
  9470. int async_err = 0;
  9471. do {
  9472. Py_BEGIN_ALLOW_THREADS
  9473. res = FSTAT(fd, &st);
  9474. Py_END_ALLOW_THREADS
  9475. } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9476. if (res != 0) {
  9477. #ifdef MS_WINDOWS
  9478. return PyErr_SetFromWindowsErr(0);
  9479. #else
  9480. return (!async_err) ? posix_error() : NULL;
  9481. #endif
  9482. }
  9483. return _pystat_fromstructstat(module, &st);
  9484. }
  9485. /*[clinic input]
  9486. os.isatty -> bool
  9487. fd: int
  9488. /
  9489. Return True if the fd is connected to a terminal.
  9490. Return True if the file descriptor is an open file descriptor
  9491. connected to the slave end of a terminal.
  9492. [clinic start generated code]*/
  9493. static int
  9494. os_isatty_impl(PyObject *module, int fd)
  9495. /*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
  9496. {
  9497. int return_value;
  9498. Py_BEGIN_ALLOW_THREADS
  9499. _Py_BEGIN_SUPPRESS_IPH
  9500. return_value = isatty(fd);
  9501. _Py_END_SUPPRESS_IPH
  9502. Py_END_ALLOW_THREADS
  9503. return return_value;
  9504. }
  9505. #ifdef HAVE_PIPE
  9506. /*[clinic input]
  9507. os.pipe
  9508. Create a pipe.
  9509. Returns a tuple of two file descriptors:
  9510. (read_fd, write_fd)
  9511. [clinic start generated code]*/
  9512. static PyObject *
  9513. os_pipe_impl(PyObject *module)
  9514. /*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
  9515. {
  9516. int fds[2];
  9517. #ifdef MS_WINDOWS
  9518. HANDLE read, write;
  9519. SECURITY_ATTRIBUTES attr;
  9520. BOOL ok;
  9521. #else
  9522. int res;
  9523. #endif
  9524. #ifdef MS_WINDOWS
  9525. attr.nLength = sizeof(attr);
  9526. attr.lpSecurityDescriptor = NULL;
  9527. attr.bInheritHandle = FALSE;
  9528. Py_BEGIN_ALLOW_THREADS
  9529. ok = CreatePipe(&read, &write, &attr, 0);
  9530. if (ok) {
  9531. fds[0] = _Py_open_osfhandle_noraise(read, _O_RDONLY);
  9532. fds[1] = _Py_open_osfhandle_noraise(write, _O_WRONLY);
  9533. if (fds[0] == -1 || fds[1] == -1) {
  9534. CloseHandle(read);
  9535. CloseHandle(write);
  9536. ok = 0;
  9537. }
  9538. }
  9539. Py_END_ALLOW_THREADS
  9540. if (!ok)
  9541. return PyErr_SetFromWindowsErr(0);
  9542. #else
  9543. #ifdef HAVE_PIPE2
  9544. Py_BEGIN_ALLOW_THREADS
  9545. res = pipe2(fds, O_CLOEXEC);
  9546. Py_END_ALLOW_THREADS
  9547. if (res != 0 && errno == ENOSYS)
  9548. {
  9549. #endif
  9550. Py_BEGIN_ALLOW_THREADS
  9551. res = pipe(fds);
  9552. Py_END_ALLOW_THREADS
  9553. if (res == 0) {
  9554. if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
  9555. close(fds[0]);
  9556. close(fds[1]);
  9557. return NULL;
  9558. }
  9559. if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
  9560. close(fds[0]);
  9561. close(fds[1]);
  9562. return NULL;
  9563. }
  9564. }
  9565. #ifdef HAVE_PIPE2
  9566. }
  9567. #endif
  9568. if (res != 0)
  9569. return PyErr_SetFromErrno(PyExc_OSError);
  9570. #endif /* !MS_WINDOWS */
  9571. return Py_BuildValue("(ii)", fds[0], fds[1]);
  9572. }
  9573. #endif /* HAVE_PIPE */
  9574. #ifdef HAVE_PIPE2
  9575. /*[clinic input]
  9576. os.pipe2
  9577. flags: int
  9578. /
  9579. Create a pipe with flags set atomically.
  9580. Returns a tuple of two file descriptors:
  9581. (read_fd, write_fd)
  9582. flags can be constructed by ORing together one or more of these values:
  9583. O_NONBLOCK, O_CLOEXEC.
  9584. [clinic start generated code]*/
  9585. static PyObject *
  9586. os_pipe2_impl(PyObject *module, int flags)
  9587. /*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
  9588. {
  9589. int fds[2];
  9590. int res;
  9591. res = pipe2(fds, flags);
  9592. if (res != 0)
  9593. return posix_error();
  9594. return Py_BuildValue("(ii)", fds[0], fds[1]);
  9595. }
  9596. #endif /* HAVE_PIPE2 */
  9597. #ifdef HAVE_WRITEV
  9598. /*[clinic input]
  9599. os.writev -> Py_ssize_t
  9600. fd: int
  9601. buffers: object
  9602. /
  9603. Iterate over buffers, and write the contents of each to a file descriptor.
  9604. Returns the total number of bytes written.
  9605. buffers must be a sequence of bytes-like objects.
  9606. [clinic start generated code]*/
  9607. static Py_ssize_t
  9608. os_writev_impl(PyObject *module, int fd, PyObject *buffers)
  9609. /*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
  9610. {
  9611. Py_ssize_t cnt;
  9612. Py_ssize_t result;
  9613. int async_err = 0;
  9614. struct iovec *iov;
  9615. Py_buffer *buf;
  9616. if (!PySequence_Check(buffers)) {
  9617. PyErr_SetString(PyExc_TypeError,
  9618. "writev() arg 2 must be a sequence");
  9619. return -1;
  9620. }
  9621. cnt = PySequence_Size(buffers);
  9622. if (cnt < 0)
  9623. return -1;
  9624. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
  9625. return -1;
  9626. }
  9627. do {
  9628. Py_BEGIN_ALLOW_THREADS
  9629. result = writev(fd, iov, cnt);
  9630. Py_END_ALLOW_THREADS
  9631. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9632. if (result < 0 && !async_err)
  9633. posix_error();
  9634. iov_cleanup(iov, buf, cnt);
  9635. return result;
  9636. }
  9637. #endif /* HAVE_WRITEV */
  9638. #ifdef HAVE_PWRITE
  9639. /*[clinic input]
  9640. os.pwrite -> Py_ssize_t
  9641. fd: int
  9642. buffer: Py_buffer
  9643. offset: Py_off_t
  9644. /
  9645. Write bytes to a file descriptor starting at a particular offset.
  9646. Write buffer to fd, starting at offset bytes from the beginning of
  9647. the file. Returns the number of bytes writte. Does not change the
  9648. current file offset.
  9649. [clinic start generated code]*/
  9650. static Py_ssize_t
  9651. os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
  9652. /*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
  9653. {
  9654. Py_ssize_t size;
  9655. int async_err = 0;
  9656. do {
  9657. Py_BEGIN_ALLOW_THREADS
  9658. _Py_BEGIN_SUPPRESS_IPH
  9659. size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
  9660. _Py_END_SUPPRESS_IPH
  9661. Py_END_ALLOW_THREADS
  9662. } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9663. if (size < 0 && !async_err)
  9664. posix_error();
  9665. return size;
  9666. }
  9667. #endif /* HAVE_PWRITE */
  9668. #if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
  9669. /*[clinic input]
  9670. os.pwritev -> Py_ssize_t
  9671. fd: int
  9672. buffers: object
  9673. offset: Py_off_t
  9674. flags: int = 0
  9675. /
  9676. Writes the contents of bytes-like objects to a file descriptor at a given offset.
  9677. Combines the functionality of writev() and pwrite(). All buffers must be a sequence
  9678. of bytes-like objects. Buffers are processed in array order. Entire contents of first
  9679. buffer is written before proceeding to second, and so on. The operating system may
  9680. set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
  9681. This function writes the contents of each object to the file descriptor and returns
  9682. the total number of bytes written.
  9683. The flags argument contains a bitwise OR of zero or more of the following flags:
  9684. - RWF_DSYNC
  9685. - RWF_SYNC
  9686. - RWF_APPEND
  9687. Using non-zero flags requires Linux 4.7 or newer.
  9688. [clinic start generated code]*/
  9689. static Py_ssize_t
  9690. os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
  9691. int flags)
  9692. /*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=35358c327e1a2a8e]*/
  9693. {
  9694. Py_ssize_t cnt;
  9695. Py_ssize_t result;
  9696. int async_err = 0;
  9697. struct iovec *iov;
  9698. Py_buffer *buf;
  9699. if (!PySequence_Check(buffers)) {
  9700. PyErr_SetString(PyExc_TypeError,
  9701. "pwritev() arg 2 must be a sequence");
  9702. return -1;
  9703. }
  9704. cnt = PySequence_Size(buffers);
  9705. if (cnt < 0) {
  9706. return -1;
  9707. }
  9708. #ifndef HAVE_PWRITEV2
  9709. if(flags != 0) {
  9710. argument_unavailable_error("pwritev2", "flags");
  9711. return -1;
  9712. }
  9713. #endif
  9714. if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
  9715. return -1;
  9716. }
  9717. #ifdef HAVE_PWRITEV2
  9718. do {
  9719. Py_BEGIN_ALLOW_THREADS
  9720. _Py_BEGIN_SUPPRESS_IPH
  9721. result = pwritev2(fd, iov, cnt, offset, flags);
  9722. _Py_END_SUPPRESS_IPH
  9723. Py_END_ALLOW_THREADS
  9724. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9725. #else
  9726. #if defined(__APPLE__) && defined(__clang__)
  9727. /* This entire function will be removed from the module dict when the API
  9728. * is not available.
  9729. */
  9730. #pragma clang diagnostic push
  9731. #pragma clang diagnostic ignored "-Wunguarded-availability"
  9732. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  9733. #endif
  9734. do {
  9735. Py_BEGIN_ALLOW_THREADS
  9736. _Py_BEGIN_SUPPRESS_IPH
  9737. result = pwritev(fd, iov, cnt, offset);
  9738. _Py_END_SUPPRESS_IPH
  9739. Py_END_ALLOW_THREADS
  9740. } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9741. #if defined(__APPLE__) && defined(__clang__)
  9742. #pragma clang diagnostic pop
  9743. #endif
  9744. #endif
  9745. if (result < 0) {
  9746. if (!async_err) {
  9747. posix_error();
  9748. }
  9749. result = -1;
  9750. }
  9751. iov_cleanup(iov, buf, cnt);
  9752. return result;
  9753. }
  9754. #endif /* HAVE_PWRITEV */
  9755. #ifdef HAVE_COPY_FILE_RANGE
  9756. /*[clinic input]
  9757. os.copy_file_range
  9758. src: int
  9759. Source file descriptor.
  9760. dst: int
  9761. Destination file descriptor.
  9762. count: Py_ssize_t
  9763. Number of bytes to copy.
  9764. offset_src: object = None
  9765. Starting offset in src.
  9766. offset_dst: object = None
  9767. Starting offset in dst.
  9768. Copy count bytes from one file descriptor to another.
  9769. If offset_src is None, then src is read from the current position;
  9770. respectively for offset_dst.
  9771. [clinic start generated code]*/
  9772. static PyObject *
  9773. os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
  9774. PyObject *offset_src, PyObject *offset_dst)
  9775. /*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
  9776. {
  9777. off_t offset_src_val, offset_dst_val;
  9778. off_t *p_offset_src = NULL;
  9779. off_t *p_offset_dst = NULL;
  9780. Py_ssize_t ret;
  9781. int async_err = 0;
  9782. /* The flags argument is provided to allow
  9783. * for future extensions and currently must be to 0. */
  9784. int flags = 0;
  9785. if (count < 0) {
  9786. PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
  9787. return NULL;
  9788. }
  9789. if (offset_src != Py_None) {
  9790. if (!Py_off_t_converter(offset_src, &offset_src_val)) {
  9791. return NULL;
  9792. }
  9793. p_offset_src = &offset_src_val;
  9794. }
  9795. if (offset_dst != Py_None) {
  9796. if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
  9797. return NULL;
  9798. }
  9799. p_offset_dst = &offset_dst_val;
  9800. }
  9801. do {
  9802. Py_BEGIN_ALLOW_THREADS
  9803. ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
  9804. Py_END_ALLOW_THREADS
  9805. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9806. if (ret < 0) {
  9807. return (!async_err) ? posix_error() : NULL;
  9808. }
  9809. return PyLong_FromSsize_t(ret);
  9810. }
  9811. #endif /* HAVE_COPY_FILE_RANGE*/
  9812. #if (defined(HAVE_SPLICE) && !defined(_AIX))
  9813. /*[clinic input]
  9814. os.splice
  9815. src: int
  9816. Source file descriptor.
  9817. dst: int
  9818. Destination file descriptor.
  9819. count: Py_ssize_t
  9820. Number of bytes to copy.
  9821. offset_src: object = None
  9822. Starting offset in src.
  9823. offset_dst: object = None
  9824. Starting offset in dst.
  9825. flags: unsigned_int = 0
  9826. Flags to modify the semantics of the call.
  9827. Transfer count bytes from one pipe to a descriptor or vice versa.
  9828. If offset_src is None, then src is read from the current position;
  9829. respectively for offset_dst. The offset associated to the file
  9830. descriptor that refers to a pipe must be None.
  9831. [clinic start generated code]*/
  9832. static PyObject *
  9833. os_splice_impl(PyObject *module, int src, int dst, Py_ssize_t count,
  9834. PyObject *offset_src, PyObject *offset_dst,
  9835. unsigned int flags)
  9836. /*[clinic end generated code: output=d0386f25a8519dc5 input=047527c66c6d2e0a]*/
  9837. {
  9838. off_t offset_src_val, offset_dst_val;
  9839. off_t *p_offset_src = NULL;
  9840. off_t *p_offset_dst = NULL;
  9841. Py_ssize_t ret;
  9842. int async_err = 0;
  9843. if (count < 0) {
  9844. PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
  9845. return NULL;
  9846. }
  9847. if (offset_src != Py_None) {
  9848. if (!Py_off_t_converter(offset_src, &offset_src_val)) {
  9849. return NULL;
  9850. }
  9851. p_offset_src = &offset_src_val;
  9852. }
  9853. if (offset_dst != Py_None) {
  9854. if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
  9855. return NULL;
  9856. }
  9857. p_offset_dst = &offset_dst_val;
  9858. }
  9859. do {
  9860. Py_BEGIN_ALLOW_THREADS
  9861. ret = splice(src, p_offset_src, dst, p_offset_dst, count, flags);
  9862. Py_END_ALLOW_THREADS
  9863. } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  9864. if (ret < 0) {
  9865. return (!async_err) ? posix_error() : NULL;
  9866. }
  9867. return PyLong_FromSsize_t(ret);
  9868. }
  9869. #endif /* HAVE_SPLICE*/
  9870. #ifdef HAVE_MKFIFO
  9871. /*[clinic input]
  9872. os.mkfifo
  9873. path: path_t
  9874. mode: int=0o666
  9875. *
  9876. dir_fd: dir_fd(requires='mkfifoat')=None
  9877. Create a "fifo" (a POSIX named pipe).
  9878. If dir_fd is not None, it should be a file descriptor open to a directory,
  9879. and path should be relative; path will then be relative to that directory.
  9880. dir_fd may not be implemented on your platform.
  9881. If it is unavailable, using it will raise a NotImplementedError.
  9882. [clinic start generated code]*/
  9883. static PyObject *
  9884. os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
  9885. /*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
  9886. {
  9887. int result;
  9888. int async_err = 0;
  9889. #ifdef HAVE_MKFIFOAT
  9890. int mkfifoat_unavailable = 0;
  9891. #endif
  9892. do {
  9893. Py_BEGIN_ALLOW_THREADS
  9894. #ifdef HAVE_MKFIFOAT
  9895. if (dir_fd != DEFAULT_DIR_FD) {
  9896. if (HAVE_MKFIFOAT_RUNTIME) {
  9897. result = mkfifoat(dir_fd, path->narrow, mode);
  9898. } else {
  9899. mkfifoat_unavailable = 1;
  9900. result = 0;
  9901. }
  9902. } else
  9903. #endif
  9904. result = mkfifo(path->narrow, mode);
  9905. Py_END_ALLOW_THREADS
  9906. } while (result != 0 && errno == EINTR &&
  9907. !(async_err = PyErr_CheckSignals()));
  9908. #ifdef HAVE_MKFIFOAT
  9909. if (mkfifoat_unavailable) {
  9910. argument_unavailable_error(NULL, "dir_fd");
  9911. return NULL;
  9912. }
  9913. #endif
  9914. if (result != 0)
  9915. return (!async_err) ? posix_error() : NULL;
  9916. Py_RETURN_NONE;
  9917. }
  9918. #endif /* HAVE_MKFIFO */
  9919. #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
  9920. /*[clinic input]
  9921. os.mknod
  9922. path: path_t
  9923. mode: int=0o600
  9924. device: dev_t=0
  9925. *
  9926. dir_fd: dir_fd(requires='mknodat')=None
  9927. Create a node in the file system.
  9928. Create a node in the file system (file, device special file or named pipe)
  9929. at path. mode specifies both the permissions to use and the
  9930. type of node to be created, being combined (bitwise OR) with one of
  9931. S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
  9932. device defines the newly created device special file (probably using
  9933. os.makedev()). Otherwise device is ignored.
  9934. If dir_fd is not None, it should be a file descriptor open to a directory,
  9935. and path should be relative; path will then be relative to that directory.
  9936. dir_fd may not be implemented on your platform.
  9937. If it is unavailable, using it will raise a NotImplementedError.
  9938. [clinic start generated code]*/
  9939. static PyObject *
  9940. os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
  9941. int dir_fd)
  9942. /*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
  9943. {
  9944. int result;
  9945. int async_err = 0;
  9946. #ifdef HAVE_MKNODAT
  9947. int mknodat_unavailable = 0;
  9948. #endif
  9949. do {
  9950. Py_BEGIN_ALLOW_THREADS
  9951. #ifdef HAVE_MKNODAT
  9952. if (dir_fd != DEFAULT_DIR_FD) {
  9953. if (HAVE_MKNODAT_RUNTIME) {
  9954. result = mknodat(dir_fd, path->narrow, mode, device);
  9955. } else {
  9956. mknodat_unavailable = 1;
  9957. result = 0;
  9958. }
  9959. } else
  9960. #endif
  9961. result = mknod(path->narrow, mode, device);
  9962. Py_END_ALLOW_THREADS
  9963. } while (result != 0 && errno == EINTR &&
  9964. !(async_err = PyErr_CheckSignals()));
  9965. #ifdef HAVE_MKNODAT
  9966. if (mknodat_unavailable) {
  9967. argument_unavailable_error(NULL, "dir_fd");
  9968. return NULL;
  9969. }
  9970. #endif
  9971. if (result != 0)
  9972. return (!async_err) ? posix_error() : NULL;
  9973. Py_RETURN_NONE;
  9974. }
  9975. #endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
  9976. #ifdef HAVE_DEVICE_MACROS
  9977. /*[clinic input]
  9978. os.major -> unsigned_int
  9979. device: dev_t
  9980. /
  9981. Extracts a device major number from a raw device number.
  9982. [clinic start generated code]*/
  9983. static unsigned int
  9984. os_major_impl(PyObject *module, dev_t device)
  9985. /*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
  9986. {
  9987. return major(device);
  9988. }
  9989. /*[clinic input]
  9990. os.minor -> unsigned_int
  9991. device: dev_t
  9992. /
  9993. Extracts a device minor number from a raw device number.
  9994. [clinic start generated code]*/
  9995. static unsigned int
  9996. os_minor_impl(PyObject *module, dev_t device)
  9997. /*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
  9998. {
  9999. return minor(device);
  10000. }
  10001. /*[clinic input]
  10002. os.makedev -> dev_t
  10003. major: int
  10004. minor: int
  10005. /
  10006. Composes a raw device number from the major and minor device numbers.
  10007. [clinic start generated code]*/
  10008. static dev_t
  10009. os_makedev_impl(PyObject *module, int major, int minor)
  10010. /*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
  10011. {
  10012. return makedev(major, minor);
  10013. }
  10014. #endif /* HAVE_DEVICE_MACROS */
  10015. #if defined HAVE_FTRUNCATE || defined MS_WINDOWS
  10016. /*[clinic input]
  10017. os.ftruncate
  10018. fd: int
  10019. length: Py_off_t
  10020. /
  10021. Truncate a file, specified by file descriptor, to a specific length.
  10022. [clinic start generated code]*/
  10023. static PyObject *
  10024. os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
  10025. /*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
  10026. {
  10027. int result;
  10028. int async_err = 0;
  10029. if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
  10030. return NULL;
  10031. }
  10032. do {
  10033. Py_BEGIN_ALLOW_THREADS
  10034. _Py_BEGIN_SUPPRESS_IPH
  10035. #ifdef MS_WINDOWS
  10036. result = _chsize_s(fd, length);
  10037. #else
  10038. result = ftruncate(fd, length);
  10039. #endif
  10040. _Py_END_SUPPRESS_IPH
  10041. Py_END_ALLOW_THREADS
  10042. } while (result != 0 && errno == EINTR &&
  10043. !(async_err = PyErr_CheckSignals()));
  10044. if (result != 0)
  10045. return (!async_err) ? posix_error() : NULL;
  10046. Py_RETURN_NONE;
  10047. }
  10048. #endif /* HAVE_FTRUNCATE || MS_WINDOWS */
  10049. #if defined HAVE_TRUNCATE || defined MS_WINDOWS
  10050. /*[clinic input]
  10051. os.truncate
  10052. path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
  10053. length: Py_off_t
  10054. Truncate a file, specified by path, to a specific length.
  10055. On some platforms, path may also be specified as an open file descriptor.
  10056. If this functionality is unavailable, using it raises an exception.
  10057. [clinic start generated code]*/
  10058. static PyObject *
  10059. os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
  10060. /*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
  10061. {
  10062. int result;
  10063. #ifdef MS_WINDOWS
  10064. int fd;
  10065. #endif
  10066. if (path->fd != -1)
  10067. return os_ftruncate_impl(module, path->fd, length);
  10068. if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
  10069. return NULL;
  10070. }
  10071. Py_BEGIN_ALLOW_THREADS
  10072. _Py_BEGIN_SUPPRESS_IPH
  10073. #ifdef MS_WINDOWS
  10074. fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
  10075. if (fd < 0)
  10076. result = -1;
  10077. else {
  10078. result = _chsize_s(fd, length);
  10079. close(fd);
  10080. if (result < 0)
  10081. errno = result;
  10082. }
  10083. #else
  10084. result = truncate(path->narrow, length);
  10085. #endif
  10086. _Py_END_SUPPRESS_IPH
  10087. Py_END_ALLOW_THREADS
  10088. if (result < 0)
  10089. return posix_path_error(path);
  10090. Py_RETURN_NONE;
  10091. }
  10092. #endif /* HAVE_TRUNCATE || MS_WINDOWS */
  10093. /* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
  10094. and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
  10095. defined, which is the case in Python on AIX. AIX bug report:
  10096. http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
  10097. #if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
  10098. # define POSIX_FADVISE_AIX_BUG
  10099. #endif
  10100. /* GH-111804: Due to posix_fallocate() not having consistent semantics across
  10101. OSs, support was dropped in WASI preview2. */
  10102. #if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG) && \
  10103. !defined(__wasi__)
  10104. /*[clinic input]
  10105. os.posix_fallocate
  10106. fd: int
  10107. offset: Py_off_t
  10108. length: Py_off_t
  10109. /
  10110. Ensure a file has allocated at least a particular number of bytes on disk.
  10111. Ensure that the file specified by fd encompasses a range of bytes
  10112. starting at offset bytes from the beginning and continuing for length bytes.
  10113. [clinic start generated code]*/
  10114. static PyObject *
  10115. os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
  10116. Py_off_t length)
  10117. /*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
  10118. {
  10119. int result;
  10120. int async_err = 0;
  10121. do {
  10122. Py_BEGIN_ALLOW_THREADS
  10123. result = posix_fallocate(fd, offset, length);
  10124. Py_END_ALLOW_THREADS
  10125. } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
  10126. if (result == 0)
  10127. Py_RETURN_NONE;
  10128. if (async_err)
  10129. return NULL;
  10130. errno = result;
  10131. return posix_error();
  10132. }
  10133. #endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG && !defined(__wasi__) */
  10134. #if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
  10135. /*[clinic input]
  10136. os.posix_fadvise
  10137. fd: int
  10138. offset: Py_off_t
  10139. length: Py_off_t
  10140. advice: int
  10141. /
  10142. Announce an intention to access data in a specific pattern.
  10143. Announce an intention to access data in a specific pattern, thus allowing
  10144. the kernel to make optimizations.
  10145. The advice applies to the region of the file specified by fd starting at
  10146. offset and continuing for length bytes.
  10147. advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
  10148. POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
  10149. POSIX_FADV_DONTNEED.
  10150. [clinic start generated code]*/
  10151. static PyObject *
  10152. os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
  10153. Py_off_t length, int advice)
  10154. /*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
  10155. {
  10156. int result;
  10157. int async_err = 0;
  10158. do {
  10159. Py_BEGIN_ALLOW_THREADS
  10160. result = posix_fadvise(fd, offset, length, advice);
  10161. Py_END_ALLOW_THREADS
  10162. } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
  10163. if (result == 0)
  10164. Py_RETURN_NONE;
  10165. if (async_err)
  10166. return NULL;
  10167. errno = result;
  10168. return posix_error();
  10169. }
  10170. #endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
  10171. #ifdef MS_WINDOWS
  10172. static PyObject*
  10173. win32_putenv(PyObject *name, PyObject *value)
  10174. {
  10175. /* Search from index 1 because on Windows starting '=' is allowed for
  10176. defining hidden environment variables. */
  10177. if (PyUnicode_GET_LENGTH(name) == 0 ||
  10178. PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
  10179. {
  10180. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  10181. return NULL;
  10182. }
  10183. PyObject *unicode;
  10184. if (value != NULL) {
  10185. unicode = PyUnicode_FromFormat("%U=%U", name, value);
  10186. }
  10187. else {
  10188. unicode = PyUnicode_FromFormat("%U=", name);
  10189. }
  10190. if (unicode == NULL) {
  10191. return NULL;
  10192. }
  10193. Py_ssize_t size;
  10194. wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
  10195. Py_DECREF(unicode);
  10196. if (env == NULL) {
  10197. return NULL;
  10198. }
  10199. if (size > _MAX_ENV) {
  10200. PyErr_Format(PyExc_ValueError,
  10201. "the environment variable is longer than %u characters",
  10202. _MAX_ENV);
  10203. PyMem_Free(env);
  10204. return NULL;
  10205. }
  10206. if (wcslen(env) != (size_t)size) {
  10207. PyErr_SetString(PyExc_ValueError,
  10208. "embedded null character");
  10209. PyMem_Free(env);
  10210. return NULL;
  10211. }
  10212. /* _wputenv() and SetEnvironmentVariableW() update the environment in the
  10213. Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
  10214. and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
  10215. Prefer _wputenv() to be compatible with C libraries using CRT
  10216. variables and CRT functions using these variables (ex: getenv()). */
  10217. int err = _wputenv(env);
  10218. if (err) {
  10219. posix_error();
  10220. PyMem_Free(env);
  10221. return NULL;
  10222. }
  10223. PyMem_Free(env);
  10224. Py_RETURN_NONE;
  10225. }
  10226. #endif
  10227. #ifdef MS_WINDOWS
  10228. /*[clinic input]
  10229. os.putenv
  10230. name: unicode
  10231. value: unicode
  10232. /
  10233. Change or add an environment variable.
  10234. [clinic start generated code]*/
  10235. static PyObject *
  10236. os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
  10237. /*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
  10238. {
  10239. if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
  10240. return NULL;
  10241. }
  10242. return win32_putenv(name, value);
  10243. }
  10244. #else
  10245. /*[clinic input]
  10246. os.putenv
  10247. name: FSConverter
  10248. value: FSConverter
  10249. /
  10250. Change or add an environment variable.
  10251. [clinic start generated code]*/
  10252. static PyObject *
  10253. os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
  10254. /*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
  10255. {
  10256. const char *name_string = PyBytes_AS_STRING(name);
  10257. const char *value_string = PyBytes_AS_STRING(value);
  10258. if (strchr(name_string, '=') != NULL) {
  10259. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  10260. return NULL;
  10261. }
  10262. if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
  10263. return NULL;
  10264. }
  10265. if (setenv(name_string, value_string, 1)) {
  10266. return posix_error();
  10267. }
  10268. Py_RETURN_NONE;
  10269. }
  10270. #endif /* !defined(MS_WINDOWS) */
  10271. #ifdef MS_WINDOWS
  10272. /*[clinic input]
  10273. os.unsetenv
  10274. name: unicode
  10275. /
  10276. Delete an environment variable.
  10277. [clinic start generated code]*/
  10278. static PyObject *
  10279. os_unsetenv_impl(PyObject *module, PyObject *name)
  10280. /*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
  10281. {
  10282. if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
  10283. return NULL;
  10284. }
  10285. return win32_putenv(name, NULL);
  10286. }
  10287. #else
  10288. /*[clinic input]
  10289. os.unsetenv
  10290. name: FSConverter
  10291. /
  10292. Delete an environment variable.
  10293. [clinic start generated code]*/
  10294. static PyObject *
  10295. os_unsetenv_impl(PyObject *module, PyObject *name)
  10296. /*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
  10297. {
  10298. if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
  10299. return NULL;
  10300. }
  10301. #ifdef HAVE_BROKEN_UNSETENV
  10302. unsetenv(PyBytes_AS_STRING(name));
  10303. #else
  10304. int err = unsetenv(PyBytes_AS_STRING(name));
  10305. if (err) {
  10306. return posix_error();
  10307. }
  10308. #endif
  10309. Py_RETURN_NONE;
  10310. }
  10311. #endif /* !MS_WINDOWS */
  10312. /*[clinic input]
  10313. os.strerror
  10314. code: int
  10315. /
  10316. Translate an error code to a message string.
  10317. [clinic start generated code]*/
  10318. static PyObject *
  10319. os_strerror_impl(PyObject *module, int code)
  10320. /*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
  10321. {
  10322. char *message = strerror(code);
  10323. if (message == NULL) {
  10324. PyErr_SetString(PyExc_ValueError,
  10325. "strerror() argument out of range");
  10326. return NULL;
  10327. }
  10328. return PyUnicode_DecodeLocale(message, "surrogateescape");
  10329. }
  10330. #ifdef HAVE_SYS_WAIT_H
  10331. #ifdef WCOREDUMP
  10332. /*[clinic input]
  10333. os.WCOREDUMP -> bool
  10334. status: int
  10335. /
  10336. Return True if the process returning status was dumped to a core file.
  10337. [clinic start generated code]*/
  10338. static int
  10339. os_WCOREDUMP_impl(PyObject *module, int status)
  10340. /*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
  10341. {
  10342. WAIT_TYPE wait_status;
  10343. WAIT_STATUS_INT(wait_status) = status;
  10344. return WCOREDUMP(wait_status);
  10345. }
  10346. #endif /* WCOREDUMP */
  10347. #ifdef WIFCONTINUED
  10348. /*[clinic input]
  10349. os.WIFCONTINUED -> bool
  10350. status: int
  10351. Return True if a particular process was continued from a job control stop.
  10352. Return True if the process returning status was continued from a
  10353. job control stop.
  10354. [clinic start generated code]*/
  10355. static int
  10356. os_WIFCONTINUED_impl(PyObject *module, int status)
  10357. /*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
  10358. {
  10359. WAIT_TYPE wait_status;
  10360. WAIT_STATUS_INT(wait_status) = status;
  10361. return WIFCONTINUED(wait_status);
  10362. }
  10363. #endif /* WIFCONTINUED */
  10364. #ifdef WIFSTOPPED
  10365. /*[clinic input]
  10366. os.WIFSTOPPED -> bool
  10367. status: int
  10368. Return True if the process returning status was stopped.
  10369. [clinic start generated code]*/
  10370. static int
  10371. os_WIFSTOPPED_impl(PyObject *module, int status)
  10372. /*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
  10373. {
  10374. WAIT_TYPE wait_status;
  10375. WAIT_STATUS_INT(wait_status) = status;
  10376. return WIFSTOPPED(wait_status);
  10377. }
  10378. #endif /* WIFSTOPPED */
  10379. #ifdef WIFSIGNALED
  10380. /*[clinic input]
  10381. os.WIFSIGNALED -> bool
  10382. status: int
  10383. Return True if the process returning status was terminated by a signal.
  10384. [clinic start generated code]*/
  10385. static int
  10386. os_WIFSIGNALED_impl(PyObject *module, int status)
  10387. /*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
  10388. {
  10389. WAIT_TYPE wait_status;
  10390. WAIT_STATUS_INT(wait_status) = status;
  10391. return WIFSIGNALED(wait_status);
  10392. }
  10393. #endif /* WIFSIGNALED */
  10394. #ifdef WIFEXITED
  10395. /*[clinic input]
  10396. os.WIFEXITED -> bool
  10397. status: int
  10398. Return True if the process returning status exited via the exit() system call.
  10399. [clinic start generated code]*/
  10400. static int
  10401. os_WIFEXITED_impl(PyObject *module, int status)
  10402. /*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
  10403. {
  10404. WAIT_TYPE wait_status;
  10405. WAIT_STATUS_INT(wait_status) = status;
  10406. return WIFEXITED(wait_status);
  10407. }
  10408. #endif /* WIFEXITED */
  10409. #ifdef WEXITSTATUS
  10410. /*[clinic input]
  10411. os.WEXITSTATUS -> int
  10412. status: int
  10413. Return the process return code from status.
  10414. [clinic start generated code]*/
  10415. static int
  10416. os_WEXITSTATUS_impl(PyObject *module, int status)
  10417. /*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
  10418. {
  10419. WAIT_TYPE wait_status;
  10420. WAIT_STATUS_INT(wait_status) = status;
  10421. return WEXITSTATUS(wait_status);
  10422. }
  10423. #endif /* WEXITSTATUS */
  10424. #ifdef WTERMSIG
  10425. /*[clinic input]
  10426. os.WTERMSIG -> int
  10427. status: int
  10428. Return the signal that terminated the process that provided the status value.
  10429. [clinic start generated code]*/
  10430. static int
  10431. os_WTERMSIG_impl(PyObject *module, int status)
  10432. /*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
  10433. {
  10434. WAIT_TYPE wait_status;
  10435. WAIT_STATUS_INT(wait_status) = status;
  10436. return WTERMSIG(wait_status);
  10437. }
  10438. #endif /* WTERMSIG */
  10439. #ifdef WSTOPSIG
  10440. /*[clinic input]
  10441. os.WSTOPSIG -> int
  10442. status: int
  10443. Return the signal that stopped the process that provided the status value.
  10444. [clinic start generated code]*/
  10445. static int
  10446. os_WSTOPSIG_impl(PyObject *module, int status)
  10447. /*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
  10448. {
  10449. WAIT_TYPE wait_status;
  10450. WAIT_STATUS_INT(wait_status) = status;
  10451. return WSTOPSIG(wait_status);
  10452. }
  10453. #endif /* WSTOPSIG */
  10454. #endif /* HAVE_SYS_WAIT_H */
  10455. #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
  10456. #ifdef _SCO_DS
  10457. /* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
  10458. needed definitions in sys/statvfs.h */
  10459. #define _SVID3
  10460. #endif
  10461. #include <sys/statvfs.h>
  10462. static PyObject*
  10463. _pystatvfs_fromstructstatvfs(PyObject *module, struct statvfs st) {
  10464. PyObject *StatVFSResultType = get_posix_state(module)->StatVFSResultType;
  10465. PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
  10466. if (v == NULL)
  10467. return NULL;
  10468. #if !defined(HAVE_LARGEFILE_SUPPORT)
  10469. PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
  10470. PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
  10471. PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
  10472. PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
  10473. PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
  10474. PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
  10475. PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
  10476. PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
  10477. PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
  10478. PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
  10479. #else
  10480. PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
  10481. PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
  10482. PyStructSequence_SET_ITEM(v, 2,
  10483. PyLong_FromLongLong((long long) st.f_blocks));
  10484. PyStructSequence_SET_ITEM(v, 3,
  10485. PyLong_FromLongLong((long long) st.f_bfree));
  10486. PyStructSequence_SET_ITEM(v, 4,
  10487. PyLong_FromLongLong((long long) st.f_bavail));
  10488. PyStructSequence_SET_ITEM(v, 5,
  10489. PyLong_FromLongLong((long long) st.f_files));
  10490. PyStructSequence_SET_ITEM(v, 6,
  10491. PyLong_FromLongLong((long long) st.f_ffree));
  10492. PyStructSequence_SET_ITEM(v, 7,
  10493. PyLong_FromLongLong((long long) st.f_favail));
  10494. PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
  10495. PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
  10496. #endif
  10497. /* The _ALL_SOURCE feature test macro defines f_fsid as a structure
  10498. * (issue #32390). */
  10499. #if defined(_AIX) && defined(_ALL_SOURCE)
  10500. PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
  10501. #else
  10502. PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
  10503. #endif
  10504. if (PyErr_Occurred()) {
  10505. Py_DECREF(v);
  10506. return NULL;
  10507. }
  10508. return v;
  10509. }
  10510. /*[clinic input]
  10511. os.fstatvfs
  10512. fd: int
  10513. /
  10514. Perform an fstatvfs system call on the given fd.
  10515. Equivalent to statvfs(fd).
  10516. [clinic start generated code]*/
  10517. static PyObject *
  10518. os_fstatvfs_impl(PyObject *module, int fd)
  10519. /*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
  10520. {
  10521. int result;
  10522. int async_err = 0;
  10523. struct statvfs st;
  10524. do {
  10525. Py_BEGIN_ALLOW_THREADS
  10526. result = fstatvfs(fd, &st);
  10527. Py_END_ALLOW_THREADS
  10528. } while (result != 0 && errno == EINTR &&
  10529. !(async_err = PyErr_CheckSignals()));
  10530. if (result != 0)
  10531. return (!async_err) ? posix_error() : NULL;
  10532. return _pystatvfs_fromstructstatvfs(module, st);
  10533. }
  10534. #endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
  10535. #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
  10536. #include <sys/statvfs.h>
  10537. /*[clinic input]
  10538. os.statvfs
  10539. path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
  10540. Perform a statvfs system call on the given path.
  10541. path may always be specified as a string.
  10542. On some platforms, path may also be specified as an open file descriptor.
  10543. If this functionality is unavailable, using it raises an exception.
  10544. [clinic start generated code]*/
  10545. static PyObject *
  10546. os_statvfs_impl(PyObject *module, path_t *path)
  10547. /*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
  10548. {
  10549. int result;
  10550. struct statvfs st;
  10551. Py_BEGIN_ALLOW_THREADS
  10552. #ifdef HAVE_FSTATVFS
  10553. if (path->fd != -1) {
  10554. result = fstatvfs(path->fd, &st);
  10555. }
  10556. else
  10557. #endif
  10558. result = statvfs(path->narrow, &st);
  10559. Py_END_ALLOW_THREADS
  10560. if (result) {
  10561. return path_error(path);
  10562. }
  10563. return _pystatvfs_fromstructstatvfs(module, st);
  10564. }
  10565. #endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
  10566. #ifdef MS_WINDOWS
  10567. /*[clinic input]
  10568. os._getdiskusage
  10569. path: path_t
  10570. Return disk usage statistics about the given path as a (total, free) tuple.
  10571. [clinic start generated code]*/
  10572. static PyObject *
  10573. os__getdiskusage_impl(PyObject *module, path_t *path)
  10574. /*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
  10575. {
  10576. BOOL retval;
  10577. ULARGE_INTEGER _, total, free;
  10578. DWORD err = 0;
  10579. Py_BEGIN_ALLOW_THREADS
  10580. retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
  10581. Py_END_ALLOW_THREADS
  10582. if (retval == 0) {
  10583. if (GetLastError() == ERROR_DIRECTORY) {
  10584. wchar_t *dir_path = NULL;
  10585. dir_path = PyMem_New(wchar_t, path->length + 1);
  10586. if (dir_path == NULL) {
  10587. return PyErr_NoMemory();
  10588. }
  10589. wcscpy_s(dir_path, path->length + 1, path->wide);
  10590. if (_dirnameW(dir_path) != -1) {
  10591. Py_BEGIN_ALLOW_THREADS
  10592. retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
  10593. Py_END_ALLOW_THREADS
  10594. }
  10595. /* Record the last error in case it's modified by PyMem_Free. */
  10596. err = GetLastError();
  10597. PyMem_Free(dir_path);
  10598. if (retval) {
  10599. goto success;
  10600. }
  10601. }
  10602. return PyErr_SetFromWindowsErr(err);
  10603. }
  10604. success:
  10605. return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
  10606. }
  10607. #endif /* MS_WINDOWS */
  10608. /* This is used for fpathconf(), pathconf(), confstr() and sysconf().
  10609. * It maps strings representing configuration variable names to
  10610. * integer values, allowing those functions to be called with the
  10611. * magic names instead of polluting the module's namespace with tons of
  10612. * rarely-used constants. There are three separate tables that use
  10613. * these definitions.
  10614. *
  10615. * This code is always included, even if none of the interfaces that
  10616. * need it are included. The #if hackery needed to avoid it would be
  10617. * sufficiently pervasive that it's not worth the loss of readability.
  10618. */
  10619. struct constdef {
  10620. const char *name;
  10621. int value;
  10622. };
  10623. static int
  10624. conv_confname(PyObject *arg, int *valuep, struct constdef *table,
  10625. size_t tablesize)
  10626. {
  10627. if (PyLong_Check(arg)) {
  10628. int value = _PyLong_AsInt(arg);
  10629. if (value == -1 && PyErr_Occurred())
  10630. return 0;
  10631. *valuep = value;
  10632. return 1;
  10633. }
  10634. else {
  10635. /* look up the value in the table using a binary search */
  10636. size_t lo = 0;
  10637. size_t mid;
  10638. size_t hi = tablesize;
  10639. int cmp;
  10640. const char *confname;
  10641. if (!PyUnicode_Check(arg)) {
  10642. PyErr_SetString(PyExc_TypeError,
  10643. "configuration names must be strings or integers");
  10644. return 0;
  10645. }
  10646. confname = PyUnicode_AsUTF8(arg);
  10647. if (confname == NULL)
  10648. return 0;
  10649. while (lo < hi) {
  10650. mid = (lo + hi) / 2;
  10651. cmp = strcmp(confname, table[mid].name);
  10652. if (cmp < 0)
  10653. hi = mid;
  10654. else if (cmp > 0)
  10655. lo = mid + 1;
  10656. else {
  10657. *valuep = table[mid].value;
  10658. return 1;
  10659. }
  10660. }
  10661. PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
  10662. return 0;
  10663. }
  10664. }
  10665. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  10666. static struct constdef posix_constants_pathconf[] = {
  10667. #ifdef _PC_ABI_AIO_XFER_MAX
  10668. {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
  10669. #endif
  10670. #ifdef _PC_ABI_ASYNC_IO
  10671. {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
  10672. #endif
  10673. #ifdef _PC_ASYNC_IO
  10674. {"PC_ASYNC_IO", _PC_ASYNC_IO},
  10675. #endif
  10676. #ifdef _PC_CHOWN_RESTRICTED
  10677. {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
  10678. #endif
  10679. #ifdef _PC_FILESIZEBITS
  10680. {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
  10681. #endif
  10682. #ifdef _PC_LAST
  10683. {"PC_LAST", _PC_LAST},
  10684. #endif
  10685. #ifdef _PC_LINK_MAX
  10686. {"PC_LINK_MAX", _PC_LINK_MAX},
  10687. #endif
  10688. #ifdef _PC_MAX_CANON
  10689. {"PC_MAX_CANON", _PC_MAX_CANON},
  10690. #endif
  10691. #ifdef _PC_MAX_INPUT
  10692. {"PC_MAX_INPUT", _PC_MAX_INPUT},
  10693. #endif
  10694. #ifdef _PC_NAME_MAX
  10695. {"PC_NAME_MAX", _PC_NAME_MAX},
  10696. #endif
  10697. #ifdef _PC_NO_TRUNC
  10698. {"PC_NO_TRUNC", _PC_NO_TRUNC},
  10699. #endif
  10700. #ifdef _PC_PATH_MAX
  10701. {"PC_PATH_MAX", _PC_PATH_MAX},
  10702. #endif
  10703. #ifdef _PC_PIPE_BUF
  10704. {"PC_PIPE_BUF", _PC_PIPE_BUF},
  10705. #endif
  10706. #ifdef _PC_PRIO_IO
  10707. {"PC_PRIO_IO", _PC_PRIO_IO},
  10708. #endif
  10709. #ifdef _PC_SOCK_MAXBUF
  10710. {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
  10711. #endif
  10712. #ifdef _PC_SYNC_IO
  10713. {"PC_SYNC_IO", _PC_SYNC_IO},
  10714. #endif
  10715. #ifdef _PC_VDISABLE
  10716. {"PC_VDISABLE", _PC_VDISABLE},
  10717. #endif
  10718. #ifdef _PC_ACL_ENABLED
  10719. {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
  10720. #endif
  10721. #ifdef _PC_MIN_HOLE_SIZE
  10722. {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
  10723. #endif
  10724. #ifdef _PC_ALLOC_SIZE_MIN
  10725. {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
  10726. #endif
  10727. #ifdef _PC_REC_INCR_XFER_SIZE
  10728. {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
  10729. #endif
  10730. #ifdef _PC_REC_MAX_XFER_SIZE
  10731. {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
  10732. #endif
  10733. #ifdef _PC_REC_MIN_XFER_SIZE
  10734. {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
  10735. #endif
  10736. #ifdef _PC_REC_XFER_ALIGN
  10737. {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
  10738. #endif
  10739. #ifdef _PC_SYMLINK_MAX
  10740. {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
  10741. #endif
  10742. #ifdef _PC_XATTR_ENABLED
  10743. {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
  10744. #endif
  10745. #ifdef _PC_XATTR_EXISTS
  10746. {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
  10747. #endif
  10748. #ifdef _PC_TIMESTAMP_RESOLUTION
  10749. {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
  10750. #endif
  10751. };
  10752. static int
  10753. conv_path_confname(PyObject *arg, int *valuep)
  10754. {
  10755. return conv_confname(arg, valuep, posix_constants_pathconf,
  10756. sizeof(posix_constants_pathconf)
  10757. / sizeof(struct constdef));
  10758. }
  10759. #endif
  10760. #ifdef HAVE_FPATHCONF
  10761. /*[clinic input]
  10762. os.fpathconf -> long
  10763. fd: fildes
  10764. name: path_confname
  10765. /
  10766. Return the configuration limit name for the file descriptor fd.
  10767. If there is no limit, return -1.
  10768. [clinic start generated code]*/
  10769. static long
  10770. os_fpathconf_impl(PyObject *module, int fd, int name)
  10771. /*[clinic end generated code: output=d5b7042425fc3e21 input=5b8d2471cfaae186]*/
  10772. {
  10773. long limit;
  10774. errno = 0;
  10775. limit = fpathconf(fd, name);
  10776. if (limit == -1 && errno != 0)
  10777. posix_error();
  10778. return limit;
  10779. }
  10780. #endif /* HAVE_FPATHCONF */
  10781. #ifdef HAVE_PATHCONF
  10782. /*[clinic input]
  10783. os.pathconf -> long
  10784. path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
  10785. name: path_confname
  10786. Return the configuration limit name for the file or directory path.
  10787. If there is no limit, return -1.
  10788. On some platforms, path may also be specified as an open file descriptor.
  10789. If this functionality is unavailable, using it raises an exception.
  10790. [clinic start generated code]*/
  10791. static long
  10792. os_pathconf_impl(PyObject *module, path_t *path, int name)
  10793. /*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
  10794. {
  10795. long limit;
  10796. errno = 0;
  10797. #ifdef HAVE_FPATHCONF
  10798. if (path->fd != -1)
  10799. limit = fpathconf(path->fd, name);
  10800. else
  10801. #endif
  10802. limit = pathconf(path->narrow, name);
  10803. if (limit == -1 && errno != 0) {
  10804. if (errno == EINVAL)
  10805. /* could be a path or name problem */
  10806. posix_error();
  10807. else
  10808. path_error(path);
  10809. }
  10810. return limit;
  10811. }
  10812. #endif /* HAVE_PATHCONF */
  10813. #ifdef HAVE_CONFSTR
  10814. static struct constdef posix_constants_confstr[] = {
  10815. #ifdef _CS_ARCHITECTURE
  10816. {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
  10817. #endif
  10818. #ifdef _CS_GNU_LIBC_VERSION
  10819. {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
  10820. #endif
  10821. #ifdef _CS_GNU_LIBPTHREAD_VERSION
  10822. {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
  10823. #endif
  10824. #ifdef _CS_HOSTNAME
  10825. {"CS_HOSTNAME", _CS_HOSTNAME},
  10826. #endif
  10827. #ifdef _CS_HW_PROVIDER
  10828. {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
  10829. #endif
  10830. #ifdef _CS_HW_SERIAL
  10831. {"CS_HW_SERIAL", _CS_HW_SERIAL},
  10832. #endif
  10833. #ifdef _CS_INITTAB_NAME
  10834. {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
  10835. #endif
  10836. #ifdef _CS_LFS64_CFLAGS
  10837. {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
  10838. #endif
  10839. #ifdef _CS_LFS64_LDFLAGS
  10840. {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
  10841. #endif
  10842. #ifdef _CS_LFS64_LIBS
  10843. {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
  10844. #endif
  10845. #ifdef _CS_LFS64_LINTFLAGS
  10846. {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
  10847. #endif
  10848. #ifdef _CS_LFS_CFLAGS
  10849. {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
  10850. #endif
  10851. #ifdef _CS_LFS_LDFLAGS
  10852. {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
  10853. #endif
  10854. #ifdef _CS_LFS_LIBS
  10855. {"CS_LFS_LIBS", _CS_LFS_LIBS},
  10856. #endif
  10857. #ifdef _CS_LFS_LINTFLAGS
  10858. {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
  10859. #endif
  10860. #ifdef _CS_MACHINE
  10861. {"CS_MACHINE", _CS_MACHINE},
  10862. #endif
  10863. #ifdef _CS_PATH
  10864. {"CS_PATH", _CS_PATH},
  10865. #endif
  10866. #ifdef _CS_RELEASE
  10867. {"CS_RELEASE", _CS_RELEASE},
  10868. #endif
  10869. #ifdef _CS_SRPC_DOMAIN
  10870. {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
  10871. #endif
  10872. #ifdef _CS_SYSNAME
  10873. {"CS_SYSNAME", _CS_SYSNAME},
  10874. #endif
  10875. #ifdef _CS_VERSION
  10876. {"CS_VERSION", _CS_VERSION},
  10877. #endif
  10878. #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
  10879. {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
  10880. #endif
  10881. #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
  10882. {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
  10883. #endif
  10884. #ifdef _CS_XBS5_ILP32_OFF32_LIBS
  10885. {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
  10886. #endif
  10887. #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
  10888. {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
  10889. #endif
  10890. #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
  10891. {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
  10892. #endif
  10893. #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
  10894. {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
  10895. #endif
  10896. #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
  10897. {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
  10898. #endif
  10899. #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
  10900. {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
  10901. #endif
  10902. #ifdef _CS_XBS5_LP64_OFF64_CFLAGS
  10903. {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
  10904. #endif
  10905. #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
  10906. {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
  10907. #endif
  10908. #ifdef _CS_XBS5_LP64_OFF64_LIBS
  10909. {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
  10910. #endif
  10911. #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
  10912. {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
  10913. #endif
  10914. #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
  10915. {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
  10916. #endif
  10917. #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
  10918. {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
  10919. #endif
  10920. #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
  10921. {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
  10922. #endif
  10923. #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
  10924. {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
  10925. #endif
  10926. #ifdef _MIPS_CS_AVAIL_PROCESSORS
  10927. {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
  10928. #endif
  10929. #ifdef _MIPS_CS_BASE
  10930. {"MIPS_CS_BASE", _MIPS_CS_BASE},
  10931. #endif
  10932. #ifdef _MIPS_CS_HOSTID
  10933. {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
  10934. #endif
  10935. #ifdef _MIPS_CS_HW_NAME
  10936. {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
  10937. #endif
  10938. #ifdef _MIPS_CS_NUM_PROCESSORS
  10939. {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
  10940. #endif
  10941. #ifdef _MIPS_CS_OSREL_MAJ
  10942. {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
  10943. #endif
  10944. #ifdef _MIPS_CS_OSREL_MIN
  10945. {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
  10946. #endif
  10947. #ifdef _MIPS_CS_OSREL_PATCH
  10948. {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
  10949. #endif
  10950. #ifdef _MIPS_CS_OS_NAME
  10951. {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
  10952. #endif
  10953. #ifdef _MIPS_CS_OS_PROVIDER
  10954. {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
  10955. #endif
  10956. #ifdef _MIPS_CS_PROCESSORS
  10957. {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
  10958. #endif
  10959. #ifdef _MIPS_CS_SERIAL
  10960. {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
  10961. #endif
  10962. #ifdef _MIPS_CS_VENDOR
  10963. {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
  10964. #endif
  10965. };
  10966. static int
  10967. conv_confstr_confname(PyObject *arg, int *valuep)
  10968. {
  10969. return conv_confname(arg, valuep, posix_constants_confstr,
  10970. sizeof(posix_constants_confstr)
  10971. / sizeof(struct constdef));
  10972. }
  10973. /*[clinic input]
  10974. os.confstr
  10975. name: confstr_confname
  10976. /
  10977. Return a string-valued system configuration variable.
  10978. [clinic start generated code]*/
  10979. static PyObject *
  10980. os_confstr_impl(PyObject *module, int name)
  10981. /*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
  10982. {
  10983. PyObject *result = NULL;
  10984. char buffer[255];
  10985. size_t len;
  10986. errno = 0;
  10987. len = confstr(name, buffer, sizeof(buffer));
  10988. if (len == 0) {
  10989. if (errno) {
  10990. posix_error();
  10991. return NULL;
  10992. }
  10993. else {
  10994. Py_RETURN_NONE;
  10995. }
  10996. }
  10997. if (len >= sizeof(buffer)) {
  10998. size_t len2;
  10999. char *buf = PyMem_Malloc(len);
  11000. if (buf == NULL)
  11001. return PyErr_NoMemory();
  11002. len2 = confstr(name, buf, len);
  11003. assert(len == len2);
  11004. result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
  11005. PyMem_Free(buf);
  11006. }
  11007. else
  11008. result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
  11009. return result;
  11010. }
  11011. #endif /* HAVE_CONFSTR */
  11012. #ifdef HAVE_SYSCONF
  11013. static struct constdef posix_constants_sysconf[] = {
  11014. #ifdef _SC_2_CHAR_TERM
  11015. {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
  11016. #endif
  11017. #ifdef _SC_2_C_BIND
  11018. {"SC_2_C_BIND", _SC_2_C_BIND},
  11019. #endif
  11020. #ifdef _SC_2_C_DEV
  11021. {"SC_2_C_DEV", _SC_2_C_DEV},
  11022. #endif
  11023. #ifdef _SC_2_C_VERSION
  11024. {"SC_2_C_VERSION", _SC_2_C_VERSION},
  11025. #endif
  11026. #ifdef _SC_2_FORT_DEV
  11027. {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
  11028. #endif
  11029. #ifdef _SC_2_FORT_RUN
  11030. {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
  11031. #endif
  11032. #ifdef _SC_2_LOCALEDEF
  11033. {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
  11034. #endif
  11035. #ifdef _SC_2_SW_DEV
  11036. {"SC_2_SW_DEV", _SC_2_SW_DEV},
  11037. #endif
  11038. #ifdef _SC_2_UPE
  11039. {"SC_2_UPE", _SC_2_UPE},
  11040. #endif
  11041. #ifdef _SC_2_VERSION
  11042. {"SC_2_VERSION", _SC_2_VERSION},
  11043. #endif
  11044. #ifdef _SC_ABI_ASYNCHRONOUS_IO
  11045. {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
  11046. #endif
  11047. #ifdef _SC_ACL
  11048. {"SC_ACL", _SC_ACL},
  11049. #endif
  11050. #ifdef _SC_AIO_LISTIO_MAX
  11051. {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
  11052. #endif
  11053. #ifdef _SC_AIO_MAX
  11054. {"SC_AIO_MAX", _SC_AIO_MAX},
  11055. #endif
  11056. #ifdef _SC_AIO_PRIO_DELTA_MAX
  11057. {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
  11058. #endif
  11059. #ifdef _SC_ARG_MAX
  11060. {"SC_ARG_MAX", _SC_ARG_MAX},
  11061. #endif
  11062. #ifdef _SC_ASYNCHRONOUS_IO
  11063. {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
  11064. #endif
  11065. #ifdef _SC_ATEXIT_MAX
  11066. {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
  11067. #endif
  11068. #ifdef _SC_AUDIT
  11069. {"SC_AUDIT", _SC_AUDIT},
  11070. #endif
  11071. #ifdef _SC_AVPHYS_PAGES
  11072. {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
  11073. #endif
  11074. #ifdef _SC_BC_BASE_MAX
  11075. {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
  11076. #endif
  11077. #ifdef _SC_BC_DIM_MAX
  11078. {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
  11079. #endif
  11080. #ifdef _SC_BC_SCALE_MAX
  11081. {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
  11082. #endif
  11083. #ifdef _SC_BC_STRING_MAX
  11084. {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
  11085. #endif
  11086. #ifdef _SC_CAP
  11087. {"SC_CAP", _SC_CAP},
  11088. #endif
  11089. #ifdef _SC_CHARCLASS_NAME_MAX
  11090. {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
  11091. #endif
  11092. #ifdef _SC_CHAR_BIT
  11093. {"SC_CHAR_BIT", _SC_CHAR_BIT},
  11094. #endif
  11095. #ifdef _SC_CHAR_MAX
  11096. {"SC_CHAR_MAX", _SC_CHAR_MAX},
  11097. #endif
  11098. #ifdef _SC_CHAR_MIN
  11099. {"SC_CHAR_MIN", _SC_CHAR_MIN},
  11100. #endif
  11101. #ifdef _SC_CHILD_MAX
  11102. {"SC_CHILD_MAX", _SC_CHILD_MAX},
  11103. #endif
  11104. #ifdef _SC_CLK_TCK
  11105. {"SC_CLK_TCK", _SC_CLK_TCK},
  11106. #endif
  11107. #ifdef _SC_COHER_BLKSZ
  11108. {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
  11109. #endif
  11110. #ifdef _SC_COLL_WEIGHTS_MAX
  11111. {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
  11112. #endif
  11113. #ifdef _SC_DCACHE_ASSOC
  11114. {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
  11115. #endif
  11116. #ifdef _SC_DCACHE_BLKSZ
  11117. {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
  11118. #endif
  11119. #ifdef _SC_DCACHE_LINESZ
  11120. {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
  11121. #endif
  11122. #ifdef _SC_DCACHE_SZ
  11123. {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
  11124. #endif
  11125. #ifdef _SC_DCACHE_TBLKSZ
  11126. {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
  11127. #endif
  11128. #ifdef _SC_DELAYTIMER_MAX
  11129. {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
  11130. #endif
  11131. #ifdef _SC_EQUIV_CLASS_MAX
  11132. {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
  11133. #endif
  11134. #ifdef _SC_EXPR_NEST_MAX
  11135. {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
  11136. #endif
  11137. #ifdef _SC_FSYNC
  11138. {"SC_FSYNC", _SC_FSYNC},
  11139. #endif
  11140. #ifdef _SC_GETGR_R_SIZE_MAX
  11141. {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
  11142. #endif
  11143. #ifdef _SC_GETPW_R_SIZE_MAX
  11144. {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
  11145. #endif
  11146. #ifdef _SC_ICACHE_ASSOC
  11147. {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
  11148. #endif
  11149. #ifdef _SC_ICACHE_BLKSZ
  11150. {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
  11151. #endif
  11152. #ifdef _SC_ICACHE_LINESZ
  11153. {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
  11154. #endif
  11155. #ifdef _SC_ICACHE_SZ
  11156. {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
  11157. #endif
  11158. #ifdef _SC_INF
  11159. {"SC_INF", _SC_INF},
  11160. #endif
  11161. #ifdef _SC_INT_MAX
  11162. {"SC_INT_MAX", _SC_INT_MAX},
  11163. #endif
  11164. #ifdef _SC_INT_MIN
  11165. {"SC_INT_MIN", _SC_INT_MIN},
  11166. #endif
  11167. #ifdef _SC_IOV_MAX
  11168. {"SC_IOV_MAX", _SC_IOV_MAX},
  11169. #endif
  11170. #ifdef _SC_IP_SECOPTS
  11171. {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
  11172. #endif
  11173. #ifdef _SC_JOB_CONTROL
  11174. {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
  11175. #endif
  11176. #ifdef _SC_KERN_POINTERS
  11177. {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
  11178. #endif
  11179. #ifdef _SC_KERN_SIM
  11180. {"SC_KERN_SIM", _SC_KERN_SIM},
  11181. #endif
  11182. #ifdef _SC_LINE_MAX
  11183. {"SC_LINE_MAX", _SC_LINE_MAX},
  11184. #endif
  11185. #ifdef _SC_LOGIN_NAME_MAX
  11186. {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
  11187. #endif
  11188. #ifdef _SC_LOGNAME_MAX
  11189. {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
  11190. #endif
  11191. #ifdef _SC_LONG_BIT
  11192. {"SC_LONG_BIT", _SC_LONG_BIT},
  11193. #endif
  11194. #ifdef _SC_MAC
  11195. {"SC_MAC", _SC_MAC},
  11196. #endif
  11197. #ifdef _SC_MAPPED_FILES
  11198. {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
  11199. #endif
  11200. #ifdef _SC_MAXPID
  11201. {"SC_MAXPID", _SC_MAXPID},
  11202. #endif
  11203. #ifdef _SC_MB_LEN_MAX
  11204. {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
  11205. #endif
  11206. #ifdef _SC_MEMLOCK
  11207. {"SC_MEMLOCK", _SC_MEMLOCK},
  11208. #endif
  11209. #ifdef _SC_MEMLOCK_RANGE
  11210. {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
  11211. #endif
  11212. #ifdef _SC_MEMORY_PROTECTION
  11213. {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
  11214. #endif
  11215. #ifdef _SC_MESSAGE_PASSING
  11216. {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
  11217. #endif
  11218. #ifdef _SC_MMAP_FIXED_ALIGNMENT
  11219. {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
  11220. #endif
  11221. #ifdef _SC_MQ_OPEN_MAX
  11222. {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
  11223. #endif
  11224. #ifdef _SC_MQ_PRIO_MAX
  11225. {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
  11226. #endif
  11227. #ifdef _SC_NACLS_MAX
  11228. {"SC_NACLS_MAX", _SC_NACLS_MAX},
  11229. #endif
  11230. #ifdef _SC_NGROUPS_MAX
  11231. {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
  11232. #endif
  11233. #ifdef _SC_NL_ARGMAX
  11234. {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
  11235. #endif
  11236. #ifdef _SC_NL_LANGMAX
  11237. {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
  11238. #endif
  11239. #ifdef _SC_NL_MSGMAX
  11240. {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
  11241. #endif
  11242. #ifdef _SC_NL_NMAX
  11243. {"SC_NL_NMAX", _SC_NL_NMAX},
  11244. #endif
  11245. #ifdef _SC_NL_SETMAX
  11246. {"SC_NL_SETMAX", _SC_NL_SETMAX},
  11247. #endif
  11248. #ifdef _SC_NL_TEXTMAX
  11249. {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
  11250. #endif
  11251. #ifdef _SC_NPROCESSORS_CONF
  11252. {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
  11253. #endif
  11254. #ifdef _SC_NPROCESSORS_ONLN
  11255. {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
  11256. #endif
  11257. #ifdef _SC_NPROC_CONF
  11258. {"SC_NPROC_CONF", _SC_NPROC_CONF},
  11259. #endif
  11260. #ifdef _SC_NPROC_ONLN
  11261. {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
  11262. #endif
  11263. #ifdef _SC_NZERO
  11264. {"SC_NZERO", _SC_NZERO},
  11265. #endif
  11266. #ifdef _SC_OPEN_MAX
  11267. {"SC_OPEN_MAX", _SC_OPEN_MAX},
  11268. #endif
  11269. #ifdef _SC_PAGESIZE
  11270. {"SC_PAGESIZE", _SC_PAGESIZE},
  11271. #endif
  11272. #ifdef _SC_PAGE_SIZE
  11273. {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
  11274. #endif
  11275. #ifdef _SC_AIX_REALMEM
  11276. {"SC_AIX_REALMEM", _SC_AIX_REALMEM},
  11277. #endif
  11278. #ifdef _SC_PASS_MAX
  11279. {"SC_PASS_MAX", _SC_PASS_MAX},
  11280. #endif
  11281. #ifdef _SC_PHYS_PAGES
  11282. {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
  11283. #endif
  11284. #ifdef _SC_PII
  11285. {"SC_PII", _SC_PII},
  11286. #endif
  11287. #ifdef _SC_PII_INTERNET
  11288. {"SC_PII_INTERNET", _SC_PII_INTERNET},
  11289. #endif
  11290. #ifdef _SC_PII_INTERNET_DGRAM
  11291. {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
  11292. #endif
  11293. #ifdef _SC_PII_INTERNET_STREAM
  11294. {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
  11295. #endif
  11296. #ifdef _SC_PII_OSI
  11297. {"SC_PII_OSI", _SC_PII_OSI},
  11298. #endif
  11299. #ifdef _SC_PII_OSI_CLTS
  11300. {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
  11301. #endif
  11302. #ifdef _SC_PII_OSI_COTS
  11303. {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
  11304. #endif
  11305. #ifdef _SC_PII_OSI_M
  11306. {"SC_PII_OSI_M", _SC_PII_OSI_M},
  11307. #endif
  11308. #ifdef _SC_PII_SOCKET
  11309. {"SC_PII_SOCKET", _SC_PII_SOCKET},
  11310. #endif
  11311. #ifdef _SC_PII_XTI
  11312. {"SC_PII_XTI", _SC_PII_XTI},
  11313. #endif
  11314. #ifdef _SC_POLL
  11315. {"SC_POLL", _SC_POLL},
  11316. #endif
  11317. #ifdef _SC_PRIORITIZED_IO
  11318. {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
  11319. #endif
  11320. #ifdef _SC_PRIORITY_SCHEDULING
  11321. {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
  11322. #endif
  11323. #ifdef _SC_REALTIME_SIGNALS
  11324. {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
  11325. #endif
  11326. #ifdef _SC_RE_DUP_MAX
  11327. {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
  11328. #endif
  11329. #ifdef _SC_RTSIG_MAX
  11330. {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
  11331. #endif
  11332. #ifdef _SC_SAVED_IDS
  11333. {"SC_SAVED_IDS", _SC_SAVED_IDS},
  11334. #endif
  11335. #ifdef _SC_SCHAR_MAX
  11336. {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
  11337. #endif
  11338. #ifdef _SC_SCHAR_MIN
  11339. {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
  11340. #endif
  11341. #ifdef _SC_SELECT
  11342. {"SC_SELECT", _SC_SELECT},
  11343. #endif
  11344. #ifdef _SC_SEMAPHORES
  11345. {"SC_SEMAPHORES", _SC_SEMAPHORES},
  11346. #endif
  11347. #ifdef _SC_SEM_NSEMS_MAX
  11348. {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
  11349. #endif
  11350. #ifdef _SC_SEM_VALUE_MAX
  11351. {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
  11352. #endif
  11353. #ifdef _SC_SHARED_MEMORY_OBJECTS
  11354. {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
  11355. #endif
  11356. #ifdef _SC_SHRT_MAX
  11357. {"SC_SHRT_MAX", _SC_SHRT_MAX},
  11358. #endif
  11359. #ifdef _SC_SHRT_MIN
  11360. {"SC_SHRT_MIN", _SC_SHRT_MIN},
  11361. #endif
  11362. #ifdef _SC_SIGQUEUE_MAX
  11363. {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
  11364. #endif
  11365. #ifdef _SC_SIGRT_MAX
  11366. {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
  11367. #endif
  11368. #ifdef _SC_SIGRT_MIN
  11369. {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
  11370. #endif
  11371. #ifdef _SC_SOFTPOWER
  11372. {"SC_SOFTPOWER", _SC_SOFTPOWER},
  11373. #endif
  11374. #ifdef _SC_SPLIT_CACHE
  11375. {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
  11376. #endif
  11377. #ifdef _SC_SSIZE_MAX
  11378. {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
  11379. #endif
  11380. #ifdef _SC_STACK_PROT
  11381. {"SC_STACK_PROT", _SC_STACK_PROT},
  11382. #endif
  11383. #ifdef _SC_STREAM_MAX
  11384. {"SC_STREAM_MAX", _SC_STREAM_MAX},
  11385. #endif
  11386. #ifdef _SC_SYNCHRONIZED_IO
  11387. {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
  11388. #endif
  11389. #ifdef _SC_THREADS
  11390. {"SC_THREADS", _SC_THREADS},
  11391. #endif
  11392. #ifdef _SC_THREAD_ATTR_STACKADDR
  11393. {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
  11394. #endif
  11395. #ifdef _SC_THREAD_ATTR_STACKSIZE
  11396. {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
  11397. #endif
  11398. #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
  11399. {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
  11400. #endif
  11401. #ifdef _SC_THREAD_KEYS_MAX
  11402. {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
  11403. #endif
  11404. #ifdef _SC_THREAD_PRIORITY_SCHEDULING
  11405. {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
  11406. #endif
  11407. #ifdef _SC_THREAD_PRIO_INHERIT
  11408. {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
  11409. #endif
  11410. #ifdef _SC_THREAD_PRIO_PROTECT
  11411. {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
  11412. #endif
  11413. #ifdef _SC_THREAD_PROCESS_SHARED
  11414. {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
  11415. #endif
  11416. #ifdef _SC_THREAD_SAFE_FUNCTIONS
  11417. {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
  11418. #endif
  11419. #ifdef _SC_THREAD_STACK_MIN
  11420. {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
  11421. #endif
  11422. #ifdef _SC_THREAD_THREADS_MAX
  11423. {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
  11424. #endif
  11425. #ifdef _SC_TIMERS
  11426. {"SC_TIMERS", _SC_TIMERS},
  11427. #endif
  11428. #ifdef _SC_TIMER_MAX
  11429. {"SC_TIMER_MAX", _SC_TIMER_MAX},
  11430. #endif
  11431. #ifdef _SC_TTY_NAME_MAX
  11432. {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
  11433. #endif
  11434. #ifdef _SC_TZNAME_MAX
  11435. {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
  11436. #endif
  11437. #ifdef _SC_T_IOV_MAX
  11438. {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
  11439. #endif
  11440. #ifdef _SC_UCHAR_MAX
  11441. {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
  11442. #endif
  11443. #ifdef _SC_UINT_MAX
  11444. {"SC_UINT_MAX", _SC_UINT_MAX},
  11445. #endif
  11446. #ifdef _SC_UIO_MAXIOV
  11447. {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
  11448. #endif
  11449. #ifdef _SC_ULONG_MAX
  11450. {"SC_ULONG_MAX", _SC_ULONG_MAX},
  11451. #endif
  11452. #ifdef _SC_USHRT_MAX
  11453. {"SC_USHRT_MAX", _SC_USHRT_MAX},
  11454. #endif
  11455. #ifdef _SC_VERSION
  11456. {"SC_VERSION", _SC_VERSION},
  11457. #endif
  11458. #ifdef _SC_WORD_BIT
  11459. {"SC_WORD_BIT", _SC_WORD_BIT},
  11460. #endif
  11461. #ifdef _SC_XBS5_ILP32_OFF32
  11462. {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
  11463. #endif
  11464. #ifdef _SC_XBS5_ILP32_OFFBIG
  11465. {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
  11466. #endif
  11467. #ifdef _SC_XBS5_LP64_OFF64
  11468. {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
  11469. #endif
  11470. #ifdef _SC_XBS5_LPBIG_OFFBIG
  11471. {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
  11472. #endif
  11473. #ifdef _SC_XOPEN_CRYPT
  11474. {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
  11475. #endif
  11476. #ifdef _SC_XOPEN_ENH_I18N
  11477. {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
  11478. #endif
  11479. #ifdef _SC_XOPEN_LEGACY
  11480. {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
  11481. #endif
  11482. #ifdef _SC_XOPEN_REALTIME
  11483. {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
  11484. #endif
  11485. #ifdef _SC_XOPEN_REALTIME_THREADS
  11486. {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
  11487. #endif
  11488. #ifdef _SC_XOPEN_SHM
  11489. {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
  11490. #endif
  11491. #ifdef _SC_XOPEN_UNIX
  11492. {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
  11493. #endif
  11494. #ifdef _SC_XOPEN_VERSION
  11495. {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
  11496. #endif
  11497. #ifdef _SC_XOPEN_XCU_VERSION
  11498. {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
  11499. #endif
  11500. #ifdef _SC_XOPEN_XPG2
  11501. {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
  11502. #endif
  11503. #ifdef _SC_XOPEN_XPG3
  11504. {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
  11505. #endif
  11506. #ifdef _SC_XOPEN_XPG4
  11507. {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
  11508. #endif
  11509. #ifdef _SC_MINSIGSTKSZ
  11510. {"SC_MINSIGSTKSZ", _SC_MINSIGSTKSZ},
  11511. #endif
  11512. };
  11513. static int
  11514. conv_sysconf_confname(PyObject *arg, int *valuep)
  11515. {
  11516. return conv_confname(arg, valuep, posix_constants_sysconf,
  11517. sizeof(posix_constants_sysconf)
  11518. / sizeof(struct constdef));
  11519. }
  11520. /*[clinic input]
  11521. os.sysconf -> long
  11522. name: sysconf_confname
  11523. /
  11524. Return an integer-valued system configuration variable.
  11525. [clinic start generated code]*/
  11526. static long
  11527. os_sysconf_impl(PyObject *module, int name)
  11528. /*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
  11529. {
  11530. long value;
  11531. errno = 0;
  11532. value = sysconf(name);
  11533. if (value == -1 && errno != 0)
  11534. posix_error();
  11535. return value;
  11536. }
  11537. #endif /* HAVE_SYSCONF */
  11538. /* This code is used to ensure that the tables of configuration value names
  11539. * are in sorted order as required by conv_confname(), and also to build
  11540. * the exported dictionaries that are used to publish information about the
  11541. * names available on the host platform.
  11542. *
  11543. * Sorting the table at runtime ensures that the table is properly ordered
  11544. * when used, even for platforms we're not able to test on. It also makes
  11545. * it easier to add additional entries to the tables.
  11546. */
  11547. static int
  11548. cmp_constdefs(const void *v1, const void *v2)
  11549. {
  11550. const struct constdef *c1 =
  11551. (const struct constdef *) v1;
  11552. const struct constdef *c2 =
  11553. (const struct constdef *) v2;
  11554. return strcmp(c1->name, c2->name);
  11555. }
  11556. static int
  11557. setup_confname_table(struct constdef *table, size_t tablesize,
  11558. const char *tablename, PyObject *module)
  11559. {
  11560. PyObject *d = NULL;
  11561. size_t i;
  11562. qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
  11563. d = PyDict_New();
  11564. if (d == NULL)
  11565. return -1;
  11566. for (i=0; i < tablesize; ++i) {
  11567. PyObject *o = PyLong_FromLong(table[i].value);
  11568. if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
  11569. Py_XDECREF(o);
  11570. Py_DECREF(d);
  11571. return -1;
  11572. }
  11573. Py_DECREF(o);
  11574. }
  11575. return _PyModule_Add(module, tablename, d);
  11576. }
  11577. /* Return -1 on failure, 0 on success. */
  11578. static int
  11579. setup_confname_tables(PyObject *module)
  11580. {
  11581. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  11582. if (setup_confname_table(posix_constants_pathconf,
  11583. sizeof(posix_constants_pathconf)
  11584. / sizeof(struct constdef),
  11585. "pathconf_names", module))
  11586. return -1;
  11587. #endif
  11588. #ifdef HAVE_CONFSTR
  11589. if (setup_confname_table(posix_constants_confstr,
  11590. sizeof(posix_constants_confstr)
  11591. / sizeof(struct constdef),
  11592. "confstr_names", module))
  11593. return -1;
  11594. #endif
  11595. #ifdef HAVE_SYSCONF
  11596. if (setup_confname_table(posix_constants_sysconf,
  11597. sizeof(posix_constants_sysconf)
  11598. / sizeof(struct constdef),
  11599. "sysconf_names", module))
  11600. return -1;
  11601. #endif
  11602. return 0;
  11603. }
  11604. /*[clinic input]
  11605. os.abort
  11606. Abort the interpreter immediately.
  11607. This function 'dumps core' or otherwise fails in the hardest way possible
  11608. on the hosting operating system. This function never returns.
  11609. [clinic start generated code]*/
  11610. static PyObject *
  11611. os_abort_impl(PyObject *module)
  11612. /*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
  11613. {
  11614. abort();
  11615. /*NOTREACHED*/
  11616. #ifndef __clang__
  11617. /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
  11618. GCC emits a warning without "return NULL;" (compiler bug?), but Clang
  11619. is smarter and emits a warning on the return. */
  11620. Py_FatalError("abort() called from Python code didn't abort!");
  11621. return NULL;
  11622. #endif
  11623. }
  11624. #ifdef MS_WINDOWS
  11625. /* Grab ShellExecute dynamically from shell32 */
  11626. static int has_ShellExecute = -1;
  11627. static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
  11628. LPCWSTR, INT);
  11629. static int
  11630. check_ShellExecute(void)
  11631. {
  11632. HINSTANCE hShell32;
  11633. /* only recheck */
  11634. if (-1 == has_ShellExecute) {
  11635. Py_BEGIN_ALLOW_THREADS
  11636. /* Security note: this call is not vulnerable to "DLL hijacking".
  11637. SHELL32 is part of "KnownDLLs" and so Windows always load
  11638. the system SHELL32.DLL, even if there is another SHELL32.DLL
  11639. in the DLL search path. */
  11640. hShell32 = LoadLibraryW(L"SHELL32");
  11641. if (hShell32) {
  11642. *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
  11643. "ShellExecuteW");
  11644. has_ShellExecute = Py_ShellExecuteW != NULL;
  11645. } else {
  11646. has_ShellExecute = 0;
  11647. }
  11648. Py_END_ALLOW_THREADS
  11649. }
  11650. return has_ShellExecute;
  11651. }
  11652. /*[clinic input]
  11653. os.startfile
  11654. filepath: path_t
  11655. operation: Py_UNICODE = NULL
  11656. arguments: Py_UNICODE = NULL
  11657. cwd: path_t(nullable=True) = None
  11658. show_cmd: int = 1
  11659. Start a file with its associated application.
  11660. When "operation" is not specified or "open", this acts like
  11661. double-clicking the file in Explorer, or giving the file name as an
  11662. argument to the DOS "start" command: the file is opened with whatever
  11663. application (if any) its extension is associated.
  11664. When another "operation" is given, it specifies what should be done with
  11665. the file. A typical operation is "print".
  11666. "arguments" is passed to the application, but should be omitted if the
  11667. file is a document.
  11668. "cwd" is the working directory for the operation. If "filepath" is
  11669. relative, it will be resolved against this directory. This argument
  11670. should usually be an absolute path.
  11671. "show_cmd" can be used to override the recommended visibility option.
  11672. See the Windows ShellExecute documentation for values.
  11673. startfile returns as soon as the associated application is launched.
  11674. There is no option to wait for the application to close, and no way
  11675. to retrieve the application's exit status.
  11676. The filepath is relative to the current directory. If you want to use
  11677. an absolute path, make sure the first character is not a slash ("/");
  11678. the underlying Win32 ShellExecute function doesn't work if it is.
  11679. [clinic start generated code]*/
  11680. static PyObject *
  11681. os_startfile_impl(PyObject *module, path_t *filepath,
  11682. const Py_UNICODE *operation, const Py_UNICODE *arguments,
  11683. path_t *cwd, int show_cmd)
  11684. /*[clinic end generated code: output=3baa4f9795841880 input=8248997b80669622]*/
  11685. {
  11686. HINSTANCE rc;
  11687. if(!check_ShellExecute()) {
  11688. /* If the OS doesn't have ShellExecute, return a
  11689. NotImplementedError. */
  11690. return PyErr_Format(PyExc_NotImplementedError,
  11691. "startfile not available on this platform");
  11692. }
  11693. if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
  11694. return NULL;
  11695. }
  11696. if (PySys_Audit("os.startfile/2", "OuuOi", filepath->object, operation,
  11697. arguments, cwd->object ? cwd->object : Py_None,
  11698. show_cmd) < 0) {
  11699. return NULL;
  11700. }
  11701. Py_BEGIN_ALLOW_THREADS
  11702. rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
  11703. arguments, cwd->wide, show_cmd);
  11704. Py_END_ALLOW_THREADS
  11705. if (rc <= (HINSTANCE)32) {
  11706. win32_error_object("startfile", filepath->object);
  11707. return NULL;
  11708. }
  11709. Py_RETURN_NONE;
  11710. }
  11711. #endif /* MS_WINDOWS */
  11712. #ifdef HAVE_GETLOADAVG
  11713. /*[clinic input]
  11714. os.getloadavg
  11715. Return average recent system load information.
  11716. Return the number of processes in the system run queue averaged over
  11717. the last 1, 5, and 15 minutes as a tuple of three floats.
  11718. Raises OSError if the load average was unobtainable.
  11719. [clinic start generated code]*/
  11720. static PyObject *
  11721. os_getloadavg_impl(PyObject *module)
  11722. /*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
  11723. {
  11724. double loadavg[3];
  11725. if (getloadavg(loadavg, 3)!=3) {
  11726. PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
  11727. return NULL;
  11728. } else
  11729. return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
  11730. }
  11731. #endif /* HAVE_GETLOADAVG */
  11732. /*[clinic input]
  11733. os.device_encoding
  11734. fd: int
  11735. Return a string describing the encoding of a terminal's file descriptor.
  11736. The file descriptor must be attached to a terminal.
  11737. If the device is not a terminal, return None.
  11738. [clinic start generated code]*/
  11739. static PyObject *
  11740. os_device_encoding_impl(PyObject *module, int fd)
  11741. /*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
  11742. {
  11743. return _Py_device_encoding(fd);
  11744. }
  11745. #ifdef HAVE_SETRESUID
  11746. /*[clinic input]
  11747. os.setresuid
  11748. ruid: uid_t
  11749. euid: uid_t
  11750. suid: uid_t
  11751. /
  11752. Set the current process's real, effective, and saved user ids.
  11753. [clinic start generated code]*/
  11754. static PyObject *
  11755. os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
  11756. /*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
  11757. {
  11758. if (setresuid(ruid, euid, suid) < 0)
  11759. return posix_error();
  11760. Py_RETURN_NONE;
  11761. }
  11762. #endif /* HAVE_SETRESUID */
  11763. #ifdef HAVE_SETRESGID
  11764. /*[clinic input]
  11765. os.setresgid
  11766. rgid: gid_t
  11767. egid: gid_t
  11768. sgid: gid_t
  11769. /
  11770. Set the current process's real, effective, and saved group ids.
  11771. [clinic start generated code]*/
  11772. static PyObject *
  11773. os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
  11774. /*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
  11775. {
  11776. if (setresgid(rgid, egid, sgid) < 0)
  11777. return posix_error();
  11778. Py_RETURN_NONE;
  11779. }
  11780. #endif /* HAVE_SETRESGID */
  11781. #ifdef HAVE_GETRESUID
  11782. /*[clinic input]
  11783. os.getresuid
  11784. Return a tuple of the current process's real, effective, and saved user ids.
  11785. [clinic start generated code]*/
  11786. static PyObject *
  11787. os_getresuid_impl(PyObject *module)
  11788. /*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
  11789. {
  11790. uid_t ruid, euid, suid;
  11791. if (getresuid(&ruid, &euid, &suid) < 0)
  11792. return posix_error();
  11793. return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
  11794. _PyLong_FromUid(euid),
  11795. _PyLong_FromUid(suid));
  11796. }
  11797. #endif /* HAVE_GETRESUID */
  11798. #ifdef HAVE_GETRESGID
  11799. /*[clinic input]
  11800. os.getresgid
  11801. Return a tuple of the current process's real, effective, and saved group ids.
  11802. [clinic start generated code]*/
  11803. static PyObject *
  11804. os_getresgid_impl(PyObject *module)
  11805. /*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
  11806. {
  11807. gid_t rgid, egid, sgid;
  11808. if (getresgid(&rgid, &egid, &sgid) < 0)
  11809. return posix_error();
  11810. return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
  11811. _PyLong_FromGid(egid),
  11812. _PyLong_FromGid(sgid));
  11813. }
  11814. #endif /* HAVE_GETRESGID */
  11815. #ifdef USE_XATTRS
  11816. /*[clinic input]
  11817. os.getxattr
  11818. path: path_t(allow_fd=True)
  11819. attribute: path_t
  11820. *
  11821. follow_symlinks: bool = True
  11822. Return the value of extended attribute attribute on path.
  11823. path may be either a string, a path-like object, or an open file descriptor.
  11824. If follow_symlinks is False, and the last element of the path is a symbolic
  11825. link, getxattr will examine the symbolic link itself instead of the file
  11826. the link points to.
  11827. [clinic start generated code]*/
  11828. static PyObject *
  11829. os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11830. int follow_symlinks)
  11831. /*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
  11832. {
  11833. Py_ssize_t i;
  11834. PyObject *buffer = NULL;
  11835. if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
  11836. return NULL;
  11837. if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
  11838. return NULL;
  11839. }
  11840. for (i = 0; ; i++) {
  11841. void *ptr;
  11842. ssize_t result;
  11843. static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
  11844. Py_ssize_t buffer_size = buffer_sizes[i];
  11845. if (!buffer_size) {
  11846. path_error(path);
  11847. return NULL;
  11848. }
  11849. buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
  11850. if (!buffer)
  11851. return NULL;
  11852. ptr = PyBytes_AS_STRING(buffer);
  11853. Py_BEGIN_ALLOW_THREADS;
  11854. if (path->fd >= 0)
  11855. result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
  11856. else if (follow_symlinks)
  11857. result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
  11858. else
  11859. result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
  11860. Py_END_ALLOW_THREADS;
  11861. if (result < 0) {
  11862. if (errno == ERANGE) {
  11863. Py_DECREF(buffer);
  11864. continue;
  11865. }
  11866. path_error(path);
  11867. Py_DECREF(buffer);
  11868. return NULL;
  11869. }
  11870. if (result != buffer_size) {
  11871. /* Can only shrink. */
  11872. _PyBytes_Resize(&buffer, result);
  11873. }
  11874. break;
  11875. }
  11876. return buffer;
  11877. }
  11878. /*[clinic input]
  11879. os.setxattr
  11880. path: path_t(allow_fd=True)
  11881. attribute: path_t
  11882. value: Py_buffer
  11883. flags: int = 0
  11884. *
  11885. follow_symlinks: bool = True
  11886. Set extended attribute attribute on path to value.
  11887. path may be either a string, a path-like object, or an open file descriptor.
  11888. If follow_symlinks is False, and the last element of the path is a symbolic
  11889. link, setxattr will modify the symbolic link itself instead of the file
  11890. the link points to.
  11891. [clinic start generated code]*/
  11892. static PyObject *
  11893. os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11894. Py_buffer *value, int flags, int follow_symlinks)
  11895. /*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
  11896. {
  11897. ssize_t result;
  11898. if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
  11899. return NULL;
  11900. if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
  11901. value->buf, value->len, flags) < 0) {
  11902. return NULL;
  11903. }
  11904. Py_BEGIN_ALLOW_THREADS;
  11905. if (path->fd > -1)
  11906. result = fsetxattr(path->fd, attribute->narrow,
  11907. value->buf, value->len, flags);
  11908. else if (follow_symlinks)
  11909. result = setxattr(path->narrow, attribute->narrow,
  11910. value->buf, value->len, flags);
  11911. else
  11912. result = lsetxattr(path->narrow, attribute->narrow,
  11913. value->buf, value->len, flags);
  11914. Py_END_ALLOW_THREADS;
  11915. if (result) {
  11916. path_error(path);
  11917. return NULL;
  11918. }
  11919. Py_RETURN_NONE;
  11920. }
  11921. /*[clinic input]
  11922. os.removexattr
  11923. path: path_t(allow_fd=True)
  11924. attribute: path_t
  11925. *
  11926. follow_symlinks: bool = True
  11927. Remove extended attribute attribute on path.
  11928. path may be either a string, a path-like object, or an open file descriptor.
  11929. If follow_symlinks is False, and the last element of the path is a symbolic
  11930. link, removexattr will modify the symbolic link itself instead of the file
  11931. the link points to.
  11932. [clinic start generated code]*/
  11933. static PyObject *
  11934. os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
  11935. int follow_symlinks)
  11936. /*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
  11937. {
  11938. ssize_t result;
  11939. if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
  11940. return NULL;
  11941. if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
  11942. return NULL;
  11943. }
  11944. Py_BEGIN_ALLOW_THREADS;
  11945. if (path->fd > -1)
  11946. result = fremovexattr(path->fd, attribute->narrow);
  11947. else if (follow_symlinks)
  11948. result = removexattr(path->narrow, attribute->narrow);
  11949. else
  11950. result = lremovexattr(path->narrow, attribute->narrow);
  11951. Py_END_ALLOW_THREADS;
  11952. if (result) {
  11953. return path_error(path);
  11954. }
  11955. Py_RETURN_NONE;
  11956. }
  11957. /*[clinic input]
  11958. os.listxattr
  11959. path: path_t(allow_fd=True, nullable=True) = None
  11960. *
  11961. follow_symlinks: bool = True
  11962. Return a list of extended attributes on path.
  11963. path may be either None, a string, a path-like object, or an open file descriptor.
  11964. if path is None, listxattr will examine the current directory.
  11965. If follow_symlinks is False, and the last element of the path is a symbolic
  11966. link, listxattr will examine the symbolic link itself instead of the file
  11967. the link points to.
  11968. [clinic start generated code]*/
  11969. static PyObject *
  11970. os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
  11971. /*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
  11972. {
  11973. Py_ssize_t i;
  11974. PyObject *result = NULL;
  11975. const char *name;
  11976. char *buffer = NULL;
  11977. if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
  11978. goto exit;
  11979. if (PySys_Audit("os.listxattr", "(O)",
  11980. path->object ? path->object : Py_None) < 0) {
  11981. return NULL;
  11982. }
  11983. name = path->narrow ? path->narrow : ".";
  11984. for (i = 0; ; i++) {
  11985. const char *start, *trace, *end;
  11986. ssize_t length;
  11987. static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
  11988. Py_ssize_t buffer_size = buffer_sizes[i];
  11989. if (!buffer_size) {
  11990. /* ERANGE */
  11991. path_error(path);
  11992. break;
  11993. }
  11994. buffer = PyMem_Malloc(buffer_size);
  11995. if (!buffer) {
  11996. PyErr_NoMemory();
  11997. break;
  11998. }
  11999. Py_BEGIN_ALLOW_THREADS;
  12000. if (path->fd > -1)
  12001. length = flistxattr(path->fd, buffer, buffer_size);
  12002. else if (follow_symlinks)
  12003. length = listxattr(name, buffer, buffer_size);
  12004. else
  12005. length = llistxattr(name, buffer, buffer_size);
  12006. Py_END_ALLOW_THREADS;
  12007. if (length < 0) {
  12008. if (errno == ERANGE) {
  12009. PyMem_Free(buffer);
  12010. buffer = NULL;
  12011. continue;
  12012. }
  12013. path_error(path);
  12014. break;
  12015. }
  12016. result = PyList_New(0);
  12017. if (!result) {
  12018. goto exit;
  12019. }
  12020. end = buffer + length;
  12021. for (trace = start = buffer; trace != end; trace++) {
  12022. if (!*trace) {
  12023. int error;
  12024. PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
  12025. trace - start);
  12026. if (!attribute) {
  12027. Py_SETREF(result, NULL);
  12028. goto exit;
  12029. }
  12030. error = PyList_Append(result, attribute);
  12031. Py_DECREF(attribute);
  12032. if (error) {
  12033. Py_SETREF(result, NULL);
  12034. goto exit;
  12035. }
  12036. start = trace + 1;
  12037. }
  12038. }
  12039. break;
  12040. }
  12041. exit:
  12042. if (buffer)
  12043. PyMem_Free(buffer);
  12044. return result;
  12045. }
  12046. #endif /* USE_XATTRS */
  12047. /*[clinic input]
  12048. os.urandom
  12049. size: Py_ssize_t
  12050. /
  12051. Return a bytes object containing random bytes suitable for cryptographic use.
  12052. [clinic start generated code]*/
  12053. static PyObject *
  12054. os_urandom_impl(PyObject *module, Py_ssize_t size)
  12055. /*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
  12056. {
  12057. PyObject *bytes;
  12058. int result;
  12059. if (size < 0)
  12060. return PyErr_Format(PyExc_ValueError,
  12061. "negative argument not allowed");
  12062. bytes = PyBytes_FromStringAndSize(NULL, size);
  12063. if (bytes == NULL)
  12064. return NULL;
  12065. result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
  12066. if (result == -1) {
  12067. Py_DECREF(bytes);
  12068. return NULL;
  12069. }
  12070. return bytes;
  12071. }
  12072. #ifdef HAVE_MEMFD_CREATE
  12073. /*[clinic input]
  12074. os.memfd_create
  12075. name: FSConverter
  12076. flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
  12077. [clinic start generated code]*/
  12078. static PyObject *
  12079. os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
  12080. /*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
  12081. {
  12082. int fd;
  12083. const char *bytes = PyBytes_AS_STRING(name);
  12084. Py_BEGIN_ALLOW_THREADS
  12085. fd = memfd_create(bytes, flags);
  12086. Py_END_ALLOW_THREADS
  12087. if (fd == -1) {
  12088. return PyErr_SetFromErrno(PyExc_OSError);
  12089. }
  12090. return PyLong_FromLong(fd);
  12091. }
  12092. #endif
  12093. #if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
  12094. /*[clinic input]
  12095. os.eventfd
  12096. initval: unsigned_int
  12097. flags: int(c_default="EFD_CLOEXEC") = EFD_CLOEXEC
  12098. Creates and returns an event notification file descriptor.
  12099. [clinic start generated code]*/
  12100. static PyObject *
  12101. os_eventfd_impl(PyObject *module, unsigned int initval, int flags)
  12102. /*[clinic end generated code: output=ce9c9bbd1446f2de input=66203e3c50c4028b]*/
  12103. {
  12104. /* initval is limited to uint32_t, internal counter is uint64_t */
  12105. int fd;
  12106. Py_BEGIN_ALLOW_THREADS
  12107. fd = eventfd(initval, flags);
  12108. Py_END_ALLOW_THREADS
  12109. if (fd == -1) {
  12110. return PyErr_SetFromErrno(PyExc_OSError);
  12111. }
  12112. return PyLong_FromLong(fd);
  12113. }
  12114. /*[clinic input]
  12115. os.eventfd_read
  12116. fd: fildes
  12117. Read eventfd value
  12118. [clinic start generated code]*/
  12119. static PyObject *
  12120. os_eventfd_read_impl(PyObject *module, int fd)
  12121. /*[clinic end generated code: output=8f2c7b59a3521fd1 input=110f8b57fa596afe]*/
  12122. {
  12123. eventfd_t value;
  12124. int result;
  12125. Py_BEGIN_ALLOW_THREADS
  12126. result = eventfd_read(fd, &value);
  12127. Py_END_ALLOW_THREADS
  12128. if (result == -1) {
  12129. return PyErr_SetFromErrno(PyExc_OSError);
  12130. }
  12131. return PyLong_FromUnsignedLongLong(value);
  12132. }
  12133. /*[clinic input]
  12134. os.eventfd_write
  12135. fd: fildes
  12136. value: unsigned_long_long
  12137. Write eventfd value.
  12138. [clinic start generated code]*/
  12139. static PyObject *
  12140. os_eventfd_write_impl(PyObject *module, int fd, unsigned long long value)
  12141. /*[clinic end generated code: output=bebd9040bbf987f5 input=156de8555be5a949]*/
  12142. {
  12143. int result;
  12144. Py_BEGIN_ALLOW_THREADS
  12145. result = eventfd_write(fd, value);
  12146. Py_END_ALLOW_THREADS
  12147. if (result == -1) {
  12148. return PyErr_SetFromErrno(PyExc_OSError);
  12149. }
  12150. Py_RETURN_NONE;
  12151. }
  12152. #endif /* HAVE_EVENTFD && EFD_CLOEXEC */
  12153. /* Terminal size querying */
  12154. PyDoc_STRVAR(TerminalSize_docstring,
  12155. "A tuple of (columns, lines) for holding terminal window size");
  12156. static PyStructSequence_Field TerminalSize_fields[] = {
  12157. {"columns", "width of the terminal window in characters"},
  12158. {"lines", "height of the terminal window in characters"},
  12159. {NULL, NULL}
  12160. };
  12161. static PyStructSequence_Desc TerminalSize_desc = {
  12162. "os.terminal_size",
  12163. TerminalSize_docstring,
  12164. TerminalSize_fields,
  12165. 2,
  12166. };
  12167. #if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
  12168. /*[clinic input]
  12169. os.get_terminal_size
  12170. fd: int(c_default="fileno(stdout)", py_default="<unrepresentable>") = -1
  12171. /
  12172. Return the size of the terminal window as (columns, lines).
  12173. The optional argument fd (default standard output) specifies
  12174. which file descriptor should be queried.
  12175. If the file descriptor is not connected to a terminal, an OSError
  12176. is thrown.
  12177. This function will only be defined if an implementation is
  12178. available for this system.
  12179. shutil.get_terminal_size is the high-level function which should
  12180. normally be used, os.get_terminal_size is the low-level implementation.
  12181. [clinic start generated code]*/
  12182. static PyObject *
  12183. os_get_terminal_size_impl(PyObject *module, int fd)
  12184. /*[clinic end generated code: output=fbab93acef980508 input=ead5679b82ddb920]*/
  12185. {
  12186. int columns, lines;
  12187. PyObject *termsize;
  12188. /* Under some conditions stdout may not be connected and
  12189. * fileno(stdout) may point to an invalid file descriptor. For example
  12190. * GUI apps don't have valid standard streams by default.
  12191. *
  12192. * If this happens, and the optional fd argument is not present,
  12193. * the ioctl below will fail returning EBADF. This is what we want.
  12194. */
  12195. #ifdef TERMSIZE_USE_IOCTL
  12196. {
  12197. struct winsize w;
  12198. if (ioctl(fd, TIOCGWINSZ, &w))
  12199. return PyErr_SetFromErrno(PyExc_OSError);
  12200. columns = w.ws_col;
  12201. lines = w.ws_row;
  12202. }
  12203. #endif /* TERMSIZE_USE_IOCTL */
  12204. #ifdef TERMSIZE_USE_CONIO
  12205. {
  12206. HANDLE handle;
  12207. CONSOLE_SCREEN_BUFFER_INFO csbi;
  12208. handle = _Py_get_osfhandle(fd);
  12209. if (handle == INVALID_HANDLE_VALUE)
  12210. return NULL;
  12211. if (!GetConsoleScreenBufferInfo(handle, &csbi))
  12212. return PyErr_SetFromWindowsErr(0);
  12213. columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
  12214. lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
  12215. }
  12216. #endif /* TERMSIZE_USE_CONIO */
  12217. PyObject *TerminalSizeType = get_posix_state(module)->TerminalSizeType;
  12218. termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
  12219. if (termsize == NULL)
  12220. return NULL;
  12221. PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
  12222. PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
  12223. if (PyErr_Occurred()) {
  12224. Py_DECREF(termsize);
  12225. return NULL;
  12226. }
  12227. return termsize;
  12228. }
  12229. #endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
  12230. /*[clinic input]
  12231. os.cpu_count
  12232. Return the number of CPUs in the system; return None if indeterminable.
  12233. This number is not equivalent to the number of CPUs the current process can
  12234. use. The number of usable CPUs can be obtained with
  12235. ``len(os.sched_getaffinity(0))``
  12236. [clinic start generated code]*/
  12237. static PyObject *
  12238. os_cpu_count_impl(PyObject *module)
  12239. /*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
  12240. {
  12241. int ncpu = 0;
  12242. #ifdef MS_WINDOWS
  12243. #ifdef MS_WINDOWS_DESKTOP
  12244. ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
  12245. #endif
  12246. #elif defined(__hpux)
  12247. ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
  12248. #elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
  12249. ncpu = sysconf(_SC_NPROCESSORS_ONLN);
  12250. #elif defined(__VXWORKS__)
  12251. ncpu = _Py_popcount32(vxCpuEnabledGet());
  12252. #elif defined(__DragonFly__) || \
  12253. defined(__OpenBSD__) || \
  12254. defined(__FreeBSD__) || \
  12255. defined(__NetBSD__) || \
  12256. defined(__APPLE__)
  12257. int mib[2];
  12258. size_t len = sizeof(ncpu);
  12259. mib[0] = CTL_HW;
  12260. mib[1] = HW_NCPU;
  12261. if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
  12262. ncpu = 0;
  12263. #endif
  12264. if (ncpu >= 1)
  12265. return PyLong_FromLong(ncpu);
  12266. else
  12267. Py_RETURN_NONE;
  12268. }
  12269. /*[clinic input]
  12270. os.get_inheritable -> bool
  12271. fd: int
  12272. /
  12273. Get the close-on-exe flag of the specified file descriptor.
  12274. [clinic start generated code]*/
  12275. static int
  12276. os_get_inheritable_impl(PyObject *module, int fd)
  12277. /*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
  12278. {
  12279. int return_value;
  12280. _Py_BEGIN_SUPPRESS_IPH
  12281. return_value = _Py_get_inheritable(fd);
  12282. _Py_END_SUPPRESS_IPH
  12283. return return_value;
  12284. }
  12285. /*[clinic input]
  12286. os.set_inheritable
  12287. fd: int
  12288. inheritable: int
  12289. /
  12290. Set the inheritable flag of the specified file descriptor.
  12291. [clinic start generated code]*/
  12292. static PyObject *
  12293. os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
  12294. /*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
  12295. {
  12296. int result;
  12297. _Py_BEGIN_SUPPRESS_IPH
  12298. result = _Py_set_inheritable(fd, inheritable, NULL);
  12299. _Py_END_SUPPRESS_IPH
  12300. if (result < 0)
  12301. return NULL;
  12302. Py_RETURN_NONE;
  12303. }
  12304. #ifdef MS_WINDOWS
  12305. #ifndef HANDLE_FLAG_INHERIT
  12306. #define HANDLE_FLAG_INHERIT 0x00000001
  12307. #endif
  12308. /*[clinic input]
  12309. os.get_handle_inheritable -> bool
  12310. handle: intptr_t
  12311. /
  12312. Get the close-on-exe flag of the specified file descriptor.
  12313. [clinic start generated code]*/
  12314. static int
  12315. os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
  12316. /*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
  12317. {
  12318. DWORD flags;
  12319. if (!GetHandleInformation((HANDLE)handle, &flags)) {
  12320. PyErr_SetFromWindowsErr(0);
  12321. return -1;
  12322. }
  12323. return flags & HANDLE_FLAG_INHERIT;
  12324. }
  12325. /*[clinic input]
  12326. os.set_handle_inheritable
  12327. handle: intptr_t
  12328. inheritable: bool
  12329. /
  12330. Set the inheritable flag of the specified handle.
  12331. [clinic start generated code]*/
  12332. static PyObject *
  12333. os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
  12334. int inheritable)
  12335. /*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
  12336. {
  12337. DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
  12338. if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
  12339. PyErr_SetFromWindowsErr(0);
  12340. return NULL;
  12341. }
  12342. Py_RETURN_NONE;
  12343. }
  12344. #endif /* MS_WINDOWS */
  12345. /*[clinic input]
  12346. os.get_blocking -> bool
  12347. fd: int
  12348. /
  12349. Get the blocking mode of the file descriptor.
  12350. Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
  12351. [clinic start generated code]*/
  12352. static int
  12353. os_get_blocking_impl(PyObject *module, int fd)
  12354. /*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
  12355. {
  12356. int blocking;
  12357. _Py_BEGIN_SUPPRESS_IPH
  12358. blocking = _Py_get_blocking(fd);
  12359. _Py_END_SUPPRESS_IPH
  12360. return blocking;
  12361. }
  12362. /*[clinic input]
  12363. os.set_blocking
  12364. fd: int
  12365. blocking: bool
  12366. /
  12367. Set the blocking mode of the specified file descriptor.
  12368. Set the O_NONBLOCK flag if blocking is False,
  12369. clear the O_NONBLOCK flag otherwise.
  12370. [clinic start generated code]*/
  12371. static PyObject *
  12372. os_set_blocking_impl(PyObject *module, int fd, int blocking)
  12373. /*[clinic end generated code: output=384eb43aa0762a9d input=7e9dfc9b14804dd4]*/
  12374. {
  12375. int result;
  12376. _Py_BEGIN_SUPPRESS_IPH
  12377. result = _Py_set_blocking(fd, blocking);
  12378. _Py_END_SUPPRESS_IPH
  12379. if (result < 0)
  12380. return NULL;
  12381. Py_RETURN_NONE;
  12382. }
  12383. /*[clinic input]
  12384. class os.DirEntry "DirEntry *" "DirEntryType"
  12385. [clinic start generated code]*/
  12386. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
  12387. typedef struct {
  12388. PyObject_HEAD
  12389. PyObject *name;
  12390. PyObject *path;
  12391. PyObject *stat;
  12392. PyObject *lstat;
  12393. #ifdef MS_WINDOWS
  12394. struct _Py_stat_struct win32_lstat;
  12395. uint64_t win32_file_index;
  12396. uint64_t win32_file_index_high;
  12397. int got_file_index;
  12398. #else /* POSIX */
  12399. #ifdef HAVE_DIRENT_D_TYPE
  12400. unsigned char d_type;
  12401. #endif
  12402. ino_t d_ino;
  12403. int dir_fd;
  12404. #endif
  12405. } DirEntry;
  12406. static void
  12407. DirEntry_dealloc(DirEntry *entry)
  12408. {
  12409. PyTypeObject *tp = Py_TYPE(entry);
  12410. Py_XDECREF(entry->name);
  12411. Py_XDECREF(entry->path);
  12412. Py_XDECREF(entry->stat);
  12413. Py_XDECREF(entry->lstat);
  12414. freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
  12415. free_func(entry);
  12416. Py_DECREF(tp);
  12417. }
  12418. /* Forward reference */
  12419. static int
  12420. DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
  12421. int follow_symlinks, unsigned short mode_bits);
  12422. /*[clinic input]
  12423. os.DirEntry.is_symlink -> bool
  12424. defining_class: defining_class
  12425. /
  12426. Return True if the entry is a symbolic link; cached per entry.
  12427. [clinic start generated code]*/
  12428. static int
  12429. os_DirEntry_is_symlink_impl(DirEntry *self, PyTypeObject *defining_class)
  12430. /*[clinic end generated code: output=293096d589b6d47c input=e9acc5ee4d511113]*/
  12431. {
  12432. #ifdef MS_WINDOWS
  12433. return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
  12434. #elif defined(HAVE_DIRENT_D_TYPE)
  12435. /* POSIX */
  12436. if (self->d_type != DT_UNKNOWN)
  12437. return self->d_type == DT_LNK;
  12438. else
  12439. return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
  12440. #else
  12441. /* POSIX without d_type */
  12442. return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
  12443. #endif
  12444. }
  12445. /*[clinic input]
  12446. os.DirEntry.is_junction -> bool
  12447. defining_class: defining_class
  12448. /
  12449. Return True if the entry is a junction; cached per entry.
  12450. [clinic start generated code]*/
  12451. static int
  12452. os_DirEntry_is_junction_impl(DirEntry *self, PyTypeObject *defining_class)
  12453. /*[clinic end generated code: output=7061a07b0ef2cd1f input=475cd36fb7d4723f]*/
  12454. {
  12455. #ifdef MS_WINDOWS
  12456. return self->win32_lstat.st_reparse_tag == IO_REPARSE_TAG_MOUNT_POINT;
  12457. #else
  12458. return 0;
  12459. #endif
  12460. }
  12461. static PyObject *
  12462. DirEntry_fetch_stat(PyObject *module, DirEntry *self, int follow_symlinks)
  12463. {
  12464. int result;
  12465. STRUCT_STAT st;
  12466. PyObject *ub;
  12467. #ifdef MS_WINDOWS
  12468. if (!PyUnicode_FSDecoder(self->path, &ub))
  12469. return NULL;
  12470. wchar_t *path = PyUnicode_AsWideCharString(ub, NULL);
  12471. Py_DECREF(ub);
  12472. #else /* POSIX */
  12473. if (!PyUnicode_FSConverter(self->path, &ub))
  12474. return NULL;
  12475. const char *path = PyBytes_AS_STRING(ub);
  12476. if (self->dir_fd != DEFAULT_DIR_FD) {
  12477. #ifdef HAVE_FSTATAT
  12478. if (HAVE_FSTATAT_RUNTIME) {
  12479. Py_BEGIN_ALLOW_THREADS
  12480. result = fstatat(self->dir_fd, path, &st,
  12481. follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
  12482. Py_END_ALLOW_THREADS
  12483. } else
  12484. #endif /* HAVE_FSTATAT */
  12485. {
  12486. Py_DECREF(ub);
  12487. PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
  12488. return NULL;
  12489. }
  12490. }
  12491. else
  12492. #endif
  12493. {
  12494. Py_BEGIN_ALLOW_THREADS
  12495. if (follow_symlinks) {
  12496. result = STAT(path, &st);
  12497. }
  12498. else {
  12499. result = LSTAT(path, &st);
  12500. }
  12501. Py_END_ALLOW_THREADS
  12502. }
  12503. int saved_errno = errno;
  12504. #if defined(MS_WINDOWS)
  12505. PyMem_Free(path);
  12506. #else
  12507. Py_DECREF(ub);
  12508. #endif
  12509. if (result != 0) {
  12510. errno = saved_errno;
  12511. path_object_error(self->path);
  12512. return NULL;
  12513. }
  12514. return _pystat_fromstructstat(module, &st);
  12515. }
  12516. static PyObject *
  12517. DirEntry_get_lstat(PyTypeObject *defining_class, DirEntry *self)
  12518. {
  12519. if (!self->lstat) {
  12520. PyObject *module = PyType_GetModule(defining_class);
  12521. #ifdef MS_WINDOWS
  12522. self->lstat = _pystat_fromstructstat(module, &self->win32_lstat);
  12523. #else /* POSIX */
  12524. self->lstat = DirEntry_fetch_stat(module, self, 0);
  12525. #endif
  12526. }
  12527. return Py_XNewRef(self->lstat);
  12528. }
  12529. /*[clinic input]
  12530. os.DirEntry.stat
  12531. defining_class: defining_class
  12532. /
  12533. *
  12534. follow_symlinks: bool = True
  12535. Return stat_result object for the entry; cached per entry.
  12536. [clinic start generated code]*/
  12537. static PyObject *
  12538. os_DirEntry_stat_impl(DirEntry *self, PyTypeObject *defining_class,
  12539. int follow_symlinks)
  12540. /*[clinic end generated code: output=23f803e19c3e780e input=e816273c4e67ee98]*/
  12541. {
  12542. if (!follow_symlinks) {
  12543. return DirEntry_get_lstat(defining_class, self);
  12544. }
  12545. if (!self->stat) {
  12546. int result = os_DirEntry_is_symlink_impl(self, defining_class);
  12547. if (result == -1) {
  12548. return NULL;
  12549. }
  12550. if (result) {
  12551. PyObject *module = PyType_GetModule(defining_class);
  12552. self->stat = DirEntry_fetch_stat(module, self, 1);
  12553. }
  12554. else {
  12555. self->stat = DirEntry_get_lstat(defining_class, self);
  12556. }
  12557. }
  12558. return Py_XNewRef(self->stat);
  12559. }
  12560. /* Set exception and return -1 on error, 0 for False, 1 for True */
  12561. static int
  12562. DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
  12563. int follow_symlinks, unsigned short mode_bits)
  12564. {
  12565. PyObject *stat = NULL;
  12566. PyObject *st_mode = NULL;
  12567. long mode;
  12568. int result;
  12569. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12570. int is_symlink;
  12571. int need_stat;
  12572. #endif
  12573. #ifdef MS_WINDOWS
  12574. unsigned long dir_bits;
  12575. #endif
  12576. #ifdef MS_WINDOWS
  12577. is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
  12578. need_stat = follow_symlinks && is_symlink;
  12579. #elif defined(HAVE_DIRENT_D_TYPE)
  12580. is_symlink = self->d_type == DT_LNK;
  12581. need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
  12582. #endif
  12583. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12584. if (need_stat) {
  12585. #endif
  12586. stat = os_DirEntry_stat_impl(self, defining_class, follow_symlinks);
  12587. if (!stat) {
  12588. if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
  12589. /* If file doesn't exist (anymore), then return False
  12590. (i.e., say it's not a file/directory) */
  12591. PyErr_Clear();
  12592. return 0;
  12593. }
  12594. goto error;
  12595. }
  12596. _posixstate* state = get_posix_state(PyType_GetModule(defining_class));
  12597. st_mode = PyObject_GetAttr(stat, state->st_mode);
  12598. if (!st_mode)
  12599. goto error;
  12600. mode = PyLong_AsLong(st_mode);
  12601. if (mode == -1 && PyErr_Occurred())
  12602. goto error;
  12603. Py_CLEAR(st_mode);
  12604. Py_CLEAR(stat);
  12605. result = (mode & S_IFMT) == mode_bits;
  12606. #if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
  12607. }
  12608. else if (is_symlink) {
  12609. assert(mode_bits != S_IFLNK);
  12610. result = 0;
  12611. }
  12612. else {
  12613. assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
  12614. #ifdef MS_WINDOWS
  12615. dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
  12616. if (mode_bits == S_IFDIR)
  12617. result = dir_bits != 0;
  12618. else
  12619. result = dir_bits == 0;
  12620. #else /* POSIX */
  12621. if (mode_bits == S_IFDIR)
  12622. result = self->d_type == DT_DIR;
  12623. else
  12624. result = self->d_type == DT_REG;
  12625. #endif
  12626. }
  12627. #endif
  12628. return result;
  12629. error:
  12630. Py_XDECREF(st_mode);
  12631. Py_XDECREF(stat);
  12632. return -1;
  12633. }
  12634. /*[clinic input]
  12635. os.DirEntry.is_dir -> bool
  12636. defining_class: defining_class
  12637. /
  12638. *
  12639. follow_symlinks: bool = True
  12640. Return True if the entry is a directory; cached per entry.
  12641. [clinic start generated code]*/
  12642. static int
  12643. os_DirEntry_is_dir_impl(DirEntry *self, PyTypeObject *defining_class,
  12644. int follow_symlinks)
  12645. /*[clinic end generated code: output=0cd453b9c0987fdf input=1a4ffd6dec9920cb]*/
  12646. {
  12647. return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFDIR);
  12648. }
  12649. /*[clinic input]
  12650. os.DirEntry.is_file -> bool
  12651. defining_class: defining_class
  12652. /
  12653. *
  12654. follow_symlinks: bool = True
  12655. Return True if the entry is a file; cached per entry.
  12656. [clinic start generated code]*/
  12657. static int
  12658. os_DirEntry_is_file_impl(DirEntry *self, PyTypeObject *defining_class,
  12659. int follow_symlinks)
  12660. /*[clinic end generated code: output=f7c277ab5ba80908 input=0a64c5a12e802e3b]*/
  12661. {
  12662. return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFREG);
  12663. }
  12664. /*[clinic input]
  12665. os.DirEntry.inode
  12666. Return inode of the entry; cached per entry.
  12667. [clinic start generated code]*/
  12668. static PyObject *
  12669. os_DirEntry_inode_impl(DirEntry *self)
  12670. /*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
  12671. {
  12672. #ifdef MS_WINDOWS
  12673. if (!self->got_file_index) {
  12674. PyObject *unicode;
  12675. STRUCT_STAT stat;
  12676. int result;
  12677. if (!PyUnicode_FSDecoder(self->path, &unicode))
  12678. return NULL;
  12679. wchar_t *path = PyUnicode_AsWideCharString(unicode, NULL);
  12680. Py_DECREF(unicode);
  12681. result = LSTAT(path, &stat);
  12682. int saved_errno = errno;
  12683. PyMem_Free(path);
  12684. if (result != 0) {
  12685. errno = saved_errno;
  12686. return path_object_error(self->path);
  12687. }
  12688. self->win32_file_index = stat.st_ino;
  12689. self->win32_file_index_high = stat.st_ino_high;
  12690. self->got_file_index = 1;
  12691. }
  12692. return _pystat_l128_from_l64_l64(self->win32_file_index, self->win32_file_index_high);
  12693. #else /* POSIX */
  12694. static_assert(sizeof(unsigned long long) >= sizeof(self->d_ino),
  12695. "DirEntry.d_ino is larger than unsigned long long");
  12696. return PyLong_FromUnsignedLongLong(self->d_ino);
  12697. #endif
  12698. }
  12699. static PyObject *
  12700. DirEntry_repr(DirEntry *self)
  12701. {
  12702. return PyUnicode_FromFormat("<DirEntry %R>", self->name);
  12703. }
  12704. /*[clinic input]
  12705. os.DirEntry.__fspath__
  12706. Returns the path for the entry.
  12707. [clinic start generated code]*/
  12708. static PyObject *
  12709. os_DirEntry___fspath___impl(DirEntry *self)
  12710. /*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
  12711. {
  12712. return Py_NewRef(self->path);
  12713. }
  12714. static PyMemberDef DirEntry_members[] = {
  12715. {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
  12716. "the entry's base filename, relative to scandir() \"path\" argument"},
  12717. {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
  12718. "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
  12719. {NULL}
  12720. };
  12721. #include "clinic/posixmodule.c.h"
  12722. static PyMethodDef DirEntry_methods[] = {
  12723. OS_DIRENTRY_IS_DIR_METHODDEF
  12724. OS_DIRENTRY_IS_FILE_METHODDEF
  12725. OS_DIRENTRY_IS_SYMLINK_METHODDEF
  12726. OS_DIRENTRY_IS_JUNCTION_METHODDEF
  12727. OS_DIRENTRY_STAT_METHODDEF
  12728. OS_DIRENTRY_INODE_METHODDEF
  12729. OS_DIRENTRY___FSPATH___METHODDEF
  12730. {"__class_getitem__", Py_GenericAlias,
  12731. METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  12732. {NULL}
  12733. };
  12734. static PyType_Slot DirEntryType_slots[] = {
  12735. {Py_tp_dealloc, DirEntry_dealloc},
  12736. {Py_tp_repr, DirEntry_repr},
  12737. {Py_tp_methods, DirEntry_methods},
  12738. {Py_tp_members, DirEntry_members},
  12739. {0, 0},
  12740. };
  12741. static PyType_Spec DirEntryType_spec = {
  12742. MODNAME ".DirEntry",
  12743. sizeof(DirEntry),
  12744. 0,
  12745. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
  12746. DirEntryType_slots
  12747. };
  12748. #ifdef MS_WINDOWS
  12749. static wchar_t *
  12750. join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
  12751. {
  12752. Py_ssize_t path_len;
  12753. Py_ssize_t size;
  12754. wchar_t *result;
  12755. wchar_t ch;
  12756. if (!path_wide) { /* Default arg: "." */
  12757. path_wide = L".";
  12758. path_len = 1;
  12759. }
  12760. else {
  12761. path_len = wcslen(path_wide);
  12762. }
  12763. /* The +1's are for the path separator and the NUL */
  12764. size = path_len + 1 + wcslen(filename) + 1;
  12765. result = PyMem_New(wchar_t, size);
  12766. if (!result) {
  12767. PyErr_NoMemory();
  12768. return NULL;
  12769. }
  12770. wcscpy(result, path_wide);
  12771. if (path_len > 0) {
  12772. ch = result[path_len - 1];
  12773. if (ch != SEP && ch != ALTSEP && ch != L':')
  12774. result[path_len++] = SEP;
  12775. wcscpy(result + path_len, filename);
  12776. }
  12777. return result;
  12778. }
  12779. static PyObject *
  12780. DirEntry_from_find_data(PyObject *module, path_t *path, WIN32_FIND_DATAW *dataW)
  12781. {
  12782. DirEntry *entry;
  12783. BY_HANDLE_FILE_INFORMATION file_info;
  12784. ULONG reparse_tag;
  12785. wchar_t *joined_path;
  12786. PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
  12787. entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
  12788. if (!entry)
  12789. return NULL;
  12790. entry->name = NULL;
  12791. entry->path = NULL;
  12792. entry->stat = NULL;
  12793. entry->lstat = NULL;
  12794. entry->got_file_index = 0;
  12795. entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
  12796. if (!entry->name)
  12797. goto error;
  12798. if (path->narrow) {
  12799. Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
  12800. if (!entry->name)
  12801. goto error;
  12802. }
  12803. joined_path = join_path_filenameW(path->wide, dataW->cFileName);
  12804. if (!joined_path)
  12805. goto error;
  12806. entry->path = PyUnicode_FromWideChar(joined_path, -1);
  12807. PyMem_Free(joined_path);
  12808. if (!entry->path)
  12809. goto error;
  12810. if (path->narrow) {
  12811. Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
  12812. if (!entry->path)
  12813. goto error;
  12814. }
  12815. find_data_to_file_info(dataW, &file_info, &reparse_tag);
  12816. _Py_attribute_data_to_stat(&file_info, reparse_tag, NULL, NULL, &entry->win32_lstat);
  12817. return (PyObject *)entry;
  12818. error:
  12819. Py_DECREF(entry);
  12820. return NULL;
  12821. }
  12822. #else /* POSIX */
  12823. static char *
  12824. join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
  12825. {
  12826. Py_ssize_t path_len;
  12827. Py_ssize_t size;
  12828. char *result;
  12829. if (!path_narrow) { /* Default arg: "." */
  12830. path_narrow = ".";
  12831. path_len = 1;
  12832. }
  12833. else {
  12834. path_len = strlen(path_narrow);
  12835. }
  12836. if (filename_len == -1)
  12837. filename_len = strlen(filename);
  12838. /* The +1's are for the path separator and the NUL */
  12839. size = path_len + 1 + filename_len + 1;
  12840. result = PyMem_New(char, size);
  12841. if (!result) {
  12842. PyErr_NoMemory();
  12843. return NULL;
  12844. }
  12845. strcpy(result, path_narrow);
  12846. if (path_len > 0 && result[path_len - 1] != '/')
  12847. result[path_len++] = '/';
  12848. strcpy(result + path_len, filename);
  12849. return result;
  12850. }
  12851. static PyObject *
  12852. DirEntry_from_posix_info(PyObject *module, path_t *path, const char *name,
  12853. Py_ssize_t name_len, ino_t d_ino
  12854. #ifdef HAVE_DIRENT_D_TYPE
  12855. , unsigned char d_type
  12856. #endif
  12857. )
  12858. {
  12859. DirEntry *entry;
  12860. char *joined_path;
  12861. PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
  12862. entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
  12863. if (!entry)
  12864. return NULL;
  12865. entry->name = NULL;
  12866. entry->path = NULL;
  12867. entry->stat = NULL;
  12868. entry->lstat = NULL;
  12869. if (path->fd != -1) {
  12870. entry->dir_fd = path->fd;
  12871. joined_path = NULL;
  12872. }
  12873. else {
  12874. entry->dir_fd = DEFAULT_DIR_FD;
  12875. joined_path = join_path_filename(path->narrow, name, name_len);
  12876. if (!joined_path)
  12877. goto error;
  12878. }
  12879. if (!path->narrow || !PyBytes_Check(path->object)) {
  12880. entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
  12881. if (joined_path)
  12882. entry->path = PyUnicode_DecodeFSDefault(joined_path);
  12883. }
  12884. else {
  12885. entry->name = PyBytes_FromStringAndSize(name, name_len);
  12886. if (joined_path)
  12887. entry->path = PyBytes_FromString(joined_path);
  12888. }
  12889. PyMem_Free(joined_path);
  12890. if (!entry->name)
  12891. goto error;
  12892. if (path->fd != -1) {
  12893. entry->path = Py_NewRef(entry->name);
  12894. }
  12895. else if (!entry->path)
  12896. goto error;
  12897. #ifdef HAVE_DIRENT_D_TYPE
  12898. entry->d_type = d_type;
  12899. #endif
  12900. entry->d_ino = d_ino;
  12901. return (PyObject *)entry;
  12902. error:
  12903. Py_XDECREF(entry);
  12904. return NULL;
  12905. }
  12906. #endif
  12907. typedef struct {
  12908. PyObject_HEAD
  12909. path_t path;
  12910. #ifdef MS_WINDOWS
  12911. HANDLE handle;
  12912. WIN32_FIND_DATAW file_data;
  12913. int first_time;
  12914. #else /* POSIX */
  12915. DIR *dirp;
  12916. #endif
  12917. #ifdef HAVE_FDOPENDIR
  12918. int fd;
  12919. #endif
  12920. } ScandirIterator;
  12921. #ifdef MS_WINDOWS
  12922. static int
  12923. ScandirIterator_is_closed(ScandirIterator *iterator)
  12924. {
  12925. return iterator->handle == INVALID_HANDLE_VALUE;
  12926. }
  12927. static void
  12928. ScandirIterator_closedir(ScandirIterator *iterator)
  12929. {
  12930. HANDLE handle = iterator->handle;
  12931. if (handle == INVALID_HANDLE_VALUE)
  12932. return;
  12933. iterator->handle = INVALID_HANDLE_VALUE;
  12934. Py_BEGIN_ALLOW_THREADS
  12935. FindClose(handle);
  12936. Py_END_ALLOW_THREADS
  12937. }
  12938. static PyObject *
  12939. ScandirIterator_iternext(ScandirIterator *iterator)
  12940. {
  12941. WIN32_FIND_DATAW *file_data = &iterator->file_data;
  12942. BOOL success;
  12943. PyObject *entry;
  12944. /* Happens if the iterator is iterated twice, or closed explicitly */
  12945. if (iterator->handle == INVALID_HANDLE_VALUE)
  12946. return NULL;
  12947. while (1) {
  12948. if (!iterator->first_time) {
  12949. Py_BEGIN_ALLOW_THREADS
  12950. success = FindNextFileW(iterator->handle, file_data);
  12951. Py_END_ALLOW_THREADS
  12952. if (!success) {
  12953. /* Error or no more files */
  12954. if (GetLastError() != ERROR_NO_MORE_FILES)
  12955. path_error(&iterator->path);
  12956. break;
  12957. }
  12958. }
  12959. iterator->first_time = 0;
  12960. /* Skip over . and .. */
  12961. if (wcscmp(file_data->cFileName, L".") != 0 &&
  12962. wcscmp(file_data->cFileName, L"..") != 0)
  12963. {
  12964. PyObject *module = PyType_GetModule(Py_TYPE(iterator));
  12965. entry = DirEntry_from_find_data(module, &iterator->path, file_data);
  12966. if (!entry)
  12967. break;
  12968. return entry;
  12969. }
  12970. /* Loop till we get a non-dot directory or finish iterating */
  12971. }
  12972. /* Error or no more files */
  12973. ScandirIterator_closedir(iterator);
  12974. return NULL;
  12975. }
  12976. #else /* POSIX */
  12977. static int
  12978. ScandirIterator_is_closed(ScandirIterator *iterator)
  12979. {
  12980. return !iterator->dirp;
  12981. }
  12982. static void
  12983. ScandirIterator_closedir(ScandirIterator *iterator)
  12984. {
  12985. DIR *dirp = iterator->dirp;
  12986. if (!dirp)
  12987. return;
  12988. iterator->dirp = NULL;
  12989. Py_BEGIN_ALLOW_THREADS
  12990. #ifdef HAVE_FDOPENDIR
  12991. if (iterator->path.fd != -1)
  12992. rewinddir(dirp);
  12993. #endif
  12994. closedir(dirp);
  12995. Py_END_ALLOW_THREADS
  12996. return;
  12997. }
  12998. static PyObject *
  12999. ScandirIterator_iternext(ScandirIterator *iterator)
  13000. {
  13001. struct dirent *direntp;
  13002. Py_ssize_t name_len;
  13003. int is_dot;
  13004. PyObject *entry;
  13005. /* Happens if the iterator is iterated twice, or closed explicitly */
  13006. if (!iterator->dirp)
  13007. return NULL;
  13008. while (1) {
  13009. errno = 0;
  13010. Py_BEGIN_ALLOW_THREADS
  13011. direntp = readdir(iterator->dirp);
  13012. Py_END_ALLOW_THREADS
  13013. if (!direntp) {
  13014. /* Error or no more files */
  13015. if (errno != 0)
  13016. path_error(&iterator->path);
  13017. break;
  13018. }
  13019. /* Skip over . and .. */
  13020. name_len = NAMLEN(direntp);
  13021. is_dot = direntp->d_name[0] == '.' &&
  13022. (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
  13023. if (!is_dot) {
  13024. PyObject *module = PyType_GetModule(Py_TYPE(iterator));
  13025. entry = DirEntry_from_posix_info(module,
  13026. &iterator->path, direntp->d_name,
  13027. name_len, direntp->d_ino
  13028. #ifdef HAVE_DIRENT_D_TYPE
  13029. , direntp->d_type
  13030. #endif
  13031. );
  13032. if (!entry)
  13033. break;
  13034. return entry;
  13035. }
  13036. /* Loop till we get a non-dot directory or finish iterating */
  13037. }
  13038. /* Error or no more files */
  13039. ScandirIterator_closedir(iterator);
  13040. return NULL;
  13041. }
  13042. #endif
  13043. static PyObject *
  13044. ScandirIterator_close(ScandirIterator *self, PyObject *args)
  13045. {
  13046. ScandirIterator_closedir(self);
  13047. Py_RETURN_NONE;
  13048. }
  13049. static PyObject *
  13050. ScandirIterator_enter(PyObject *self, PyObject *args)
  13051. {
  13052. return Py_NewRef(self);
  13053. }
  13054. static PyObject *
  13055. ScandirIterator_exit(ScandirIterator *self, PyObject *args)
  13056. {
  13057. ScandirIterator_closedir(self);
  13058. Py_RETURN_NONE;
  13059. }
  13060. static void
  13061. ScandirIterator_finalize(ScandirIterator *iterator)
  13062. {
  13063. /* Save the current exception, if any. */
  13064. PyObject *exc = PyErr_GetRaisedException();
  13065. if (!ScandirIterator_is_closed(iterator)) {
  13066. ScandirIterator_closedir(iterator);
  13067. if (PyErr_ResourceWarning((PyObject *)iterator, 1,
  13068. "unclosed scandir iterator %R", iterator)) {
  13069. /* Spurious errors can appear at shutdown */
  13070. if (PyErr_ExceptionMatches(PyExc_Warning)) {
  13071. PyErr_WriteUnraisable((PyObject *) iterator);
  13072. }
  13073. }
  13074. }
  13075. path_cleanup(&iterator->path);
  13076. /* Restore the saved exception. */
  13077. PyErr_SetRaisedException(exc);
  13078. }
  13079. static void
  13080. ScandirIterator_dealloc(ScandirIterator *iterator)
  13081. {
  13082. PyTypeObject *tp = Py_TYPE(iterator);
  13083. if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
  13084. return;
  13085. freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
  13086. free_func(iterator);
  13087. Py_DECREF(tp);
  13088. }
  13089. static PyMethodDef ScandirIterator_methods[] = {
  13090. {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
  13091. {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
  13092. {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
  13093. {NULL}
  13094. };
  13095. static PyType_Slot ScandirIteratorType_slots[] = {
  13096. {Py_tp_dealloc, ScandirIterator_dealloc},
  13097. {Py_tp_finalize, ScandirIterator_finalize},
  13098. {Py_tp_iter, PyObject_SelfIter},
  13099. {Py_tp_iternext, ScandirIterator_iternext},
  13100. {Py_tp_methods, ScandirIterator_methods},
  13101. {0, 0},
  13102. };
  13103. static PyType_Spec ScandirIteratorType_spec = {
  13104. MODNAME ".ScandirIterator",
  13105. sizeof(ScandirIterator),
  13106. 0,
  13107. // bpo-40549: Py_TPFLAGS_BASETYPE should not be used, since
  13108. // PyType_GetModule(Py_TYPE(self)) doesn't work on a subclass instance.
  13109. (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE
  13110. | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  13111. ScandirIteratorType_slots
  13112. };
  13113. /*[clinic input]
  13114. os.scandir
  13115. path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
  13116. Return an iterator of DirEntry objects for given path.
  13117. path can be specified as either str, bytes, or a path-like object. If path
  13118. is bytes, the names of yielded DirEntry objects will also be bytes; in
  13119. all other circumstances they will be str.
  13120. If path is None, uses the path='.'.
  13121. [clinic start generated code]*/
  13122. static PyObject *
  13123. os_scandir_impl(PyObject *module, path_t *path)
  13124. /*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
  13125. {
  13126. ScandirIterator *iterator;
  13127. #ifdef MS_WINDOWS
  13128. wchar_t *path_strW;
  13129. #else
  13130. const char *path_str;
  13131. #ifdef HAVE_FDOPENDIR
  13132. int fd = -1;
  13133. #endif
  13134. #endif
  13135. if (PySys_Audit("os.scandir", "O",
  13136. path->object ? path->object : Py_None) < 0) {
  13137. return NULL;
  13138. }
  13139. PyObject *ScandirIteratorType = get_posix_state(module)->ScandirIteratorType;
  13140. iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
  13141. if (!iterator)
  13142. return NULL;
  13143. #ifdef MS_WINDOWS
  13144. iterator->handle = INVALID_HANDLE_VALUE;
  13145. #else
  13146. iterator->dirp = NULL;
  13147. #endif
  13148. /* Move the ownership to iterator->path */
  13149. memcpy(&iterator->path, path, sizeof(path_t));
  13150. memset(path, 0, sizeof(path_t));
  13151. #ifdef MS_WINDOWS
  13152. iterator->first_time = 1;
  13153. path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
  13154. if (!path_strW)
  13155. goto error;
  13156. Py_BEGIN_ALLOW_THREADS
  13157. iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
  13158. Py_END_ALLOW_THREADS
  13159. if (iterator->handle == INVALID_HANDLE_VALUE) {
  13160. path_error(&iterator->path);
  13161. PyMem_Free(path_strW);
  13162. goto error;
  13163. }
  13164. PyMem_Free(path_strW);
  13165. #else /* POSIX */
  13166. errno = 0;
  13167. #ifdef HAVE_FDOPENDIR
  13168. if (iterator->path.fd != -1) {
  13169. if (HAVE_FDOPENDIR_RUNTIME) {
  13170. /* closedir() closes the FD, so we duplicate it */
  13171. fd = _Py_dup(iterator->path.fd);
  13172. if (fd == -1)
  13173. goto error;
  13174. Py_BEGIN_ALLOW_THREADS
  13175. iterator->dirp = fdopendir(fd);
  13176. Py_END_ALLOW_THREADS
  13177. } else {
  13178. PyErr_SetString(PyExc_TypeError,
  13179. "scandir: path should be string, bytes, os.PathLike or None, not int");
  13180. return NULL;
  13181. }
  13182. }
  13183. else
  13184. #endif
  13185. {
  13186. if (iterator->path.narrow)
  13187. path_str = iterator->path.narrow;
  13188. else
  13189. path_str = ".";
  13190. Py_BEGIN_ALLOW_THREADS
  13191. iterator->dirp = opendir(path_str);
  13192. Py_END_ALLOW_THREADS
  13193. }
  13194. if (!iterator->dirp) {
  13195. path_error(&iterator->path);
  13196. #ifdef HAVE_FDOPENDIR
  13197. if (fd != -1) {
  13198. Py_BEGIN_ALLOW_THREADS
  13199. close(fd);
  13200. Py_END_ALLOW_THREADS
  13201. }
  13202. #endif
  13203. goto error;
  13204. }
  13205. #endif
  13206. return (PyObject *)iterator;
  13207. error:
  13208. Py_DECREF(iterator);
  13209. return NULL;
  13210. }
  13211. /*
  13212. Return the file system path representation of the object.
  13213. If the object is str or bytes, then allow it to pass through with
  13214. an incremented refcount. If the object defines __fspath__(), then
  13215. return the result of that method. All other types raise a TypeError.
  13216. */
  13217. PyObject *
  13218. PyOS_FSPath(PyObject *path)
  13219. {
  13220. /* For error message reasons, this function is manually inlined in
  13221. path_converter(). */
  13222. PyObject *func = NULL;
  13223. PyObject *path_repr = NULL;
  13224. if (PyUnicode_Check(path) || PyBytes_Check(path)) {
  13225. return Py_NewRef(path);
  13226. }
  13227. func = _PyObject_LookupSpecial(path, &_Py_ID(__fspath__));
  13228. if (NULL == func) {
  13229. return PyErr_Format(PyExc_TypeError,
  13230. "expected str, bytes or os.PathLike object, "
  13231. "not %.200s",
  13232. _PyType_Name(Py_TYPE(path)));
  13233. }
  13234. path_repr = _PyObject_CallNoArgs(func);
  13235. Py_DECREF(func);
  13236. if (NULL == path_repr) {
  13237. return NULL;
  13238. }
  13239. if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
  13240. PyErr_Format(PyExc_TypeError,
  13241. "expected %.200s.__fspath__() to return str or bytes, "
  13242. "not %.200s", _PyType_Name(Py_TYPE(path)),
  13243. _PyType_Name(Py_TYPE(path_repr)));
  13244. Py_DECREF(path_repr);
  13245. return NULL;
  13246. }
  13247. return path_repr;
  13248. }
  13249. /*[clinic input]
  13250. os.fspath
  13251. path: object
  13252. Return the file system path representation of the object.
  13253. If the object is str or bytes, then allow it to pass through as-is. If the
  13254. object defines __fspath__(), then return the result of that method. All other
  13255. types raise a TypeError.
  13256. [clinic start generated code]*/
  13257. static PyObject *
  13258. os_fspath_impl(PyObject *module, PyObject *path)
  13259. /*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
  13260. {
  13261. return PyOS_FSPath(path);
  13262. }
  13263. #ifdef HAVE_GETRANDOM_SYSCALL
  13264. /*[clinic input]
  13265. os.getrandom
  13266. size: Py_ssize_t
  13267. flags: int=0
  13268. Obtain a series of random bytes.
  13269. [clinic start generated code]*/
  13270. static PyObject *
  13271. os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
  13272. /*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
  13273. {
  13274. PyObject *bytes;
  13275. Py_ssize_t n;
  13276. if (size < 0) {
  13277. errno = EINVAL;
  13278. return posix_error();
  13279. }
  13280. bytes = PyBytes_FromStringAndSize(NULL, size);
  13281. if (bytes == NULL) {
  13282. PyErr_NoMemory();
  13283. return NULL;
  13284. }
  13285. while (1) {
  13286. n = syscall(SYS_getrandom,
  13287. PyBytes_AS_STRING(bytes),
  13288. PyBytes_GET_SIZE(bytes),
  13289. flags);
  13290. if (n < 0 && errno == EINTR) {
  13291. if (PyErr_CheckSignals() < 0) {
  13292. goto error;
  13293. }
  13294. /* getrandom() was interrupted by a signal: retry */
  13295. continue;
  13296. }
  13297. break;
  13298. }
  13299. if (n < 0) {
  13300. PyErr_SetFromErrno(PyExc_OSError);
  13301. goto error;
  13302. }
  13303. if (n != size) {
  13304. _PyBytes_Resize(&bytes, n);
  13305. }
  13306. return bytes;
  13307. error:
  13308. Py_DECREF(bytes);
  13309. return NULL;
  13310. }
  13311. #endif /* HAVE_GETRANDOM_SYSCALL */
  13312. #if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
  13313. /* bpo-36085: Helper functions for managing DLL search directories
  13314. * on win32
  13315. */
  13316. /*[clinic input]
  13317. os._add_dll_directory
  13318. path: path_t
  13319. Add a path to the DLL search path.
  13320. This search path is used when resolving dependencies for imported
  13321. extension modules (the module itself is resolved through sys.path),
  13322. and also by ctypes.
  13323. Returns an opaque value that may be passed to os.remove_dll_directory
  13324. to remove this directory from the search path.
  13325. [clinic start generated code]*/
  13326. static PyObject *
  13327. os__add_dll_directory_impl(PyObject *module, path_t *path)
  13328. /*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
  13329. {
  13330. DLL_DIRECTORY_COOKIE cookie = 0;
  13331. DWORD err = 0;
  13332. if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
  13333. return NULL;
  13334. }
  13335. Py_BEGIN_ALLOW_THREADS
  13336. if (!(cookie = AddDllDirectory(path->wide))) {
  13337. err = GetLastError();
  13338. }
  13339. Py_END_ALLOW_THREADS
  13340. if (err) {
  13341. return win32_error_object_err("add_dll_directory",
  13342. path->object, err);
  13343. }
  13344. return PyCapsule_New(cookie, "DLL directory cookie", NULL);
  13345. }
  13346. /*[clinic input]
  13347. os._remove_dll_directory
  13348. cookie: object
  13349. Removes a path from the DLL search path.
  13350. The parameter is an opaque value that was returned from
  13351. os.add_dll_directory. You can only remove directories that you added
  13352. yourself.
  13353. [clinic start generated code]*/
  13354. static PyObject *
  13355. os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
  13356. /*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
  13357. {
  13358. DLL_DIRECTORY_COOKIE cookieValue;
  13359. DWORD err = 0;
  13360. if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
  13361. PyErr_SetString(PyExc_TypeError,
  13362. "Provided cookie was not returned from os.add_dll_directory");
  13363. return NULL;
  13364. }
  13365. cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
  13366. cookie, "DLL directory cookie");
  13367. Py_BEGIN_ALLOW_THREADS
  13368. if (!RemoveDllDirectory(cookieValue)) {
  13369. err = GetLastError();
  13370. }
  13371. Py_END_ALLOW_THREADS
  13372. if (err) {
  13373. return win32_error_object_err("remove_dll_directory",
  13374. NULL, err);
  13375. }
  13376. if (PyCapsule_SetName(cookie, NULL)) {
  13377. return NULL;
  13378. }
  13379. Py_RETURN_NONE;
  13380. }
  13381. #endif /* MS_WINDOWS_APP || MS_WINDOWS_SYSTEM */
  13382. /* Only check if WIFEXITED is available: expect that it comes
  13383. with WEXITSTATUS, WIFSIGNALED, etc.
  13384. os.waitstatus_to_exitcode() is implemented in C and not in Python, so
  13385. subprocess can safely call it during late Python finalization without
  13386. risking that used os attributes were set to None by finalize_modules(). */
  13387. #if defined(WIFEXITED) || defined(MS_WINDOWS)
  13388. /*[clinic input]
  13389. os.waitstatus_to_exitcode
  13390. status as status_obj: object
  13391. Convert a wait status to an exit code.
  13392. On Unix:
  13393. * If WIFEXITED(status) is true, return WEXITSTATUS(status).
  13394. * If WIFSIGNALED(status) is true, return -WTERMSIG(status).
  13395. * Otherwise, raise a ValueError.
  13396. On Windows, return status shifted right by 8 bits.
  13397. On Unix, if the process is being traced or if waitpid() was called with
  13398. WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true.
  13399. This function must not be called if WIFSTOPPED(status) is true.
  13400. [clinic start generated code]*/
  13401. static PyObject *
  13402. os_waitstatus_to_exitcode_impl(PyObject *module, PyObject *status_obj)
  13403. /*[clinic end generated code: output=db50b1b0ba3c7153 input=7fe2d7fdaea3db42]*/
  13404. {
  13405. #ifndef MS_WINDOWS
  13406. int status = _PyLong_AsInt(status_obj);
  13407. if (status == -1 && PyErr_Occurred()) {
  13408. return NULL;
  13409. }
  13410. WAIT_TYPE wait_status;
  13411. WAIT_STATUS_INT(wait_status) = status;
  13412. int exitcode;
  13413. if (WIFEXITED(wait_status)) {
  13414. exitcode = WEXITSTATUS(wait_status);
  13415. /* Sanity check to provide warranty on the function behavior.
  13416. It should not occur in practice */
  13417. if (exitcode < 0) {
  13418. PyErr_Format(PyExc_ValueError, "invalid WEXITSTATUS: %i", exitcode);
  13419. return NULL;
  13420. }
  13421. }
  13422. else if (WIFSIGNALED(wait_status)) {
  13423. int signum = WTERMSIG(wait_status);
  13424. /* Sanity check to provide warranty on the function behavior.
  13425. It should not occurs in practice */
  13426. if (signum <= 0) {
  13427. PyErr_Format(PyExc_ValueError, "invalid WTERMSIG: %i", signum);
  13428. return NULL;
  13429. }
  13430. exitcode = -signum;
  13431. } else if (WIFSTOPPED(wait_status)) {
  13432. /* Status only received if the process is being traced
  13433. or if waitpid() was called with WUNTRACED option. */
  13434. int signum = WSTOPSIG(wait_status);
  13435. PyErr_Format(PyExc_ValueError,
  13436. "process stopped by delivery of signal %i",
  13437. signum);
  13438. return NULL;
  13439. }
  13440. else {
  13441. PyErr_Format(PyExc_ValueError, "invalid wait status: %i", status);
  13442. return NULL;
  13443. }
  13444. return PyLong_FromLong(exitcode);
  13445. #else
  13446. /* Windows implementation: see os.waitpid() implementation
  13447. which uses _cwait(). */
  13448. unsigned long long status = PyLong_AsUnsignedLongLong(status_obj);
  13449. if (status == (unsigned long long)-1 && PyErr_Occurred()) {
  13450. return NULL;
  13451. }
  13452. unsigned long long exitcode = (status >> 8);
  13453. /* ExitProcess() accepts an UINT type:
  13454. reject exit code which doesn't fit in an UINT */
  13455. if (exitcode > UINT_MAX) {
  13456. PyErr_Format(PyExc_ValueError, "invalid exit code: %llu", exitcode);
  13457. return NULL;
  13458. }
  13459. return PyLong_FromUnsignedLong((unsigned long)exitcode);
  13460. #endif
  13461. }
  13462. #endif
  13463. static PyMethodDef posix_methods[] = {
  13464. OS_STAT_METHODDEF
  13465. OS_ACCESS_METHODDEF
  13466. OS_TTYNAME_METHODDEF
  13467. OS_CHDIR_METHODDEF
  13468. OS_CHFLAGS_METHODDEF
  13469. OS_CHMOD_METHODDEF
  13470. OS_FCHMOD_METHODDEF
  13471. OS_LCHMOD_METHODDEF
  13472. OS_CHOWN_METHODDEF
  13473. OS_FCHOWN_METHODDEF
  13474. OS_LCHOWN_METHODDEF
  13475. OS_LCHFLAGS_METHODDEF
  13476. OS_CHROOT_METHODDEF
  13477. OS_CTERMID_METHODDEF
  13478. OS_GETCWD_METHODDEF
  13479. OS_GETCWDB_METHODDEF
  13480. OS_LINK_METHODDEF
  13481. OS_LISTDIR_METHODDEF
  13482. OS_LISTDRIVES_METHODDEF
  13483. OS_LISTMOUNTS_METHODDEF
  13484. OS_LISTVOLUMES_METHODDEF
  13485. OS_LSTAT_METHODDEF
  13486. OS_MKDIR_METHODDEF
  13487. OS_NICE_METHODDEF
  13488. OS_GETPRIORITY_METHODDEF
  13489. OS_SETPRIORITY_METHODDEF
  13490. OS_POSIX_SPAWN_METHODDEF
  13491. OS_POSIX_SPAWNP_METHODDEF
  13492. OS_READLINK_METHODDEF
  13493. OS_COPY_FILE_RANGE_METHODDEF
  13494. OS_SPLICE_METHODDEF
  13495. OS_RENAME_METHODDEF
  13496. OS_REPLACE_METHODDEF
  13497. OS_RMDIR_METHODDEF
  13498. OS_SYMLINK_METHODDEF
  13499. OS_SYSTEM_METHODDEF
  13500. OS_UMASK_METHODDEF
  13501. OS_UNAME_METHODDEF
  13502. OS_UNLINK_METHODDEF
  13503. OS_REMOVE_METHODDEF
  13504. OS_UTIME_METHODDEF
  13505. OS_TIMES_METHODDEF
  13506. OS__EXIT_METHODDEF
  13507. OS__FCOPYFILE_METHODDEF
  13508. OS_EXECV_METHODDEF
  13509. OS_EXECVE_METHODDEF
  13510. OS_SPAWNV_METHODDEF
  13511. OS_SPAWNVE_METHODDEF
  13512. OS_FORK1_METHODDEF
  13513. OS_FORK_METHODDEF
  13514. OS_REGISTER_AT_FORK_METHODDEF
  13515. OS_SCHED_GET_PRIORITY_MAX_METHODDEF
  13516. OS_SCHED_GET_PRIORITY_MIN_METHODDEF
  13517. OS_SCHED_GETPARAM_METHODDEF
  13518. OS_SCHED_GETSCHEDULER_METHODDEF
  13519. OS_SCHED_RR_GET_INTERVAL_METHODDEF
  13520. OS_SCHED_SETPARAM_METHODDEF
  13521. OS_SCHED_SETSCHEDULER_METHODDEF
  13522. OS_SCHED_YIELD_METHODDEF
  13523. OS_SCHED_SETAFFINITY_METHODDEF
  13524. OS_SCHED_GETAFFINITY_METHODDEF
  13525. OS_OPENPTY_METHODDEF
  13526. OS_LOGIN_TTY_METHODDEF
  13527. OS_FORKPTY_METHODDEF
  13528. OS_GETEGID_METHODDEF
  13529. OS_GETEUID_METHODDEF
  13530. OS_GETGID_METHODDEF
  13531. OS_GETGROUPLIST_METHODDEF
  13532. OS_GETGROUPS_METHODDEF
  13533. OS_GETPID_METHODDEF
  13534. OS_GETPGRP_METHODDEF
  13535. OS_GETPPID_METHODDEF
  13536. OS_GETUID_METHODDEF
  13537. OS_GETLOGIN_METHODDEF
  13538. OS_KILL_METHODDEF
  13539. OS_KILLPG_METHODDEF
  13540. OS_PLOCK_METHODDEF
  13541. OS_STARTFILE_METHODDEF
  13542. OS_SETUID_METHODDEF
  13543. OS_SETEUID_METHODDEF
  13544. OS_SETREUID_METHODDEF
  13545. OS_SETGID_METHODDEF
  13546. OS_SETEGID_METHODDEF
  13547. OS_SETREGID_METHODDEF
  13548. OS_SETGROUPS_METHODDEF
  13549. OS_INITGROUPS_METHODDEF
  13550. OS_GETPGID_METHODDEF
  13551. OS_SETPGRP_METHODDEF
  13552. OS_WAIT_METHODDEF
  13553. OS_WAIT3_METHODDEF
  13554. OS_WAIT4_METHODDEF
  13555. OS_WAITID_METHODDEF
  13556. OS_WAITPID_METHODDEF
  13557. OS_PIDFD_OPEN_METHODDEF
  13558. OS_GETSID_METHODDEF
  13559. OS_SETSID_METHODDEF
  13560. OS_SETPGID_METHODDEF
  13561. OS_TCGETPGRP_METHODDEF
  13562. OS_TCSETPGRP_METHODDEF
  13563. OS_OPEN_METHODDEF
  13564. OS_CLOSE_METHODDEF
  13565. OS_CLOSERANGE_METHODDEF
  13566. OS_DEVICE_ENCODING_METHODDEF
  13567. OS_DUP_METHODDEF
  13568. OS_DUP2_METHODDEF
  13569. OS_LOCKF_METHODDEF
  13570. OS_LSEEK_METHODDEF
  13571. OS_READ_METHODDEF
  13572. OS_READV_METHODDEF
  13573. OS_PREAD_METHODDEF
  13574. OS_PREADV_METHODDEF
  13575. OS_WRITE_METHODDEF
  13576. OS_WRITEV_METHODDEF
  13577. OS_PWRITE_METHODDEF
  13578. OS_PWRITEV_METHODDEF
  13579. OS_SENDFILE_METHODDEF
  13580. OS_FSTAT_METHODDEF
  13581. OS_ISATTY_METHODDEF
  13582. OS_PIPE_METHODDEF
  13583. OS_PIPE2_METHODDEF
  13584. OS_MKFIFO_METHODDEF
  13585. OS_MKNOD_METHODDEF
  13586. OS_MAJOR_METHODDEF
  13587. OS_MINOR_METHODDEF
  13588. OS_MAKEDEV_METHODDEF
  13589. OS_FTRUNCATE_METHODDEF
  13590. OS_TRUNCATE_METHODDEF
  13591. OS_POSIX_FALLOCATE_METHODDEF
  13592. OS_POSIX_FADVISE_METHODDEF
  13593. OS_PUTENV_METHODDEF
  13594. OS_UNSETENV_METHODDEF
  13595. OS_STRERROR_METHODDEF
  13596. OS_FCHDIR_METHODDEF
  13597. OS_FSYNC_METHODDEF
  13598. OS_SYNC_METHODDEF
  13599. OS_FDATASYNC_METHODDEF
  13600. OS_WCOREDUMP_METHODDEF
  13601. OS_WIFCONTINUED_METHODDEF
  13602. OS_WIFSTOPPED_METHODDEF
  13603. OS_WIFSIGNALED_METHODDEF
  13604. OS_WIFEXITED_METHODDEF
  13605. OS_WEXITSTATUS_METHODDEF
  13606. OS_WTERMSIG_METHODDEF
  13607. OS_WSTOPSIG_METHODDEF
  13608. OS_FSTATVFS_METHODDEF
  13609. OS_STATVFS_METHODDEF
  13610. OS_CONFSTR_METHODDEF
  13611. OS_SYSCONF_METHODDEF
  13612. OS_FPATHCONF_METHODDEF
  13613. OS_PATHCONF_METHODDEF
  13614. OS_ABORT_METHODDEF
  13615. OS__GETFULLPATHNAME_METHODDEF
  13616. OS__GETDISKUSAGE_METHODDEF
  13617. OS__GETFINALPATHNAME_METHODDEF
  13618. OS__GETVOLUMEPATHNAME_METHODDEF
  13619. OS__PATH_SPLITROOT_METHODDEF
  13620. OS__PATH_NORMPATH_METHODDEF
  13621. OS_GETLOADAVG_METHODDEF
  13622. OS_URANDOM_METHODDEF
  13623. OS_SETRESUID_METHODDEF
  13624. OS_SETRESGID_METHODDEF
  13625. OS_GETRESUID_METHODDEF
  13626. OS_GETRESGID_METHODDEF
  13627. OS_GETXATTR_METHODDEF
  13628. OS_SETXATTR_METHODDEF
  13629. OS_REMOVEXATTR_METHODDEF
  13630. OS_LISTXATTR_METHODDEF
  13631. OS_GET_TERMINAL_SIZE_METHODDEF
  13632. OS_CPU_COUNT_METHODDEF
  13633. OS_GET_INHERITABLE_METHODDEF
  13634. OS_SET_INHERITABLE_METHODDEF
  13635. OS_GET_HANDLE_INHERITABLE_METHODDEF
  13636. OS_SET_HANDLE_INHERITABLE_METHODDEF
  13637. OS_GET_BLOCKING_METHODDEF
  13638. OS_SET_BLOCKING_METHODDEF
  13639. OS_SCANDIR_METHODDEF
  13640. OS_FSPATH_METHODDEF
  13641. OS_GETRANDOM_METHODDEF
  13642. OS_MEMFD_CREATE_METHODDEF
  13643. OS_EVENTFD_METHODDEF
  13644. OS_EVENTFD_READ_METHODDEF
  13645. OS_EVENTFD_WRITE_METHODDEF
  13646. OS__ADD_DLL_DIRECTORY_METHODDEF
  13647. OS__REMOVE_DLL_DIRECTORY_METHODDEF
  13648. OS_WAITSTATUS_TO_EXITCODE_METHODDEF
  13649. OS_SETNS_METHODDEF
  13650. OS_UNSHARE_METHODDEF
  13651. OS__PATH_ISDEVDRIVE_METHODDEF
  13652. OS__PATH_ISDIR_METHODDEF
  13653. OS__PATH_ISFILE_METHODDEF
  13654. OS__PATH_ISLINK_METHODDEF
  13655. OS__PATH_EXISTS_METHODDEF
  13656. {NULL, NULL} /* Sentinel */
  13657. };
  13658. static int
  13659. all_ins(PyObject *m)
  13660. {
  13661. #ifdef F_OK
  13662. if (PyModule_AddIntMacro(m, F_OK)) return -1;
  13663. #endif
  13664. #ifdef R_OK
  13665. if (PyModule_AddIntMacro(m, R_OK)) return -1;
  13666. #endif
  13667. #ifdef W_OK
  13668. if (PyModule_AddIntMacro(m, W_OK)) return -1;
  13669. #endif
  13670. #ifdef X_OK
  13671. if (PyModule_AddIntMacro(m, X_OK)) return -1;
  13672. #endif
  13673. #ifdef NGROUPS_MAX
  13674. if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
  13675. #endif
  13676. #ifdef TMP_MAX
  13677. if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
  13678. #endif
  13679. #ifdef WCONTINUED
  13680. if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
  13681. #endif
  13682. #ifdef WNOHANG
  13683. if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
  13684. #endif
  13685. #ifdef WUNTRACED
  13686. if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
  13687. #endif
  13688. #ifdef O_RDONLY
  13689. if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
  13690. #endif
  13691. #ifdef O_WRONLY
  13692. if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
  13693. #endif
  13694. #ifdef O_RDWR
  13695. if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
  13696. #endif
  13697. #ifdef O_NDELAY
  13698. if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
  13699. #endif
  13700. #ifdef O_NONBLOCK
  13701. if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
  13702. #endif
  13703. #ifdef O_APPEND
  13704. if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
  13705. #endif
  13706. #ifdef O_DSYNC
  13707. if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
  13708. #endif
  13709. #ifdef O_RSYNC
  13710. if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
  13711. #endif
  13712. #ifdef O_SYNC
  13713. if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
  13714. #endif
  13715. #ifdef O_NOCTTY
  13716. if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
  13717. #endif
  13718. #ifdef O_CREAT
  13719. if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
  13720. #endif
  13721. #ifdef O_EXCL
  13722. if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
  13723. #endif
  13724. #ifdef O_TRUNC
  13725. if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
  13726. #endif
  13727. #ifdef O_BINARY
  13728. if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
  13729. #endif
  13730. #ifdef O_TEXT
  13731. if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
  13732. #endif
  13733. #ifdef O_XATTR
  13734. if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
  13735. #endif
  13736. #ifdef O_LARGEFILE
  13737. if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
  13738. #endif
  13739. #ifndef __GNU__
  13740. #ifdef O_SHLOCK
  13741. if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
  13742. #endif
  13743. #ifdef O_EXLOCK
  13744. if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
  13745. #endif
  13746. #endif
  13747. #ifdef O_EXEC
  13748. if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
  13749. #endif
  13750. #ifdef O_SEARCH
  13751. if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
  13752. #endif
  13753. #ifdef O_PATH
  13754. if (PyModule_AddIntMacro(m, O_PATH)) return -1;
  13755. #endif
  13756. #ifdef O_TTY_INIT
  13757. if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
  13758. #endif
  13759. #ifdef O_TMPFILE
  13760. if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
  13761. #endif
  13762. #ifdef PRIO_PROCESS
  13763. if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
  13764. #endif
  13765. #ifdef PRIO_PGRP
  13766. if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
  13767. #endif
  13768. #ifdef PRIO_USER
  13769. if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
  13770. #endif
  13771. #ifdef PRIO_DARWIN_THREAD
  13772. if (PyModule_AddIntMacro(m, PRIO_DARWIN_THREAD)) return -1;
  13773. #endif
  13774. #ifdef PRIO_DARWIN_PROCESS
  13775. if (PyModule_AddIntMacro(m, PRIO_DARWIN_PROCESS)) return -1;
  13776. #endif
  13777. #ifdef PRIO_DARWIN_BG
  13778. if (PyModule_AddIntMacro(m, PRIO_DARWIN_BG)) return -1;
  13779. #endif
  13780. #ifdef PRIO_DARWIN_NONUI
  13781. if (PyModule_AddIntMacro(m, PRIO_DARWIN_NONUI)) return -1;
  13782. #endif
  13783. #ifdef O_CLOEXEC
  13784. if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
  13785. #endif
  13786. #ifdef O_ACCMODE
  13787. if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
  13788. #endif
  13789. #ifdef O_EVTONLY
  13790. if (PyModule_AddIntMacro(m, O_EVTONLY)) return -1;
  13791. #endif
  13792. #ifdef O_FSYNC
  13793. if (PyModule_AddIntMacro(m, O_FSYNC)) return -1;
  13794. #endif
  13795. #ifdef O_SYMLINK
  13796. if (PyModule_AddIntMacro(m, O_SYMLINK)) return -1;
  13797. #endif
  13798. #ifdef SEEK_HOLE
  13799. if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
  13800. #endif
  13801. #ifdef SEEK_DATA
  13802. if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
  13803. #endif
  13804. /* MS Windows */
  13805. #ifdef O_NOINHERIT
  13806. /* Don't inherit in child processes. */
  13807. if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
  13808. #endif
  13809. #ifdef _O_SHORT_LIVED
  13810. /* Optimize for short life (keep in memory). */
  13811. /* MS forgot to define this one with a non-underscore form too. */
  13812. if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
  13813. #endif
  13814. #ifdef O_TEMPORARY
  13815. /* Automatically delete when last handle is closed. */
  13816. if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
  13817. #endif
  13818. #ifdef O_RANDOM
  13819. /* Optimize for random access. */
  13820. if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
  13821. #endif
  13822. #ifdef O_SEQUENTIAL
  13823. /* Optimize for sequential access. */
  13824. if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
  13825. #endif
  13826. /* GNU extensions. */
  13827. #ifdef O_ASYNC
  13828. /* Send a SIGIO signal whenever input or output
  13829. becomes available on file descriptor */
  13830. if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
  13831. #endif
  13832. #ifdef O_DIRECT
  13833. /* Direct disk access. */
  13834. if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
  13835. #endif
  13836. #ifdef O_DIRECTORY
  13837. /* Must be a directory. */
  13838. if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
  13839. #endif
  13840. #ifdef O_NOFOLLOW
  13841. /* Do not follow links. */
  13842. if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
  13843. #endif
  13844. #ifdef O_NOFOLLOW_ANY
  13845. if (PyModule_AddIntMacro(m, O_NOFOLLOW_ANY)) return -1;
  13846. #endif
  13847. #ifdef O_NOLINKS
  13848. /* Fails if link count of the named file is greater than 1 */
  13849. if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
  13850. #endif
  13851. #ifdef O_NOATIME
  13852. /* Do not update the access time. */
  13853. if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
  13854. #endif
  13855. /* These come from sysexits.h */
  13856. #ifdef EX_OK
  13857. if (PyModule_AddIntMacro(m, EX_OK)) return -1;
  13858. #endif /* EX_OK */
  13859. #ifdef EX_USAGE
  13860. if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
  13861. #endif /* EX_USAGE */
  13862. #ifdef EX_DATAERR
  13863. if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
  13864. #endif /* EX_DATAERR */
  13865. #ifdef EX_NOINPUT
  13866. if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
  13867. #endif /* EX_NOINPUT */
  13868. #ifdef EX_NOUSER
  13869. if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
  13870. #endif /* EX_NOUSER */
  13871. #ifdef EX_NOHOST
  13872. if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
  13873. #endif /* EX_NOHOST */
  13874. #ifdef EX_UNAVAILABLE
  13875. if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
  13876. #endif /* EX_UNAVAILABLE */
  13877. #ifdef EX_SOFTWARE
  13878. if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
  13879. #endif /* EX_SOFTWARE */
  13880. #ifdef EX_OSERR
  13881. if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
  13882. #endif /* EX_OSERR */
  13883. #ifdef EX_OSFILE
  13884. if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
  13885. #endif /* EX_OSFILE */
  13886. #ifdef EX_CANTCREAT
  13887. if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
  13888. #endif /* EX_CANTCREAT */
  13889. #ifdef EX_IOERR
  13890. if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
  13891. #endif /* EX_IOERR */
  13892. #ifdef EX_TEMPFAIL
  13893. if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
  13894. #endif /* EX_TEMPFAIL */
  13895. #ifdef EX_PROTOCOL
  13896. if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
  13897. #endif /* EX_PROTOCOL */
  13898. #ifdef EX_NOPERM
  13899. if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
  13900. #endif /* EX_NOPERM */
  13901. #ifdef EX_CONFIG
  13902. if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
  13903. #endif /* EX_CONFIG */
  13904. #ifdef EX_NOTFOUND
  13905. if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
  13906. #endif /* EX_NOTFOUND */
  13907. /* statvfs */
  13908. #ifdef ST_RDONLY
  13909. if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
  13910. #endif /* ST_RDONLY */
  13911. #ifdef ST_NOSUID
  13912. if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
  13913. #endif /* ST_NOSUID */
  13914. /* GNU extensions */
  13915. #ifdef ST_NODEV
  13916. if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
  13917. #endif /* ST_NODEV */
  13918. #ifdef ST_NOEXEC
  13919. if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
  13920. #endif /* ST_NOEXEC */
  13921. #ifdef ST_SYNCHRONOUS
  13922. if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
  13923. #endif /* ST_SYNCHRONOUS */
  13924. #ifdef ST_MANDLOCK
  13925. if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
  13926. #endif /* ST_MANDLOCK */
  13927. #ifdef ST_WRITE
  13928. if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
  13929. #endif /* ST_WRITE */
  13930. #ifdef ST_APPEND
  13931. if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
  13932. #endif /* ST_APPEND */
  13933. #ifdef ST_NOATIME
  13934. if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
  13935. #endif /* ST_NOATIME */
  13936. #ifdef ST_NODIRATIME
  13937. if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
  13938. #endif /* ST_NODIRATIME */
  13939. #ifdef ST_RELATIME
  13940. if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
  13941. #endif /* ST_RELATIME */
  13942. /* FreeBSD sendfile() constants */
  13943. #ifdef SF_NODISKIO
  13944. if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
  13945. #endif
  13946. /* is obsolete since the 11.x release */
  13947. #ifdef SF_MNOWAIT
  13948. if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
  13949. #endif
  13950. #ifdef SF_SYNC
  13951. if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
  13952. #endif
  13953. #ifdef SF_NOCACHE
  13954. if (PyModule_AddIntMacro(m, SF_NOCACHE)) return -1;
  13955. #endif
  13956. /* constants for posix_fadvise */
  13957. #ifdef POSIX_FADV_NORMAL
  13958. if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
  13959. #endif
  13960. #ifdef POSIX_FADV_SEQUENTIAL
  13961. if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
  13962. #endif
  13963. #ifdef POSIX_FADV_RANDOM
  13964. if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
  13965. #endif
  13966. #ifdef POSIX_FADV_NOREUSE
  13967. if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
  13968. #endif
  13969. #ifdef POSIX_FADV_WILLNEED
  13970. if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
  13971. #endif
  13972. #ifdef POSIX_FADV_DONTNEED
  13973. if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
  13974. #endif
  13975. /* constants for waitid */
  13976. #if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
  13977. if (PyModule_AddIntMacro(m, P_PID)) return -1;
  13978. if (PyModule_AddIntMacro(m, P_PGID)) return -1;
  13979. if (PyModule_AddIntMacro(m, P_ALL)) return -1;
  13980. #ifdef P_PIDFD
  13981. if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
  13982. #endif
  13983. #ifdef PIDFD_NONBLOCK
  13984. if (PyModule_AddIntMacro(m, PIDFD_NONBLOCK)) return -1;
  13985. #endif
  13986. #endif
  13987. #ifdef WEXITED
  13988. if (PyModule_AddIntMacro(m, WEXITED)) return -1;
  13989. #endif
  13990. #ifdef WNOWAIT
  13991. if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
  13992. #endif
  13993. #ifdef WSTOPPED
  13994. if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
  13995. #endif
  13996. #ifdef CLD_EXITED
  13997. if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
  13998. #endif
  13999. #ifdef CLD_KILLED
  14000. if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
  14001. #endif
  14002. #ifdef CLD_DUMPED
  14003. if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
  14004. #endif
  14005. #ifdef CLD_TRAPPED
  14006. if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
  14007. #endif
  14008. #ifdef CLD_STOPPED
  14009. if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
  14010. #endif
  14011. #ifdef CLD_CONTINUED
  14012. if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
  14013. #endif
  14014. /* constants for lockf */
  14015. #ifdef F_LOCK
  14016. if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
  14017. #endif
  14018. #ifdef F_TLOCK
  14019. if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
  14020. #endif
  14021. #ifdef F_ULOCK
  14022. if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
  14023. #endif
  14024. #ifdef F_TEST
  14025. if (PyModule_AddIntMacro(m, F_TEST)) return -1;
  14026. #endif
  14027. #ifdef RWF_DSYNC
  14028. if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
  14029. #endif
  14030. #ifdef RWF_HIPRI
  14031. if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
  14032. #endif
  14033. #ifdef RWF_SYNC
  14034. if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
  14035. #endif
  14036. #ifdef RWF_NOWAIT
  14037. if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
  14038. #endif
  14039. #ifdef RWF_APPEND
  14040. if (PyModule_AddIntConstant(m, "RWF_APPEND", RWF_APPEND)) return -1;
  14041. #endif
  14042. /* constants for splice */
  14043. #if defined(HAVE_SPLICE) && defined(__linux__)
  14044. if (PyModule_AddIntConstant(m, "SPLICE_F_MOVE", SPLICE_F_MOVE)) return -1;
  14045. if (PyModule_AddIntConstant(m, "SPLICE_F_NONBLOCK", SPLICE_F_NONBLOCK)) return -1;
  14046. if (PyModule_AddIntConstant(m, "SPLICE_F_MORE", SPLICE_F_MORE)) return -1;
  14047. #endif
  14048. /* constants for posix_spawn */
  14049. #ifdef HAVE_POSIX_SPAWN
  14050. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
  14051. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
  14052. if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
  14053. #endif
  14054. #if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
  14055. if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
  14056. if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
  14057. if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
  14058. #endif
  14059. #ifdef HAVE_SPAWNV
  14060. if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
  14061. if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
  14062. #endif
  14063. #ifdef HAVE_SCHED_H
  14064. #ifdef SCHED_OTHER
  14065. if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
  14066. #endif
  14067. #ifdef SCHED_FIFO
  14068. if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
  14069. #endif
  14070. #ifdef SCHED_RR
  14071. if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
  14072. #endif
  14073. #ifdef SCHED_SPORADIC
  14074. if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
  14075. #endif
  14076. #ifdef SCHED_BATCH
  14077. if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
  14078. #endif
  14079. #ifdef SCHED_IDLE
  14080. if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
  14081. #endif
  14082. #ifdef SCHED_RESET_ON_FORK
  14083. if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
  14084. #endif
  14085. #ifdef SCHED_SYS
  14086. if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
  14087. #endif
  14088. #ifdef SCHED_IA
  14089. if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
  14090. #endif
  14091. #ifdef SCHED_FSS
  14092. if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
  14093. #endif
  14094. #ifdef SCHED_FX
  14095. if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
  14096. #endif
  14097. /* constants for namespaces */
  14098. #if defined(HAVE_SETNS) || defined(HAVE_UNSHARE)
  14099. #ifdef CLONE_FS
  14100. if (PyModule_AddIntMacro(m, CLONE_FS)) return -1;
  14101. #endif
  14102. #ifdef CLONE_FILES
  14103. if (PyModule_AddIntMacro(m, CLONE_FILES)) return -1;
  14104. #endif
  14105. #ifdef CLONE_NEWNS
  14106. if (PyModule_AddIntMacro(m, CLONE_NEWNS)) return -1;
  14107. #endif
  14108. #ifdef CLONE_NEWCGROUP
  14109. if (PyModule_AddIntMacro(m, CLONE_NEWCGROUP)) return -1;
  14110. #endif
  14111. #ifdef CLONE_NEWUTS
  14112. if (PyModule_AddIntMacro(m, CLONE_NEWUTS)) return -1;
  14113. #endif
  14114. #ifdef CLONE_NEWIPC
  14115. if (PyModule_AddIntMacro(m, CLONE_NEWIPC)) return -1;
  14116. #endif
  14117. #ifdef CLONE_NEWUSER
  14118. if (PyModule_AddIntMacro(m, CLONE_NEWUSER)) return -1;
  14119. #endif
  14120. #ifdef CLONE_NEWPID
  14121. if (PyModule_AddIntMacro(m, CLONE_NEWPID)) return -1;
  14122. #endif
  14123. #ifdef CLONE_NEWNET
  14124. if (PyModule_AddIntMacro(m, CLONE_NEWNET)) return -1;
  14125. #endif
  14126. #ifdef CLONE_NEWTIME
  14127. if (PyModule_AddIntMacro(m, CLONE_NEWTIME)) return -1;
  14128. #endif
  14129. #ifdef CLONE_SYSVSEM
  14130. if (PyModule_AddIntMacro(m, CLONE_SYSVSEM)) return -1;
  14131. #endif
  14132. #ifdef CLONE_THREAD
  14133. if (PyModule_AddIntMacro(m, CLONE_THREAD)) return -1;
  14134. #endif
  14135. #ifdef CLONE_SIGHAND
  14136. if (PyModule_AddIntMacro(m, CLONE_SIGHAND)) return -1;
  14137. #endif
  14138. #ifdef CLONE_VM
  14139. if (PyModule_AddIntMacro(m, CLONE_VM)) return -1;
  14140. #endif
  14141. #endif
  14142. #endif
  14143. #ifdef USE_XATTRS
  14144. if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
  14145. if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
  14146. if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
  14147. #endif
  14148. #if HAVE_DECL_RTLD_LAZY
  14149. if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
  14150. #endif
  14151. #if HAVE_DECL_RTLD_NOW
  14152. if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
  14153. #endif
  14154. #if HAVE_DECL_RTLD_GLOBAL
  14155. if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
  14156. #endif
  14157. #if HAVE_DECL_RTLD_LOCAL
  14158. if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
  14159. #endif
  14160. #if HAVE_DECL_RTLD_NODELETE
  14161. if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
  14162. #endif
  14163. #if HAVE_DECL_RTLD_NOLOAD
  14164. if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
  14165. #endif
  14166. #if HAVE_DECL_RTLD_DEEPBIND
  14167. if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
  14168. #endif
  14169. #if HAVE_DECL_RTLD_MEMBER
  14170. if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
  14171. #endif
  14172. #ifdef HAVE_GETRANDOM_SYSCALL
  14173. if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
  14174. if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
  14175. #endif
  14176. #ifdef HAVE_MEMFD_CREATE
  14177. if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
  14178. if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
  14179. #ifdef MFD_HUGETLB
  14180. if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
  14181. #endif
  14182. #ifdef MFD_HUGE_SHIFT
  14183. if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
  14184. #endif
  14185. #ifdef MFD_HUGE_MASK
  14186. if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
  14187. #endif
  14188. #ifdef MFD_HUGE_64KB
  14189. if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
  14190. #endif
  14191. #ifdef MFD_HUGE_512KB
  14192. if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
  14193. #endif
  14194. #ifdef MFD_HUGE_1MB
  14195. if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
  14196. #endif
  14197. #ifdef MFD_HUGE_2MB
  14198. if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
  14199. #endif
  14200. #ifdef MFD_HUGE_8MB
  14201. if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
  14202. #endif
  14203. #ifdef MFD_HUGE_16MB
  14204. if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
  14205. #endif
  14206. #ifdef MFD_HUGE_32MB
  14207. if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
  14208. #endif
  14209. #ifdef MFD_HUGE_256MB
  14210. if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
  14211. #endif
  14212. #ifdef MFD_HUGE_512MB
  14213. if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
  14214. #endif
  14215. #ifdef MFD_HUGE_1GB
  14216. if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
  14217. #endif
  14218. #ifdef MFD_HUGE_2GB
  14219. if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
  14220. #endif
  14221. #ifdef MFD_HUGE_16GB
  14222. if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
  14223. #endif
  14224. #endif /* HAVE_MEMFD_CREATE */
  14225. #if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
  14226. if (PyModule_AddIntMacro(m, EFD_CLOEXEC)) return -1;
  14227. #ifdef EFD_NONBLOCK
  14228. if (PyModule_AddIntMacro(m, EFD_NONBLOCK)) return -1;
  14229. #endif
  14230. #ifdef EFD_SEMAPHORE
  14231. if (PyModule_AddIntMacro(m, EFD_SEMAPHORE)) return -1;
  14232. #endif
  14233. #endif /* HAVE_EVENTFD && EFD_CLOEXEC */
  14234. #if defined(__APPLE__)
  14235. if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
  14236. if (PyModule_AddIntConstant(m, "_COPYFILE_STAT", COPYFILE_STAT)) return -1;
  14237. if (PyModule_AddIntConstant(m, "_COPYFILE_ACL", COPYFILE_ACL)) return -1;
  14238. if (PyModule_AddIntConstant(m, "_COPYFILE_XATTR", COPYFILE_XATTR)) return -1;
  14239. #endif
  14240. #ifdef MS_WINDOWS
  14241. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
  14242. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
  14243. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
  14244. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
  14245. if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
  14246. #endif
  14247. return 0;
  14248. }
  14249. #define PROBE(name, test) \
  14250. static int name(void) \
  14251. { \
  14252. if (test) { \
  14253. return 1; \
  14254. } else { \
  14255. return 0; \
  14256. } \
  14257. }
  14258. #ifdef HAVE_FSTATAT
  14259. PROBE(probe_fstatat, HAVE_FSTATAT_RUNTIME)
  14260. #endif
  14261. #ifdef HAVE_FACCESSAT
  14262. PROBE(probe_faccessat, HAVE_FACCESSAT_RUNTIME)
  14263. #endif
  14264. #ifdef HAVE_FCHMODAT
  14265. PROBE(probe_fchmodat, HAVE_FCHMODAT_RUNTIME)
  14266. #endif
  14267. #ifdef HAVE_FCHOWNAT
  14268. PROBE(probe_fchownat, HAVE_FCHOWNAT_RUNTIME)
  14269. #endif
  14270. #ifdef HAVE_LINKAT
  14271. PROBE(probe_linkat, HAVE_LINKAT_RUNTIME)
  14272. #endif
  14273. #ifdef HAVE_FDOPENDIR
  14274. PROBE(probe_fdopendir, HAVE_FDOPENDIR_RUNTIME)
  14275. #endif
  14276. #ifdef HAVE_MKDIRAT
  14277. PROBE(probe_mkdirat, HAVE_MKDIRAT_RUNTIME)
  14278. #endif
  14279. #ifdef HAVE_MKFIFOAT
  14280. PROBE(probe_mkfifoat, HAVE_MKFIFOAT_RUNTIME)
  14281. #endif
  14282. #ifdef HAVE_MKNODAT
  14283. PROBE(probe_mknodat, HAVE_MKNODAT_RUNTIME)
  14284. #endif
  14285. #ifdef HAVE_RENAMEAT
  14286. PROBE(probe_renameat, HAVE_RENAMEAT_RUNTIME)
  14287. #endif
  14288. #ifdef HAVE_UNLINKAT
  14289. PROBE(probe_unlinkat, HAVE_UNLINKAT_RUNTIME)
  14290. #endif
  14291. #ifdef HAVE_OPENAT
  14292. PROBE(probe_openat, HAVE_OPENAT_RUNTIME)
  14293. #endif
  14294. #ifdef HAVE_READLINKAT
  14295. PROBE(probe_readlinkat, HAVE_READLINKAT_RUNTIME)
  14296. #endif
  14297. #ifdef HAVE_SYMLINKAT
  14298. PROBE(probe_symlinkat, HAVE_SYMLINKAT_RUNTIME)
  14299. #endif
  14300. #ifdef HAVE_FUTIMENS
  14301. PROBE(probe_futimens, HAVE_FUTIMENS_RUNTIME)
  14302. #endif
  14303. #ifdef HAVE_UTIMENSAT
  14304. PROBE(probe_utimensat, HAVE_UTIMENSAT_RUNTIME)
  14305. #endif
  14306. static const struct have_function {
  14307. const char * const label;
  14308. int (*probe)(void);
  14309. } have_functions[] = {
  14310. #ifdef HAVE_EVENTFD
  14311. {"HAVE_EVENTFD", NULL},
  14312. #endif
  14313. #ifdef HAVE_FACCESSAT
  14314. { "HAVE_FACCESSAT", probe_faccessat },
  14315. #endif
  14316. #ifdef HAVE_FCHDIR
  14317. { "HAVE_FCHDIR", NULL },
  14318. #endif
  14319. #ifdef HAVE_FCHMOD
  14320. { "HAVE_FCHMOD", NULL },
  14321. #endif
  14322. #ifdef HAVE_FCHMODAT
  14323. { "HAVE_FCHMODAT", probe_fchmodat },
  14324. #endif
  14325. #ifdef HAVE_FCHOWN
  14326. { "HAVE_FCHOWN", NULL },
  14327. #endif
  14328. #ifdef HAVE_FCHOWNAT
  14329. { "HAVE_FCHOWNAT", probe_fchownat },
  14330. #endif
  14331. #ifdef HAVE_FEXECVE
  14332. { "HAVE_FEXECVE", NULL },
  14333. #endif
  14334. #ifdef HAVE_FDOPENDIR
  14335. { "HAVE_FDOPENDIR", probe_fdopendir },
  14336. #endif
  14337. #ifdef HAVE_FPATHCONF
  14338. { "HAVE_FPATHCONF", NULL },
  14339. #endif
  14340. #ifdef HAVE_FSTATAT
  14341. { "HAVE_FSTATAT", probe_fstatat },
  14342. #endif
  14343. #ifdef HAVE_FSTATVFS
  14344. { "HAVE_FSTATVFS", NULL },
  14345. #endif
  14346. #if defined HAVE_FTRUNCATE || defined MS_WINDOWS
  14347. { "HAVE_FTRUNCATE", NULL },
  14348. #endif
  14349. #ifdef HAVE_FUTIMENS
  14350. { "HAVE_FUTIMENS", probe_futimens },
  14351. #endif
  14352. #ifdef HAVE_FUTIMES
  14353. { "HAVE_FUTIMES", NULL },
  14354. #endif
  14355. #ifdef HAVE_FUTIMESAT
  14356. { "HAVE_FUTIMESAT", NULL },
  14357. #endif
  14358. #ifdef HAVE_LINKAT
  14359. { "HAVE_LINKAT", probe_linkat },
  14360. #endif
  14361. #ifdef HAVE_LCHFLAGS
  14362. { "HAVE_LCHFLAGS", NULL },
  14363. #endif
  14364. #ifdef HAVE_LCHMOD
  14365. { "HAVE_LCHMOD", NULL },
  14366. #endif
  14367. #ifdef HAVE_LCHOWN
  14368. { "HAVE_LCHOWN", NULL },
  14369. #endif
  14370. #ifdef HAVE_LSTAT
  14371. { "HAVE_LSTAT", NULL },
  14372. #endif
  14373. #ifdef HAVE_LUTIMES
  14374. { "HAVE_LUTIMES", NULL },
  14375. #endif
  14376. #ifdef HAVE_MEMFD_CREATE
  14377. { "HAVE_MEMFD_CREATE", NULL },
  14378. #endif
  14379. #ifdef HAVE_MKDIRAT
  14380. { "HAVE_MKDIRAT", probe_mkdirat },
  14381. #endif
  14382. #ifdef HAVE_MKFIFOAT
  14383. { "HAVE_MKFIFOAT", probe_mkfifoat },
  14384. #endif
  14385. #ifdef HAVE_MKNODAT
  14386. { "HAVE_MKNODAT", probe_mknodat },
  14387. #endif
  14388. #ifdef HAVE_OPENAT
  14389. { "HAVE_OPENAT", probe_openat },
  14390. #endif
  14391. #ifdef HAVE_READLINKAT
  14392. { "HAVE_READLINKAT", probe_readlinkat },
  14393. #endif
  14394. #ifdef HAVE_RENAMEAT
  14395. { "HAVE_RENAMEAT", probe_renameat },
  14396. #endif
  14397. #ifdef HAVE_SYMLINKAT
  14398. { "HAVE_SYMLINKAT", probe_symlinkat },
  14399. #endif
  14400. #ifdef HAVE_UNLINKAT
  14401. { "HAVE_UNLINKAT", probe_unlinkat },
  14402. #endif
  14403. #ifdef HAVE_UTIMENSAT
  14404. { "HAVE_UTIMENSAT", probe_utimensat },
  14405. #endif
  14406. #ifdef MS_WINDOWS
  14407. { "MS_WINDOWS", NULL },
  14408. #endif
  14409. { NULL, NULL }
  14410. };
  14411. static int
  14412. posixmodule_exec(PyObject *m)
  14413. {
  14414. _posixstate *state = get_posix_state(m);
  14415. #if defined(HAVE_PWRITEV)
  14416. if (HAVE_PWRITEV_RUNTIME) {} else {
  14417. PyObject* dct = PyModule_GetDict(m);
  14418. if (dct == NULL) {
  14419. return -1;
  14420. }
  14421. if (PyDict_DelItemString(dct, "pwritev") == -1) {
  14422. PyErr_Clear();
  14423. }
  14424. if (PyDict_DelItemString(dct, "preadv") == -1) {
  14425. PyErr_Clear();
  14426. }
  14427. }
  14428. #endif
  14429. /* Initialize environ dictionary */
  14430. if (_PyModule_Add(m, "environ", convertenviron()) != 0) {
  14431. return -1;
  14432. }
  14433. if (all_ins(m))
  14434. return -1;
  14435. if (setup_confname_tables(m))
  14436. return -1;
  14437. if (PyModule_AddObjectRef(m, "error", PyExc_OSError) < 0) {
  14438. return -1;
  14439. }
  14440. #if defined(HAVE_WAITID) && !defined(__APPLE__)
  14441. waitid_result_desc.name = MODNAME ".waitid_result";
  14442. state->WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
  14443. if (PyModule_AddObjectRef(m, "waitid_result", state->WaitidResultType) < 0) {
  14444. return -1;
  14445. }
  14446. #endif
  14447. stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
  14448. stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
  14449. stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
  14450. stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
  14451. state->StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
  14452. if (PyModule_AddObjectRef(m, "stat_result", state->StatResultType) < 0) {
  14453. return -1;
  14454. }
  14455. state->statresult_new_orig = ((PyTypeObject *)state->StatResultType)->tp_new;
  14456. ((PyTypeObject *)state->StatResultType)->tp_new = statresult_new;
  14457. statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
  14458. state->StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
  14459. if (PyModule_AddObjectRef(m, "statvfs_result", state->StatVFSResultType) < 0) {
  14460. return -1;
  14461. }
  14462. #if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
  14463. sched_param_desc.name = MODNAME ".sched_param";
  14464. state->SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
  14465. if (PyModule_AddObjectRef(m, "sched_param", state->SchedParamType) < 0) {
  14466. return -1;
  14467. }
  14468. ((PyTypeObject *)state->SchedParamType)->tp_new = os_sched_param;
  14469. #endif
  14470. /* initialize TerminalSize_info */
  14471. state->TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
  14472. if (PyModule_AddObjectRef(m, "terminal_size", state->TerminalSizeType) < 0) {
  14473. return -1;
  14474. }
  14475. /* initialize scandir types */
  14476. PyObject *ScandirIteratorType = PyType_FromModuleAndSpec(m, &ScandirIteratorType_spec, NULL);
  14477. if (ScandirIteratorType == NULL) {
  14478. return -1;
  14479. }
  14480. state->ScandirIteratorType = ScandirIteratorType;
  14481. state->DirEntryType = PyType_FromModuleAndSpec(m, &DirEntryType_spec, NULL);
  14482. if (PyModule_AddObjectRef(m, "DirEntry", state->DirEntryType) < 0) {
  14483. return -1;
  14484. }
  14485. times_result_desc.name = MODNAME ".times_result";
  14486. state->TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
  14487. if (PyModule_AddObjectRef(m, "times_result", state->TimesResultType) < 0) {
  14488. return -1;
  14489. }
  14490. state->UnameResultType = (PyObject *)PyStructSequence_NewType(&uname_result_desc);
  14491. if (PyModule_AddObjectRef(m, "uname_result", state->UnameResultType) < 0) {
  14492. return -1;
  14493. }
  14494. if ((state->billion = PyLong_FromLong(1000000000)) == NULL)
  14495. return -1;
  14496. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  14497. state->struct_rusage = PyUnicode_InternFromString("struct_rusage");
  14498. if (state->struct_rusage == NULL)
  14499. return -1;
  14500. #endif
  14501. state->st_mode = PyUnicode_InternFromString("st_mode");
  14502. if (state->st_mode == NULL)
  14503. return -1;
  14504. /* suppress "function not used" warnings */
  14505. {
  14506. int ignored;
  14507. fd_specified("", -1);
  14508. follow_symlinks_specified("", 1);
  14509. dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
  14510. dir_fd_converter(Py_None, &ignored);
  14511. dir_fd_unavailable(Py_None, &ignored);
  14512. }
  14513. /*
  14514. * provide list of locally available functions
  14515. * so os.py can populate support_* lists
  14516. */
  14517. PyObject *list = PyList_New(0);
  14518. if (!list) {
  14519. return -1;
  14520. }
  14521. for (const struct have_function *trace = have_functions; trace->label; trace++) {
  14522. PyObject *unicode;
  14523. if (trace->probe && !trace->probe()) continue;
  14524. unicode = PyUnicode_DecodeASCII(trace->label, strlen(trace->label), NULL);
  14525. if (!unicode)
  14526. return -1;
  14527. if (PyList_Append(list, unicode))
  14528. return -1;
  14529. Py_DECREF(unicode);
  14530. }
  14531. return _PyModule_Add(m, "_have_functions", list);
  14532. }
  14533. static PyModuleDef_Slot posixmodile_slots[] = {
  14534. {Py_mod_exec, posixmodule_exec},
  14535. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  14536. {0, NULL}
  14537. };
  14538. static struct PyModuleDef posixmodule = {
  14539. PyModuleDef_HEAD_INIT,
  14540. .m_name = MODNAME,
  14541. .m_doc = posix__doc__,
  14542. .m_size = sizeof(_posixstate),
  14543. .m_methods = posix_methods,
  14544. .m_slots = posixmodile_slots,
  14545. .m_traverse = _posix_traverse,
  14546. .m_clear = _posix_clear,
  14547. .m_free = _posix_free,
  14548. };
  14549. PyMODINIT_FUNC
  14550. INITFUNC(void)
  14551. {
  14552. return PyModuleDef_Init(&posixmodule);
  14553. }
  14554. #ifdef __cplusplus
  14555. }
  14556. #endif