posixmodule.c 259 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365
  1. /* POSIX module implementation */
  2. /* This file is also used for Windows NT/MS-Win and OS/2. In that case the
  3. module actually calls itself 'nt' or 'os2', 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. '__BORLANDC__' or '_MSC_VER'. For OS/2, the compiler
  8. independent macro PYOS_OS2 should be defined. On OS/2 the default
  9. compiler is assumed to be IBM's VisualAge C++ (VACPP). PYCC_GCC is used
  10. as the compiler specific macro for the EMX port of gcc to OS/2. */
  11. /* See also ../Dos/dosmodule.c */
  12. #ifdef __APPLE__
  13. /*
  14. * Step 1 of support for weak-linking a number of symbols existing on
  15. * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
  16. * at the end of this file for more information.
  17. */
  18. # pragma weak lchown
  19. # pragma weak statvfs
  20. # pragma weak fstatvfs
  21. #endif /* __APPLE__ */
  22. #define PY_SSIZE_T_CLEAN
  23. #include "Python.h"
  24. #include "structseq.h"
  25. #if defined(__VMS)
  26. # include <unixio.h>
  27. #endif /* defined(__VMS) */
  28. #ifdef __cplusplus
  29. extern "C" {
  30. #endif
  31. PyDoc_STRVAR(posix__doc__,
  32. "This module provides access to operating system functionality that is\n\
  33. standardized by the C Standard and the POSIX standard (a thinly\n\
  34. disguised Unix interface). Refer to the library manual and\n\
  35. corresponding Unix manual entries for more information on calls.");
  36. #ifndef Py_USING_UNICODE
  37. /* This is used in signatures of functions. */
  38. #define Py_UNICODE void
  39. #endif
  40. #if defined(PYOS_OS2)
  41. #define INCL_DOS
  42. #define INCL_DOSERRORS
  43. #define INCL_DOSPROCESS
  44. #define INCL_NOPMAPI
  45. #include <os2.h>
  46. #if defined(PYCC_GCC)
  47. #include <ctype.h>
  48. #include <io.h>
  49. #include <stdio.h>
  50. #include <process.h>
  51. #endif
  52. #include "osdefs.h"
  53. #endif
  54. #ifdef HAVE_SYS_TYPES_H
  55. #include <sys/types.h>
  56. #endif /* HAVE_SYS_TYPES_H */
  57. #ifdef HAVE_SYS_STAT_H
  58. #include <sys/stat.h>
  59. #endif /* HAVE_SYS_STAT_H */
  60. #ifdef HAVE_SYS_WAIT_H
  61. #include <sys/wait.h> /* For WNOHANG */
  62. #endif
  63. #ifdef HAVE_SIGNAL_H
  64. #include <signal.h>
  65. #endif
  66. #ifdef HAVE_FCNTL_H
  67. #include <fcntl.h>
  68. #endif /* HAVE_FCNTL_H */
  69. #ifdef HAVE_GRP_H
  70. #include <grp.h>
  71. #endif
  72. #ifdef HAVE_SYSEXITS_H
  73. #include <sysexits.h>
  74. #endif /* HAVE_SYSEXITS_H */
  75. #ifdef HAVE_SYS_LOADAVG_H
  76. #include <sys/loadavg.h>
  77. #endif
  78. /* Various compilers have only certain posix functions */
  79. /* XXX Gosh I wish these were all moved into pyconfig.h */
  80. #if defined(PYCC_VACPP) && defined(PYOS_OS2)
  81. #include <process.h>
  82. #else
  83. #if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
  84. #define HAVE_GETCWD 1
  85. #define HAVE_OPENDIR 1
  86. #define HAVE_SYSTEM 1
  87. #if defined(__OS2__)
  88. #define HAVE_EXECV 1
  89. #define HAVE_WAIT 1
  90. #endif
  91. #include <process.h>
  92. #else
  93. #ifdef __BORLANDC__ /* Borland compiler */
  94. #define HAVE_EXECV 1
  95. #define HAVE_GETCWD 1
  96. #define HAVE_OPENDIR 1
  97. #define HAVE_PIPE 1
  98. #define HAVE_POPEN 1
  99. #define HAVE_SYSTEM 1
  100. #define HAVE_WAIT 1
  101. #else
  102. #ifdef _MSC_VER /* Microsoft compiler */
  103. #define HAVE_GETCWD 1
  104. #define HAVE_SPAWNV 1
  105. #define HAVE_EXECV 1
  106. #define HAVE_PIPE 1
  107. #define HAVE_POPEN 1
  108. #define HAVE_SYSTEM 1
  109. #define HAVE_CWAIT 1
  110. #define HAVE_FSYNC 1
  111. #define fsync _commit
  112. #else
  113. #if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS)
  114. /* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */
  115. #else /* all other compilers */
  116. /* Unix functions that the configure script doesn't check for */
  117. #define HAVE_EXECV 1
  118. #define HAVE_FORK 1
  119. #if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
  120. #define HAVE_FORK1 1
  121. #endif
  122. #define HAVE_GETCWD 1
  123. #define HAVE_GETEGID 1
  124. #define HAVE_GETEUID 1
  125. #define HAVE_GETGID 1
  126. #define HAVE_GETPPID 1
  127. #define HAVE_GETUID 1
  128. #define HAVE_KILL 1
  129. #define HAVE_OPENDIR 1
  130. #define HAVE_PIPE 1
  131. #ifndef __rtems__
  132. #define HAVE_POPEN 1
  133. #endif
  134. #define HAVE_SYSTEM 1
  135. #define HAVE_WAIT 1
  136. #define HAVE_TTYNAME 1
  137. #endif /* PYOS_OS2 && PYCC_GCC && __VMS */
  138. #endif /* _MSC_VER */
  139. #endif /* __BORLANDC__ */
  140. #endif /* ! __WATCOMC__ || __QNX__ */
  141. #endif /* ! __IBMC__ */
  142. #ifndef _MSC_VER
  143. #if defined(__sgi)&&_COMPILER_VERSION>=700
  144. /* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
  145. (default) */
  146. extern char *ctermid_r(char *);
  147. #endif
  148. #ifndef HAVE_UNISTD_H
  149. #if defined(PYCC_VACPP)
  150. extern int mkdir(char *);
  151. #else
  152. #if ( defined(__WATCOMC__) || defined(_MSC_VER) ) && !defined(__QNX__)
  153. extern int mkdir(const char *);
  154. #else
  155. extern int mkdir(const char *, mode_t);
  156. #endif
  157. #endif
  158. #if defined(__IBMC__) || defined(__IBMCPP__)
  159. extern int chdir(char *);
  160. extern int rmdir(char *);
  161. #else
  162. extern int chdir(const char *);
  163. extern int rmdir(const char *);
  164. #endif
  165. #ifdef __BORLANDC__
  166. extern int chmod(const char *, int);
  167. #else
  168. extern int chmod(const char *, mode_t);
  169. #endif
  170. /*#ifdef HAVE_FCHMOD
  171. extern int fchmod(int, mode_t);
  172. #endif*/
  173. /*#ifdef HAVE_LCHMOD
  174. extern int lchmod(const char *, mode_t);
  175. #endif*/
  176. extern int chown(const char *, uid_t, gid_t);
  177. extern char *getcwd(char *, int);
  178. extern char *strerror(int);
  179. extern int link(const char *, const char *);
  180. extern int rename(const char *, const char *);
  181. extern int stat(const char *, struct stat *);
  182. extern int unlink(const char *);
  183. extern int pclose(FILE *);
  184. #ifdef HAVE_SYMLINK
  185. extern int symlink(const char *, const char *);
  186. #endif /* HAVE_SYMLINK */
  187. #ifdef HAVE_LSTAT
  188. extern int lstat(const char *, struct stat *);
  189. #endif /* HAVE_LSTAT */
  190. #endif /* !HAVE_UNISTD_H */
  191. #endif /* !_MSC_VER */
  192. #ifdef HAVE_UTIME_H
  193. #include <utime.h>
  194. #endif /* HAVE_UTIME_H */
  195. #ifdef HAVE_SYS_UTIME_H
  196. #include <sys/utime.h>
  197. #define HAVE_UTIME_H /* pretend we do for the rest of this file */
  198. #endif /* HAVE_SYS_UTIME_H */
  199. #ifdef HAVE_SYS_TIMES_H
  200. #include <sys/times.h>
  201. #endif /* HAVE_SYS_TIMES_H */
  202. #ifdef HAVE_SYS_PARAM_H
  203. #include <sys/param.h>
  204. #endif /* HAVE_SYS_PARAM_H */
  205. #ifdef HAVE_SYS_UTSNAME_H
  206. #include <sys/utsname.h>
  207. #endif /* HAVE_SYS_UTSNAME_H */
  208. #ifdef HAVE_DIRENT_H
  209. #include <dirent.h>
  210. #define NAMLEN(dirent) strlen((dirent)->d_name)
  211. #else
  212. #if defined(__WATCOMC__) && !defined(__QNX__)
  213. #include <direct.h>
  214. #define NAMLEN(dirent) strlen((dirent)->d_name)
  215. #else
  216. #define dirent direct
  217. #define NAMLEN(dirent) (dirent)->d_namlen
  218. #endif
  219. #ifdef HAVE_SYS_NDIR_H
  220. #include <sys/ndir.h>
  221. #endif
  222. #ifdef HAVE_SYS_DIR_H
  223. #include <sys/dir.h>
  224. #endif
  225. #ifdef HAVE_NDIR_H
  226. #include <ndir.h>
  227. #endif
  228. #endif
  229. #ifdef _MSC_VER
  230. #ifdef HAVE_DIRECT_H
  231. #include <direct.h>
  232. #endif
  233. #ifdef HAVE_IO_H
  234. #include <io.h>
  235. #endif
  236. #ifdef HAVE_PROCESS_H
  237. #include <process.h>
  238. #endif
  239. #include "osdefs.h"
  240. #include <malloc.h>
  241. #include <windows.h>
  242. #include <shellapi.h> /* for ShellExecute() */
  243. #define popen _popen
  244. #define pclose _pclose
  245. #endif /* _MSC_VER */
  246. #if defined(PYCC_VACPP) && defined(PYOS_OS2)
  247. #include <io.h>
  248. #endif /* OS2 */
  249. #ifndef MAXPATHLEN
  250. #if defined(PATH_MAX) && PATH_MAX > 1024
  251. #define MAXPATHLEN PATH_MAX
  252. #else
  253. #define MAXPATHLEN 1024
  254. #endif
  255. #endif /* MAXPATHLEN */
  256. #ifdef UNION_WAIT
  257. /* Emulate some macros on systems that have a union instead of macros */
  258. #ifndef WIFEXITED
  259. #define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
  260. #endif
  261. #ifndef WEXITSTATUS
  262. #define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
  263. #endif
  264. #ifndef WTERMSIG
  265. #define WTERMSIG(u_wait) ((u_wait).w_termsig)
  266. #endif
  267. #define WAIT_TYPE union wait
  268. #define WAIT_STATUS_INT(s) (s.w_status)
  269. #else /* !UNION_WAIT */
  270. #define WAIT_TYPE int
  271. #define WAIT_STATUS_INT(s) (s)
  272. #endif /* UNION_WAIT */
  273. /* Issue #1983: pid_t can be longer than a C long on some systems */
  274. #if !defined(SIZEOF_PID_T) || SIZEOF_PID_T == SIZEOF_INT
  275. #define PARSE_PID "i"
  276. #define PyLong_FromPid PyInt_FromLong
  277. #define PyLong_AsPid PyInt_AsLong
  278. #elif SIZEOF_PID_T == SIZEOF_LONG
  279. #define PARSE_PID "l"
  280. #define PyLong_FromPid PyInt_FromLong
  281. #define PyLong_AsPid PyInt_AsLong
  282. #elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG
  283. #define PARSE_PID "L"
  284. #define PyLong_FromPid PyLong_FromLongLong
  285. #define PyLong_AsPid PyInt_AsLongLong
  286. #else
  287. #error "sizeof(pid_t) is neither sizeof(int), sizeof(long) or sizeof(long long)"
  288. #endif /* SIZEOF_PID_T */
  289. /* Don't use the "_r" form if we don't need it (also, won't have a
  290. prototype for it, at least on Solaris -- maybe others as well?). */
  291. #if defined(HAVE_CTERMID_R) && defined(WITH_THREAD)
  292. #define USE_CTERMID_R
  293. #endif
  294. #if defined(HAVE_TMPNAM_R) && defined(WITH_THREAD)
  295. #define USE_TMPNAM_R
  296. #endif
  297. /* choose the appropriate stat and fstat functions and return structs */
  298. #undef STAT
  299. #if defined(MS_WIN64) || defined(MS_WINDOWS)
  300. # define STAT win32_stat
  301. # define FSTAT win32_fstat
  302. # define STRUCT_STAT struct win32_stat
  303. #else
  304. # define STAT stat
  305. # define FSTAT fstat
  306. # define STRUCT_STAT struct stat
  307. #endif
  308. #if defined(MAJOR_IN_MKDEV)
  309. #include <sys/mkdev.h>
  310. #else
  311. #if defined(MAJOR_IN_SYSMACROS)
  312. #include <sys/sysmacros.h>
  313. #endif
  314. #if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
  315. #include <sys/mkdev.h>
  316. #endif
  317. #endif
  318. #if defined _MSC_VER && _MSC_VER >= 1400
  319. /* Microsoft CRT in VS2005 and higher will verify that a filehandle is
  320. * valid and throw an assertion if it isn't.
  321. * Normally, an invalid fd is likely to be a C program error and therefore
  322. * an assertion can be useful, but it does contradict the POSIX standard
  323. * which for write(2) states:
  324. * "Otherwise, -1 shall be returned and errno set to indicate the error."
  325. * "[EBADF] The fildes argument is not a valid file descriptor open for
  326. * writing."
  327. * Furthermore, python allows the user to enter any old integer
  328. * as a fd and should merely raise a python exception on error.
  329. * The Microsoft CRT doesn't provide an official way to check for the
  330. * validity of a file descriptor, but we can emulate its internal behaviour
  331. * by using the exported __pinfo data member and knowledge of the
  332. * internal structures involved.
  333. * The structures below must be updated for each version of visual studio
  334. * according to the file internal.h in the CRT source, until MS comes
  335. * up with a less hacky way to do this.
  336. * (all of this is to avoid globally modifying the CRT behaviour using
  337. * _set_invalid_parameter_handler() and _CrtSetReportMode())
  338. */
  339. /* The actual size of the structure is determined at runtime.
  340. * Only the first items must be present.
  341. */
  342. typedef struct {
  343. intptr_t osfhnd;
  344. char osfile;
  345. } my_ioinfo;
  346. extern __declspec(dllimport) char * __pioinfo[];
  347. #define IOINFO_L2E 5
  348. #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
  349. #define IOINFO_ARRAYS 64
  350. #define _NHANDLE_ (IOINFO_ARRAYS * IOINFO_ARRAY_ELTS)
  351. #define FOPEN 0x01
  352. #define _NO_CONSOLE_FILENO (intptr_t)-2
  353. /* This function emulates what the windows CRT does to validate file handles */
  354. int
  355. _PyVerify_fd(int fd)
  356. {
  357. const int i1 = fd >> IOINFO_L2E;
  358. const int i2 = fd & ((1 << IOINFO_L2E) - 1);
  359. static int sizeof_ioinfo = 0;
  360. /* Determine the actual size of the ioinfo structure,
  361. * as used by the CRT loaded in memory
  362. */
  363. if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) {
  364. sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS;
  365. }
  366. if (sizeof_ioinfo == 0) {
  367. /* This should not happen... */
  368. goto fail;
  369. }
  370. /* See that it isn't a special CLEAR fileno */
  371. if (fd != _NO_CONSOLE_FILENO) {
  372. /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that. Instead
  373. * we check pointer validity and other info
  374. */
  375. if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) {
  376. /* finally, check that the file is open */
  377. my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo);
  378. if (info->osfile & FOPEN) {
  379. return 1;
  380. }
  381. }
  382. }
  383. fail:
  384. errno = EBADF;
  385. return 0;
  386. }
  387. /* the special case of checking dup2. The target fd must be in a sensible range */
  388. static int
  389. _PyVerify_fd_dup2(int fd1, int fd2)
  390. {
  391. if (!_PyVerify_fd(fd1))
  392. return 0;
  393. if (fd2 == _NO_CONSOLE_FILENO)
  394. return 0;
  395. if ((unsigned)fd2 < _NHANDLE_)
  396. return 1;
  397. else
  398. return 0;
  399. }
  400. #else
  401. /* dummy version. _PyVerify_fd() is already defined in fileobject.h */
  402. #define _PyVerify_fd_dup2(A, B) (1)
  403. #endif
  404. /* Return a dictionary corresponding to the POSIX environment table */
  405. #ifdef WITH_NEXT_FRAMEWORK
  406. /* On Darwin/MacOSX a shared library or framework has no access to
  407. ** environ directly, we must obtain it with _NSGetEnviron().
  408. */
  409. #include <crt_externs.h>
  410. static char **environ;
  411. #elif !defined(_MSC_VER) && ( !defined(__WATCOMC__) || defined(__QNX__) )
  412. extern char **environ;
  413. #endif /* !_MSC_VER */
  414. static PyObject *
  415. convertenviron(void)
  416. {
  417. PyObject *d;
  418. char **e;
  419. #if defined(PYOS_OS2)
  420. APIRET rc;
  421. char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */
  422. #endif
  423. d = PyDict_New();
  424. if (d == NULL)
  425. return NULL;
  426. #ifdef WITH_NEXT_FRAMEWORK
  427. if (environ == NULL)
  428. environ = *_NSGetEnviron();
  429. #endif
  430. if (environ == NULL)
  431. return d;
  432. /* This part ignores errors */
  433. for (e = environ; *e != NULL; e++) {
  434. PyObject *k;
  435. PyObject *v;
  436. char *p = strchr(*e, '=');
  437. if (p == NULL)
  438. continue;
  439. k = PyString_FromStringAndSize(*e, (int)(p-*e));
  440. if (k == NULL) {
  441. PyErr_Clear();
  442. continue;
  443. }
  444. v = PyString_FromString(p+1);
  445. if (v == NULL) {
  446. PyErr_Clear();
  447. Py_DECREF(k);
  448. continue;
  449. }
  450. if (PyDict_GetItem(d, k) == NULL) {
  451. if (PyDict_SetItem(d, k, v) != 0)
  452. PyErr_Clear();
  453. }
  454. Py_DECREF(k);
  455. Py_DECREF(v);
  456. }
  457. #if defined(PYOS_OS2)
  458. rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH);
  459. if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */
  460. PyObject *v = PyString_FromString(buffer);
  461. PyDict_SetItemString(d, "BEGINLIBPATH", v);
  462. Py_DECREF(v);
  463. }
  464. rc = DosQueryExtLIBPATH(buffer, END_LIBPATH);
  465. if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */
  466. PyObject *v = PyString_FromString(buffer);
  467. PyDict_SetItemString(d, "ENDLIBPATH", v);
  468. Py_DECREF(v);
  469. }
  470. #endif
  471. return d;
  472. }
  473. /* Set a POSIX-specific error from errno, and return NULL */
  474. static PyObject *
  475. posix_error(void)
  476. {
  477. return PyErr_SetFromErrno(PyExc_OSError);
  478. }
  479. static PyObject *
  480. posix_error_with_filename(char* name)
  481. {
  482. return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
  483. }
  484. #ifdef MS_WINDOWS
  485. static PyObject *
  486. posix_error_with_unicode_filename(Py_UNICODE* name)
  487. {
  488. return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name);
  489. }
  490. #endif /* MS_WINDOWS */
  491. static PyObject *
  492. posix_error_with_allocated_filename(char* name)
  493. {
  494. PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
  495. PyMem_Free(name);
  496. return rc;
  497. }
  498. #ifdef MS_WINDOWS
  499. static PyObject *
  500. win32_error(char* function, char* filename)
  501. {
  502. /* XXX We should pass the function name along in the future.
  503. (_winreg.c also wants to pass the function name.)
  504. This would however require an additional param to the
  505. Windows error object, which is non-trivial.
  506. */
  507. errno = GetLastError();
  508. if (filename)
  509. return PyErr_SetFromWindowsErrWithFilename(errno, filename);
  510. else
  511. return PyErr_SetFromWindowsErr(errno);
  512. }
  513. static PyObject *
  514. win32_error_unicode(char* function, Py_UNICODE* filename)
  515. {
  516. /* XXX - see win32_error for comments on 'function' */
  517. errno = GetLastError();
  518. if (filename)
  519. return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename);
  520. else
  521. return PyErr_SetFromWindowsErr(errno);
  522. }
  523. static int
  524. convert_to_unicode(PyObject **param)
  525. {
  526. if (PyUnicode_CheckExact(*param))
  527. Py_INCREF(*param);
  528. else if (PyUnicode_Check(*param))
  529. /* For a Unicode subtype that's not a Unicode object,
  530. return a true Unicode object with the same data. */
  531. *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param),
  532. PyUnicode_GET_SIZE(*param));
  533. else
  534. *param = PyUnicode_FromEncodedObject(*param,
  535. Py_FileSystemDefaultEncoding,
  536. "strict");
  537. return (*param) != NULL;
  538. }
  539. #endif /* MS_WINDOWS */
  540. #if defined(PYOS_OS2)
  541. /**********************************************************************
  542. * Helper Function to Trim and Format OS/2 Messages
  543. **********************************************************************/
  544. static void
  545. os2_formatmsg(char *msgbuf, int msglen, char *reason)
  546. {
  547. msgbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
  548. if (strlen(msgbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */
  549. char *lastc = &msgbuf[ strlen(msgbuf)-1 ];
  550. while (lastc > msgbuf && isspace(Py_CHARMASK(*lastc)))
  551. *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
  552. }
  553. /* Add Optional Reason Text */
  554. if (reason) {
  555. strcat(msgbuf, " : ");
  556. strcat(msgbuf, reason);
  557. }
  558. }
  559. /**********************************************************************
  560. * Decode an OS/2 Operating System Error Code
  561. *
  562. * A convenience function to lookup an OS/2 error code and return a
  563. * text message we can use to raise a Python exception.
  564. *
  565. * Notes:
  566. * The messages for errors returned from the OS/2 kernel reside in
  567. * the file OSO001.MSG in the \OS2 directory hierarchy.
  568. *
  569. **********************************************************************/
  570. static char *
  571. os2_strerror(char *msgbuf, int msgbuflen, int errorcode, char *reason)
  572. {
  573. APIRET rc;
  574. ULONG msglen;
  575. /* Retrieve Kernel-Related Error Message from OSO001.MSG File */
  576. Py_BEGIN_ALLOW_THREADS
  577. rc = DosGetMessage(NULL, 0, msgbuf, msgbuflen,
  578. errorcode, "oso001.msg", &msglen);
  579. Py_END_ALLOW_THREADS
  580. if (rc == NO_ERROR)
  581. os2_formatmsg(msgbuf, msglen, reason);
  582. else
  583. PyOS_snprintf(msgbuf, msgbuflen,
  584. "unknown OS error #%d", errorcode);
  585. return msgbuf;
  586. }
  587. /* Set an OS/2-specific error and return NULL. OS/2 kernel
  588. errors are not in a global variable e.g. 'errno' nor are
  589. they congruent with posix error numbers. */
  590. static PyObject *
  591. os2_error(int code)
  592. {
  593. char text[1024];
  594. PyObject *v;
  595. os2_strerror(text, sizeof(text), code, "");
  596. v = Py_BuildValue("(is)", code, text);
  597. if (v != NULL) {
  598. PyErr_SetObject(PyExc_OSError, v);
  599. Py_DECREF(v);
  600. }
  601. return NULL; /* Signal to Python that an Exception is Pending */
  602. }
  603. #endif /* OS2 */
  604. /* POSIX generic methods */
  605. static PyObject *
  606. posix_fildes(PyObject *fdobj, int (*func)(int))
  607. {
  608. int fd;
  609. int res;
  610. fd = PyObject_AsFileDescriptor(fdobj);
  611. if (fd < 0)
  612. return NULL;
  613. if (!_PyVerify_fd(fd))
  614. return posix_error();
  615. Py_BEGIN_ALLOW_THREADS
  616. res = (*func)(fd);
  617. Py_END_ALLOW_THREADS
  618. if (res < 0)
  619. return posix_error();
  620. Py_INCREF(Py_None);
  621. return Py_None;
  622. }
  623. static PyObject *
  624. posix_1str(PyObject *args, char *format, int (*func)(const char*))
  625. {
  626. char *path1 = NULL;
  627. int res;
  628. if (!PyArg_ParseTuple(args, format,
  629. Py_FileSystemDefaultEncoding, &path1))
  630. return NULL;
  631. Py_BEGIN_ALLOW_THREADS
  632. res = (*func)(path1);
  633. Py_END_ALLOW_THREADS
  634. if (res < 0)
  635. return posix_error_with_allocated_filename(path1);
  636. PyMem_Free(path1);
  637. Py_INCREF(Py_None);
  638. return Py_None;
  639. }
  640. static PyObject *
  641. posix_2str(PyObject *args,
  642. char *format,
  643. int (*func)(const char *, const char *))
  644. {
  645. char *path1 = NULL, *path2 = NULL;
  646. int res;
  647. if (!PyArg_ParseTuple(args, format,
  648. Py_FileSystemDefaultEncoding, &path1,
  649. Py_FileSystemDefaultEncoding, &path2))
  650. return NULL;
  651. Py_BEGIN_ALLOW_THREADS
  652. res = (*func)(path1, path2);
  653. Py_END_ALLOW_THREADS
  654. PyMem_Free(path1);
  655. PyMem_Free(path2);
  656. if (res != 0)
  657. /* XXX how to report both path1 and path2??? */
  658. return posix_error();
  659. Py_INCREF(Py_None);
  660. return Py_None;
  661. }
  662. #ifdef MS_WINDOWS
  663. static PyObject*
  664. win32_1str(PyObject* args, char* func,
  665. char* format, BOOL (__stdcall *funcA)(LPCSTR),
  666. char* wformat, BOOL (__stdcall *funcW)(LPWSTR))
  667. {
  668. PyObject *uni;
  669. char *ansi;
  670. BOOL result;
  671. if (!PyArg_ParseTuple(args, wformat, &uni))
  672. PyErr_Clear();
  673. else {
  674. Py_BEGIN_ALLOW_THREADS
  675. result = funcW(PyUnicode_AsUnicode(uni));
  676. Py_END_ALLOW_THREADS
  677. if (!result)
  678. return win32_error_unicode(func, PyUnicode_AsUnicode(uni));
  679. Py_INCREF(Py_None);
  680. return Py_None;
  681. }
  682. if (!PyArg_ParseTuple(args, format, &ansi))
  683. return NULL;
  684. Py_BEGIN_ALLOW_THREADS
  685. result = funcA(ansi);
  686. Py_END_ALLOW_THREADS
  687. if (!result)
  688. return win32_error(func, ansi);
  689. Py_INCREF(Py_None);
  690. return Py_None;
  691. }
  692. /* This is a reimplementation of the C library's chdir function,
  693. but one that produces Win32 errors instead of DOS error codes.
  694. chdir is essentially a wrapper around SetCurrentDirectory; however,
  695. it also needs to set "magic" environment variables indicating
  696. the per-drive current directory, which are of the form =<drive>: */
  697. static BOOL __stdcall
  698. win32_chdir(LPCSTR path)
  699. {
  700. char new_path[MAX_PATH+1];
  701. int result;
  702. char env[4] = "=x:";
  703. if(!SetCurrentDirectoryA(path))
  704. return FALSE;
  705. result = GetCurrentDirectoryA(MAX_PATH+1, new_path);
  706. if (!result)
  707. return FALSE;
  708. /* In the ANSI API, there should not be any paths longer
  709. than MAX_PATH. */
  710. assert(result <= MAX_PATH+1);
  711. if (strncmp(new_path, "\\\\", 2) == 0 ||
  712. strncmp(new_path, "//", 2) == 0)
  713. /* UNC path, nothing to do. */
  714. return TRUE;
  715. env[1] = new_path[0];
  716. return SetEnvironmentVariableA(env, new_path);
  717. }
  718. /* The Unicode version differs from the ANSI version
  719. since the current directory might exceed MAX_PATH characters */
  720. static BOOL __stdcall
  721. win32_wchdir(LPCWSTR path)
  722. {
  723. wchar_t _new_path[MAX_PATH+1], *new_path = _new_path;
  724. int result;
  725. wchar_t env[4] = L"=x:";
  726. if(!SetCurrentDirectoryW(path))
  727. return FALSE;
  728. result = GetCurrentDirectoryW(MAX_PATH+1, new_path);
  729. if (!result)
  730. return FALSE;
  731. if (result > MAX_PATH+1) {
  732. new_path = malloc(result * sizeof(wchar_t));
  733. if (!new_path) {
  734. SetLastError(ERROR_OUTOFMEMORY);
  735. return FALSE;
  736. }
  737. result = GetCurrentDirectoryW(result, new_path);
  738. if (!result) {
  739. free(new_path);
  740. return FALSE;
  741. }
  742. }
  743. if (wcsncmp(new_path, L"\\\\", 2) == 0 ||
  744. wcsncmp(new_path, L"//", 2) == 0)
  745. /* UNC path, nothing to do. */
  746. return TRUE;
  747. env[1] = new_path[0];
  748. result = SetEnvironmentVariableW(env, new_path);
  749. if (new_path != _new_path)
  750. free(new_path);
  751. return result;
  752. }
  753. #endif
  754. #ifdef MS_WINDOWS
  755. /* The CRT of Windows has a number of flaws wrt. its stat() implementation:
  756. - time stamps are restricted to second resolution
  757. - file modification times suffer from forth-and-back conversions between
  758. UTC and local time
  759. Therefore, we implement our own stat, based on the Win32 API directly.
  760. */
  761. #define HAVE_STAT_NSEC 1
  762. struct win32_stat{
  763. int st_dev;
  764. __int64 st_ino;
  765. unsigned short st_mode;
  766. int st_nlink;
  767. int st_uid;
  768. int st_gid;
  769. int st_rdev;
  770. __int64 st_size;
  771. int st_atime;
  772. int st_atime_nsec;
  773. int st_mtime;
  774. int st_mtime_nsec;
  775. int st_ctime;
  776. int st_ctime_nsec;
  777. };
  778. static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
  779. static void
  780. FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, int *time_out, int* nsec_out)
  781. {
  782. /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
  783. /* Cannot simply cast and dereference in_ptr,
  784. since it might not be aligned properly */
  785. __int64 in;
  786. memcpy(&in, in_ptr, sizeof(in));
  787. *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
  788. /* XXX Win32 supports time stamps past 2038; we currently don't */
  789. *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int);
  790. }
  791. static void
  792. time_t_to_FILE_TIME(int time_in, int nsec_in, FILETIME *out_ptr)
  793. {
  794. /* XXX endianness */
  795. __int64 out;
  796. out = time_in + secs_between_epochs;
  797. out = out * 10000000 + nsec_in / 100;
  798. memcpy(out_ptr, &out, sizeof(out));
  799. }
  800. /* Below, we *know* that ugo+r is 0444 */
  801. #if _S_IREAD != 0400
  802. #error Unsupported C library
  803. #endif
  804. static int
  805. attributes_to_mode(DWORD attr)
  806. {
  807. int m = 0;
  808. if (attr & FILE_ATTRIBUTE_DIRECTORY)
  809. m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
  810. else
  811. m |= _S_IFREG;
  812. if (attr & FILE_ATTRIBUTE_READONLY)
  813. m |= 0444;
  814. else
  815. m |= 0666;
  816. return m;
  817. }
  818. static int
  819. attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA *info, struct win32_stat *result)
  820. {
  821. memset(result, 0, sizeof(*result));
  822. result->st_mode = attributes_to_mode(info->dwFileAttributes);
  823. result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
  824. FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
  825. FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
  826. FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
  827. return 0;
  828. }
  829. static BOOL
  830. attributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
  831. {
  832. HANDLE hFindFile;
  833. WIN32_FIND_DATAA FileData;
  834. hFindFile = FindFirstFileA(pszFile, &FileData);
  835. if (hFindFile == INVALID_HANDLE_VALUE)
  836. return FALSE;
  837. FindClose(hFindFile);
  838. pfad->dwFileAttributes = FileData.dwFileAttributes;
  839. pfad->ftCreationTime = FileData.ftCreationTime;
  840. pfad->ftLastAccessTime = FileData.ftLastAccessTime;
  841. pfad->ftLastWriteTime = FileData.ftLastWriteTime;
  842. pfad->nFileSizeHigh = FileData.nFileSizeHigh;
  843. pfad->nFileSizeLow = FileData.nFileSizeLow;
  844. return TRUE;
  845. }
  846. static BOOL
  847. attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
  848. {
  849. HANDLE hFindFile;
  850. WIN32_FIND_DATAW FileData;
  851. hFindFile = FindFirstFileW(pszFile, &FileData);
  852. if (hFindFile == INVALID_HANDLE_VALUE)
  853. return FALSE;
  854. FindClose(hFindFile);
  855. pfad->dwFileAttributes = FileData.dwFileAttributes;
  856. pfad->ftCreationTime = FileData.ftCreationTime;
  857. pfad->ftLastAccessTime = FileData.ftLastAccessTime;
  858. pfad->ftLastWriteTime = FileData.ftLastWriteTime;
  859. pfad->nFileSizeHigh = FileData.nFileSizeHigh;
  860. pfad->nFileSizeLow = FileData.nFileSizeLow;
  861. return TRUE;
  862. }
  863. static int
  864. win32_stat(const char* path, struct win32_stat *result)
  865. {
  866. WIN32_FILE_ATTRIBUTE_DATA info;
  867. int code;
  868. char *dot;
  869. if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) {
  870. if (GetLastError() != ERROR_SHARING_VIOLATION) {
  871. /* Protocol violation: we explicitly clear errno, instead of
  872. setting it to a POSIX error. Callers should use GetLastError. */
  873. errno = 0;
  874. return -1;
  875. } else {
  876. /* Could not get attributes on open file. Fall back to
  877. reading the directory. */
  878. if (!attributes_from_dir(path, &info)) {
  879. /* Very strange. This should not fail now */
  880. errno = 0;
  881. return -1;
  882. }
  883. }
  884. }
  885. code = attribute_data_to_stat(&info, result);
  886. if (code != 0)
  887. return code;
  888. /* Set S_IFEXEC if it is an .exe, .bat, ... */
  889. dot = strrchr(path, '.');
  890. if (dot) {
  891. if (stricmp(dot, ".bat") == 0 ||
  892. stricmp(dot, ".cmd") == 0 ||
  893. stricmp(dot, ".exe") == 0 ||
  894. stricmp(dot, ".com") == 0)
  895. result->st_mode |= 0111;
  896. }
  897. return code;
  898. }
  899. static int
  900. win32_wstat(const wchar_t* path, struct win32_stat *result)
  901. {
  902. int code;
  903. const wchar_t *dot;
  904. WIN32_FILE_ATTRIBUTE_DATA info;
  905. if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) {
  906. if (GetLastError() != ERROR_SHARING_VIOLATION) {
  907. /* Protocol violation: we explicitly clear errno, instead of
  908. setting it to a POSIX error. Callers should use GetLastError. */
  909. errno = 0;
  910. return -1;
  911. } else {
  912. /* Could not get attributes on open file. Fall back to
  913. reading the directory. */
  914. if (!attributes_from_dir_w(path, &info)) {
  915. /* Very strange. This should not fail now */
  916. errno = 0;
  917. return -1;
  918. }
  919. }
  920. }
  921. code = attribute_data_to_stat(&info, result);
  922. if (code < 0)
  923. return code;
  924. /* Set IFEXEC if it is an .exe, .bat, ... */
  925. dot = wcsrchr(path, '.');
  926. if (dot) {
  927. if (_wcsicmp(dot, L".bat") == 0 ||
  928. _wcsicmp(dot, L".cmd") == 0 ||
  929. _wcsicmp(dot, L".exe") == 0 ||
  930. _wcsicmp(dot, L".com") == 0)
  931. result->st_mode |= 0111;
  932. }
  933. return code;
  934. }
  935. static int
  936. win32_fstat(int file_number, struct win32_stat *result)
  937. {
  938. BY_HANDLE_FILE_INFORMATION info;
  939. HANDLE h;
  940. int type;
  941. h = (HANDLE)_get_osfhandle(file_number);
  942. /* Protocol violation: we explicitly clear errno, instead of
  943. setting it to a POSIX error. Callers should use GetLastError. */
  944. errno = 0;
  945. if (h == INVALID_HANDLE_VALUE) {
  946. /* This is really a C library error (invalid file handle).
  947. We set the Win32 error to the closes one matching. */
  948. SetLastError(ERROR_INVALID_HANDLE);
  949. return -1;
  950. }
  951. memset(result, 0, sizeof(*result));
  952. type = GetFileType(h);
  953. if (type == FILE_TYPE_UNKNOWN) {
  954. DWORD error = GetLastError();
  955. if (error != 0) {
  956. return -1;
  957. }
  958. /* else: valid but unknown file */
  959. }
  960. if (type != FILE_TYPE_DISK) {
  961. if (type == FILE_TYPE_CHAR)
  962. result->st_mode = _S_IFCHR;
  963. else if (type == FILE_TYPE_PIPE)
  964. result->st_mode = _S_IFIFO;
  965. return 0;
  966. }
  967. if (!GetFileInformationByHandle(h, &info)) {
  968. return -1;
  969. }
  970. /* similar to stat() */
  971. result->st_mode = attributes_to_mode(info.dwFileAttributes);
  972. result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow;
  973. FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
  974. FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
  975. FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
  976. /* specific to fstat() */
  977. result->st_nlink = info.nNumberOfLinks;
  978. result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow;
  979. return 0;
  980. }
  981. #endif /* MS_WINDOWS */
  982. PyDoc_STRVAR(stat_result__doc__,
  983. "stat_result: Result from stat or lstat.\n\n\
  984. This object may be accessed either as a tuple of\n\
  985. (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
  986. or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
  987. \n\
  988. Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
  989. or st_flags, they are available as attributes only.\n\
  990. \n\
  991. See os.stat for more information.");
  992. static PyStructSequence_Field stat_result_fields[] = {
  993. {"st_mode", "protection bits"},
  994. {"st_ino", "inode"},
  995. {"st_dev", "device"},
  996. {"st_nlink", "number of hard links"},
  997. {"st_uid", "user ID of owner"},
  998. {"st_gid", "group ID of owner"},
  999. {"st_size", "total size, in bytes"},
  1000. /* The NULL is replaced with PyStructSequence_UnnamedField later. */
  1001. {NULL, "integer time of last access"},
  1002. {NULL, "integer time of last modification"},
  1003. {NULL, "integer time of last change"},
  1004. {"st_atime", "time of last access"},
  1005. {"st_mtime", "time of last modification"},
  1006. {"st_ctime", "time of last change"},
  1007. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1008. {"st_blksize", "blocksize for filesystem I/O"},
  1009. #endif
  1010. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1011. {"st_blocks", "number of blocks allocated"},
  1012. #endif
  1013. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1014. {"st_rdev", "device type (if inode device)"},
  1015. #endif
  1016. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1017. {"st_flags", "user defined flags for file"},
  1018. #endif
  1019. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1020. {"st_gen", "generation number"},
  1021. #endif
  1022. #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
  1023. {"st_birthtime", "time of creation"},
  1024. #endif
  1025. {0}
  1026. };
  1027. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1028. #define ST_BLKSIZE_IDX 13
  1029. #else
  1030. #define ST_BLKSIZE_IDX 12
  1031. #endif
  1032. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1033. #define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
  1034. #else
  1035. #define ST_BLOCKS_IDX ST_BLKSIZE_IDX
  1036. #endif
  1037. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1038. #define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
  1039. #else
  1040. #define ST_RDEV_IDX ST_BLOCKS_IDX
  1041. #endif
  1042. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1043. #define ST_FLAGS_IDX (ST_RDEV_IDX+1)
  1044. #else
  1045. #define ST_FLAGS_IDX ST_RDEV_IDX
  1046. #endif
  1047. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1048. #define ST_GEN_IDX (ST_FLAGS_IDX+1)
  1049. #else
  1050. #define ST_GEN_IDX ST_FLAGS_IDX
  1051. #endif
  1052. #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
  1053. #define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
  1054. #else
  1055. #define ST_BIRTHTIME_IDX ST_GEN_IDX
  1056. #endif
  1057. static PyStructSequence_Desc stat_result_desc = {
  1058. "stat_result", /* name */
  1059. stat_result__doc__, /* doc */
  1060. stat_result_fields,
  1061. 10
  1062. };
  1063. PyDoc_STRVAR(statvfs_result__doc__,
  1064. "statvfs_result: Result from statvfs or fstatvfs.\n\n\
  1065. This object may be accessed either as a tuple of\n\
  1066. (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
  1067. or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
  1068. \n\
  1069. See os.statvfs for more information.");
  1070. static PyStructSequence_Field statvfs_result_fields[] = {
  1071. {"f_bsize", },
  1072. {"f_frsize", },
  1073. {"f_blocks", },
  1074. {"f_bfree", },
  1075. {"f_bavail", },
  1076. {"f_files", },
  1077. {"f_ffree", },
  1078. {"f_favail", },
  1079. {"f_flag", },
  1080. {"f_namemax",},
  1081. {0}
  1082. };
  1083. static PyStructSequence_Desc statvfs_result_desc = {
  1084. "statvfs_result", /* name */
  1085. statvfs_result__doc__, /* doc */
  1086. statvfs_result_fields,
  1087. 10
  1088. };
  1089. static int initialized;
  1090. static PyTypeObject StatResultType;
  1091. static PyTypeObject StatVFSResultType;
  1092. static newfunc structseq_new;
  1093. static PyObject *
  1094. statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1095. {
  1096. PyStructSequence *result;
  1097. int i;
  1098. result = (PyStructSequence*)structseq_new(type, args, kwds);
  1099. if (!result)
  1100. return NULL;
  1101. /* If we have been initialized from a tuple,
  1102. st_?time might be set to None. Initialize it
  1103. from the int slots. */
  1104. for (i = 7; i <= 9; i++) {
  1105. if (result->ob_item[i+3] == Py_None) {
  1106. Py_DECREF(Py_None);
  1107. Py_INCREF(result->ob_item[i]);
  1108. result->ob_item[i+3] = result->ob_item[i];
  1109. }
  1110. }
  1111. return (PyObject*)result;
  1112. }
  1113. /* If true, st_?time is float. */
  1114. static int _stat_float_times = 1;
  1115. PyDoc_STRVAR(stat_float_times__doc__,
  1116. "stat_float_times([newval]) -> oldval\n\n\
  1117. Determine whether os.[lf]stat represents time stamps as float objects.\n\
  1118. If newval is True, future calls to stat() return floats, if it is False,\n\
  1119. future calls return ints. \n\
  1120. If newval is omitted, return the current setting.\n");
  1121. static PyObject*
  1122. stat_float_times(PyObject* self, PyObject *args)
  1123. {
  1124. int newval = -1;
  1125. if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval))
  1126. return NULL;
  1127. if (newval == -1)
  1128. /* Return old value */
  1129. return PyBool_FromLong(_stat_float_times);
  1130. _stat_float_times = newval;
  1131. Py_INCREF(Py_None);
  1132. return Py_None;
  1133. }
  1134. static void
  1135. fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
  1136. {
  1137. PyObject *fval,*ival;
  1138. #if SIZEOF_TIME_T > SIZEOF_LONG
  1139. ival = PyLong_FromLongLong((PY_LONG_LONG)sec);
  1140. #else
  1141. ival = PyInt_FromLong((long)sec);
  1142. #endif
  1143. if (!ival)
  1144. return;
  1145. if (_stat_float_times) {
  1146. fval = PyFloat_FromDouble(sec + 1e-9*nsec);
  1147. } else {
  1148. fval = ival;
  1149. Py_INCREF(fval);
  1150. }
  1151. PyStructSequence_SET_ITEM(v, index, ival);
  1152. PyStructSequence_SET_ITEM(v, index+3, fval);
  1153. }
  1154. /* pack a system stat C structure into the Python stat tuple
  1155. (used by posix_stat() and posix_fstat()) */
  1156. static PyObject*
  1157. _pystat_fromstructstat(STRUCT_STAT *st)
  1158. {
  1159. unsigned long ansec, mnsec, cnsec;
  1160. PyObject *v = PyStructSequence_New(&StatResultType);
  1161. if (v == NULL)
  1162. return NULL;
  1163. PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long)st->st_mode));
  1164. #ifdef HAVE_LARGEFILE_SUPPORT
  1165. PyStructSequence_SET_ITEM(v, 1,
  1166. PyLong_FromLongLong((PY_LONG_LONG)st->st_ino));
  1167. #else
  1168. PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long)st->st_ino));
  1169. #endif
  1170. #if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS)
  1171. PyStructSequence_SET_ITEM(v, 2,
  1172. PyLong_FromLongLong((PY_LONG_LONG)st->st_dev));
  1173. #else
  1174. PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long)st->st_dev));
  1175. #endif
  1176. PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long)st->st_nlink));
  1177. PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long)st->st_uid));
  1178. PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long)st->st_gid));
  1179. #ifdef HAVE_LARGEFILE_SUPPORT
  1180. PyStructSequence_SET_ITEM(v, 6,
  1181. PyLong_FromLongLong((PY_LONG_LONG)st->st_size));
  1182. #else
  1183. PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong(st->st_size));
  1184. #endif
  1185. #if defined(HAVE_STAT_TV_NSEC)
  1186. ansec = st->st_atim.tv_nsec;
  1187. mnsec = st->st_mtim.tv_nsec;
  1188. cnsec = st->st_ctim.tv_nsec;
  1189. #elif defined(HAVE_STAT_TV_NSEC2)
  1190. ansec = st->st_atimespec.tv_nsec;
  1191. mnsec = st->st_mtimespec.tv_nsec;
  1192. cnsec = st->st_ctimespec.tv_nsec;
  1193. #elif defined(HAVE_STAT_NSEC)
  1194. ansec = st->st_atime_nsec;
  1195. mnsec = st->st_mtime_nsec;
  1196. cnsec = st->st_ctime_nsec;
  1197. #else
  1198. ansec = mnsec = cnsec = 0;
  1199. #endif
  1200. fill_time(v, 7, st->st_atime, ansec);
  1201. fill_time(v, 8, st->st_mtime, mnsec);
  1202. fill_time(v, 9, st->st_ctime, cnsec);
  1203. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1204. PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
  1205. PyInt_FromLong((long)st->st_blksize));
  1206. #endif
  1207. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1208. PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
  1209. PyInt_FromLong((long)st->st_blocks));
  1210. #endif
  1211. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1212. PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
  1213. PyInt_FromLong((long)st->st_rdev));
  1214. #endif
  1215. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1216. PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
  1217. PyInt_FromLong((long)st->st_gen));
  1218. #endif
  1219. #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
  1220. {
  1221. PyObject *val;
  1222. unsigned long bsec,bnsec;
  1223. bsec = (long)st->st_birthtime;
  1224. #ifdef HAVE_STAT_TV_NSEC2
  1225. bnsec = st->st_birthtimespec.tv_nsec;
  1226. #else
  1227. bnsec = 0;
  1228. #endif
  1229. if (_stat_float_times) {
  1230. val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
  1231. } else {
  1232. val = PyInt_FromLong((long)bsec);
  1233. }
  1234. PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
  1235. val);
  1236. }
  1237. #endif
  1238. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1239. PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
  1240. PyInt_FromLong((long)st->st_flags));
  1241. #endif
  1242. if (PyErr_Occurred()) {
  1243. Py_DECREF(v);
  1244. return NULL;
  1245. }
  1246. return v;
  1247. }
  1248. #ifdef MS_WINDOWS
  1249. /* IsUNCRoot -- test whether the supplied path is of the form \\SERVER\SHARE\,
  1250. where / can be used in place of \ and the trailing slash is optional.
  1251. Both SERVER and SHARE must have at least one character.
  1252. */
  1253. #define ISSLASHA(c) ((c) == '\\' || (c) == '/')
  1254. #define ISSLASHW(c) ((c) == L'\\' || (c) == L'/')
  1255. #ifndef ARRAYSIZE
  1256. #define ARRAYSIZE(a) (sizeof(a) / sizeof(a[0]))
  1257. #endif
  1258. static BOOL
  1259. IsUNCRootA(char *path, int pathlen)
  1260. {
  1261. #define ISSLASH ISSLASHA
  1262. int i, share;
  1263. if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1]))
  1264. /* minimum UNCRoot is \\x\y */
  1265. return FALSE;
  1266. for (i = 2; i < pathlen ; i++)
  1267. if (ISSLASH(path[i])) break;
  1268. if (i == 2 || i == pathlen)
  1269. /* do not allow \\\SHARE or \\SERVER */
  1270. return FALSE;
  1271. share = i+1;
  1272. for (i = share; i < pathlen; i++)
  1273. if (ISSLASH(path[i])) break;
  1274. return (i != share && (i == pathlen || i == pathlen-1));
  1275. #undef ISSLASH
  1276. }
  1277. static BOOL
  1278. IsUNCRootW(Py_UNICODE *path, int pathlen)
  1279. {
  1280. #define ISSLASH ISSLASHW
  1281. int i, share;
  1282. if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1]))
  1283. /* minimum UNCRoot is \\x\y */
  1284. return FALSE;
  1285. for (i = 2; i < pathlen ; i++)
  1286. if (ISSLASH(path[i])) break;
  1287. if (i == 2 || i == pathlen)
  1288. /* do not allow \\\SHARE or \\SERVER */
  1289. return FALSE;
  1290. share = i+1;
  1291. for (i = share; i < pathlen; i++)
  1292. if (ISSLASH(path[i])) break;
  1293. return (i != share && (i == pathlen || i == pathlen-1));
  1294. #undef ISSLASH
  1295. }
  1296. #endif /* MS_WINDOWS */
  1297. static PyObject *
  1298. posix_do_stat(PyObject *self, PyObject *args,
  1299. char *format,
  1300. #ifdef __VMS
  1301. int (*statfunc)(const char *, STRUCT_STAT *, ...),
  1302. #else
  1303. int (*statfunc)(const char *, STRUCT_STAT *),
  1304. #endif
  1305. char *wformat,
  1306. int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *))
  1307. {
  1308. STRUCT_STAT st;
  1309. char *path = NULL; /* pass this to stat; do not free() it */
  1310. char *pathfree = NULL; /* this memory must be free'd */
  1311. int res;
  1312. PyObject *result;
  1313. #ifdef MS_WINDOWS
  1314. PyUnicodeObject *po;
  1315. if (PyArg_ParseTuple(args, wformat, &po)) {
  1316. Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);
  1317. Py_BEGIN_ALLOW_THREADS
  1318. /* PyUnicode_AS_UNICODE result OK without
  1319. thread lock as it is a simple dereference. */
  1320. res = wstatfunc(wpath, &st);
  1321. Py_END_ALLOW_THREADS
  1322. if (res != 0)
  1323. return win32_error_unicode("stat", wpath);
  1324. return _pystat_fromstructstat(&st);
  1325. }
  1326. /* Drop the argument parsing error as narrow strings
  1327. are also valid. */
  1328. PyErr_Clear();
  1329. #endif
  1330. if (!PyArg_ParseTuple(args, format,
  1331. Py_FileSystemDefaultEncoding, &path))
  1332. return NULL;
  1333. pathfree = path;
  1334. Py_BEGIN_ALLOW_THREADS
  1335. res = (*statfunc)(path, &st);
  1336. Py_END_ALLOW_THREADS
  1337. if (res != 0) {
  1338. #ifdef MS_WINDOWS
  1339. result = win32_error("stat", pathfree);
  1340. #else
  1341. result = posix_error_with_filename(pathfree);
  1342. #endif
  1343. }
  1344. else
  1345. result = _pystat_fromstructstat(&st);
  1346. PyMem_Free(pathfree);
  1347. return result;
  1348. }
  1349. /* POSIX methods */
  1350. PyDoc_STRVAR(posix_access__doc__,
  1351. "access(path, mode) -> True if granted, False otherwise\n\n\
  1352. Use the real uid/gid to test for access to a path. Note that most\n\
  1353. operations will use the effective uid/gid, therefore this routine can\n\
  1354. be used in a suid/sgid environment to test if the invoking user has the\n\
  1355. specified access to the path. The mode argument can be F_OK to test\n\
  1356. existence, or the inclusive-OR of R_OK, W_OK, and X_OK.");
  1357. static PyObject *
  1358. posix_access(PyObject *self, PyObject *args)
  1359. {
  1360. char *path;
  1361. int mode;
  1362. #ifdef MS_WINDOWS
  1363. DWORD attr;
  1364. PyUnicodeObject *po;
  1365. if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) {
  1366. Py_BEGIN_ALLOW_THREADS
  1367. /* PyUnicode_AS_UNICODE OK without thread lock as
  1368. it is a simple dereference. */
  1369. attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po));
  1370. Py_END_ALLOW_THREADS
  1371. goto finish;
  1372. }
  1373. /* Drop the argument parsing error as narrow strings
  1374. are also valid. */
  1375. PyErr_Clear();
  1376. if (!PyArg_ParseTuple(args, "eti:access",
  1377. Py_FileSystemDefaultEncoding, &path, &mode))
  1378. return NULL;
  1379. Py_BEGIN_ALLOW_THREADS
  1380. attr = GetFileAttributesA(path);
  1381. Py_END_ALLOW_THREADS
  1382. PyMem_Free(path);
  1383. finish:
  1384. if (attr == 0xFFFFFFFF)
  1385. /* File does not exist, or cannot read attributes */
  1386. return PyBool_FromLong(0);
  1387. /* Access is possible if either write access wasn't requested, or
  1388. the file isn't read-only, or if it's a directory, as there are
  1389. no read-only directories on Windows. */
  1390. return PyBool_FromLong(!(mode & 2)
  1391. || !(attr & FILE_ATTRIBUTE_READONLY)
  1392. || (attr & FILE_ATTRIBUTE_DIRECTORY));
  1393. #else /* MS_WINDOWS */
  1394. int res;
  1395. if (!PyArg_ParseTuple(args, "eti:access",
  1396. Py_FileSystemDefaultEncoding, &path, &mode))
  1397. return NULL;
  1398. Py_BEGIN_ALLOW_THREADS
  1399. res = access(path, mode);
  1400. Py_END_ALLOW_THREADS
  1401. PyMem_Free(path);
  1402. return PyBool_FromLong(res == 0);
  1403. #endif /* MS_WINDOWS */
  1404. }
  1405. #ifndef F_OK
  1406. #define F_OK 0
  1407. #endif
  1408. #ifndef R_OK
  1409. #define R_OK 4
  1410. #endif
  1411. #ifndef W_OK
  1412. #define W_OK 2
  1413. #endif
  1414. #ifndef X_OK
  1415. #define X_OK 1
  1416. #endif
  1417. #ifdef HAVE_TTYNAME
  1418. PyDoc_STRVAR(posix_ttyname__doc__,
  1419. "ttyname(fd) -> string\n\n\
  1420. Return the name of the terminal device connected to 'fd'.");
  1421. static PyObject *
  1422. posix_ttyname(PyObject *self, PyObject *args)
  1423. {
  1424. int id;
  1425. char *ret;
  1426. if (!PyArg_ParseTuple(args, "i:ttyname", &id))
  1427. return NULL;
  1428. #if defined(__VMS)
  1429. /* file descriptor 0 only, the default input device (stdin) */
  1430. if (id == 0) {
  1431. ret = ttyname();
  1432. }
  1433. else {
  1434. ret = NULL;
  1435. }
  1436. #else
  1437. ret = ttyname(id);
  1438. #endif
  1439. if (ret == NULL)
  1440. return posix_error();
  1441. return PyString_FromString(ret);
  1442. }
  1443. #endif
  1444. #ifdef HAVE_CTERMID
  1445. PyDoc_STRVAR(posix_ctermid__doc__,
  1446. "ctermid() -> string\n\n\
  1447. Return the name of the controlling terminal for this process.");
  1448. static PyObject *
  1449. posix_ctermid(PyObject *self, PyObject *noargs)
  1450. {
  1451. char *ret;
  1452. char buffer[L_ctermid];
  1453. #ifdef USE_CTERMID_R
  1454. ret = ctermid_r(buffer);
  1455. #else
  1456. ret = ctermid(buffer);
  1457. #endif
  1458. if (ret == NULL)
  1459. return posix_error();
  1460. return PyString_FromString(buffer);
  1461. }
  1462. #endif
  1463. PyDoc_STRVAR(posix_chdir__doc__,
  1464. "chdir(path)\n\n\
  1465. Change the current working directory to the specified path.");
  1466. static PyObject *
  1467. posix_chdir(PyObject *self, PyObject *args)
  1468. {
  1469. #ifdef MS_WINDOWS
  1470. return win32_1str(args, "chdir", "s:chdir", win32_chdir, "U:chdir", win32_wchdir);
  1471. #elif defined(PYOS_OS2) && defined(PYCC_GCC)
  1472. return posix_1str(args, "et:chdir", _chdir2);
  1473. #elif defined(__VMS)
  1474. return posix_1str(args, "et:chdir", (int (*)(const char *))chdir);
  1475. #else
  1476. return posix_1str(args, "et:chdir", chdir);
  1477. #endif
  1478. }
  1479. #ifdef HAVE_FCHDIR
  1480. PyDoc_STRVAR(posix_fchdir__doc__,
  1481. "fchdir(fildes)\n\n\
  1482. Change to the directory of the given file descriptor. fildes must be\n\
  1483. opened on a directory, not a file.");
  1484. static PyObject *
  1485. posix_fchdir(PyObject *self, PyObject *fdobj)
  1486. {
  1487. return posix_fildes(fdobj, fchdir);
  1488. }
  1489. #endif /* HAVE_FCHDIR */
  1490. PyDoc_STRVAR(posix_chmod__doc__,
  1491. "chmod(path, mode)\n\n\
  1492. Change the access permissions of a file.");
  1493. static PyObject *
  1494. posix_chmod(PyObject *self, PyObject *args)
  1495. {
  1496. char *path = NULL;
  1497. int i;
  1498. int res;
  1499. #ifdef MS_WINDOWS
  1500. DWORD attr;
  1501. PyUnicodeObject *po;
  1502. if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) {
  1503. Py_BEGIN_ALLOW_THREADS
  1504. attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po));
  1505. if (attr != 0xFFFFFFFF) {
  1506. if (i & _S_IWRITE)
  1507. attr &= ~FILE_ATTRIBUTE_READONLY;
  1508. else
  1509. attr |= FILE_ATTRIBUTE_READONLY;
  1510. res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr);
  1511. }
  1512. else
  1513. res = 0;
  1514. Py_END_ALLOW_THREADS
  1515. if (!res)
  1516. return win32_error_unicode("chmod",
  1517. PyUnicode_AS_UNICODE(po));
  1518. Py_INCREF(Py_None);
  1519. return Py_None;
  1520. }
  1521. /* Drop the argument parsing error as narrow strings
  1522. are also valid. */
  1523. PyErr_Clear();
  1524. if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding,
  1525. &path, &i))
  1526. return NULL;
  1527. Py_BEGIN_ALLOW_THREADS
  1528. attr = GetFileAttributesA(path);
  1529. if (attr != 0xFFFFFFFF) {
  1530. if (i & _S_IWRITE)
  1531. attr &= ~FILE_ATTRIBUTE_READONLY;
  1532. else
  1533. attr |= FILE_ATTRIBUTE_READONLY;
  1534. res = SetFileAttributesA(path, attr);
  1535. }
  1536. else
  1537. res = 0;
  1538. Py_END_ALLOW_THREADS
  1539. if (!res) {
  1540. win32_error("chmod", path);
  1541. PyMem_Free(path);
  1542. return NULL;
  1543. }
  1544. PyMem_Free(path);
  1545. Py_INCREF(Py_None);
  1546. return Py_None;
  1547. #else /* MS_WINDOWS */
  1548. if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding,
  1549. &path, &i))
  1550. return NULL;
  1551. Py_BEGIN_ALLOW_THREADS
  1552. res = chmod(path, i);
  1553. Py_END_ALLOW_THREADS
  1554. if (res < 0)
  1555. return posix_error_with_allocated_filename(path);
  1556. PyMem_Free(path);
  1557. Py_INCREF(Py_None);
  1558. return Py_None;
  1559. #endif
  1560. }
  1561. #ifdef HAVE_FCHMOD
  1562. PyDoc_STRVAR(posix_fchmod__doc__,
  1563. "fchmod(fd, mode)\n\n\
  1564. Change the access permissions of the file given by file\n\
  1565. descriptor fd.");
  1566. static PyObject *
  1567. posix_fchmod(PyObject *self, PyObject *args)
  1568. {
  1569. int fd, mode, res;
  1570. if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode))
  1571. return NULL;
  1572. Py_BEGIN_ALLOW_THREADS
  1573. res = fchmod(fd, mode);
  1574. Py_END_ALLOW_THREADS
  1575. if (res < 0)
  1576. return posix_error();
  1577. Py_RETURN_NONE;
  1578. }
  1579. #endif /* HAVE_FCHMOD */
  1580. #ifdef HAVE_LCHMOD
  1581. PyDoc_STRVAR(posix_lchmod__doc__,
  1582. "lchmod(path, mode)\n\n\
  1583. Change the access permissions of a file. If path is a symlink, this\n\
  1584. affects the link itself rather than the target.");
  1585. static PyObject *
  1586. posix_lchmod(PyObject *self, PyObject *args)
  1587. {
  1588. char *path = NULL;
  1589. int i;
  1590. int res;
  1591. if (!PyArg_ParseTuple(args, "eti:lchmod", Py_FileSystemDefaultEncoding,
  1592. &path, &i))
  1593. return NULL;
  1594. Py_BEGIN_ALLOW_THREADS
  1595. res = lchmod(path, i);
  1596. Py_END_ALLOW_THREADS
  1597. if (res < 0)
  1598. return posix_error_with_allocated_filename(path);
  1599. PyMem_Free(path);
  1600. Py_RETURN_NONE;
  1601. }
  1602. #endif /* HAVE_LCHMOD */
  1603. #ifdef HAVE_CHFLAGS
  1604. PyDoc_STRVAR(posix_chflags__doc__,
  1605. "chflags(path, flags)\n\n\
  1606. Set file flags.");
  1607. static PyObject *
  1608. posix_chflags(PyObject *self, PyObject *args)
  1609. {
  1610. char *path;
  1611. unsigned long flags;
  1612. int res;
  1613. if (!PyArg_ParseTuple(args, "etk:chflags",
  1614. Py_FileSystemDefaultEncoding, &path, &flags))
  1615. return NULL;
  1616. Py_BEGIN_ALLOW_THREADS
  1617. res = chflags(path, flags);
  1618. Py_END_ALLOW_THREADS
  1619. if (res < 0)
  1620. return posix_error_with_allocated_filename(path);
  1621. PyMem_Free(path);
  1622. Py_INCREF(Py_None);
  1623. return Py_None;
  1624. }
  1625. #endif /* HAVE_CHFLAGS */
  1626. #ifdef HAVE_LCHFLAGS
  1627. PyDoc_STRVAR(posix_lchflags__doc__,
  1628. "lchflags(path, flags)\n\n\
  1629. Set file flags.\n\
  1630. This function will not follow symbolic links.");
  1631. static PyObject *
  1632. posix_lchflags(PyObject *self, PyObject *args)
  1633. {
  1634. char *path;
  1635. unsigned long flags;
  1636. int res;
  1637. if (!PyArg_ParseTuple(args, "etk:lchflags",
  1638. Py_FileSystemDefaultEncoding, &path, &flags))
  1639. return NULL;
  1640. Py_BEGIN_ALLOW_THREADS
  1641. res = lchflags(path, flags);
  1642. Py_END_ALLOW_THREADS
  1643. if (res < 0)
  1644. return posix_error_with_allocated_filename(path);
  1645. PyMem_Free(path);
  1646. Py_INCREF(Py_None);
  1647. return Py_None;
  1648. }
  1649. #endif /* HAVE_LCHFLAGS */
  1650. #ifdef HAVE_CHROOT
  1651. PyDoc_STRVAR(posix_chroot__doc__,
  1652. "chroot(path)\n\n\
  1653. Change root directory to path.");
  1654. static PyObject *
  1655. posix_chroot(PyObject *self, PyObject *args)
  1656. {
  1657. return posix_1str(args, "et:chroot", chroot);
  1658. }
  1659. #endif
  1660. #ifdef HAVE_FSYNC
  1661. PyDoc_STRVAR(posix_fsync__doc__,
  1662. "fsync(fildes)\n\n\
  1663. force write of file with filedescriptor to disk.");
  1664. static PyObject *
  1665. posix_fsync(PyObject *self, PyObject *fdobj)
  1666. {
  1667. return posix_fildes(fdobj, fsync);
  1668. }
  1669. #endif /* HAVE_FSYNC */
  1670. #ifdef HAVE_FDATASYNC
  1671. #ifdef __hpux
  1672. extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
  1673. #endif
  1674. PyDoc_STRVAR(posix_fdatasync__doc__,
  1675. "fdatasync(fildes)\n\n\
  1676. force write of file with filedescriptor to disk.\n\
  1677. does not force update of metadata.");
  1678. static PyObject *
  1679. posix_fdatasync(PyObject *self, PyObject *fdobj)
  1680. {
  1681. return posix_fildes(fdobj, fdatasync);
  1682. }
  1683. #endif /* HAVE_FDATASYNC */
  1684. #ifdef HAVE_CHOWN
  1685. PyDoc_STRVAR(posix_chown__doc__,
  1686. "chown(path, uid, gid)\n\n\
  1687. Change the owner and group id of path to the numeric uid and gid.");
  1688. static PyObject *
  1689. posix_chown(PyObject *self, PyObject *args)
  1690. {
  1691. char *path = NULL;
  1692. long uid, gid;
  1693. int res;
  1694. if (!PyArg_ParseTuple(args, "etll:chown",
  1695. Py_FileSystemDefaultEncoding, &path,
  1696. &uid, &gid))
  1697. return NULL;
  1698. Py_BEGIN_ALLOW_THREADS
  1699. res = chown(path, (uid_t) uid, (gid_t) gid);
  1700. Py_END_ALLOW_THREADS
  1701. if (res < 0)
  1702. return posix_error_with_allocated_filename(path);
  1703. PyMem_Free(path);
  1704. Py_INCREF(Py_None);
  1705. return Py_None;
  1706. }
  1707. #endif /* HAVE_CHOWN */
  1708. #ifdef HAVE_FCHOWN
  1709. PyDoc_STRVAR(posix_fchown__doc__,
  1710. "fchown(fd, uid, gid)\n\n\
  1711. Change the owner and group id of the file given by file descriptor\n\
  1712. fd to the numeric uid and gid.");
  1713. static PyObject *
  1714. posix_fchown(PyObject *self, PyObject *args)
  1715. {
  1716. int fd;
  1717. long uid, gid;
  1718. int res;
  1719. if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid))
  1720. return NULL;
  1721. Py_BEGIN_ALLOW_THREADS
  1722. res = fchown(fd, (uid_t) uid, (gid_t) gid);
  1723. Py_END_ALLOW_THREADS
  1724. if (res < 0)
  1725. return posix_error();
  1726. Py_RETURN_NONE;
  1727. }
  1728. #endif /* HAVE_FCHOWN */
  1729. #ifdef HAVE_LCHOWN
  1730. PyDoc_STRVAR(posix_lchown__doc__,
  1731. "lchown(path, uid, gid)\n\n\
  1732. Change the owner and group id of path to the numeric uid and gid.\n\
  1733. This function will not follow symbolic links.");
  1734. static PyObject *
  1735. posix_lchown(PyObject *self, PyObject *args)
  1736. {
  1737. char *path = NULL;
  1738. long uid, gid;
  1739. int res;
  1740. if (!PyArg_ParseTuple(args, "etll:lchown",
  1741. Py_FileSystemDefaultEncoding, &path,
  1742. &uid, &gid))
  1743. return NULL;
  1744. Py_BEGIN_ALLOW_THREADS
  1745. res = lchown(path, (uid_t) uid, (gid_t) gid);
  1746. Py_END_ALLOW_THREADS
  1747. if (res < 0)
  1748. return posix_error_with_allocated_filename(path);
  1749. PyMem_Free(path);
  1750. Py_INCREF(Py_None);
  1751. return Py_None;
  1752. }
  1753. #endif /* HAVE_LCHOWN */
  1754. #ifdef HAVE_GETCWD
  1755. PyDoc_STRVAR(posix_getcwd__doc__,
  1756. "getcwd() -> path\n\n\
  1757. Return a string representing the current working directory.");
  1758. #if (defined(__sun) && defined(__SVR4)) || defined(__OpenBSD__)
  1759. /* Issue 9185: getcwd() returns NULL/ERANGE indefinitely. */
  1760. static PyObject *
  1761. posix_getcwd(PyObject *self, PyObject *noargs)
  1762. {
  1763. char buf[PATH_MAX+2];
  1764. char *res;
  1765. Py_BEGIN_ALLOW_THREADS
  1766. res = getcwd(buf, sizeof buf);
  1767. Py_END_ALLOW_THREADS
  1768. if (res == NULL)
  1769. return posix_error();
  1770. return PyString_FromString(buf);
  1771. }
  1772. #else
  1773. static PyObject *
  1774. posix_getcwd(PyObject *self, PyObject *noargs)
  1775. {
  1776. int bufsize_incr = 1024;
  1777. int bufsize = 0;
  1778. char *tmpbuf = NULL;
  1779. char *res = NULL;
  1780. PyObject *dynamic_return;
  1781. Py_BEGIN_ALLOW_THREADS
  1782. do {
  1783. bufsize = bufsize + bufsize_incr;
  1784. tmpbuf = malloc(bufsize);
  1785. if (tmpbuf == NULL) {
  1786. break;
  1787. }
  1788. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  1789. res = _getcwd2(tmpbuf, bufsize);
  1790. #else
  1791. res = getcwd(tmpbuf, bufsize);
  1792. #endif
  1793. if (res == NULL) {
  1794. free(tmpbuf);
  1795. }
  1796. } while ((res == NULL) && (errno == ERANGE));
  1797. Py_END_ALLOW_THREADS
  1798. if (res == NULL)
  1799. return posix_error();
  1800. dynamic_return = PyString_FromString(tmpbuf);
  1801. free(tmpbuf);
  1802. return dynamic_return;
  1803. }
  1804. #endif /* getcwd() NULL/ERANGE workaround. */
  1805. #ifdef Py_USING_UNICODE
  1806. PyDoc_STRVAR(posix_getcwdu__doc__,
  1807. "getcwdu() -> path\n\n\
  1808. Return a unicode string representing the current working directory.");
  1809. static PyObject *
  1810. posix_getcwdu(PyObject *self, PyObject *noargs)
  1811. {
  1812. char buf[1026];
  1813. char *res;
  1814. #ifdef MS_WINDOWS
  1815. DWORD len;
  1816. wchar_t wbuf[1026];
  1817. wchar_t *wbuf2 = wbuf;
  1818. PyObject *resobj;
  1819. Py_BEGIN_ALLOW_THREADS
  1820. len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf);
  1821. /* If the buffer is large enough, len does not include the
  1822. terminating \0. If the buffer is too small, len includes
  1823. the space needed for the terminator. */
  1824. if (len >= sizeof wbuf/ sizeof wbuf[0]) {
  1825. wbuf2 = malloc(len * sizeof(wchar_t));
  1826. if (wbuf2)
  1827. len = GetCurrentDirectoryW(len, wbuf2);
  1828. }
  1829. Py_END_ALLOW_THREADS
  1830. if (!wbuf2) {
  1831. PyErr_NoMemory();
  1832. return NULL;
  1833. }
  1834. if (!len) {
  1835. if (wbuf2 != wbuf) free(wbuf2);
  1836. return win32_error("getcwdu", NULL);
  1837. }
  1838. resobj = PyUnicode_FromWideChar(wbuf2, len);
  1839. if (wbuf2 != wbuf) free(wbuf2);
  1840. return resobj;
  1841. #endif /* MS_WINDOWS */
  1842. Py_BEGIN_ALLOW_THREADS
  1843. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  1844. res = _getcwd2(buf, sizeof buf);
  1845. #else
  1846. res = getcwd(buf, sizeof buf);
  1847. #endif
  1848. Py_END_ALLOW_THREADS
  1849. if (res == NULL)
  1850. return posix_error();
  1851. return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"strict");
  1852. }
  1853. #endif /* Py_USING_UNICODE */
  1854. #endif /* HAVE_GETCWD */
  1855. #ifdef HAVE_LINK
  1856. PyDoc_STRVAR(posix_link__doc__,
  1857. "link(src, dst)\n\n\
  1858. Create a hard link to a file.");
  1859. static PyObject *
  1860. posix_link(PyObject *self, PyObject *args)
  1861. {
  1862. return posix_2str(args, "etet:link", link);
  1863. }
  1864. #endif /* HAVE_LINK */
  1865. PyDoc_STRVAR(posix_listdir__doc__,
  1866. "listdir(path) -> list_of_strings\n\n\
  1867. Return a list containing the names of the entries in the directory.\n\
  1868. \n\
  1869. path: path of directory to list\n\
  1870. \n\
  1871. The list is in arbitrary order. It does not include the special\n\
  1872. entries '.' and '..' even if they are present in the directory.");
  1873. static PyObject *
  1874. posix_listdir(PyObject *self, PyObject *args)
  1875. {
  1876. /* XXX Should redo this putting the (now four) versions of opendir
  1877. in separate files instead of having them all here... */
  1878. #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
  1879. PyObject *d, *v;
  1880. HANDLE hFindFile;
  1881. BOOL result;
  1882. WIN32_FIND_DATA FileData;
  1883. char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */
  1884. char *bufptr = namebuf;
  1885. Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */
  1886. PyObject *po;
  1887. if (PyArg_ParseTuple(args, "U:listdir", &po)) {
  1888. WIN32_FIND_DATAW wFileData;
  1889. Py_UNICODE *wnamebuf;
  1890. /* Overallocate for \\*.*\0 */
  1891. len = PyUnicode_GET_SIZE(po);
  1892. wnamebuf = malloc((len + 5) * sizeof(wchar_t));
  1893. if (!wnamebuf) {
  1894. PyErr_NoMemory();
  1895. return NULL;
  1896. }
  1897. wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po));
  1898. if (len > 0) {
  1899. Py_UNICODE wch = wnamebuf[len-1];
  1900. if (wch != L'/' && wch != L'\\' && wch != L':')
  1901. wnamebuf[len++] = L'\\';
  1902. wcscpy(wnamebuf + len, L"*.*");
  1903. }
  1904. if ((d = PyList_New(0)) == NULL) {
  1905. free(wnamebuf);
  1906. return NULL;
  1907. }
  1908. Py_BEGIN_ALLOW_THREADS
  1909. hFindFile = FindFirstFileW(wnamebuf, &wFileData);
  1910. Py_END_ALLOW_THREADS
  1911. if (hFindFile == INVALID_HANDLE_VALUE) {
  1912. int error = GetLastError();
  1913. if (error == ERROR_FILE_NOT_FOUND) {
  1914. free(wnamebuf);
  1915. return d;
  1916. }
  1917. Py_DECREF(d);
  1918. win32_error_unicode("FindFirstFileW", wnamebuf);
  1919. free(wnamebuf);
  1920. return NULL;
  1921. }
  1922. do {
  1923. /* Skip over . and .. */
  1924. if (wcscmp(wFileData.cFileName, L".") != 0 &&
  1925. wcscmp(wFileData.cFileName, L"..") != 0) {
  1926. v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName));
  1927. if (v == NULL) {
  1928. Py_DECREF(d);
  1929. d = NULL;
  1930. break;
  1931. }
  1932. if (PyList_Append(d, v) != 0) {
  1933. Py_DECREF(v);
  1934. Py_DECREF(d);
  1935. d = NULL;
  1936. break;
  1937. }
  1938. Py_DECREF(v);
  1939. }
  1940. Py_BEGIN_ALLOW_THREADS
  1941. result = FindNextFileW(hFindFile, &wFileData);
  1942. Py_END_ALLOW_THREADS
  1943. /* FindNextFile sets error to ERROR_NO_MORE_FILES if
  1944. it got to the end of the directory. */
  1945. if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
  1946. Py_DECREF(d);
  1947. win32_error_unicode("FindNextFileW", wnamebuf);
  1948. FindClose(hFindFile);
  1949. free(wnamebuf);
  1950. return NULL;
  1951. }
  1952. } while (result == TRUE);
  1953. if (FindClose(hFindFile) == FALSE) {
  1954. Py_DECREF(d);
  1955. win32_error_unicode("FindClose", wnamebuf);
  1956. free(wnamebuf);
  1957. return NULL;
  1958. }
  1959. free(wnamebuf);
  1960. return d;
  1961. }
  1962. /* Drop the argument parsing error as narrow strings
  1963. are also valid. */
  1964. PyErr_Clear();
  1965. if (!PyArg_ParseTuple(args, "et#:listdir",
  1966. Py_FileSystemDefaultEncoding, &bufptr, &len))
  1967. return NULL;
  1968. if (len > 0) {
  1969. char ch = namebuf[len-1];
  1970. if (ch != SEP && ch != ALTSEP && ch != ':')
  1971. namebuf[len++] = '/';
  1972. strcpy(namebuf + len, "*.*");
  1973. }
  1974. if ((d = PyList_New(0)) == NULL)
  1975. return NULL;
  1976. Py_BEGIN_ALLOW_THREADS
  1977. hFindFile = FindFirstFile(namebuf, &FileData);
  1978. Py_END_ALLOW_THREADS
  1979. if (hFindFile == INVALID_HANDLE_VALUE) {
  1980. int error = GetLastError();
  1981. if (error == ERROR_FILE_NOT_FOUND)
  1982. return d;
  1983. Py_DECREF(d);
  1984. return win32_error("FindFirstFile", namebuf);
  1985. }
  1986. do {
  1987. /* Skip over . and .. */
  1988. if (strcmp(FileData.cFileName, ".") != 0 &&
  1989. strcmp(FileData.cFileName, "..") != 0) {
  1990. v = PyString_FromString(FileData.cFileName);
  1991. if (v == NULL) {
  1992. Py_DECREF(d);
  1993. d = NULL;
  1994. break;
  1995. }
  1996. if (PyList_Append(d, v) != 0) {
  1997. Py_DECREF(v);
  1998. Py_DECREF(d);
  1999. d = NULL;
  2000. break;
  2001. }
  2002. Py_DECREF(v);
  2003. }
  2004. Py_BEGIN_ALLOW_THREADS
  2005. result = FindNextFile(hFindFile, &FileData);
  2006. Py_END_ALLOW_THREADS
  2007. /* FindNextFile sets error to ERROR_NO_MORE_FILES if
  2008. it got to the end of the directory. */
  2009. if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
  2010. Py_DECREF(d);
  2011. win32_error("FindNextFile", namebuf);
  2012. FindClose(hFindFile);
  2013. return NULL;
  2014. }
  2015. } while (result == TRUE);
  2016. if (FindClose(hFindFile) == FALSE) {
  2017. Py_DECREF(d);
  2018. return win32_error("FindClose", namebuf);
  2019. }
  2020. return d;
  2021. #elif defined(PYOS_OS2)
  2022. #ifndef MAX_PATH
  2023. #define MAX_PATH CCHMAXPATH
  2024. #endif
  2025. char *name, *pt;
  2026. Py_ssize_t len;
  2027. PyObject *d, *v;
  2028. char namebuf[MAX_PATH+5];
  2029. HDIR hdir = 1;
  2030. ULONG srchcnt = 1;
  2031. FILEFINDBUF3 ep;
  2032. APIRET rc;
  2033. if (!PyArg_ParseTuple(args, "t#:listdir", &name, &len))
  2034. return NULL;
  2035. if (len >= MAX_PATH) {
  2036. PyErr_SetString(PyExc_ValueError, "path too long");
  2037. return NULL;
  2038. }
  2039. strcpy(namebuf, name);
  2040. for (pt = namebuf; *pt; pt++)
  2041. if (*pt == ALTSEP)
  2042. *pt = SEP;
  2043. if (namebuf[len-1] != SEP)
  2044. namebuf[len++] = SEP;
  2045. strcpy(namebuf + len, "*.*");
  2046. if ((d = PyList_New(0)) == NULL)
  2047. return NULL;
  2048. rc = DosFindFirst(namebuf, /* Wildcard Pattern to Match */
  2049. &hdir, /* Handle to Use While Search Directory */
  2050. FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
  2051. &ep, sizeof(ep), /* Structure to Receive Directory Entry */
  2052. &srchcnt, /* Max and Actual Count of Entries Per Iteration */
  2053. FIL_STANDARD); /* Format of Entry (EAs or Not) */
  2054. if (rc != NO_ERROR) {
  2055. errno = ENOENT;
  2056. return posix_error_with_filename(name);
  2057. }
  2058. if (srchcnt > 0) { /* If Directory is NOT Totally Empty, */
  2059. do {
  2060. if (ep.achName[0] == '.'
  2061. && (ep.achName[1] == '\0' || (ep.achName[1] == '.' && ep.achName[2] == '\0')))
  2062. continue; /* Skip Over "." and ".." Names */
  2063. strcpy(namebuf, ep.achName);
  2064. /* Leave Case of Name Alone -- In Native Form */
  2065. /* (Removed Forced Lowercasing Code) */
  2066. v = PyString_FromString(namebuf);
  2067. if (v == NULL) {
  2068. Py_DECREF(d);
  2069. d = NULL;
  2070. break;
  2071. }
  2072. if (PyList_Append(d, v) != 0) {
  2073. Py_DECREF(v);
  2074. Py_DECREF(d);
  2075. d = NULL;
  2076. break;
  2077. }
  2078. Py_DECREF(v);
  2079. } while (DosFindNext(hdir, &ep, sizeof(ep), &srchcnt) == NO_ERROR && srchcnt > 0);
  2080. }
  2081. return d;
  2082. #else
  2083. char *name = NULL;
  2084. PyObject *d, *v;
  2085. DIR *dirp;
  2086. struct dirent *ep;
  2087. int arg_is_unicode = 1;
  2088. errno = 0;
  2089. if (!PyArg_ParseTuple(args, "U:listdir", &v)) {
  2090. arg_is_unicode = 0;
  2091. PyErr_Clear();
  2092. }
  2093. if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name))
  2094. return NULL;
  2095. Py_BEGIN_ALLOW_THREADS
  2096. dirp = opendir(name);
  2097. Py_END_ALLOW_THREADS
  2098. if (dirp == NULL) {
  2099. return posix_error_with_allocated_filename(name);
  2100. }
  2101. if ((d = PyList_New(0)) == NULL) {
  2102. Py_BEGIN_ALLOW_THREADS
  2103. closedir(dirp);
  2104. Py_END_ALLOW_THREADS
  2105. PyMem_Free(name);
  2106. return NULL;
  2107. }
  2108. for (;;) {
  2109. errno = 0;
  2110. Py_BEGIN_ALLOW_THREADS
  2111. ep = readdir(dirp);
  2112. Py_END_ALLOW_THREADS
  2113. if (ep == NULL) {
  2114. if (errno == 0) {
  2115. break;
  2116. } else {
  2117. Py_BEGIN_ALLOW_THREADS
  2118. closedir(dirp);
  2119. Py_END_ALLOW_THREADS
  2120. Py_DECREF(d);
  2121. return posix_error_with_allocated_filename(name);
  2122. }
  2123. }
  2124. if (ep->d_name[0] == '.' &&
  2125. (NAMLEN(ep) == 1 ||
  2126. (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
  2127. continue;
  2128. v = PyString_FromStringAndSize(ep->d_name, NAMLEN(ep));
  2129. if (v == NULL) {
  2130. Py_DECREF(d);
  2131. d = NULL;
  2132. break;
  2133. }
  2134. #ifdef Py_USING_UNICODE
  2135. if (arg_is_unicode) {
  2136. PyObject *w;
  2137. w = PyUnicode_FromEncodedObject(v,
  2138. Py_FileSystemDefaultEncoding,
  2139. "strict");
  2140. if (w != NULL) {
  2141. Py_DECREF(v);
  2142. v = w;
  2143. }
  2144. else {
  2145. /* fall back to the original byte string, as
  2146. discussed in patch #683592 */
  2147. PyErr_Clear();
  2148. }
  2149. }
  2150. #endif
  2151. if (PyList_Append(d, v) != 0) {
  2152. Py_DECREF(v);
  2153. Py_DECREF(d);
  2154. d = NULL;
  2155. break;
  2156. }
  2157. Py_DECREF(v);
  2158. }
  2159. Py_BEGIN_ALLOW_THREADS
  2160. closedir(dirp);
  2161. Py_END_ALLOW_THREADS
  2162. PyMem_Free(name);
  2163. return d;
  2164. #endif /* which OS */
  2165. } /* end of posix_listdir */
  2166. #ifdef MS_WINDOWS
  2167. /* A helper function for abspath on win32 */
  2168. static PyObject *
  2169. posix__getfullpathname(PyObject *self, PyObject *args)
  2170. {
  2171. /* assume encoded strings won't more than double no of chars */
  2172. char inbuf[MAX_PATH*2];
  2173. char *inbufp = inbuf;
  2174. Py_ssize_t insize = sizeof(inbuf);
  2175. char outbuf[MAX_PATH*2];
  2176. char *temp;
  2177. PyUnicodeObject *po;
  2178. if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) {
  2179. Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);
  2180. Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf;
  2181. Py_UNICODE *wtemp;
  2182. DWORD result;
  2183. PyObject *v;
  2184. result = GetFullPathNameW(wpath,
  2185. sizeof(woutbuf)/sizeof(woutbuf[0]),
  2186. woutbuf, &wtemp);
  2187. if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) {
  2188. woutbufp = malloc(result * sizeof(Py_UNICODE));
  2189. if (!woutbufp)
  2190. return PyErr_NoMemory();
  2191. result = GetFullPathNameW(wpath, result, woutbufp, &wtemp);
  2192. }
  2193. if (result)
  2194. v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp));
  2195. else
  2196. v = win32_error_unicode("GetFullPathNameW", wpath);
  2197. if (woutbufp != woutbuf)
  2198. free(woutbufp);
  2199. return v;
  2200. }
  2201. /* Drop the argument parsing error as narrow strings
  2202. are also valid. */
  2203. PyErr_Clear();
  2204. if (!PyArg_ParseTuple (args, "et#:_getfullpathname",
  2205. Py_FileSystemDefaultEncoding, &inbufp,
  2206. &insize))
  2207. return NULL;
  2208. if (!GetFullPathName(inbuf, sizeof(outbuf)/sizeof(outbuf[0]),
  2209. outbuf, &temp))
  2210. return win32_error("GetFullPathName", inbuf);
  2211. if (PyUnicode_Check(PyTuple_GetItem(args, 0))) {
  2212. return PyUnicode_Decode(outbuf, strlen(outbuf),
  2213. Py_FileSystemDefaultEncoding, NULL);
  2214. }
  2215. return PyString_FromString(outbuf);
  2216. } /* end of posix__getfullpathname */
  2217. #endif /* MS_WINDOWS */
  2218. PyDoc_STRVAR(posix_mkdir__doc__,
  2219. "mkdir(path [, mode=0777])\n\n\
  2220. Create a directory.");
  2221. static PyObject *
  2222. posix_mkdir(PyObject *self, PyObject *args)
  2223. {
  2224. int res;
  2225. char *path = NULL;
  2226. int mode = 0777;
  2227. #ifdef MS_WINDOWS
  2228. PyUnicodeObject *po;
  2229. if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) {
  2230. Py_BEGIN_ALLOW_THREADS
  2231. /* PyUnicode_AS_UNICODE OK without thread lock as
  2232. it is a simple dereference. */
  2233. res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL);
  2234. Py_END_ALLOW_THREADS
  2235. if (!res)
  2236. return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po));
  2237. Py_INCREF(Py_None);
  2238. return Py_None;
  2239. }
  2240. /* Drop the argument parsing error as narrow strings
  2241. are also valid. */
  2242. PyErr_Clear();
  2243. if (!PyArg_ParseTuple(args, "et|i:mkdir",
  2244. Py_FileSystemDefaultEncoding, &path, &mode))
  2245. return NULL;
  2246. Py_BEGIN_ALLOW_THREADS
  2247. /* PyUnicode_AS_UNICODE OK without thread lock as
  2248. it is a simple dereference. */
  2249. res = CreateDirectoryA(path, NULL);
  2250. Py_END_ALLOW_THREADS
  2251. if (!res) {
  2252. win32_error("mkdir", path);
  2253. PyMem_Free(path);
  2254. return NULL;
  2255. }
  2256. PyMem_Free(path);
  2257. Py_INCREF(Py_None);
  2258. return Py_None;
  2259. #else /* MS_WINDOWS */
  2260. if (!PyArg_ParseTuple(args, "et|i:mkdir",
  2261. Py_FileSystemDefaultEncoding, &path, &mode))
  2262. return NULL;
  2263. Py_BEGIN_ALLOW_THREADS
  2264. #if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__)
  2265. res = mkdir(path);
  2266. #else
  2267. res = mkdir(path, mode);
  2268. #endif
  2269. Py_END_ALLOW_THREADS
  2270. if (res < 0)
  2271. return posix_error_with_allocated_filename(path);
  2272. PyMem_Free(path);
  2273. Py_INCREF(Py_None);
  2274. return Py_None;
  2275. #endif /* MS_WINDOWS */
  2276. }
  2277. /* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
  2278. #if defined(HAVE_SYS_RESOURCE_H)
  2279. #include <sys/resource.h>
  2280. #endif
  2281. #ifdef HAVE_NICE
  2282. PyDoc_STRVAR(posix_nice__doc__,
  2283. "nice(inc) -> new_priority\n\n\
  2284. Decrease the priority of process by inc and return the new priority.");
  2285. static PyObject *
  2286. posix_nice(PyObject *self, PyObject *args)
  2287. {
  2288. int increment, value;
  2289. if (!PyArg_ParseTuple(args, "i:nice", &increment))
  2290. return NULL;
  2291. /* There are two flavours of 'nice': one that returns the new
  2292. priority (as required by almost all standards out there) and the
  2293. Linux/FreeBSD/BSDI one, which returns '0' on success and advices
  2294. the use of getpriority() to get the new priority.
  2295. If we are of the nice family that returns the new priority, we
  2296. need to clear errno before the call, and check if errno is filled
  2297. before calling posix_error() on a returnvalue of -1, because the
  2298. -1 may be the actual new priority! */
  2299. errno = 0;
  2300. value = nice(increment);
  2301. #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
  2302. if (value == 0)
  2303. value = getpriority(PRIO_PROCESS, 0);
  2304. #endif
  2305. if (value == -1 && errno != 0)
  2306. /* either nice() or getpriority() returned an error */
  2307. return posix_error();
  2308. return PyInt_FromLong((long) value);
  2309. }
  2310. #endif /* HAVE_NICE */
  2311. PyDoc_STRVAR(posix_rename__doc__,
  2312. "rename(old, new)\n\n\
  2313. Rename a file or directory.");
  2314. static PyObject *
  2315. posix_rename(PyObject *self, PyObject *args)
  2316. {
  2317. #ifdef MS_WINDOWS
  2318. PyObject *o1, *o2;
  2319. char *p1, *p2;
  2320. BOOL result;
  2321. if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2))
  2322. goto error;
  2323. if (!convert_to_unicode(&o1))
  2324. goto error;
  2325. if (!convert_to_unicode(&o2)) {
  2326. Py_DECREF(o1);
  2327. goto error;
  2328. }
  2329. Py_BEGIN_ALLOW_THREADS
  2330. result = MoveFileW(PyUnicode_AsUnicode(o1),
  2331. PyUnicode_AsUnicode(o2));
  2332. Py_END_ALLOW_THREADS
  2333. Py_DECREF(o1);
  2334. Py_DECREF(o2);
  2335. if (!result)
  2336. return win32_error("rename", NULL);
  2337. Py_INCREF(Py_None);
  2338. return Py_None;
  2339. error:
  2340. PyErr_Clear();
  2341. if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2))
  2342. return NULL;
  2343. Py_BEGIN_ALLOW_THREADS
  2344. result = MoveFileA(p1, p2);
  2345. Py_END_ALLOW_THREADS
  2346. if (!result)
  2347. return win32_error("rename", NULL);
  2348. Py_INCREF(Py_None);
  2349. return Py_None;
  2350. #else
  2351. return posix_2str(args, "etet:rename", rename);
  2352. #endif
  2353. }
  2354. PyDoc_STRVAR(posix_rmdir__doc__,
  2355. "rmdir(path)\n\n\
  2356. Remove a directory.");
  2357. static PyObject *
  2358. posix_rmdir(PyObject *self, PyObject *args)
  2359. {
  2360. #ifdef MS_WINDOWS
  2361. return win32_1str(args, "rmdir", "s:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW);
  2362. #else
  2363. return posix_1str(args, "et:rmdir", rmdir);
  2364. #endif
  2365. }
  2366. PyDoc_STRVAR(posix_stat__doc__,
  2367. "stat(path) -> stat result\n\n\
  2368. Perform a stat system call on the given path.");
  2369. static PyObject *
  2370. posix_stat(PyObject *self, PyObject *args)
  2371. {
  2372. #ifdef MS_WINDOWS
  2373. return posix_do_stat(self, args, "et:stat", STAT, "U:stat", win32_wstat);
  2374. #else
  2375. return posix_do_stat(self, args, "et:stat", STAT, NULL, NULL);
  2376. #endif
  2377. }
  2378. #ifdef HAVE_SYSTEM
  2379. PyDoc_STRVAR(posix_system__doc__,
  2380. "system(command) -> exit_status\n\n\
  2381. Execute the command (a string) in a subshell.");
  2382. static PyObject *
  2383. posix_system(PyObject *self, PyObject *args)
  2384. {
  2385. char *command;
  2386. long sts;
  2387. if (!PyArg_ParseTuple(args, "s:system", &command))
  2388. return NULL;
  2389. Py_BEGIN_ALLOW_THREADS
  2390. sts = system(command);
  2391. Py_END_ALLOW_THREADS
  2392. return PyInt_FromLong(sts);
  2393. }
  2394. #endif
  2395. PyDoc_STRVAR(posix_umask__doc__,
  2396. "umask(new_mask) -> old_mask\n\n\
  2397. Set the current numeric umask and return the previous umask.");
  2398. static PyObject *
  2399. posix_umask(PyObject *self, PyObject *args)
  2400. {
  2401. int i;
  2402. if (!PyArg_ParseTuple(args, "i:umask", &i))
  2403. return NULL;
  2404. i = (int)umask(i);
  2405. if (i < 0)
  2406. return posix_error();
  2407. return PyInt_FromLong((long)i);
  2408. }
  2409. PyDoc_STRVAR(posix_unlink__doc__,
  2410. "unlink(path)\n\n\
  2411. Remove a file (same as remove(path)).");
  2412. PyDoc_STRVAR(posix_remove__doc__,
  2413. "remove(path)\n\n\
  2414. Remove a file (same as unlink(path)).");
  2415. static PyObject *
  2416. posix_unlink(PyObject *self, PyObject *args)
  2417. {
  2418. #ifdef MS_WINDOWS
  2419. return win32_1str(args, "remove", "s:remove", DeleteFileA, "U:remove", DeleteFileW);
  2420. #else
  2421. return posix_1str(args, "et:remove", unlink);
  2422. #endif
  2423. }
  2424. #ifdef HAVE_UNAME
  2425. PyDoc_STRVAR(posix_uname__doc__,
  2426. "uname() -> (sysname, nodename, release, version, machine)\n\n\
  2427. Return a tuple identifying the current operating system.");
  2428. static PyObject *
  2429. posix_uname(PyObject *self, PyObject *noargs)
  2430. {
  2431. struct utsname u;
  2432. int res;
  2433. Py_BEGIN_ALLOW_THREADS
  2434. res = uname(&u);
  2435. Py_END_ALLOW_THREADS
  2436. if (res < 0)
  2437. return posix_error();
  2438. return Py_BuildValue("(sssss)",
  2439. u.sysname,
  2440. u.nodename,
  2441. u.release,
  2442. u.version,
  2443. u.machine);
  2444. }
  2445. #endif /* HAVE_UNAME */
  2446. static int
  2447. extract_time(PyObject *t, long* sec, long* usec)
  2448. {
  2449. long intval;
  2450. if (PyFloat_Check(t)) {
  2451. double tval = PyFloat_AsDouble(t);
  2452. PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t);
  2453. if (!intobj)
  2454. return -1;
  2455. intval = PyInt_AsLong(intobj);
  2456. Py_DECREF(intobj);
  2457. if (intval == -1 && PyErr_Occurred())
  2458. return -1;
  2459. *sec = intval;
  2460. *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */
  2461. if (*usec < 0)
  2462. /* If rounding gave us a negative number,
  2463. truncate. */
  2464. *usec = 0;
  2465. return 0;
  2466. }
  2467. intval = PyInt_AsLong(t);
  2468. if (intval == -1 && PyErr_Occurred())
  2469. return -1;
  2470. *sec = intval;
  2471. *usec = 0;
  2472. return 0;
  2473. }
  2474. PyDoc_STRVAR(posix_utime__doc__,
  2475. "utime(path, (atime, mtime))\n\
  2476. utime(path, None)\n\n\
  2477. Set the access and modified time of the file to the given values. If the\n\
  2478. second form is used, set the access and modified times to the current time.");
  2479. static PyObject *
  2480. posix_utime(PyObject *self, PyObject *args)
  2481. {
  2482. #ifdef MS_WINDOWS
  2483. PyObject *arg;
  2484. PyUnicodeObject *obwpath;
  2485. wchar_t *wpath = NULL;
  2486. char *apath = NULL;
  2487. HANDLE hFile;
  2488. long atimesec, mtimesec, ausec, musec;
  2489. FILETIME atime, mtime;
  2490. PyObject *result = NULL;
  2491. if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) {
  2492. wpath = PyUnicode_AS_UNICODE(obwpath);
  2493. Py_BEGIN_ALLOW_THREADS
  2494. hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0,
  2495. NULL, OPEN_EXISTING,
  2496. FILE_FLAG_BACKUP_SEMANTICS, NULL);
  2497. Py_END_ALLOW_THREADS
  2498. if (hFile == INVALID_HANDLE_VALUE)
  2499. return win32_error_unicode("utime", wpath);
  2500. } else
  2501. /* Drop the argument parsing error as narrow strings
  2502. are also valid. */
  2503. PyErr_Clear();
  2504. if (!wpath) {
  2505. if (!PyArg_ParseTuple(args, "etO:utime",
  2506. Py_FileSystemDefaultEncoding, &apath, &arg))
  2507. return NULL;
  2508. Py_BEGIN_ALLOW_THREADS
  2509. hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0,
  2510. NULL, OPEN_EXISTING,
  2511. FILE_FLAG_BACKUP_SEMANTICS, NULL);
  2512. Py_END_ALLOW_THREADS
  2513. if (hFile == INVALID_HANDLE_VALUE) {
  2514. win32_error("utime", apath);
  2515. PyMem_Free(apath);
  2516. return NULL;
  2517. }
  2518. PyMem_Free(apath);
  2519. }
  2520. if (arg == Py_None) {
  2521. SYSTEMTIME now;
  2522. GetSystemTime(&now);
  2523. if (!SystemTimeToFileTime(&now, &mtime) ||
  2524. !SystemTimeToFileTime(&now, &atime)) {
  2525. win32_error("utime", NULL);
  2526. goto done;
  2527. }
  2528. }
  2529. else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) {
  2530. PyErr_SetString(PyExc_TypeError,
  2531. "utime() arg 2 must be a tuple (atime, mtime)");
  2532. goto done;
  2533. }
  2534. else {
  2535. if (extract_time(PyTuple_GET_ITEM(arg, 0),
  2536. &atimesec, &ausec) == -1)
  2537. goto done;
  2538. time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime);
  2539. if (extract_time(PyTuple_GET_ITEM(arg, 1),
  2540. &mtimesec, &musec) == -1)
  2541. goto done;
  2542. time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime);
  2543. }
  2544. if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
  2545. /* Avoid putting the file name into the error here,
  2546. as that may confuse the user into believing that
  2547. something is wrong with the file, when it also
  2548. could be the time stamp that gives a problem. */
  2549. win32_error("utime", NULL);
  2550. }
  2551. Py_INCREF(Py_None);
  2552. result = Py_None;
  2553. done:
  2554. CloseHandle(hFile);
  2555. return result;
  2556. #else /* MS_WINDOWS */
  2557. char *path = NULL;
  2558. long atime, mtime, ausec, musec;
  2559. int res;
  2560. PyObject* arg;
  2561. #if defined(HAVE_UTIMES)
  2562. struct timeval buf[2];
  2563. #define ATIME buf[0].tv_sec
  2564. #define MTIME buf[1].tv_sec
  2565. #elif defined(HAVE_UTIME_H)
  2566. /* XXX should define struct utimbuf instead, above */
  2567. struct utimbuf buf;
  2568. #define ATIME buf.actime
  2569. #define MTIME buf.modtime
  2570. #define UTIME_ARG &buf
  2571. #else /* HAVE_UTIMES */
  2572. time_t buf[2];
  2573. #define ATIME buf[0]
  2574. #define MTIME buf[1]
  2575. #define UTIME_ARG buf
  2576. #endif /* HAVE_UTIMES */
  2577. if (!PyArg_ParseTuple(args, "etO:utime",
  2578. Py_FileSystemDefaultEncoding, &path, &arg))
  2579. return NULL;
  2580. if (arg == Py_None) {
  2581. /* optional time values not given */
  2582. Py_BEGIN_ALLOW_THREADS
  2583. res = utime(path, NULL);
  2584. Py_END_ALLOW_THREADS
  2585. }
  2586. else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) {
  2587. PyErr_SetString(PyExc_TypeError,
  2588. "utime() arg 2 must be a tuple (atime, mtime)");
  2589. PyMem_Free(path);
  2590. return NULL;
  2591. }
  2592. else {
  2593. if (extract_time(PyTuple_GET_ITEM(arg, 0),
  2594. &atime, &ausec) == -1) {
  2595. PyMem_Free(path);
  2596. return NULL;
  2597. }
  2598. if (extract_time(PyTuple_GET_ITEM(arg, 1),
  2599. &mtime, &musec) == -1) {
  2600. PyMem_Free(path);
  2601. return NULL;
  2602. }
  2603. ATIME = atime;
  2604. MTIME = mtime;
  2605. #ifdef HAVE_UTIMES
  2606. buf[0].tv_usec = ausec;
  2607. buf[1].tv_usec = musec;
  2608. Py_BEGIN_ALLOW_THREADS
  2609. res = utimes(path, buf);
  2610. Py_END_ALLOW_THREADS
  2611. #else
  2612. Py_BEGIN_ALLOW_THREADS
  2613. res = utime(path, UTIME_ARG);
  2614. Py_END_ALLOW_THREADS
  2615. #endif /* HAVE_UTIMES */
  2616. }
  2617. if (res < 0) {
  2618. return posix_error_with_allocated_filename(path);
  2619. }
  2620. PyMem_Free(path);
  2621. Py_INCREF(Py_None);
  2622. return Py_None;
  2623. #undef UTIME_ARG
  2624. #undef ATIME
  2625. #undef MTIME
  2626. #endif /* MS_WINDOWS */
  2627. }
  2628. /* Process operations */
  2629. PyDoc_STRVAR(posix__exit__doc__,
  2630. "_exit(status)\n\n\
  2631. Exit to the system with specified status, without normal exit processing.");
  2632. static PyObject *
  2633. posix__exit(PyObject *self, PyObject *args)
  2634. {
  2635. int sts;
  2636. if (!PyArg_ParseTuple(args, "i:_exit", &sts))
  2637. return NULL;
  2638. _exit(sts);
  2639. return NULL; /* Make gcc -Wall happy */
  2640. }
  2641. #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV)
  2642. static void
  2643. free_string_array(char **array, Py_ssize_t count)
  2644. {
  2645. Py_ssize_t i;
  2646. for (i = 0; i < count; i++)
  2647. PyMem_Free(array[i]);
  2648. PyMem_DEL(array);
  2649. }
  2650. #endif
  2651. #ifdef HAVE_EXECV
  2652. PyDoc_STRVAR(posix_execv__doc__,
  2653. "execv(path, args)\n\n\
  2654. Execute an executable path with arguments, replacing current process.\n\
  2655. \n\
  2656. path: path of executable file\n\
  2657. args: tuple or list of strings");
  2658. static PyObject *
  2659. posix_execv(PyObject *self, PyObject *args)
  2660. {
  2661. char *path;
  2662. PyObject *argv;
  2663. char **argvlist;
  2664. Py_ssize_t i, argc;
  2665. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  2666. /* execv has two arguments: (path, argv), where
  2667. argv is a list or tuple of strings. */
  2668. if (!PyArg_ParseTuple(args, "etO:execv",
  2669. Py_FileSystemDefaultEncoding,
  2670. &path, &argv))
  2671. return NULL;
  2672. if (PyList_Check(argv)) {
  2673. argc = PyList_Size(argv);
  2674. getitem = PyList_GetItem;
  2675. }
  2676. else if (PyTuple_Check(argv)) {
  2677. argc = PyTuple_Size(argv);
  2678. getitem = PyTuple_GetItem;
  2679. }
  2680. else {
  2681. PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list");
  2682. PyMem_Free(path);
  2683. return NULL;
  2684. }
  2685. if (argc < 1) {
  2686. PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
  2687. PyMem_Free(path);
  2688. return NULL;
  2689. }
  2690. argvlist = PyMem_NEW(char *, argc+1);
  2691. if (argvlist == NULL) {
  2692. PyMem_Free(path);
  2693. return PyErr_NoMemory();
  2694. }
  2695. for (i = 0; i < argc; i++) {
  2696. if (!PyArg_Parse((*getitem)(argv, i), "et",
  2697. Py_FileSystemDefaultEncoding,
  2698. &argvlist[i])) {
  2699. free_string_array(argvlist, i);
  2700. PyErr_SetString(PyExc_TypeError,
  2701. "execv() arg 2 must contain only strings");
  2702. PyMem_Free(path);
  2703. return NULL;
  2704. }
  2705. }
  2706. argvlist[argc] = NULL;
  2707. execv(path, argvlist);
  2708. /* If we get here it's definitely an error */
  2709. free_string_array(argvlist, argc);
  2710. PyMem_Free(path);
  2711. return posix_error();
  2712. }
  2713. PyDoc_STRVAR(posix_execve__doc__,
  2714. "execve(path, args, env)\n\n\
  2715. Execute a path with arguments and environment, replacing current process.\n\
  2716. \n\
  2717. path: path of executable file\n\
  2718. args: tuple or list of arguments\n\
  2719. env: dictionary of strings mapping to strings");
  2720. static PyObject *
  2721. posix_execve(PyObject *self, PyObject *args)
  2722. {
  2723. char *path;
  2724. PyObject *argv, *env;
  2725. char **argvlist;
  2726. char **envlist;
  2727. PyObject *key, *val, *keys=NULL, *vals=NULL;
  2728. Py_ssize_t i, pos, argc, envc;
  2729. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  2730. Py_ssize_t lastarg = 0;
  2731. /* execve has three arguments: (path, argv, env), where
  2732. argv is a list or tuple of strings and env is a dictionary
  2733. like posix.environ. */
  2734. if (!PyArg_ParseTuple(args, "etOO:execve",
  2735. Py_FileSystemDefaultEncoding,
  2736. &path, &argv, &env))
  2737. return NULL;
  2738. if (PyList_Check(argv)) {
  2739. argc = PyList_Size(argv);
  2740. getitem = PyList_GetItem;
  2741. }
  2742. else if (PyTuple_Check(argv)) {
  2743. argc = PyTuple_Size(argv);
  2744. getitem = PyTuple_GetItem;
  2745. }
  2746. else {
  2747. PyErr_SetString(PyExc_TypeError,
  2748. "execve() arg 2 must be a tuple or list");
  2749. goto fail_0;
  2750. }
  2751. if (!PyMapping_Check(env)) {
  2752. PyErr_SetString(PyExc_TypeError,
  2753. "execve() arg 3 must be a mapping object");
  2754. goto fail_0;
  2755. }
  2756. argvlist = PyMem_NEW(char *, argc+1);
  2757. if (argvlist == NULL) {
  2758. PyErr_NoMemory();
  2759. goto fail_0;
  2760. }
  2761. for (i = 0; i < argc; i++) {
  2762. if (!PyArg_Parse((*getitem)(argv, i),
  2763. "et;execve() arg 2 must contain only strings",
  2764. Py_FileSystemDefaultEncoding,
  2765. &argvlist[i]))
  2766. {
  2767. lastarg = i;
  2768. goto fail_1;
  2769. }
  2770. }
  2771. lastarg = argc;
  2772. argvlist[argc] = NULL;
  2773. i = PyMapping_Size(env);
  2774. if (i < 0)
  2775. goto fail_1;
  2776. envlist = PyMem_NEW(char *, i + 1);
  2777. if (envlist == NULL) {
  2778. PyErr_NoMemory();
  2779. goto fail_1;
  2780. }
  2781. envc = 0;
  2782. keys = PyMapping_Keys(env);
  2783. vals = PyMapping_Values(env);
  2784. if (!keys || !vals)
  2785. goto fail_2;
  2786. if (!PyList_Check(keys) || !PyList_Check(vals)) {
  2787. PyErr_SetString(PyExc_TypeError,
  2788. "execve(): env.keys() or env.values() is not a list");
  2789. goto fail_2;
  2790. }
  2791. for (pos = 0; pos < i; pos++) {
  2792. char *p, *k, *v;
  2793. size_t len;
  2794. key = PyList_GetItem(keys, pos);
  2795. val = PyList_GetItem(vals, pos);
  2796. if (!key || !val)
  2797. goto fail_2;
  2798. if (!PyArg_Parse(
  2799. key,
  2800. "s;execve() arg 3 contains a non-string key",
  2801. &k) ||
  2802. !PyArg_Parse(
  2803. val,
  2804. "s;execve() arg 3 contains a non-string value",
  2805. &v))
  2806. {
  2807. goto fail_2;
  2808. }
  2809. #if defined(PYOS_OS2)
  2810. /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */
  2811. if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) {
  2812. #endif
  2813. len = PyString_Size(key) + PyString_Size(val) + 2;
  2814. p = PyMem_NEW(char, len);
  2815. if (p == NULL) {
  2816. PyErr_NoMemory();
  2817. goto fail_2;
  2818. }
  2819. PyOS_snprintf(p, len, "%s=%s", k, v);
  2820. envlist[envc++] = p;
  2821. #if defined(PYOS_OS2)
  2822. }
  2823. #endif
  2824. }
  2825. envlist[envc] = 0;
  2826. execve(path, argvlist, envlist);
  2827. /* If we get here it's definitely an error */
  2828. (void) posix_error();
  2829. fail_2:
  2830. while (--envc >= 0)
  2831. PyMem_DEL(envlist[envc]);
  2832. PyMem_DEL(envlist);
  2833. fail_1:
  2834. free_string_array(argvlist, lastarg);
  2835. Py_XDECREF(vals);
  2836. Py_XDECREF(keys);
  2837. fail_0:
  2838. PyMem_Free(path);
  2839. return NULL;
  2840. }
  2841. #endif /* HAVE_EXECV */
  2842. #ifdef HAVE_SPAWNV
  2843. PyDoc_STRVAR(posix_spawnv__doc__,
  2844. "spawnv(mode, path, args)\n\n\
  2845. Execute the program 'path' in a new process.\n\
  2846. \n\
  2847. mode: mode of process creation\n\
  2848. path: path of executable file\n\
  2849. args: tuple or list of strings");
  2850. static PyObject *
  2851. posix_spawnv(PyObject *self, PyObject *args)
  2852. {
  2853. char *path;
  2854. PyObject *argv;
  2855. char **argvlist;
  2856. int mode, i;
  2857. Py_ssize_t argc;
  2858. Py_intptr_t spawnval;
  2859. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  2860. /* spawnv has three arguments: (mode, path, argv), where
  2861. argv is a list or tuple of strings. */
  2862. if (!PyArg_ParseTuple(args, "ietO:spawnv", &mode,
  2863. Py_FileSystemDefaultEncoding,
  2864. &path, &argv))
  2865. return NULL;
  2866. if (PyList_Check(argv)) {
  2867. argc = PyList_Size(argv);
  2868. getitem = PyList_GetItem;
  2869. }
  2870. else if (PyTuple_Check(argv)) {
  2871. argc = PyTuple_Size(argv);
  2872. getitem = PyTuple_GetItem;
  2873. }
  2874. else {
  2875. PyErr_SetString(PyExc_TypeError,
  2876. "spawnv() arg 2 must be a tuple or list");
  2877. PyMem_Free(path);
  2878. return NULL;
  2879. }
  2880. argvlist = PyMem_NEW(char *, argc+1);
  2881. if (argvlist == NULL) {
  2882. PyMem_Free(path);
  2883. return PyErr_NoMemory();
  2884. }
  2885. for (i = 0; i < argc; i++) {
  2886. if (!PyArg_Parse((*getitem)(argv, i), "et",
  2887. Py_FileSystemDefaultEncoding,
  2888. &argvlist[i])) {
  2889. free_string_array(argvlist, i);
  2890. PyErr_SetString(
  2891. PyExc_TypeError,
  2892. "spawnv() arg 2 must contain only strings");
  2893. PyMem_Free(path);
  2894. return NULL;
  2895. }
  2896. }
  2897. argvlist[argc] = NULL;
  2898. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  2899. Py_BEGIN_ALLOW_THREADS
  2900. spawnval = spawnv(mode, path, argvlist);
  2901. Py_END_ALLOW_THREADS
  2902. #else
  2903. if (mode == _OLD_P_OVERLAY)
  2904. mode = _P_OVERLAY;
  2905. Py_BEGIN_ALLOW_THREADS
  2906. spawnval = _spawnv(mode, path, argvlist);
  2907. Py_END_ALLOW_THREADS
  2908. #endif
  2909. free_string_array(argvlist, argc);
  2910. PyMem_Free(path);
  2911. if (spawnval == -1)
  2912. return posix_error();
  2913. else
  2914. #if SIZEOF_LONG == SIZEOF_VOID_P
  2915. return Py_BuildValue("l", (long) spawnval);
  2916. #else
  2917. return Py_BuildValue("L", (PY_LONG_LONG) spawnval);
  2918. #endif
  2919. }
  2920. PyDoc_STRVAR(posix_spawnve__doc__,
  2921. "spawnve(mode, path, args, env)\n\n\
  2922. Execute the program 'path' in a new process.\n\
  2923. \n\
  2924. mode: mode of process creation\n\
  2925. path: path of executable file\n\
  2926. args: tuple or list of arguments\n\
  2927. env: dictionary of strings mapping to strings");
  2928. static PyObject *
  2929. posix_spawnve(PyObject *self, PyObject *args)
  2930. {
  2931. char *path;
  2932. PyObject *argv, *env;
  2933. char **argvlist;
  2934. char **envlist;
  2935. PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL;
  2936. int mode, pos, envc;
  2937. Py_ssize_t argc, i;
  2938. Py_intptr_t spawnval;
  2939. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  2940. Py_ssize_t lastarg = 0;
  2941. /* spawnve has four arguments: (mode, path, argv, env), where
  2942. argv is a list or tuple of strings and env is a dictionary
  2943. like posix.environ. */
  2944. if (!PyArg_ParseTuple(args, "ietOO:spawnve", &mode,
  2945. Py_FileSystemDefaultEncoding,
  2946. &path, &argv, &env))
  2947. return NULL;
  2948. if (PyList_Check(argv)) {
  2949. argc = PyList_Size(argv);
  2950. getitem = PyList_GetItem;
  2951. }
  2952. else if (PyTuple_Check(argv)) {
  2953. argc = PyTuple_Size(argv);
  2954. getitem = PyTuple_GetItem;
  2955. }
  2956. else {
  2957. PyErr_SetString(PyExc_TypeError,
  2958. "spawnve() arg 2 must be a tuple or list");
  2959. goto fail_0;
  2960. }
  2961. if (!PyMapping_Check(env)) {
  2962. PyErr_SetString(PyExc_TypeError,
  2963. "spawnve() arg 3 must be a mapping object");
  2964. goto fail_0;
  2965. }
  2966. argvlist = PyMem_NEW(char *, argc+1);
  2967. if (argvlist == NULL) {
  2968. PyErr_NoMemory();
  2969. goto fail_0;
  2970. }
  2971. for (i = 0; i < argc; i++) {
  2972. if (!PyArg_Parse((*getitem)(argv, i),
  2973. "et;spawnve() arg 2 must contain only strings",
  2974. Py_FileSystemDefaultEncoding,
  2975. &argvlist[i]))
  2976. {
  2977. lastarg = i;
  2978. goto fail_1;
  2979. }
  2980. }
  2981. lastarg = argc;
  2982. argvlist[argc] = NULL;
  2983. i = PyMapping_Size(env);
  2984. if (i < 0)
  2985. goto fail_1;
  2986. envlist = PyMem_NEW(char *, i + 1);
  2987. if (envlist == NULL) {
  2988. PyErr_NoMemory();
  2989. goto fail_1;
  2990. }
  2991. envc = 0;
  2992. keys = PyMapping_Keys(env);
  2993. vals = PyMapping_Values(env);
  2994. if (!keys || !vals)
  2995. goto fail_2;
  2996. if (!PyList_Check(keys) || !PyList_Check(vals)) {
  2997. PyErr_SetString(PyExc_TypeError,
  2998. "spawnve(): env.keys() or env.values() is not a list");
  2999. goto fail_2;
  3000. }
  3001. for (pos = 0; pos < i; pos++) {
  3002. char *p, *k, *v;
  3003. size_t len;
  3004. key = PyList_GetItem(keys, pos);
  3005. val = PyList_GetItem(vals, pos);
  3006. if (!key || !val)
  3007. goto fail_2;
  3008. if (!PyArg_Parse(
  3009. key,
  3010. "s;spawnve() arg 3 contains a non-string key",
  3011. &k) ||
  3012. !PyArg_Parse(
  3013. val,
  3014. "s;spawnve() arg 3 contains a non-string value",
  3015. &v))
  3016. {
  3017. goto fail_2;
  3018. }
  3019. len = PyString_Size(key) + PyString_Size(val) + 2;
  3020. p = PyMem_NEW(char, len);
  3021. if (p == NULL) {
  3022. PyErr_NoMemory();
  3023. goto fail_2;
  3024. }
  3025. PyOS_snprintf(p, len, "%s=%s", k, v);
  3026. envlist[envc++] = p;
  3027. }
  3028. envlist[envc] = 0;
  3029. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  3030. Py_BEGIN_ALLOW_THREADS
  3031. spawnval = spawnve(mode, path, argvlist, envlist);
  3032. Py_END_ALLOW_THREADS
  3033. #else
  3034. if (mode == _OLD_P_OVERLAY)
  3035. mode = _P_OVERLAY;
  3036. Py_BEGIN_ALLOW_THREADS
  3037. spawnval = _spawnve(mode, path, argvlist, envlist);
  3038. Py_END_ALLOW_THREADS
  3039. #endif
  3040. if (spawnval == -1)
  3041. (void) posix_error();
  3042. else
  3043. #if SIZEOF_LONG == SIZEOF_VOID_P
  3044. res = Py_BuildValue("l", (long) spawnval);
  3045. #else
  3046. res = Py_BuildValue("L", (PY_LONG_LONG) spawnval);
  3047. #endif
  3048. fail_2:
  3049. while (--envc >= 0)
  3050. PyMem_DEL(envlist[envc]);
  3051. PyMem_DEL(envlist);
  3052. fail_1:
  3053. free_string_array(argvlist, lastarg);
  3054. Py_XDECREF(vals);
  3055. Py_XDECREF(keys);
  3056. fail_0:
  3057. PyMem_Free(path);
  3058. return res;
  3059. }
  3060. /* OS/2 supports spawnvp & spawnvpe natively */
  3061. #if defined(PYOS_OS2)
  3062. PyDoc_STRVAR(posix_spawnvp__doc__,
  3063. "spawnvp(mode, file, args)\n\n\
  3064. Execute the program 'file' in a new process, using the environment\n\
  3065. search path to find the file.\n\
  3066. \n\
  3067. mode: mode of process creation\n\
  3068. file: executable file name\n\
  3069. args: tuple or list of strings");
  3070. static PyObject *
  3071. posix_spawnvp(PyObject *self, PyObject *args)
  3072. {
  3073. char *path;
  3074. PyObject *argv;
  3075. char **argvlist;
  3076. int mode, i, argc;
  3077. Py_intptr_t spawnval;
  3078. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  3079. /* spawnvp has three arguments: (mode, path, argv), where
  3080. argv is a list or tuple of strings. */
  3081. if (!PyArg_ParseTuple(args, "ietO:spawnvp", &mode,
  3082. Py_FileSystemDefaultEncoding,
  3083. &path, &argv))
  3084. return NULL;
  3085. if (PyList_Check(argv)) {
  3086. argc = PyList_Size(argv);
  3087. getitem = PyList_GetItem;
  3088. }
  3089. else if (PyTuple_Check(argv)) {
  3090. argc = PyTuple_Size(argv);
  3091. getitem = PyTuple_GetItem;
  3092. }
  3093. else {
  3094. PyErr_SetString(PyExc_TypeError,
  3095. "spawnvp() arg 2 must be a tuple or list");
  3096. PyMem_Free(path);
  3097. return NULL;
  3098. }
  3099. argvlist = PyMem_NEW(char *, argc+1);
  3100. if (argvlist == NULL) {
  3101. PyMem_Free(path);
  3102. return PyErr_NoMemory();
  3103. }
  3104. for (i = 0; i < argc; i++) {
  3105. if (!PyArg_Parse((*getitem)(argv, i), "et",
  3106. Py_FileSystemDefaultEncoding,
  3107. &argvlist[i])) {
  3108. free_string_array(argvlist, i);
  3109. PyErr_SetString(
  3110. PyExc_TypeError,
  3111. "spawnvp() arg 2 must contain only strings");
  3112. PyMem_Free(path);
  3113. return NULL;
  3114. }
  3115. }
  3116. argvlist[argc] = NULL;
  3117. Py_BEGIN_ALLOW_THREADS
  3118. #if defined(PYCC_GCC)
  3119. spawnval = spawnvp(mode, path, argvlist);
  3120. #else
  3121. spawnval = _spawnvp(mode, path, argvlist);
  3122. #endif
  3123. Py_END_ALLOW_THREADS
  3124. free_string_array(argvlist, argc);
  3125. PyMem_Free(path);
  3126. if (spawnval == -1)
  3127. return posix_error();
  3128. else
  3129. return Py_BuildValue("l", (long) spawnval);
  3130. }
  3131. PyDoc_STRVAR(posix_spawnvpe__doc__,
  3132. "spawnvpe(mode, file, args, env)\n\n\
  3133. Execute the program 'file' in a new process, using the environment\n\
  3134. search path to find the file.\n\
  3135. \n\
  3136. mode: mode of process creation\n\
  3137. file: executable file name\n\
  3138. args: tuple or list of arguments\n\
  3139. env: dictionary of strings mapping to strings");
  3140. static PyObject *
  3141. posix_spawnvpe(PyObject *self, PyObject *args)
  3142. {
  3143. char *path;
  3144. PyObject *argv, *env;
  3145. char **argvlist;
  3146. char **envlist;
  3147. PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL;
  3148. int mode, i, pos, argc, envc;
  3149. Py_intptr_t spawnval;
  3150. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  3151. int lastarg = 0;
  3152. /* spawnvpe has four arguments: (mode, path, argv, env), where
  3153. argv is a list or tuple of strings and env is a dictionary
  3154. like posix.environ. */
  3155. if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode,
  3156. Py_FileSystemDefaultEncoding,
  3157. &path, &argv, &env))
  3158. return NULL;
  3159. if (PyList_Check(argv)) {
  3160. argc = PyList_Size(argv);
  3161. getitem = PyList_GetItem;
  3162. }
  3163. else if (PyTuple_Check(argv)) {
  3164. argc = PyTuple_Size(argv);
  3165. getitem = PyTuple_GetItem;
  3166. }
  3167. else {
  3168. PyErr_SetString(PyExc_TypeError,
  3169. "spawnvpe() arg 2 must be a tuple or list");
  3170. goto fail_0;
  3171. }
  3172. if (!PyMapping_Check(env)) {
  3173. PyErr_SetString(PyExc_TypeError,
  3174. "spawnvpe() arg 3 must be a mapping object");
  3175. goto fail_0;
  3176. }
  3177. argvlist = PyMem_NEW(char *, argc+1);
  3178. if (argvlist == NULL) {
  3179. PyErr_NoMemory();
  3180. goto fail_0;
  3181. }
  3182. for (i = 0; i < argc; i++) {
  3183. if (!PyArg_Parse((*getitem)(argv, i),
  3184. "et;spawnvpe() arg 2 must contain only strings",
  3185. Py_FileSystemDefaultEncoding,
  3186. &argvlist[i]))
  3187. {
  3188. lastarg = i;
  3189. goto fail_1;
  3190. }
  3191. }
  3192. lastarg = argc;
  3193. argvlist[argc] = NULL;
  3194. i = PyMapping_Size(env);
  3195. if (i < 0)
  3196. goto fail_1;
  3197. envlist = PyMem_NEW(char *, i + 1);
  3198. if (envlist == NULL) {
  3199. PyErr_NoMemory();
  3200. goto fail_1;
  3201. }
  3202. envc = 0;
  3203. keys = PyMapping_Keys(env);
  3204. vals = PyMapping_Values(env);
  3205. if (!keys || !vals)
  3206. goto fail_2;
  3207. if (!PyList_Check(keys) || !PyList_Check(vals)) {
  3208. PyErr_SetString(PyExc_TypeError,
  3209. "spawnvpe(): env.keys() or env.values() is not a list");
  3210. goto fail_2;
  3211. }
  3212. for (pos = 0; pos < i; pos++) {
  3213. char *p, *k, *v;
  3214. size_t len;
  3215. key = PyList_GetItem(keys, pos);
  3216. val = PyList_GetItem(vals, pos);
  3217. if (!key || !val)
  3218. goto fail_2;
  3219. if (!PyArg_Parse(
  3220. key,
  3221. "s;spawnvpe() arg 3 contains a non-string key",
  3222. &k) ||
  3223. !PyArg_Parse(
  3224. val,
  3225. "s;spawnvpe() arg 3 contains a non-string value",
  3226. &v))
  3227. {
  3228. goto fail_2;
  3229. }
  3230. len = PyString_Size(key) + PyString_Size(val) + 2;
  3231. p = PyMem_NEW(char, len);
  3232. if (p == NULL) {
  3233. PyErr_NoMemory();
  3234. goto fail_2;
  3235. }
  3236. PyOS_snprintf(p, len, "%s=%s", k, v);
  3237. envlist[envc++] = p;
  3238. }
  3239. envlist[envc] = 0;
  3240. Py_BEGIN_ALLOW_THREADS
  3241. #if defined(PYCC_GCC)
  3242. spawnval = spawnvpe(mode, path, argvlist, envlist);
  3243. #else
  3244. spawnval = _spawnvpe(mode, path, argvlist, envlist);
  3245. #endif
  3246. Py_END_ALLOW_THREADS
  3247. if (spawnval == -1)
  3248. (void) posix_error();
  3249. else
  3250. res = Py_BuildValue("l", (long) spawnval);
  3251. fail_2:
  3252. while (--envc >= 0)
  3253. PyMem_DEL(envlist[envc]);
  3254. PyMem_DEL(envlist);
  3255. fail_1:
  3256. free_string_array(argvlist, lastarg);
  3257. Py_XDECREF(vals);
  3258. Py_XDECREF(keys);
  3259. fail_0:
  3260. PyMem_Free(path);
  3261. return res;
  3262. }
  3263. #endif /* PYOS_OS2 */
  3264. #endif /* HAVE_SPAWNV */
  3265. #ifdef HAVE_FORK1
  3266. PyDoc_STRVAR(posix_fork1__doc__,
  3267. "fork1() -> pid\n\n\
  3268. Fork a child process with a single multiplexed (i.e., not bound) thread.\n\
  3269. \n\
  3270. Return 0 to child process and PID of child to parent process.");
  3271. static PyObject *
  3272. posix_fork1(PyObject *self, PyObject *noargs)
  3273. {
  3274. pid_t pid;
  3275. int result = 0;
  3276. _PyImport_AcquireLock();
  3277. pid = fork1();
  3278. if (pid == 0) {
  3279. /* child: this clobbers and resets the import lock. */
  3280. PyOS_AfterFork();
  3281. } else {
  3282. /* parent: release the import lock. */
  3283. result = _PyImport_ReleaseLock();
  3284. }
  3285. if (pid == -1)
  3286. return posix_error();
  3287. if (result < 0) {
  3288. /* Don't clobber the OSError if the fork failed. */
  3289. PyErr_SetString(PyExc_RuntimeError,
  3290. "not holding the import lock");
  3291. return NULL;
  3292. }
  3293. return PyLong_FromPid(pid);
  3294. }
  3295. #endif
  3296. #ifdef HAVE_FORK
  3297. PyDoc_STRVAR(posix_fork__doc__,
  3298. "fork() -> pid\n\n\
  3299. Fork a child process.\n\
  3300. Return 0 to child process and PID of child to parent process.");
  3301. static PyObject *
  3302. posix_fork(PyObject *self, PyObject *noargs)
  3303. {
  3304. pid_t pid;
  3305. int result = 0;
  3306. _PyImport_AcquireLock();
  3307. pid = fork();
  3308. if (pid == 0) {
  3309. /* child: this clobbers and resets the import lock. */
  3310. PyOS_AfterFork();
  3311. } else {
  3312. /* parent: release the import lock. */
  3313. result = _PyImport_ReleaseLock();
  3314. }
  3315. if (pid == -1)
  3316. return posix_error();
  3317. if (result < 0) {
  3318. /* Don't clobber the OSError if the fork failed. */
  3319. PyErr_SetString(PyExc_RuntimeError,
  3320. "not holding the import lock");
  3321. return NULL;
  3322. }
  3323. return PyLong_FromPid(pid);
  3324. }
  3325. #endif
  3326. /* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
  3327. /* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
  3328. #if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
  3329. #define DEV_PTY_FILE "/dev/ptc"
  3330. #define HAVE_DEV_PTMX
  3331. #else
  3332. #define DEV_PTY_FILE "/dev/ptmx"
  3333. #endif
  3334. #if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
  3335. #ifdef HAVE_PTY_H
  3336. #include <pty.h>
  3337. #else
  3338. #ifdef HAVE_LIBUTIL_H
  3339. #include <libutil.h>
  3340. #else
  3341. #ifdef HAVE_UTIL_H
  3342. #include <util.h>
  3343. #endif /* HAVE_UTIL_H */
  3344. #endif /* HAVE_LIBUTIL_H */
  3345. #endif /* HAVE_PTY_H */
  3346. #ifdef HAVE_STROPTS_H
  3347. #include <stropts.h>
  3348. #endif
  3349. #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX */
  3350. #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
  3351. PyDoc_STRVAR(posix_openpty__doc__,
  3352. "openpty() -> (master_fd, slave_fd)\n\n\
  3353. Open a pseudo-terminal, returning open fd's for both master and slave end.\n");
  3354. static PyObject *
  3355. posix_openpty(PyObject *self, PyObject *noargs)
  3356. {
  3357. int master_fd, slave_fd;
  3358. #ifndef HAVE_OPENPTY
  3359. char * slave_name;
  3360. #endif
  3361. #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
  3362. PyOS_sighandler_t sig_saved;
  3363. #ifdef sun
  3364. extern char *ptsname(int fildes);
  3365. #endif
  3366. #endif
  3367. #ifdef HAVE_OPENPTY
  3368. if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
  3369. return posix_error();
  3370. #elif defined(HAVE__GETPTY)
  3371. slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
  3372. if (slave_name == NULL)
  3373. return posix_error();
  3374. slave_fd = open(slave_name, O_RDWR);
  3375. if (slave_fd < 0)
  3376. return posix_error();
  3377. #else
  3378. master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
  3379. if (master_fd < 0)
  3380. return posix_error();
  3381. sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
  3382. /* change permission of slave */
  3383. if (grantpt(master_fd) < 0) {
  3384. PyOS_setsig(SIGCHLD, sig_saved);
  3385. return posix_error();
  3386. }
  3387. /* unlock slave */
  3388. if (unlockpt(master_fd) < 0) {
  3389. PyOS_setsig(SIGCHLD, sig_saved);
  3390. return posix_error();
  3391. }
  3392. PyOS_setsig(SIGCHLD, sig_saved);
  3393. slave_name = ptsname(master_fd); /* get name of slave */
  3394. if (slave_name == NULL)
  3395. return posix_error();
  3396. slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
  3397. if (slave_fd < 0)
  3398. return posix_error();
  3399. #endif /* HAVE_OPENPTY */
  3400. return Py_BuildValue("(ii)", master_fd, slave_fd);
  3401. }
  3402. #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
  3403. #ifdef HAVE_FORKPTY
  3404. PyDoc_STRVAR(posix_forkpty__doc__,
  3405. "forkpty() -> (pid, master_fd)\n\n\
  3406. Fork a new process with a new pseudo-terminal as controlling tty.\n\n\
  3407. Like fork(), return 0 as pid to child process, and PID of child to parent.\n\
  3408. To both, return fd of newly opened pseudo-terminal.\n");
  3409. static PyObject *
  3410. posix_forkpty(PyObject *self, PyObject *noargs)
  3411. {
  3412. int master_fd = -1, result = 0;
  3413. pid_t pid;
  3414. _PyImport_AcquireLock();
  3415. pid = forkpty(&master_fd, NULL, NULL, NULL);
  3416. if (pid == 0) {
  3417. /* child: this clobbers and resets the import lock. */
  3418. PyOS_AfterFork();
  3419. } else {
  3420. /* parent: release the import lock. */
  3421. result = _PyImport_ReleaseLock();
  3422. }
  3423. if (pid == -1)
  3424. return posix_error();
  3425. if (result < 0) {
  3426. /* Don't clobber the OSError if the fork failed. */
  3427. PyErr_SetString(PyExc_RuntimeError,
  3428. "not holding the import lock");
  3429. return NULL;
  3430. }
  3431. return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
  3432. }
  3433. #endif
  3434. #ifdef HAVE_GETEGID
  3435. PyDoc_STRVAR(posix_getegid__doc__,
  3436. "getegid() -> egid\n\n\
  3437. Return the current process's effective group id.");
  3438. static PyObject *
  3439. posix_getegid(PyObject *self, PyObject *noargs)
  3440. {
  3441. return PyInt_FromLong((long)getegid());
  3442. }
  3443. #endif
  3444. #ifdef HAVE_GETEUID
  3445. PyDoc_STRVAR(posix_geteuid__doc__,
  3446. "geteuid() -> euid\n\n\
  3447. Return the current process's effective user id.");
  3448. static PyObject *
  3449. posix_geteuid(PyObject *self, PyObject *noargs)
  3450. {
  3451. return PyInt_FromLong((long)geteuid());
  3452. }
  3453. #endif
  3454. #ifdef HAVE_GETGID
  3455. PyDoc_STRVAR(posix_getgid__doc__,
  3456. "getgid() -> gid\n\n\
  3457. Return the current process's group id.");
  3458. static PyObject *
  3459. posix_getgid(PyObject *self, PyObject *noargs)
  3460. {
  3461. return PyInt_FromLong((long)getgid());
  3462. }
  3463. #endif
  3464. PyDoc_STRVAR(posix_getpid__doc__,
  3465. "getpid() -> pid\n\n\
  3466. Return the current process id");
  3467. static PyObject *
  3468. posix_getpid(PyObject *self, PyObject *noargs)
  3469. {
  3470. return PyLong_FromPid(getpid());
  3471. }
  3472. #ifdef HAVE_GETGROUPS
  3473. PyDoc_STRVAR(posix_getgroups__doc__,
  3474. "getgroups() -> list of group IDs\n\n\
  3475. Return list of supplemental group IDs for the process.");
  3476. static PyObject *
  3477. posix_getgroups(PyObject *self, PyObject *noargs)
  3478. {
  3479. PyObject *result = NULL;
  3480. #ifdef NGROUPS_MAX
  3481. #define MAX_GROUPS NGROUPS_MAX
  3482. #else
  3483. /* defined to be 16 on Solaris7, so this should be a small number */
  3484. #define MAX_GROUPS 64
  3485. #endif
  3486. gid_t grouplist[MAX_GROUPS];
  3487. /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
  3488. * This is a helper variable to store the intermediate result when
  3489. * that happens.
  3490. *
  3491. * To keep the code readable the OSX behaviour is unconditional,
  3492. * according to the POSIX spec this should be safe on all unix-y
  3493. * systems.
  3494. */
  3495. gid_t* alt_grouplist = grouplist;
  3496. int n;
  3497. n = getgroups(MAX_GROUPS, grouplist);
  3498. if (n < 0) {
  3499. if (errno == EINVAL) {
  3500. n = getgroups(0, NULL);
  3501. if (n == -1) {
  3502. return posix_error();
  3503. }
  3504. if (n == 0) {
  3505. /* Avoid malloc(0) */
  3506. alt_grouplist = grouplist;
  3507. } else {
  3508. alt_grouplist = PyMem_Malloc(n * sizeof(gid_t));
  3509. if (alt_grouplist == NULL) {
  3510. errno = EINVAL;
  3511. return posix_error();
  3512. }
  3513. n = getgroups(n, alt_grouplist);
  3514. if (n == -1) {
  3515. PyMem_Free(alt_grouplist);
  3516. return posix_error();
  3517. }
  3518. }
  3519. } else {
  3520. return posix_error();
  3521. }
  3522. }
  3523. result = PyList_New(n);
  3524. if (result != NULL) {
  3525. int i;
  3526. for (i = 0; i < n; ++i) {
  3527. PyObject *o = PyInt_FromLong((long)alt_grouplist[i]);
  3528. if (o == NULL) {
  3529. Py_DECREF(result);
  3530. result = NULL;
  3531. break;
  3532. }
  3533. PyList_SET_ITEM(result, i, o);
  3534. }
  3535. }
  3536. if (alt_grouplist != grouplist) {
  3537. PyMem_Free(alt_grouplist);
  3538. }
  3539. return result;
  3540. }
  3541. #endif
  3542. #ifdef HAVE_INITGROUPS
  3543. PyDoc_STRVAR(posix_initgroups__doc__,
  3544. "initgroups(username, gid) -> None\n\n\
  3545. Call the system initgroups() to initialize the group access list with all of\n\
  3546. the groups of which the specified username is a member, plus the specified\n\
  3547. group id.");
  3548. static PyObject *
  3549. posix_initgroups(PyObject *self, PyObject *args)
  3550. {
  3551. char *username;
  3552. long gid;
  3553. if (!PyArg_ParseTuple(args, "sl:initgroups", &username, &gid))
  3554. return NULL;
  3555. if (initgroups(username, (gid_t) gid) == -1)
  3556. return PyErr_SetFromErrno(PyExc_OSError);
  3557. Py_INCREF(Py_None);
  3558. return Py_None;
  3559. }
  3560. #endif
  3561. #ifdef HAVE_GETPGID
  3562. PyDoc_STRVAR(posix_getpgid__doc__,
  3563. "getpgid(pid) -> pgid\n\n\
  3564. Call the system call getpgid().");
  3565. static PyObject *
  3566. posix_getpgid(PyObject *self, PyObject *args)
  3567. {
  3568. pid_t pid, pgid;
  3569. if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid))
  3570. return NULL;
  3571. pgid = getpgid(pid);
  3572. if (pgid < 0)
  3573. return posix_error();
  3574. return PyLong_FromPid(pgid);
  3575. }
  3576. #endif /* HAVE_GETPGID */
  3577. #ifdef HAVE_GETPGRP
  3578. PyDoc_STRVAR(posix_getpgrp__doc__,
  3579. "getpgrp() -> pgrp\n\n\
  3580. Return the current process group id.");
  3581. static PyObject *
  3582. posix_getpgrp(PyObject *self, PyObject *noargs)
  3583. {
  3584. #ifdef GETPGRP_HAVE_ARG
  3585. return PyLong_FromPid(getpgrp(0));
  3586. #else /* GETPGRP_HAVE_ARG */
  3587. return PyLong_FromPid(getpgrp());
  3588. #endif /* GETPGRP_HAVE_ARG */
  3589. }
  3590. #endif /* HAVE_GETPGRP */
  3591. #ifdef HAVE_SETPGRP
  3592. PyDoc_STRVAR(posix_setpgrp__doc__,
  3593. "setpgrp()\n\n\
  3594. Make this process the process group leader.");
  3595. static PyObject *
  3596. posix_setpgrp(PyObject *self, PyObject *noargs)
  3597. {
  3598. #ifdef SETPGRP_HAVE_ARG
  3599. if (setpgrp(0, 0) < 0)
  3600. #else /* SETPGRP_HAVE_ARG */
  3601. if (setpgrp() < 0)
  3602. #endif /* SETPGRP_HAVE_ARG */
  3603. return posix_error();
  3604. Py_INCREF(Py_None);
  3605. return Py_None;
  3606. }
  3607. #endif /* HAVE_SETPGRP */
  3608. #ifdef HAVE_GETPPID
  3609. PyDoc_STRVAR(posix_getppid__doc__,
  3610. "getppid() -> ppid\n\n\
  3611. Return the parent's process id.");
  3612. static PyObject *
  3613. posix_getppid(PyObject *self, PyObject *noargs)
  3614. {
  3615. return PyLong_FromPid(getppid());
  3616. }
  3617. #endif
  3618. #ifdef HAVE_GETLOGIN
  3619. PyDoc_STRVAR(posix_getlogin__doc__,
  3620. "getlogin() -> string\n\n\
  3621. Return the actual login name.");
  3622. static PyObject *
  3623. posix_getlogin(PyObject *self, PyObject *noargs)
  3624. {
  3625. PyObject *result = NULL;
  3626. char *name;
  3627. int old_errno = errno;
  3628. errno = 0;
  3629. name = getlogin();
  3630. if (name == NULL) {
  3631. if (errno)
  3632. posix_error();
  3633. else
  3634. PyErr_SetString(PyExc_OSError,
  3635. "unable to determine login name");
  3636. }
  3637. else
  3638. result = PyString_FromString(name);
  3639. errno = old_errno;
  3640. return result;
  3641. }
  3642. #endif
  3643. #ifdef HAVE_GETUID
  3644. PyDoc_STRVAR(posix_getuid__doc__,
  3645. "getuid() -> uid\n\n\
  3646. Return the current process's user id.");
  3647. static PyObject *
  3648. posix_getuid(PyObject *self, PyObject *noargs)
  3649. {
  3650. return PyInt_FromLong((long)getuid());
  3651. }
  3652. #endif
  3653. #ifdef HAVE_KILL
  3654. PyDoc_STRVAR(posix_kill__doc__,
  3655. "kill(pid, sig)\n\n\
  3656. Kill a process with a signal.");
  3657. static PyObject *
  3658. posix_kill(PyObject *self, PyObject *args)
  3659. {
  3660. pid_t pid;
  3661. int sig;
  3662. if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig))
  3663. return NULL;
  3664. #if defined(PYOS_OS2) && !defined(PYCC_GCC)
  3665. if (sig == XCPT_SIGNAL_INTR || sig == XCPT_SIGNAL_BREAK) {
  3666. APIRET rc;
  3667. if ((rc = DosSendSignalException(pid, sig)) != NO_ERROR)
  3668. return os2_error(rc);
  3669. } else if (sig == XCPT_SIGNAL_KILLPROC) {
  3670. APIRET rc;
  3671. if ((rc = DosKillProcess(DKP_PROCESS, pid)) != NO_ERROR)
  3672. return os2_error(rc);
  3673. } else
  3674. return NULL; /* Unrecognized Signal Requested */
  3675. #else
  3676. if (kill(pid, sig) == -1)
  3677. return posix_error();
  3678. #endif
  3679. Py_INCREF(Py_None);
  3680. return Py_None;
  3681. }
  3682. #endif
  3683. #ifdef HAVE_KILLPG
  3684. PyDoc_STRVAR(posix_killpg__doc__,
  3685. "killpg(pgid, sig)\n\n\
  3686. Kill a process group with a signal.");
  3687. static PyObject *
  3688. posix_killpg(PyObject *self, PyObject *args)
  3689. {
  3690. int sig;
  3691. pid_t pgid;
  3692. /* XXX some man pages make the `pgid` parameter an int, others
  3693. a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
  3694. take the same type. Moreover, pid_t is always at least as wide as
  3695. int (else compilation of this module fails), which is safe. */
  3696. if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig))
  3697. return NULL;
  3698. if (killpg(pgid, sig) == -1)
  3699. return posix_error();
  3700. Py_INCREF(Py_None);
  3701. return Py_None;
  3702. }
  3703. #endif
  3704. #ifdef MS_WINDOWS
  3705. PyDoc_STRVAR(win32_kill__doc__,
  3706. "kill(pid, sig)\n\n\
  3707. Kill a process with a signal.");
  3708. static PyObject *
  3709. win32_kill(PyObject *self, PyObject *args)
  3710. {
  3711. PyObject *result;
  3712. DWORD pid, sig, err;
  3713. HANDLE handle;
  3714. if (!PyArg_ParseTuple(args, "kk:kill", &pid, &sig))
  3715. return NULL;
  3716. /* Console processes which share a common console can be sent CTRL+C or
  3717. CTRL+BREAK events, provided they handle said events. */
  3718. if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
  3719. if (GenerateConsoleCtrlEvent(sig, pid) == 0) {
  3720. err = GetLastError();
  3721. return PyErr_SetFromWindowsErr(err);
  3722. }
  3723. else
  3724. Py_RETURN_NONE;
  3725. }
  3726. /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
  3727. attempt to open and terminate the process. */
  3728. handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
  3729. if (handle == NULL) {
  3730. err = GetLastError();
  3731. return PyErr_SetFromWindowsErr(err);
  3732. }
  3733. if (TerminateProcess(handle, sig) == 0) {
  3734. err = GetLastError();
  3735. result = PyErr_SetFromWindowsErr(err);
  3736. } else {
  3737. Py_INCREF(Py_None);
  3738. result = Py_None;
  3739. }
  3740. CloseHandle(handle);
  3741. return result;
  3742. }
  3743. #endif /* MS_WINDOWS */
  3744. #ifdef HAVE_PLOCK
  3745. #ifdef HAVE_SYS_LOCK_H
  3746. #include <sys/lock.h>
  3747. #endif
  3748. PyDoc_STRVAR(posix_plock__doc__,
  3749. "plock(op)\n\n\
  3750. Lock program segments into memory.");
  3751. static PyObject *
  3752. posix_plock(PyObject *self, PyObject *args)
  3753. {
  3754. int op;
  3755. if (!PyArg_ParseTuple(args, "i:plock", &op))
  3756. return NULL;
  3757. if (plock(op) == -1)
  3758. return posix_error();
  3759. Py_INCREF(Py_None);
  3760. return Py_None;
  3761. }
  3762. #endif
  3763. #ifdef HAVE_POPEN
  3764. PyDoc_STRVAR(posix_popen__doc__,
  3765. "popen(command [, mode='r' [, bufsize]]) -> pipe\n\n\
  3766. Open a pipe to/from a command returning a file object.");
  3767. #if defined(PYOS_OS2)
  3768. #if defined(PYCC_VACPP)
  3769. static int
  3770. async_system(const char *command)
  3771. {
  3772. char errormsg[256], args[1024];
  3773. RESULTCODES rcodes;
  3774. APIRET rc;
  3775. char *shell = getenv("COMSPEC");
  3776. if (!shell)
  3777. shell = "cmd";
  3778. /* avoid overflowing the argument buffer */
  3779. if (strlen(shell) + 3 + strlen(command) >= 1024)
  3780. return ERROR_NOT_ENOUGH_MEMORY
  3781. args[0] = '\0';
  3782. strcat(args, shell);
  3783. strcat(args, "/c ");
  3784. strcat(args, command);
  3785. /* execute asynchronously, inheriting the environment */
  3786. rc = DosExecPgm(errormsg,
  3787. sizeof(errormsg),
  3788. EXEC_ASYNC,
  3789. args,
  3790. NULL,
  3791. &rcodes,
  3792. shell);
  3793. return rc;
  3794. }
  3795. static FILE *
  3796. popen(const char *command, const char *mode, int pipesize, int *err)
  3797. {
  3798. int oldfd, tgtfd;
  3799. HFILE pipeh[2];
  3800. APIRET rc;
  3801. /* mode determines which of stdin or stdout is reconnected to
  3802. * the pipe to the child
  3803. */
  3804. if (strchr(mode, 'r') != NULL) {
  3805. tgt_fd = 1; /* stdout */
  3806. } else if (strchr(mode, 'w')) {
  3807. tgt_fd = 0; /* stdin */
  3808. } else {
  3809. *err = ERROR_INVALID_ACCESS;
  3810. return NULL;
  3811. }
  3812. /* setup the pipe */
  3813. if ((rc = DosCreatePipe(&pipeh[0], &pipeh[1], pipesize)) != NO_ERROR) {
  3814. *err = rc;
  3815. return NULL;
  3816. }
  3817. /* prevent other threads accessing stdio */
  3818. DosEnterCritSec();
  3819. /* reconnect stdio and execute child */
  3820. oldfd = dup(tgtfd);
  3821. close(tgtfd);
  3822. if (dup2(pipeh[tgtfd], tgtfd) == 0) {
  3823. DosClose(pipeh[tgtfd]);
  3824. rc = async_system(command);
  3825. }
  3826. /* restore stdio */
  3827. dup2(oldfd, tgtfd);
  3828. close(oldfd);
  3829. /* allow other threads access to stdio */
  3830. DosExitCritSec();
  3831. /* if execution of child was successful return file stream */
  3832. if (rc == NO_ERROR)
  3833. return fdopen(pipeh[1 - tgtfd], mode);
  3834. else {
  3835. DosClose(pipeh[1 - tgtfd]);
  3836. *err = rc;
  3837. return NULL;
  3838. }
  3839. }
  3840. static PyObject *
  3841. posix_popen(PyObject *self, PyObject *args)
  3842. {
  3843. char *name;
  3844. char *mode = "r";
  3845. int err, bufsize = -1;
  3846. FILE *fp;
  3847. PyObject *f;
  3848. if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
  3849. return NULL;
  3850. Py_BEGIN_ALLOW_THREADS
  3851. fp = popen(name, mode, (bufsize > 0) ? bufsize : 4096, &err);
  3852. Py_END_ALLOW_THREADS
  3853. if (fp == NULL)
  3854. return os2_error(err);
  3855. f = PyFile_FromFile(fp, name, mode, fclose);
  3856. if (f != NULL)
  3857. PyFile_SetBufSize(f, bufsize);
  3858. return f;
  3859. }
  3860. #elif defined(PYCC_GCC)
  3861. /* standard posix version of popen() support */
  3862. static PyObject *
  3863. posix_popen(PyObject *self, PyObject *args)
  3864. {
  3865. char *name;
  3866. char *mode = "r";
  3867. int bufsize = -1;
  3868. FILE *fp;
  3869. PyObject *f;
  3870. if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
  3871. return NULL;
  3872. Py_BEGIN_ALLOW_THREADS
  3873. fp = popen(name, mode);
  3874. Py_END_ALLOW_THREADS
  3875. if (fp == NULL)
  3876. return posix_error();
  3877. f = PyFile_FromFile(fp, name, mode, pclose);
  3878. if (f != NULL)
  3879. PyFile_SetBufSize(f, bufsize);
  3880. return f;
  3881. }
  3882. /* fork() under OS/2 has lots'o'warts
  3883. * EMX supports pipe() and spawn*() so we can synthesize popen[234]()
  3884. * most of this code is a ripoff of the win32 code, but using the
  3885. * capabilities of EMX's C library routines
  3886. */
  3887. /* These tell _PyPopen() whether to return 1, 2, or 3 file objects. */
  3888. #define POPEN_1 1
  3889. #define POPEN_2 2
  3890. #define POPEN_3 3
  3891. #define POPEN_4 4
  3892. static PyObject *_PyPopen(char *, int, int, int);
  3893. static int _PyPclose(FILE *file);
  3894. /*
  3895. * Internal dictionary mapping popen* file pointers to process handles,
  3896. * for use when retrieving the process exit code. See _PyPclose() below
  3897. * for more information on this dictionary's use.
  3898. */
  3899. static PyObject *_PyPopenProcs = NULL;
  3900. /* os2emx version of popen2()
  3901. *
  3902. * The result of this function is a pipe (file) connected to the
  3903. * process's stdin, and a pipe connected to the process's stdout.
  3904. */
  3905. static PyObject *
  3906. os2emx_popen2(PyObject *self, PyObject *args)
  3907. {
  3908. PyObject *f;
  3909. int tm=0;
  3910. char *cmdstring;
  3911. char *mode = "t";
  3912. int bufsize = -1;
  3913. if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize))
  3914. return NULL;
  3915. if (*mode == 't')
  3916. tm = O_TEXT;
  3917. else if (*mode != 'b') {
  3918. PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
  3919. return NULL;
  3920. } else
  3921. tm = O_BINARY;
  3922. f = _PyPopen(cmdstring, tm, POPEN_2, bufsize);
  3923. return f;
  3924. }
  3925. /*
  3926. * Variation on os2emx.popen2
  3927. *
  3928. * The result of this function is 3 pipes - the process's stdin,
  3929. * stdout and stderr
  3930. */
  3931. static PyObject *
  3932. os2emx_popen3(PyObject *self, PyObject *args)
  3933. {
  3934. PyObject *f;
  3935. int tm = 0;
  3936. char *cmdstring;
  3937. char *mode = "t";
  3938. int bufsize = -1;
  3939. if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize))
  3940. return NULL;
  3941. if (*mode == 't')
  3942. tm = O_TEXT;
  3943. else if (*mode != 'b') {
  3944. PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
  3945. return NULL;
  3946. } else
  3947. tm = O_BINARY;
  3948. f = _PyPopen(cmdstring, tm, POPEN_3, bufsize);
  3949. return f;
  3950. }
  3951. /*
  3952. * Variation on os2emx.popen2
  3953. *
  3954. * The result of this function is 2 pipes - the processes stdin,
  3955. * and stdout+stderr combined as a single pipe.
  3956. */
  3957. static PyObject *
  3958. os2emx_popen4(PyObject *self, PyObject *args)
  3959. {
  3960. PyObject *f;
  3961. int tm = 0;
  3962. char *cmdstring;
  3963. char *mode = "t";
  3964. int bufsize = -1;
  3965. if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize))
  3966. return NULL;
  3967. if (*mode == 't')
  3968. tm = O_TEXT;
  3969. else if (*mode != 'b') {
  3970. PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
  3971. return NULL;
  3972. } else
  3973. tm = O_BINARY;
  3974. f = _PyPopen(cmdstring, tm, POPEN_4, bufsize);
  3975. return f;
  3976. }
  3977. /* a couple of structures for convenient handling of multiple
  3978. * file handles and pipes
  3979. */
  3980. struct file_ref
  3981. {
  3982. int handle;
  3983. int flags;
  3984. };
  3985. struct pipe_ref
  3986. {
  3987. int rd;
  3988. int wr;
  3989. };
  3990. /* The following code is derived from the win32 code */
  3991. static PyObject *
  3992. _PyPopen(char *cmdstring, int mode, int n, int bufsize)
  3993. {
  3994. struct file_ref stdio[3];
  3995. struct pipe_ref p_fd[3];
  3996. FILE *p_s[3];
  3997. int file_count, i, pipe_err;
  3998. pid_t pipe_pid;
  3999. char *shell, *sh_name, *opt, *rd_mode, *wr_mode;
  4000. PyObject *f, *p_f[3];
  4001. /* file modes for subsequent fdopen's on pipe handles */
  4002. if (mode == O_TEXT)
  4003. {
  4004. rd_mode = "rt";
  4005. wr_mode = "wt";
  4006. }
  4007. else
  4008. {
  4009. rd_mode = "rb";
  4010. wr_mode = "wb";
  4011. }
  4012. /* prepare shell references */
  4013. if ((shell = getenv("EMXSHELL")) == NULL)
  4014. if ((shell = getenv("COMSPEC")) == NULL)
  4015. {
  4016. errno = ENOENT;
  4017. return posix_error();
  4018. }
  4019. sh_name = _getname(shell);
  4020. if (stricmp(sh_name, "cmd.exe") == 0 || stricmp(sh_name, "4os2.exe") == 0)
  4021. opt = "/c";
  4022. else
  4023. opt = "-c";
  4024. /* save current stdio fds + their flags, and set not inheritable */
  4025. i = pipe_err = 0;
  4026. while (pipe_err >= 0 && i < 3)
  4027. {
  4028. pipe_err = stdio[i].handle = dup(i);
  4029. stdio[i].flags = fcntl(i, F_GETFD, 0);
  4030. fcntl(stdio[i].handle, F_SETFD, stdio[i].flags | FD_CLOEXEC);
  4031. i++;
  4032. }
  4033. if (pipe_err < 0)
  4034. {
  4035. /* didn't get them all saved - clean up and bail out */
  4036. int saved_err = errno;
  4037. while (i-- > 0)
  4038. {
  4039. close(stdio[i].handle);
  4040. }
  4041. errno = saved_err;
  4042. return posix_error();
  4043. }
  4044. /* create pipe ends */
  4045. file_count = 2;
  4046. if (n == POPEN_3)
  4047. file_count = 3;
  4048. i = pipe_err = 0;
  4049. while ((pipe_err == 0) && (i < file_count))
  4050. pipe_err = pipe((int *)&p_fd[i++]);
  4051. if (pipe_err < 0)
  4052. {
  4053. /* didn't get them all made - clean up and bail out */
  4054. while (i-- > 0)
  4055. {
  4056. close(p_fd[i].wr);
  4057. close(p_fd[i].rd);
  4058. }
  4059. errno = EPIPE;
  4060. return posix_error();
  4061. }
  4062. /* change the actual standard IO streams over temporarily,
  4063. * making the retained pipe ends non-inheritable
  4064. */
  4065. pipe_err = 0;
  4066. /* - stdin */
  4067. if (dup2(p_fd[0].rd, 0) == 0)
  4068. {
  4069. close(p_fd[0].rd);
  4070. i = fcntl(p_fd[0].wr, F_GETFD, 0);
  4071. fcntl(p_fd[0].wr, F_SETFD, i | FD_CLOEXEC);
  4072. if ((p_s[0] = fdopen(p_fd[0].wr, wr_mode)) == NULL)
  4073. {
  4074. close(p_fd[0].wr);
  4075. pipe_err = -1;
  4076. }
  4077. }
  4078. else
  4079. {
  4080. pipe_err = -1;
  4081. }
  4082. /* - stdout */
  4083. if (pipe_err == 0)
  4084. {
  4085. if (dup2(p_fd[1].wr, 1) == 1)
  4086. {
  4087. close(p_fd[1].wr);
  4088. i = fcntl(p_fd[1].rd, F_GETFD, 0);
  4089. fcntl(p_fd[1].rd, F_SETFD, i | FD_CLOEXEC);
  4090. if ((p_s[1] = fdopen(p_fd[1].rd, rd_mode)) == NULL)
  4091. {
  4092. close(p_fd[1].rd);
  4093. pipe_err = -1;
  4094. }
  4095. }
  4096. else
  4097. {
  4098. pipe_err = -1;
  4099. }
  4100. }
  4101. /* - stderr, as required */
  4102. if (pipe_err == 0)
  4103. switch (n)
  4104. {
  4105. case POPEN_3:
  4106. {
  4107. if (dup2(p_fd[2].wr, 2) == 2)
  4108. {
  4109. close(p_fd[2].wr);
  4110. i = fcntl(p_fd[2].rd, F_GETFD, 0);
  4111. fcntl(p_fd[2].rd, F_SETFD, i | FD_CLOEXEC);
  4112. if ((p_s[2] = fdopen(p_fd[2].rd, rd_mode)) == NULL)
  4113. {
  4114. close(p_fd[2].rd);
  4115. pipe_err = -1;
  4116. }
  4117. }
  4118. else
  4119. {
  4120. pipe_err = -1;
  4121. }
  4122. break;
  4123. }
  4124. case POPEN_4:
  4125. {
  4126. if (dup2(1, 2) != 2)
  4127. {
  4128. pipe_err = -1;
  4129. }
  4130. break;
  4131. }
  4132. }
  4133. /* spawn the child process */
  4134. if (pipe_err == 0)
  4135. {
  4136. pipe_pid = spawnlp(P_NOWAIT, shell, shell, opt, cmdstring, (char *)0);
  4137. if (pipe_pid == -1)
  4138. {
  4139. pipe_err = -1;
  4140. }
  4141. else
  4142. {
  4143. /* save the PID into the FILE structure
  4144. * NOTE: this implementation doesn't actually
  4145. * take advantage of this, but do it for
  4146. * completeness - AIM Apr01
  4147. */
  4148. for (i = 0; i < file_count; i++)
  4149. p_s[i]->_pid = pipe_pid;
  4150. }
  4151. }
  4152. /* reset standard IO to normal */
  4153. for (i = 0; i < 3; i++)
  4154. {
  4155. dup2(stdio[i].handle, i);
  4156. fcntl(i, F_SETFD, stdio[i].flags);
  4157. close(stdio[i].handle);
  4158. }
  4159. /* if any remnant problems, clean up and bail out */
  4160. if (pipe_err < 0)
  4161. {
  4162. for (i = 0; i < 3; i++)
  4163. {
  4164. close(p_fd[i].rd);
  4165. close(p_fd[i].wr);
  4166. }
  4167. errno = EPIPE;
  4168. return posix_error_with_filename(cmdstring);
  4169. }
  4170. /* build tuple of file objects to return */
  4171. if ((p_f[0] = PyFile_FromFile(p_s[0], cmdstring, wr_mode, _PyPclose)) != NULL)
  4172. PyFile_SetBufSize(p_f[0], bufsize);
  4173. if ((p_f[1] = PyFile_FromFile(p_s[1], cmdstring, rd_mode, _PyPclose)) != NULL)
  4174. PyFile_SetBufSize(p_f[1], bufsize);
  4175. if (n == POPEN_3)
  4176. {
  4177. if ((p_f[2] = PyFile_FromFile(p_s[2], cmdstring, rd_mode, _PyPclose)) != NULL)
  4178. PyFile_SetBufSize(p_f[0], bufsize);
  4179. f = PyTuple_Pack(3, p_f[0], p_f[1], p_f[2]);
  4180. }
  4181. else
  4182. f = PyTuple_Pack(2, p_f[0], p_f[1]);
  4183. /*
  4184. * Insert the files we've created into the process dictionary
  4185. * all referencing the list with the process handle and the
  4186. * initial number of files (see description below in _PyPclose).
  4187. * Since if _PyPclose later tried to wait on a process when all
  4188. * handles weren't closed, it could create a deadlock with the
  4189. * child, we spend some energy here to try to ensure that we
  4190. * either insert all file handles into the dictionary or none
  4191. * at all. It's a little clumsy with the various popen modes
  4192. * and variable number of files involved.
  4193. */
  4194. if (!_PyPopenProcs)
  4195. {
  4196. _PyPopenProcs = PyDict_New();
  4197. }
  4198. if (_PyPopenProcs)
  4199. {
  4200. PyObject *procObj, *pidObj, *intObj, *fileObj[3];
  4201. int ins_rc[3];
  4202. fileObj[0] = fileObj[1] = fileObj[2] = NULL;
  4203. ins_rc[0] = ins_rc[1] = ins_rc[2] = 0;
  4204. procObj = PyList_New(2);
  4205. pidObj = PyLong_FromPid(pipe_pid);
  4206. intObj = PyInt_FromLong((long) file_count);
  4207. if (procObj && pidObj && intObj)
  4208. {
  4209. PyList_SetItem(procObj, 0, pidObj);
  4210. PyList_SetItem(procObj, 1, intObj);
  4211. fileObj[0] = PyLong_FromVoidPtr(p_s[0]);
  4212. if (fileObj[0])
  4213. {
  4214. ins_rc[0] = PyDict_SetItem(_PyPopenProcs,
  4215. fileObj[0],
  4216. procObj);
  4217. }
  4218. fileObj[1] = PyLong_FromVoidPtr(p_s[1]);
  4219. if (fileObj[1])
  4220. {
  4221. ins_rc[1] = PyDict_SetItem(_PyPopenProcs,
  4222. fileObj[1],
  4223. procObj);
  4224. }
  4225. if (file_count >= 3)
  4226. {
  4227. fileObj[2] = PyLong_FromVoidPtr(p_s[2]);
  4228. if (fileObj[2])
  4229. {
  4230. ins_rc[2] = PyDict_SetItem(_PyPopenProcs,
  4231. fileObj[2],
  4232. procObj);
  4233. }
  4234. }
  4235. if (ins_rc[0] < 0 || !fileObj[0] ||
  4236. ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) ||
  4237. ins_rc[2] < 0 || (file_count > 2 && !fileObj[2]))
  4238. {
  4239. /* Something failed - remove any dictionary
  4240. * entries that did make it.
  4241. */
  4242. if (!ins_rc[0] && fileObj[0])
  4243. {
  4244. PyDict_DelItem(_PyPopenProcs,
  4245. fileObj[0]);
  4246. }
  4247. if (!ins_rc[1] && fileObj[1])
  4248. {
  4249. PyDict_DelItem(_PyPopenProcs,
  4250. fileObj[1]);
  4251. }
  4252. if (!ins_rc[2] && fileObj[2])
  4253. {
  4254. PyDict_DelItem(_PyPopenProcs,
  4255. fileObj[2]);
  4256. }
  4257. }
  4258. }
  4259. /*
  4260. * Clean up our localized references for the dictionary keys
  4261. * and value since PyDict_SetItem will Py_INCREF any copies
  4262. * that got placed in the dictionary.
  4263. */
  4264. Py_XDECREF(procObj);
  4265. Py_XDECREF(fileObj[0]);
  4266. Py_XDECREF(fileObj[1]);
  4267. Py_XDECREF(fileObj[2]);
  4268. }
  4269. /* Child is launched. */
  4270. return f;
  4271. }
  4272. /*
  4273. * Wrapper for fclose() to use for popen* files, so we can retrieve the
  4274. * exit code for the child process and return as a result of the close.
  4275. *
  4276. * This function uses the _PyPopenProcs dictionary in order to map the
  4277. * input file pointer to information about the process that was
  4278. * originally created by the popen* call that created the file pointer.
  4279. * The dictionary uses the file pointer as a key (with one entry
  4280. * inserted for each file returned by the original popen* call) and a
  4281. * single list object as the value for all files from a single call.
  4282. * The list object contains the Win32 process handle at [0], and a file
  4283. * count at [1], which is initialized to the total number of file
  4284. * handles using that list.
  4285. *
  4286. * This function closes whichever handle it is passed, and decrements
  4287. * the file count in the dictionary for the process handle pointed to
  4288. * by this file. On the last close (when the file count reaches zero),
  4289. * this function will wait for the child process and then return its
  4290. * exit code as the result of the close() operation. This permits the
  4291. * files to be closed in any order - it is always the close() of the
  4292. * final handle that will return the exit code.
  4293. *
  4294. * NOTE: This function is currently called with the GIL released.
  4295. * hence we use the GILState API to manage our state.
  4296. */
  4297. static int _PyPclose(FILE *file)
  4298. {
  4299. int result;
  4300. int exit_code;
  4301. pid_t pipe_pid;
  4302. PyObject *procObj, *pidObj, *intObj, *fileObj;
  4303. int file_count;
  4304. #ifdef WITH_THREAD
  4305. PyGILState_STATE state;
  4306. #endif
  4307. /* Close the file handle first, to ensure it can't block the
  4308. * child from exiting if it's the last handle.
  4309. */
  4310. result = fclose(file);
  4311. #ifdef WITH_THREAD
  4312. state = PyGILState_Ensure();
  4313. #endif
  4314. if (_PyPopenProcs)
  4315. {
  4316. if ((fileObj = PyLong_FromVoidPtr(file)) != NULL &&
  4317. (procObj = PyDict_GetItem(_PyPopenProcs,
  4318. fileObj)) != NULL &&
  4319. (pidObj = PyList_GetItem(procObj,0)) != NULL &&
  4320. (intObj = PyList_GetItem(procObj,1)) != NULL)
  4321. {
  4322. pipe_pid = (pid_t) PyLong_AsPid(pidObj);
  4323. file_count = (int) PyInt_AsLong(intObj);
  4324. if (file_count > 1)
  4325. {
  4326. /* Still other files referencing process */
  4327. file_count--;
  4328. PyList_SetItem(procObj,1,
  4329. PyInt_FromLong((long) file_count));
  4330. }
  4331. else
  4332. {
  4333. /* Last file for this process */
  4334. if (result != EOF &&
  4335. waitpid(pipe_pid, &exit_code, 0) == pipe_pid)
  4336. {
  4337. /* extract exit status */
  4338. if (WIFEXITED(exit_code))
  4339. {
  4340. result = WEXITSTATUS(exit_code);
  4341. }
  4342. else
  4343. {
  4344. errno = EPIPE;
  4345. result = -1;
  4346. }
  4347. }
  4348. else
  4349. {
  4350. /* Indicate failure - this will cause the file object
  4351. * to raise an I/O error and translate the last
  4352. * error code from errno. We do have a problem with
  4353. * last errors that overlap the normal errno table,
  4354. * but that's a consistent problem with the file object.
  4355. */
  4356. result = -1;
  4357. }
  4358. }
  4359. /* Remove this file pointer from dictionary */
  4360. PyDict_DelItem(_PyPopenProcs, fileObj);
  4361. if (PyDict_Size(_PyPopenProcs) == 0)
  4362. {
  4363. Py_DECREF(_PyPopenProcs);
  4364. _PyPopenProcs = NULL;
  4365. }
  4366. } /* if object retrieval ok */
  4367. Py_XDECREF(fileObj);
  4368. } /* if _PyPopenProcs */
  4369. #ifdef WITH_THREAD
  4370. PyGILState_Release(state);
  4371. #endif
  4372. return result;
  4373. }
  4374. #endif /* PYCC_??? */
  4375. #elif defined(MS_WINDOWS)
  4376. /*
  4377. * Portable 'popen' replacement for Win32.
  4378. *
  4379. * Written by Bill Tutt <billtut@microsoft.com>. Minor tweaks
  4380. * and 2.0 integration by Fredrik Lundh <fredrik@pythonware.com>
  4381. * Return code handling by David Bolen <db3l@fitlinxx.com>.
  4382. */
  4383. #include <malloc.h>
  4384. #include <io.h>
  4385. #include <fcntl.h>
  4386. /* These tell _PyPopen() wether to return 1, 2, or 3 file objects. */
  4387. #define POPEN_1 1
  4388. #define POPEN_2 2
  4389. #define POPEN_3 3
  4390. #define POPEN_4 4
  4391. static PyObject *_PyPopen(char *, int, int);
  4392. static int _PyPclose(FILE *file);
  4393. /*
  4394. * Internal dictionary mapping popen* file pointers to process handles,
  4395. * for use when retrieving the process exit code. See _PyPclose() below
  4396. * for more information on this dictionary's use.
  4397. */
  4398. static PyObject *_PyPopenProcs = NULL;
  4399. /* popen that works from a GUI.
  4400. *
  4401. * The result of this function is a pipe (file) connected to the
  4402. * processes stdin or stdout, depending on the requested mode.
  4403. */
  4404. static PyObject *
  4405. posix_popen(PyObject *self, PyObject *args)
  4406. {
  4407. PyObject *f;
  4408. int tm = 0;
  4409. char *cmdstring;
  4410. char *mode = "r";
  4411. int bufsize = -1;
  4412. if (!PyArg_ParseTuple(args, "s|si:popen", &cmdstring, &mode, &bufsize))
  4413. return NULL;
  4414. if (*mode == 'r')
  4415. tm = _O_RDONLY;
  4416. else if (*mode != 'w') {
  4417. PyErr_SetString(PyExc_ValueError, "popen() arg 2 must be 'r' or 'w'");
  4418. return NULL;
  4419. } else
  4420. tm = _O_WRONLY;
  4421. if (bufsize != -1) {
  4422. PyErr_SetString(PyExc_ValueError, "popen() arg 3 must be -1");
  4423. return NULL;
  4424. }
  4425. if (*(mode+1) == 't')
  4426. f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1);
  4427. else if (*(mode+1) == 'b')
  4428. f = _PyPopen(cmdstring, tm | _O_BINARY, POPEN_1);
  4429. else
  4430. f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1);
  4431. return f;
  4432. }
  4433. /* Variation on win32pipe.popen
  4434. *
  4435. * The result of this function is a pipe (file) connected to the
  4436. * process's stdin, and a pipe connected to the process's stdout.
  4437. */
  4438. static PyObject *
  4439. win32_popen2(PyObject *self, PyObject *args)
  4440. {
  4441. PyObject *f;
  4442. int tm=0;
  4443. char *cmdstring;
  4444. char *mode = "t";
  4445. int bufsize = -1;
  4446. if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize))
  4447. return NULL;
  4448. if (*mode == 't')
  4449. tm = _O_TEXT;
  4450. else if (*mode != 'b') {
  4451. PyErr_SetString(PyExc_ValueError, "popen2() arg 2 must be 't' or 'b'");
  4452. return NULL;
  4453. } else
  4454. tm = _O_BINARY;
  4455. if (bufsize != -1) {
  4456. PyErr_SetString(PyExc_ValueError, "popen2() arg 3 must be -1");
  4457. return NULL;
  4458. }
  4459. f = _PyPopen(cmdstring, tm, POPEN_2);
  4460. return f;
  4461. }
  4462. /*
  4463. * Variation on <om win32pipe.popen>
  4464. *
  4465. * The result of this function is 3 pipes - the process's stdin,
  4466. * stdout and stderr
  4467. */
  4468. static PyObject *
  4469. win32_popen3(PyObject *self, PyObject *args)
  4470. {
  4471. PyObject *f;
  4472. int tm = 0;
  4473. char *cmdstring;
  4474. char *mode = "t";
  4475. int bufsize = -1;
  4476. if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize))
  4477. return NULL;
  4478. if (*mode == 't')
  4479. tm = _O_TEXT;
  4480. else if (*mode != 'b') {
  4481. PyErr_SetString(PyExc_ValueError, "popen3() arg 2 must be 't' or 'b'");
  4482. return NULL;
  4483. } else
  4484. tm = _O_BINARY;
  4485. if (bufsize != -1) {
  4486. PyErr_SetString(PyExc_ValueError, "popen3() arg 3 must be -1");
  4487. return NULL;
  4488. }
  4489. f = _PyPopen(cmdstring, tm, POPEN_3);
  4490. return f;
  4491. }
  4492. /*
  4493. * Variation on win32pipe.popen
  4494. *
  4495. * The result of this function is 2 pipes - the processes stdin,
  4496. * and stdout+stderr combined as a single pipe.
  4497. */
  4498. static PyObject *
  4499. win32_popen4(PyObject *self, PyObject *args)
  4500. {
  4501. PyObject *f;
  4502. int tm = 0;
  4503. char *cmdstring;
  4504. char *mode = "t";
  4505. int bufsize = -1;
  4506. if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize))
  4507. return NULL;
  4508. if (*mode == 't')
  4509. tm = _O_TEXT;
  4510. else if (*mode != 'b') {
  4511. PyErr_SetString(PyExc_ValueError, "popen4() arg 2 must be 't' or 'b'");
  4512. return NULL;
  4513. } else
  4514. tm = _O_BINARY;
  4515. if (bufsize != -1) {
  4516. PyErr_SetString(PyExc_ValueError, "popen4() arg 3 must be -1");
  4517. return NULL;
  4518. }
  4519. f = _PyPopen(cmdstring, tm, POPEN_4);
  4520. return f;
  4521. }
  4522. static BOOL
  4523. _PyPopenCreateProcess(char *cmdstring,
  4524. HANDLE hStdin,
  4525. HANDLE hStdout,
  4526. HANDLE hStderr,
  4527. HANDLE *hProcess)
  4528. {
  4529. PROCESS_INFORMATION piProcInfo;
  4530. STARTUPINFO siStartInfo;
  4531. DWORD dwProcessFlags = 0; /* no NEW_CONSOLE by default for Ctrl+C handling */
  4532. char *s1,*s2, *s3 = " /c ";
  4533. const char *szConsoleSpawn = "w9xpopen.exe";
  4534. int i;
  4535. Py_ssize_t x;
  4536. if (i = GetEnvironmentVariable("COMSPEC",NULL,0)) {
  4537. char *comshell;
  4538. s1 = (char *)alloca(i);
  4539. if (!(x = GetEnvironmentVariable("COMSPEC", s1, i)))
  4540. /* x < i, so x fits into an integer */
  4541. return (int)x;
  4542. /* Explicitly check if we are using COMMAND.COM. If we are
  4543. * then use the w9xpopen hack.
  4544. */
  4545. comshell = s1 + x;
  4546. while (comshell >= s1 && *comshell != '\\')
  4547. --comshell;
  4548. ++comshell;
  4549. if (GetVersion() < 0x80000000 &&
  4550. _stricmp(comshell, "command.com") != 0) {
  4551. /* NT/2000 and not using command.com. */
  4552. x = i + strlen(s3) + strlen(cmdstring) + 1;
  4553. s2 = (char *)alloca(x);
  4554. ZeroMemory(s2, x);
  4555. PyOS_snprintf(s2, x, "%s%s%s", s1, s3, cmdstring);
  4556. }
  4557. else {
  4558. /*
  4559. * Oh gag, we're on Win9x or using COMMAND.COM. Use
  4560. * the workaround listed in KB: Q150956
  4561. */
  4562. char modulepath[_MAX_PATH];
  4563. struct stat statinfo;
  4564. GetModuleFileName(NULL, modulepath, sizeof(modulepath));
  4565. for (x = i = 0; modulepath[i]; i++)
  4566. if (modulepath[i] == SEP)
  4567. x = i+1;
  4568. modulepath[x] = '\0';
  4569. /* Create the full-name to w9xpopen, so we can test it exists */
  4570. strncat(modulepath,
  4571. szConsoleSpawn,
  4572. (sizeof(modulepath)/sizeof(modulepath[0]))
  4573. -strlen(modulepath));
  4574. if (stat(modulepath, &statinfo) != 0) {
  4575. size_t mplen = sizeof(modulepath)/sizeof(modulepath[0]);
  4576. /* Eeek - file-not-found - possibly an embedding
  4577. situation - see if we can locate it in sys.prefix
  4578. */
  4579. strncpy(modulepath,
  4580. Py_GetExecPrefix(),
  4581. mplen);
  4582. modulepath[mplen-1] = '\0';
  4583. if (modulepath[strlen(modulepath)-1] != '\\')
  4584. strcat(modulepath, "\\");
  4585. strncat(modulepath,
  4586. szConsoleSpawn,
  4587. mplen-strlen(modulepath));
  4588. /* No where else to look - raise an easily identifiable
  4589. error, rather than leaving Windows to report
  4590. "file not found" - as the user is probably blissfully
  4591. unaware this shim EXE is used, and it will confuse them.
  4592. (well, it confused me for a while ;-)
  4593. */
  4594. if (stat(modulepath, &statinfo) != 0) {
  4595. PyErr_Format(PyExc_RuntimeError,
  4596. "Can not locate '%s' which is needed "
  4597. "for popen to work with your shell "
  4598. "or platform.",
  4599. szConsoleSpawn);
  4600. return FALSE;
  4601. }
  4602. }
  4603. x = i + strlen(s3) + strlen(cmdstring) + 1 +
  4604. strlen(modulepath) +
  4605. strlen(szConsoleSpawn) + 1;
  4606. s2 = (char *)alloca(x);
  4607. ZeroMemory(s2, x);
  4608. /* To maintain correct argument passing semantics,
  4609. we pass the command-line as it stands, and allow
  4610. quoting to be applied. w9xpopen.exe will then
  4611. use its argv vector, and re-quote the necessary
  4612. args for the ultimate child process.
  4613. */
  4614. PyOS_snprintf(
  4615. s2, x,
  4616. "\"%s\" %s%s%s",
  4617. modulepath,
  4618. s1,
  4619. s3,
  4620. cmdstring);
  4621. /* Not passing CREATE_NEW_CONSOLE has been known to
  4622. cause random failures on win9x. Specifically a
  4623. dialog:
  4624. "Your program accessed mem currently in use at xxx"
  4625. and a hopeful warning about the stability of your
  4626. system.
  4627. Cost is Ctrl+C won't kill children, but anyone
  4628. who cares can have a go!
  4629. */
  4630. dwProcessFlags |= CREATE_NEW_CONSOLE;
  4631. }
  4632. }
  4633. /* Could be an else here to try cmd.exe / command.com in the path
  4634. Now we'll just error out.. */
  4635. else {
  4636. PyErr_SetString(PyExc_RuntimeError,
  4637. "Cannot locate a COMSPEC environment variable to "
  4638. "use as the shell");
  4639. return FALSE;
  4640. }
  4641. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  4642. siStartInfo.cb = sizeof(STARTUPINFO);
  4643. siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4644. siStartInfo.hStdInput = hStdin;
  4645. siStartInfo.hStdOutput = hStdout;
  4646. siStartInfo.hStdError = hStderr;
  4647. siStartInfo.wShowWindow = SW_HIDE;
  4648. if (CreateProcess(NULL,
  4649. s2,
  4650. NULL,
  4651. NULL,
  4652. TRUE,
  4653. dwProcessFlags,
  4654. NULL,
  4655. NULL,
  4656. &siStartInfo,
  4657. &piProcInfo) ) {
  4658. /* Close the handles now so anyone waiting is woken. */
  4659. CloseHandle(piProcInfo.hThread);
  4660. /* Return process handle */
  4661. *hProcess = piProcInfo.hProcess;
  4662. return TRUE;
  4663. }
  4664. win32_error("CreateProcess", s2);
  4665. return FALSE;
  4666. }
  4667. /* The following code is based off of KB: Q190351 */
  4668. static PyObject *
  4669. _PyPopen(char *cmdstring, int mode, int n)
  4670. {
  4671. HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr,
  4672. hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup,
  4673. hChildStderrRdDup, hProcess; /* hChildStdoutWrDup; */
  4674. SECURITY_ATTRIBUTES saAttr;
  4675. BOOL fSuccess;
  4676. int fd1, fd2, fd3;
  4677. FILE *f1, *f2, *f3;
  4678. long file_count;
  4679. PyObject *f;
  4680. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  4681. saAttr.bInheritHandle = TRUE;
  4682. saAttr.lpSecurityDescriptor = NULL;
  4683. if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0))
  4684. return win32_error("CreatePipe", NULL);
  4685. /* Create new output read handle and the input write handle. Set
  4686. * the inheritance properties to FALSE. Otherwise, the child inherits
  4687. * these handles; resulting in non-closeable handles to the pipes
  4688. * being created. */
  4689. fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
  4690. GetCurrentProcess(), &hChildStdinWrDup, 0,
  4691. FALSE,
  4692. DUPLICATE_SAME_ACCESS);
  4693. if (!fSuccess)
  4694. return win32_error("DuplicateHandle", NULL);
  4695. /* Close the inheritable version of ChildStdin
  4696. that we're using. */
  4697. CloseHandle(hChildStdinWr);
  4698. if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
  4699. return win32_error("CreatePipe", NULL);
  4700. fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
  4701. GetCurrentProcess(), &hChildStdoutRdDup, 0,
  4702. FALSE, DUPLICATE_SAME_ACCESS);
  4703. if (!fSuccess)
  4704. return win32_error("DuplicateHandle", NULL);
  4705. /* Close the inheritable version of ChildStdout
  4706. that we're using. */
  4707. CloseHandle(hChildStdoutRd);
  4708. if (n != POPEN_4) {
  4709. if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0))
  4710. return win32_error("CreatePipe", NULL);
  4711. fSuccess = DuplicateHandle(GetCurrentProcess(),
  4712. hChildStderrRd,
  4713. GetCurrentProcess(),
  4714. &hChildStderrRdDup, 0,
  4715. FALSE, DUPLICATE_SAME_ACCESS);
  4716. if (!fSuccess)
  4717. return win32_error("DuplicateHandle", NULL);
  4718. /* Close the inheritable version of ChildStdErr that we're using. */
  4719. CloseHandle(hChildStderrRd);
  4720. }
  4721. switch (n) {
  4722. case POPEN_1:
  4723. switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY)) {
  4724. case _O_WRONLY | _O_TEXT:
  4725. /* Case for writing to child Stdin in text mode. */
  4726. fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
  4727. f1 = _fdopen(fd1, "w");
  4728. f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose);
  4729. PyFile_SetBufSize(f, 0);
  4730. /* We don't care about these pipes anymore, so close them. */
  4731. CloseHandle(hChildStdoutRdDup);
  4732. CloseHandle(hChildStderrRdDup);
  4733. break;
  4734. case _O_RDONLY | _O_TEXT:
  4735. /* Case for reading from child Stdout in text mode. */
  4736. fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
  4737. f1 = _fdopen(fd1, "r");
  4738. f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose);
  4739. PyFile_SetBufSize(f, 0);
  4740. /* We don't care about these pipes anymore, so close them. */
  4741. CloseHandle(hChildStdinWrDup);
  4742. CloseHandle(hChildStderrRdDup);
  4743. break;
  4744. case _O_RDONLY | _O_BINARY:
  4745. /* Case for readinig from child Stdout in binary mode. */
  4746. fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
  4747. f1 = _fdopen(fd1, "rb");
  4748. f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose);
  4749. PyFile_SetBufSize(f, 0);
  4750. /* We don't care about these pipes anymore, so close them. */
  4751. CloseHandle(hChildStdinWrDup);
  4752. CloseHandle(hChildStderrRdDup);
  4753. break;
  4754. case _O_WRONLY | _O_BINARY:
  4755. /* Case for writing to child Stdin in binary mode. */
  4756. fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
  4757. f1 = _fdopen(fd1, "wb");
  4758. f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose);
  4759. PyFile_SetBufSize(f, 0);
  4760. /* We don't care about these pipes anymore, so close them. */
  4761. CloseHandle(hChildStdoutRdDup);
  4762. CloseHandle(hChildStderrRdDup);
  4763. break;
  4764. }
  4765. file_count = 1;
  4766. break;
  4767. case POPEN_2:
  4768. case POPEN_4:
  4769. {
  4770. char *m1, *m2;
  4771. PyObject *p1, *p2;
  4772. if (mode & _O_TEXT) {
  4773. m1 = "r";
  4774. m2 = "w";
  4775. } else {
  4776. m1 = "rb";
  4777. m2 = "wb";
  4778. }
  4779. fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
  4780. f1 = _fdopen(fd1, m2);
  4781. fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
  4782. f2 = _fdopen(fd2, m1);
  4783. p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);
  4784. PyFile_SetBufSize(p1, 0);
  4785. p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);
  4786. PyFile_SetBufSize(p2, 0);
  4787. if (n != 4)
  4788. CloseHandle(hChildStderrRdDup);
  4789. f = PyTuple_Pack(2,p1,p2);
  4790. Py_XDECREF(p1);
  4791. Py_XDECREF(p2);
  4792. file_count = 2;
  4793. break;
  4794. }
  4795. case POPEN_3:
  4796. {
  4797. char *m1, *m2;
  4798. PyObject *p1, *p2, *p3;
  4799. if (mode & _O_TEXT) {
  4800. m1 = "r";
  4801. m2 = "w";
  4802. } else {
  4803. m1 = "rb";
  4804. m2 = "wb";
  4805. }
  4806. fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
  4807. f1 = _fdopen(fd1, m2);
  4808. fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
  4809. f2 = _fdopen(fd2, m1);
  4810. fd3 = _open_osfhandle((Py_intptr_t)hChildStderrRdDup, mode);
  4811. f3 = _fdopen(fd3, m1);
  4812. p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);
  4813. p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);
  4814. p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose);
  4815. PyFile_SetBufSize(p1, 0);
  4816. PyFile_SetBufSize(p2, 0);
  4817. PyFile_SetBufSize(p3, 0);
  4818. f = PyTuple_Pack(3,p1,p2,p3);
  4819. Py_XDECREF(p1);
  4820. Py_XDECREF(p2);
  4821. Py_XDECREF(p3);
  4822. file_count = 3;
  4823. break;
  4824. }
  4825. }
  4826. if (n == POPEN_4) {
  4827. if (!_PyPopenCreateProcess(cmdstring,
  4828. hChildStdinRd,
  4829. hChildStdoutWr,
  4830. hChildStdoutWr,
  4831. &hProcess))
  4832. return NULL;
  4833. }
  4834. else {
  4835. if (!_PyPopenCreateProcess(cmdstring,
  4836. hChildStdinRd,
  4837. hChildStdoutWr,
  4838. hChildStderrWr,
  4839. &hProcess))
  4840. return NULL;
  4841. }
  4842. /*
  4843. * Insert the files we've created into the process dictionary
  4844. * all referencing the list with the process handle and the
  4845. * initial number of files (see description below in _PyPclose).
  4846. * Since if _PyPclose later tried to wait on a process when all
  4847. * handles weren't closed, it could create a deadlock with the
  4848. * child, we spend some energy here to try to ensure that we
  4849. * either insert all file handles into the dictionary or none
  4850. * at all. It's a little clumsy with the various popen modes
  4851. * and variable number of files involved.
  4852. */
  4853. if (!_PyPopenProcs) {
  4854. _PyPopenProcs = PyDict_New();
  4855. }
  4856. if (_PyPopenProcs) {
  4857. PyObject *procObj, *hProcessObj, *intObj, *fileObj[3];
  4858. int ins_rc[3];
  4859. fileObj[0] = fileObj[1] = fileObj[2] = NULL;
  4860. ins_rc[0] = ins_rc[1] = ins_rc[2] = 0;
  4861. procObj = PyList_New(2);
  4862. hProcessObj = PyLong_FromVoidPtr(hProcess);
  4863. intObj = PyInt_FromLong(file_count);
  4864. if (procObj && hProcessObj && intObj) {
  4865. PyList_SetItem(procObj,0,hProcessObj);
  4866. PyList_SetItem(procObj,1,intObj);
  4867. fileObj[0] = PyLong_FromVoidPtr(f1);
  4868. if (fileObj[0]) {
  4869. ins_rc[0] = PyDict_SetItem(_PyPopenProcs,
  4870. fileObj[0],
  4871. procObj);
  4872. }
  4873. if (file_count >= 2) {
  4874. fileObj[1] = PyLong_FromVoidPtr(f2);
  4875. if (fileObj[1]) {
  4876. ins_rc[1] = PyDict_SetItem(_PyPopenProcs,
  4877. fileObj[1],
  4878. procObj);
  4879. }
  4880. }
  4881. if (file_count >= 3) {
  4882. fileObj[2] = PyLong_FromVoidPtr(f3);
  4883. if (fileObj[2]) {
  4884. ins_rc[2] = PyDict_SetItem(_PyPopenProcs,
  4885. fileObj[2],
  4886. procObj);
  4887. }
  4888. }
  4889. if (ins_rc[0] < 0 || !fileObj[0] ||
  4890. ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) ||
  4891. ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) {
  4892. /* Something failed - remove any dictionary
  4893. * entries that did make it.
  4894. */
  4895. if (!ins_rc[0] && fileObj[0]) {
  4896. PyDict_DelItem(_PyPopenProcs,
  4897. fileObj[0]);
  4898. }
  4899. if (!ins_rc[1] && fileObj[1]) {
  4900. PyDict_DelItem(_PyPopenProcs,
  4901. fileObj[1]);
  4902. }
  4903. if (!ins_rc[2] && fileObj[2]) {
  4904. PyDict_DelItem(_PyPopenProcs,
  4905. fileObj[2]);
  4906. }
  4907. }
  4908. }
  4909. /*
  4910. * Clean up our localized references for the dictionary keys
  4911. * and value since PyDict_SetItem will Py_INCREF any copies
  4912. * that got placed in the dictionary.
  4913. */
  4914. Py_XDECREF(procObj);
  4915. Py_XDECREF(fileObj[0]);
  4916. Py_XDECREF(fileObj[1]);
  4917. Py_XDECREF(fileObj[2]);
  4918. }
  4919. /* Child is launched. Close the parents copy of those pipe
  4920. * handles that only the child should have open. You need to
  4921. * make sure that no handles to the write end of the output pipe
  4922. * are maintained in this process or else the pipe will not close
  4923. * when the child process exits and the ReadFile will hang. */
  4924. if (!CloseHandle(hChildStdinRd))
  4925. return win32_error("CloseHandle", NULL);
  4926. if (!CloseHandle(hChildStdoutWr))
  4927. return win32_error("CloseHandle", NULL);
  4928. if ((n != 4) && (!CloseHandle(hChildStderrWr)))
  4929. return win32_error("CloseHandle", NULL);
  4930. return f;
  4931. }
  4932. /*
  4933. * Wrapper for fclose() to use for popen* files, so we can retrieve the
  4934. * exit code for the child process and return as a result of the close.
  4935. *
  4936. * This function uses the _PyPopenProcs dictionary in order to map the
  4937. * input file pointer to information about the process that was
  4938. * originally created by the popen* call that created the file pointer.
  4939. * The dictionary uses the file pointer as a key (with one entry
  4940. * inserted for each file returned by the original popen* call) and a
  4941. * single list object as the value for all files from a single call.
  4942. * The list object contains the Win32 process handle at [0], and a file
  4943. * count at [1], which is initialized to the total number of file
  4944. * handles using that list.
  4945. *
  4946. * This function closes whichever handle it is passed, and decrements
  4947. * the file count in the dictionary for the process handle pointed to
  4948. * by this file. On the last close (when the file count reaches zero),
  4949. * this function will wait for the child process and then return its
  4950. * exit code as the result of the close() operation. This permits the
  4951. * files to be closed in any order - it is always the close() of the
  4952. * final handle that will return the exit code.
  4953. *
  4954. * NOTE: This function is currently called with the GIL released.
  4955. * hence we use the GILState API to manage our state.
  4956. */
  4957. static int _PyPclose(FILE *file)
  4958. {
  4959. int result;
  4960. DWORD exit_code;
  4961. HANDLE hProcess;
  4962. PyObject *procObj, *hProcessObj, *intObj, *fileObj;
  4963. long file_count;
  4964. #ifdef WITH_THREAD
  4965. PyGILState_STATE state;
  4966. #endif
  4967. /* Close the file handle first, to ensure it can't block the
  4968. * child from exiting if it's the last handle.
  4969. */
  4970. result = fclose(file);
  4971. #ifdef WITH_THREAD
  4972. state = PyGILState_Ensure();
  4973. #endif
  4974. if (_PyPopenProcs) {
  4975. if ((fileObj = PyLong_FromVoidPtr(file)) != NULL &&
  4976. (procObj = PyDict_GetItem(_PyPopenProcs,
  4977. fileObj)) != NULL &&
  4978. (hProcessObj = PyList_GetItem(procObj,0)) != NULL &&
  4979. (intObj = PyList_GetItem(procObj,1)) != NULL) {
  4980. hProcess = PyLong_AsVoidPtr(hProcessObj);
  4981. file_count = PyInt_AsLong(intObj);
  4982. if (file_count > 1) {
  4983. /* Still other files referencing process */
  4984. file_count--;
  4985. PyList_SetItem(procObj,1,
  4986. PyInt_FromLong(file_count));
  4987. } else {
  4988. /* Last file for this process */
  4989. if (result != EOF &&
  4990. WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED &&
  4991. GetExitCodeProcess(hProcess, &exit_code)) {
  4992. /* Possible truncation here in 16-bit environments, but
  4993. * real exit codes are just the lower byte in any event.
  4994. */
  4995. result = exit_code;
  4996. } else {
  4997. /* Indicate failure - this will cause the file object
  4998. * to raise an I/O error and translate the last Win32
  4999. * error code from errno. We do have a problem with
  5000. * last errors that overlap the normal errno table,
  5001. * but that's a consistent problem with the file object.
  5002. */
  5003. if (result != EOF) {
  5004. /* If the error wasn't from the fclose(), then
  5005. * set errno for the file object error handling.
  5006. */
  5007. errno = GetLastError();
  5008. }
  5009. result = -1;
  5010. }
  5011. /* Free up the native handle at this point */
  5012. CloseHandle(hProcess);
  5013. }
  5014. /* Remove this file pointer from dictionary */
  5015. PyDict_DelItem(_PyPopenProcs, fileObj);
  5016. if (PyDict_Size(_PyPopenProcs) == 0) {
  5017. Py_DECREF(_PyPopenProcs);
  5018. _PyPopenProcs = NULL;
  5019. }
  5020. } /* if object retrieval ok */
  5021. Py_XDECREF(fileObj);
  5022. } /* if _PyPopenProcs */
  5023. #ifdef WITH_THREAD
  5024. PyGILState_Release(state);
  5025. #endif
  5026. return result;
  5027. }
  5028. #else /* which OS? */
  5029. static PyObject *
  5030. posix_popen(PyObject *self, PyObject *args)
  5031. {
  5032. char *name;
  5033. char *mode = "r";
  5034. int bufsize = -1;
  5035. FILE *fp;
  5036. PyObject *f;
  5037. if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
  5038. return NULL;
  5039. /* Strip mode of binary or text modifiers */
  5040. if (strcmp(mode, "rb") == 0 || strcmp(mode, "rt") == 0)
  5041. mode = "r";
  5042. else if (strcmp(mode, "wb") == 0 || strcmp(mode, "wt") == 0)
  5043. mode = "w";
  5044. Py_BEGIN_ALLOW_THREADS
  5045. fp = popen(name, mode);
  5046. Py_END_ALLOW_THREADS
  5047. if (fp == NULL)
  5048. return posix_error();
  5049. f = PyFile_FromFile(fp, name, mode, pclose);
  5050. if (f != NULL)
  5051. PyFile_SetBufSize(f, bufsize);
  5052. return f;
  5053. }
  5054. #endif /* PYOS_??? */
  5055. #endif /* HAVE_POPEN */
  5056. #ifdef HAVE_SETUID
  5057. PyDoc_STRVAR(posix_setuid__doc__,
  5058. "setuid(uid)\n\n\
  5059. Set the current process's user id.");
  5060. static PyObject *
  5061. posix_setuid(PyObject *self, PyObject *args)
  5062. {
  5063. long uid_arg;
  5064. uid_t uid;
  5065. if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg))
  5066. return NULL;
  5067. uid = uid_arg;
  5068. if (uid != uid_arg) {
  5069. PyErr_SetString(PyExc_OverflowError, "user id too big");
  5070. return NULL;
  5071. }
  5072. if (setuid(uid) < 0)
  5073. return posix_error();
  5074. Py_INCREF(Py_None);
  5075. return Py_None;
  5076. }
  5077. #endif /* HAVE_SETUID */
  5078. #ifdef HAVE_SETEUID
  5079. PyDoc_STRVAR(posix_seteuid__doc__,
  5080. "seteuid(uid)\n\n\
  5081. Set the current process's effective user id.");
  5082. static PyObject *
  5083. posix_seteuid (PyObject *self, PyObject *args)
  5084. {
  5085. long euid_arg;
  5086. uid_t euid;
  5087. if (!PyArg_ParseTuple(args, "l", &euid_arg))
  5088. return NULL;
  5089. euid = euid_arg;
  5090. if (euid != euid_arg) {
  5091. PyErr_SetString(PyExc_OverflowError, "user id too big");
  5092. return NULL;
  5093. }
  5094. if (seteuid(euid) < 0) {
  5095. return posix_error();
  5096. } else {
  5097. Py_INCREF(Py_None);
  5098. return Py_None;
  5099. }
  5100. }
  5101. #endif /* HAVE_SETEUID */
  5102. #ifdef HAVE_SETEGID
  5103. PyDoc_STRVAR(posix_setegid__doc__,
  5104. "setegid(gid)\n\n\
  5105. Set the current process's effective group id.");
  5106. static PyObject *
  5107. posix_setegid (PyObject *self, PyObject *args)
  5108. {
  5109. long egid_arg;
  5110. gid_t egid;
  5111. if (!PyArg_ParseTuple(args, "l", &egid_arg))
  5112. return NULL;
  5113. egid = egid_arg;
  5114. if (egid != egid_arg) {
  5115. PyErr_SetString(PyExc_OverflowError, "group id too big");
  5116. return NULL;
  5117. }
  5118. if (setegid(egid) < 0) {
  5119. return posix_error();
  5120. } else {
  5121. Py_INCREF(Py_None);
  5122. return Py_None;
  5123. }
  5124. }
  5125. #endif /* HAVE_SETEGID */
  5126. #ifdef HAVE_SETREUID
  5127. PyDoc_STRVAR(posix_setreuid__doc__,
  5128. "setreuid(ruid, euid)\n\n\
  5129. Set the current process's real and effective user ids.");
  5130. static PyObject *
  5131. posix_setreuid (PyObject *self, PyObject *args)
  5132. {
  5133. long ruid_arg, euid_arg;
  5134. uid_t ruid, euid;
  5135. if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg))
  5136. return NULL;
  5137. if (ruid_arg == -1)
  5138. ruid = (uid_t)-1; /* let the compiler choose how -1 fits */
  5139. else
  5140. ruid = ruid_arg; /* otherwise, assign from our long */
  5141. if (euid_arg == -1)
  5142. euid = (uid_t)-1;
  5143. else
  5144. euid = euid_arg;
  5145. if ((euid_arg != -1 && euid != euid_arg) ||
  5146. (ruid_arg != -1 && ruid != ruid_arg)) {
  5147. PyErr_SetString(PyExc_OverflowError, "user id too big");
  5148. return NULL;
  5149. }
  5150. if (setreuid(ruid, euid) < 0) {
  5151. return posix_error();
  5152. } else {
  5153. Py_INCREF(Py_None);
  5154. return Py_None;
  5155. }
  5156. }
  5157. #endif /* HAVE_SETREUID */
  5158. #ifdef HAVE_SETREGID
  5159. PyDoc_STRVAR(posix_setregid__doc__,
  5160. "setregid(rgid, egid)\n\n\
  5161. Set the current process's real and effective group ids.");
  5162. static PyObject *
  5163. posix_setregid (PyObject *self, PyObject *args)
  5164. {
  5165. long rgid_arg, egid_arg;
  5166. gid_t rgid, egid;
  5167. if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg))
  5168. return NULL;
  5169. if (rgid_arg == -1)
  5170. rgid = (gid_t)-1; /* let the compiler choose how -1 fits */
  5171. else
  5172. rgid = rgid_arg; /* otherwise, assign from our long */
  5173. if (egid_arg == -1)
  5174. egid = (gid_t)-1;
  5175. else
  5176. egid = egid_arg;
  5177. if ((egid_arg != -1 && egid != egid_arg) ||
  5178. (rgid_arg != -1 && rgid != rgid_arg)) {
  5179. PyErr_SetString(PyExc_OverflowError, "group id too big");
  5180. return NULL;
  5181. }
  5182. if (setregid(rgid, egid) < 0) {
  5183. return posix_error();
  5184. } else {
  5185. Py_INCREF(Py_None);
  5186. return Py_None;
  5187. }
  5188. }
  5189. #endif /* HAVE_SETREGID */
  5190. #ifdef HAVE_SETGID
  5191. PyDoc_STRVAR(posix_setgid__doc__,
  5192. "setgid(gid)\n\n\
  5193. Set the current process's group id.");
  5194. static PyObject *
  5195. posix_setgid(PyObject *self, PyObject *args)
  5196. {
  5197. long gid_arg;
  5198. gid_t gid;
  5199. if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg))
  5200. return NULL;
  5201. gid = gid_arg;
  5202. if (gid != gid_arg) {
  5203. PyErr_SetString(PyExc_OverflowError, "group id too big");
  5204. return NULL;
  5205. }
  5206. if (setgid(gid) < 0)
  5207. return posix_error();
  5208. Py_INCREF(Py_None);
  5209. return Py_None;
  5210. }
  5211. #endif /* HAVE_SETGID */
  5212. #ifdef HAVE_SETGROUPS
  5213. PyDoc_STRVAR(posix_setgroups__doc__,
  5214. "setgroups(list)\n\n\
  5215. Set the groups of the current process to list.");
  5216. static PyObject *
  5217. posix_setgroups(PyObject *self, PyObject *groups)
  5218. {
  5219. int i, len;
  5220. gid_t grouplist[MAX_GROUPS];
  5221. if (!PySequence_Check(groups)) {
  5222. PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
  5223. return NULL;
  5224. }
  5225. len = PySequence_Size(groups);
  5226. if (len > MAX_GROUPS) {
  5227. PyErr_SetString(PyExc_ValueError, "too many groups");
  5228. return NULL;
  5229. }
  5230. for(i = 0; i < len; i++) {
  5231. PyObject *elem;
  5232. elem = PySequence_GetItem(groups, i);
  5233. if (!elem)
  5234. return NULL;
  5235. if (!PyInt_Check(elem)) {
  5236. if (!PyLong_Check(elem)) {
  5237. PyErr_SetString(PyExc_TypeError,
  5238. "groups must be integers");
  5239. Py_DECREF(elem);
  5240. return NULL;
  5241. } else {
  5242. unsigned long x = PyLong_AsUnsignedLong(elem);
  5243. if (PyErr_Occurred()) {
  5244. PyErr_SetString(PyExc_TypeError,
  5245. "group id too big");
  5246. Py_DECREF(elem);
  5247. return NULL;
  5248. }
  5249. grouplist[i] = x;
  5250. /* read back to see if it fits in gid_t */
  5251. if (grouplist[i] != x) {
  5252. PyErr_SetString(PyExc_TypeError,
  5253. "group id too big");
  5254. Py_DECREF(elem);
  5255. return NULL;
  5256. }
  5257. }
  5258. } else {
  5259. long x = PyInt_AsLong(elem);
  5260. grouplist[i] = x;
  5261. if (grouplist[i] != x) {
  5262. PyErr_SetString(PyExc_TypeError,
  5263. "group id too big");
  5264. Py_DECREF(elem);
  5265. return NULL;
  5266. }
  5267. }
  5268. Py_DECREF(elem);
  5269. }
  5270. if (setgroups(len, grouplist) < 0)
  5271. return posix_error();
  5272. Py_INCREF(Py_None);
  5273. return Py_None;
  5274. }
  5275. #endif /* HAVE_SETGROUPS */
  5276. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  5277. static PyObject *
  5278. wait_helper(pid_t pid, int status, struct rusage *ru)
  5279. {
  5280. PyObject *result;
  5281. static PyObject *struct_rusage;
  5282. if (pid == -1)
  5283. return posix_error();
  5284. if (struct_rusage == NULL) {
  5285. PyObject *m = PyImport_ImportModuleNoBlock("resource");
  5286. if (m == NULL)
  5287. return NULL;
  5288. struct_rusage = PyObject_GetAttrString(m, "struct_rusage");
  5289. Py_DECREF(m);
  5290. if (struct_rusage == NULL)
  5291. return NULL;
  5292. }
  5293. /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
  5294. result = PyStructSequence_New((PyTypeObject*) struct_rusage);
  5295. if (!result)
  5296. return NULL;
  5297. #ifndef doubletime
  5298. #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
  5299. #endif
  5300. PyStructSequence_SET_ITEM(result, 0,
  5301. PyFloat_FromDouble(doubletime(ru->ru_utime)));
  5302. PyStructSequence_SET_ITEM(result, 1,
  5303. PyFloat_FromDouble(doubletime(ru->ru_stime)));
  5304. #define SET_INT(result, index, value)\
  5305. PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value))
  5306. SET_INT(result, 2, ru->ru_maxrss);
  5307. SET_INT(result, 3, ru->ru_ixrss);
  5308. SET_INT(result, 4, ru->ru_idrss);
  5309. SET_INT(result, 5, ru->ru_isrss);
  5310. SET_INT(result, 6, ru->ru_minflt);
  5311. SET_INT(result, 7, ru->ru_majflt);
  5312. SET_INT(result, 8, ru->ru_nswap);
  5313. SET_INT(result, 9, ru->ru_inblock);
  5314. SET_INT(result, 10, ru->ru_oublock);
  5315. SET_INT(result, 11, ru->ru_msgsnd);
  5316. SET_INT(result, 12, ru->ru_msgrcv);
  5317. SET_INT(result, 13, ru->ru_nsignals);
  5318. SET_INT(result, 14, ru->ru_nvcsw);
  5319. SET_INT(result, 15, ru->ru_nivcsw);
  5320. #undef SET_INT
  5321. if (PyErr_Occurred()) {
  5322. Py_DECREF(result);
  5323. return NULL;
  5324. }
  5325. return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
  5326. }
  5327. #endif /* HAVE_WAIT3 || HAVE_WAIT4 */
  5328. #ifdef HAVE_WAIT3
  5329. PyDoc_STRVAR(posix_wait3__doc__,
  5330. "wait3(options) -> (pid, status, rusage)\n\n\
  5331. Wait for completion of a child process.");
  5332. static PyObject *
  5333. posix_wait3(PyObject *self, PyObject *args)
  5334. {
  5335. pid_t pid;
  5336. int options;
  5337. struct rusage ru;
  5338. WAIT_TYPE status;
  5339. WAIT_STATUS_INT(status) = 0;
  5340. if (!PyArg_ParseTuple(args, "i:wait3", &options))
  5341. return NULL;
  5342. Py_BEGIN_ALLOW_THREADS
  5343. pid = wait3(&status, options, &ru);
  5344. Py_END_ALLOW_THREADS
  5345. return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
  5346. }
  5347. #endif /* HAVE_WAIT3 */
  5348. #ifdef HAVE_WAIT4
  5349. PyDoc_STRVAR(posix_wait4__doc__,
  5350. "wait4(pid, options) -> (pid, status, rusage)\n\n\
  5351. Wait for completion of a given child process.");
  5352. static PyObject *
  5353. posix_wait4(PyObject *self, PyObject *args)
  5354. {
  5355. pid_t pid;
  5356. int options;
  5357. struct rusage ru;
  5358. WAIT_TYPE status;
  5359. WAIT_STATUS_INT(status) = 0;
  5360. if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options))
  5361. return NULL;
  5362. Py_BEGIN_ALLOW_THREADS
  5363. pid = wait4(pid, &status, options, &ru);
  5364. Py_END_ALLOW_THREADS
  5365. return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
  5366. }
  5367. #endif /* HAVE_WAIT4 */
  5368. #ifdef HAVE_WAITPID
  5369. PyDoc_STRVAR(posix_waitpid__doc__,
  5370. "waitpid(pid, options) -> (pid, status)\n\n\
  5371. Wait for completion of a given child process.");
  5372. static PyObject *
  5373. posix_waitpid(PyObject *self, PyObject *args)
  5374. {
  5375. pid_t pid;
  5376. int options;
  5377. WAIT_TYPE status;
  5378. WAIT_STATUS_INT(status) = 0;
  5379. if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options))
  5380. return NULL;
  5381. Py_BEGIN_ALLOW_THREADS
  5382. pid = waitpid(pid, &status, options);
  5383. Py_END_ALLOW_THREADS
  5384. if (pid == -1)
  5385. return posix_error();
  5386. return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
  5387. }
  5388. #elif defined(HAVE_CWAIT)
  5389. /* MS C has a variant of waitpid() that's usable for most purposes. */
  5390. PyDoc_STRVAR(posix_waitpid__doc__,
  5391. "waitpid(pid, options) -> (pid, status << 8)\n\n"
  5392. "Wait for completion of a given process. options is ignored on Windows.");
  5393. static PyObject *
  5394. posix_waitpid(PyObject *self, PyObject *args)
  5395. {
  5396. Py_intptr_t pid;
  5397. int status, options;
  5398. if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options))
  5399. return NULL;
  5400. Py_BEGIN_ALLOW_THREADS
  5401. pid = _cwait(&status, pid, options);
  5402. Py_END_ALLOW_THREADS
  5403. if (pid == -1)
  5404. return posix_error();
  5405. /* shift the status left a byte so this is more like the POSIX waitpid */
  5406. return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8);
  5407. }
  5408. #endif /* HAVE_WAITPID || HAVE_CWAIT */
  5409. #ifdef HAVE_WAIT
  5410. PyDoc_STRVAR(posix_wait__doc__,
  5411. "wait() -> (pid, status)\n\n\
  5412. Wait for completion of a child process.");
  5413. static PyObject *
  5414. posix_wait(PyObject *self, PyObject *noargs)
  5415. {
  5416. pid_t pid;
  5417. WAIT_TYPE status;
  5418. WAIT_STATUS_INT(status) = 0;
  5419. Py_BEGIN_ALLOW_THREADS
  5420. pid = wait(&status);
  5421. Py_END_ALLOW_THREADS
  5422. if (pid == -1)
  5423. return posix_error();
  5424. return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
  5425. }
  5426. #endif
  5427. PyDoc_STRVAR(posix_lstat__doc__,
  5428. "lstat(path) -> stat result\n\n\
  5429. Like stat(path), but do not follow symbolic links.");
  5430. static PyObject *
  5431. posix_lstat(PyObject *self, PyObject *args)
  5432. {
  5433. #ifdef HAVE_LSTAT
  5434. return posix_do_stat(self, args, "et:lstat", lstat, NULL, NULL);
  5435. #else /* !HAVE_LSTAT */
  5436. #ifdef MS_WINDOWS
  5437. return posix_do_stat(self, args, "et:lstat", STAT, "U:lstat", win32_wstat);
  5438. #else
  5439. return posix_do_stat(self, args, "et:lstat", STAT, NULL, NULL);
  5440. #endif
  5441. #endif /* !HAVE_LSTAT */
  5442. }
  5443. #ifdef HAVE_READLINK
  5444. PyDoc_STRVAR(posix_readlink__doc__,
  5445. "readlink(path) -> path\n\n\
  5446. Return a string representing the path to which the symbolic link points.");
  5447. static PyObject *
  5448. posix_readlink(PyObject *self, PyObject *args)
  5449. {
  5450. PyObject* v;
  5451. char buf[MAXPATHLEN];
  5452. char *path;
  5453. int n;
  5454. #ifdef Py_USING_UNICODE
  5455. int arg_is_unicode = 0;
  5456. #endif
  5457. if (!PyArg_ParseTuple(args, "et:readlink",
  5458. Py_FileSystemDefaultEncoding, &path))
  5459. return NULL;
  5460. #ifdef Py_USING_UNICODE
  5461. v = PySequence_GetItem(args, 0);
  5462. if (v == NULL) {
  5463. PyMem_Free(path);
  5464. return NULL;
  5465. }
  5466. if (PyUnicode_Check(v)) {
  5467. arg_is_unicode = 1;
  5468. }
  5469. Py_DECREF(v);
  5470. #endif
  5471. Py_BEGIN_ALLOW_THREADS
  5472. n = readlink(path, buf, (int) sizeof buf);
  5473. Py_END_ALLOW_THREADS
  5474. if (n < 0)
  5475. return posix_error_with_allocated_filename(path);
  5476. PyMem_Free(path);
  5477. v = PyString_FromStringAndSize(buf, n);
  5478. #ifdef Py_USING_UNICODE
  5479. if (arg_is_unicode) {
  5480. PyObject *w;
  5481. w = PyUnicode_FromEncodedObject(v,
  5482. Py_FileSystemDefaultEncoding,
  5483. "strict");
  5484. if (w != NULL) {
  5485. Py_DECREF(v);
  5486. v = w;
  5487. }
  5488. else {
  5489. /* fall back to the original byte string, as
  5490. discussed in patch #683592 */
  5491. PyErr_Clear();
  5492. }
  5493. }
  5494. #endif
  5495. return v;
  5496. }
  5497. #endif /* HAVE_READLINK */
  5498. #ifdef HAVE_SYMLINK
  5499. PyDoc_STRVAR(posix_symlink__doc__,
  5500. "symlink(src, dst)\n\n\
  5501. Create a symbolic link pointing to src named dst.");
  5502. static PyObject *
  5503. posix_symlink(PyObject *self, PyObject *args)
  5504. {
  5505. return posix_2str(args, "etet:symlink", symlink);
  5506. }
  5507. #endif /* HAVE_SYMLINK */
  5508. #ifdef HAVE_TIMES
  5509. #if defined(PYCC_VACPP) && defined(PYOS_OS2)
  5510. static long
  5511. system_uptime(void)
  5512. {
  5513. ULONG value = 0;
  5514. Py_BEGIN_ALLOW_THREADS
  5515. DosQuerySysInfo(QSV_MS_COUNT, QSV_MS_COUNT, &value, sizeof(value));
  5516. Py_END_ALLOW_THREADS
  5517. return value;
  5518. }
  5519. static PyObject *
  5520. posix_times(PyObject *self, PyObject *noargs)
  5521. {
  5522. /* Currently Only Uptime is Provided -- Others Later */
  5523. return Py_BuildValue("ddddd",
  5524. (double)0 /* t.tms_utime / HZ */,
  5525. (double)0 /* t.tms_stime / HZ */,
  5526. (double)0 /* t.tms_cutime / HZ */,
  5527. (double)0 /* t.tms_cstime / HZ */,
  5528. (double)system_uptime() / 1000);
  5529. }
  5530. #else /* not OS2 */
  5531. #define NEED_TICKS_PER_SECOND
  5532. static long ticks_per_second = -1;
  5533. static PyObject *
  5534. posix_times(PyObject *self, PyObject *noargs)
  5535. {
  5536. struct tms t;
  5537. clock_t c;
  5538. errno = 0;
  5539. c = times(&t);
  5540. if (c == (clock_t) -1)
  5541. return posix_error();
  5542. return Py_BuildValue("ddddd",
  5543. (double)t.tms_utime / ticks_per_second,
  5544. (double)t.tms_stime / ticks_per_second,
  5545. (double)t.tms_cutime / ticks_per_second,
  5546. (double)t.tms_cstime / ticks_per_second,
  5547. (double)c / ticks_per_second);
  5548. }
  5549. #endif /* not OS2 */
  5550. #endif /* HAVE_TIMES */
  5551. #ifdef MS_WINDOWS
  5552. #define HAVE_TIMES /* so the method table will pick it up */
  5553. static PyObject *
  5554. posix_times(PyObject *self, PyObject *noargs)
  5555. {
  5556. FILETIME create, exit, kernel, user;
  5557. HANDLE hProc;
  5558. hProc = GetCurrentProcess();
  5559. GetProcessTimes(hProc, &create, &exit, &kernel, &user);
  5560. /* The fields of a FILETIME structure are the hi and lo part
  5561. of a 64-bit value expressed in 100 nanosecond units.
  5562. 1e7 is one second in such units; 1e-7 the inverse.
  5563. 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
  5564. */
  5565. return Py_BuildValue(
  5566. "ddddd",
  5567. (double)(user.dwHighDateTime*429.4967296 +
  5568. user.dwLowDateTime*1e-7),
  5569. (double)(kernel.dwHighDateTime*429.4967296 +
  5570. kernel.dwLowDateTime*1e-7),
  5571. (double)0,
  5572. (double)0,
  5573. (double)0);
  5574. }
  5575. #endif /* MS_WINDOWS */
  5576. #ifdef HAVE_TIMES
  5577. PyDoc_STRVAR(posix_times__doc__,
  5578. "times() -> (utime, stime, cutime, cstime, elapsed_time)\n\n\
  5579. Return a tuple of floating point numbers indicating process times.");
  5580. #endif
  5581. #ifdef HAVE_GETSID
  5582. PyDoc_STRVAR(posix_getsid__doc__,
  5583. "getsid(pid) -> sid\n\n\
  5584. Call the system call getsid().");
  5585. static PyObject *
  5586. posix_getsid(PyObject *self, PyObject *args)
  5587. {
  5588. pid_t pid;
  5589. int sid;
  5590. if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid))
  5591. return NULL;
  5592. sid = getsid(pid);
  5593. if (sid < 0)
  5594. return posix_error();
  5595. return PyInt_FromLong((long)sid);
  5596. }
  5597. #endif /* HAVE_GETSID */
  5598. #ifdef HAVE_SETSID
  5599. PyDoc_STRVAR(posix_setsid__doc__,
  5600. "setsid()\n\n\
  5601. Call the system call setsid().");
  5602. static PyObject *
  5603. posix_setsid(PyObject *self, PyObject *noargs)
  5604. {
  5605. if (setsid() < 0)
  5606. return posix_error();
  5607. Py_INCREF(Py_None);
  5608. return Py_None;
  5609. }
  5610. #endif /* HAVE_SETSID */
  5611. #ifdef HAVE_SETPGID
  5612. PyDoc_STRVAR(posix_setpgid__doc__,
  5613. "setpgid(pid, pgrp)\n\n\
  5614. Call the system call setpgid().");
  5615. static PyObject *
  5616. posix_setpgid(PyObject *self, PyObject *args)
  5617. {
  5618. pid_t pid;
  5619. int pgrp;
  5620. if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp))
  5621. return NULL;
  5622. if (setpgid(pid, pgrp) < 0)
  5623. return posix_error();
  5624. Py_INCREF(Py_None);
  5625. return Py_None;
  5626. }
  5627. #endif /* HAVE_SETPGID */
  5628. #ifdef HAVE_TCGETPGRP
  5629. PyDoc_STRVAR(posix_tcgetpgrp__doc__,
  5630. "tcgetpgrp(fd) -> pgid\n\n\
  5631. Return the process group associated with the terminal given by a fd.");
  5632. static PyObject *
  5633. posix_tcgetpgrp(PyObject *self, PyObject *args)
  5634. {
  5635. int fd;
  5636. pid_t pgid;
  5637. if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd))
  5638. return NULL;
  5639. pgid = tcgetpgrp(fd);
  5640. if (pgid < 0)
  5641. return posix_error();
  5642. return PyLong_FromPid(pgid);
  5643. }
  5644. #endif /* HAVE_TCGETPGRP */
  5645. #ifdef HAVE_TCSETPGRP
  5646. PyDoc_STRVAR(posix_tcsetpgrp__doc__,
  5647. "tcsetpgrp(fd, pgid)\n\n\
  5648. Set the process group associated with the terminal given by a fd.");
  5649. static PyObject *
  5650. posix_tcsetpgrp(PyObject *self, PyObject *args)
  5651. {
  5652. int fd;
  5653. pid_t pgid;
  5654. if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid))
  5655. return NULL;
  5656. if (tcsetpgrp(fd, pgid) < 0)
  5657. return posix_error();
  5658. Py_INCREF(Py_None);
  5659. return Py_None;
  5660. }
  5661. #endif /* HAVE_TCSETPGRP */
  5662. /* Functions acting on file descriptors */
  5663. PyDoc_STRVAR(posix_open__doc__,
  5664. "open(filename, flag [, mode=0777]) -> fd\n\n\
  5665. Open a file (for low level IO).");
  5666. static PyObject *
  5667. posix_open(PyObject *self, PyObject *args)
  5668. {
  5669. char *file = NULL;
  5670. int flag;
  5671. int mode = 0777;
  5672. int fd;
  5673. #ifdef MS_WINDOWS
  5674. PyUnicodeObject *po;
  5675. if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) {
  5676. Py_BEGIN_ALLOW_THREADS
  5677. /* PyUnicode_AS_UNICODE OK without thread
  5678. lock as it is a simple dereference. */
  5679. fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode);
  5680. Py_END_ALLOW_THREADS
  5681. if (fd < 0)
  5682. return posix_error();
  5683. return PyInt_FromLong((long)fd);
  5684. }
  5685. /* Drop the argument parsing error as narrow strings
  5686. are also valid. */
  5687. PyErr_Clear();
  5688. #endif
  5689. if (!PyArg_ParseTuple(args, "eti|i",
  5690. Py_FileSystemDefaultEncoding, &file,
  5691. &flag, &mode))
  5692. return NULL;
  5693. Py_BEGIN_ALLOW_THREADS
  5694. fd = open(file, flag, mode);
  5695. Py_END_ALLOW_THREADS
  5696. if (fd < 0)
  5697. return posix_error_with_allocated_filename(file);
  5698. PyMem_Free(file);
  5699. return PyInt_FromLong((long)fd);
  5700. }
  5701. PyDoc_STRVAR(posix_close__doc__,
  5702. "close(fd)\n\n\
  5703. Close a file descriptor (for low level IO).");
  5704. static PyObject *
  5705. posix_close(PyObject *self, PyObject *args)
  5706. {
  5707. int fd, res;
  5708. if (!PyArg_ParseTuple(args, "i:close", &fd))
  5709. return NULL;
  5710. if (!_PyVerify_fd(fd))
  5711. return posix_error();
  5712. Py_BEGIN_ALLOW_THREADS
  5713. res = close(fd);
  5714. Py_END_ALLOW_THREADS
  5715. if (res < 0)
  5716. return posix_error();
  5717. Py_INCREF(Py_None);
  5718. return Py_None;
  5719. }
  5720. PyDoc_STRVAR(posix_closerange__doc__,
  5721. "closerange(fd_low, fd_high)\n\n\
  5722. Closes all file descriptors in [fd_low, fd_high), ignoring errors.");
  5723. static PyObject *
  5724. posix_closerange(PyObject *self, PyObject *args)
  5725. {
  5726. int fd_from, fd_to, i;
  5727. if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to))
  5728. return NULL;
  5729. Py_BEGIN_ALLOW_THREADS
  5730. for (i = fd_from; i < fd_to; i++)
  5731. if (_PyVerify_fd(i))
  5732. close(i);
  5733. Py_END_ALLOW_THREADS
  5734. Py_RETURN_NONE;
  5735. }
  5736. PyDoc_STRVAR(posix_dup__doc__,
  5737. "dup(fd) -> fd2\n\n\
  5738. Return a duplicate of a file descriptor.");
  5739. static PyObject *
  5740. posix_dup(PyObject *self, PyObject *args)
  5741. {
  5742. int fd;
  5743. if (!PyArg_ParseTuple(args, "i:dup", &fd))
  5744. return NULL;
  5745. if (!_PyVerify_fd(fd))
  5746. return posix_error();
  5747. Py_BEGIN_ALLOW_THREADS
  5748. fd = dup(fd);
  5749. Py_END_ALLOW_THREADS
  5750. if (fd < 0)
  5751. return posix_error();
  5752. return PyInt_FromLong((long)fd);
  5753. }
  5754. PyDoc_STRVAR(posix_dup2__doc__,
  5755. "dup2(old_fd, new_fd)\n\n\
  5756. Duplicate file descriptor.");
  5757. static PyObject *
  5758. posix_dup2(PyObject *self, PyObject *args)
  5759. {
  5760. int fd, fd2, res;
  5761. if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2))
  5762. return NULL;
  5763. if (!_PyVerify_fd_dup2(fd, fd2))
  5764. return posix_error();
  5765. Py_BEGIN_ALLOW_THREADS
  5766. res = dup2(fd, fd2);
  5767. Py_END_ALLOW_THREADS
  5768. if (res < 0)
  5769. return posix_error();
  5770. Py_INCREF(Py_None);
  5771. return Py_None;
  5772. }
  5773. PyDoc_STRVAR(posix_lseek__doc__,
  5774. "lseek(fd, pos, how) -> newpos\n\n\
  5775. Set the current position of a file descriptor.");
  5776. static PyObject *
  5777. posix_lseek(PyObject *self, PyObject *args)
  5778. {
  5779. int fd, how;
  5780. #if defined(MS_WIN64) || defined(MS_WINDOWS)
  5781. PY_LONG_LONG pos, res;
  5782. #else
  5783. off_t pos, res;
  5784. #endif
  5785. PyObject *posobj;
  5786. if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how))
  5787. return NULL;
  5788. #ifdef SEEK_SET
  5789. /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
  5790. switch (how) {
  5791. case 0: how = SEEK_SET; break;
  5792. case 1: how = SEEK_CUR; break;
  5793. case 2: how = SEEK_END; break;
  5794. }
  5795. #endif /* SEEK_END */
  5796. #if !defined(HAVE_LARGEFILE_SUPPORT)
  5797. pos = PyInt_AsLong(posobj);
  5798. #else
  5799. pos = PyLong_Check(posobj) ?
  5800. PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
  5801. #endif
  5802. if (PyErr_Occurred())
  5803. return NULL;
  5804. if (!_PyVerify_fd(fd))
  5805. return posix_error();
  5806. Py_BEGIN_ALLOW_THREADS
  5807. #if defined(MS_WIN64) || defined(MS_WINDOWS)
  5808. res = _lseeki64(fd, pos, how);
  5809. #else
  5810. res = lseek(fd, pos, how);
  5811. #endif
  5812. Py_END_ALLOW_THREADS
  5813. if (res < 0)
  5814. return posix_error();
  5815. #if !defined(HAVE_LARGEFILE_SUPPORT)
  5816. return PyInt_FromLong(res);
  5817. #else
  5818. return PyLong_FromLongLong(res);
  5819. #endif
  5820. }
  5821. PyDoc_STRVAR(posix_read__doc__,
  5822. "read(fd, buffersize) -> string\n\n\
  5823. Read a file descriptor.");
  5824. static PyObject *
  5825. posix_read(PyObject *self, PyObject *args)
  5826. {
  5827. int fd, size, n;
  5828. PyObject *buffer;
  5829. if (!PyArg_ParseTuple(args, "ii:read", &fd, &size))
  5830. return NULL;
  5831. if (size < 0) {
  5832. errno = EINVAL;
  5833. return posix_error();
  5834. }
  5835. buffer = PyString_FromStringAndSize((char *)NULL, size);
  5836. if (buffer == NULL)
  5837. return NULL;
  5838. if (!_PyVerify_fd(fd)) {
  5839. Py_DECREF(buffer);
  5840. return posix_error();
  5841. }
  5842. Py_BEGIN_ALLOW_THREADS
  5843. n = read(fd, PyString_AsString(buffer), size);
  5844. Py_END_ALLOW_THREADS
  5845. if (n < 0) {
  5846. Py_DECREF(buffer);
  5847. return posix_error();
  5848. }
  5849. if (n != size)
  5850. _PyString_Resize(&buffer, n);
  5851. return buffer;
  5852. }
  5853. PyDoc_STRVAR(posix_write__doc__,
  5854. "write(fd, string) -> byteswritten\n\n\
  5855. Write a string to a file descriptor.");
  5856. static PyObject *
  5857. posix_write(PyObject *self, PyObject *args)
  5858. {
  5859. Py_buffer pbuf;
  5860. int fd;
  5861. Py_ssize_t size;
  5862. if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf))
  5863. return NULL;
  5864. if (!_PyVerify_fd(fd)) {
  5865. PyBuffer_Release(&pbuf);
  5866. return posix_error();
  5867. }
  5868. Py_BEGIN_ALLOW_THREADS
  5869. size = write(fd, pbuf.buf, (size_t)pbuf.len);
  5870. Py_END_ALLOW_THREADS
  5871. PyBuffer_Release(&pbuf);
  5872. if (size < 0)
  5873. return posix_error();
  5874. return PyInt_FromSsize_t(size);
  5875. }
  5876. PyDoc_STRVAR(posix_fstat__doc__,
  5877. "fstat(fd) -> stat result\n\n\
  5878. Like stat(), but for an open file descriptor.");
  5879. static PyObject *
  5880. posix_fstat(PyObject *self, PyObject *args)
  5881. {
  5882. int fd;
  5883. STRUCT_STAT st;
  5884. int res;
  5885. if (!PyArg_ParseTuple(args, "i:fstat", &fd))
  5886. return NULL;
  5887. #ifdef __VMS
  5888. /* on OpenVMS we must ensure that all bytes are written to the file */
  5889. fsync(fd);
  5890. #endif
  5891. if (!_PyVerify_fd(fd))
  5892. return posix_error();
  5893. Py_BEGIN_ALLOW_THREADS
  5894. res = FSTAT(fd, &st);
  5895. Py_END_ALLOW_THREADS
  5896. if (res != 0) {
  5897. #ifdef MS_WINDOWS
  5898. return win32_error("fstat", NULL);
  5899. #else
  5900. return posix_error();
  5901. #endif
  5902. }
  5903. return _pystat_fromstructstat(&st);
  5904. }
  5905. PyDoc_STRVAR(posix_fdopen__doc__,
  5906. "fdopen(fd [, mode='r' [, bufsize]]) -> file_object\n\n\
  5907. Return an open file object connected to a file descriptor.");
  5908. static PyObject *
  5909. posix_fdopen(PyObject *self, PyObject *args)
  5910. {
  5911. int fd;
  5912. char *orgmode = "r";
  5913. int bufsize = -1;
  5914. FILE *fp;
  5915. PyObject *f;
  5916. char *mode;
  5917. if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize))
  5918. return NULL;
  5919. /* Sanitize mode. See fileobject.c */
  5920. mode = PyMem_MALLOC(strlen(orgmode)+3);
  5921. if (!mode) {
  5922. PyErr_NoMemory();
  5923. return NULL;
  5924. }
  5925. strcpy(mode, orgmode);
  5926. if (_PyFile_SanitizeMode(mode)) {
  5927. PyMem_FREE(mode);
  5928. return NULL;
  5929. }
  5930. if (!_PyVerify_fd(fd))
  5931. return posix_error();
  5932. Py_BEGIN_ALLOW_THREADS
  5933. #if !defined(MS_WINDOWS) && defined(HAVE_FCNTL_H)
  5934. if (mode[0] == 'a') {
  5935. /* try to make sure the O_APPEND flag is set */
  5936. int flags;
  5937. flags = fcntl(fd, F_GETFL);
  5938. if (flags != -1)
  5939. fcntl(fd, F_SETFL, flags | O_APPEND);
  5940. fp = fdopen(fd, mode);
  5941. if (fp == NULL && flags != -1)
  5942. /* restore old mode if fdopen failed */
  5943. fcntl(fd, F_SETFL, flags);
  5944. } else {
  5945. fp = fdopen(fd, mode);
  5946. }
  5947. #else
  5948. fp = fdopen(fd, mode);
  5949. #endif
  5950. Py_END_ALLOW_THREADS
  5951. PyMem_FREE(mode);
  5952. if (fp == NULL)
  5953. return posix_error();
  5954. f = PyFile_FromFile(fp, "<fdopen>", orgmode, fclose);
  5955. if (f != NULL)
  5956. PyFile_SetBufSize(f, bufsize);
  5957. return f;
  5958. }
  5959. PyDoc_STRVAR(posix_isatty__doc__,
  5960. "isatty(fd) -> bool\n\n\
  5961. Return True if the file descriptor 'fd' is an open file descriptor\n\
  5962. connected to the slave end of a terminal.");
  5963. static PyObject *
  5964. posix_isatty(PyObject *self, PyObject *args)
  5965. {
  5966. int fd;
  5967. if (!PyArg_ParseTuple(args, "i:isatty", &fd))
  5968. return NULL;
  5969. if (!_PyVerify_fd(fd))
  5970. return PyBool_FromLong(0);
  5971. return PyBool_FromLong(isatty(fd));
  5972. }
  5973. #ifdef HAVE_PIPE
  5974. PyDoc_STRVAR(posix_pipe__doc__,
  5975. "pipe() -> (read_end, write_end)\n\n\
  5976. Create a pipe.");
  5977. static PyObject *
  5978. posix_pipe(PyObject *self, PyObject *noargs)
  5979. {
  5980. #if defined(PYOS_OS2)
  5981. HFILE read, write;
  5982. APIRET rc;
  5983. Py_BEGIN_ALLOW_THREADS
  5984. rc = DosCreatePipe( &read, &write, 4096);
  5985. Py_END_ALLOW_THREADS
  5986. if (rc != NO_ERROR)
  5987. return os2_error(rc);
  5988. return Py_BuildValue("(ii)", read, write);
  5989. #else
  5990. #if !defined(MS_WINDOWS)
  5991. int fds[2];
  5992. int res;
  5993. Py_BEGIN_ALLOW_THREADS
  5994. res = pipe(fds);
  5995. Py_END_ALLOW_THREADS
  5996. if (res != 0)
  5997. return posix_error();
  5998. return Py_BuildValue("(ii)", fds[0], fds[1]);
  5999. #else /* MS_WINDOWS */
  6000. HANDLE read, write;
  6001. int read_fd, write_fd;
  6002. BOOL ok;
  6003. Py_BEGIN_ALLOW_THREADS
  6004. ok = CreatePipe(&read, &write, NULL, 0);
  6005. Py_END_ALLOW_THREADS
  6006. if (!ok)
  6007. return win32_error("CreatePipe", NULL);
  6008. read_fd = _open_osfhandle((Py_intptr_t)read, 0);
  6009. write_fd = _open_osfhandle((Py_intptr_t)write, 1);
  6010. return Py_BuildValue("(ii)", read_fd, write_fd);
  6011. #endif /* MS_WINDOWS */
  6012. #endif
  6013. }
  6014. #endif /* HAVE_PIPE */
  6015. #ifdef HAVE_MKFIFO
  6016. PyDoc_STRVAR(posix_mkfifo__doc__,
  6017. "mkfifo(filename [, mode=0666])\n\n\
  6018. Create a FIFO (a POSIX named pipe).");
  6019. static PyObject *
  6020. posix_mkfifo(PyObject *self, PyObject *args)
  6021. {
  6022. char *filename;
  6023. int mode = 0666;
  6024. int res;
  6025. if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode))
  6026. return NULL;
  6027. Py_BEGIN_ALLOW_THREADS
  6028. res = mkfifo(filename, mode);
  6029. Py_END_ALLOW_THREADS
  6030. if (res < 0)
  6031. return posix_error();
  6032. Py_INCREF(Py_None);
  6033. return Py_None;
  6034. }
  6035. #endif
  6036. #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
  6037. PyDoc_STRVAR(posix_mknod__doc__,
  6038. "mknod(filename [, mode=0600, device])\n\n\
  6039. Create a filesystem node (file, device special file or named pipe)\n\
  6040. named filename. mode specifies both the permissions to use and the\n\
  6041. type of node to be created, being combined (bitwise OR) with one of\n\
  6042. S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. For S_IFCHR and S_IFBLK,\n\
  6043. device defines the newly created device special file (probably using\n\
  6044. os.makedev()), otherwise it is ignored.");
  6045. static PyObject *
  6046. posix_mknod(PyObject *self, PyObject *args)
  6047. {
  6048. char *filename;
  6049. int mode = 0600;
  6050. int device = 0;
  6051. int res;
  6052. if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device))
  6053. return NULL;
  6054. Py_BEGIN_ALLOW_THREADS
  6055. res = mknod(filename, mode, device);
  6056. Py_END_ALLOW_THREADS
  6057. if (res < 0)
  6058. return posix_error();
  6059. Py_INCREF(Py_None);
  6060. return Py_None;
  6061. }
  6062. #endif
  6063. #ifdef HAVE_DEVICE_MACROS
  6064. PyDoc_STRVAR(posix_major__doc__,
  6065. "major(device) -> major number\n\
  6066. Extracts a device major number from a raw device number.");
  6067. static PyObject *
  6068. posix_major(PyObject *self, PyObject *args)
  6069. {
  6070. int device;
  6071. if (!PyArg_ParseTuple(args, "i:major", &device))
  6072. return NULL;
  6073. return PyInt_FromLong((long)major(device));
  6074. }
  6075. PyDoc_STRVAR(posix_minor__doc__,
  6076. "minor(device) -> minor number\n\
  6077. Extracts a device minor number from a raw device number.");
  6078. static PyObject *
  6079. posix_minor(PyObject *self, PyObject *args)
  6080. {
  6081. int device;
  6082. if (!PyArg_ParseTuple(args, "i:minor", &device))
  6083. return NULL;
  6084. return PyInt_FromLong((long)minor(device));
  6085. }
  6086. PyDoc_STRVAR(posix_makedev__doc__,
  6087. "makedev(major, minor) -> device number\n\
  6088. Composes a raw device number from the major and minor device numbers.");
  6089. static PyObject *
  6090. posix_makedev(PyObject *self, PyObject *args)
  6091. {
  6092. int major, minor;
  6093. if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor))
  6094. return NULL;
  6095. return PyInt_FromLong((long)makedev(major, minor));
  6096. }
  6097. #endif /* device macros */
  6098. #ifdef HAVE_FTRUNCATE
  6099. PyDoc_STRVAR(posix_ftruncate__doc__,
  6100. "ftruncate(fd, length)\n\n\
  6101. Truncate a file to a specified length.");
  6102. static PyObject *
  6103. posix_ftruncate(PyObject *self, PyObject *args)
  6104. {
  6105. int fd;
  6106. off_t length;
  6107. int res;
  6108. PyObject *lenobj;
  6109. if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj))
  6110. return NULL;
  6111. #if !defined(HAVE_LARGEFILE_SUPPORT)
  6112. length = PyInt_AsLong(lenobj);
  6113. #else
  6114. length = PyLong_Check(lenobj) ?
  6115. PyLong_AsLongLong(lenobj) : PyInt_AsLong(lenobj);
  6116. #endif
  6117. if (PyErr_Occurred())
  6118. return NULL;
  6119. Py_BEGIN_ALLOW_THREADS
  6120. res = ftruncate(fd, length);
  6121. Py_END_ALLOW_THREADS
  6122. if (res < 0)
  6123. return posix_error();
  6124. Py_INCREF(Py_None);
  6125. return Py_None;
  6126. }
  6127. #endif
  6128. #ifdef HAVE_PUTENV
  6129. PyDoc_STRVAR(posix_putenv__doc__,
  6130. "putenv(key, value)\n\n\
  6131. Change or add an environment variable.");
  6132. /* Save putenv() parameters as values here, so we can collect them when they
  6133. * get re-set with another call for the same key. */
  6134. static PyObject *posix_putenv_garbage;
  6135. static PyObject *
  6136. posix_putenv(PyObject *self, PyObject *args)
  6137. {
  6138. char *s1, *s2;
  6139. char *newenv;
  6140. PyObject *newstr;
  6141. size_t len;
  6142. if (!PyArg_ParseTuple(args, "ss:putenv", &s1, &s2))
  6143. return NULL;
  6144. #if defined(PYOS_OS2)
  6145. if (stricmp(s1, "BEGINLIBPATH") == 0) {
  6146. APIRET rc;
  6147. rc = DosSetExtLIBPATH(s2, BEGIN_LIBPATH);
  6148. if (rc != NO_ERROR)
  6149. return os2_error(rc);
  6150. } else if (stricmp(s1, "ENDLIBPATH") == 0) {
  6151. APIRET rc;
  6152. rc = DosSetExtLIBPATH(s2, END_LIBPATH);
  6153. if (rc != NO_ERROR)
  6154. return os2_error(rc);
  6155. } else {
  6156. #endif
  6157. /* XXX This can leak memory -- not easy to fix :-( */
  6158. len = strlen(s1) + strlen(s2) + 2;
  6159. /* len includes space for a trailing \0; the size arg to
  6160. PyString_FromStringAndSize does not count that */
  6161. newstr = PyString_FromStringAndSize(NULL, (int)len - 1);
  6162. if (newstr == NULL)
  6163. return PyErr_NoMemory();
  6164. newenv = PyString_AS_STRING(newstr);
  6165. PyOS_snprintf(newenv, len, "%s=%s", s1, s2);
  6166. if (putenv(newenv)) {
  6167. Py_DECREF(newstr);
  6168. posix_error();
  6169. return NULL;
  6170. }
  6171. /* Install the first arg and newstr in posix_putenv_garbage;
  6172. * this will cause previous value to be collected. This has to
  6173. * happen after the real putenv() call because the old value
  6174. * was still accessible until then. */
  6175. if (PyDict_SetItem(posix_putenv_garbage,
  6176. PyTuple_GET_ITEM(args, 0), newstr)) {
  6177. /* really not much we can do; just leak */
  6178. PyErr_Clear();
  6179. }
  6180. else {
  6181. Py_DECREF(newstr);
  6182. }
  6183. #if defined(PYOS_OS2)
  6184. }
  6185. #endif
  6186. Py_INCREF(Py_None);
  6187. return Py_None;
  6188. }
  6189. #endif /* putenv */
  6190. #ifdef HAVE_UNSETENV
  6191. PyDoc_STRVAR(posix_unsetenv__doc__,
  6192. "unsetenv(key)\n\n\
  6193. Delete an environment variable.");
  6194. static PyObject *
  6195. posix_unsetenv(PyObject *self, PyObject *args)
  6196. {
  6197. char *s1;
  6198. if (!PyArg_ParseTuple(args, "s:unsetenv", &s1))
  6199. return NULL;
  6200. unsetenv(s1);
  6201. /* Remove the key from posix_putenv_garbage;
  6202. * this will cause it to be collected. This has to
  6203. * happen after the real unsetenv() call because the
  6204. * old value was still accessible until then.
  6205. */
  6206. if (PyDict_DelItem(posix_putenv_garbage,
  6207. PyTuple_GET_ITEM(args, 0))) {
  6208. /* really not much we can do; just leak */
  6209. PyErr_Clear();
  6210. }
  6211. Py_INCREF(Py_None);
  6212. return Py_None;
  6213. }
  6214. #endif /* unsetenv */
  6215. PyDoc_STRVAR(posix_strerror__doc__,
  6216. "strerror(code) -> string\n\n\
  6217. Translate an error code to a message string.");
  6218. static PyObject *
  6219. posix_strerror(PyObject *self, PyObject *args)
  6220. {
  6221. int code;
  6222. char *message;
  6223. if (!PyArg_ParseTuple(args, "i:strerror", &code))
  6224. return NULL;
  6225. message = strerror(code);
  6226. if (message == NULL) {
  6227. PyErr_SetString(PyExc_ValueError,
  6228. "strerror() argument out of range");
  6229. return NULL;
  6230. }
  6231. return PyString_FromString(message);
  6232. }
  6233. #ifdef HAVE_SYS_WAIT_H
  6234. #ifdef WCOREDUMP
  6235. PyDoc_STRVAR(posix_WCOREDUMP__doc__,
  6236. "WCOREDUMP(status) -> bool\n\n\
  6237. Return True if the process returning 'status' was dumped to a core file.");
  6238. static PyObject *
  6239. posix_WCOREDUMP(PyObject *self, PyObject *args)
  6240. {
  6241. WAIT_TYPE status;
  6242. WAIT_STATUS_INT(status) = 0;
  6243. if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status)))
  6244. return NULL;
  6245. return PyBool_FromLong(WCOREDUMP(status));
  6246. }
  6247. #endif /* WCOREDUMP */
  6248. #ifdef WIFCONTINUED
  6249. PyDoc_STRVAR(posix_WIFCONTINUED__doc__,
  6250. "WIFCONTINUED(status) -> bool\n\n\
  6251. Return True if the process returning 'status' was continued from a\n\
  6252. job control stop.");
  6253. static PyObject *
  6254. posix_WIFCONTINUED(PyObject *self, PyObject *args)
  6255. {
  6256. WAIT_TYPE status;
  6257. WAIT_STATUS_INT(status) = 0;
  6258. if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status)))
  6259. return NULL;
  6260. return PyBool_FromLong(WIFCONTINUED(status));
  6261. }
  6262. #endif /* WIFCONTINUED */
  6263. #ifdef WIFSTOPPED
  6264. PyDoc_STRVAR(posix_WIFSTOPPED__doc__,
  6265. "WIFSTOPPED(status) -> bool\n\n\
  6266. Return True if the process returning 'status' was stopped.");
  6267. static PyObject *
  6268. posix_WIFSTOPPED(PyObject *self, PyObject *args)
  6269. {
  6270. WAIT_TYPE status;
  6271. WAIT_STATUS_INT(status) = 0;
  6272. if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status)))
  6273. return NULL;
  6274. return PyBool_FromLong(WIFSTOPPED(status));
  6275. }
  6276. #endif /* WIFSTOPPED */
  6277. #ifdef WIFSIGNALED
  6278. PyDoc_STRVAR(posix_WIFSIGNALED__doc__,
  6279. "WIFSIGNALED(status) -> bool\n\n\
  6280. Return True if the process returning 'status' was terminated by a signal.");
  6281. static PyObject *
  6282. posix_WIFSIGNALED(PyObject *self, PyObject *args)
  6283. {
  6284. WAIT_TYPE status;
  6285. WAIT_STATUS_INT(status) = 0;
  6286. if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status)))
  6287. return NULL;
  6288. return PyBool_FromLong(WIFSIGNALED(status));
  6289. }
  6290. #endif /* WIFSIGNALED */
  6291. #ifdef WIFEXITED
  6292. PyDoc_STRVAR(posix_WIFEXITED__doc__,
  6293. "WIFEXITED(status) -> bool\n\n\
  6294. Return true if the process returning 'status' exited using the exit()\n\
  6295. system call.");
  6296. static PyObject *
  6297. posix_WIFEXITED(PyObject *self, PyObject *args)
  6298. {
  6299. WAIT_TYPE status;
  6300. WAIT_STATUS_INT(status) = 0;
  6301. if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status)))
  6302. return NULL;
  6303. return PyBool_FromLong(WIFEXITED(status));
  6304. }
  6305. #endif /* WIFEXITED */
  6306. #ifdef WEXITSTATUS
  6307. PyDoc_STRVAR(posix_WEXITSTATUS__doc__,
  6308. "WEXITSTATUS(status) -> integer\n\n\
  6309. Return the process return code from 'status'.");
  6310. static PyObject *
  6311. posix_WEXITSTATUS(PyObject *self, PyObject *args)
  6312. {
  6313. WAIT_TYPE status;
  6314. WAIT_STATUS_INT(status) = 0;
  6315. if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status)))
  6316. return NULL;
  6317. return Py_BuildValue("i", WEXITSTATUS(status));
  6318. }
  6319. #endif /* WEXITSTATUS */
  6320. #ifdef WTERMSIG
  6321. PyDoc_STRVAR(posix_WTERMSIG__doc__,
  6322. "WTERMSIG(status) -> integer\n\n\
  6323. Return the signal that terminated the process that provided the 'status'\n\
  6324. value.");
  6325. static PyObject *
  6326. posix_WTERMSIG(PyObject *self, PyObject *args)
  6327. {
  6328. WAIT_TYPE status;
  6329. WAIT_STATUS_INT(status) = 0;
  6330. if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status)))
  6331. return NULL;
  6332. return Py_BuildValue("i", WTERMSIG(status));
  6333. }
  6334. #endif /* WTERMSIG */
  6335. #ifdef WSTOPSIG
  6336. PyDoc_STRVAR(posix_WSTOPSIG__doc__,
  6337. "WSTOPSIG(status) -> integer\n\n\
  6338. Return the signal that stopped the process that provided\n\
  6339. the 'status' value.");
  6340. static PyObject *
  6341. posix_WSTOPSIG(PyObject *self, PyObject *args)
  6342. {
  6343. WAIT_TYPE status;
  6344. WAIT_STATUS_INT(status) = 0;
  6345. if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status)))
  6346. return NULL;
  6347. return Py_BuildValue("i", WSTOPSIG(status));
  6348. }
  6349. #endif /* WSTOPSIG */
  6350. #endif /* HAVE_SYS_WAIT_H */
  6351. #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
  6352. #ifdef _SCO_DS
  6353. /* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
  6354. needed definitions in sys/statvfs.h */
  6355. #define _SVID3
  6356. #endif
  6357. #include <sys/statvfs.h>
  6358. static PyObject*
  6359. _pystatvfs_fromstructstatvfs(struct statvfs st) {
  6360. PyObject *v = PyStructSequence_New(&StatVFSResultType);
  6361. if (v == NULL)
  6362. return NULL;
  6363. #if !defined(HAVE_LARGEFILE_SUPPORT)
  6364. PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize));
  6365. PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize));
  6366. PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) st.f_blocks));
  6367. PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) st.f_bfree));
  6368. PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) st.f_bavail));
  6369. PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) st.f_files));
  6370. PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong((long) st.f_ffree));
  6371. PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) st.f_favail));
  6372. PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag));
  6373. PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax));
  6374. #else
  6375. PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize));
  6376. PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize));
  6377. PyStructSequence_SET_ITEM(v, 2,
  6378. PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks));
  6379. PyStructSequence_SET_ITEM(v, 3,
  6380. PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree));
  6381. PyStructSequence_SET_ITEM(v, 4,
  6382. PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail));
  6383. PyStructSequence_SET_ITEM(v, 5,
  6384. PyLong_FromLongLong((PY_LONG_LONG) st.f_files));
  6385. PyStructSequence_SET_ITEM(v, 6,
  6386. PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree));
  6387. PyStructSequence_SET_ITEM(v, 7,
  6388. PyLong_FromLongLong((PY_LONG_LONG) st.f_favail));
  6389. PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag));
  6390. PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax));
  6391. #endif
  6392. return v;
  6393. }
  6394. PyDoc_STRVAR(posix_fstatvfs__doc__,
  6395. "fstatvfs(fd) -> statvfs result\n\n\
  6396. Perform an fstatvfs system call on the given fd.");
  6397. static PyObject *
  6398. posix_fstatvfs(PyObject *self, PyObject *args)
  6399. {
  6400. int fd, res;
  6401. struct statvfs st;
  6402. if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd))
  6403. return NULL;
  6404. Py_BEGIN_ALLOW_THREADS
  6405. res = fstatvfs(fd, &st);
  6406. Py_END_ALLOW_THREADS
  6407. if (res != 0)
  6408. return posix_error();
  6409. return _pystatvfs_fromstructstatvfs(st);
  6410. }
  6411. #endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */
  6412. #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
  6413. #include <sys/statvfs.h>
  6414. PyDoc_STRVAR(posix_statvfs__doc__,
  6415. "statvfs(path) -> statvfs result\n\n\
  6416. Perform a statvfs system call on the given path.");
  6417. static PyObject *
  6418. posix_statvfs(PyObject *self, PyObject *args)
  6419. {
  6420. char *path;
  6421. int res;
  6422. struct statvfs st;
  6423. if (!PyArg_ParseTuple(args, "s:statvfs", &path))
  6424. return NULL;
  6425. Py_BEGIN_ALLOW_THREADS
  6426. res = statvfs(path, &st);
  6427. Py_END_ALLOW_THREADS
  6428. if (res != 0)
  6429. return posix_error_with_filename(path);
  6430. return _pystatvfs_fromstructstatvfs(st);
  6431. }
  6432. #endif /* HAVE_STATVFS */
  6433. #ifdef HAVE_TEMPNAM
  6434. PyDoc_STRVAR(posix_tempnam__doc__,
  6435. "tempnam([dir[, prefix]]) -> string\n\n\
  6436. Return a unique name for a temporary file.\n\
  6437. The directory and a prefix may be specified as strings; they may be omitted\n\
  6438. or None if not needed.");
  6439. static PyObject *
  6440. posix_tempnam(PyObject *self, PyObject *args)
  6441. {
  6442. PyObject *result = NULL;
  6443. char *dir = NULL;
  6444. char *pfx = NULL;
  6445. char *name;
  6446. if (!PyArg_ParseTuple(args, "|zz:tempnam", &dir, &pfx))
  6447. return NULL;
  6448. if (PyErr_Warn(PyExc_RuntimeWarning,
  6449. "tempnam is a potential security risk to your program") < 0)
  6450. return NULL;
  6451. #ifdef MS_WINDOWS
  6452. name = _tempnam(dir, pfx);
  6453. #else
  6454. name = tempnam(dir, pfx);
  6455. #endif
  6456. if (name == NULL)
  6457. return PyErr_NoMemory();
  6458. result = PyString_FromString(name);
  6459. free(name);
  6460. return result;
  6461. }
  6462. #endif
  6463. #ifdef HAVE_TMPFILE
  6464. PyDoc_STRVAR(posix_tmpfile__doc__,
  6465. "tmpfile() -> file object\n\n\
  6466. Create a temporary file with no directory entries.");
  6467. static PyObject *
  6468. posix_tmpfile(PyObject *self, PyObject *noargs)
  6469. {
  6470. FILE *fp;
  6471. fp = tmpfile();
  6472. if (fp == NULL)
  6473. return posix_error();
  6474. return PyFile_FromFile(fp, "<tmpfile>", "w+b", fclose);
  6475. }
  6476. #endif
  6477. #ifdef HAVE_TMPNAM
  6478. PyDoc_STRVAR(posix_tmpnam__doc__,
  6479. "tmpnam() -> string\n\n\
  6480. Return a unique name for a temporary file.");
  6481. static PyObject *
  6482. posix_tmpnam(PyObject *self, PyObject *noargs)
  6483. {
  6484. char buffer[L_tmpnam];
  6485. char *name;
  6486. if (PyErr_Warn(PyExc_RuntimeWarning,
  6487. "tmpnam is a potential security risk to your program") < 0)
  6488. return NULL;
  6489. #ifdef USE_TMPNAM_R
  6490. name = tmpnam_r(buffer);
  6491. #else
  6492. name = tmpnam(buffer);
  6493. #endif
  6494. if (name == NULL) {
  6495. PyObject *err = Py_BuildValue("is", 0,
  6496. #ifdef USE_TMPNAM_R
  6497. "unexpected NULL from tmpnam_r"
  6498. #else
  6499. "unexpected NULL from tmpnam"
  6500. #endif
  6501. );
  6502. PyErr_SetObject(PyExc_OSError, err);
  6503. Py_XDECREF(err);
  6504. return NULL;
  6505. }
  6506. return PyString_FromString(buffer);
  6507. }
  6508. #endif
  6509. /* This is used for fpathconf(), pathconf(), confstr() and sysconf().
  6510. * It maps strings representing configuration variable names to
  6511. * integer values, allowing those functions to be called with the
  6512. * magic names instead of polluting the module's namespace with tons of
  6513. * rarely-used constants. There are three separate tables that use
  6514. * these definitions.
  6515. *
  6516. * This code is always included, even if none of the interfaces that
  6517. * need it are included. The #if hackery needed to avoid it would be
  6518. * sufficiently pervasive that it's not worth the loss of readability.
  6519. */
  6520. struct constdef {
  6521. char *name;
  6522. long value;
  6523. };
  6524. static int
  6525. conv_confname(PyObject *arg, int *valuep, struct constdef *table,
  6526. size_t tablesize)
  6527. {
  6528. if (PyInt_Check(arg)) {
  6529. *valuep = PyInt_AS_LONG(arg);
  6530. return 1;
  6531. }
  6532. if (PyString_Check(arg)) {
  6533. /* look up the value in the table using a binary search */
  6534. size_t lo = 0;
  6535. size_t mid;
  6536. size_t hi = tablesize;
  6537. int cmp;
  6538. char *confname = PyString_AS_STRING(arg);
  6539. while (lo < hi) {
  6540. mid = (lo + hi) / 2;
  6541. cmp = strcmp(confname, table[mid].name);
  6542. if (cmp < 0)
  6543. hi = mid;
  6544. else if (cmp > 0)
  6545. lo = mid + 1;
  6546. else {
  6547. *valuep = table[mid].value;
  6548. return 1;
  6549. }
  6550. }
  6551. PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
  6552. }
  6553. else
  6554. PyErr_SetString(PyExc_TypeError,
  6555. "configuration names must be strings or integers");
  6556. return 0;
  6557. }
  6558. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  6559. static struct constdef posix_constants_pathconf[] = {
  6560. #ifdef _PC_ABI_AIO_XFER_MAX
  6561. {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
  6562. #endif
  6563. #ifdef _PC_ABI_ASYNC_IO
  6564. {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
  6565. #endif
  6566. #ifdef _PC_ASYNC_IO
  6567. {"PC_ASYNC_IO", _PC_ASYNC_IO},
  6568. #endif
  6569. #ifdef _PC_CHOWN_RESTRICTED
  6570. {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
  6571. #endif
  6572. #ifdef _PC_FILESIZEBITS
  6573. {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
  6574. #endif
  6575. #ifdef _PC_LAST
  6576. {"PC_LAST", _PC_LAST},
  6577. #endif
  6578. #ifdef _PC_LINK_MAX
  6579. {"PC_LINK_MAX", _PC_LINK_MAX},
  6580. #endif
  6581. #ifdef _PC_MAX_CANON
  6582. {"PC_MAX_CANON", _PC_MAX_CANON},
  6583. #endif
  6584. #ifdef _PC_MAX_INPUT
  6585. {"PC_MAX_INPUT", _PC_MAX_INPUT},
  6586. #endif
  6587. #ifdef _PC_NAME_MAX
  6588. {"PC_NAME_MAX", _PC_NAME_MAX},
  6589. #endif
  6590. #ifdef _PC_NO_TRUNC
  6591. {"PC_NO_TRUNC", _PC_NO_TRUNC},
  6592. #endif
  6593. #ifdef _PC_PATH_MAX
  6594. {"PC_PATH_MAX", _PC_PATH_MAX},
  6595. #endif
  6596. #ifdef _PC_PIPE_BUF
  6597. {"PC_PIPE_BUF", _PC_PIPE_BUF},
  6598. #endif
  6599. #ifdef _PC_PRIO_IO
  6600. {"PC_PRIO_IO", _PC_PRIO_IO},
  6601. #endif
  6602. #ifdef _PC_SOCK_MAXBUF
  6603. {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
  6604. #endif
  6605. #ifdef _PC_SYNC_IO
  6606. {"PC_SYNC_IO", _PC_SYNC_IO},
  6607. #endif
  6608. #ifdef _PC_VDISABLE
  6609. {"PC_VDISABLE", _PC_VDISABLE},
  6610. #endif
  6611. };
  6612. static int
  6613. conv_path_confname(PyObject *arg, int *valuep)
  6614. {
  6615. return conv_confname(arg, valuep, posix_constants_pathconf,
  6616. sizeof(posix_constants_pathconf)
  6617. / sizeof(struct constdef));
  6618. }
  6619. #endif
  6620. #ifdef HAVE_FPATHCONF
  6621. PyDoc_STRVAR(posix_fpathconf__doc__,
  6622. "fpathconf(fd, name) -> integer\n\n\
  6623. Return the configuration limit name for the file descriptor fd.\n\
  6624. If there is no limit, return -1.");
  6625. static PyObject *
  6626. posix_fpathconf(PyObject *self, PyObject *args)
  6627. {
  6628. PyObject *result = NULL;
  6629. int name, fd;
  6630. if (PyArg_ParseTuple(args, "iO&:fpathconf", &fd,
  6631. conv_path_confname, &name)) {
  6632. long limit;
  6633. errno = 0;
  6634. limit = fpathconf(fd, name);
  6635. if (limit == -1 && errno != 0)
  6636. posix_error();
  6637. else
  6638. result = PyInt_FromLong(limit);
  6639. }
  6640. return result;
  6641. }
  6642. #endif
  6643. #ifdef HAVE_PATHCONF
  6644. PyDoc_STRVAR(posix_pathconf__doc__,
  6645. "pathconf(path, name) -> integer\n\n\
  6646. Return the configuration limit name for the file or directory path.\n\
  6647. If there is no limit, return -1.");
  6648. static PyObject *
  6649. posix_pathconf(PyObject *self, PyObject *args)
  6650. {
  6651. PyObject *result = NULL;
  6652. int name;
  6653. char *path;
  6654. if (PyArg_ParseTuple(args, "sO&:pathconf", &path,
  6655. conv_path_confname, &name)) {
  6656. long limit;
  6657. errno = 0;
  6658. limit = pathconf(path, name);
  6659. if (limit == -1 && errno != 0) {
  6660. if (errno == EINVAL)
  6661. /* could be a path or name problem */
  6662. posix_error();
  6663. else
  6664. posix_error_with_filename(path);
  6665. }
  6666. else
  6667. result = PyInt_FromLong(limit);
  6668. }
  6669. return result;
  6670. }
  6671. #endif
  6672. #ifdef HAVE_CONFSTR
  6673. static struct constdef posix_constants_confstr[] = {
  6674. #ifdef _CS_ARCHITECTURE
  6675. {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
  6676. #endif
  6677. #ifdef _CS_HOSTNAME
  6678. {"CS_HOSTNAME", _CS_HOSTNAME},
  6679. #endif
  6680. #ifdef _CS_HW_PROVIDER
  6681. {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
  6682. #endif
  6683. #ifdef _CS_HW_SERIAL
  6684. {"CS_HW_SERIAL", _CS_HW_SERIAL},
  6685. #endif
  6686. #ifdef _CS_INITTAB_NAME
  6687. {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
  6688. #endif
  6689. #ifdef _CS_LFS64_CFLAGS
  6690. {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
  6691. #endif
  6692. #ifdef _CS_LFS64_LDFLAGS
  6693. {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
  6694. #endif
  6695. #ifdef _CS_LFS64_LIBS
  6696. {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
  6697. #endif
  6698. #ifdef _CS_LFS64_LINTFLAGS
  6699. {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
  6700. #endif
  6701. #ifdef _CS_LFS_CFLAGS
  6702. {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
  6703. #endif
  6704. #ifdef _CS_LFS_LDFLAGS
  6705. {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
  6706. #endif
  6707. #ifdef _CS_LFS_LIBS
  6708. {"CS_LFS_LIBS", _CS_LFS_LIBS},
  6709. #endif
  6710. #ifdef _CS_LFS_LINTFLAGS
  6711. {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
  6712. #endif
  6713. #ifdef _CS_MACHINE
  6714. {"CS_MACHINE", _CS_MACHINE},
  6715. #endif
  6716. #ifdef _CS_PATH
  6717. {"CS_PATH", _CS_PATH},
  6718. #endif
  6719. #ifdef _CS_RELEASE
  6720. {"CS_RELEASE", _CS_RELEASE},
  6721. #endif
  6722. #ifdef _CS_SRPC_DOMAIN
  6723. {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
  6724. #endif
  6725. #ifdef _CS_SYSNAME
  6726. {"CS_SYSNAME", _CS_SYSNAME},
  6727. #endif
  6728. #ifdef _CS_VERSION
  6729. {"CS_VERSION", _CS_VERSION},
  6730. #endif
  6731. #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
  6732. {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
  6733. #endif
  6734. #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
  6735. {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
  6736. #endif
  6737. #ifdef _CS_XBS5_ILP32_OFF32_LIBS
  6738. {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
  6739. #endif
  6740. #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
  6741. {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
  6742. #endif
  6743. #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
  6744. {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
  6745. #endif
  6746. #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
  6747. {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
  6748. #endif
  6749. #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
  6750. {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
  6751. #endif
  6752. #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
  6753. {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
  6754. #endif
  6755. #ifdef _CS_XBS5_LP64_OFF64_CFLAGS
  6756. {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
  6757. #endif
  6758. #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
  6759. {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
  6760. #endif
  6761. #ifdef _CS_XBS5_LP64_OFF64_LIBS
  6762. {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
  6763. #endif
  6764. #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
  6765. {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
  6766. #endif
  6767. #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
  6768. {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
  6769. #endif
  6770. #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
  6771. {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
  6772. #endif
  6773. #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
  6774. {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
  6775. #endif
  6776. #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
  6777. {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
  6778. #endif
  6779. #ifdef _MIPS_CS_AVAIL_PROCESSORS
  6780. {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
  6781. #endif
  6782. #ifdef _MIPS_CS_BASE
  6783. {"MIPS_CS_BASE", _MIPS_CS_BASE},
  6784. #endif
  6785. #ifdef _MIPS_CS_HOSTID
  6786. {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
  6787. #endif
  6788. #ifdef _MIPS_CS_HW_NAME
  6789. {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
  6790. #endif
  6791. #ifdef _MIPS_CS_NUM_PROCESSORS
  6792. {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
  6793. #endif
  6794. #ifdef _MIPS_CS_OSREL_MAJ
  6795. {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
  6796. #endif
  6797. #ifdef _MIPS_CS_OSREL_MIN
  6798. {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
  6799. #endif
  6800. #ifdef _MIPS_CS_OSREL_PATCH
  6801. {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
  6802. #endif
  6803. #ifdef _MIPS_CS_OS_NAME
  6804. {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
  6805. #endif
  6806. #ifdef _MIPS_CS_OS_PROVIDER
  6807. {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
  6808. #endif
  6809. #ifdef _MIPS_CS_PROCESSORS
  6810. {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
  6811. #endif
  6812. #ifdef _MIPS_CS_SERIAL
  6813. {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
  6814. #endif
  6815. #ifdef _MIPS_CS_VENDOR
  6816. {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
  6817. #endif
  6818. };
  6819. static int
  6820. conv_confstr_confname(PyObject *arg, int *valuep)
  6821. {
  6822. return conv_confname(arg, valuep, posix_constants_confstr,
  6823. sizeof(posix_constants_confstr)
  6824. / sizeof(struct constdef));
  6825. }
  6826. PyDoc_STRVAR(posix_confstr__doc__,
  6827. "confstr(name) -> string\n\n\
  6828. Return a string-valued system configuration variable.");
  6829. static PyObject *
  6830. posix_confstr(PyObject *self, PyObject *args)
  6831. {
  6832. PyObject *result = NULL;
  6833. int name;
  6834. char buffer[256];
  6835. if (PyArg_ParseTuple(args, "O&:confstr", conv_confstr_confname, &name)) {
  6836. int len;
  6837. errno = 0;
  6838. len = confstr(name, buffer, sizeof(buffer));
  6839. if (len == 0) {
  6840. if (errno) {
  6841. posix_error();
  6842. }
  6843. else {
  6844. result = Py_None;
  6845. Py_INCREF(Py_None);
  6846. }
  6847. }
  6848. else {
  6849. if ((unsigned int)len >= sizeof(buffer)) {
  6850. result = PyString_FromStringAndSize(NULL, len-1);
  6851. if (result != NULL)
  6852. confstr(name, PyString_AS_STRING(result), len);
  6853. }
  6854. else
  6855. result = PyString_FromStringAndSize(buffer, len-1);
  6856. }
  6857. }
  6858. return result;
  6859. }
  6860. #endif
  6861. #ifdef HAVE_SYSCONF
  6862. static struct constdef posix_constants_sysconf[] = {
  6863. #ifdef _SC_2_CHAR_TERM
  6864. {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
  6865. #endif
  6866. #ifdef _SC_2_C_BIND
  6867. {"SC_2_C_BIND", _SC_2_C_BIND},
  6868. #endif
  6869. #ifdef _SC_2_C_DEV
  6870. {"SC_2_C_DEV", _SC_2_C_DEV},
  6871. #endif
  6872. #ifdef _SC_2_C_VERSION
  6873. {"SC_2_C_VERSION", _SC_2_C_VERSION},
  6874. #endif
  6875. #ifdef _SC_2_FORT_DEV
  6876. {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
  6877. #endif
  6878. #ifdef _SC_2_FORT_RUN
  6879. {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
  6880. #endif
  6881. #ifdef _SC_2_LOCALEDEF
  6882. {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
  6883. #endif
  6884. #ifdef _SC_2_SW_DEV
  6885. {"SC_2_SW_DEV", _SC_2_SW_DEV},
  6886. #endif
  6887. #ifdef _SC_2_UPE
  6888. {"SC_2_UPE", _SC_2_UPE},
  6889. #endif
  6890. #ifdef _SC_2_VERSION
  6891. {"SC_2_VERSION", _SC_2_VERSION},
  6892. #endif
  6893. #ifdef _SC_ABI_ASYNCHRONOUS_IO
  6894. {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
  6895. #endif
  6896. #ifdef _SC_ACL
  6897. {"SC_ACL", _SC_ACL},
  6898. #endif
  6899. #ifdef _SC_AIO_LISTIO_MAX
  6900. {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
  6901. #endif
  6902. #ifdef _SC_AIO_MAX
  6903. {"SC_AIO_MAX", _SC_AIO_MAX},
  6904. #endif
  6905. #ifdef _SC_AIO_PRIO_DELTA_MAX
  6906. {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
  6907. #endif
  6908. #ifdef _SC_ARG_MAX
  6909. {"SC_ARG_MAX", _SC_ARG_MAX},
  6910. #endif
  6911. #ifdef _SC_ASYNCHRONOUS_IO
  6912. {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
  6913. #endif
  6914. #ifdef _SC_ATEXIT_MAX
  6915. {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
  6916. #endif
  6917. #ifdef _SC_AUDIT
  6918. {"SC_AUDIT", _SC_AUDIT},
  6919. #endif
  6920. #ifdef _SC_AVPHYS_PAGES
  6921. {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
  6922. #endif
  6923. #ifdef _SC_BC_BASE_MAX
  6924. {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
  6925. #endif
  6926. #ifdef _SC_BC_DIM_MAX
  6927. {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
  6928. #endif
  6929. #ifdef _SC_BC_SCALE_MAX
  6930. {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
  6931. #endif
  6932. #ifdef _SC_BC_STRING_MAX
  6933. {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
  6934. #endif
  6935. #ifdef _SC_CAP
  6936. {"SC_CAP", _SC_CAP},
  6937. #endif
  6938. #ifdef _SC_CHARCLASS_NAME_MAX
  6939. {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
  6940. #endif
  6941. #ifdef _SC_CHAR_BIT
  6942. {"SC_CHAR_BIT", _SC_CHAR_BIT},
  6943. #endif
  6944. #ifdef _SC_CHAR_MAX
  6945. {"SC_CHAR_MAX", _SC_CHAR_MAX},
  6946. #endif
  6947. #ifdef _SC_CHAR_MIN
  6948. {"SC_CHAR_MIN", _SC_CHAR_MIN},
  6949. #endif
  6950. #ifdef _SC_CHILD_MAX
  6951. {"SC_CHILD_MAX", _SC_CHILD_MAX},
  6952. #endif
  6953. #ifdef _SC_CLK_TCK
  6954. {"SC_CLK_TCK", _SC_CLK_TCK},
  6955. #endif
  6956. #ifdef _SC_COHER_BLKSZ
  6957. {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
  6958. #endif
  6959. #ifdef _SC_COLL_WEIGHTS_MAX
  6960. {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
  6961. #endif
  6962. #ifdef _SC_DCACHE_ASSOC
  6963. {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
  6964. #endif
  6965. #ifdef _SC_DCACHE_BLKSZ
  6966. {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
  6967. #endif
  6968. #ifdef _SC_DCACHE_LINESZ
  6969. {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
  6970. #endif
  6971. #ifdef _SC_DCACHE_SZ
  6972. {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
  6973. #endif
  6974. #ifdef _SC_DCACHE_TBLKSZ
  6975. {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
  6976. #endif
  6977. #ifdef _SC_DELAYTIMER_MAX
  6978. {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
  6979. #endif
  6980. #ifdef _SC_EQUIV_CLASS_MAX
  6981. {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
  6982. #endif
  6983. #ifdef _SC_EXPR_NEST_MAX
  6984. {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
  6985. #endif
  6986. #ifdef _SC_FSYNC
  6987. {"SC_FSYNC", _SC_FSYNC},
  6988. #endif
  6989. #ifdef _SC_GETGR_R_SIZE_MAX
  6990. {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
  6991. #endif
  6992. #ifdef _SC_GETPW_R_SIZE_MAX
  6993. {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
  6994. #endif
  6995. #ifdef _SC_ICACHE_ASSOC
  6996. {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
  6997. #endif
  6998. #ifdef _SC_ICACHE_BLKSZ
  6999. {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
  7000. #endif
  7001. #ifdef _SC_ICACHE_LINESZ
  7002. {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
  7003. #endif
  7004. #ifdef _SC_ICACHE_SZ
  7005. {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
  7006. #endif
  7007. #ifdef _SC_INF
  7008. {"SC_INF", _SC_INF},
  7009. #endif
  7010. #ifdef _SC_INT_MAX
  7011. {"SC_INT_MAX", _SC_INT_MAX},
  7012. #endif
  7013. #ifdef _SC_INT_MIN
  7014. {"SC_INT_MIN", _SC_INT_MIN},
  7015. #endif
  7016. #ifdef _SC_IOV_MAX
  7017. {"SC_IOV_MAX", _SC_IOV_MAX},
  7018. #endif
  7019. #ifdef _SC_IP_SECOPTS
  7020. {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
  7021. #endif
  7022. #ifdef _SC_JOB_CONTROL
  7023. {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
  7024. #endif
  7025. #ifdef _SC_KERN_POINTERS
  7026. {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
  7027. #endif
  7028. #ifdef _SC_KERN_SIM
  7029. {"SC_KERN_SIM", _SC_KERN_SIM},
  7030. #endif
  7031. #ifdef _SC_LINE_MAX
  7032. {"SC_LINE_MAX", _SC_LINE_MAX},
  7033. #endif
  7034. #ifdef _SC_LOGIN_NAME_MAX
  7035. {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
  7036. #endif
  7037. #ifdef _SC_LOGNAME_MAX
  7038. {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
  7039. #endif
  7040. #ifdef _SC_LONG_BIT
  7041. {"SC_LONG_BIT", _SC_LONG_BIT},
  7042. #endif
  7043. #ifdef _SC_MAC
  7044. {"SC_MAC", _SC_MAC},
  7045. #endif
  7046. #ifdef _SC_MAPPED_FILES
  7047. {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
  7048. #endif
  7049. #ifdef _SC_MAXPID
  7050. {"SC_MAXPID", _SC_MAXPID},
  7051. #endif
  7052. #ifdef _SC_MB_LEN_MAX
  7053. {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
  7054. #endif
  7055. #ifdef _SC_MEMLOCK
  7056. {"SC_MEMLOCK", _SC_MEMLOCK},
  7057. #endif
  7058. #ifdef _SC_MEMLOCK_RANGE
  7059. {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
  7060. #endif
  7061. #ifdef _SC_MEMORY_PROTECTION
  7062. {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
  7063. #endif
  7064. #ifdef _SC_MESSAGE_PASSING
  7065. {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
  7066. #endif
  7067. #ifdef _SC_MMAP_FIXED_ALIGNMENT
  7068. {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
  7069. #endif
  7070. #ifdef _SC_MQ_OPEN_MAX
  7071. {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
  7072. #endif
  7073. #ifdef _SC_MQ_PRIO_MAX
  7074. {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
  7075. #endif
  7076. #ifdef _SC_NACLS_MAX
  7077. {"SC_NACLS_MAX", _SC_NACLS_MAX},
  7078. #endif
  7079. #ifdef _SC_NGROUPS_MAX
  7080. {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
  7081. #endif
  7082. #ifdef _SC_NL_ARGMAX
  7083. {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
  7084. #endif
  7085. #ifdef _SC_NL_LANGMAX
  7086. {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
  7087. #endif
  7088. #ifdef _SC_NL_MSGMAX
  7089. {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
  7090. #endif
  7091. #ifdef _SC_NL_NMAX
  7092. {"SC_NL_NMAX", _SC_NL_NMAX},
  7093. #endif
  7094. #ifdef _SC_NL_SETMAX
  7095. {"SC_NL_SETMAX", _SC_NL_SETMAX},
  7096. #endif
  7097. #ifdef _SC_NL_TEXTMAX
  7098. {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
  7099. #endif
  7100. #ifdef _SC_NPROCESSORS_CONF
  7101. {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
  7102. #endif
  7103. #ifdef _SC_NPROCESSORS_ONLN
  7104. {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
  7105. #endif
  7106. #ifdef _SC_NPROC_CONF
  7107. {"SC_NPROC_CONF", _SC_NPROC_CONF},
  7108. #endif
  7109. #ifdef _SC_NPROC_ONLN
  7110. {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
  7111. #endif
  7112. #ifdef _SC_NZERO
  7113. {"SC_NZERO", _SC_NZERO},
  7114. #endif
  7115. #ifdef _SC_OPEN_MAX
  7116. {"SC_OPEN_MAX", _SC_OPEN_MAX},
  7117. #endif
  7118. #ifdef _SC_PAGESIZE
  7119. {"SC_PAGESIZE", _SC_PAGESIZE},
  7120. #endif
  7121. #ifdef _SC_PAGE_SIZE
  7122. {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
  7123. #endif
  7124. #ifdef _SC_PASS_MAX
  7125. {"SC_PASS_MAX", _SC_PASS_MAX},
  7126. #endif
  7127. #ifdef _SC_PHYS_PAGES
  7128. {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
  7129. #endif
  7130. #ifdef _SC_PII
  7131. {"SC_PII", _SC_PII},
  7132. #endif
  7133. #ifdef _SC_PII_INTERNET
  7134. {"SC_PII_INTERNET", _SC_PII_INTERNET},
  7135. #endif
  7136. #ifdef _SC_PII_INTERNET_DGRAM
  7137. {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
  7138. #endif
  7139. #ifdef _SC_PII_INTERNET_STREAM
  7140. {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
  7141. #endif
  7142. #ifdef _SC_PII_OSI
  7143. {"SC_PII_OSI", _SC_PII_OSI},
  7144. #endif
  7145. #ifdef _SC_PII_OSI_CLTS
  7146. {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
  7147. #endif
  7148. #ifdef _SC_PII_OSI_COTS
  7149. {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
  7150. #endif
  7151. #ifdef _SC_PII_OSI_M
  7152. {"SC_PII_OSI_M", _SC_PII_OSI_M},
  7153. #endif
  7154. #ifdef _SC_PII_SOCKET
  7155. {"SC_PII_SOCKET", _SC_PII_SOCKET},
  7156. #endif
  7157. #ifdef _SC_PII_XTI
  7158. {"SC_PII_XTI", _SC_PII_XTI},
  7159. #endif
  7160. #ifdef _SC_POLL
  7161. {"SC_POLL", _SC_POLL},
  7162. #endif
  7163. #ifdef _SC_PRIORITIZED_IO
  7164. {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
  7165. #endif
  7166. #ifdef _SC_PRIORITY_SCHEDULING
  7167. {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
  7168. #endif
  7169. #ifdef _SC_REALTIME_SIGNALS
  7170. {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
  7171. #endif
  7172. #ifdef _SC_RE_DUP_MAX
  7173. {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
  7174. #endif
  7175. #ifdef _SC_RTSIG_MAX
  7176. {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
  7177. #endif
  7178. #ifdef _SC_SAVED_IDS
  7179. {"SC_SAVED_IDS", _SC_SAVED_IDS},
  7180. #endif
  7181. #ifdef _SC_SCHAR_MAX
  7182. {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
  7183. #endif
  7184. #ifdef _SC_SCHAR_MIN
  7185. {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
  7186. #endif
  7187. #ifdef _SC_SELECT
  7188. {"SC_SELECT", _SC_SELECT},
  7189. #endif
  7190. #ifdef _SC_SEMAPHORES
  7191. {"SC_SEMAPHORES", _SC_SEMAPHORES},
  7192. #endif
  7193. #ifdef _SC_SEM_NSEMS_MAX
  7194. {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
  7195. #endif
  7196. #ifdef _SC_SEM_VALUE_MAX
  7197. {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
  7198. #endif
  7199. #ifdef _SC_SHARED_MEMORY_OBJECTS
  7200. {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
  7201. #endif
  7202. #ifdef _SC_SHRT_MAX
  7203. {"SC_SHRT_MAX", _SC_SHRT_MAX},
  7204. #endif
  7205. #ifdef _SC_SHRT_MIN
  7206. {"SC_SHRT_MIN", _SC_SHRT_MIN},
  7207. #endif
  7208. #ifdef _SC_SIGQUEUE_MAX
  7209. {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
  7210. #endif
  7211. #ifdef _SC_SIGRT_MAX
  7212. {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
  7213. #endif
  7214. #ifdef _SC_SIGRT_MIN
  7215. {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
  7216. #endif
  7217. #ifdef _SC_SOFTPOWER
  7218. {"SC_SOFTPOWER", _SC_SOFTPOWER},
  7219. #endif
  7220. #ifdef _SC_SPLIT_CACHE
  7221. {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
  7222. #endif
  7223. #ifdef _SC_SSIZE_MAX
  7224. {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
  7225. #endif
  7226. #ifdef _SC_STACK_PROT
  7227. {"SC_STACK_PROT", _SC_STACK_PROT},
  7228. #endif
  7229. #ifdef _SC_STREAM_MAX
  7230. {"SC_STREAM_MAX", _SC_STREAM_MAX},
  7231. #endif
  7232. #ifdef _SC_SYNCHRONIZED_IO
  7233. {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
  7234. #endif
  7235. #ifdef _SC_THREADS
  7236. {"SC_THREADS", _SC_THREADS},
  7237. #endif
  7238. #ifdef _SC_THREAD_ATTR_STACKADDR
  7239. {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
  7240. #endif
  7241. #ifdef _SC_THREAD_ATTR_STACKSIZE
  7242. {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
  7243. #endif
  7244. #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
  7245. {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
  7246. #endif
  7247. #ifdef _SC_THREAD_KEYS_MAX
  7248. {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
  7249. #endif
  7250. #ifdef _SC_THREAD_PRIORITY_SCHEDULING
  7251. {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
  7252. #endif
  7253. #ifdef _SC_THREAD_PRIO_INHERIT
  7254. {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
  7255. #endif
  7256. #ifdef _SC_THREAD_PRIO_PROTECT
  7257. {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
  7258. #endif
  7259. #ifdef _SC_THREAD_PROCESS_SHARED
  7260. {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
  7261. #endif
  7262. #ifdef _SC_THREAD_SAFE_FUNCTIONS
  7263. {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
  7264. #endif
  7265. #ifdef _SC_THREAD_STACK_MIN
  7266. {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
  7267. #endif
  7268. #ifdef _SC_THREAD_THREADS_MAX
  7269. {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
  7270. #endif
  7271. #ifdef _SC_TIMERS
  7272. {"SC_TIMERS", _SC_TIMERS},
  7273. #endif
  7274. #ifdef _SC_TIMER_MAX
  7275. {"SC_TIMER_MAX", _SC_TIMER_MAX},
  7276. #endif
  7277. #ifdef _SC_TTY_NAME_MAX
  7278. {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
  7279. #endif
  7280. #ifdef _SC_TZNAME_MAX
  7281. {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
  7282. #endif
  7283. #ifdef _SC_T_IOV_MAX
  7284. {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
  7285. #endif
  7286. #ifdef _SC_UCHAR_MAX
  7287. {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
  7288. #endif
  7289. #ifdef _SC_UINT_MAX
  7290. {"SC_UINT_MAX", _SC_UINT_MAX},
  7291. #endif
  7292. #ifdef _SC_UIO_MAXIOV
  7293. {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
  7294. #endif
  7295. #ifdef _SC_ULONG_MAX
  7296. {"SC_ULONG_MAX", _SC_ULONG_MAX},
  7297. #endif
  7298. #ifdef _SC_USHRT_MAX
  7299. {"SC_USHRT_MAX", _SC_USHRT_MAX},
  7300. #endif
  7301. #ifdef _SC_VERSION
  7302. {"SC_VERSION", _SC_VERSION},
  7303. #endif
  7304. #ifdef _SC_WORD_BIT
  7305. {"SC_WORD_BIT", _SC_WORD_BIT},
  7306. #endif
  7307. #ifdef _SC_XBS5_ILP32_OFF32
  7308. {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
  7309. #endif
  7310. #ifdef _SC_XBS5_ILP32_OFFBIG
  7311. {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
  7312. #endif
  7313. #ifdef _SC_XBS5_LP64_OFF64
  7314. {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
  7315. #endif
  7316. #ifdef _SC_XBS5_LPBIG_OFFBIG
  7317. {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
  7318. #endif
  7319. #ifdef _SC_XOPEN_CRYPT
  7320. {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
  7321. #endif
  7322. #ifdef _SC_XOPEN_ENH_I18N
  7323. {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
  7324. #endif
  7325. #ifdef _SC_XOPEN_LEGACY
  7326. {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
  7327. #endif
  7328. #ifdef _SC_XOPEN_REALTIME
  7329. {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
  7330. #endif
  7331. #ifdef _SC_XOPEN_REALTIME_THREADS
  7332. {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
  7333. #endif
  7334. #ifdef _SC_XOPEN_SHM
  7335. {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
  7336. #endif
  7337. #ifdef _SC_XOPEN_UNIX
  7338. {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
  7339. #endif
  7340. #ifdef _SC_XOPEN_VERSION
  7341. {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
  7342. #endif
  7343. #ifdef _SC_XOPEN_XCU_VERSION
  7344. {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
  7345. #endif
  7346. #ifdef _SC_XOPEN_XPG2
  7347. {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
  7348. #endif
  7349. #ifdef _SC_XOPEN_XPG3
  7350. {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
  7351. #endif
  7352. #ifdef _SC_XOPEN_XPG4
  7353. {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
  7354. #endif
  7355. };
  7356. static int
  7357. conv_sysconf_confname(PyObject *arg, int *valuep)
  7358. {
  7359. return conv_confname(arg, valuep, posix_constants_sysconf,
  7360. sizeof(posix_constants_sysconf)
  7361. / sizeof(struct constdef));
  7362. }
  7363. PyDoc_STRVAR(posix_sysconf__doc__,
  7364. "sysconf(name) -> integer\n\n\
  7365. Return an integer-valued system configuration variable.");
  7366. static PyObject *
  7367. posix_sysconf(PyObject *self, PyObject *args)
  7368. {
  7369. PyObject *result = NULL;
  7370. int name;
  7371. if (PyArg_ParseTuple(args, "O&:sysconf", conv_sysconf_confname, &name)) {
  7372. int value;
  7373. errno = 0;
  7374. value = sysconf(name);
  7375. if (value == -1 && errno != 0)
  7376. posix_error();
  7377. else
  7378. result = PyInt_FromLong(value);
  7379. }
  7380. return result;
  7381. }
  7382. #endif
  7383. /* This code is used to ensure that the tables of configuration value names
  7384. * are in sorted order as required by conv_confname(), and also to build the
  7385. * the exported dictionaries that are used to publish information about the
  7386. * names available on the host platform.
  7387. *
  7388. * Sorting the table at runtime ensures that the table is properly ordered
  7389. * when used, even for platforms we're not able to test on. It also makes
  7390. * it easier to add additional entries to the tables.
  7391. */
  7392. static int
  7393. cmp_constdefs(const void *v1, const void *v2)
  7394. {
  7395. const struct constdef *c1 =
  7396. (const struct constdef *) v1;
  7397. const struct constdef *c2 =
  7398. (const struct constdef *) v2;
  7399. return strcmp(c1->name, c2->name);
  7400. }
  7401. static int
  7402. setup_confname_table(struct constdef *table, size_t tablesize,
  7403. char *tablename, PyObject *module)
  7404. {
  7405. PyObject *d = NULL;
  7406. size_t i;
  7407. qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
  7408. d = PyDict_New();
  7409. if (d == NULL)
  7410. return -1;
  7411. for (i=0; i < tablesize; ++i) {
  7412. PyObject *o = PyInt_FromLong(table[i].value);
  7413. if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
  7414. Py_XDECREF(o);
  7415. Py_DECREF(d);
  7416. return -1;
  7417. }
  7418. Py_DECREF(o);
  7419. }
  7420. return PyModule_AddObject(module, tablename, d);
  7421. }
  7422. /* Return -1 on failure, 0 on success. */
  7423. static int
  7424. setup_confname_tables(PyObject *module)
  7425. {
  7426. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  7427. if (setup_confname_table(posix_constants_pathconf,
  7428. sizeof(posix_constants_pathconf)
  7429. / sizeof(struct constdef),
  7430. "pathconf_names", module))
  7431. return -1;
  7432. #endif
  7433. #ifdef HAVE_CONFSTR
  7434. if (setup_confname_table(posix_constants_confstr,
  7435. sizeof(posix_constants_confstr)
  7436. / sizeof(struct constdef),
  7437. "confstr_names", module))
  7438. return -1;
  7439. #endif
  7440. #ifdef HAVE_SYSCONF
  7441. if (setup_confname_table(posix_constants_sysconf,
  7442. sizeof(posix_constants_sysconf)
  7443. / sizeof(struct constdef),
  7444. "sysconf_names", module))
  7445. return -1;
  7446. #endif
  7447. return 0;
  7448. }
  7449. PyDoc_STRVAR(posix_abort__doc__,
  7450. "abort() -> does not return!\n\n\
  7451. Abort the interpreter immediately. This 'dumps core' or otherwise fails\n\
  7452. in the hardest way possible on the hosting operating system.");
  7453. static PyObject *
  7454. posix_abort(PyObject *self, PyObject *noargs)
  7455. {
  7456. abort();
  7457. /*NOTREACHED*/
  7458. Py_FatalError("abort() called from Python code didn't abort!");
  7459. return NULL;
  7460. }
  7461. #ifdef MS_WINDOWS
  7462. PyDoc_STRVAR(win32_startfile__doc__,
  7463. "startfile(filepath [, operation]) - Start a file with its associated\n\
  7464. application.\n\
  7465. \n\
  7466. When \"operation\" is not specified or \"open\", this acts like\n\
  7467. double-clicking the file in Explorer, or giving the file name as an\n\
  7468. argument to the DOS \"start\" command: the file is opened with whatever\n\
  7469. application (if any) its extension is associated.\n\
  7470. When another \"operation\" is given, it specifies what should be done with\n\
  7471. the file. A typical operation is \"print\".\n\
  7472. \n\
  7473. startfile returns as soon as the associated application is launched.\n\
  7474. There is no option to wait for the application to close, and no way\n\
  7475. to retrieve the application's exit status.\n\
  7476. \n\
  7477. The filepath is relative to the current directory. If you want to use\n\
  7478. an absolute path, make sure the first character is not a slash (\"/\");\n\
  7479. the underlying Win32 ShellExecute function doesn't work if it is.");
  7480. static PyObject *
  7481. win32_startfile(PyObject *self, PyObject *args)
  7482. {
  7483. char *filepath;
  7484. char *operation = NULL;
  7485. HINSTANCE rc;
  7486. PyObject *unipath, *woperation = NULL;
  7487. if (!PyArg_ParseTuple(args, "U|s:startfile",
  7488. &unipath, &operation)) {
  7489. PyErr_Clear();
  7490. goto normal;
  7491. }
  7492. if (operation) {
  7493. woperation = PyUnicode_DecodeASCII(operation,
  7494. strlen(operation), NULL);
  7495. if (!woperation) {
  7496. PyErr_Clear();
  7497. operation = NULL;
  7498. goto normal;
  7499. }
  7500. }
  7501. Py_BEGIN_ALLOW_THREADS
  7502. rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0,
  7503. PyUnicode_AS_UNICODE(unipath),
  7504. NULL, NULL, SW_SHOWNORMAL);
  7505. Py_END_ALLOW_THREADS
  7506. Py_XDECREF(woperation);
  7507. if (rc <= (HINSTANCE)32) {
  7508. PyObject *errval = win32_error_unicode("startfile",
  7509. PyUnicode_AS_UNICODE(unipath));
  7510. return errval;
  7511. }
  7512. Py_INCREF(Py_None);
  7513. return Py_None;
  7514. normal:
  7515. if (!PyArg_ParseTuple(args, "et|s:startfile",
  7516. Py_FileSystemDefaultEncoding, &filepath,
  7517. &operation))
  7518. return NULL;
  7519. Py_BEGIN_ALLOW_THREADS
  7520. rc = ShellExecute((HWND)0, operation, filepath,
  7521. NULL, NULL, SW_SHOWNORMAL);
  7522. Py_END_ALLOW_THREADS
  7523. if (rc <= (HINSTANCE)32) {
  7524. PyObject *errval = win32_error("startfile", filepath);
  7525. PyMem_Free(filepath);
  7526. return errval;
  7527. }
  7528. PyMem_Free(filepath);
  7529. Py_INCREF(Py_None);
  7530. return Py_None;
  7531. }
  7532. #endif /* MS_WINDOWS */
  7533. #ifdef HAVE_GETLOADAVG
  7534. PyDoc_STRVAR(posix_getloadavg__doc__,
  7535. "getloadavg() -> (float, float, float)\n\n\
  7536. Return the number of processes in the system run queue averaged over\n\
  7537. the last 1, 5, and 15 minutes or raises OSError if the load average\n\
  7538. was unobtainable");
  7539. static PyObject *
  7540. posix_getloadavg(PyObject *self, PyObject *noargs)
  7541. {
  7542. double loadavg[3];
  7543. if (getloadavg(loadavg, 3)!=3) {
  7544. PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
  7545. return NULL;
  7546. } else
  7547. return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
  7548. }
  7549. #endif
  7550. #ifdef MS_WINDOWS
  7551. PyDoc_STRVAR(win32_urandom__doc__,
  7552. "urandom(n) -> str\n\n\
  7553. Return a string of n random bytes suitable for cryptographic use.");
  7554. typedef BOOL (WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv,\
  7555. LPCSTR pszContainer, LPCSTR pszProvider, DWORD dwProvType,\
  7556. DWORD dwFlags );
  7557. typedef BOOL (WINAPI *CRYPTGENRANDOM)(HCRYPTPROV hProv, DWORD dwLen,\
  7558. BYTE *pbBuffer );
  7559. static CRYPTGENRANDOM pCryptGenRandom = NULL;
  7560. /* This handle is never explicitly released. Instead, the operating
  7561. system will release it when the process terminates. */
  7562. static HCRYPTPROV hCryptProv = 0;
  7563. static PyObject*
  7564. win32_urandom(PyObject *self, PyObject *args)
  7565. {
  7566. int howMany;
  7567. PyObject* result;
  7568. /* Read arguments */
  7569. if (! PyArg_ParseTuple(args, "i:urandom", &howMany))
  7570. return NULL;
  7571. if (howMany < 0)
  7572. return PyErr_Format(PyExc_ValueError,
  7573. "negative argument not allowed");
  7574. if (hCryptProv == 0) {
  7575. HINSTANCE hAdvAPI32 = NULL;
  7576. CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL;
  7577. /* Obtain handle to the DLL containing CryptoAPI
  7578. This should not fail */
  7579. hAdvAPI32 = GetModuleHandle("advapi32.dll");
  7580. if(hAdvAPI32 == NULL)
  7581. return win32_error("GetModuleHandle", NULL);
  7582. /* Obtain pointers to the CryptoAPI functions
  7583. This will fail on some early versions of Win95 */
  7584. pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress(
  7585. hAdvAPI32,
  7586. "CryptAcquireContextA");
  7587. if (pCryptAcquireContext == NULL)
  7588. return PyErr_Format(PyExc_NotImplementedError,
  7589. "CryptAcquireContextA not found");
  7590. pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress(
  7591. hAdvAPI32, "CryptGenRandom");
  7592. if (pCryptGenRandom == NULL)
  7593. return PyErr_Format(PyExc_NotImplementedError,
  7594. "CryptGenRandom not found");
  7595. /* Acquire context */
  7596. if (! pCryptAcquireContext(&hCryptProv, NULL, NULL,
  7597. PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
  7598. return win32_error("CryptAcquireContext", NULL);
  7599. }
  7600. /* Allocate bytes */
  7601. result = PyString_FromStringAndSize(NULL, howMany);
  7602. if (result != NULL) {
  7603. /* Get random data */
  7604. memset(PyString_AS_STRING(result), 0, howMany); /* zero seed */
  7605. if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*)
  7606. PyString_AS_STRING(result))) {
  7607. Py_DECREF(result);
  7608. return win32_error("CryptGenRandom", NULL);
  7609. }
  7610. }
  7611. return result;
  7612. }
  7613. #endif
  7614. #ifdef __VMS
  7615. /* Use openssl random routine */
  7616. #include <openssl/rand.h>
  7617. PyDoc_STRVAR(vms_urandom__doc__,
  7618. "urandom(n) -> str\n\n\
  7619. Return a string of n random bytes suitable for cryptographic use.");
  7620. static PyObject*
  7621. vms_urandom(PyObject *self, PyObject *args)
  7622. {
  7623. int howMany;
  7624. PyObject* result;
  7625. /* Read arguments */
  7626. if (! PyArg_ParseTuple(args, "i:urandom", &howMany))
  7627. return NULL;
  7628. if (howMany < 0)
  7629. return PyErr_Format(PyExc_ValueError,
  7630. "negative argument not allowed");
  7631. /* Allocate bytes */
  7632. result = PyString_FromStringAndSize(NULL, howMany);
  7633. if (result != NULL) {
  7634. /* Get random data */
  7635. if (RAND_pseudo_bytes((unsigned char*)
  7636. PyString_AS_STRING(result),
  7637. howMany) < 0) {
  7638. Py_DECREF(result);
  7639. return PyErr_Format(PyExc_ValueError,
  7640. "RAND_pseudo_bytes");
  7641. }
  7642. }
  7643. return result;
  7644. }
  7645. #endif
  7646. #ifdef HAVE_SETRESUID
  7647. PyDoc_STRVAR(posix_setresuid__doc__,
  7648. "setresuid(ruid, euid, suid)\n\n\
  7649. Set the current process's real, effective, and saved user ids.");
  7650. static PyObject*
  7651. posix_setresuid (PyObject *self, PyObject *args)
  7652. {
  7653. /* We assume uid_t is no larger than a long. */
  7654. long ruid, euid, suid;
  7655. if (!PyArg_ParseTuple(args, "lll", &ruid, &euid, &suid))
  7656. return NULL;
  7657. if (setresuid(ruid, euid, suid) < 0)
  7658. return posix_error();
  7659. Py_RETURN_NONE;
  7660. }
  7661. #endif
  7662. #ifdef HAVE_SETRESGID
  7663. PyDoc_STRVAR(posix_setresgid__doc__,
  7664. "setresgid(rgid, egid, sgid)\n\n\
  7665. Set the current process's real, effective, and saved group ids.");
  7666. static PyObject*
  7667. posix_setresgid (PyObject *self, PyObject *args)
  7668. {
  7669. /* We assume uid_t is no larger than a long. */
  7670. long rgid, egid, sgid;
  7671. if (!PyArg_ParseTuple(args, "lll", &rgid, &egid, &sgid))
  7672. return NULL;
  7673. if (setresgid(rgid, egid, sgid) < 0)
  7674. return posix_error();
  7675. Py_RETURN_NONE;
  7676. }
  7677. #endif
  7678. #ifdef HAVE_GETRESUID
  7679. PyDoc_STRVAR(posix_getresuid__doc__,
  7680. "getresuid() -> (ruid, euid, suid)\n\n\
  7681. Get tuple of the current process's real, effective, and saved user ids.");
  7682. static PyObject*
  7683. posix_getresuid (PyObject *self, PyObject *noargs)
  7684. {
  7685. uid_t ruid, euid, suid;
  7686. long l_ruid, l_euid, l_suid;
  7687. if (getresuid(&ruid, &euid, &suid) < 0)
  7688. return posix_error();
  7689. /* Force the values into long's as we don't know the size of uid_t. */
  7690. l_ruid = ruid;
  7691. l_euid = euid;
  7692. l_suid = suid;
  7693. return Py_BuildValue("(lll)", l_ruid, l_euid, l_suid);
  7694. }
  7695. #endif
  7696. #ifdef HAVE_GETRESGID
  7697. PyDoc_STRVAR(posix_getresgid__doc__,
  7698. "getresgid() -> (rgid, egid, sgid)\n\n\
  7699. Get tuple of the current process's real, effective, and saved group ids.");
  7700. static PyObject*
  7701. posix_getresgid (PyObject *self, PyObject *noargs)
  7702. {
  7703. uid_t rgid, egid, sgid;
  7704. long l_rgid, l_egid, l_sgid;
  7705. if (getresgid(&rgid, &egid, &sgid) < 0)
  7706. return posix_error();
  7707. /* Force the values into long's as we don't know the size of uid_t. */
  7708. l_rgid = rgid;
  7709. l_egid = egid;
  7710. l_sgid = sgid;
  7711. return Py_BuildValue("(lll)", l_rgid, l_egid, l_sgid);
  7712. }
  7713. #endif
  7714. static PyMethodDef posix_methods[] = {
  7715. {"access", posix_access, METH_VARARGS, posix_access__doc__},
  7716. #ifdef HAVE_TTYNAME
  7717. {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__},
  7718. #endif
  7719. {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__},
  7720. #ifdef HAVE_CHFLAGS
  7721. {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__},
  7722. #endif /* HAVE_CHFLAGS */
  7723. {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__},
  7724. #ifdef HAVE_FCHMOD
  7725. {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__},
  7726. #endif /* HAVE_FCHMOD */
  7727. #ifdef HAVE_CHOWN
  7728. {"chown", posix_chown, METH_VARARGS, posix_chown__doc__},
  7729. #endif /* HAVE_CHOWN */
  7730. #ifdef HAVE_LCHMOD
  7731. {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__},
  7732. #endif /* HAVE_LCHMOD */
  7733. #ifdef HAVE_FCHOWN
  7734. {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__},
  7735. #endif /* HAVE_FCHOWN */
  7736. #ifdef HAVE_LCHFLAGS
  7737. {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__},
  7738. #endif /* HAVE_LCHFLAGS */
  7739. #ifdef HAVE_LCHOWN
  7740. {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__},
  7741. #endif /* HAVE_LCHOWN */
  7742. #ifdef HAVE_CHROOT
  7743. {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__},
  7744. #endif
  7745. #ifdef HAVE_CTERMID
  7746. {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__},
  7747. #endif
  7748. #ifdef HAVE_GETCWD
  7749. {"getcwd", posix_getcwd, METH_NOARGS, posix_getcwd__doc__},
  7750. #ifdef Py_USING_UNICODE
  7751. {"getcwdu", posix_getcwdu, METH_NOARGS, posix_getcwdu__doc__},
  7752. #endif
  7753. #endif
  7754. #ifdef HAVE_LINK
  7755. {"link", posix_link, METH_VARARGS, posix_link__doc__},
  7756. #endif /* HAVE_LINK */
  7757. {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__},
  7758. {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__},
  7759. {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__},
  7760. #ifdef HAVE_NICE
  7761. {"nice", posix_nice, METH_VARARGS, posix_nice__doc__},
  7762. #endif /* HAVE_NICE */
  7763. #ifdef HAVE_READLINK
  7764. {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__},
  7765. #endif /* HAVE_READLINK */
  7766. {"rename", posix_rename, METH_VARARGS, posix_rename__doc__},
  7767. {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__},
  7768. {"stat", posix_stat, METH_VARARGS, posix_stat__doc__},
  7769. {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__},
  7770. #ifdef HAVE_SYMLINK
  7771. {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__},
  7772. #endif /* HAVE_SYMLINK */
  7773. #ifdef HAVE_SYSTEM
  7774. {"system", posix_system, METH_VARARGS, posix_system__doc__},
  7775. #endif
  7776. {"umask", posix_umask, METH_VARARGS, posix_umask__doc__},
  7777. #ifdef HAVE_UNAME
  7778. {"uname", posix_uname, METH_NOARGS, posix_uname__doc__},
  7779. #endif /* HAVE_UNAME */
  7780. {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__},
  7781. {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__},
  7782. {"utime", posix_utime, METH_VARARGS, posix_utime__doc__},
  7783. #ifdef HAVE_TIMES
  7784. {"times", posix_times, METH_NOARGS, posix_times__doc__},
  7785. #endif /* HAVE_TIMES */
  7786. {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__},
  7787. #ifdef HAVE_EXECV
  7788. {"execv", posix_execv, METH_VARARGS, posix_execv__doc__},
  7789. {"execve", posix_execve, METH_VARARGS, posix_execve__doc__},
  7790. #endif /* HAVE_EXECV */
  7791. #ifdef HAVE_SPAWNV
  7792. {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__},
  7793. {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__},
  7794. #if defined(PYOS_OS2)
  7795. {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__},
  7796. {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__},
  7797. #endif /* PYOS_OS2 */
  7798. #endif /* HAVE_SPAWNV */
  7799. #ifdef HAVE_FORK1
  7800. {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__},
  7801. #endif /* HAVE_FORK1 */
  7802. #ifdef HAVE_FORK
  7803. {"fork", posix_fork, METH_NOARGS, posix_fork__doc__},
  7804. #endif /* HAVE_FORK */
  7805. #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
  7806. {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__},
  7807. #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */
  7808. #ifdef HAVE_FORKPTY
  7809. {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__},
  7810. #endif /* HAVE_FORKPTY */
  7811. #ifdef HAVE_GETEGID
  7812. {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__},
  7813. #endif /* HAVE_GETEGID */
  7814. #ifdef HAVE_GETEUID
  7815. {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__},
  7816. #endif /* HAVE_GETEUID */
  7817. #ifdef HAVE_GETGID
  7818. {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__},
  7819. #endif /* HAVE_GETGID */
  7820. #ifdef HAVE_GETGROUPS
  7821. {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__},
  7822. #endif
  7823. {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__},
  7824. #ifdef HAVE_GETPGRP
  7825. {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__},
  7826. #endif /* HAVE_GETPGRP */
  7827. #ifdef HAVE_GETPPID
  7828. {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__},
  7829. #endif /* HAVE_GETPPID */
  7830. #ifdef HAVE_GETUID
  7831. {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__},
  7832. #endif /* HAVE_GETUID */
  7833. #ifdef HAVE_GETLOGIN
  7834. {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__},
  7835. #endif
  7836. #ifdef HAVE_KILL
  7837. {"kill", posix_kill, METH_VARARGS, posix_kill__doc__},
  7838. #endif /* HAVE_KILL */
  7839. #ifdef HAVE_KILLPG
  7840. {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__},
  7841. #endif /* HAVE_KILLPG */
  7842. #ifdef HAVE_PLOCK
  7843. {"plock", posix_plock, METH_VARARGS, posix_plock__doc__},
  7844. #endif /* HAVE_PLOCK */
  7845. #ifdef HAVE_POPEN
  7846. {"popen", posix_popen, METH_VARARGS, posix_popen__doc__},
  7847. #ifdef MS_WINDOWS
  7848. {"popen2", win32_popen2, METH_VARARGS},
  7849. {"popen3", win32_popen3, METH_VARARGS},
  7850. {"popen4", win32_popen4, METH_VARARGS},
  7851. {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__},
  7852. {"kill", win32_kill, METH_VARARGS, win32_kill__doc__},
  7853. #else
  7854. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  7855. {"popen2", os2emx_popen2, METH_VARARGS},
  7856. {"popen3", os2emx_popen3, METH_VARARGS},
  7857. {"popen4", os2emx_popen4, METH_VARARGS},
  7858. #endif
  7859. #endif
  7860. #endif /* HAVE_POPEN */
  7861. #ifdef HAVE_SETUID
  7862. {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__},
  7863. #endif /* HAVE_SETUID */
  7864. #ifdef HAVE_SETEUID
  7865. {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__},
  7866. #endif /* HAVE_SETEUID */
  7867. #ifdef HAVE_SETEGID
  7868. {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__},
  7869. #endif /* HAVE_SETEGID */
  7870. #ifdef HAVE_SETREUID
  7871. {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__},
  7872. #endif /* HAVE_SETREUID */
  7873. #ifdef HAVE_SETREGID
  7874. {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__},
  7875. #endif /* HAVE_SETREGID */
  7876. #ifdef HAVE_SETGID
  7877. {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__},
  7878. #endif /* HAVE_SETGID */
  7879. #ifdef HAVE_SETGROUPS
  7880. {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__},
  7881. #endif /* HAVE_SETGROUPS */
  7882. #ifdef HAVE_INITGROUPS
  7883. {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
  7884. #endif /* HAVE_INITGROUPS */
  7885. #ifdef HAVE_GETPGID
  7886. {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__},
  7887. #endif /* HAVE_GETPGID */
  7888. #ifdef HAVE_SETPGRP
  7889. {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__},
  7890. #endif /* HAVE_SETPGRP */
  7891. #ifdef HAVE_WAIT
  7892. {"wait", posix_wait, METH_NOARGS, posix_wait__doc__},
  7893. #endif /* HAVE_WAIT */
  7894. #ifdef HAVE_WAIT3
  7895. {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__},
  7896. #endif /* HAVE_WAIT3 */
  7897. #ifdef HAVE_WAIT4
  7898. {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__},
  7899. #endif /* HAVE_WAIT4 */
  7900. #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT)
  7901. {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__},
  7902. #endif /* HAVE_WAITPID */
  7903. #ifdef HAVE_GETSID
  7904. {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__},
  7905. #endif /* HAVE_GETSID */
  7906. #ifdef HAVE_SETSID
  7907. {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__},
  7908. #endif /* HAVE_SETSID */
  7909. #ifdef HAVE_SETPGID
  7910. {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__},
  7911. #endif /* HAVE_SETPGID */
  7912. #ifdef HAVE_TCGETPGRP
  7913. {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__},
  7914. #endif /* HAVE_TCGETPGRP */
  7915. #ifdef HAVE_TCSETPGRP
  7916. {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__},
  7917. #endif /* HAVE_TCSETPGRP */
  7918. {"open", posix_open, METH_VARARGS, posix_open__doc__},
  7919. {"close", posix_close, METH_VARARGS, posix_close__doc__},
  7920. {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__},
  7921. {"dup", posix_dup, METH_VARARGS, posix_dup__doc__},
  7922. {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__},
  7923. {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__},
  7924. {"read", posix_read, METH_VARARGS, posix_read__doc__},
  7925. {"write", posix_write, METH_VARARGS, posix_write__doc__},
  7926. {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__},
  7927. {"fdopen", posix_fdopen, METH_VARARGS, posix_fdopen__doc__},
  7928. {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__},
  7929. #ifdef HAVE_PIPE
  7930. {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__},
  7931. #endif
  7932. #ifdef HAVE_MKFIFO
  7933. {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__},
  7934. #endif
  7935. #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
  7936. {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__},
  7937. #endif
  7938. #ifdef HAVE_DEVICE_MACROS
  7939. {"major", posix_major, METH_VARARGS, posix_major__doc__},
  7940. {"minor", posix_minor, METH_VARARGS, posix_minor__doc__},
  7941. {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__},
  7942. #endif
  7943. #ifdef HAVE_FTRUNCATE
  7944. {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__},
  7945. #endif
  7946. #ifdef HAVE_PUTENV
  7947. {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__},
  7948. #endif
  7949. #ifdef HAVE_UNSETENV
  7950. {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__},
  7951. #endif
  7952. {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__},
  7953. #ifdef HAVE_FCHDIR
  7954. {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__},
  7955. #endif
  7956. #ifdef HAVE_FSYNC
  7957. {"fsync", posix_fsync, METH_O, posix_fsync__doc__},
  7958. #endif
  7959. #ifdef HAVE_FDATASYNC
  7960. {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__},
  7961. #endif
  7962. #ifdef HAVE_SYS_WAIT_H
  7963. #ifdef WCOREDUMP
  7964. {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__},
  7965. #endif /* WCOREDUMP */
  7966. #ifdef WIFCONTINUED
  7967. {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__},
  7968. #endif /* WIFCONTINUED */
  7969. #ifdef WIFSTOPPED
  7970. {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__},
  7971. #endif /* WIFSTOPPED */
  7972. #ifdef WIFSIGNALED
  7973. {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__},
  7974. #endif /* WIFSIGNALED */
  7975. #ifdef WIFEXITED
  7976. {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__},
  7977. #endif /* WIFEXITED */
  7978. #ifdef WEXITSTATUS
  7979. {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__},
  7980. #endif /* WEXITSTATUS */
  7981. #ifdef WTERMSIG
  7982. {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__},
  7983. #endif /* WTERMSIG */
  7984. #ifdef WSTOPSIG
  7985. {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__},
  7986. #endif /* WSTOPSIG */
  7987. #endif /* HAVE_SYS_WAIT_H */
  7988. #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
  7989. {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__},
  7990. #endif
  7991. #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
  7992. {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__},
  7993. #endif
  7994. #ifdef HAVE_TMPFILE
  7995. {"tmpfile", posix_tmpfile, METH_NOARGS, posix_tmpfile__doc__},
  7996. #endif
  7997. #ifdef HAVE_TEMPNAM
  7998. {"tempnam", posix_tempnam, METH_VARARGS, posix_tempnam__doc__},
  7999. #endif
  8000. #ifdef HAVE_TMPNAM
  8001. {"tmpnam", posix_tmpnam, METH_NOARGS, posix_tmpnam__doc__},
  8002. #endif
  8003. #ifdef HAVE_CONFSTR
  8004. {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__},
  8005. #endif
  8006. #ifdef HAVE_SYSCONF
  8007. {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__},
  8008. #endif
  8009. #ifdef HAVE_FPATHCONF
  8010. {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__},
  8011. #endif
  8012. #ifdef HAVE_PATHCONF
  8013. {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__},
  8014. #endif
  8015. {"abort", posix_abort, METH_NOARGS, posix_abort__doc__},
  8016. #ifdef MS_WINDOWS
  8017. {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL},
  8018. #endif
  8019. #ifdef HAVE_GETLOADAVG
  8020. {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__},
  8021. #endif
  8022. #ifdef MS_WINDOWS
  8023. {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__},
  8024. #endif
  8025. #ifdef __VMS
  8026. {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__},
  8027. #endif
  8028. #ifdef HAVE_SETRESUID
  8029. {"setresuid", posix_setresuid, METH_VARARGS, posix_setresuid__doc__},
  8030. #endif
  8031. #ifdef HAVE_SETRESGID
  8032. {"setresgid", posix_setresgid, METH_VARARGS, posix_setresgid__doc__},
  8033. #endif
  8034. #ifdef HAVE_GETRESUID
  8035. {"getresuid", posix_getresuid, METH_NOARGS, posix_getresuid__doc__},
  8036. #endif
  8037. #ifdef HAVE_GETRESGID
  8038. {"getresgid", posix_getresgid, METH_NOARGS, posix_getresgid__doc__},
  8039. #endif
  8040. {NULL, NULL} /* Sentinel */
  8041. };
  8042. static int
  8043. ins(PyObject *module, char *symbol, long value)
  8044. {
  8045. return PyModule_AddIntConstant(module, symbol, value);
  8046. }
  8047. #if defined(PYOS_OS2)
  8048. /* Insert Platform-Specific Constant Values (Strings & Numbers) of Common Use */
  8049. static int insertvalues(PyObject *module)
  8050. {
  8051. APIRET rc;
  8052. ULONG values[QSV_MAX+1];
  8053. PyObject *v;
  8054. char *ver, tmp[50];
  8055. Py_BEGIN_ALLOW_THREADS
  8056. rc = DosQuerySysInfo(1L, QSV_MAX, &values[1], sizeof(ULONG) * QSV_MAX);
  8057. Py_END_ALLOW_THREADS
  8058. if (rc != NO_ERROR) {
  8059. os2_error(rc);
  8060. return -1;
  8061. }
  8062. if (ins(module, "meminstalled", values[QSV_TOTPHYSMEM])) return -1;
  8063. if (ins(module, "memkernel", values[QSV_TOTRESMEM])) return -1;
  8064. if (ins(module, "memvirtual", values[QSV_TOTAVAILMEM])) return -1;
  8065. if (ins(module, "maxpathlen", values[QSV_MAX_PATH_LENGTH])) return -1;
  8066. if (ins(module, "maxnamelen", values[QSV_MAX_COMP_LENGTH])) return -1;
  8067. if (ins(module, "revision", values[QSV_VERSION_REVISION])) return -1;
  8068. if (ins(module, "timeslice", values[QSV_MIN_SLICE])) return -1;
  8069. switch (values[QSV_VERSION_MINOR]) {
  8070. case 0: ver = "2.00"; break;
  8071. case 10: ver = "2.10"; break;
  8072. case 11: ver = "2.11"; break;
  8073. case 30: ver = "3.00"; break;
  8074. case 40: ver = "4.00"; break;
  8075. case 50: ver = "5.00"; break;
  8076. default:
  8077. PyOS_snprintf(tmp, sizeof(tmp),
  8078. "%d-%d", values[QSV_VERSION_MAJOR],
  8079. values[QSV_VERSION_MINOR]);
  8080. ver = &tmp[0];
  8081. }
  8082. /* Add Indicator of the Version of the Operating System */
  8083. if (PyModule_AddStringConstant(module, "version", tmp) < 0)
  8084. return -1;
  8085. /* Add Indicator of Which Drive was Used to Boot the System */
  8086. tmp[0] = 'A' + values[QSV_BOOT_DRIVE] - 1;
  8087. tmp[1] = ':';
  8088. tmp[2] = '\0';
  8089. return PyModule_AddStringConstant(module, "bootdrive", tmp);
  8090. }
  8091. #endif
  8092. static int
  8093. all_ins(PyObject *d)
  8094. {
  8095. #ifdef F_OK
  8096. if (ins(d, "F_OK", (long)F_OK)) return -1;
  8097. #endif
  8098. #ifdef R_OK
  8099. if (ins(d, "R_OK", (long)R_OK)) return -1;
  8100. #endif
  8101. #ifdef W_OK
  8102. if (ins(d, "W_OK", (long)W_OK)) return -1;
  8103. #endif
  8104. #ifdef X_OK
  8105. if (ins(d, "X_OK", (long)X_OK)) return -1;
  8106. #endif
  8107. #ifdef NGROUPS_MAX
  8108. if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1;
  8109. #endif
  8110. #ifdef TMP_MAX
  8111. if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1;
  8112. #endif
  8113. #ifdef WCONTINUED
  8114. if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1;
  8115. #endif
  8116. #ifdef WNOHANG
  8117. if (ins(d, "WNOHANG", (long)WNOHANG)) return -1;
  8118. #endif
  8119. #ifdef WUNTRACED
  8120. if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1;
  8121. #endif
  8122. #ifdef O_RDONLY
  8123. if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1;
  8124. #endif
  8125. #ifdef O_WRONLY
  8126. if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1;
  8127. #endif
  8128. #ifdef O_RDWR
  8129. if (ins(d, "O_RDWR", (long)O_RDWR)) return -1;
  8130. #endif
  8131. #ifdef O_NDELAY
  8132. if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1;
  8133. #endif
  8134. #ifdef O_NONBLOCK
  8135. if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1;
  8136. #endif
  8137. #ifdef O_APPEND
  8138. if (ins(d, "O_APPEND", (long)O_APPEND)) return -1;
  8139. #endif
  8140. #ifdef O_DSYNC
  8141. if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1;
  8142. #endif
  8143. #ifdef O_RSYNC
  8144. if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1;
  8145. #endif
  8146. #ifdef O_SYNC
  8147. if (ins(d, "O_SYNC", (long)O_SYNC)) return -1;
  8148. #endif
  8149. #ifdef O_NOCTTY
  8150. if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1;
  8151. #endif
  8152. #ifdef O_CREAT
  8153. if (ins(d, "O_CREAT", (long)O_CREAT)) return -1;
  8154. #endif
  8155. #ifdef O_EXCL
  8156. if (ins(d, "O_EXCL", (long)O_EXCL)) return -1;
  8157. #endif
  8158. #ifdef O_TRUNC
  8159. if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1;
  8160. #endif
  8161. #ifdef O_BINARY
  8162. if (ins(d, "O_BINARY", (long)O_BINARY)) return -1;
  8163. #endif
  8164. #ifdef O_TEXT
  8165. if (ins(d, "O_TEXT", (long)O_TEXT)) return -1;
  8166. #endif
  8167. #ifdef O_LARGEFILE
  8168. if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1;
  8169. #endif
  8170. #ifdef O_SHLOCK
  8171. if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1;
  8172. #endif
  8173. #ifdef O_EXLOCK
  8174. if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1;
  8175. #endif
  8176. /* MS Windows */
  8177. #ifdef O_NOINHERIT
  8178. /* Don't inherit in child processes. */
  8179. if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1;
  8180. #endif
  8181. #ifdef _O_SHORT_LIVED
  8182. /* Optimize for short life (keep in memory). */
  8183. /* MS forgot to define this one with a non-underscore form too. */
  8184. if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1;
  8185. #endif
  8186. #ifdef O_TEMPORARY
  8187. /* Automatically delete when last handle is closed. */
  8188. if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1;
  8189. #endif
  8190. #ifdef O_RANDOM
  8191. /* Optimize for random access. */
  8192. if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1;
  8193. #endif
  8194. #ifdef O_SEQUENTIAL
  8195. /* Optimize for sequential access. */
  8196. if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1;
  8197. #endif
  8198. /* GNU extensions. */
  8199. #ifdef O_ASYNC
  8200. /* Send a SIGIO signal whenever input or output
  8201. becomes available on file descriptor */
  8202. if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1;
  8203. #endif
  8204. #ifdef O_DIRECT
  8205. /* Direct disk access. */
  8206. if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1;
  8207. #endif
  8208. #ifdef O_DIRECTORY
  8209. /* Must be a directory. */
  8210. if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1;
  8211. #endif
  8212. #ifdef O_NOFOLLOW
  8213. /* Do not follow links. */
  8214. if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1;
  8215. #endif
  8216. #ifdef O_NOATIME
  8217. /* Do not update the access time. */
  8218. if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1;
  8219. #endif
  8220. /* These come from sysexits.h */
  8221. #ifdef EX_OK
  8222. if (ins(d, "EX_OK", (long)EX_OK)) return -1;
  8223. #endif /* EX_OK */
  8224. #ifdef EX_USAGE
  8225. if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1;
  8226. #endif /* EX_USAGE */
  8227. #ifdef EX_DATAERR
  8228. if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1;
  8229. #endif /* EX_DATAERR */
  8230. #ifdef EX_NOINPUT
  8231. if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1;
  8232. #endif /* EX_NOINPUT */
  8233. #ifdef EX_NOUSER
  8234. if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1;
  8235. #endif /* EX_NOUSER */
  8236. #ifdef EX_NOHOST
  8237. if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1;
  8238. #endif /* EX_NOHOST */
  8239. #ifdef EX_UNAVAILABLE
  8240. if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1;
  8241. #endif /* EX_UNAVAILABLE */
  8242. #ifdef EX_SOFTWARE
  8243. if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1;
  8244. #endif /* EX_SOFTWARE */
  8245. #ifdef EX_OSERR
  8246. if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1;
  8247. #endif /* EX_OSERR */
  8248. #ifdef EX_OSFILE
  8249. if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1;
  8250. #endif /* EX_OSFILE */
  8251. #ifdef EX_CANTCREAT
  8252. if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1;
  8253. #endif /* EX_CANTCREAT */
  8254. #ifdef EX_IOERR
  8255. if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1;
  8256. #endif /* EX_IOERR */
  8257. #ifdef EX_TEMPFAIL
  8258. if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1;
  8259. #endif /* EX_TEMPFAIL */
  8260. #ifdef EX_PROTOCOL
  8261. if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1;
  8262. #endif /* EX_PROTOCOL */
  8263. #ifdef EX_NOPERM
  8264. if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1;
  8265. #endif /* EX_NOPERM */
  8266. #ifdef EX_CONFIG
  8267. if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1;
  8268. #endif /* EX_CONFIG */
  8269. #ifdef EX_NOTFOUND
  8270. if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1;
  8271. #endif /* EX_NOTFOUND */
  8272. #ifdef HAVE_SPAWNV
  8273. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  8274. if (ins(d, "P_WAIT", (long)P_WAIT)) return -1;
  8275. if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1;
  8276. if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1;
  8277. if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1;
  8278. if (ins(d, "P_SESSION", (long)P_SESSION)) return -1;
  8279. if (ins(d, "P_DETACH", (long)P_DETACH)) return -1;
  8280. if (ins(d, "P_PM", (long)P_PM)) return -1;
  8281. if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1;
  8282. if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1;
  8283. if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1;
  8284. if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1;
  8285. if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1;
  8286. if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1;
  8287. if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1;
  8288. if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1;
  8289. if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1;
  8290. if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1;
  8291. if (ins(d, "P_TILDE", (long)P_TILDE)) return -1;
  8292. if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1;
  8293. if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1;
  8294. #else
  8295. if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1;
  8296. if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1;
  8297. if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1;
  8298. if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1;
  8299. if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1;
  8300. #endif
  8301. #endif
  8302. #if defined(PYOS_OS2)
  8303. if (insertvalues(d)) return -1;
  8304. #endif
  8305. return 0;
  8306. }
  8307. #if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__)) && !defined(__QNX__)
  8308. #define INITFUNC initnt
  8309. #define MODNAME "nt"
  8310. #elif defined(PYOS_OS2)
  8311. #define INITFUNC initos2
  8312. #define MODNAME "os2"
  8313. #else
  8314. #define INITFUNC initposix
  8315. #define MODNAME "posix"
  8316. #endif
  8317. PyMODINIT_FUNC
  8318. INITFUNC(void)
  8319. {
  8320. PyObject *m, *v;
  8321. m = Py_InitModule3(MODNAME,
  8322. posix_methods,
  8323. posix__doc__);
  8324. if (m == NULL)
  8325. return;
  8326. /* Initialize environ dictionary */
  8327. v = convertenviron();
  8328. Py_XINCREF(v);
  8329. if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
  8330. return;
  8331. Py_DECREF(v);
  8332. if (all_ins(m))
  8333. return;
  8334. if (setup_confname_tables(m))
  8335. return;
  8336. Py_INCREF(PyExc_OSError);
  8337. PyModule_AddObject(m, "error", PyExc_OSError);
  8338. #ifdef HAVE_PUTENV
  8339. if (posix_putenv_garbage == NULL)
  8340. posix_putenv_garbage = PyDict_New();
  8341. #endif
  8342. if (!initialized) {
  8343. stat_result_desc.name = MODNAME ".stat_result";
  8344. stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
  8345. stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
  8346. stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
  8347. PyStructSequence_InitType(&StatResultType, &stat_result_desc);
  8348. structseq_new = StatResultType.tp_new;
  8349. StatResultType.tp_new = statresult_new;
  8350. statvfs_result_desc.name = MODNAME ".statvfs_result";
  8351. PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc);
  8352. #ifdef NEED_TICKS_PER_SECOND
  8353. # if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
  8354. ticks_per_second = sysconf(_SC_CLK_TCK);
  8355. # elif defined(HZ)
  8356. ticks_per_second = HZ;
  8357. # else
  8358. ticks_per_second = 60; /* magic fallback value; may be bogus */
  8359. # endif
  8360. #endif
  8361. }
  8362. Py_INCREF((PyObject*) &StatResultType);
  8363. PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType);
  8364. Py_INCREF((PyObject*) &StatVFSResultType);
  8365. PyModule_AddObject(m, "statvfs_result",
  8366. (PyObject*) &StatVFSResultType);
  8367. initialized = 1;
  8368. #ifdef __APPLE__
  8369. /*
  8370. * Step 2 of weak-linking support on Mac OS X.
  8371. *
  8372. * The code below removes functions that are not available on the
  8373. * currently active platform.
  8374. *
  8375. * This block allow one to use a python binary that was build on
  8376. * OSX 10.4 on OSX 10.3, without loosing access to new APIs on
  8377. * OSX 10.4.
  8378. */
  8379. #ifdef HAVE_FSTATVFS
  8380. if (fstatvfs == NULL) {
  8381. if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
  8382. return;
  8383. }
  8384. }
  8385. #endif /* HAVE_FSTATVFS */
  8386. #ifdef HAVE_STATVFS
  8387. if (statvfs == NULL) {
  8388. if (PyObject_DelAttrString(m, "statvfs") == -1) {
  8389. return;
  8390. }
  8391. }
  8392. #endif /* HAVE_STATVFS */
  8393. # ifdef HAVE_LCHOWN
  8394. if (lchown == NULL) {
  8395. if (PyObject_DelAttrString(m, "lchown") == -1) {
  8396. return;
  8397. }
  8398. }
  8399. #endif /* HAVE_LCHOWN */
  8400. #endif /* __APPLE__ */
  8401. }
  8402. #ifdef __cplusplus
  8403. }
  8404. #endif