_pickle.c 228 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006
  1. /* pickle accelerator C extensor: _pickle module.
  2. *
  3. * It is built as a built-in module (Py_BUILD_CORE_BUILTIN define) on Windows
  4. * and as an extension module (Py_BUILD_CORE_MODULE define) on other
  5. * platforms. */
  6. #ifndef Py_BUILD_CORE_BUILTIN
  7. # define Py_BUILD_CORE_MODULE 1
  8. #endif
  9. #include "Python.h"
  10. #include "pycore_ceval.h" // _Py_EnterRecursiveCall()
  11. #include "pycore_moduleobject.h" // _PyModule_GetState()
  12. #include "pycore_runtime.h" // _Py_ID()
  13. #include "pycore_pystate.h" // _PyThreadState_GET()
  14. #include "structmember.h" // PyMemberDef
  15. #include <stdlib.h> // strtol()
  16. PyDoc_STRVAR(pickle_module_doc,
  17. "Optimized C implementation for the Python pickle module.");
  18. /*[clinic input]
  19. module _pickle
  20. class _pickle.Pickler "PicklerObject *" ""
  21. class _pickle.PicklerMemoProxy "PicklerMemoProxyObject *" ""
  22. class _pickle.Unpickler "UnpicklerObject *" ""
  23. class _pickle.UnpicklerMemoProxy "UnpicklerMemoProxyObject *" ""
  24. [clinic start generated code]*/
  25. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=b6d7191ab6466cda]*/
  26. /* Bump HIGHEST_PROTOCOL when new opcodes are added to the pickle protocol.
  27. Bump DEFAULT_PROTOCOL only when the oldest still supported version of Python
  28. already includes it. */
  29. enum {
  30. HIGHEST_PROTOCOL = 5,
  31. DEFAULT_PROTOCOL = 4
  32. };
  33. #ifdef MS_WINDOWS
  34. // These are already typedefs from windows.h, pulled in via pycore_runtime.h.
  35. #define FLOAT FLOAT_
  36. #define INT INT_
  37. #define LONG LONG_
  38. /* This can already be defined on Windows to set the character set
  39. the Windows header files treat as default */
  40. #ifdef UNICODE
  41. #undef UNICODE
  42. #endif
  43. #endif
  44. /* Pickle opcodes. These must be kept updated with pickle.py.
  45. Extensive docs are in pickletools.py. */
  46. enum opcode {
  47. MARK = '(',
  48. STOP = '.',
  49. POP = '0',
  50. POP_MARK = '1',
  51. DUP = '2',
  52. FLOAT = 'F',
  53. INT = 'I',
  54. BININT = 'J',
  55. BININT1 = 'K',
  56. LONG = 'L',
  57. BININT2 = 'M',
  58. NONE = 'N',
  59. PERSID = 'P',
  60. BINPERSID = 'Q',
  61. REDUCE = 'R',
  62. STRING = 'S',
  63. BINSTRING = 'T',
  64. SHORT_BINSTRING = 'U',
  65. UNICODE = 'V',
  66. BINUNICODE = 'X',
  67. APPEND = 'a',
  68. BUILD = 'b',
  69. GLOBAL = 'c',
  70. DICT = 'd',
  71. EMPTY_DICT = '}',
  72. APPENDS = 'e',
  73. GET = 'g',
  74. BINGET = 'h',
  75. INST = 'i',
  76. LONG_BINGET = 'j',
  77. LIST = 'l',
  78. EMPTY_LIST = ']',
  79. OBJ = 'o',
  80. PUT = 'p',
  81. BINPUT = 'q',
  82. LONG_BINPUT = 'r',
  83. SETITEM = 's',
  84. TUPLE = 't',
  85. EMPTY_TUPLE = ')',
  86. SETITEMS = 'u',
  87. BINFLOAT = 'G',
  88. /* Protocol 2. */
  89. PROTO = '\x80',
  90. NEWOBJ = '\x81',
  91. EXT1 = '\x82',
  92. EXT2 = '\x83',
  93. EXT4 = '\x84',
  94. TUPLE1 = '\x85',
  95. TUPLE2 = '\x86',
  96. TUPLE3 = '\x87',
  97. NEWTRUE = '\x88',
  98. NEWFALSE = '\x89',
  99. LONG1 = '\x8a',
  100. LONG4 = '\x8b',
  101. /* Protocol 3 (Python 3.x) */
  102. BINBYTES = 'B',
  103. SHORT_BINBYTES = 'C',
  104. /* Protocol 4 */
  105. SHORT_BINUNICODE = '\x8c',
  106. BINUNICODE8 = '\x8d',
  107. BINBYTES8 = '\x8e',
  108. EMPTY_SET = '\x8f',
  109. ADDITEMS = '\x90',
  110. FROZENSET = '\x91',
  111. NEWOBJ_EX = '\x92',
  112. STACK_GLOBAL = '\x93',
  113. MEMOIZE = '\x94',
  114. FRAME = '\x95',
  115. /* Protocol 5 */
  116. BYTEARRAY8 = '\x96',
  117. NEXT_BUFFER = '\x97',
  118. READONLY_BUFFER = '\x98'
  119. };
  120. enum {
  121. /* Keep in synch with pickle.Pickler._BATCHSIZE. This is how many elements
  122. batch_list/dict() pumps out before doing APPENDS/SETITEMS. Nothing will
  123. break if this gets out of synch with pickle.py, but it's unclear that would
  124. help anything either. */
  125. BATCHSIZE = 1000,
  126. /* Nesting limit until Pickler, when running in "fast mode", starts
  127. checking for self-referential data-structures. */
  128. FAST_NESTING_LIMIT = 50,
  129. /* Initial size of the write buffer of Pickler. */
  130. WRITE_BUF_SIZE = 4096,
  131. /* Prefetch size when unpickling (disabled on unpeekable streams) */
  132. PREFETCH = 8192 * 16,
  133. FRAME_SIZE_MIN = 4,
  134. FRAME_SIZE_TARGET = 64 * 1024,
  135. FRAME_HEADER_SIZE = 9
  136. };
  137. /*************************************************************************/
  138. /* State of the pickle module, per PEP 3121. */
  139. typedef struct {
  140. /* Exception classes for pickle. */
  141. PyObject *PickleError;
  142. PyObject *PicklingError;
  143. PyObject *UnpicklingError;
  144. /* copyreg.dispatch_table, {type_object: pickling_function} */
  145. PyObject *dispatch_table;
  146. /* For the extension opcodes EXT1, EXT2 and EXT4. */
  147. /* copyreg._extension_registry, {(module_name, function_name): code} */
  148. PyObject *extension_registry;
  149. /* copyreg._extension_cache, {code: object} */
  150. PyObject *extension_cache;
  151. /* copyreg._inverted_registry, {code: (module_name, function_name)} */
  152. PyObject *inverted_registry;
  153. /* Import mappings for compatibility with Python 2.x */
  154. /* _compat_pickle.NAME_MAPPING,
  155. {(oldmodule, oldname): (newmodule, newname)} */
  156. PyObject *name_mapping_2to3;
  157. /* _compat_pickle.IMPORT_MAPPING, {oldmodule: newmodule} */
  158. PyObject *import_mapping_2to3;
  159. /* Same, but with REVERSE_NAME_MAPPING / REVERSE_IMPORT_MAPPING */
  160. PyObject *name_mapping_3to2;
  161. PyObject *import_mapping_3to2;
  162. /* codecs.encode, used for saving bytes in older protocols */
  163. PyObject *codecs_encode;
  164. /* builtins.getattr, used for saving nested names with protocol < 4 */
  165. PyObject *getattr;
  166. /* functools.partial, used for implementing __newobj_ex__ with protocols
  167. 2 and 3 */
  168. PyObject *partial;
  169. /* Types */
  170. PyTypeObject *Pickler_Type;
  171. PyTypeObject *Unpickler_Type;
  172. PyTypeObject *Pdata_Type;
  173. PyTypeObject *PicklerMemoProxyType;
  174. PyTypeObject *UnpicklerMemoProxyType;
  175. } PickleState;
  176. /* Forward declaration of the _pickle module definition. */
  177. static struct PyModuleDef _picklemodule;
  178. /* Given a module object, get its per-module state. */
  179. static inline PickleState *
  180. _Pickle_GetState(PyObject *module)
  181. {
  182. void *state = _PyModule_GetState(module);
  183. assert(state != NULL);
  184. return (PickleState *)state;
  185. }
  186. static inline PickleState *
  187. _Pickle_GetStateByClass(PyTypeObject *cls)
  188. {
  189. void *state = _PyType_GetModuleState(cls);
  190. assert(state != NULL);
  191. return (PickleState *)state;
  192. }
  193. static inline PickleState *
  194. _Pickle_FindStateByType(PyTypeObject *tp)
  195. {
  196. PyObject *module = PyType_GetModuleByDef(tp, &_picklemodule);
  197. assert(module != NULL);
  198. return _Pickle_GetState(module);
  199. }
  200. /* Clear the given pickle module state. */
  201. static void
  202. _Pickle_ClearState(PickleState *st)
  203. {
  204. Py_CLEAR(st->PickleError);
  205. Py_CLEAR(st->PicklingError);
  206. Py_CLEAR(st->UnpicklingError);
  207. Py_CLEAR(st->dispatch_table);
  208. Py_CLEAR(st->extension_registry);
  209. Py_CLEAR(st->extension_cache);
  210. Py_CLEAR(st->inverted_registry);
  211. Py_CLEAR(st->name_mapping_2to3);
  212. Py_CLEAR(st->import_mapping_2to3);
  213. Py_CLEAR(st->name_mapping_3to2);
  214. Py_CLEAR(st->import_mapping_3to2);
  215. Py_CLEAR(st->codecs_encode);
  216. Py_CLEAR(st->getattr);
  217. Py_CLEAR(st->partial);
  218. Py_CLEAR(st->Pickler_Type);
  219. Py_CLEAR(st->Unpickler_Type);
  220. Py_CLEAR(st->Pdata_Type);
  221. Py_CLEAR(st->PicklerMemoProxyType);
  222. Py_CLEAR(st->UnpicklerMemoProxyType);
  223. }
  224. /* Initialize the given pickle module state. */
  225. static int
  226. _Pickle_InitState(PickleState *st)
  227. {
  228. PyObject *copyreg = NULL;
  229. PyObject *compat_pickle = NULL;
  230. st->getattr = _PyEval_GetBuiltin(&_Py_ID(getattr));
  231. if (st->getattr == NULL)
  232. goto error;
  233. copyreg = PyImport_ImportModule("copyreg");
  234. if (!copyreg)
  235. goto error;
  236. st->dispatch_table = PyObject_GetAttrString(copyreg, "dispatch_table");
  237. if (!st->dispatch_table)
  238. goto error;
  239. if (!PyDict_CheckExact(st->dispatch_table)) {
  240. PyErr_Format(PyExc_RuntimeError,
  241. "copyreg.dispatch_table should be a dict, not %.200s",
  242. Py_TYPE(st->dispatch_table)->tp_name);
  243. goto error;
  244. }
  245. st->extension_registry = \
  246. PyObject_GetAttrString(copyreg, "_extension_registry");
  247. if (!st->extension_registry)
  248. goto error;
  249. if (!PyDict_CheckExact(st->extension_registry)) {
  250. PyErr_Format(PyExc_RuntimeError,
  251. "copyreg._extension_registry should be a dict, "
  252. "not %.200s", Py_TYPE(st->extension_registry)->tp_name);
  253. goto error;
  254. }
  255. st->inverted_registry = \
  256. PyObject_GetAttrString(copyreg, "_inverted_registry");
  257. if (!st->inverted_registry)
  258. goto error;
  259. if (!PyDict_CheckExact(st->inverted_registry)) {
  260. PyErr_Format(PyExc_RuntimeError,
  261. "copyreg._inverted_registry should be a dict, "
  262. "not %.200s", Py_TYPE(st->inverted_registry)->tp_name);
  263. goto error;
  264. }
  265. st->extension_cache = PyObject_GetAttrString(copyreg, "_extension_cache");
  266. if (!st->extension_cache)
  267. goto error;
  268. if (!PyDict_CheckExact(st->extension_cache)) {
  269. PyErr_Format(PyExc_RuntimeError,
  270. "copyreg._extension_cache should be a dict, "
  271. "not %.200s", Py_TYPE(st->extension_cache)->tp_name);
  272. goto error;
  273. }
  274. Py_CLEAR(copyreg);
  275. /* Load the 2.x -> 3.x stdlib module mapping tables */
  276. compat_pickle = PyImport_ImportModule("_compat_pickle");
  277. if (!compat_pickle)
  278. goto error;
  279. st->name_mapping_2to3 = \
  280. PyObject_GetAttrString(compat_pickle, "NAME_MAPPING");
  281. if (!st->name_mapping_2to3)
  282. goto error;
  283. if (!PyDict_CheckExact(st->name_mapping_2to3)) {
  284. PyErr_Format(PyExc_RuntimeError,
  285. "_compat_pickle.NAME_MAPPING should be a dict, not %.200s",
  286. Py_TYPE(st->name_mapping_2to3)->tp_name);
  287. goto error;
  288. }
  289. st->import_mapping_2to3 = \
  290. PyObject_GetAttrString(compat_pickle, "IMPORT_MAPPING");
  291. if (!st->import_mapping_2to3)
  292. goto error;
  293. if (!PyDict_CheckExact(st->import_mapping_2to3)) {
  294. PyErr_Format(PyExc_RuntimeError,
  295. "_compat_pickle.IMPORT_MAPPING should be a dict, "
  296. "not %.200s", Py_TYPE(st->import_mapping_2to3)->tp_name);
  297. goto error;
  298. }
  299. /* ... and the 3.x -> 2.x mapping tables */
  300. st->name_mapping_3to2 = \
  301. PyObject_GetAttrString(compat_pickle, "REVERSE_NAME_MAPPING");
  302. if (!st->name_mapping_3to2)
  303. goto error;
  304. if (!PyDict_CheckExact(st->name_mapping_3to2)) {
  305. PyErr_Format(PyExc_RuntimeError,
  306. "_compat_pickle.REVERSE_NAME_MAPPING should be a dict, "
  307. "not %.200s", Py_TYPE(st->name_mapping_3to2)->tp_name);
  308. goto error;
  309. }
  310. st->import_mapping_3to2 = \
  311. PyObject_GetAttrString(compat_pickle, "REVERSE_IMPORT_MAPPING");
  312. if (!st->import_mapping_3to2)
  313. goto error;
  314. if (!PyDict_CheckExact(st->import_mapping_3to2)) {
  315. PyErr_Format(PyExc_RuntimeError,
  316. "_compat_pickle.REVERSE_IMPORT_MAPPING should be a dict, "
  317. "not %.200s", Py_TYPE(st->import_mapping_3to2)->tp_name);
  318. goto error;
  319. }
  320. Py_CLEAR(compat_pickle);
  321. st->codecs_encode = _PyImport_GetModuleAttrString("codecs", "encode");
  322. if (st->codecs_encode == NULL) {
  323. goto error;
  324. }
  325. if (!PyCallable_Check(st->codecs_encode)) {
  326. PyErr_Format(PyExc_RuntimeError,
  327. "codecs.encode should be a callable, not %.200s",
  328. Py_TYPE(st->codecs_encode)->tp_name);
  329. goto error;
  330. }
  331. st->partial = _PyImport_GetModuleAttrString("functools", "partial");
  332. if (!st->partial)
  333. goto error;
  334. return 0;
  335. error:
  336. Py_CLEAR(copyreg);
  337. Py_CLEAR(compat_pickle);
  338. _Pickle_ClearState(st);
  339. return -1;
  340. }
  341. /* Helper for calling a function with a single argument quickly.
  342. This function steals the reference of the given argument. */
  343. static PyObject *
  344. _Pickle_FastCall(PyObject *func, PyObject *obj)
  345. {
  346. PyObject *result;
  347. result = PyObject_CallOneArg(func, obj);
  348. Py_DECREF(obj);
  349. return result;
  350. }
  351. /*************************************************************************/
  352. /* Retrieve and deconstruct a method for avoiding a reference cycle
  353. (pickler -> bound method of pickler -> pickler) */
  354. static int
  355. init_method_ref(PyObject *self, PyObject *name,
  356. PyObject **method_func, PyObject **method_self)
  357. {
  358. PyObject *func, *func2;
  359. int ret;
  360. /* *method_func and *method_self should be consistent. All refcount decrements
  361. should be occurred after setting *method_self and *method_func. */
  362. ret = _PyObject_LookupAttr(self, name, &func);
  363. if (func == NULL) {
  364. *method_self = NULL;
  365. Py_CLEAR(*method_func);
  366. return ret;
  367. }
  368. if (PyMethod_Check(func) && PyMethod_GET_SELF(func) == self) {
  369. /* Deconstruct a bound Python method */
  370. *method_self = self; /* borrowed */
  371. func2 = PyMethod_GET_FUNCTION(func);
  372. Py_XSETREF(*method_func, Py_NewRef(func2));
  373. Py_DECREF(func);
  374. return 0;
  375. }
  376. else {
  377. *method_self = NULL;
  378. Py_XSETREF(*method_func, func);
  379. return 0;
  380. }
  381. }
  382. /* Bind a method if it was deconstructed */
  383. static PyObject *
  384. reconstruct_method(PyObject *func, PyObject *self)
  385. {
  386. if (self) {
  387. return PyMethod_New(func, self);
  388. }
  389. else {
  390. return Py_NewRef(func);
  391. }
  392. }
  393. static PyObject *
  394. call_method(PyObject *func, PyObject *self, PyObject *obj)
  395. {
  396. if (self) {
  397. return PyObject_CallFunctionObjArgs(func, self, obj, NULL);
  398. }
  399. else {
  400. return PyObject_CallOneArg(func, obj);
  401. }
  402. }
  403. /*************************************************************************/
  404. /* Internal data type used as the unpickling stack. */
  405. typedef struct {
  406. PyObject_VAR_HEAD
  407. PyObject **data;
  408. int mark_set; /* is MARK set? */
  409. Py_ssize_t fence; /* position of top MARK or 0 */
  410. Py_ssize_t allocated; /* number of slots in data allocated */
  411. } Pdata;
  412. static int
  413. Pdata_traverse(Pdata *self, visitproc visit, void *arg)
  414. {
  415. Py_VISIT(Py_TYPE(self));
  416. return 0;
  417. }
  418. static void
  419. Pdata_dealloc(Pdata *self)
  420. {
  421. PyTypeObject *tp = Py_TYPE(self);
  422. PyObject_GC_UnTrack(self);
  423. Py_ssize_t i = Py_SIZE(self);
  424. while (--i >= 0) {
  425. Py_DECREF(self->data[i]);
  426. }
  427. PyMem_Free(self->data);
  428. tp->tp_free((PyObject *)self);
  429. Py_DECREF(tp);
  430. }
  431. static PyType_Slot pdata_slots[] = {
  432. {Py_tp_dealloc, Pdata_dealloc},
  433. {Py_tp_traverse, Pdata_traverse},
  434. {0, NULL},
  435. };
  436. static PyType_Spec pdata_spec = {
  437. .name = "_pickle.Pdata",
  438. .basicsize = sizeof(Pdata),
  439. .itemsize = sizeof(PyObject *),
  440. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  441. Py_TPFLAGS_IMMUTABLETYPE),
  442. .slots = pdata_slots,
  443. };
  444. static PyObject *
  445. Pdata_New(PickleState *state)
  446. {
  447. Pdata *self;
  448. if (!(self = PyObject_GC_New(Pdata, state->Pdata_Type)))
  449. return NULL;
  450. Py_SET_SIZE(self, 0);
  451. self->mark_set = 0;
  452. self->fence = 0;
  453. self->allocated = 8;
  454. self->data = PyMem_Malloc(self->allocated * sizeof(PyObject *));
  455. if (self->data) {
  456. PyObject_GC_Track(self);
  457. return (PyObject *)self;
  458. }
  459. Py_DECREF(self);
  460. return PyErr_NoMemory();
  461. }
  462. /* Retain only the initial clearto items. If clearto >= the current
  463. * number of items, this is a (non-erroneous) NOP.
  464. */
  465. static int
  466. Pdata_clear(Pdata *self, Py_ssize_t clearto)
  467. {
  468. Py_ssize_t i = Py_SIZE(self);
  469. assert(clearto >= self->fence);
  470. if (clearto >= i)
  471. return 0;
  472. while (--i >= clearto) {
  473. Py_CLEAR(self->data[i]);
  474. }
  475. Py_SET_SIZE(self, clearto);
  476. return 0;
  477. }
  478. static int
  479. Pdata_grow(Pdata *self)
  480. {
  481. PyObject **data = self->data;
  482. size_t allocated = (size_t)self->allocated;
  483. size_t new_allocated;
  484. new_allocated = (allocated >> 3) + 6;
  485. /* check for integer overflow */
  486. if (new_allocated > (size_t)PY_SSIZE_T_MAX - allocated)
  487. goto nomemory;
  488. new_allocated += allocated;
  489. PyMem_RESIZE(data, PyObject *, new_allocated);
  490. if (data == NULL)
  491. goto nomemory;
  492. self->data = data;
  493. self->allocated = (Py_ssize_t)new_allocated;
  494. return 0;
  495. nomemory:
  496. PyErr_NoMemory();
  497. return -1;
  498. }
  499. static int
  500. Pdata_stack_underflow(PickleState *st, Pdata *self)
  501. {
  502. PyErr_SetString(st->UnpicklingError,
  503. self->mark_set ?
  504. "unexpected MARK found" :
  505. "unpickling stack underflow");
  506. return -1;
  507. }
  508. /* D is a Pdata*. Pop the topmost element and store it into V, which
  509. * must be an lvalue holding PyObject*. On stack underflow, UnpicklingError
  510. * is raised and V is set to NULL.
  511. */
  512. static PyObject *
  513. Pdata_pop(PickleState *state, Pdata *self)
  514. {
  515. if (Py_SIZE(self) <= self->fence) {
  516. Pdata_stack_underflow(state, self);
  517. return NULL;
  518. }
  519. Py_SET_SIZE(self, Py_SIZE(self) - 1);
  520. return self->data[Py_SIZE(self)];
  521. }
  522. #define PDATA_POP(S, D, V) do { (V) = Pdata_pop(S, (D)); } while (0)
  523. static int
  524. Pdata_push(Pdata *self, PyObject *obj)
  525. {
  526. if (Py_SIZE(self) == self->allocated && Pdata_grow(self) < 0) {
  527. return -1;
  528. }
  529. self->data[Py_SIZE(self)] = obj;
  530. Py_SET_SIZE(self, Py_SIZE(self) + 1);
  531. return 0;
  532. }
  533. /* Push an object on stack, transferring its ownership to the stack. */
  534. #define PDATA_PUSH(D, O, ER) do { \
  535. if (Pdata_push((D), (O)) < 0) return (ER); } while(0)
  536. /* Push an object on stack, adding a new reference to the object. */
  537. #define PDATA_APPEND(D, O, ER) do { \
  538. Py_INCREF((O)); \
  539. if (Pdata_push((D), (O)) < 0) return (ER); } while(0)
  540. static PyObject *
  541. Pdata_poptuple(PickleState *state, Pdata *self, Py_ssize_t start)
  542. {
  543. PyObject *tuple;
  544. Py_ssize_t len, i, j;
  545. if (start < self->fence) {
  546. Pdata_stack_underflow(state, self);
  547. return NULL;
  548. }
  549. len = Py_SIZE(self) - start;
  550. tuple = PyTuple_New(len);
  551. if (tuple == NULL)
  552. return NULL;
  553. for (i = start, j = 0; j < len; i++, j++)
  554. PyTuple_SET_ITEM(tuple, j, self->data[i]);
  555. Py_SET_SIZE(self, start);
  556. return tuple;
  557. }
  558. static PyObject *
  559. Pdata_poplist(Pdata *self, Py_ssize_t start)
  560. {
  561. PyObject *list;
  562. Py_ssize_t len, i, j;
  563. len = Py_SIZE(self) - start;
  564. list = PyList_New(len);
  565. if (list == NULL)
  566. return NULL;
  567. for (i = start, j = 0; j < len; i++, j++)
  568. PyList_SET_ITEM(list, j, self->data[i]);
  569. Py_SET_SIZE(self, start);
  570. return list;
  571. }
  572. typedef struct {
  573. PyObject *me_key;
  574. Py_ssize_t me_value;
  575. } PyMemoEntry;
  576. typedef struct {
  577. size_t mt_mask;
  578. size_t mt_used;
  579. size_t mt_allocated;
  580. PyMemoEntry *mt_table;
  581. } PyMemoTable;
  582. typedef struct PicklerObject {
  583. PyObject_HEAD
  584. PyMemoTable *memo; /* Memo table, keep track of the seen
  585. objects to support self-referential objects
  586. pickling. */
  587. PyObject *pers_func; /* persistent_id() method, can be NULL */
  588. PyObject *pers_func_self; /* borrowed reference to self if pers_func
  589. is an unbound method, NULL otherwise */
  590. PyObject *dispatch_table; /* private dispatch_table, can be NULL */
  591. PyObject *reducer_override; /* hook for invoking user-defined callbacks
  592. instead of save_global when pickling
  593. functions and classes*/
  594. PyObject *write; /* write() method of the output stream. */
  595. PyObject *output_buffer; /* Write into a local bytearray buffer before
  596. flushing to the stream. */
  597. Py_ssize_t output_len; /* Length of output_buffer. */
  598. Py_ssize_t max_output_len; /* Allocation size of output_buffer. */
  599. int proto; /* Pickle protocol number, >= 0 */
  600. int bin; /* Boolean, true if proto > 0 */
  601. int framing; /* True when framing is enabled, proto >= 4 */
  602. Py_ssize_t frame_start; /* Position in output_buffer where the
  603. current frame begins. -1 if there
  604. is no frame currently open. */
  605. Py_ssize_t buf_size; /* Size of the current buffered pickle data */
  606. int fast; /* Enable fast mode if set to a true value.
  607. The fast mode disable the usage of memo,
  608. therefore speeding the pickling process by
  609. not generating superfluous PUT opcodes. It
  610. should not be used if with self-referential
  611. objects. */
  612. int fast_nesting;
  613. int fix_imports; /* Indicate whether Pickler should fix
  614. the name of globals for Python 2.x. */
  615. PyObject *fast_memo;
  616. PyObject *buffer_callback; /* Callback for out-of-band buffers, or NULL */
  617. } PicklerObject;
  618. typedef struct UnpicklerObject {
  619. PyObject_HEAD
  620. Pdata *stack; /* Pickle data stack, store unpickled objects. */
  621. /* The unpickler memo is just an array of PyObject *s. Using a dict
  622. is unnecessary, since the keys are contiguous ints. */
  623. PyObject **memo;
  624. size_t memo_size; /* Capacity of the memo array */
  625. size_t memo_len; /* Number of objects in the memo */
  626. PyObject *pers_func; /* persistent_load() method, can be NULL. */
  627. PyObject *pers_func_self; /* borrowed reference to self if pers_func
  628. is an unbound method, NULL otherwise */
  629. Py_buffer buffer;
  630. char *input_buffer;
  631. char *input_line;
  632. Py_ssize_t input_len;
  633. Py_ssize_t next_read_idx;
  634. Py_ssize_t prefetched_idx; /* index of first prefetched byte */
  635. PyObject *read; /* read() method of the input stream. */
  636. PyObject *readinto; /* readinto() method of the input stream. */
  637. PyObject *readline; /* readline() method of the input stream. */
  638. PyObject *peek; /* peek() method of the input stream, or NULL */
  639. PyObject *buffers; /* iterable of out-of-band buffers, or NULL */
  640. char *encoding; /* Name of the encoding to be used for
  641. decoding strings pickled using Python
  642. 2.x. The default value is "ASCII" */
  643. char *errors; /* Name of errors handling scheme to used when
  644. decoding strings. The default value is
  645. "strict". */
  646. Py_ssize_t *marks; /* Mark stack, used for unpickling container
  647. objects. */
  648. Py_ssize_t num_marks; /* Number of marks in the mark stack. */
  649. Py_ssize_t marks_size; /* Current allocated size of the mark stack. */
  650. int proto; /* Protocol of the pickle loaded. */
  651. int fix_imports; /* Indicate whether Unpickler should fix
  652. the name of globals pickled by Python 2.x. */
  653. } UnpicklerObject;
  654. typedef struct {
  655. PyObject_HEAD
  656. PicklerObject *pickler; /* Pickler whose memo table we're proxying. */
  657. } PicklerMemoProxyObject;
  658. typedef struct {
  659. PyObject_HEAD
  660. UnpicklerObject *unpickler;
  661. } UnpicklerMemoProxyObject;
  662. /* Forward declarations */
  663. static int save(PickleState *state, PicklerObject *, PyObject *, int);
  664. static int save_reduce(PickleState *, PicklerObject *, PyObject *, PyObject *);
  665. #include "clinic/_pickle.c.h"
  666. /*************************************************************************
  667. A custom hashtable mapping void* to Python ints. This is used by the pickler
  668. for memoization. Using a custom hashtable rather than PyDict allows us to skip
  669. a bunch of unnecessary object creation. This makes a huge performance
  670. difference. */
  671. #define MT_MINSIZE 8
  672. #define PERTURB_SHIFT 5
  673. static PyMemoTable *
  674. PyMemoTable_New(void)
  675. {
  676. PyMemoTable *memo = PyMem_Malloc(sizeof(PyMemoTable));
  677. if (memo == NULL) {
  678. PyErr_NoMemory();
  679. return NULL;
  680. }
  681. memo->mt_used = 0;
  682. memo->mt_allocated = MT_MINSIZE;
  683. memo->mt_mask = MT_MINSIZE - 1;
  684. memo->mt_table = PyMem_Malloc(MT_MINSIZE * sizeof(PyMemoEntry));
  685. if (memo->mt_table == NULL) {
  686. PyMem_Free(memo);
  687. PyErr_NoMemory();
  688. return NULL;
  689. }
  690. memset(memo->mt_table, 0, MT_MINSIZE * sizeof(PyMemoEntry));
  691. return memo;
  692. }
  693. static PyMemoTable *
  694. PyMemoTable_Copy(PyMemoTable *self)
  695. {
  696. PyMemoTable *new = PyMemoTable_New();
  697. if (new == NULL)
  698. return NULL;
  699. new->mt_used = self->mt_used;
  700. new->mt_allocated = self->mt_allocated;
  701. new->mt_mask = self->mt_mask;
  702. /* The table we get from _New() is probably smaller than we wanted.
  703. Free it and allocate one that's the right size. */
  704. PyMem_Free(new->mt_table);
  705. new->mt_table = PyMem_NEW(PyMemoEntry, self->mt_allocated);
  706. if (new->mt_table == NULL) {
  707. PyMem_Free(new);
  708. PyErr_NoMemory();
  709. return NULL;
  710. }
  711. for (size_t i = 0; i < self->mt_allocated; i++) {
  712. Py_XINCREF(self->mt_table[i].me_key);
  713. }
  714. memcpy(new->mt_table, self->mt_table,
  715. sizeof(PyMemoEntry) * self->mt_allocated);
  716. return new;
  717. }
  718. static Py_ssize_t
  719. PyMemoTable_Size(PyMemoTable *self)
  720. {
  721. return self->mt_used;
  722. }
  723. static int
  724. PyMemoTable_Clear(PyMemoTable *self)
  725. {
  726. Py_ssize_t i = self->mt_allocated;
  727. while (--i >= 0) {
  728. Py_XDECREF(self->mt_table[i].me_key);
  729. }
  730. self->mt_used = 0;
  731. memset(self->mt_table, 0, self->mt_allocated * sizeof(PyMemoEntry));
  732. return 0;
  733. }
  734. static void
  735. PyMemoTable_Del(PyMemoTable *self)
  736. {
  737. if (self == NULL)
  738. return;
  739. PyMemoTable_Clear(self);
  740. PyMem_Free(self->mt_table);
  741. PyMem_Free(self);
  742. }
  743. /* Since entries cannot be deleted from this hashtable, _PyMemoTable_Lookup()
  744. can be considerably simpler than dictobject.c's lookdict(). */
  745. static PyMemoEntry *
  746. _PyMemoTable_Lookup(PyMemoTable *self, PyObject *key)
  747. {
  748. size_t i;
  749. size_t perturb;
  750. size_t mask = self->mt_mask;
  751. PyMemoEntry *table = self->mt_table;
  752. PyMemoEntry *entry;
  753. Py_hash_t hash = (Py_hash_t)key >> 3;
  754. i = hash & mask;
  755. entry = &table[i];
  756. if (entry->me_key == NULL || entry->me_key == key)
  757. return entry;
  758. for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
  759. i = (i << 2) + i + perturb + 1;
  760. entry = &table[i & mask];
  761. if (entry->me_key == NULL || entry->me_key == key)
  762. return entry;
  763. }
  764. Py_UNREACHABLE();
  765. }
  766. /* Returns -1 on failure, 0 on success. */
  767. static int
  768. _PyMemoTable_ResizeTable(PyMemoTable *self, size_t min_size)
  769. {
  770. PyMemoEntry *oldtable = NULL;
  771. PyMemoEntry *oldentry, *newentry;
  772. size_t new_size = MT_MINSIZE;
  773. size_t to_process;
  774. assert(min_size > 0);
  775. if (min_size > PY_SSIZE_T_MAX) {
  776. PyErr_NoMemory();
  777. return -1;
  778. }
  779. /* Find the smallest valid table size >= min_size. */
  780. while (new_size < min_size) {
  781. new_size <<= 1;
  782. }
  783. /* new_size needs to be a power of two. */
  784. assert((new_size & (new_size - 1)) == 0);
  785. /* Allocate new table. */
  786. oldtable = self->mt_table;
  787. self->mt_table = PyMem_NEW(PyMemoEntry, new_size);
  788. if (self->mt_table == NULL) {
  789. self->mt_table = oldtable;
  790. PyErr_NoMemory();
  791. return -1;
  792. }
  793. self->mt_allocated = new_size;
  794. self->mt_mask = new_size - 1;
  795. memset(self->mt_table, 0, sizeof(PyMemoEntry) * new_size);
  796. /* Copy entries from the old table. */
  797. to_process = self->mt_used;
  798. for (oldentry = oldtable; to_process > 0; oldentry++) {
  799. if (oldentry->me_key != NULL) {
  800. to_process--;
  801. /* newentry is a pointer to a chunk of the new
  802. mt_table, so we're setting the key:value pair
  803. in-place. */
  804. newentry = _PyMemoTable_Lookup(self, oldentry->me_key);
  805. newentry->me_key = oldentry->me_key;
  806. newentry->me_value = oldentry->me_value;
  807. }
  808. }
  809. /* Deallocate the old table. */
  810. PyMem_Free(oldtable);
  811. return 0;
  812. }
  813. /* Returns NULL on failure, a pointer to the value otherwise. */
  814. static Py_ssize_t *
  815. PyMemoTable_Get(PyMemoTable *self, PyObject *key)
  816. {
  817. PyMemoEntry *entry = _PyMemoTable_Lookup(self, key);
  818. if (entry->me_key == NULL)
  819. return NULL;
  820. return &entry->me_value;
  821. }
  822. /* Returns -1 on failure, 0 on success. */
  823. static int
  824. PyMemoTable_Set(PyMemoTable *self, PyObject *key, Py_ssize_t value)
  825. {
  826. PyMemoEntry *entry;
  827. assert(key != NULL);
  828. entry = _PyMemoTable_Lookup(self, key);
  829. if (entry->me_key != NULL) {
  830. entry->me_value = value;
  831. return 0;
  832. }
  833. entry->me_key = Py_NewRef(key);
  834. entry->me_value = value;
  835. self->mt_used++;
  836. /* If we added a key, we can safely resize. Otherwise just return!
  837. * If used >= 2/3 size, adjust size. Normally, this quaduples the size.
  838. *
  839. * Quadrupling the size improves average table sparseness
  840. * (reducing collisions) at the cost of some memory. It also halves
  841. * the number of expensive resize operations in a growing memo table.
  842. *
  843. * Very large memo tables (over 50K items) use doubling instead.
  844. * This may help applications with severe memory constraints.
  845. */
  846. if (SIZE_MAX / 3 >= self->mt_used && self->mt_used * 3 < self->mt_allocated * 2) {
  847. return 0;
  848. }
  849. // self->mt_used is always < PY_SSIZE_T_MAX, so this can't overflow.
  850. size_t desired_size = (self->mt_used > 50000 ? 2 : 4) * self->mt_used;
  851. return _PyMemoTable_ResizeTable(self, desired_size);
  852. }
  853. #undef MT_MINSIZE
  854. #undef PERTURB_SHIFT
  855. /*************************************************************************/
  856. static int
  857. _Pickler_ClearBuffer(PicklerObject *self)
  858. {
  859. Py_XSETREF(self->output_buffer,
  860. PyBytes_FromStringAndSize(NULL, self->max_output_len));
  861. if (self->output_buffer == NULL)
  862. return -1;
  863. self->output_len = 0;
  864. self->frame_start = -1;
  865. return 0;
  866. }
  867. static void
  868. _write_size64(char *out, size_t value)
  869. {
  870. size_t i;
  871. static_assert(sizeof(size_t) <= 8, "size_t is larger than 64-bit");
  872. for (i = 0; i < sizeof(size_t); i++) {
  873. out[i] = (unsigned char)((value >> (8 * i)) & 0xff);
  874. }
  875. for (i = sizeof(size_t); i < 8; i++) {
  876. out[i] = 0;
  877. }
  878. }
  879. static int
  880. _Pickler_CommitFrame(PicklerObject *self)
  881. {
  882. size_t frame_len;
  883. char *qdata;
  884. if (!self->framing || self->frame_start == -1)
  885. return 0;
  886. frame_len = self->output_len - self->frame_start - FRAME_HEADER_SIZE;
  887. qdata = PyBytes_AS_STRING(self->output_buffer) + self->frame_start;
  888. if (frame_len >= FRAME_SIZE_MIN) {
  889. qdata[0] = FRAME;
  890. _write_size64(qdata + 1, frame_len);
  891. }
  892. else {
  893. memmove(qdata, qdata + FRAME_HEADER_SIZE, frame_len);
  894. self->output_len -= FRAME_HEADER_SIZE;
  895. }
  896. self->frame_start = -1;
  897. return 0;
  898. }
  899. static PyObject *
  900. _Pickler_GetString(PicklerObject *self)
  901. {
  902. PyObject *output_buffer = self->output_buffer;
  903. assert(self->output_buffer != NULL);
  904. if (_Pickler_CommitFrame(self))
  905. return NULL;
  906. self->output_buffer = NULL;
  907. /* Resize down to exact size */
  908. if (_PyBytes_Resize(&output_buffer, self->output_len) < 0)
  909. return NULL;
  910. return output_buffer;
  911. }
  912. static int
  913. _Pickler_FlushToFile(PicklerObject *self)
  914. {
  915. PyObject *output, *result;
  916. assert(self->write != NULL);
  917. /* This will commit the frame first */
  918. output = _Pickler_GetString(self);
  919. if (output == NULL)
  920. return -1;
  921. result = _Pickle_FastCall(self->write, output);
  922. Py_XDECREF(result);
  923. return (result == NULL) ? -1 : 0;
  924. }
  925. static int
  926. _Pickler_OpcodeBoundary(PicklerObject *self)
  927. {
  928. Py_ssize_t frame_len;
  929. if (!self->framing || self->frame_start == -1) {
  930. return 0;
  931. }
  932. frame_len = self->output_len - self->frame_start - FRAME_HEADER_SIZE;
  933. if (frame_len >= FRAME_SIZE_TARGET) {
  934. if(_Pickler_CommitFrame(self)) {
  935. return -1;
  936. }
  937. /* Flush the content of the committed frame to the underlying
  938. * file and reuse the pickler buffer for the next frame so as
  939. * to limit memory usage when dumping large complex objects to
  940. * a file.
  941. *
  942. * self->write is NULL when called via dumps.
  943. */
  944. if (self->write != NULL) {
  945. if (_Pickler_FlushToFile(self) < 0) {
  946. return -1;
  947. }
  948. if (_Pickler_ClearBuffer(self) < 0) {
  949. return -1;
  950. }
  951. }
  952. }
  953. return 0;
  954. }
  955. static Py_ssize_t
  956. _Pickler_Write(PicklerObject *self, const char *s, Py_ssize_t data_len)
  957. {
  958. Py_ssize_t i, n, required;
  959. char *buffer;
  960. int need_new_frame;
  961. assert(s != NULL);
  962. need_new_frame = (self->framing && self->frame_start == -1);
  963. if (need_new_frame)
  964. n = data_len + FRAME_HEADER_SIZE;
  965. else
  966. n = data_len;
  967. required = self->output_len + n;
  968. if (required > self->max_output_len) {
  969. /* Make place in buffer for the pickle chunk */
  970. if (self->output_len >= PY_SSIZE_T_MAX / 2 - n) {
  971. PyErr_NoMemory();
  972. return -1;
  973. }
  974. self->max_output_len = (self->output_len + n) / 2 * 3;
  975. if (_PyBytes_Resize(&self->output_buffer, self->max_output_len) < 0)
  976. return -1;
  977. }
  978. buffer = PyBytes_AS_STRING(self->output_buffer);
  979. if (need_new_frame) {
  980. /* Setup new frame */
  981. Py_ssize_t frame_start = self->output_len;
  982. self->frame_start = frame_start;
  983. for (i = 0; i < FRAME_HEADER_SIZE; i++) {
  984. /* Write an invalid value, for debugging */
  985. buffer[frame_start + i] = 0xFE;
  986. }
  987. self->output_len += FRAME_HEADER_SIZE;
  988. }
  989. if (data_len < 8) {
  990. /* This is faster than memcpy when the string is short. */
  991. for (i = 0; i < data_len; i++) {
  992. buffer[self->output_len + i] = s[i];
  993. }
  994. }
  995. else {
  996. memcpy(buffer + self->output_len, s, data_len);
  997. }
  998. self->output_len += data_len;
  999. return data_len;
  1000. }
  1001. static PicklerObject *
  1002. _Pickler_New(PickleState *st)
  1003. {
  1004. PyMemoTable *memo = PyMemoTable_New();
  1005. if (memo == NULL) {
  1006. return NULL;
  1007. }
  1008. const Py_ssize_t max_output_len = WRITE_BUF_SIZE;
  1009. PyObject *output_buffer = PyBytes_FromStringAndSize(NULL, max_output_len);
  1010. if (output_buffer == NULL) {
  1011. goto error;
  1012. }
  1013. PicklerObject *self = PyObject_GC_New(PicklerObject, st->Pickler_Type);
  1014. if (self == NULL) {
  1015. goto error;
  1016. }
  1017. self->memo = memo;
  1018. self->pers_func = NULL;
  1019. self->pers_func_self = NULL;
  1020. self->dispatch_table = NULL;
  1021. self->reducer_override = NULL;
  1022. self->write = NULL;
  1023. self->output_buffer = output_buffer;
  1024. self->output_len = 0;
  1025. self->max_output_len = max_output_len;
  1026. self->proto = 0;
  1027. self->bin = 0;
  1028. self->framing = 0;
  1029. self->frame_start = -1;
  1030. self->buf_size = 0;
  1031. self->fast = 0;
  1032. self->fast_nesting = 0;
  1033. self->fix_imports = 0;
  1034. self->fast_memo = NULL;
  1035. self->buffer_callback = NULL;
  1036. PyObject_GC_Track(self);
  1037. return self;
  1038. error:
  1039. PyMem_Free(memo);
  1040. Py_XDECREF(output_buffer);
  1041. return NULL;
  1042. }
  1043. static int
  1044. _Pickler_SetProtocol(PicklerObject *self, PyObject *protocol, int fix_imports)
  1045. {
  1046. long proto;
  1047. if (protocol == Py_None) {
  1048. proto = DEFAULT_PROTOCOL;
  1049. }
  1050. else {
  1051. proto = PyLong_AsLong(protocol);
  1052. if (proto < 0) {
  1053. if (proto == -1 && PyErr_Occurred())
  1054. return -1;
  1055. proto = HIGHEST_PROTOCOL;
  1056. }
  1057. else if (proto > HIGHEST_PROTOCOL) {
  1058. PyErr_Format(PyExc_ValueError, "pickle protocol must be <= %d",
  1059. HIGHEST_PROTOCOL);
  1060. return -1;
  1061. }
  1062. }
  1063. self->proto = (int)proto;
  1064. self->bin = proto > 0;
  1065. self->fix_imports = fix_imports && proto < 3;
  1066. return 0;
  1067. }
  1068. /* Returns -1 (with an exception set) on failure, 0 on success. This may
  1069. be called once on a freshly created Pickler. */
  1070. static int
  1071. _Pickler_SetOutputStream(PicklerObject *self, PyObject *file)
  1072. {
  1073. assert(file != NULL);
  1074. if (_PyObject_LookupAttr(file, &_Py_ID(write), &self->write) < 0) {
  1075. return -1;
  1076. }
  1077. if (self->write == NULL) {
  1078. PyErr_SetString(PyExc_TypeError,
  1079. "file must have a 'write' attribute");
  1080. return -1;
  1081. }
  1082. return 0;
  1083. }
  1084. static int
  1085. _Pickler_SetBufferCallback(PicklerObject *self, PyObject *buffer_callback)
  1086. {
  1087. if (buffer_callback == Py_None) {
  1088. buffer_callback = NULL;
  1089. }
  1090. if (buffer_callback != NULL && self->proto < 5) {
  1091. PyErr_SetString(PyExc_ValueError,
  1092. "buffer_callback needs protocol >= 5");
  1093. return -1;
  1094. }
  1095. self->buffer_callback = Py_XNewRef(buffer_callback);
  1096. return 0;
  1097. }
  1098. /* Returns the size of the input on success, -1 on failure. This takes its
  1099. own reference to `input`. */
  1100. static Py_ssize_t
  1101. _Unpickler_SetStringInput(UnpicklerObject *self, PyObject *input)
  1102. {
  1103. if (self->buffer.buf != NULL)
  1104. PyBuffer_Release(&self->buffer);
  1105. if (PyObject_GetBuffer(input, &self->buffer, PyBUF_CONTIG_RO) < 0)
  1106. return -1;
  1107. self->input_buffer = self->buffer.buf;
  1108. self->input_len = self->buffer.len;
  1109. self->next_read_idx = 0;
  1110. self->prefetched_idx = self->input_len;
  1111. return self->input_len;
  1112. }
  1113. static int
  1114. bad_readline(PickleState *st)
  1115. {
  1116. PyErr_SetString(st->UnpicklingError, "pickle data was truncated");
  1117. return -1;
  1118. }
  1119. /* Skip any consumed data that was only prefetched using peek() */
  1120. static int
  1121. _Unpickler_SkipConsumed(UnpicklerObject *self)
  1122. {
  1123. Py_ssize_t consumed;
  1124. PyObject *r;
  1125. consumed = self->next_read_idx - self->prefetched_idx;
  1126. if (consumed <= 0)
  1127. return 0;
  1128. assert(self->peek); /* otherwise we did something wrong */
  1129. /* This makes a useless copy... */
  1130. r = PyObject_CallFunction(self->read, "n", consumed);
  1131. if (r == NULL)
  1132. return -1;
  1133. Py_DECREF(r);
  1134. self->prefetched_idx = self->next_read_idx;
  1135. return 0;
  1136. }
  1137. static const Py_ssize_t READ_WHOLE_LINE = -1;
  1138. /* If reading from a file, we need to only pull the bytes we need, since there
  1139. may be multiple pickle objects arranged contiguously in the same input
  1140. buffer.
  1141. If `n` is READ_WHOLE_LINE, read a whole line. Otherwise, read up to `n`
  1142. bytes from the input stream/buffer.
  1143. Update the unpickler's input buffer with the newly-read data. Returns -1 on
  1144. failure; on success, returns the number of bytes read from the file.
  1145. On success, self->input_len will be 0; this is intentional so that when
  1146. unpickling from a file, the "we've run out of data" code paths will trigger,
  1147. causing the Unpickler to go back to the file for more data. Use the returned
  1148. size to tell you how much data you can process. */
  1149. static Py_ssize_t
  1150. _Unpickler_ReadFromFile(UnpicklerObject *self, Py_ssize_t n)
  1151. {
  1152. PyObject *data;
  1153. Py_ssize_t read_size;
  1154. assert(self->read != NULL);
  1155. if (_Unpickler_SkipConsumed(self) < 0)
  1156. return -1;
  1157. if (n == READ_WHOLE_LINE) {
  1158. data = PyObject_CallNoArgs(self->readline);
  1159. }
  1160. else {
  1161. PyObject *len;
  1162. /* Prefetch some data without advancing the file pointer, if possible */
  1163. if (self->peek && n < PREFETCH) {
  1164. len = PyLong_FromSsize_t(PREFETCH);
  1165. if (len == NULL)
  1166. return -1;
  1167. data = _Pickle_FastCall(self->peek, len);
  1168. if (data == NULL) {
  1169. if (!PyErr_ExceptionMatches(PyExc_NotImplementedError))
  1170. return -1;
  1171. /* peek() is probably not supported by the given file object */
  1172. PyErr_Clear();
  1173. Py_CLEAR(self->peek);
  1174. }
  1175. else {
  1176. read_size = _Unpickler_SetStringInput(self, data);
  1177. Py_DECREF(data);
  1178. if (read_size < 0) {
  1179. return -1;
  1180. }
  1181. self->prefetched_idx = 0;
  1182. if (n <= read_size)
  1183. return n;
  1184. }
  1185. }
  1186. len = PyLong_FromSsize_t(n);
  1187. if (len == NULL)
  1188. return -1;
  1189. data = _Pickle_FastCall(self->read, len);
  1190. }
  1191. if (data == NULL)
  1192. return -1;
  1193. read_size = _Unpickler_SetStringInput(self, data);
  1194. Py_DECREF(data);
  1195. return read_size;
  1196. }
  1197. /* Don't call it directly: use _Unpickler_Read() */
  1198. static Py_ssize_t
  1199. _Unpickler_ReadImpl(UnpicklerObject *self, PickleState *st, char **s, Py_ssize_t n)
  1200. {
  1201. Py_ssize_t num_read;
  1202. *s = NULL;
  1203. if (self->next_read_idx > PY_SSIZE_T_MAX - n) {
  1204. PyErr_SetString(st->UnpicklingError,
  1205. "read would overflow (invalid bytecode)");
  1206. return -1;
  1207. }
  1208. /* This case is handled by the _Unpickler_Read() macro for efficiency */
  1209. assert(self->next_read_idx + n > self->input_len);
  1210. if (!self->read)
  1211. return bad_readline(st);
  1212. /* Extend the buffer to satisfy desired size */
  1213. num_read = _Unpickler_ReadFromFile(self, n);
  1214. if (num_read < 0)
  1215. return -1;
  1216. if (num_read < n)
  1217. return bad_readline(st);
  1218. *s = self->input_buffer;
  1219. self->next_read_idx = n;
  1220. return n;
  1221. }
  1222. /* Read `n` bytes from the unpickler's data source, storing the result in `buf`.
  1223. *
  1224. * This should only be used for non-small data reads where potentially
  1225. * avoiding a copy is beneficial. This method does not try to prefetch
  1226. * more data into the input buffer.
  1227. *
  1228. * _Unpickler_Read() is recommended in most cases.
  1229. */
  1230. static Py_ssize_t
  1231. _Unpickler_ReadInto(PickleState *state, UnpicklerObject *self, char *buf,
  1232. Py_ssize_t n)
  1233. {
  1234. assert(n != READ_WHOLE_LINE);
  1235. /* Read from available buffer data, if any */
  1236. Py_ssize_t in_buffer = self->input_len - self->next_read_idx;
  1237. if (in_buffer > 0) {
  1238. Py_ssize_t to_read = Py_MIN(in_buffer, n);
  1239. memcpy(buf, self->input_buffer + self->next_read_idx, to_read);
  1240. self->next_read_idx += to_read;
  1241. buf += to_read;
  1242. n -= to_read;
  1243. if (n == 0) {
  1244. /* Entire read was satisfied from buffer */
  1245. return n;
  1246. }
  1247. }
  1248. /* Read from file */
  1249. if (!self->read) {
  1250. /* We're unpickling memory, this means the input is truncated */
  1251. return bad_readline(state);
  1252. }
  1253. if (_Unpickler_SkipConsumed(self) < 0) {
  1254. return -1;
  1255. }
  1256. if (!self->readinto) {
  1257. /* readinto() not supported on file-like object, fall back to read()
  1258. * and copy into destination buffer (bpo-39681) */
  1259. PyObject* len = PyLong_FromSsize_t(n);
  1260. if (len == NULL) {
  1261. return -1;
  1262. }
  1263. PyObject* data = _Pickle_FastCall(self->read, len);
  1264. if (data == NULL) {
  1265. return -1;
  1266. }
  1267. if (!PyBytes_Check(data)) {
  1268. PyErr_Format(PyExc_ValueError,
  1269. "read() returned non-bytes object (%R)",
  1270. Py_TYPE(data));
  1271. Py_DECREF(data);
  1272. return -1;
  1273. }
  1274. Py_ssize_t read_size = PyBytes_GET_SIZE(data);
  1275. if (read_size < n) {
  1276. Py_DECREF(data);
  1277. return bad_readline(state);
  1278. }
  1279. memcpy(buf, PyBytes_AS_STRING(data), n);
  1280. Py_DECREF(data);
  1281. return n;
  1282. }
  1283. /* Call readinto() into user buffer */
  1284. PyObject *buf_obj = PyMemoryView_FromMemory(buf, n, PyBUF_WRITE);
  1285. if (buf_obj == NULL) {
  1286. return -1;
  1287. }
  1288. PyObject *read_size_obj = _Pickle_FastCall(self->readinto, buf_obj);
  1289. if (read_size_obj == NULL) {
  1290. return -1;
  1291. }
  1292. Py_ssize_t read_size = PyLong_AsSsize_t(read_size_obj);
  1293. Py_DECREF(read_size_obj);
  1294. if (read_size < 0) {
  1295. if (!PyErr_Occurred()) {
  1296. PyErr_SetString(PyExc_ValueError,
  1297. "readinto() returned negative size");
  1298. }
  1299. return -1;
  1300. }
  1301. if (read_size < n) {
  1302. return bad_readline(state);
  1303. }
  1304. return n;
  1305. }
  1306. /* Read `n` bytes from the unpickler's data source, storing the result in `*s`.
  1307. This should be used for all data reads, rather than accessing the unpickler's
  1308. input buffer directly. This method deals correctly with reading from input
  1309. streams, which the input buffer doesn't deal with.
  1310. Note that when reading from a file-like object, self->next_read_idx won't
  1311. be updated (it should remain at 0 for the entire unpickling process). You
  1312. should use this function's return value to know how many bytes you can
  1313. consume.
  1314. Returns -1 (with an exception set) on failure. On success, return the
  1315. number of chars read. */
  1316. #define _Unpickler_Read(self, state, s, n) \
  1317. (((n) <= (self)->input_len - (self)->next_read_idx) \
  1318. ? (*(s) = (self)->input_buffer + (self)->next_read_idx, \
  1319. (self)->next_read_idx += (n), \
  1320. (n)) \
  1321. : _Unpickler_ReadImpl(self, state, (s), (n)))
  1322. static Py_ssize_t
  1323. _Unpickler_CopyLine(UnpicklerObject *self, char *line, Py_ssize_t len,
  1324. char **result)
  1325. {
  1326. char *input_line = PyMem_Realloc(self->input_line, len + 1);
  1327. if (input_line == NULL) {
  1328. PyErr_NoMemory();
  1329. return -1;
  1330. }
  1331. memcpy(input_line, line, len);
  1332. input_line[len] = '\0';
  1333. self->input_line = input_line;
  1334. *result = self->input_line;
  1335. return len;
  1336. }
  1337. /* Read a line from the input stream/buffer. If we run off the end of the input
  1338. before hitting \n, raise an error.
  1339. Returns the number of chars read, or -1 on failure. */
  1340. static Py_ssize_t
  1341. _Unpickler_Readline(PickleState *state, UnpicklerObject *self, char **result)
  1342. {
  1343. Py_ssize_t i, num_read;
  1344. for (i = self->next_read_idx; i < self->input_len; i++) {
  1345. if (self->input_buffer[i] == '\n') {
  1346. char *line_start = self->input_buffer + self->next_read_idx;
  1347. num_read = i - self->next_read_idx + 1;
  1348. self->next_read_idx = i + 1;
  1349. return _Unpickler_CopyLine(self, line_start, num_read, result);
  1350. }
  1351. }
  1352. if (!self->read)
  1353. return bad_readline(state);
  1354. num_read = _Unpickler_ReadFromFile(self, READ_WHOLE_LINE);
  1355. if (num_read < 0)
  1356. return -1;
  1357. if (num_read == 0 || self->input_buffer[num_read - 1] != '\n')
  1358. return bad_readline(state);
  1359. self->next_read_idx = num_read;
  1360. return _Unpickler_CopyLine(self, self->input_buffer, num_read, result);
  1361. }
  1362. /* Returns -1 (with an exception set) on failure, 0 on success. The memo array
  1363. will be modified in place. */
  1364. static int
  1365. _Unpickler_ResizeMemoList(UnpicklerObject *self, size_t new_size)
  1366. {
  1367. size_t i;
  1368. assert(new_size > self->memo_size);
  1369. PyObject **memo_new = self->memo;
  1370. PyMem_RESIZE(memo_new, PyObject *, new_size);
  1371. if (memo_new == NULL) {
  1372. PyErr_NoMemory();
  1373. return -1;
  1374. }
  1375. self->memo = memo_new;
  1376. for (i = self->memo_size; i < new_size; i++)
  1377. self->memo[i] = NULL;
  1378. self->memo_size = new_size;
  1379. return 0;
  1380. }
  1381. /* Returns NULL if idx is out of bounds. */
  1382. static PyObject *
  1383. _Unpickler_MemoGet(UnpicklerObject *self, size_t idx)
  1384. {
  1385. if (idx >= self->memo_size)
  1386. return NULL;
  1387. return self->memo[idx];
  1388. }
  1389. /* Returns -1 (with an exception set) on failure, 0 on success.
  1390. This takes its own reference to `value`. */
  1391. static int
  1392. _Unpickler_MemoPut(UnpicklerObject *self, size_t idx, PyObject *value)
  1393. {
  1394. PyObject *old_item;
  1395. if (idx >= self->memo_size) {
  1396. if (_Unpickler_ResizeMemoList(self, idx * 2) < 0)
  1397. return -1;
  1398. assert(idx < self->memo_size);
  1399. }
  1400. old_item = self->memo[idx];
  1401. self->memo[idx] = Py_NewRef(value);
  1402. if (old_item != NULL) {
  1403. Py_DECREF(old_item);
  1404. }
  1405. else {
  1406. self->memo_len++;
  1407. }
  1408. return 0;
  1409. }
  1410. static PyObject **
  1411. _Unpickler_NewMemo(Py_ssize_t new_size)
  1412. {
  1413. PyObject **memo = PyMem_NEW(PyObject *, new_size);
  1414. if (memo == NULL) {
  1415. PyErr_NoMemory();
  1416. return NULL;
  1417. }
  1418. memset(memo, 0, new_size * sizeof(PyObject *));
  1419. return memo;
  1420. }
  1421. /* Free the unpickler's memo, taking care to decref any items left in it. */
  1422. static void
  1423. _Unpickler_MemoCleanup(UnpicklerObject *self)
  1424. {
  1425. Py_ssize_t i;
  1426. PyObject **memo = self->memo;
  1427. if (self->memo == NULL)
  1428. return;
  1429. self->memo = NULL;
  1430. i = self->memo_size;
  1431. while (--i >= 0) {
  1432. Py_XDECREF(memo[i]);
  1433. }
  1434. PyMem_Free(memo);
  1435. }
  1436. static UnpicklerObject *
  1437. _Unpickler_New(PyObject *module)
  1438. {
  1439. const int MEMO_SIZE = 32;
  1440. PyObject **memo = _Unpickler_NewMemo(MEMO_SIZE);
  1441. if (memo == NULL) {
  1442. return NULL;
  1443. }
  1444. PickleState *st = _Pickle_GetState(module);
  1445. PyObject *stack = Pdata_New(st);
  1446. if (stack == NULL) {
  1447. goto error;
  1448. }
  1449. UnpicklerObject *self = PyObject_GC_New(UnpicklerObject,
  1450. st->Unpickler_Type);
  1451. if (self == NULL) {
  1452. goto error;
  1453. }
  1454. self->stack = (Pdata *)stack;
  1455. self->memo = memo;
  1456. self->memo_size = MEMO_SIZE;
  1457. self->memo_len = 0;
  1458. self->pers_func = NULL;
  1459. self->pers_func_self = NULL;
  1460. memset(&self->buffer, 0, sizeof(Py_buffer));
  1461. self->input_buffer = NULL;
  1462. self->input_line = NULL;
  1463. self->input_len = 0;
  1464. self->next_read_idx = 0;
  1465. self->prefetched_idx = 0;
  1466. self->read = NULL;
  1467. self->readinto = NULL;
  1468. self->readline = NULL;
  1469. self->peek = NULL;
  1470. self->buffers = NULL;
  1471. self->encoding = NULL;
  1472. self->errors = NULL;
  1473. self->marks = NULL;
  1474. self->num_marks = 0;
  1475. self->marks_size = 0;
  1476. self->proto = 0;
  1477. self->fix_imports = 0;
  1478. PyObject_GC_Track(self);
  1479. return self;
  1480. error:
  1481. PyMem_Free(memo);
  1482. Py_XDECREF(stack);
  1483. return NULL;
  1484. }
  1485. /* Returns -1 (with an exception set) on failure, 0 on success. This may
  1486. be called once on a freshly created Unpickler. */
  1487. static int
  1488. _Unpickler_SetInputStream(UnpicklerObject *self, PyObject *file)
  1489. {
  1490. /* Optional file methods */
  1491. if (_PyObject_LookupAttr(file, &_Py_ID(peek), &self->peek) < 0) {
  1492. goto error;
  1493. }
  1494. if (_PyObject_LookupAttr(file, &_Py_ID(readinto), &self->readinto) < 0) {
  1495. goto error;
  1496. }
  1497. if (_PyObject_LookupAttr(file, &_Py_ID(read), &self->read) < 0) {
  1498. goto error;
  1499. }
  1500. if (_PyObject_LookupAttr(file, &_Py_ID(readline), &self->readline) < 0) {
  1501. goto error;
  1502. }
  1503. if (!self->readline || !self->read) {
  1504. PyErr_SetString(PyExc_TypeError,
  1505. "file must have 'read' and 'readline' attributes");
  1506. goto error;
  1507. }
  1508. return 0;
  1509. error:
  1510. Py_CLEAR(self->read);
  1511. Py_CLEAR(self->readinto);
  1512. Py_CLEAR(self->readline);
  1513. Py_CLEAR(self->peek);
  1514. return -1;
  1515. }
  1516. /* Returns -1 (with an exception set) on failure, 0 on success. This may
  1517. be called once on a freshly created Unpickler. */
  1518. static int
  1519. _Unpickler_SetInputEncoding(UnpicklerObject *self,
  1520. const char *encoding,
  1521. const char *errors)
  1522. {
  1523. if (encoding == NULL)
  1524. encoding = "ASCII";
  1525. if (errors == NULL)
  1526. errors = "strict";
  1527. self->encoding = _PyMem_Strdup(encoding);
  1528. self->errors = _PyMem_Strdup(errors);
  1529. if (self->encoding == NULL || self->errors == NULL) {
  1530. PyErr_NoMemory();
  1531. return -1;
  1532. }
  1533. return 0;
  1534. }
  1535. /* Returns -1 (with an exception set) on failure, 0 on success. This may
  1536. be called once on a freshly created Unpickler. */
  1537. static int
  1538. _Unpickler_SetBuffers(UnpicklerObject *self, PyObject *buffers)
  1539. {
  1540. if (buffers == NULL || buffers == Py_None) {
  1541. self->buffers = NULL;
  1542. }
  1543. else {
  1544. self->buffers = PyObject_GetIter(buffers);
  1545. if (self->buffers == NULL) {
  1546. return -1;
  1547. }
  1548. }
  1549. return 0;
  1550. }
  1551. /* Generate a GET opcode for an object stored in the memo. */
  1552. static int
  1553. memo_get(PickleState *st, PicklerObject *self, PyObject *key)
  1554. {
  1555. Py_ssize_t *value;
  1556. char pdata[30];
  1557. Py_ssize_t len;
  1558. value = PyMemoTable_Get(self->memo, key);
  1559. if (value == NULL) {
  1560. PyErr_SetObject(PyExc_KeyError, key);
  1561. return -1;
  1562. }
  1563. if (!self->bin) {
  1564. pdata[0] = GET;
  1565. PyOS_snprintf(pdata + 1, sizeof(pdata) - 1,
  1566. "%zd\n", *value);
  1567. len = strlen(pdata);
  1568. }
  1569. else {
  1570. if (*value < 256) {
  1571. pdata[0] = BINGET;
  1572. pdata[1] = (unsigned char)(*value & 0xff);
  1573. len = 2;
  1574. }
  1575. else if ((size_t)*value <= 0xffffffffUL) {
  1576. pdata[0] = LONG_BINGET;
  1577. pdata[1] = (unsigned char)(*value & 0xff);
  1578. pdata[2] = (unsigned char)((*value >> 8) & 0xff);
  1579. pdata[3] = (unsigned char)((*value >> 16) & 0xff);
  1580. pdata[4] = (unsigned char)((*value >> 24) & 0xff);
  1581. len = 5;
  1582. }
  1583. else { /* unlikely */
  1584. PyErr_SetString(st->PicklingError,
  1585. "memo id too large for LONG_BINGET");
  1586. return -1;
  1587. }
  1588. }
  1589. if (_Pickler_Write(self, pdata, len) < 0)
  1590. return -1;
  1591. return 0;
  1592. }
  1593. /* Store an object in the memo, assign it a new unique ID based on the number
  1594. of objects currently stored in the memo and generate a PUT opcode. */
  1595. static int
  1596. memo_put(PickleState *st, PicklerObject *self, PyObject *obj)
  1597. {
  1598. char pdata[30];
  1599. Py_ssize_t len;
  1600. Py_ssize_t idx;
  1601. const char memoize_op = MEMOIZE;
  1602. if (self->fast)
  1603. return 0;
  1604. idx = PyMemoTable_Size(self->memo);
  1605. if (PyMemoTable_Set(self->memo, obj, idx) < 0)
  1606. return -1;
  1607. if (self->proto >= 4) {
  1608. if (_Pickler_Write(self, &memoize_op, 1) < 0)
  1609. return -1;
  1610. return 0;
  1611. }
  1612. else if (!self->bin) {
  1613. pdata[0] = PUT;
  1614. PyOS_snprintf(pdata + 1, sizeof(pdata) - 1,
  1615. "%zd\n", idx);
  1616. len = strlen(pdata);
  1617. }
  1618. else {
  1619. if (idx < 256) {
  1620. pdata[0] = BINPUT;
  1621. pdata[1] = (unsigned char)idx;
  1622. len = 2;
  1623. }
  1624. else if ((size_t)idx <= 0xffffffffUL) {
  1625. pdata[0] = LONG_BINPUT;
  1626. pdata[1] = (unsigned char)(idx & 0xff);
  1627. pdata[2] = (unsigned char)((idx >> 8) & 0xff);
  1628. pdata[3] = (unsigned char)((idx >> 16) & 0xff);
  1629. pdata[4] = (unsigned char)((idx >> 24) & 0xff);
  1630. len = 5;
  1631. }
  1632. else { /* unlikely */
  1633. PyErr_SetString(st->PicklingError,
  1634. "memo id too large for LONG_BINPUT");
  1635. return -1;
  1636. }
  1637. }
  1638. if (_Pickler_Write(self, pdata, len) < 0)
  1639. return -1;
  1640. return 0;
  1641. }
  1642. static PyObject *
  1643. get_dotted_path(PyObject *obj, PyObject *name)
  1644. {
  1645. PyObject *dotted_path;
  1646. Py_ssize_t i, n;
  1647. dotted_path = PyUnicode_Split(name, _Py_LATIN1_CHR('.'), -1);
  1648. if (dotted_path == NULL)
  1649. return NULL;
  1650. n = PyList_GET_SIZE(dotted_path);
  1651. assert(n >= 1);
  1652. for (i = 0; i < n; i++) {
  1653. PyObject *subpath = PyList_GET_ITEM(dotted_path, i);
  1654. if (_PyUnicode_EqualToASCIIString(subpath, "<locals>")) {
  1655. if (obj == NULL)
  1656. PyErr_Format(PyExc_AttributeError,
  1657. "Can't get local object %R", name);
  1658. else
  1659. PyErr_Format(PyExc_AttributeError,
  1660. "Can't get local attribute %R on %R", name, obj);
  1661. Py_DECREF(dotted_path);
  1662. return NULL;
  1663. }
  1664. }
  1665. return dotted_path;
  1666. }
  1667. static PyObject *
  1668. get_deep_attribute(PyObject *obj, PyObject *names, PyObject **pparent)
  1669. {
  1670. Py_ssize_t i, n;
  1671. PyObject *parent = NULL;
  1672. assert(PyList_CheckExact(names));
  1673. Py_INCREF(obj);
  1674. n = PyList_GET_SIZE(names);
  1675. for (i = 0; i < n; i++) {
  1676. PyObject *name = PyList_GET_ITEM(names, i);
  1677. Py_XSETREF(parent, obj);
  1678. (void)_PyObject_LookupAttr(parent, name, &obj);
  1679. if (obj == NULL) {
  1680. Py_DECREF(parent);
  1681. return NULL;
  1682. }
  1683. }
  1684. if (pparent != NULL)
  1685. *pparent = parent;
  1686. else
  1687. Py_XDECREF(parent);
  1688. return obj;
  1689. }
  1690. static PyObject *
  1691. getattribute(PyObject *obj, PyObject *name, int allow_qualname)
  1692. {
  1693. PyObject *dotted_path, *attr;
  1694. if (allow_qualname) {
  1695. dotted_path = get_dotted_path(obj, name);
  1696. if (dotted_path == NULL)
  1697. return NULL;
  1698. attr = get_deep_attribute(obj, dotted_path, NULL);
  1699. Py_DECREF(dotted_path);
  1700. }
  1701. else {
  1702. (void)_PyObject_LookupAttr(obj, name, &attr);
  1703. }
  1704. if (attr == NULL && !PyErr_Occurred()) {
  1705. PyErr_Format(PyExc_AttributeError,
  1706. "Can't get attribute %R on %R", name, obj);
  1707. }
  1708. return attr;
  1709. }
  1710. static int
  1711. _checkmodule(PyObject *module_name, PyObject *module,
  1712. PyObject *global, PyObject *dotted_path)
  1713. {
  1714. if (module == Py_None) {
  1715. return -1;
  1716. }
  1717. if (PyUnicode_Check(module_name) &&
  1718. _PyUnicode_EqualToASCIIString(module_name, "__main__")) {
  1719. return -1;
  1720. }
  1721. PyObject *candidate = get_deep_attribute(module, dotted_path, NULL);
  1722. if (candidate == NULL) {
  1723. return -1;
  1724. }
  1725. if (candidate != global) {
  1726. Py_DECREF(candidate);
  1727. return -1;
  1728. }
  1729. Py_DECREF(candidate);
  1730. return 0;
  1731. }
  1732. static PyObject *
  1733. whichmodule(PyObject *global, PyObject *dotted_path)
  1734. {
  1735. PyObject *module_name;
  1736. PyObject *module = NULL;
  1737. Py_ssize_t i;
  1738. PyObject *modules;
  1739. if (_PyObject_LookupAttr(global, &_Py_ID(__module__), &module_name) < 0) {
  1740. return NULL;
  1741. }
  1742. if (module_name) {
  1743. /* In some rare cases (e.g., bound methods of extension types),
  1744. __module__ can be None. If it is so, then search sys.modules for
  1745. the module of global. */
  1746. if (module_name != Py_None)
  1747. return module_name;
  1748. Py_CLEAR(module_name);
  1749. }
  1750. assert(module_name == NULL);
  1751. /* Fallback on walking sys.modules */
  1752. PyThreadState *tstate = _PyThreadState_GET();
  1753. modules = _PySys_GetAttr(tstate, &_Py_ID(modules));
  1754. if (modules == NULL) {
  1755. PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
  1756. return NULL;
  1757. }
  1758. if (PyDict_CheckExact(modules)) {
  1759. i = 0;
  1760. while (PyDict_Next(modules, &i, &module_name, &module)) {
  1761. if (_checkmodule(module_name, module, global, dotted_path) == 0) {
  1762. return Py_NewRef(module_name);
  1763. }
  1764. if (PyErr_Occurred()) {
  1765. return NULL;
  1766. }
  1767. }
  1768. }
  1769. else {
  1770. PyObject *iterator = PyObject_GetIter(modules);
  1771. if (iterator == NULL) {
  1772. return NULL;
  1773. }
  1774. while ((module_name = PyIter_Next(iterator))) {
  1775. module = PyObject_GetItem(modules, module_name);
  1776. if (module == NULL) {
  1777. Py_DECREF(module_name);
  1778. Py_DECREF(iterator);
  1779. return NULL;
  1780. }
  1781. if (_checkmodule(module_name, module, global, dotted_path) == 0) {
  1782. Py_DECREF(module);
  1783. Py_DECREF(iterator);
  1784. return module_name;
  1785. }
  1786. Py_DECREF(module);
  1787. Py_DECREF(module_name);
  1788. if (PyErr_Occurred()) {
  1789. Py_DECREF(iterator);
  1790. return NULL;
  1791. }
  1792. }
  1793. Py_DECREF(iterator);
  1794. }
  1795. /* If no module is found, use __main__. */
  1796. module_name = &_Py_ID(__main__);
  1797. return Py_NewRef(module_name);
  1798. }
  1799. /* fast_save_enter() and fast_save_leave() are guards against recursive
  1800. objects when Pickler is used with the "fast mode" (i.e., with object
  1801. memoization disabled). If the nesting of a list or dict object exceed
  1802. FAST_NESTING_LIMIT, these guards will start keeping an internal
  1803. reference to the seen list or dict objects and check whether these objects
  1804. are recursive. These are not strictly necessary, since save() has a
  1805. hard-coded recursion limit, but they give a nicer error message than the
  1806. typical RuntimeError. */
  1807. static int
  1808. fast_save_enter(PicklerObject *self, PyObject *obj)
  1809. {
  1810. /* if fast_nesting < 0, we're doing an error exit. */
  1811. if (++self->fast_nesting >= FAST_NESTING_LIMIT) {
  1812. PyObject *key = NULL;
  1813. if (self->fast_memo == NULL) {
  1814. self->fast_memo = PyDict_New();
  1815. if (self->fast_memo == NULL) {
  1816. self->fast_nesting = -1;
  1817. return 0;
  1818. }
  1819. }
  1820. key = PyLong_FromVoidPtr(obj);
  1821. if (key == NULL) {
  1822. self->fast_nesting = -1;
  1823. return 0;
  1824. }
  1825. int r = PyDict_Contains(self->fast_memo, key);
  1826. if (r > 0) {
  1827. PyErr_Format(PyExc_ValueError,
  1828. "fast mode: can't pickle cyclic objects "
  1829. "including object type %.200s at %p",
  1830. Py_TYPE(obj)->tp_name, obj);
  1831. }
  1832. else if (r == 0) {
  1833. r = PyDict_SetItem(self->fast_memo, key, Py_None);
  1834. }
  1835. Py_DECREF(key);
  1836. if (r != 0) {
  1837. self->fast_nesting = -1;
  1838. return 0;
  1839. }
  1840. }
  1841. return 1;
  1842. }
  1843. static int
  1844. fast_save_leave(PicklerObject *self, PyObject *obj)
  1845. {
  1846. if (self->fast_nesting-- >= FAST_NESTING_LIMIT) {
  1847. PyObject *key = PyLong_FromVoidPtr(obj);
  1848. if (key == NULL)
  1849. return 0;
  1850. if (PyDict_DelItem(self->fast_memo, key) < 0) {
  1851. Py_DECREF(key);
  1852. return 0;
  1853. }
  1854. Py_DECREF(key);
  1855. }
  1856. return 1;
  1857. }
  1858. static int
  1859. save_none(PicklerObject *self, PyObject *obj)
  1860. {
  1861. const char none_op = NONE;
  1862. if (_Pickler_Write(self, &none_op, 1) < 0)
  1863. return -1;
  1864. return 0;
  1865. }
  1866. static int
  1867. save_bool(PicklerObject *self, PyObject *obj)
  1868. {
  1869. if (self->proto >= 2) {
  1870. const char bool_op = (obj == Py_True) ? NEWTRUE : NEWFALSE;
  1871. if (_Pickler_Write(self, &bool_op, 1) < 0)
  1872. return -1;
  1873. }
  1874. else {
  1875. /* These aren't opcodes -- they're ways to pickle bools before protocol 2
  1876. * so that unpicklers written before bools were introduced unpickle them
  1877. * as ints, but unpicklers after can recognize that bools were intended.
  1878. * Note that protocol 2 added direct ways to pickle bools.
  1879. */
  1880. const char *bool_str = (obj == Py_True) ? "I01\n" : "I00\n";
  1881. if (_Pickler_Write(self, bool_str, strlen(bool_str)) < 0)
  1882. return -1;
  1883. }
  1884. return 0;
  1885. }
  1886. static int
  1887. save_long(PicklerObject *self, PyObject *obj)
  1888. {
  1889. PyObject *repr = NULL;
  1890. Py_ssize_t size;
  1891. long val;
  1892. int overflow;
  1893. int status = 0;
  1894. val= PyLong_AsLongAndOverflow(obj, &overflow);
  1895. if (!overflow && (sizeof(long) <= 4 ||
  1896. (val <= 0x7fffffffL && val >= (-0x7fffffffL - 1))))
  1897. {
  1898. /* result fits in a signed 4-byte integer.
  1899. Note: we can't use -0x80000000L in the above condition because some
  1900. compilers (e.g., MSVC) will promote 0x80000000L to an unsigned type
  1901. before applying the unary minus when sizeof(long) <= 4. The
  1902. resulting value stays unsigned which is commonly not what we want,
  1903. so MSVC happily warns us about it. However, that result would have
  1904. been fine because we guard for sizeof(long) <= 4 which turns the
  1905. condition true in that particular case. */
  1906. char pdata[32];
  1907. Py_ssize_t len = 0;
  1908. if (self->bin) {
  1909. pdata[1] = (unsigned char)(val & 0xff);
  1910. pdata[2] = (unsigned char)((val >> 8) & 0xff);
  1911. pdata[3] = (unsigned char)((val >> 16) & 0xff);
  1912. pdata[4] = (unsigned char)((val >> 24) & 0xff);
  1913. if ((pdata[4] != 0) || (pdata[3] != 0)) {
  1914. pdata[0] = BININT;
  1915. len = 5;
  1916. }
  1917. else if (pdata[2] != 0) {
  1918. pdata[0] = BININT2;
  1919. len = 3;
  1920. }
  1921. else {
  1922. pdata[0] = BININT1;
  1923. len = 2;
  1924. }
  1925. }
  1926. else {
  1927. sprintf(pdata, "%c%ld\n", INT, val);
  1928. len = strlen(pdata);
  1929. }
  1930. if (_Pickler_Write(self, pdata, len) < 0)
  1931. return -1;
  1932. return 0;
  1933. }
  1934. assert(!PyErr_Occurred());
  1935. if (self->proto >= 2) {
  1936. /* Linear-time pickling. */
  1937. size_t nbits;
  1938. size_t nbytes;
  1939. unsigned char *pdata;
  1940. char header[5];
  1941. int i;
  1942. int sign = _PyLong_Sign(obj);
  1943. if (sign == 0) {
  1944. header[0] = LONG1;
  1945. header[1] = 0; /* It's 0 -- an empty bytestring. */
  1946. if (_Pickler_Write(self, header, 2) < 0)
  1947. goto error;
  1948. return 0;
  1949. }
  1950. nbits = _PyLong_NumBits(obj);
  1951. if (nbits == (size_t)-1 && PyErr_Occurred())
  1952. goto error;
  1953. /* How many bytes do we need? There are nbits >> 3 full
  1954. * bytes of data, and nbits & 7 leftover bits. If there
  1955. * are any leftover bits, then we clearly need another
  1956. * byte. What's not so obvious is that we *probably*
  1957. * need another byte even if there aren't any leftovers:
  1958. * the most-significant bit of the most-significant byte
  1959. * acts like a sign bit, and it's usually got a sense
  1960. * opposite of the one we need. The exception is ints
  1961. * of the form -(2**(8*j-1)) for j > 0. Such an int is
  1962. * its own 256's-complement, so has the right sign bit
  1963. * even without the extra byte. That's a pain to check
  1964. * for in advance, though, so we always grab an extra
  1965. * byte at the start, and cut it back later if possible.
  1966. */
  1967. nbytes = (nbits >> 3) + 1;
  1968. if (nbytes > 0x7fffffffL) {
  1969. PyErr_SetString(PyExc_OverflowError,
  1970. "int too large to pickle");
  1971. goto error;
  1972. }
  1973. repr = PyBytes_FromStringAndSize(NULL, (Py_ssize_t)nbytes);
  1974. if (repr == NULL)
  1975. goto error;
  1976. pdata = (unsigned char *)PyBytes_AS_STRING(repr);
  1977. i = _PyLong_AsByteArray((PyLongObject *)obj,
  1978. pdata, nbytes,
  1979. 1 /* little endian */ , 1 /* signed */ );
  1980. if (i < 0)
  1981. goto error;
  1982. /* If the int is negative, this may be a byte more than
  1983. * needed. This is so iff the MSB is all redundant sign
  1984. * bits.
  1985. */
  1986. if (sign < 0 &&
  1987. nbytes > 1 &&
  1988. pdata[nbytes - 1] == 0xff &&
  1989. (pdata[nbytes - 2] & 0x80) != 0) {
  1990. nbytes--;
  1991. }
  1992. if (nbytes < 256) {
  1993. header[0] = LONG1;
  1994. header[1] = (unsigned char)nbytes;
  1995. size = 2;
  1996. }
  1997. else {
  1998. header[0] = LONG4;
  1999. size = (Py_ssize_t) nbytes;
  2000. for (i = 1; i < 5; i++) {
  2001. header[i] = (unsigned char)(size & 0xff);
  2002. size >>= 8;
  2003. }
  2004. size = 5;
  2005. }
  2006. if (_Pickler_Write(self, header, size) < 0 ||
  2007. _Pickler_Write(self, (char *)pdata, (int)nbytes) < 0)
  2008. goto error;
  2009. }
  2010. else {
  2011. const char long_op = LONG;
  2012. const char *string;
  2013. /* proto < 2: write the repr and newline. This is quadratic-time (in
  2014. the number of digits), in both directions. We add a trailing 'L'
  2015. to the repr, for compatibility with Python 2.x. */
  2016. repr = PyObject_Repr(obj);
  2017. if (repr == NULL)
  2018. goto error;
  2019. string = PyUnicode_AsUTF8AndSize(repr, &size);
  2020. if (string == NULL)
  2021. goto error;
  2022. if (_Pickler_Write(self, &long_op, 1) < 0 ||
  2023. _Pickler_Write(self, string, size) < 0 ||
  2024. _Pickler_Write(self, "L\n", 2) < 0)
  2025. goto error;
  2026. }
  2027. if (0) {
  2028. error:
  2029. status = -1;
  2030. }
  2031. Py_XDECREF(repr);
  2032. return status;
  2033. }
  2034. static int
  2035. save_float(PicklerObject *self, PyObject *obj)
  2036. {
  2037. double x = PyFloat_AS_DOUBLE((PyFloatObject *)obj);
  2038. if (self->bin) {
  2039. char pdata[9];
  2040. pdata[0] = BINFLOAT;
  2041. if (PyFloat_Pack8(x, &pdata[1], 0) < 0)
  2042. return -1;
  2043. if (_Pickler_Write(self, pdata, 9) < 0)
  2044. return -1;
  2045. }
  2046. else {
  2047. int result = -1;
  2048. char *buf = NULL;
  2049. char op = FLOAT;
  2050. if (_Pickler_Write(self, &op, 1) < 0)
  2051. goto done;
  2052. buf = PyOS_double_to_string(x, 'r', 0, Py_DTSF_ADD_DOT_0, NULL);
  2053. if (!buf) {
  2054. PyErr_NoMemory();
  2055. goto done;
  2056. }
  2057. if (_Pickler_Write(self, buf, strlen(buf)) < 0)
  2058. goto done;
  2059. if (_Pickler_Write(self, "\n", 1) < 0)
  2060. goto done;
  2061. result = 0;
  2062. done:
  2063. PyMem_Free(buf);
  2064. return result;
  2065. }
  2066. return 0;
  2067. }
  2068. /* Perform direct write of the header and payload of the binary object.
  2069. The large contiguous data is written directly into the underlying file
  2070. object, bypassing the output_buffer of the Pickler. We intentionally
  2071. do not insert a protocol 4 frame opcode to make it possible to optimize
  2072. file.read calls in the loader.
  2073. */
  2074. static int
  2075. _Pickler_write_bytes(PicklerObject *self,
  2076. const char *header, Py_ssize_t header_size,
  2077. const char *data, Py_ssize_t data_size,
  2078. PyObject *payload)
  2079. {
  2080. int bypass_buffer = (data_size >= FRAME_SIZE_TARGET);
  2081. int framing = self->framing;
  2082. if (bypass_buffer) {
  2083. assert(self->output_buffer != NULL);
  2084. /* Commit the previous frame. */
  2085. if (_Pickler_CommitFrame(self)) {
  2086. return -1;
  2087. }
  2088. /* Disable framing temporarily */
  2089. self->framing = 0;
  2090. }
  2091. if (_Pickler_Write(self, header, header_size) < 0) {
  2092. return -1;
  2093. }
  2094. if (bypass_buffer && self->write != NULL) {
  2095. /* Bypass the in-memory buffer to directly stream large data
  2096. into the underlying file object. */
  2097. PyObject *result, *mem = NULL;
  2098. /* Dump the output buffer to the file. */
  2099. if (_Pickler_FlushToFile(self) < 0) {
  2100. return -1;
  2101. }
  2102. /* Stream write the payload into the file without going through the
  2103. output buffer. */
  2104. if (payload == NULL) {
  2105. /* TODO: It would be better to use a memoryview with a linked
  2106. original string if this is possible. */
  2107. payload = mem = PyBytes_FromStringAndSize(data, data_size);
  2108. if (payload == NULL) {
  2109. return -1;
  2110. }
  2111. }
  2112. result = PyObject_CallOneArg(self->write, payload);
  2113. Py_XDECREF(mem);
  2114. if (result == NULL) {
  2115. return -1;
  2116. }
  2117. Py_DECREF(result);
  2118. /* Reinitialize the buffer for subsequent calls to _Pickler_Write. */
  2119. if (_Pickler_ClearBuffer(self) < 0) {
  2120. return -1;
  2121. }
  2122. }
  2123. else {
  2124. if (_Pickler_Write(self, data, data_size) < 0) {
  2125. return -1;
  2126. }
  2127. }
  2128. /* Re-enable framing for subsequent calls to _Pickler_Write. */
  2129. self->framing = framing;
  2130. return 0;
  2131. }
  2132. static int
  2133. _save_bytes_data(PickleState *st, PicklerObject *self, PyObject *obj,
  2134. const char *data, Py_ssize_t size)
  2135. {
  2136. assert(self->proto >= 3);
  2137. char header[9];
  2138. Py_ssize_t len;
  2139. if (size < 0)
  2140. return -1;
  2141. if (size <= 0xff) {
  2142. header[0] = SHORT_BINBYTES;
  2143. header[1] = (unsigned char)size;
  2144. len = 2;
  2145. }
  2146. else if ((size_t)size <= 0xffffffffUL) {
  2147. header[0] = BINBYTES;
  2148. header[1] = (unsigned char)(size & 0xff);
  2149. header[2] = (unsigned char)((size >> 8) & 0xff);
  2150. header[3] = (unsigned char)((size >> 16) & 0xff);
  2151. header[4] = (unsigned char)((size >> 24) & 0xff);
  2152. len = 5;
  2153. }
  2154. else if (self->proto >= 4) {
  2155. header[0] = BINBYTES8;
  2156. _write_size64(header + 1, size);
  2157. len = 9;
  2158. }
  2159. else {
  2160. PyErr_SetString(PyExc_OverflowError,
  2161. "serializing a bytes object larger than 4 GiB "
  2162. "requires pickle protocol 4 or higher");
  2163. return -1;
  2164. }
  2165. if (_Pickler_write_bytes(self, header, len, data, size, obj) < 0) {
  2166. return -1;
  2167. }
  2168. if (memo_put(st, self, obj) < 0) {
  2169. return -1;
  2170. }
  2171. return 0;
  2172. }
  2173. static int
  2174. save_bytes(PickleState *st, PicklerObject *self, PyObject *obj)
  2175. {
  2176. if (self->proto < 3) {
  2177. /* Older pickle protocols do not have an opcode for pickling bytes
  2178. objects. Therefore, we need to fake the copy protocol (i.e.,
  2179. the __reduce__ method) to permit bytes object unpickling.
  2180. Here we use a hack to be compatible with Python 2. Since in Python
  2181. 2 'bytes' is just an alias for 'str' (which has different
  2182. parameters than the actual bytes object), we use codecs.encode
  2183. to create the appropriate 'str' object when unpickled using
  2184. Python 2 *and* the appropriate 'bytes' object when unpickled
  2185. using Python 3. Again this is a hack and we don't need to do this
  2186. with newer protocols. */
  2187. PyObject *reduce_value;
  2188. int status;
  2189. if (PyBytes_GET_SIZE(obj) == 0) {
  2190. reduce_value = Py_BuildValue("(O())", (PyObject*)&PyBytes_Type);
  2191. }
  2192. else {
  2193. PyObject *unicode_str =
  2194. PyUnicode_DecodeLatin1(PyBytes_AS_STRING(obj),
  2195. PyBytes_GET_SIZE(obj),
  2196. "strict");
  2197. if (unicode_str == NULL)
  2198. return -1;
  2199. reduce_value = Py_BuildValue("(O(OO))",
  2200. st->codecs_encode, unicode_str,
  2201. &_Py_ID(latin1));
  2202. Py_DECREF(unicode_str);
  2203. }
  2204. if (reduce_value == NULL)
  2205. return -1;
  2206. /* save_reduce() will memoize the object automatically. */
  2207. status = save_reduce(st, self, reduce_value, obj);
  2208. Py_DECREF(reduce_value);
  2209. return status;
  2210. }
  2211. else {
  2212. return _save_bytes_data(st, self, obj, PyBytes_AS_STRING(obj),
  2213. PyBytes_GET_SIZE(obj));
  2214. }
  2215. }
  2216. static int
  2217. _save_bytearray_data(PickleState *state, PicklerObject *self, PyObject *obj,
  2218. const char *data, Py_ssize_t size)
  2219. {
  2220. assert(self->proto >= 5);
  2221. char header[9];
  2222. Py_ssize_t len;
  2223. if (size < 0)
  2224. return -1;
  2225. header[0] = BYTEARRAY8;
  2226. _write_size64(header + 1, size);
  2227. len = 9;
  2228. if (_Pickler_write_bytes(self, header, len, data, size, obj) < 0) {
  2229. return -1;
  2230. }
  2231. if (memo_put(state, self, obj) < 0) {
  2232. return -1;
  2233. }
  2234. return 0;
  2235. }
  2236. static int
  2237. save_bytearray(PickleState *state, PicklerObject *self, PyObject *obj)
  2238. {
  2239. if (self->proto < 5) {
  2240. /* Older pickle protocols do not have an opcode for pickling
  2241. * bytearrays. */
  2242. PyObject *reduce_value = NULL;
  2243. int status;
  2244. if (PyByteArray_GET_SIZE(obj) == 0) {
  2245. reduce_value = Py_BuildValue("(O())",
  2246. (PyObject *) &PyByteArray_Type);
  2247. }
  2248. else {
  2249. PyObject *bytes_obj = PyBytes_FromObject(obj);
  2250. if (bytes_obj != NULL) {
  2251. reduce_value = Py_BuildValue("(O(O))",
  2252. (PyObject *) &PyByteArray_Type,
  2253. bytes_obj);
  2254. Py_DECREF(bytes_obj);
  2255. }
  2256. }
  2257. if (reduce_value == NULL)
  2258. return -1;
  2259. /* save_reduce() will memoize the object automatically. */
  2260. status = save_reduce(state, self, reduce_value, obj);
  2261. Py_DECREF(reduce_value);
  2262. return status;
  2263. }
  2264. else {
  2265. return _save_bytearray_data(state, self, obj,
  2266. PyByteArray_AS_STRING(obj),
  2267. PyByteArray_GET_SIZE(obj));
  2268. }
  2269. }
  2270. static int
  2271. save_picklebuffer(PickleState *st, PicklerObject *self, PyObject *obj)
  2272. {
  2273. if (self->proto < 5) {
  2274. PyErr_SetString(st->PicklingError,
  2275. "PickleBuffer can only be pickled with protocol >= 5");
  2276. return -1;
  2277. }
  2278. const Py_buffer* view = PyPickleBuffer_GetBuffer(obj);
  2279. if (view == NULL) {
  2280. return -1;
  2281. }
  2282. if (view->suboffsets != NULL || !PyBuffer_IsContiguous(view, 'A')) {
  2283. PyErr_SetString(st->PicklingError,
  2284. "PickleBuffer can not be pickled when "
  2285. "pointing to a non-contiguous buffer");
  2286. return -1;
  2287. }
  2288. int in_band = 1;
  2289. if (self->buffer_callback != NULL) {
  2290. PyObject *ret = PyObject_CallOneArg(self->buffer_callback, obj);
  2291. if (ret == NULL) {
  2292. return -1;
  2293. }
  2294. in_band = PyObject_IsTrue(ret);
  2295. Py_DECREF(ret);
  2296. if (in_band == -1) {
  2297. return -1;
  2298. }
  2299. }
  2300. if (in_band) {
  2301. /* Write data in-band */
  2302. if (view->readonly) {
  2303. return _save_bytes_data(st, self, obj, (const char *)view->buf,
  2304. view->len);
  2305. }
  2306. else {
  2307. return _save_bytearray_data(st, self, obj, (const char *)view->buf,
  2308. view->len);
  2309. }
  2310. }
  2311. else {
  2312. /* Write data out-of-band */
  2313. const char next_buffer_op = NEXT_BUFFER;
  2314. if (_Pickler_Write(self, &next_buffer_op, 1) < 0) {
  2315. return -1;
  2316. }
  2317. if (view->readonly) {
  2318. const char readonly_buffer_op = READONLY_BUFFER;
  2319. if (_Pickler_Write(self, &readonly_buffer_op, 1) < 0) {
  2320. return -1;
  2321. }
  2322. }
  2323. }
  2324. return 0;
  2325. }
  2326. /* A copy of PyUnicode_AsRawUnicodeEscapeString() that also translates
  2327. backslash and newline characters to \uXXXX escapes. */
  2328. static PyObject *
  2329. raw_unicode_escape(PyObject *obj)
  2330. {
  2331. char *p;
  2332. Py_ssize_t i, size;
  2333. const void *data;
  2334. int kind;
  2335. _PyBytesWriter writer;
  2336. if (PyUnicode_READY(obj))
  2337. return NULL;
  2338. _PyBytesWriter_Init(&writer);
  2339. size = PyUnicode_GET_LENGTH(obj);
  2340. data = PyUnicode_DATA(obj);
  2341. kind = PyUnicode_KIND(obj);
  2342. p = _PyBytesWriter_Alloc(&writer, size);
  2343. if (p == NULL)
  2344. goto error;
  2345. writer.overallocate = 1;
  2346. for (i=0; i < size; i++) {
  2347. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  2348. /* Map 32-bit characters to '\Uxxxxxxxx' */
  2349. if (ch >= 0x10000) {
  2350. /* -1: subtract 1 preallocated byte */
  2351. p = _PyBytesWriter_Prepare(&writer, p, 10-1);
  2352. if (p == NULL)
  2353. goto error;
  2354. *p++ = '\\';
  2355. *p++ = 'U';
  2356. *p++ = Py_hexdigits[(ch >> 28) & 0xf];
  2357. *p++ = Py_hexdigits[(ch >> 24) & 0xf];
  2358. *p++ = Py_hexdigits[(ch >> 20) & 0xf];
  2359. *p++ = Py_hexdigits[(ch >> 16) & 0xf];
  2360. *p++ = Py_hexdigits[(ch >> 12) & 0xf];
  2361. *p++ = Py_hexdigits[(ch >> 8) & 0xf];
  2362. *p++ = Py_hexdigits[(ch >> 4) & 0xf];
  2363. *p++ = Py_hexdigits[ch & 15];
  2364. }
  2365. /* Map 16-bit characters, '\\' and '\n' to '\uxxxx' */
  2366. else if (ch >= 256 ||
  2367. ch == '\\' || ch == 0 || ch == '\n' || ch == '\r' ||
  2368. ch == 0x1a)
  2369. {
  2370. /* -1: subtract 1 preallocated byte */
  2371. p = _PyBytesWriter_Prepare(&writer, p, 6-1);
  2372. if (p == NULL)
  2373. goto error;
  2374. *p++ = '\\';
  2375. *p++ = 'u';
  2376. *p++ = Py_hexdigits[(ch >> 12) & 0xf];
  2377. *p++ = Py_hexdigits[(ch >> 8) & 0xf];
  2378. *p++ = Py_hexdigits[(ch >> 4) & 0xf];
  2379. *p++ = Py_hexdigits[ch & 15];
  2380. }
  2381. /* Copy everything else as-is */
  2382. else
  2383. *p++ = (char) ch;
  2384. }
  2385. return _PyBytesWriter_Finish(&writer, p);
  2386. error:
  2387. _PyBytesWriter_Dealloc(&writer);
  2388. return NULL;
  2389. }
  2390. static int
  2391. write_unicode_binary(PicklerObject *self, PyObject *obj)
  2392. {
  2393. char header[9];
  2394. Py_ssize_t len;
  2395. PyObject *encoded = NULL;
  2396. Py_ssize_t size;
  2397. const char *data;
  2398. if (PyUnicode_READY(obj))
  2399. return -1;
  2400. data = PyUnicode_AsUTF8AndSize(obj, &size);
  2401. if (data == NULL) {
  2402. /* Issue #8383: for strings with lone surrogates, fallback on the
  2403. "surrogatepass" error handler. */
  2404. PyErr_Clear();
  2405. encoded = PyUnicode_AsEncodedString(obj, "utf-8", "surrogatepass");
  2406. if (encoded == NULL)
  2407. return -1;
  2408. data = PyBytes_AS_STRING(encoded);
  2409. size = PyBytes_GET_SIZE(encoded);
  2410. }
  2411. assert(size >= 0);
  2412. if (size <= 0xff && self->proto >= 4) {
  2413. header[0] = SHORT_BINUNICODE;
  2414. header[1] = (unsigned char)(size & 0xff);
  2415. len = 2;
  2416. }
  2417. else if ((size_t)size <= 0xffffffffUL) {
  2418. header[0] = BINUNICODE;
  2419. header[1] = (unsigned char)(size & 0xff);
  2420. header[2] = (unsigned char)((size >> 8) & 0xff);
  2421. header[3] = (unsigned char)((size >> 16) & 0xff);
  2422. header[4] = (unsigned char)((size >> 24) & 0xff);
  2423. len = 5;
  2424. }
  2425. else if (self->proto >= 4) {
  2426. header[0] = BINUNICODE8;
  2427. _write_size64(header + 1, size);
  2428. len = 9;
  2429. }
  2430. else {
  2431. PyErr_SetString(PyExc_OverflowError,
  2432. "serializing a string larger than 4 GiB "
  2433. "requires pickle protocol 4 or higher");
  2434. Py_XDECREF(encoded);
  2435. return -1;
  2436. }
  2437. if (_Pickler_write_bytes(self, header, len, data, size, encoded) < 0) {
  2438. Py_XDECREF(encoded);
  2439. return -1;
  2440. }
  2441. Py_XDECREF(encoded);
  2442. return 0;
  2443. }
  2444. static int
  2445. save_unicode(PickleState *state, PicklerObject *self, PyObject *obj)
  2446. {
  2447. if (self->bin) {
  2448. if (write_unicode_binary(self, obj) < 0)
  2449. return -1;
  2450. }
  2451. else {
  2452. PyObject *encoded;
  2453. Py_ssize_t size;
  2454. const char unicode_op = UNICODE;
  2455. encoded = raw_unicode_escape(obj);
  2456. if (encoded == NULL)
  2457. return -1;
  2458. if (_Pickler_Write(self, &unicode_op, 1) < 0) {
  2459. Py_DECREF(encoded);
  2460. return -1;
  2461. }
  2462. size = PyBytes_GET_SIZE(encoded);
  2463. if (_Pickler_Write(self, PyBytes_AS_STRING(encoded), size) < 0) {
  2464. Py_DECREF(encoded);
  2465. return -1;
  2466. }
  2467. Py_DECREF(encoded);
  2468. if (_Pickler_Write(self, "\n", 1) < 0)
  2469. return -1;
  2470. }
  2471. if (memo_put(state, self, obj) < 0)
  2472. return -1;
  2473. return 0;
  2474. }
  2475. /* A helper for save_tuple. Push the len elements in tuple t on the stack. */
  2476. static int
  2477. store_tuple_elements(PickleState *state, PicklerObject *self, PyObject *t,
  2478. Py_ssize_t len)
  2479. {
  2480. Py_ssize_t i;
  2481. assert(PyTuple_Size(t) == len);
  2482. for (i = 0; i < len; i++) {
  2483. PyObject *element = PyTuple_GET_ITEM(t, i);
  2484. if (element == NULL)
  2485. return -1;
  2486. if (save(state, self, element, 0) < 0)
  2487. return -1;
  2488. }
  2489. return 0;
  2490. }
  2491. /* Tuples are ubiquitous in the pickle protocols, so many techniques are
  2492. * used across protocols to minimize the space needed to pickle them.
  2493. * Tuples are also the only builtin immutable type that can be recursive
  2494. * (a tuple can be reached from itself), and that requires some subtle
  2495. * magic so that it works in all cases. IOW, this is a long routine.
  2496. */
  2497. static int
  2498. save_tuple(PickleState *state, PicklerObject *self, PyObject *obj)
  2499. {
  2500. Py_ssize_t len, i;
  2501. const char mark_op = MARK;
  2502. const char tuple_op = TUPLE;
  2503. const char pop_op = POP;
  2504. const char pop_mark_op = POP_MARK;
  2505. const char len2opcode[] = {EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3};
  2506. if ((len = PyTuple_Size(obj)) < 0)
  2507. return -1;
  2508. if (len == 0) {
  2509. char pdata[2];
  2510. if (self->proto) {
  2511. pdata[0] = EMPTY_TUPLE;
  2512. len = 1;
  2513. }
  2514. else {
  2515. pdata[0] = MARK;
  2516. pdata[1] = TUPLE;
  2517. len = 2;
  2518. }
  2519. if (_Pickler_Write(self, pdata, len) < 0)
  2520. return -1;
  2521. return 0;
  2522. }
  2523. /* The tuple isn't in the memo now. If it shows up there after
  2524. * saving the tuple elements, the tuple must be recursive, in
  2525. * which case we'll pop everything we put on the stack, and fetch
  2526. * its value from the memo.
  2527. */
  2528. if (len <= 3 && self->proto >= 2) {
  2529. /* Use TUPLE{1,2,3} opcodes. */
  2530. if (store_tuple_elements(state, self, obj, len) < 0)
  2531. return -1;
  2532. if (PyMemoTable_Get(self->memo, obj)) {
  2533. /* pop the len elements */
  2534. for (i = 0; i < len; i++)
  2535. if (_Pickler_Write(self, &pop_op, 1) < 0)
  2536. return -1;
  2537. /* fetch from memo */
  2538. if (memo_get(state, self, obj) < 0)
  2539. return -1;
  2540. return 0;
  2541. }
  2542. else { /* Not recursive. */
  2543. if (_Pickler_Write(self, len2opcode + len, 1) < 0)
  2544. return -1;
  2545. }
  2546. goto memoize;
  2547. }
  2548. /* proto < 2 and len > 0, or proto >= 2 and len > 3.
  2549. * Generate MARK e1 e2 ... TUPLE
  2550. */
  2551. if (_Pickler_Write(self, &mark_op, 1) < 0)
  2552. return -1;
  2553. if (store_tuple_elements(state, self, obj, len) < 0)
  2554. return -1;
  2555. if (PyMemoTable_Get(self->memo, obj)) {
  2556. /* pop the stack stuff we pushed */
  2557. if (self->bin) {
  2558. if (_Pickler_Write(self, &pop_mark_op, 1) < 0)
  2559. return -1;
  2560. }
  2561. else {
  2562. /* Note that we pop one more than len, to remove
  2563. * the MARK too.
  2564. */
  2565. for (i = 0; i <= len; i++)
  2566. if (_Pickler_Write(self, &pop_op, 1) < 0)
  2567. return -1;
  2568. }
  2569. /* fetch from memo */
  2570. if (memo_get(state, self, obj) < 0)
  2571. return -1;
  2572. return 0;
  2573. }
  2574. else { /* Not recursive. */
  2575. if (_Pickler_Write(self, &tuple_op, 1) < 0)
  2576. return -1;
  2577. }
  2578. memoize:
  2579. if (memo_put(state, self, obj) < 0)
  2580. return -1;
  2581. return 0;
  2582. }
  2583. /* iter is an iterator giving items, and we batch up chunks of
  2584. * MARK item item ... item APPENDS
  2585. * opcode sequences. Calling code should have arranged to first create an
  2586. * empty list, or list-like object, for the APPENDS to operate on.
  2587. * Returns 0 on success, <0 on error.
  2588. */
  2589. static int
  2590. batch_list(PickleState *state, PicklerObject *self, PyObject *iter)
  2591. {
  2592. PyObject *obj = NULL;
  2593. PyObject *firstitem = NULL;
  2594. int i, n;
  2595. const char mark_op = MARK;
  2596. const char append_op = APPEND;
  2597. const char appends_op = APPENDS;
  2598. assert(iter != NULL);
  2599. /* XXX: I think this function could be made faster by avoiding the
  2600. iterator interface and fetching objects directly from list using
  2601. PyList_GET_ITEM.
  2602. */
  2603. if (self->proto == 0) {
  2604. /* APPENDS isn't available; do one at a time. */
  2605. for (;;) {
  2606. obj = PyIter_Next(iter);
  2607. if (obj == NULL) {
  2608. if (PyErr_Occurred())
  2609. return -1;
  2610. break;
  2611. }
  2612. i = save(state, self, obj, 0);
  2613. Py_DECREF(obj);
  2614. if (i < 0)
  2615. return -1;
  2616. if (_Pickler_Write(self, &append_op, 1) < 0)
  2617. return -1;
  2618. }
  2619. return 0;
  2620. }
  2621. /* proto > 0: write in batches of BATCHSIZE. */
  2622. do {
  2623. /* Get first item */
  2624. firstitem = PyIter_Next(iter);
  2625. if (firstitem == NULL) {
  2626. if (PyErr_Occurred())
  2627. goto error;
  2628. /* nothing more to add */
  2629. break;
  2630. }
  2631. /* Try to get a second item */
  2632. obj = PyIter_Next(iter);
  2633. if (obj == NULL) {
  2634. if (PyErr_Occurred())
  2635. goto error;
  2636. /* Only one item to write */
  2637. if (save(state, self, firstitem, 0) < 0)
  2638. goto error;
  2639. if (_Pickler_Write(self, &append_op, 1) < 0)
  2640. goto error;
  2641. Py_CLEAR(firstitem);
  2642. break;
  2643. }
  2644. /* More than one item to write */
  2645. /* Pump out MARK, items, APPENDS. */
  2646. if (_Pickler_Write(self, &mark_op, 1) < 0)
  2647. goto error;
  2648. if (save(state, self, firstitem, 0) < 0)
  2649. goto error;
  2650. Py_CLEAR(firstitem);
  2651. n = 1;
  2652. /* Fetch and save up to BATCHSIZE items */
  2653. while (obj) {
  2654. if (save(state, self, obj, 0) < 0)
  2655. goto error;
  2656. Py_CLEAR(obj);
  2657. n += 1;
  2658. if (n == BATCHSIZE)
  2659. break;
  2660. obj = PyIter_Next(iter);
  2661. if (obj == NULL) {
  2662. if (PyErr_Occurred())
  2663. goto error;
  2664. break;
  2665. }
  2666. }
  2667. if (_Pickler_Write(self, &appends_op, 1) < 0)
  2668. goto error;
  2669. } while (n == BATCHSIZE);
  2670. return 0;
  2671. error:
  2672. Py_XDECREF(firstitem);
  2673. Py_XDECREF(obj);
  2674. return -1;
  2675. }
  2676. /* This is a variant of batch_list() above, specialized for lists (with no
  2677. * support for list subclasses). Like batch_list(), we batch up chunks of
  2678. * MARK item item ... item APPENDS
  2679. * opcode sequences. Calling code should have arranged to first create an
  2680. * empty list, or list-like object, for the APPENDS to operate on.
  2681. * Returns 0 on success, -1 on error.
  2682. *
  2683. * This version is considerably faster than batch_list(), if less general.
  2684. *
  2685. * Note that this only works for protocols > 0.
  2686. */
  2687. static int
  2688. batch_list_exact(PickleState *state, PicklerObject *self, PyObject *obj)
  2689. {
  2690. PyObject *item = NULL;
  2691. Py_ssize_t this_batch, total;
  2692. const char append_op = APPEND;
  2693. const char appends_op = APPENDS;
  2694. const char mark_op = MARK;
  2695. assert(obj != NULL);
  2696. assert(self->proto > 0);
  2697. assert(PyList_CheckExact(obj));
  2698. if (PyList_GET_SIZE(obj) == 1) {
  2699. item = PyList_GET_ITEM(obj, 0);
  2700. Py_INCREF(item);
  2701. int err = save(state, self, item, 0);
  2702. Py_DECREF(item);
  2703. if (err < 0)
  2704. return -1;
  2705. if (_Pickler_Write(self, &append_op, 1) < 0)
  2706. return -1;
  2707. return 0;
  2708. }
  2709. /* Write in batches of BATCHSIZE. */
  2710. total = 0;
  2711. do {
  2712. this_batch = 0;
  2713. if (_Pickler_Write(self, &mark_op, 1) < 0)
  2714. return -1;
  2715. while (total < PyList_GET_SIZE(obj)) {
  2716. item = PyList_GET_ITEM(obj, total);
  2717. Py_INCREF(item);
  2718. int err = save(state, self, item, 0);
  2719. Py_DECREF(item);
  2720. if (err < 0)
  2721. return -1;
  2722. total++;
  2723. if (++this_batch == BATCHSIZE)
  2724. break;
  2725. }
  2726. if (_Pickler_Write(self, &appends_op, 1) < 0)
  2727. return -1;
  2728. } while (total < PyList_GET_SIZE(obj));
  2729. return 0;
  2730. }
  2731. static int
  2732. save_list(PickleState *state, PicklerObject *self, PyObject *obj)
  2733. {
  2734. char header[3];
  2735. Py_ssize_t len;
  2736. int status = 0;
  2737. if (self->fast && !fast_save_enter(self, obj))
  2738. goto error;
  2739. /* Create an empty list. */
  2740. if (self->bin) {
  2741. header[0] = EMPTY_LIST;
  2742. len = 1;
  2743. }
  2744. else {
  2745. header[0] = MARK;
  2746. header[1] = LIST;
  2747. len = 2;
  2748. }
  2749. if (_Pickler_Write(self, header, len) < 0)
  2750. goto error;
  2751. /* Get list length, and bow out early if empty. */
  2752. if ((len = PyList_Size(obj)) < 0)
  2753. goto error;
  2754. if (memo_put(state, self, obj) < 0)
  2755. goto error;
  2756. if (len != 0) {
  2757. /* Materialize the list elements. */
  2758. if (PyList_CheckExact(obj) && self->proto > 0) {
  2759. if (_Py_EnterRecursiveCall(" while pickling an object"))
  2760. goto error;
  2761. status = batch_list_exact(state, self, obj);
  2762. _Py_LeaveRecursiveCall();
  2763. } else {
  2764. PyObject *iter = PyObject_GetIter(obj);
  2765. if (iter == NULL)
  2766. goto error;
  2767. if (_Py_EnterRecursiveCall(" while pickling an object")) {
  2768. Py_DECREF(iter);
  2769. goto error;
  2770. }
  2771. status = batch_list(state, self, iter);
  2772. _Py_LeaveRecursiveCall();
  2773. Py_DECREF(iter);
  2774. }
  2775. }
  2776. if (0) {
  2777. error:
  2778. status = -1;
  2779. }
  2780. if (self->fast && !fast_save_leave(self, obj))
  2781. status = -1;
  2782. return status;
  2783. }
  2784. /* iter is an iterator giving (key, value) pairs, and we batch up chunks of
  2785. * MARK key value ... key value SETITEMS
  2786. * opcode sequences. Calling code should have arranged to first create an
  2787. * empty dict, or dict-like object, for the SETITEMS to operate on.
  2788. * Returns 0 on success, <0 on error.
  2789. *
  2790. * This is very much like batch_list(). The difference between saving
  2791. * elements directly, and picking apart two-tuples, is so long-winded at
  2792. * the C level, though, that attempts to combine these routines were too
  2793. * ugly to bear.
  2794. */
  2795. static int
  2796. batch_dict(PickleState *state, PicklerObject *self, PyObject *iter)
  2797. {
  2798. PyObject *obj = NULL;
  2799. PyObject *firstitem = NULL;
  2800. int i, n;
  2801. const char mark_op = MARK;
  2802. const char setitem_op = SETITEM;
  2803. const char setitems_op = SETITEMS;
  2804. assert(iter != NULL);
  2805. if (self->proto == 0) {
  2806. /* SETITEMS isn't available; do one at a time. */
  2807. for (;;) {
  2808. obj = PyIter_Next(iter);
  2809. if (obj == NULL) {
  2810. if (PyErr_Occurred())
  2811. return -1;
  2812. break;
  2813. }
  2814. if (!PyTuple_Check(obj) || PyTuple_Size(obj) != 2) {
  2815. PyErr_SetString(PyExc_TypeError, "dict items "
  2816. "iterator must return 2-tuples");
  2817. Py_DECREF(obj);
  2818. return -1;
  2819. }
  2820. i = save(state, self, PyTuple_GET_ITEM(obj, 0), 0);
  2821. if (i >= 0)
  2822. i = save(state, self, PyTuple_GET_ITEM(obj, 1), 0);
  2823. Py_DECREF(obj);
  2824. if (i < 0)
  2825. return -1;
  2826. if (_Pickler_Write(self, &setitem_op, 1) < 0)
  2827. return -1;
  2828. }
  2829. return 0;
  2830. }
  2831. /* proto > 0: write in batches of BATCHSIZE. */
  2832. do {
  2833. /* Get first item */
  2834. firstitem = PyIter_Next(iter);
  2835. if (firstitem == NULL) {
  2836. if (PyErr_Occurred())
  2837. goto error;
  2838. /* nothing more to add */
  2839. break;
  2840. }
  2841. if (!PyTuple_Check(firstitem) || PyTuple_Size(firstitem) != 2) {
  2842. PyErr_SetString(PyExc_TypeError, "dict items "
  2843. "iterator must return 2-tuples");
  2844. goto error;
  2845. }
  2846. /* Try to get a second item */
  2847. obj = PyIter_Next(iter);
  2848. if (obj == NULL) {
  2849. if (PyErr_Occurred())
  2850. goto error;
  2851. /* Only one item to write */
  2852. if (save(state, self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
  2853. goto error;
  2854. if (save(state, self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
  2855. goto error;
  2856. if (_Pickler_Write(self, &setitem_op, 1) < 0)
  2857. goto error;
  2858. Py_CLEAR(firstitem);
  2859. break;
  2860. }
  2861. /* More than one item to write */
  2862. /* Pump out MARK, items, SETITEMS. */
  2863. if (_Pickler_Write(self, &mark_op, 1) < 0)
  2864. goto error;
  2865. if (save(state, self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
  2866. goto error;
  2867. if (save(state, self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
  2868. goto error;
  2869. Py_CLEAR(firstitem);
  2870. n = 1;
  2871. /* Fetch and save up to BATCHSIZE items */
  2872. while (obj) {
  2873. if (!PyTuple_Check(obj) || PyTuple_Size(obj) != 2) {
  2874. PyErr_SetString(PyExc_TypeError, "dict items "
  2875. "iterator must return 2-tuples");
  2876. goto error;
  2877. }
  2878. if (save(state, self, PyTuple_GET_ITEM(obj, 0), 0) < 0 ||
  2879. save(state, self, PyTuple_GET_ITEM(obj, 1), 0) < 0)
  2880. goto error;
  2881. Py_CLEAR(obj);
  2882. n += 1;
  2883. if (n == BATCHSIZE)
  2884. break;
  2885. obj = PyIter_Next(iter);
  2886. if (obj == NULL) {
  2887. if (PyErr_Occurred())
  2888. goto error;
  2889. break;
  2890. }
  2891. }
  2892. if (_Pickler_Write(self, &setitems_op, 1) < 0)
  2893. goto error;
  2894. } while (n == BATCHSIZE);
  2895. return 0;
  2896. error:
  2897. Py_XDECREF(firstitem);
  2898. Py_XDECREF(obj);
  2899. return -1;
  2900. }
  2901. /* This is a variant of batch_dict() above that specializes for dicts, with no
  2902. * support for dict subclasses. Like batch_dict(), we batch up chunks of
  2903. * MARK key value ... key value SETITEMS
  2904. * opcode sequences. Calling code should have arranged to first create an
  2905. * empty dict, or dict-like object, for the SETITEMS to operate on.
  2906. * Returns 0 on success, -1 on error.
  2907. *
  2908. * Note that this currently doesn't work for protocol 0.
  2909. */
  2910. static int
  2911. batch_dict_exact(PickleState *state, PicklerObject *self, PyObject *obj)
  2912. {
  2913. PyObject *key = NULL, *value = NULL;
  2914. int i;
  2915. Py_ssize_t dict_size, ppos = 0;
  2916. const char mark_op = MARK;
  2917. const char setitem_op = SETITEM;
  2918. const char setitems_op = SETITEMS;
  2919. assert(obj != NULL && PyDict_CheckExact(obj));
  2920. assert(self->proto > 0);
  2921. dict_size = PyDict_GET_SIZE(obj);
  2922. /* Special-case len(d) == 1 to save space. */
  2923. if (dict_size == 1) {
  2924. PyDict_Next(obj, &ppos, &key, &value);
  2925. Py_INCREF(key);
  2926. Py_INCREF(value);
  2927. if (save(state, self, key, 0) < 0) {
  2928. goto error;
  2929. }
  2930. if (save(state, self, value, 0) < 0) {
  2931. goto error;
  2932. }
  2933. Py_CLEAR(key);
  2934. Py_CLEAR(value);
  2935. if (_Pickler_Write(self, &setitem_op, 1) < 0)
  2936. return -1;
  2937. return 0;
  2938. }
  2939. /* Write in batches of BATCHSIZE. */
  2940. do {
  2941. i = 0;
  2942. if (_Pickler_Write(self, &mark_op, 1) < 0)
  2943. return -1;
  2944. while (PyDict_Next(obj, &ppos, &key, &value)) {
  2945. Py_INCREF(key);
  2946. Py_INCREF(value);
  2947. if (save(state, self, key, 0) < 0) {
  2948. goto error;
  2949. }
  2950. if (save(state, self, value, 0) < 0) {
  2951. goto error;
  2952. }
  2953. Py_CLEAR(key);
  2954. Py_CLEAR(value);
  2955. if (++i == BATCHSIZE)
  2956. break;
  2957. }
  2958. if (_Pickler_Write(self, &setitems_op, 1) < 0)
  2959. return -1;
  2960. if (PyDict_GET_SIZE(obj) != dict_size) {
  2961. PyErr_Format(
  2962. PyExc_RuntimeError,
  2963. "dictionary changed size during iteration");
  2964. return -1;
  2965. }
  2966. } while (i == BATCHSIZE);
  2967. return 0;
  2968. error:
  2969. Py_XDECREF(key);
  2970. Py_XDECREF(value);
  2971. return -1;
  2972. }
  2973. static int
  2974. save_dict(PickleState *state, PicklerObject *self, PyObject *obj)
  2975. {
  2976. PyObject *items, *iter;
  2977. char header[3];
  2978. Py_ssize_t len;
  2979. int status = 0;
  2980. assert(PyDict_Check(obj));
  2981. if (self->fast && !fast_save_enter(self, obj))
  2982. goto error;
  2983. /* Create an empty dict. */
  2984. if (self->bin) {
  2985. header[0] = EMPTY_DICT;
  2986. len = 1;
  2987. }
  2988. else {
  2989. header[0] = MARK;
  2990. header[1] = DICT;
  2991. len = 2;
  2992. }
  2993. if (_Pickler_Write(self, header, len) < 0)
  2994. goto error;
  2995. if (memo_put(state, self, obj) < 0)
  2996. goto error;
  2997. if (PyDict_GET_SIZE(obj)) {
  2998. /* Save the dict items. */
  2999. if (PyDict_CheckExact(obj) && self->proto > 0) {
  3000. /* We can take certain shortcuts if we know this is a dict and
  3001. not a dict subclass. */
  3002. if (_Py_EnterRecursiveCall(" while pickling an object"))
  3003. goto error;
  3004. status = batch_dict_exact(state, self, obj);
  3005. _Py_LeaveRecursiveCall();
  3006. } else {
  3007. items = PyObject_CallMethodNoArgs(obj, &_Py_ID(items));
  3008. if (items == NULL)
  3009. goto error;
  3010. iter = PyObject_GetIter(items);
  3011. Py_DECREF(items);
  3012. if (iter == NULL)
  3013. goto error;
  3014. if (_Py_EnterRecursiveCall(" while pickling an object")) {
  3015. Py_DECREF(iter);
  3016. goto error;
  3017. }
  3018. status = batch_dict(state, self, iter);
  3019. _Py_LeaveRecursiveCall();
  3020. Py_DECREF(iter);
  3021. }
  3022. }
  3023. if (0) {
  3024. error:
  3025. status = -1;
  3026. }
  3027. if (self->fast && !fast_save_leave(self, obj))
  3028. status = -1;
  3029. return status;
  3030. }
  3031. static int
  3032. save_set(PickleState *state, PicklerObject *self, PyObject *obj)
  3033. {
  3034. PyObject *item;
  3035. int i;
  3036. Py_ssize_t set_size, ppos = 0;
  3037. Py_hash_t hash;
  3038. const char empty_set_op = EMPTY_SET;
  3039. const char mark_op = MARK;
  3040. const char additems_op = ADDITEMS;
  3041. if (self->proto < 4) {
  3042. PyObject *items;
  3043. PyObject *reduce_value;
  3044. int status;
  3045. items = PySequence_List(obj);
  3046. if (items == NULL) {
  3047. return -1;
  3048. }
  3049. reduce_value = Py_BuildValue("(O(O))", (PyObject*)&PySet_Type, items);
  3050. Py_DECREF(items);
  3051. if (reduce_value == NULL) {
  3052. return -1;
  3053. }
  3054. /* save_reduce() will memoize the object automatically. */
  3055. status = save_reduce(state, self, reduce_value, obj);
  3056. Py_DECREF(reduce_value);
  3057. return status;
  3058. }
  3059. if (_Pickler_Write(self, &empty_set_op, 1) < 0)
  3060. return -1;
  3061. if (memo_put(state, self, obj) < 0)
  3062. return -1;
  3063. set_size = PySet_GET_SIZE(obj);
  3064. if (set_size == 0)
  3065. return 0; /* nothing to do */
  3066. /* Write in batches of BATCHSIZE. */
  3067. do {
  3068. i = 0;
  3069. if (_Pickler_Write(self, &mark_op, 1) < 0)
  3070. return -1;
  3071. while (_PySet_NextEntry(obj, &ppos, &item, &hash)) {
  3072. Py_INCREF(item);
  3073. int err = save(state, self, item, 0);
  3074. Py_CLEAR(item);
  3075. if (err < 0)
  3076. return -1;
  3077. if (++i == BATCHSIZE)
  3078. break;
  3079. }
  3080. if (_Pickler_Write(self, &additems_op, 1) < 0)
  3081. return -1;
  3082. if (PySet_GET_SIZE(obj) != set_size) {
  3083. PyErr_Format(
  3084. PyExc_RuntimeError,
  3085. "set changed size during iteration");
  3086. return -1;
  3087. }
  3088. } while (i == BATCHSIZE);
  3089. return 0;
  3090. }
  3091. static int
  3092. save_frozenset(PickleState *state, PicklerObject *self, PyObject *obj)
  3093. {
  3094. PyObject *iter;
  3095. const char mark_op = MARK;
  3096. const char frozenset_op = FROZENSET;
  3097. if (self->fast && !fast_save_enter(self, obj))
  3098. return -1;
  3099. if (self->proto < 4) {
  3100. PyObject *items;
  3101. PyObject *reduce_value;
  3102. int status;
  3103. items = PySequence_List(obj);
  3104. if (items == NULL) {
  3105. return -1;
  3106. }
  3107. reduce_value = Py_BuildValue("(O(O))", (PyObject*)&PyFrozenSet_Type,
  3108. items);
  3109. Py_DECREF(items);
  3110. if (reduce_value == NULL) {
  3111. return -1;
  3112. }
  3113. /* save_reduce() will memoize the object automatically. */
  3114. status = save_reduce(state, self, reduce_value, obj);
  3115. Py_DECREF(reduce_value);
  3116. return status;
  3117. }
  3118. if (_Pickler_Write(self, &mark_op, 1) < 0)
  3119. return -1;
  3120. iter = PyObject_GetIter(obj);
  3121. if (iter == NULL) {
  3122. return -1;
  3123. }
  3124. for (;;) {
  3125. PyObject *item;
  3126. item = PyIter_Next(iter);
  3127. if (item == NULL) {
  3128. if (PyErr_Occurred()) {
  3129. Py_DECREF(iter);
  3130. return -1;
  3131. }
  3132. break;
  3133. }
  3134. if (save(state, self, item, 0) < 0) {
  3135. Py_DECREF(item);
  3136. Py_DECREF(iter);
  3137. return -1;
  3138. }
  3139. Py_DECREF(item);
  3140. }
  3141. Py_DECREF(iter);
  3142. /* If the object is already in the memo, this means it is
  3143. recursive. In this case, throw away everything we put on the
  3144. stack, and fetch the object back from the memo. */
  3145. if (PyMemoTable_Get(self->memo, obj)) {
  3146. const char pop_mark_op = POP_MARK;
  3147. if (_Pickler_Write(self, &pop_mark_op, 1) < 0)
  3148. return -1;
  3149. if (memo_get(state, self, obj) < 0)
  3150. return -1;
  3151. return 0;
  3152. }
  3153. if (_Pickler_Write(self, &frozenset_op, 1) < 0)
  3154. return -1;
  3155. if (memo_put(state, self, obj) < 0)
  3156. return -1;
  3157. return 0;
  3158. }
  3159. static int
  3160. fix_imports(PickleState *st, PyObject **module_name, PyObject **global_name)
  3161. {
  3162. PyObject *key;
  3163. PyObject *item;
  3164. key = PyTuple_Pack(2, *module_name, *global_name);
  3165. if (key == NULL)
  3166. return -1;
  3167. item = PyDict_GetItemWithError(st->name_mapping_3to2, key);
  3168. Py_DECREF(key);
  3169. if (item) {
  3170. PyObject *fixed_module_name;
  3171. PyObject *fixed_global_name;
  3172. if (!PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 2) {
  3173. PyErr_Format(PyExc_RuntimeError,
  3174. "_compat_pickle.REVERSE_NAME_MAPPING values "
  3175. "should be 2-tuples, not %.200s",
  3176. Py_TYPE(item)->tp_name);
  3177. return -1;
  3178. }
  3179. fixed_module_name = PyTuple_GET_ITEM(item, 0);
  3180. fixed_global_name = PyTuple_GET_ITEM(item, 1);
  3181. if (!PyUnicode_Check(fixed_module_name) ||
  3182. !PyUnicode_Check(fixed_global_name)) {
  3183. PyErr_Format(PyExc_RuntimeError,
  3184. "_compat_pickle.REVERSE_NAME_MAPPING values "
  3185. "should be pairs of str, not (%.200s, %.200s)",
  3186. Py_TYPE(fixed_module_name)->tp_name,
  3187. Py_TYPE(fixed_global_name)->tp_name);
  3188. return -1;
  3189. }
  3190. Py_CLEAR(*module_name);
  3191. Py_CLEAR(*global_name);
  3192. *module_name = Py_NewRef(fixed_module_name);
  3193. *global_name = Py_NewRef(fixed_global_name);
  3194. return 0;
  3195. }
  3196. else if (PyErr_Occurred()) {
  3197. return -1;
  3198. }
  3199. item = PyDict_GetItemWithError(st->import_mapping_3to2, *module_name);
  3200. if (item) {
  3201. if (!PyUnicode_Check(item)) {
  3202. PyErr_Format(PyExc_RuntimeError,
  3203. "_compat_pickle.REVERSE_IMPORT_MAPPING values "
  3204. "should be strings, not %.200s",
  3205. Py_TYPE(item)->tp_name);
  3206. return -1;
  3207. }
  3208. Py_XSETREF(*module_name, Py_NewRef(item));
  3209. }
  3210. else if (PyErr_Occurred()) {
  3211. return -1;
  3212. }
  3213. return 0;
  3214. }
  3215. static int
  3216. save_global(PickleState *st, PicklerObject *self, PyObject *obj,
  3217. PyObject *name)
  3218. {
  3219. PyObject *global_name = NULL;
  3220. PyObject *module_name = NULL;
  3221. PyObject *module = NULL;
  3222. PyObject *parent = NULL;
  3223. PyObject *dotted_path = NULL;
  3224. PyObject *cls;
  3225. int status = 0;
  3226. const char global_op = GLOBAL;
  3227. if (name) {
  3228. global_name = Py_NewRef(name);
  3229. }
  3230. else {
  3231. if (_PyObject_LookupAttr(obj, &_Py_ID(__qualname__), &global_name) < 0)
  3232. goto error;
  3233. if (global_name == NULL) {
  3234. global_name = PyObject_GetAttr(obj, &_Py_ID(__name__));
  3235. if (global_name == NULL)
  3236. goto error;
  3237. }
  3238. }
  3239. dotted_path = get_dotted_path(module, global_name);
  3240. if (dotted_path == NULL)
  3241. goto error;
  3242. module_name = whichmodule(obj, dotted_path);
  3243. if (module_name == NULL)
  3244. goto error;
  3245. /* XXX: Change to use the import C API directly with level=0 to disallow
  3246. relative imports.
  3247. XXX: PyImport_ImportModuleLevel could be used. However, this bypasses
  3248. builtins.__import__. Therefore, _pickle, unlike pickle.py, will ignore
  3249. custom import functions (IMHO, this would be a nice security
  3250. feature). The import C API would need to be extended to support the
  3251. extra parameters of __import__ to fix that. */
  3252. module = PyImport_Import(module_name);
  3253. if (module == NULL) {
  3254. PyErr_Format(st->PicklingError,
  3255. "Can't pickle %R: import of module %R failed",
  3256. obj, module_name);
  3257. goto error;
  3258. }
  3259. cls = get_deep_attribute(module, dotted_path, &parent);
  3260. if (cls == NULL) {
  3261. PyErr_Format(st->PicklingError,
  3262. "Can't pickle %R: attribute lookup %S on %S failed",
  3263. obj, global_name, module_name);
  3264. goto error;
  3265. }
  3266. if (cls != obj) {
  3267. Py_DECREF(cls);
  3268. PyErr_Format(st->PicklingError,
  3269. "Can't pickle %R: it's not the same object as %S.%S",
  3270. obj, module_name, global_name);
  3271. goto error;
  3272. }
  3273. Py_DECREF(cls);
  3274. if (self->proto >= 2) {
  3275. /* See whether this is in the extension registry, and if
  3276. * so generate an EXT opcode.
  3277. */
  3278. PyObject *extension_key;
  3279. PyObject *code_obj; /* extension code as Python object */
  3280. long code; /* extension code as C value */
  3281. char pdata[5];
  3282. Py_ssize_t n;
  3283. extension_key = PyTuple_Pack(2, module_name, global_name);
  3284. if (extension_key == NULL) {
  3285. goto error;
  3286. }
  3287. code_obj = PyDict_GetItemWithError(st->extension_registry,
  3288. extension_key);
  3289. Py_DECREF(extension_key);
  3290. if (code_obj == NULL) {
  3291. if (PyErr_Occurred()) {
  3292. goto error;
  3293. }
  3294. /* The object is not registered in the extension registry.
  3295. This is the most likely code path. */
  3296. goto gen_global;
  3297. }
  3298. Py_INCREF(code_obj);
  3299. code = PyLong_AsLong(code_obj);
  3300. Py_DECREF(code_obj);
  3301. if (code <= 0 || code > 0x7fffffffL) {
  3302. /* Should never happen in normal circumstances, since the type and
  3303. the value of the code are checked in copyreg.add_extension(). */
  3304. if (!PyErr_Occurred())
  3305. PyErr_Format(PyExc_RuntimeError, "extension code %ld is out of range", code);
  3306. goto error;
  3307. }
  3308. /* Generate an EXT opcode. */
  3309. if (code <= 0xff) {
  3310. pdata[0] = EXT1;
  3311. pdata[1] = (unsigned char)code;
  3312. n = 2;
  3313. }
  3314. else if (code <= 0xffff) {
  3315. pdata[0] = EXT2;
  3316. pdata[1] = (unsigned char)(code & 0xff);
  3317. pdata[2] = (unsigned char)((code >> 8) & 0xff);
  3318. n = 3;
  3319. }
  3320. else {
  3321. pdata[0] = EXT4;
  3322. pdata[1] = (unsigned char)(code & 0xff);
  3323. pdata[2] = (unsigned char)((code >> 8) & 0xff);
  3324. pdata[3] = (unsigned char)((code >> 16) & 0xff);
  3325. pdata[4] = (unsigned char)((code >> 24) & 0xff);
  3326. n = 5;
  3327. }
  3328. if (_Pickler_Write(self, pdata, n) < 0)
  3329. goto error;
  3330. }
  3331. else {
  3332. gen_global:
  3333. if (parent == module) {
  3334. Py_SETREF(global_name,
  3335. Py_NewRef(PyList_GET_ITEM(dotted_path,
  3336. PyList_GET_SIZE(dotted_path) - 1)));
  3337. Py_CLEAR(dotted_path);
  3338. }
  3339. if (self->proto >= 4) {
  3340. const char stack_global_op = STACK_GLOBAL;
  3341. if (save(st, self, module_name, 0) < 0)
  3342. goto error;
  3343. if (save(st, self, global_name, 0) < 0)
  3344. goto error;
  3345. if (_Pickler_Write(self, &stack_global_op, 1) < 0)
  3346. goto error;
  3347. }
  3348. else {
  3349. /* Generate a normal global opcode if we are using a pickle
  3350. protocol < 4, or if the object is not registered in the
  3351. extension registry.
  3352. Objects with multi-part __qualname__ are represented as
  3353. getattr(getattr(..., attrname1), attrname2). */
  3354. const char mark_op = MARK;
  3355. const char tupletwo_op = (self->proto < 2) ? TUPLE : TUPLE2;
  3356. const char reduce_op = REDUCE;
  3357. Py_ssize_t i;
  3358. if (dotted_path) {
  3359. if (PyList_GET_SIZE(dotted_path) > 1) {
  3360. Py_SETREF(global_name, Py_NewRef(PyList_GET_ITEM(dotted_path, 0)));
  3361. }
  3362. for (i = 1; i < PyList_GET_SIZE(dotted_path); i++) {
  3363. if (save(st, self, st->getattr, 0) < 0 ||
  3364. (self->proto < 2 && _Pickler_Write(self, &mark_op, 1) < 0))
  3365. {
  3366. goto error;
  3367. }
  3368. }
  3369. }
  3370. PyObject *encoded;
  3371. PyObject *(*unicode_encoder)(PyObject *);
  3372. if (_Pickler_Write(self, &global_op, 1) < 0)
  3373. goto error;
  3374. /* For protocol < 3 and if the user didn't request against doing
  3375. so, we convert module names to the old 2.x module names. */
  3376. if (self->proto < 3 && self->fix_imports) {
  3377. if (fix_imports(st, &module_name, &global_name) < 0) {
  3378. goto error;
  3379. }
  3380. }
  3381. /* Since Python 3.0 now supports non-ASCII identifiers, we encode
  3382. both the module name and the global name using UTF-8. We do so
  3383. only when we are using the pickle protocol newer than version
  3384. 3. This is to ensure compatibility with older Unpickler running
  3385. on Python 2.x. */
  3386. if (self->proto == 3) {
  3387. unicode_encoder = PyUnicode_AsUTF8String;
  3388. }
  3389. else {
  3390. unicode_encoder = PyUnicode_AsASCIIString;
  3391. }
  3392. encoded = unicode_encoder(module_name);
  3393. if (encoded == NULL) {
  3394. if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
  3395. PyErr_Format(st->PicklingError,
  3396. "can't pickle module identifier '%S' using "
  3397. "pickle protocol %i",
  3398. module_name, self->proto);
  3399. goto error;
  3400. }
  3401. if (_Pickler_Write(self, PyBytes_AS_STRING(encoded),
  3402. PyBytes_GET_SIZE(encoded)) < 0) {
  3403. Py_DECREF(encoded);
  3404. goto error;
  3405. }
  3406. Py_DECREF(encoded);
  3407. if(_Pickler_Write(self, "\n", 1) < 0)
  3408. goto error;
  3409. /* Save the name of the module. */
  3410. encoded = unicode_encoder(global_name);
  3411. if (encoded == NULL) {
  3412. if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
  3413. PyErr_Format(st->PicklingError,
  3414. "can't pickle global identifier '%S' using "
  3415. "pickle protocol %i",
  3416. global_name, self->proto);
  3417. goto error;
  3418. }
  3419. if (_Pickler_Write(self, PyBytes_AS_STRING(encoded),
  3420. PyBytes_GET_SIZE(encoded)) < 0) {
  3421. Py_DECREF(encoded);
  3422. goto error;
  3423. }
  3424. Py_DECREF(encoded);
  3425. if (_Pickler_Write(self, "\n", 1) < 0)
  3426. goto error;
  3427. if (dotted_path) {
  3428. for (i = 1; i < PyList_GET_SIZE(dotted_path); i++) {
  3429. if (save(st, self, PyList_GET_ITEM(dotted_path, i), 0) < 0 ||
  3430. _Pickler_Write(self, &tupletwo_op, 1) < 0 ||
  3431. _Pickler_Write(self, &reduce_op, 1) < 0)
  3432. {
  3433. goto error;
  3434. }
  3435. }
  3436. }
  3437. }
  3438. /* Memoize the object. */
  3439. if (memo_put(st, self, obj) < 0)
  3440. goto error;
  3441. }
  3442. if (0) {
  3443. error:
  3444. status = -1;
  3445. }
  3446. Py_XDECREF(module_name);
  3447. Py_XDECREF(global_name);
  3448. Py_XDECREF(module);
  3449. Py_XDECREF(parent);
  3450. Py_XDECREF(dotted_path);
  3451. return status;
  3452. }
  3453. static int
  3454. save_singleton_type(PickleState *state, PicklerObject *self, PyObject *obj,
  3455. PyObject *singleton)
  3456. {
  3457. PyObject *reduce_value;
  3458. int status;
  3459. reduce_value = Py_BuildValue("O(O)", &PyType_Type, singleton);
  3460. if (reduce_value == NULL) {
  3461. return -1;
  3462. }
  3463. status = save_reduce(state, self, reduce_value, obj);
  3464. Py_DECREF(reduce_value);
  3465. return status;
  3466. }
  3467. static int
  3468. save_type(PickleState *state, PicklerObject *self, PyObject *obj)
  3469. {
  3470. if (obj == (PyObject *)&_PyNone_Type) {
  3471. return save_singleton_type(state, self, obj, Py_None);
  3472. }
  3473. else if (obj == (PyObject *)&PyEllipsis_Type) {
  3474. return save_singleton_type(state, self, obj, Py_Ellipsis);
  3475. }
  3476. else if (obj == (PyObject *)&_PyNotImplemented_Type) {
  3477. return save_singleton_type(state, self, obj, Py_NotImplemented);
  3478. }
  3479. return save_global(state, self, obj, NULL);
  3480. }
  3481. static int
  3482. save_pers(PickleState *state, PicklerObject *self, PyObject *obj)
  3483. {
  3484. PyObject *pid = NULL;
  3485. int status = 0;
  3486. const char persid_op = PERSID;
  3487. const char binpersid_op = BINPERSID;
  3488. pid = call_method(self->pers_func, self->pers_func_self, obj);
  3489. if (pid == NULL)
  3490. return -1;
  3491. if (pid != Py_None) {
  3492. if (self->bin) {
  3493. if (save(state, self, pid, 1) < 0 ||
  3494. _Pickler_Write(self, &binpersid_op, 1) < 0)
  3495. goto error;
  3496. }
  3497. else {
  3498. PyObject *pid_str;
  3499. pid_str = PyObject_Str(pid);
  3500. if (pid_str == NULL)
  3501. goto error;
  3502. /* XXX: Should it check whether the pid contains embedded
  3503. newlines? */
  3504. if (!PyUnicode_IS_ASCII(pid_str)) {
  3505. PyErr_SetString(state->PicklingError,
  3506. "persistent IDs in protocol 0 must be "
  3507. "ASCII strings");
  3508. Py_DECREF(pid_str);
  3509. goto error;
  3510. }
  3511. if (_Pickler_Write(self, &persid_op, 1) < 0 ||
  3512. _Pickler_Write(self, PyUnicode_DATA(pid_str),
  3513. PyUnicode_GET_LENGTH(pid_str)) < 0 ||
  3514. _Pickler_Write(self, "\n", 1) < 0) {
  3515. Py_DECREF(pid_str);
  3516. goto error;
  3517. }
  3518. Py_DECREF(pid_str);
  3519. }
  3520. status = 1;
  3521. }
  3522. if (0) {
  3523. error:
  3524. status = -1;
  3525. }
  3526. Py_XDECREF(pid);
  3527. return status;
  3528. }
  3529. static PyObject *
  3530. get_class(PyObject *obj)
  3531. {
  3532. PyObject *cls;
  3533. if (_PyObject_LookupAttr(obj, &_Py_ID(__class__), &cls) == 0) {
  3534. cls = Py_NewRef(Py_TYPE(obj));
  3535. }
  3536. return cls;
  3537. }
  3538. /* We're saving obj, and args is the 2-thru-5 tuple returned by the
  3539. * appropriate __reduce__ method for obj.
  3540. */
  3541. static int
  3542. save_reduce(PickleState *st, PicklerObject *self, PyObject *args,
  3543. PyObject *obj)
  3544. {
  3545. PyObject *callable;
  3546. PyObject *argtup;
  3547. PyObject *state = NULL;
  3548. PyObject *listitems = Py_None;
  3549. PyObject *dictitems = Py_None;
  3550. PyObject *state_setter = Py_None;
  3551. Py_ssize_t size;
  3552. int use_newobj = 0, use_newobj_ex = 0;
  3553. const char reduce_op = REDUCE;
  3554. const char build_op = BUILD;
  3555. const char newobj_op = NEWOBJ;
  3556. const char newobj_ex_op = NEWOBJ_EX;
  3557. size = PyTuple_Size(args);
  3558. if (size < 2 || size > 6) {
  3559. PyErr_SetString(st->PicklingError, "tuple returned by "
  3560. "__reduce__ must contain 2 through 6 elements");
  3561. return -1;
  3562. }
  3563. if (!PyArg_UnpackTuple(args, "save_reduce", 2, 6,
  3564. &callable, &argtup, &state, &listitems, &dictitems,
  3565. &state_setter))
  3566. return -1;
  3567. if (!PyCallable_Check(callable)) {
  3568. PyErr_SetString(st->PicklingError, "first item of the tuple "
  3569. "returned by __reduce__ must be callable");
  3570. return -1;
  3571. }
  3572. if (!PyTuple_Check(argtup)) {
  3573. PyErr_SetString(st->PicklingError, "second item of the tuple "
  3574. "returned by __reduce__ must be a tuple");
  3575. return -1;
  3576. }
  3577. if (state == Py_None)
  3578. state = NULL;
  3579. if (listitems == Py_None)
  3580. listitems = NULL;
  3581. else if (!PyIter_Check(listitems)) {
  3582. PyErr_Format(st->PicklingError, "fourth element of the tuple "
  3583. "returned by __reduce__ must be an iterator, not %s",
  3584. Py_TYPE(listitems)->tp_name);
  3585. return -1;
  3586. }
  3587. if (dictitems == Py_None)
  3588. dictitems = NULL;
  3589. else if (!PyIter_Check(dictitems)) {
  3590. PyErr_Format(st->PicklingError, "fifth element of the tuple "
  3591. "returned by __reduce__ must be an iterator, not %s",
  3592. Py_TYPE(dictitems)->tp_name);
  3593. return -1;
  3594. }
  3595. if (state_setter == Py_None)
  3596. state_setter = NULL;
  3597. else if (!PyCallable_Check(state_setter)) {
  3598. PyErr_Format(st->PicklingError, "sixth element of the tuple "
  3599. "returned by __reduce__ must be a function, not %s",
  3600. Py_TYPE(state_setter)->tp_name);
  3601. return -1;
  3602. }
  3603. if (self->proto >= 2) {
  3604. PyObject *name;
  3605. if (_PyObject_LookupAttr(callable, &_Py_ID(__name__), &name) < 0) {
  3606. return -1;
  3607. }
  3608. if (name != NULL && PyUnicode_Check(name)) {
  3609. use_newobj_ex = _PyUnicode_Equal(name, &_Py_ID(__newobj_ex__));
  3610. if (!use_newobj_ex) {
  3611. use_newobj = _PyUnicode_Equal(name, &_Py_ID(__newobj__));
  3612. }
  3613. }
  3614. Py_XDECREF(name);
  3615. }
  3616. if (use_newobj_ex) {
  3617. PyObject *cls;
  3618. PyObject *args;
  3619. PyObject *kwargs;
  3620. if (PyTuple_GET_SIZE(argtup) != 3) {
  3621. PyErr_Format(st->PicklingError,
  3622. "length of the NEWOBJ_EX argument tuple must be "
  3623. "exactly 3, not %zd", PyTuple_GET_SIZE(argtup));
  3624. return -1;
  3625. }
  3626. cls = PyTuple_GET_ITEM(argtup, 0);
  3627. if (!PyType_Check(cls)) {
  3628. PyErr_Format(st->PicklingError,
  3629. "first item from NEWOBJ_EX argument tuple must "
  3630. "be a class, not %.200s", Py_TYPE(cls)->tp_name);
  3631. return -1;
  3632. }
  3633. args = PyTuple_GET_ITEM(argtup, 1);
  3634. if (!PyTuple_Check(args)) {
  3635. PyErr_Format(st->PicklingError,
  3636. "second item from NEWOBJ_EX argument tuple must "
  3637. "be a tuple, not %.200s", Py_TYPE(args)->tp_name);
  3638. return -1;
  3639. }
  3640. kwargs = PyTuple_GET_ITEM(argtup, 2);
  3641. if (!PyDict_Check(kwargs)) {
  3642. PyErr_Format(st->PicklingError,
  3643. "third item from NEWOBJ_EX argument tuple must "
  3644. "be a dict, not %.200s", Py_TYPE(kwargs)->tp_name);
  3645. return -1;
  3646. }
  3647. if (self->proto >= 4) {
  3648. if (save(st, self, cls, 0) < 0 ||
  3649. save(st, self, args, 0) < 0 ||
  3650. save(st, self, kwargs, 0) < 0 ||
  3651. _Pickler_Write(self, &newobj_ex_op, 1) < 0) {
  3652. return -1;
  3653. }
  3654. }
  3655. else {
  3656. PyObject *newargs;
  3657. PyObject *cls_new;
  3658. Py_ssize_t i;
  3659. newargs = PyTuple_New(PyTuple_GET_SIZE(args) + 2);
  3660. if (newargs == NULL)
  3661. return -1;
  3662. cls_new = PyObject_GetAttr(cls, &_Py_ID(__new__));
  3663. if (cls_new == NULL) {
  3664. Py_DECREF(newargs);
  3665. return -1;
  3666. }
  3667. PyTuple_SET_ITEM(newargs, 0, cls_new);
  3668. PyTuple_SET_ITEM(newargs, 1, Py_NewRef(cls));
  3669. for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
  3670. PyObject *item = PyTuple_GET_ITEM(args, i);
  3671. PyTuple_SET_ITEM(newargs, i + 2, Py_NewRef(item));
  3672. }
  3673. callable = PyObject_Call(st->partial, newargs, kwargs);
  3674. Py_DECREF(newargs);
  3675. if (callable == NULL)
  3676. return -1;
  3677. newargs = PyTuple_New(0);
  3678. if (newargs == NULL) {
  3679. Py_DECREF(callable);
  3680. return -1;
  3681. }
  3682. if (save(st, self, callable, 0) < 0 ||
  3683. save(st, self, newargs, 0) < 0 ||
  3684. _Pickler_Write(self, &reduce_op, 1) < 0) {
  3685. Py_DECREF(newargs);
  3686. Py_DECREF(callable);
  3687. return -1;
  3688. }
  3689. Py_DECREF(newargs);
  3690. Py_DECREF(callable);
  3691. }
  3692. }
  3693. else if (use_newobj) {
  3694. PyObject *cls;
  3695. PyObject *newargtup;
  3696. PyObject *obj_class;
  3697. int p;
  3698. /* Sanity checks. */
  3699. if (PyTuple_GET_SIZE(argtup) < 1) {
  3700. PyErr_SetString(st->PicklingError, "__newobj__ arglist is empty");
  3701. return -1;
  3702. }
  3703. cls = PyTuple_GET_ITEM(argtup, 0);
  3704. if (!PyType_Check(cls)) {
  3705. PyErr_SetString(st->PicklingError, "args[0] from "
  3706. "__newobj__ args is not a type");
  3707. return -1;
  3708. }
  3709. if (obj != NULL) {
  3710. obj_class = get_class(obj);
  3711. if (obj_class == NULL) {
  3712. return -1;
  3713. }
  3714. p = obj_class != cls;
  3715. Py_DECREF(obj_class);
  3716. if (p) {
  3717. PyErr_SetString(st->PicklingError, "args[0] from "
  3718. "__newobj__ args has the wrong class");
  3719. return -1;
  3720. }
  3721. }
  3722. /* XXX: These calls save() are prone to infinite recursion. Imagine
  3723. what happen if the value returned by the __reduce__() method of
  3724. some extension type contains another object of the same type. Ouch!
  3725. Here is a quick example, that I ran into, to illustrate what I
  3726. mean:
  3727. >>> import pickle, copyreg
  3728. >>> copyreg.dispatch_table.pop(complex)
  3729. >>> pickle.dumps(1+2j)
  3730. Traceback (most recent call last):
  3731. ...
  3732. RecursionError: maximum recursion depth exceeded
  3733. Removing the complex class from copyreg.dispatch_table made the
  3734. __reduce_ex__() method emit another complex object:
  3735. >>> (1+1j).__reduce_ex__(2)
  3736. (<function __newobj__ at 0xb7b71c3c>,
  3737. (<class 'complex'>, (1+1j)), None, None, None)
  3738. Thus when save() was called on newargstup (the 2nd item) recursion
  3739. ensued. Of course, the bug was in the complex class which had a
  3740. broken __getnewargs__() that emitted another complex object. But,
  3741. the point, here, is it is quite easy to end up with a broken reduce
  3742. function. */
  3743. /* Save the class and its __new__ arguments. */
  3744. if (save(st, self, cls, 0) < 0) {
  3745. return -1;
  3746. }
  3747. newargtup = PyTuple_GetSlice(argtup, 1, PyTuple_GET_SIZE(argtup));
  3748. if (newargtup == NULL)
  3749. return -1;
  3750. p = save(st, self, newargtup, 0);
  3751. Py_DECREF(newargtup);
  3752. if (p < 0)
  3753. return -1;
  3754. /* Add NEWOBJ opcode. */
  3755. if (_Pickler_Write(self, &newobj_op, 1) < 0)
  3756. return -1;
  3757. }
  3758. else { /* Not using NEWOBJ. */
  3759. if (save(st, self, callable, 0) < 0 ||
  3760. save(st, self, argtup, 0) < 0 ||
  3761. _Pickler_Write(self, &reduce_op, 1) < 0)
  3762. return -1;
  3763. }
  3764. /* obj can be NULL when save_reduce() is used directly. A NULL obj means
  3765. the caller do not want to memoize the object. Not particularly useful,
  3766. but that is to mimic the behavior save_reduce() in pickle.py when
  3767. obj is None. */
  3768. if (obj != NULL) {
  3769. /* If the object is already in the memo, this means it is
  3770. recursive. In this case, throw away everything we put on the
  3771. stack, and fetch the object back from the memo. */
  3772. if (PyMemoTable_Get(self->memo, obj)) {
  3773. const char pop_op = POP;
  3774. if (_Pickler_Write(self, &pop_op, 1) < 0)
  3775. return -1;
  3776. if (memo_get(st, self, obj) < 0)
  3777. return -1;
  3778. return 0;
  3779. }
  3780. else if (memo_put(st, self, obj) < 0)
  3781. return -1;
  3782. }
  3783. if (listitems && batch_list(st, self, listitems) < 0)
  3784. return -1;
  3785. if (dictitems && batch_dict(st, self, dictitems) < 0)
  3786. return -1;
  3787. if (state) {
  3788. if (state_setter == NULL) {
  3789. if (save(st, self, state, 0) < 0 ||
  3790. _Pickler_Write(self, &build_op, 1) < 0)
  3791. return -1;
  3792. }
  3793. else {
  3794. /* If a state_setter is specified, call it instead of load_build to
  3795. * update obj's with its previous state.
  3796. * The first 4 save/write instructions push state_setter and its
  3797. * tuple of expected arguments (obj, state) onto the stack. The
  3798. * REDUCE opcode triggers the state_setter(obj, state) function
  3799. * call. Finally, because state-updating routines only do in-place
  3800. * modification, the whole operation has to be stack-transparent.
  3801. * Thus, we finally pop the call's output from the stack.*/
  3802. const char tupletwo_op = TUPLE2;
  3803. const char pop_op = POP;
  3804. if (save(st, self, state_setter, 0) < 0 ||
  3805. save(st, self, obj, 0) < 0 || save(st, self, state, 0) < 0 ||
  3806. _Pickler_Write(self, &tupletwo_op, 1) < 0 ||
  3807. _Pickler_Write(self, &reduce_op, 1) < 0 ||
  3808. _Pickler_Write(self, &pop_op, 1) < 0)
  3809. return -1;
  3810. }
  3811. }
  3812. return 0;
  3813. }
  3814. static int
  3815. save(PickleState *st, PicklerObject *self, PyObject *obj, int pers_save)
  3816. {
  3817. PyTypeObject *type;
  3818. PyObject *reduce_func = NULL;
  3819. PyObject *reduce_value = NULL;
  3820. int status = 0;
  3821. if (_Pickler_OpcodeBoundary(self) < 0)
  3822. return -1;
  3823. /* The extra pers_save argument is necessary to avoid calling save_pers()
  3824. on its returned object. */
  3825. if (!pers_save && self->pers_func) {
  3826. /* save_pers() returns:
  3827. -1 to signal an error;
  3828. 0 if it did nothing successfully;
  3829. 1 if a persistent id was saved.
  3830. */
  3831. if ((status = save_pers(st, self, obj)) != 0)
  3832. return status;
  3833. }
  3834. type = Py_TYPE(obj);
  3835. /* The old cPickle had an optimization that used switch-case statement
  3836. dispatching on the first letter of the type name. This has was removed
  3837. since benchmarks shown that this optimization was actually slowing
  3838. things down. */
  3839. /* Atom types; these aren't memoized, so don't check the memo. */
  3840. if (obj == Py_None) {
  3841. return save_none(self, obj);
  3842. }
  3843. else if (obj == Py_False || obj == Py_True) {
  3844. return save_bool(self, obj);
  3845. }
  3846. else if (type == &PyLong_Type) {
  3847. return save_long(self, obj);
  3848. }
  3849. else if (type == &PyFloat_Type) {
  3850. return save_float(self, obj);
  3851. }
  3852. /* Check the memo to see if it has the object. If so, generate
  3853. a GET (or BINGET) opcode, instead of pickling the object
  3854. once again. */
  3855. if (PyMemoTable_Get(self->memo, obj)) {
  3856. return memo_get(st, self, obj);
  3857. }
  3858. if (type == &PyBytes_Type) {
  3859. return save_bytes(st, self, obj);
  3860. }
  3861. else if (type == &PyUnicode_Type) {
  3862. return save_unicode(st, self, obj);
  3863. }
  3864. /* We're only calling _Py_EnterRecursiveCall here so that atomic
  3865. types above are pickled faster. */
  3866. if (_Py_EnterRecursiveCall(" while pickling an object")) {
  3867. return -1;
  3868. }
  3869. if (type == &PyDict_Type) {
  3870. status = save_dict(st, self, obj);
  3871. goto done;
  3872. }
  3873. else if (type == &PySet_Type) {
  3874. status = save_set(st, self, obj);
  3875. goto done;
  3876. }
  3877. else if (type == &PyFrozenSet_Type) {
  3878. status = save_frozenset(st, self, obj);
  3879. goto done;
  3880. }
  3881. else if (type == &PyList_Type) {
  3882. status = save_list(st, self, obj);
  3883. goto done;
  3884. }
  3885. else if (type == &PyTuple_Type) {
  3886. status = save_tuple(st, self, obj);
  3887. goto done;
  3888. }
  3889. else if (type == &PyByteArray_Type) {
  3890. status = save_bytearray(st, self, obj);
  3891. goto done;
  3892. }
  3893. else if (type == &PyPickleBuffer_Type) {
  3894. status = save_picklebuffer(st, self, obj);
  3895. goto done;
  3896. }
  3897. /* Now, check reducer_override. If it returns NotImplemented,
  3898. * fallback to save_type or save_global, and then perhaps to the
  3899. * regular reduction mechanism.
  3900. */
  3901. if (self->reducer_override != NULL) {
  3902. reduce_value = PyObject_CallOneArg(self->reducer_override, obj);
  3903. if (reduce_value == NULL) {
  3904. goto error;
  3905. }
  3906. if (reduce_value != Py_NotImplemented) {
  3907. goto reduce;
  3908. }
  3909. Py_SETREF(reduce_value, NULL);
  3910. }
  3911. if (type == &PyType_Type) {
  3912. status = save_type(st, self, obj);
  3913. goto done;
  3914. }
  3915. else if (type == &PyFunction_Type) {
  3916. status = save_global(st, self, obj, NULL);
  3917. goto done;
  3918. }
  3919. /* XXX: This part needs some unit tests. */
  3920. /* Get a reduction callable, and call it. This may come from
  3921. * self.dispatch_table, copyreg.dispatch_table, the object's
  3922. * __reduce_ex__ method, or the object's __reduce__ method.
  3923. */
  3924. if (self->dispatch_table == NULL) {
  3925. reduce_func = PyDict_GetItemWithError(st->dispatch_table,
  3926. (PyObject *)type);
  3927. if (reduce_func == NULL) {
  3928. if (PyErr_Occurred()) {
  3929. goto error;
  3930. }
  3931. } else {
  3932. /* PyDict_GetItemWithError() returns a borrowed reference.
  3933. Increase the reference count to be consistent with
  3934. PyObject_GetItem and _PyObject_GetAttrId used below. */
  3935. Py_INCREF(reduce_func);
  3936. }
  3937. } else {
  3938. reduce_func = PyObject_GetItem(self->dispatch_table,
  3939. (PyObject *)type);
  3940. if (reduce_func == NULL) {
  3941. if (PyErr_ExceptionMatches(PyExc_KeyError))
  3942. PyErr_Clear();
  3943. else
  3944. goto error;
  3945. }
  3946. }
  3947. if (reduce_func != NULL) {
  3948. reduce_value = _Pickle_FastCall(reduce_func, Py_NewRef(obj));
  3949. }
  3950. else if (PyType_IsSubtype(type, &PyType_Type)) {
  3951. status = save_global(st, self, obj, NULL);
  3952. goto done;
  3953. }
  3954. else {
  3955. /* XXX: If the __reduce__ method is defined, __reduce_ex__ is
  3956. automatically defined as __reduce__. While this is convenient, this
  3957. make it impossible to know which method was actually called. Of
  3958. course, this is not a big deal. But still, it would be nice to let
  3959. the user know which method was called when something go
  3960. wrong. Incidentally, this means if __reduce_ex__ is not defined, we
  3961. don't actually have to check for a __reduce__ method. */
  3962. /* Check for a __reduce_ex__ method. */
  3963. if (_PyObject_LookupAttr(obj, &_Py_ID(__reduce_ex__), &reduce_func) < 0) {
  3964. goto error;
  3965. }
  3966. if (reduce_func != NULL) {
  3967. PyObject *proto;
  3968. proto = PyLong_FromLong(self->proto);
  3969. if (proto != NULL) {
  3970. reduce_value = _Pickle_FastCall(reduce_func, proto);
  3971. }
  3972. }
  3973. else {
  3974. /* Check for a __reduce__ method. */
  3975. if (_PyObject_LookupAttr(obj, &_Py_ID(__reduce__), &reduce_func) < 0) {
  3976. goto error;
  3977. }
  3978. if (reduce_func != NULL) {
  3979. reduce_value = PyObject_CallNoArgs(reduce_func);
  3980. }
  3981. else {
  3982. PyErr_Format(st->PicklingError,
  3983. "can't pickle '%.200s' object: %R",
  3984. type->tp_name, obj);
  3985. goto error;
  3986. }
  3987. }
  3988. }
  3989. if (reduce_value == NULL)
  3990. goto error;
  3991. reduce:
  3992. if (PyUnicode_Check(reduce_value)) {
  3993. status = save_global(st, self, obj, reduce_value);
  3994. goto done;
  3995. }
  3996. if (!PyTuple_Check(reduce_value)) {
  3997. PyErr_SetString(st->PicklingError,
  3998. "__reduce__ must return a string or tuple");
  3999. goto error;
  4000. }
  4001. status = save_reduce(st, self, reduce_value, obj);
  4002. if (0) {
  4003. error:
  4004. status = -1;
  4005. }
  4006. done:
  4007. _Py_LeaveRecursiveCall();
  4008. Py_XDECREF(reduce_func);
  4009. Py_XDECREF(reduce_value);
  4010. return status;
  4011. }
  4012. static int
  4013. dump(PickleState *state, PicklerObject *self, PyObject *obj)
  4014. {
  4015. const char stop_op = STOP;
  4016. int status = -1;
  4017. PyObject *tmp;
  4018. if (_PyObject_LookupAttr((PyObject *)self, &_Py_ID(reducer_override),
  4019. &tmp) < 0) {
  4020. goto error;
  4021. }
  4022. /* Cache the reducer_override method, if it exists. */
  4023. if (tmp != NULL) {
  4024. Py_XSETREF(self->reducer_override, tmp);
  4025. }
  4026. else {
  4027. Py_CLEAR(self->reducer_override);
  4028. }
  4029. if (self->proto >= 2) {
  4030. char header[2];
  4031. header[0] = PROTO;
  4032. assert(self->proto >= 0 && self->proto < 256);
  4033. header[1] = (unsigned char)self->proto;
  4034. if (_Pickler_Write(self, header, 2) < 0)
  4035. goto error;
  4036. if (self->proto >= 4)
  4037. self->framing = 1;
  4038. }
  4039. if (save(state, self, obj, 0) < 0 ||
  4040. _Pickler_Write(self, &stop_op, 1) < 0 ||
  4041. _Pickler_CommitFrame(self) < 0)
  4042. goto error;
  4043. // Success
  4044. status = 0;
  4045. error:
  4046. self->framing = 0;
  4047. /* Break the reference cycle we generated at the beginning this function
  4048. * call when setting the reducer_override attribute of the Pickler instance
  4049. * to a bound method of the same instance. This is important as the Pickler
  4050. * instance holds a reference to each object it has pickled (through its
  4051. * memo): thus, these objects won't be garbage-collected as long as the
  4052. * Pickler itself is not collected. */
  4053. Py_CLEAR(self->reducer_override);
  4054. return status;
  4055. }
  4056. /*[clinic input]
  4057. _pickle.Pickler.clear_memo
  4058. Clears the pickler's "memo".
  4059. The memo is the data structure that remembers which objects the
  4060. pickler has already seen, so that shared or recursive objects are
  4061. pickled by reference and not by value. This method is useful when
  4062. re-using picklers.
  4063. [clinic start generated code]*/
  4064. static PyObject *
  4065. _pickle_Pickler_clear_memo_impl(PicklerObject *self)
  4066. /*[clinic end generated code: output=8665c8658aaa094b input=01bdad52f3d93e56]*/
  4067. {
  4068. if (self->memo)
  4069. PyMemoTable_Clear(self->memo);
  4070. Py_RETURN_NONE;
  4071. }
  4072. /*[clinic input]
  4073. _pickle.Pickler.dump
  4074. cls: defining_class
  4075. obj: object
  4076. /
  4077. Write a pickled representation of the given object to the open file.
  4078. [clinic start generated code]*/
  4079. static PyObject *
  4080. _pickle_Pickler_dump_impl(PicklerObject *self, PyTypeObject *cls,
  4081. PyObject *obj)
  4082. /*[clinic end generated code: output=952cf7f68b1445bb input=f949d84151983594]*/
  4083. {
  4084. PickleState *st = _Pickle_GetStateByClass(cls);
  4085. /* Check whether the Pickler was initialized correctly (issue3664).
  4086. Developers often forget to call __init__() in their subclasses, which
  4087. would trigger a segfault without this check. */
  4088. if (self->write == NULL) {
  4089. PyErr_Format(st->PicklingError,
  4090. "Pickler.__init__() was not called by %s.__init__()",
  4091. Py_TYPE(self)->tp_name);
  4092. return NULL;
  4093. }
  4094. if (_Pickler_ClearBuffer(self) < 0)
  4095. return NULL;
  4096. if (dump(st, self, obj) < 0)
  4097. return NULL;
  4098. if (_Pickler_FlushToFile(self) < 0)
  4099. return NULL;
  4100. Py_RETURN_NONE;
  4101. }
  4102. /*[clinic input]
  4103. _pickle.Pickler.__sizeof__ -> size_t
  4104. Returns size in memory, in bytes.
  4105. [clinic start generated code]*/
  4106. static size_t
  4107. _pickle_Pickler___sizeof___impl(PicklerObject *self)
  4108. /*[clinic end generated code: output=23ad75658d3b59ff input=d8127c8e7012ebd7]*/
  4109. {
  4110. size_t res = _PyObject_SIZE(Py_TYPE(self));
  4111. if (self->memo != NULL) {
  4112. res += sizeof(PyMemoTable);
  4113. res += self->memo->mt_allocated * sizeof(PyMemoEntry);
  4114. }
  4115. if (self->output_buffer != NULL) {
  4116. size_t s = _PySys_GetSizeOf(self->output_buffer);
  4117. if (s == (size_t)-1) {
  4118. return -1;
  4119. }
  4120. res += s;
  4121. }
  4122. return res;
  4123. }
  4124. static struct PyMethodDef Pickler_methods[] = {
  4125. _PICKLE_PICKLER_DUMP_METHODDEF
  4126. _PICKLE_PICKLER_CLEAR_MEMO_METHODDEF
  4127. _PICKLE_PICKLER___SIZEOF___METHODDEF
  4128. {NULL, NULL} /* sentinel */
  4129. };
  4130. static int
  4131. Pickler_clear(PicklerObject *self)
  4132. {
  4133. Py_CLEAR(self->output_buffer);
  4134. Py_CLEAR(self->write);
  4135. Py_CLEAR(self->pers_func);
  4136. Py_CLEAR(self->dispatch_table);
  4137. Py_CLEAR(self->fast_memo);
  4138. Py_CLEAR(self->reducer_override);
  4139. Py_CLEAR(self->buffer_callback);
  4140. if (self->memo != NULL) {
  4141. PyMemoTable *memo = self->memo;
  4142. self->memo = NULL;
  4143. PyMemoTable_Del(memo);
  4144. }
  4145. return 0;
  4146. }
  4147. static void
  4148. Pickler_dealloc(PicklerObject *self)
  4149. {
  4150. PyTypeObject *tp = Py_TYPE(self);
  4151. PyObject_GC_UnTrack(self);
  4152. (void)Pickler_clear(self);
  4153. tp->tp_free((PyObject *)self);
  4154. Py_DECREF(tp);
  4155. }
  4156. static int
  4157. Pickler_traverse(PicklerObject *self, visitproc visit, void *arg)
  4158. {
  4159. Py_VISIT(Py_TYPE(self));
  4160. Py_VISIT(self->write);
  4161. Py_VISIT(self->pers_func);
  4162. Py_VISIT(self->dispatch_table);
  4163. Py_VISIT(self->fast_memo);
  4164. Py_VISIT(self->reducer_override);
  4165. Py_VISIT(self->buffer_callback);
  4166. PyMemoTable *memo = self->memo;
  4167. if (memo && memo->mt_table) {
  4168. Py_ssize_t i = memo->mt_allocated;
  4169. while (--i >= 0) {
  4170. Py_VISIT(memo->mt_table[i].me_key);
  4171. }
  4172. }
  4173. return 0;
  4174. }
  4175. /*[clinic input]
  4176. _pickle.Pickler.__init__
  4177. file: object
  4178. protocol: object = None
  4179. fix_imports: bool = True
  4180. buffer_callback: object = None
  4181. This takes a binary file for writing a pickle data stream.
  4182. The optional *protocol* argument tells the pickler to use the given
  4183. protocol; supported protocols are 0, 1, 2, 3, 4 and 5. The default
  4184. protocol is 4. It was introduced in Python 3.4, and is incompatible
  4185. with previous versions.
  4186. Specifying a negative protocol version selects the highest protocol
  4187. version supported. The higher the protocol used, the more recent the
  4188. version of Python needed to read the pickle produced.
  4189. The *file* argument must have a write() method that accepts a single
  4190. bytes argument. It can thus be a file object opened for binary
  4191. writing, an io.BytesIO instance, or any other custom object that meets
  4192. this interface.
  4193. If *fix_imports* is True and protocol is less than 3, pickle will try
  4194. to map the new Python 3 names to the old module names used in Python
  4195. 2, so that the pickle data stream is readable with Python 2.
  4196. If *buffer_callback* is None (the default), buffer views are
  4197. serialized into *file* as part of the pickle stream.
  4198. If *buffer_callback* is not None, then it can be called any number
  4199. of times with a buffer view. If the callback returns a false value
  4200. (such as None), the given buffer is out-of-band; otherwise the
  4201. buffer is serialized in-band, i.e. inside the pickle stream.
  4202. It is an error if *buffer_callback* is not None and *protocol*
  4203. is None or smaller than 5.
  4204. [clinic start generated code]*/
  4205. static int
  4206. _pickle_Pickler___init___impl(PicklerObject *self, PyObject *file,
  4207. PyObject *protocol, int fix_imports,
  4208. PyObject *buffer_callback)
  4209. /*[clinic end generated code: output=0abedc50590d259b input=a7c969699bf5dad3]*/
  4210. {
  4211. /* In case of multiple __init__() calls, clear previous content. */
  4212. if (self->write != NULL)
  4213. (void)Pickler_clear(self);
  4214. if (_Pickler_SetProtocol(self, protocol, fix_imports) < 0)
  4215. return -1;
  4216. if (_Pickler_SetOutputStream(self, file) < 0)
  4217. return -1;
  4218. if (_Pickler_SetBufferCallback(self, buffer_callback) < 0)
  4219. return -1;
  4220. /* memo and output_buffer may have already been created in _Pickler_New */
  4221. if (self->memo == NULL) {
  4222. self->memo = PyMemoTable_New();
  4223. if (self->memo == NULL)
  4224. return -1;
  4225. }
  4226. self->output_len = 0;
  4227. if (self->output_buffer == NULL) {
  4228. self->max_output_len = WRITE_BUF_SIZE;
  4229. self->output_buffer = PyBytes_FromStringAndSize(NULL,
  4230. self->max_output_len);
  4231. if (self->output_buffer == NULL)
  4232. return -1;
  4233. }
  4234. self->fast = 0;
  4235. self->fast_nesting = 0;
  4236. self->fast_memo = NULL;
  4237. if (init_method_ref((PyObject *)self, &_Py_ID(persistent_id),
  4238. &self->pers_func, &self->pers_func_self) < 0)
  4239. {
  4240. return -1;
  4241. }
  4242. if (self->dispatch_table != NULL) {
  4243. return 0;
  4244. }
  4245. if (_PyObject_LookupAttr((PyObject *)self, &_Py_ID(dispatch_table),
  4246. &self->dispatch_table) < 0) {
  4247. return -1;
  4248. }
  4249. return 0;
  4250. }
  4251. /* Define a proxy object for the Pickler's internal memo object. This is to
  4252. * avoid breaking code like:
  4253. * pickler.memo.clear()
  4254. * and
  4255. * pickler.memo = saved_memo
  4256. * Is this a good idea? Not really, but we don't want to break code that uses
  4257. * it. Note that we don't implement the entire mapping API here. This is
  4258. * intentional, as these should be treated as black-box implementation details.
  4259. */
  4260. /*[clinic input]
  4261. _pickle.PicklerMemoProxy.clear
  4262. Remove all items from memo.
  4263. [clinic start generated code]*/
  4264. static PyObject *
  4265. _pickle_PicklerMemoProxy_clear_impl(PicklerMemoProxyObject *self)
  4266. /*[clinic end generated code: output=5fb9370d48ae8b05 input=ccc186dacd0f1405]*/
  4267. {
  4268. if (self->pickler->memo)
  4269. PyMemoTable_Clear(self->pickler->memo);
  4270. Py_RETURN_NONE;
  4271. }
  4272. /*[clinic input]
  4273. _pickle.PicklerMemoProxy.copy
  4274. Copy the memo to a new object.
  4275. [clinic start generated code]*/
  4276. static PyObject *
  4277. _pickle_PicklerMemoProxy_copy_impl(PicklerMemoProxyObject *self)
  4278. /*[clinic end generated code: output=bb83a919d29225ef input=b73043485ac30b36]*/
  4279. {
  4280. PyMemoTable *memo;
  4281. PyObject *new_memo = PyDict_New();
  4282. if (new_memo == NULL)
  4283. return NULL;
  4284. memo = self->pickler->memo;
  4285. for (size_t i = 0; i < memo->mt_allocated; ++i) {
  4286. PyMemoEntry entry = memo->mt_table[i];
  4287. if (entry.me_key != NULL) {
  4288. int status;
  4289. PyObject *key, *value;
  4290. key = PyLong_FromVoidPtr(entry.me_key);
  4291. if (key == NULL) {
  4292. goto error;
  4293. }
  4294. value = Py_BuildValue("nO", entry.me_value, entry.me_key);
  4295. if (value == NULL) {
  4296. Py_DECREF(key);
  4297. goto error;
  4298. }
  4299. status = PyDict_SetItem(new_memo, key, value);
  4300. Py_DECREF(key);
  4301. Py_DECREF(value);
  4302. if (status < 0)
  4303. goto error;
  4304. }
  4305. }
  4306. return new_memo;
  4307. error:
  4308. Py_XDECREF(new_memo);
  4309. return NULL;
  4310. }
  4311. /*[clinic input]
  4312. _pickle.PicklerMemoProxy.__reduce__
  4313. Implement pickle support.
  4314. [clinic start generated code]*/
  4315. static PyObject *
  4316. _pickle_PicklerMemoProxy___reduce___impl(PicklerMemoProxyObject *self)
  4317. /*[clinic end generated code: output=bebba1168863ab1d input=2f7c540e24b7aae4]*/
  4318. {
  4319. PyObject *reduce_value, *dict_args;
  4320. PyObject *contents = _pickle_PicklerMemoProxy_copy_impl(self);
  4321. if (contents == NULL)
  4322. return NULL;
  4323. reduce_value = PyTuple_New(2);
  4324. if (reduce_value == NULL) {
  4325. Py_DECREF(contents);
  4326. return NULL;
  4327. }
  4328. dict_args = PyTuple_New(1);
  4329. if (dict_args == NULL) {
  4330. Py_DECREF(contents);
  4331. Py_DECREF(reduce_value);
  4332. return NULL;
  4333. }
  4334. PyTuple_SET_ITEM(dict_args, 0, contents);
  4335. PyTuple_SET_ITEM(reduce_value, 0, Py_NewRef(&PyDict_Type));
  4336. PyTuple_SET_ITEM(reduce_value, 1, dict_args);
  4337. return reduce_value;
  4338. }
  4339. static PyMethodDef picklerproxy_methods[] = {
  4340. _PICKLE_PICKLERMEMOPROXY_CLEAR_METHODDEF
  4341. _PICKLE_PICKLERMEMOPROXY_COPY_METHODDEF
  4342. _PICKLE_PICKLERMEMOPROXY___REDUCE___METHODDEF
  4343. {NULL, NULL} /* sentinel */
  4344. };
  4345. static void
  4346. PicklerMemoProxy_dealloc(PicklerMemoProxyObject *self)
  4347. {
  4348. PyTypeObject *tp = Py_TYPE(self);
  4349. PyObject_GC_UnTrack(self);
  4350. Py_CLEAR(self->pickler);
  4351. tp->tp_free((PyObject *)self);
  4352. Py_DECREF(tp);
  4353. }
  4354. static int
  4355. PicklerMemoProxy_traverse(PicklerMemoProxyObject *self,
  4356. visitproc visit, void *arg)
  4357. {
  4358. Py_VISIT(Py_TYPE(self));
  4359. Py_VISIT(self->pickler);
  4360. return 0;
  4361. }
  4362. static int
  4363. PicklerMemoProxy_clear(PicklerMemoProxyObject *self)
  4364. {
  4365. Py_CLEAR(self->pickler);
  4366. return 0;
  4367. }
  4368. static PyType_Slot memoproxy_slots[] = {
  4369. {Py_tp_dealloc, PicklerMemoProxy_dealloc},
  4370. {Py_tp_traverse, PicklerMemoProxy_traverse},
  4371. {Py_tp_clear, PicklerMemoProxy_clear},
  4372. {Py_tp_methods, picklerproxy_methods},
  4373. {Py_tp_hash, PyObject_HashNotImplemented},
  4374. {0, NULL},
  4375. };
  4376. static PyType_Spec memoproxy_spec = {
  4377. .name = "_pickle.PicklerMemoProxy",
  4378. .basicsize = sizeof(PicklerMemoProxyObject),
  4379. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  4380. Py_TPFLAGS_IMMUTABLETYPE),
  4381. .slots = memoproxy_slots,
  4382. };
  4383. static PyObject *
  4384. PicklerMemoProxy_New(PicklerObject *pickler)
  4385. {
  4386. PicklerMemoProxyObject *self;
  4387. PickleState *st = _Pickle_FindStateByType(Py_TYPE(pickler));
  4388. self = PyObject_GC_New(PicklerMemoProxyObject, st->PicklerMemoProxyType);
  4389. if (self == NULL)
  4390. return NULL;
  4391. self->pickler = (PicklerObject*)Py_NewRef(pickler);
  4392. PyObject_GC_Track(self);
  4393. return (PyObject *)self;
  4394. }
  4395. /*****************************************************************************/
  4396. static PyObject *
  4397. Pickler_get_memo(PicklerObject *self, void *Py_UNUSED(ignored))
  4398. {
  4399. return PicklerMemoProxy_New(self);
  4400. }
  4401. static int
  4402. Pickler_set_memo(PicklerObject *self, PyObject *obj, void *Py_UNUSED(ignored))
  4403. {
  4404. PyMemoTable *new_memo = NULL;
  4405. if (obj == NULL) {
  4406. PyErr_SetString(PyExc_TypeError,
  4407. "attribute deletion is not supported");
  4408. return -1;
  4409. }
  4410. PickleState *st = _Pickle_FindStateByType(Py_TYPE(self));
  4411. if (Py_IS_TYPE(obj, st->PicklerMemoProxyType)) {
  4412. PicklerObject *pickler =
  4413. ((PicklerMemoProxyObject *)obj)->pickler;
  4414. new_memo = PyMemoTable_Copy(pickler->memo);
  4415. if (new_memo == NULL)
  4416. return -1;
  4417. }
  4418. else if (PyDict_Check(obj)) {
  4419. Py_ssize_t i = 0;
  4420. PyObject *key, *value;
  4421. new_memo = PyMemoTable_New();
  4422. if (new_memo == NULL)
  4423. return -1;
  4424. while (PyDict_Next(obj, &i, &key, &value)) {
  4425. Py_ssize_t memo_id;
  4426. PyObject *memo_obj;
  4427. if (!PyTuple_Check(value) || PyTuple_GET_SIZE(value) != 2) {
  4428. PyErr_SetString(PyExc_TypeError,
  4429. "'memo' values must be 2-item tuples");
  4430. goto error;
  4431. }
  4432. memo_id = PyLong_AsSsize_t(PyTuple_GET_ITEM(value, 0));
  4433. if (memo_id == -1 && PyErr_Occurred())
  4434. goto error;
  4435. memo_obj = PyTuple_GET_ITEM(value, 1);
  4436. if (PyMemoTable_Set(new_memo, memo_obj, memo_id) < 0)
  4437. goto error;
  4438. }
  4439. }
  4440. else {
  4441. PyErr_Format(PyExc_TypeError,
  4442. "'memo' attribute must be a PicklerMemoProxy object "
  4443. "or dict, not %.200s", Py_TYPE(obj)->tp_name);
  4444. return -1;
  4445. }
  4446. PyMemoTable_Del(self->memo);
  4447. self->memo = new_memo;
  4448. return 0;
  4449. error:
  4450. if (new_memo)
  4451. PyMemoTable_Del(new_memo);
  4452. return -1;
  4453. }
  4454. static PyObject *
  4455. Pickler_get_persid(PicklerObject *self, void *Py_UNUSED(ignored))
  4456. {
  4457. if (self->pers_func == NULL) {
  4458. PyErr_SetString(PyExc_AttributeError, "persistent_id");
  4459. return NULL;
  4460. }
  4461. return reconstruct_method(self->pers_func, self->pers_func_self);
  4462. }
  4463. static int
  4464. Pickler_set_persid(PicklerObject *self, PyObject *value, void *Py_UNUSED(ignored))
  4465. {
  4466. if (value == NULL) {
  4467. PyErr_SetString(PyExc_TypeError,
  4468. "attribute deletion is not supported");
  4469. return -1;
  4470. }
  4471. if (!PyCallable_Check(value)) {
  4472. PyErr_SetString(PyExc_TypeError,
  4473. "persistent_id must be a callable taking one argument");
  4474. return -1;
  4475. }
  4476. self->pers_func_self = NULL;
  4477. Py_XSETREF(self->pers_func, Py_NewRef(value));
  4478. return 0;
  4479. }
  4480. static PyMemberDef Pickler_members[] = {
  4481. {"bin", T_INT, offsetof(PicklerObject, bin)},
  4482. {"fast", T_INT, offsetof(PicklerObject, fast)},
  4483. {"dispatch_table", T_OBJECT_EX, offsetof(PicklerObject, dispatch_table)},
  4484. {NULL}
  4485. };
  4486. static PyGetSetDef Pickler_getsets[] = {
  4487. {"memo", (getter)Pickler_get_memo,
  4488. (setter)Pickler_set_memo},
  4489. {"persistent_id", (getter)Pickler_get_persid,
  4490. (setter)Pickler_set_persid},
  4491. {NULL}
  4492. };
  4493. static PyType_Slot pickler_type_slots[] = {
  4494. {Py_tp_dealloc, Pickler_dealloc},
  4495. {Py_tp_methods, Pickler_methods},
  4496. {Py_tp_members, Pickler_members},
  4497. {Py_tp_getset, Pickler_getsets},
  4498. {Py_tp_clear, Pickler_clear},
  4499. {Py_tp_doc, (char*)_pickle_Pickler___init____doc__},
  4500. {Py_tp_traverse, Pickler_traverse},
  4501. {Py_tp_init, _pickle_Pickler___init__},
  4502. {Py_tp_new, PyType_GenericNew},
  4503. {Py_tp_alloc, PyType_GenericAlloc},
  4504. {Py_tp_free, PyObject_GC_Del},
  4505. {0, NULL},
  4506. };
  4507. static PyType_Spec pickler_type_spec = {
  4508. .name = "_pickle.Pickler",
  4509. .basicsize = sizeof(PicklerObject),
  4510. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  4511. Py_TPFLAGS_IMMUTABLETYPE),
  4512. .slots = pickler_type_slots,
  4513. };
  4514. /* Temporary helper for calling self.find_class().
  4515. XXX: It would be nice to able to avoid Python function call overhead, by
  4516. using directly the C version of find_class(), when find_class() is not
  4517. overridden by a subclass. Although, this could become rather hackish. A
  4518. simpler optimization would be to call the C function when self is not a
  4519. subclass instance. */
  4520. static PyObject *
  4521. find_class(UnpicklerObject *self, PyObject *module_name, PyObject *global_name)
  4522. {
  4523. return PyObject_CallMethodObjArgs((PyObject *)self, &_Py_ID(find_class),
  4524. module_name, global_name, NULL);
  4525. }
  4526. static Py_ssize_t
  4527. marker(PickleState *st, UnpicklerObject *self)
  4528. {
  4529. if (self->num_marks < 1) {
  4530. PyErr_SetString(st->UnpicklingError, "could not find MARK");
  4531. return -1;
  4532. }
  4533. Py_ssize_t mark = self->marks[--self->num_marks];
  4534. self->stack->mark_set = self->num_marks != 0;
  4535. self->stack->fence = self->num_marks ?
  4536. self->marks[self->num_marks - 1] : 0;
  4537. return mark;
  4538. }
  4539. static int
  4540. load_none(PickleState *state, UnpicklerObject *self)
  4541. {
  4542. PDATA_APPEND(self->stack, Py_None, -1);
  4543. return 0;
  4544. }
  4545. static int
  4546. load_int(PickleState *state, UnpicklerObject *self)
  4547. {
  4548. PyObject *value;
  4549. char *endptr, *s;
  4550. Py_ssize_t len;
  4551. long x;
  4552. if ((len = _Unpickler_Readline(state, self, &s)) < 0)
  4553. return -1;
  4554. if (len < 2)
  4555. return bad_readline(state);
  4556. errno = 0;
  4557. /* XXX: Should the base argument of strtol() be explicitly set to 10?
  4558. XXX(avassalotti): Should this uses PyOS_strtol()? */
  4559. x = strtol(s, &endptr, 0);
  4560. if (errno || (*endptr != '\n' && *endptr != '\0')) {
  4561. /* Hm, maybe we've got something long. Let's try reading
  4562. * it as a Python int object. */
  4563. errno = 0;
  4564. /* XXX: Same thing about the base here. */
  4565. value = PyLong_FromString(s, NULL, 0);
  4566. if (value == NULL) {
  4567. PyErr_SetString(PyExc_ValueError,
  4568. "could not convert string to int");
  4569. return -1;
  4570. }
  4571. }
  4572. else {
  4573. if (len == 3 && (x == 0 || x == 1)) {
  4574. if ((value = PyBool_FromLong(x)) == NULL)
  4575. return -1;
  4576. }
  4577. else {
  4578. if ((value = PyLong_FromLong(x)) == NULL)
  4579. return -1;
  4580. }
  4581. }
  4582. PDATA_PUSH(self->stack, value, -1);
  4583. return 0;
  4584. }
  4585. static int
  4586. load_bool(PickleState *state, UnpicklerObject *self, PyObject *boolean)
  4587. {
  4588. assert(boolean == Py_True || boolean == Py_False);
  4589. PDATA_APPEND(self->stack, boolean, -1);
  4590. return 0;
  4591. }
  4592. /* s contains x bytes of an unsigned little-endian integer. Return its value
  4593. * as a C Py_ssize_t, or -1 if it's higher than PY_SSIZE_T_MAX.
  4594. */
  4595. static Py_ssize_t
  4596. calc_binsize(char *bytes, int nbytes)
  4597. {
  4598. unsigned char *s = (unsigned char *)bytes;
  4599. int i;
  4600. size_t x = 0;
  4601. if (nbytes > (int)sizeof(size_t)) {
  4602. /* Check for integer overflow. BINBYTES8 and BINUNICODE8 opcodes
  4603. * have 64-bit size that can't be represented on 32-bit platform.
  4604. */
  4605. for (i = (int)sizeof(size_t); i < nbytes; i++) {
  4606. if (s[i])
  4607. return -1;
  4608. }
  4609. nbytes = (int)sizeof(size_t);
  4610. }
  4611. for (i = 0; i < nbytes; i++) {
  4612. x |= (size_t) s[i] << (8 * i);
  4613. }
  4614. if (x > PY_SSIZE_T_MAX)
  4615. return -1;
  4616. else
  4617. return (Py_ssize_t) x;
  4618. }
  4619. /* s contains x bytes of a little-endian integer. Return its value as a
  4620. * C int. Obscure: when x is 1 or 2, this is an unsigned little-endian
  4621. * int, but when x is 4 it's a signed one. This is a historical source
  4622. * of x-platform bugs.
  4623. */
  4624. static long
  4625. calc_binint(char *bytes, int nbytes)
  4626. {
  4627. unsigned char *s = (unsigned char *)bytes;
  4628. Py_ssize_t i;
  4629. long x = 0;
  4630. for (i = 0; i < nbytes; i++) {
  4631. x |= (long)s[i] << (8 * i);
  4632. }
  4633. /* Unlike BININT1 and BININT2, BININT (more accurately BININT4)
  4634. * is signed, so on a box with longs bigger than 4 bytes we need
  4635. * to extend a BININT's sign bit to the full width.
  4636. */
  4637. if (SIZEOF_LONG > 4 && nbytes == 4) {
  4638. x |= -(x & (1L << 31));
  4639. }
  4640. return x;
  4641. }
  4642. static int
  4643. load_binintx(UnpicklerObject *self, char *s, int size)
  4644. {
  4645. PyObject *value;
  4646. long x;
  4647. x = calc_binint(s, size);
  4648. if ((value = PyLong_FromLong(x)) == NULL)
  4649. return -1;
  4650. PDATA_PUSH(self->stack, value, -1);
  4651. return 0;
  4652. }
  4653. static int
  4654. load_binint(PickleState *state, UnpicklerObject *self)
  4655. {
  4656. char *s;
  4657. if (_Unpickler_Read(self, state, &s, 4) < 0)
  4658. return -1;
  4659. return load_binintx(self, s, 4);
  4660. }
  4661. static int
  4662. load_binint1(PickleState *state, UnpicklerObject *self)
  4663. {
  4664. char *s;
  4665. if (_Unpickler_Read(self, state, &s, 1) < 0)
  4666. return -1;
  4667. return load_binintx(self, s, 1);
  4668. }
  4669. static int
  4670. load_binint2(PickleState *state, UnpicklerObject *self)
  4671. {
  4672. char *s;
  4673. if (_Unpickler_Read(self, state, &s, 2) < 0)
  4674. return -1;
  4675. return load_binintx(self, s, 2);
  4676. }
  4677. static int
  4678. load_long(PickleState *state, UnpicklerObject *self)
  4679. {
  4680. PyObject *value;
  4681. char *s = NULL;
  4682. Py_ssize_t len;
  4683. if ((len = _Unpickler_Readline(state, self, &s)) < 0)
  4684. return -1;
  4685. if (len < 2)
  4686. return bad_readline(state);
  4687. /* s[len-2] will usually be 'L' (and s[len-1] is '\n'); we need to remove
  4688. the 'L' before calling PyLong_FromString. In order to maintain
  4689. compatibility with Python 3.0.0, we don't actually *require*
  4690. the 'L' to be present. */
  4691. if (s[len-2] == 'L')
  4692. s[len-2] = '\0';
  4693. /* XXX: Should the base argument explicitly set to 10? */
  4694. value = PyLong_FromString(s, NULL, 0);
  4695. if (value == NULL)
  4696. return -1;
  4697. PDATA_PUSH(self->stack, value, -1);
  4698. return 0;
  4699. }
  4700. /* 'size' bytes contain the # of bytes of little-endian 256's-complement
  4701. * data following.
  4702. */
  4703. static int
  4704. load_counted_long(PickleState *st, UnpicklerObject *self, int size)
  4705. {
  4706. PyObject *value;
  4707. char *nbytes;
  4708. char *pdata;
  4709. assert(size == 1 || size == 4);
  4710. if (_Unpickler_Read(self, st, &nbytes, size) < 0)
  4711. return -1;
  4712. size = calc_binint(nbytes, size);
  4713. if (size < 0) {
  4714. /* Corrupt or hostile pickle -- we never write one like this */
  4715. PyErr_SetString(st->UnpicklingError,
  4716. "LONG pickle has negative byte count");
  4717. return -1;
  4718. }
  4719. if (size == 0)
  4720. value = PyLong_FromLong(0L);
  4721. else {
  4722. /* Read the raw little-endian bytes and convert. */
  4723. if (_Unpickler_Read(self, st, &pdata, size) < 0)
  4724. return -1;
  4725. value = _PyLong_FromByteArray((unsigned char *)pdata, (size_t)size,
  4726. 1 /* little endian */ , 1 /* signed */ );
  4727. }
  4728. if (value == NULL)
  4729. return -1;
  4730. PDATA_PUSH(self->stack, value, -1);
  4731. return 0;
  4732. }
  4733. static int
  4734. load_float(PickleState *state, UnpicklerObject *self)
  4735. {
  4736. PyObject *value;
  4737. char *endptr, *s;
  4738. Py_ssize_t len;
  4739. double d;
  4740. if ((len = _Unpickler_Readline(state, self, &s)) < 0)
  4741. return -1;
  4742. if (len < 2)
  4743. return bad_readline(state);
  4744. errno = 0;
  4745. d = PyOS_string_to_double(s, &endptr, PyExc_OverflowError);
  4746. if (d == -1.0 && PyErr_Occurred())
  4747. return -1;
  4748. if ((endptr[0] != '\n') && (endptr[0] != '\0')) {
  4749. PyErr_SetString(PyExc_ValueError, "could not convert string to float");
  4750. return -1;
  4751. }
  4752. value = PyFloat_FromDouble(d);
  4753. if (value == NULL)
  4754. return -1;
  4755. PDATA_PUSH(self->stack, value, -1);
  4756. return 0;
  4757. }
  4758. static int
  4759. load_binfloat(PickleState *state, UnpicklerObject *self)
  4760. {
  4761. PyObject *value;
  4762. double x;
  4763. char *s;
  4764. if (_Unpickler_Read(self, state, &s, 8) < 0)
  4765. return -1;
  4766. x = PyFloat_Unpack8(s, 0);
  4767. if (x == -1.0 && PyErr_Occurred())
  4768. return -1;
  4769. if ((value = PyFloat_FromDouble(x)) == NULL)
  4770. return -1;
  4771. PDATA_PUSH(self->stack, value, -1);
  4772. return 0;
  4773. }
  4774. static int
  4775. load_string(PickleState *st, UnpicklerObject *self)
  4776. {
  4777. PyObject *bytes;
  4778. PyObject *obj;
  4779. Py_ssize_t len;
  4780. char *s, *p;
  4781. if ((len = _Unpickler_Readline(st, self, &s)) < 0)
  4782. return -1;
  4783. /* Strip the newline */
  4784. len--;
  4785. /* Strip outermost quotes */
  4786. if (len >= 2 && s[0] == s[len - 1] && (s[0] == '\'' || s[0] == '"')) {
  4787. p = s + 1;
  4788. len -= 2;
  4789. }
  4790. else {
  4791. PyErr_SetString(st->UnpicklingError,
  4792. "the STRING opcode argument must be quoted");
  4793. return -1;
  4794. }
  4795. assert(len >= 0);
  4796. /* Use the PyBytes API to decode the string, since that is what is used
  4797. to encode, and then coerce the result to Unicode. */
  4798. bytes = PyBytes_DecodeEscape(p, len, NULL, 0, NULL);
  4799. if (bytes == NULL)
  4800. return -1;
  4801. /* Leave the Python 2.x strings as bytes if the *encoding* given to the
  4802. Unpickler was 'bytes'. Otherwise, convert them to unicode. */
  4803. if (strcmp(self->encoding, "bytes") == 0) {
  4804. obj = bytes;
  4805. }
  4806. else {
  4807. obj = PyUnicode_FromEncodedObject(bytes, self->encoding, self->errors);
  4808. Py_DECREF(bytes);
  4809. if (obj == NULL) {
  4810. return -1;
  4811. }
  4812. }
  4813. PDATA_PUSH(self->stack, obj, -1);
  4814. return 0;
  4815. }
  4816. static int
  4817. load_counted_binstring(PickleState *st, UnpicklerObject *self, int nbytes)
  4818. {
  4819. PyObject *obj;
  4820. Py_ssize_t size;
  4821. char *s;
  4822. if (_Unpickler_Read(self, st, &s, nbytes) < 0)
  4823. return -1;
  4824. size = calc_binsize(s, nbytes);
  4825. if (size < 0) {
  4826. PyErr_Format(st->UnpicklingError,
  4827. "BINSTRING exceeds system's maximum size of %zd bytes",
  4828. PY_SSIZE_T_MAX);
  4829. return -1;
  4830. }
  4831. if (_Unpickler_Read(self, st, &s, size) < 0)
  4832. return -1;
  4833. /* Convert Python 2.x strings to bytes if the *encoding* given to the
  4834. Unpickler was 'bytes'. Otherwise, convert them to unicode. */
  4835. if (strcmp(self->encoding, "bytes") == 0) {
  4836. obj = PyBytes_FromStringAndSize(s, size);
  4837. }
  4838. else {
  4839. obj = PyUnicode_Decode(s, size, self->encoding, self->errors);
  4840. }
  4841. if (obj == NULL) {
  4842. return -1;
  4843. }
  4844. PDATA_PUSH(self->stack, obj, -1);
  4845. return 0;
  4846. }
  4847. static int
  4848. load_counted_binbytes(PickleState *state, UnpicklerObject *self, int nbytes)
  4849. {
  4850. PyObject *bytes;
  4851. Py_ssize_t size;
  4852. char *s;
  4853. if (_Unpickler_Read(self, state, &s, nbytes) < 0)
  4854. return -1;
  4855. size = calc_binsize(s, nbytes);
  4856. if (size < 0) {
  4857. PyErr_Format(PyExc_OverflowError,
  4858. "BINBYTES exceeds system's maximum size of %zd bytes",
  4859. PY_SSIZE_T_MAX);
  4860. return -1;
  4861. }
  4862. bytes = PyBytes_FromStringAndSize(NULL, size);
  4863. if (bytes == NULL)
  4864. return -1;
  4865. if (_Unpickler_ReadInto(state, self, PyBytes_AS_STRING(bytes), size) < 0) {
  4866. Py_DECREF(bytes);
  4867. return -1;
  4868. }
  4869. PDATA_PUSH(self->stack, bytes, -1);
  4870. return 0;
  4871. }
  4872. static int
  4873. load_counted_bytearray(PickleState *state, UnpicklerObject *self)
  4874. {
  4875. PyObject *bytearray;
  4876. Py_ssize_t size;
  4877. char *s;
  4878. if (_Unpickler_Read(self, state, &s, 8) < 0) {
  4879. return -1;
  4880. }
  4881. size = calc_binsize(s, 8);
  4882. if (size < 0) {
  4883. PyErr_Format(PyExc_OverflowError,
  4884. "BYTEARRAY8 exceeds system's maximum size of %zd bytes",
  4885. PY_SSIZE_T_MAX);
  4886. return -1;
  4887. }
  4888. bytearray = PyByteArray_FromStringAndSize(NULL, size);
  4889. if (bytearray == NULL) {
  4890. return -1;
  4891. }
  4892. char *str = PyByteArray_AS_STRING(bytearray);
  4893. if (_Unpickler_ReadInto(state, self, str, size) < 0) {
  4894. Py_DECREF(bytearray);
  4895. return -1;
  4896. }
  4897. PDATA_PUSH(self->stack, bytearray, -1);
  4898. return 0;
  4899. }
  4900. static int
  4901. load_next_buffer(PickleState *st, UnpicklerObject *self)
  4902. {
  4903. if (self->buffers == NULL) {
  4904. PyErr_SetString(st->UnpicklingError,
  4905. "pickle stream refers to out-of-band data "
  4906. "but no *buffers* argument was given");
  4907. return -1;
  4908. }
  4909. PyObject *buf = PyIter_Next(self->buffers);
  4910. if (buf == NULL) {
  4911. if (!PyErr_Occurred()) {
  4912. PyErr_SetString(st->UnpicklingError,
  4913. "not enough out-of-band buffers");
  4914. }
  4915. return -1;
  4916. }
  4917. PDATA_PUSH(self->stack, buf, -1);
  4918. return 0;
  4919. }
  4920. static int
  4921. load_readonly_buffer(PickleState *state, UnpicklerObject *self)
  4922. {
  4923. Py_ssize_t len = Py_SIZE(self->stack);
  4924. if (len <= self->stack->fence) {
  4925. return Pdata_stack_underflow(state, self->stack);
  4926. }
  4927. PyObject *obj = self->stack->data[len - 1];
  4928. PyObject *view = PyMemoryView_FromObject(obj);
  4929. if (view == NULL) {
  4930. return -1;
  4931. }
  4932. if (!PyMemoryView_GET_BUFFER(view)->readonly) {
  4933. /* Original object is writable */
  4934. PyMemoryView_GET_BUFFER(view)->readonly = 1;
  4935. self->stack->data[len - 1] = view;
  4936. Py_DECREF(obj);
  4937. }
  4938. else {
  4939. /* Original object is read-only, no need to replace it */
  4940. Py_DECREF(view);
  4941. }
  4942. return 0;
  4943. }
  4944. static int
  4945. load_unicode(PickleState *state, UnpicklerObject *self)
  4946. {
  4947. PyObject *str;
  4948. Py_ssize_t len;
  4949. char *s = NULL;
  4950. if ((len = _Unpickler_Readline(state, self, &s)) < 0)
  4951. return -1;
  4952. if (len < 1)
  4953. return bad_readline(state);
  4954. str = PyUnicode_DecodeRawUnicodeEscape(s, len - 1, NULL);
  4955. if (str == NULL)
  4956. return -1;
  4957. PDATA_PUSH(self->stack, str, -1);
  4958. return 0;
  4959. }
  4960. static int
  4961. load_counted_binunicode(PickleState *state, UnpicklerObject *self, int nbytes)
  4962. {
  4963. PyObject *str;
  4964. Py_ssize_t size;
  4965. char *s;
  4966. if (_Unpickler_Read(self, state, &s, nbytes) < 0)
  4967. return -1;
  4968. size = calc_binsize(s, nbytes);
  4969. if (size < 0) {
  4970. PyErr_Format(PyExc_OverflowError,
  4971. "BINUNICODE exceeds system's maximum size of %zd bytes",
  4972. PY_SSIZE_T_MAX);
  4973. return -1;
  4974. }
  4975. if (_Unpickler_Read(self, state, &s, size) < 0)
  4976. return -1;
  4977. str = PyUnicode_DecodeUTF8(s, size, "surrogatepass");
  4978. if (str == NULL)
  4979. return -1;
  4980. PDATA_PUSH(self->stack, str, -1);
  4981. return 0;
  4982. }
  4983. static int
  4984. load_counted_tuple(PickleState *state, UnpicklerObject *self, Py_ssize_t len)
  4985. {
  4986. PyObject *tuple;
  4987. if (Py_SIZE(self->stack) < len)
  4988. return Pdata_stack_underflow(state, self->stack);
  4989. tuple = Pdata_poptuple(state, self->stack, Py_SIZE(self->stack) - len);
  4990. if (tuple == NULL)
  4991. return -1;
  4992. PDATA_PUSH(self->stack, tuple, -1);
  4993. return 0;
  4994. }
  4995. static int
  4996. load_tuple(PickleState *state, UnpicklerObject *self)
  4997. {
  4998. Py_ssize_t i;
  4999. if ((i = marker(state, self)) < 0)
  5000. return -1;
  5001. return load_counted_tuple(state, self, Py_SIZE(self->stack) - i);
  5002. }
  5003. static int
  5004. load_empty_list(PickleState *state, UnpicklerObject *self)
  5005. {
  5006. PyObject *list;
  5007. if ((list = PyList_New(0)) == NULL)
  5008. return -1;
  5009. PDATA_PUSH(self->stack, list, -1);
  5010. return 0;
  5011. }
  5012. static int
  5013. load_empty_dict(PickleState *state, UnpicklerObject *self)
  5014. {
  5015. PyObject *dict;
  5016. if ((dict = PyDict_New()) == NULL)
  5017. return -1;
  5018. PDATA_PUSH(self->stack, dict, -1);
  5019. return 0;
  5020. }
  5021. static int
  5022. load_empty_set(PickleState *state, UnpicklerObject *self)
  5023. {
  5024. PyObject *set;
  5025. if ((set = PySet_New(NULL)) == NULL)
  5026. return -1;
  5027. PDATA_PUSH(self->stack, set, -1);
  5028. return 0;
  5029. }
  5030. static int
  5031. load_list(PickleState *state, UnpicklerObject *self)
  5032. {
  5033. PyObject *list;
  5034. Py_ssize_t i;
  5035. if ((i = marker(state, self)) < 0)
  5036. return -1;
  5037. list = Pdata_poplist(self->stack, i);
  5038. if (list == NULL)
  5039. return -1;
  5040. PDATA_PUSH(self->stack, list, -1);
  5041. return 0;
  5042. }
  5043. static int
  5044. load_dict(PickleState *st, UnpicklerObject *self)
  5045. {
  5046. PyObject *dict, *key, *value;
  5047. Py_ssize_t i, j, k;
  5048. if ((i = marker(st, self)) < 0)
  5049. return -1;
  5050. j = Py_SIZE(self->stack);
  5051. if ((dict = PyDict_New()) == NULL)
  5052. return -1;
  5053. if ((j - i) % 2 != 0) {
  5054. PyErr_SetString(st->UnpicklingError, "odd number of items for DICT");
  5055. Py_DECREF(dict);
  5056. return -1;
  5057. }
  5058. for (k = i + 1; k < j; k += 2) {
  5059. key = self->stack->data[k - 1];
  5060. value = self->stack->data[k];
  5061. if (PyDict_SetItem(dict, key, value) < 0) {
  5062. Py_DECREF(dict);
  5063. return -1;
  5064. }
  5065. }
  5066. Pdata_clear(self->stack, i);
  5067. PDATA_PUSH(self->stack, dict, -1);
  5068. return 0;
  5069. }
  5070. static int
  5071. load_frozenset(PickleState *state, UnpicklerObject *self)
  5072. {
  5073. PyObject *items;
  5074. PyObject *frozenset;
  5075. Py_ssize_t i;
  5076. if ((i = marker(state, self)) < 0)
  5077. return -1;
  5078. items = Pdata_poptuple(state, self->stack, i);
  5079. if (items == NULL)
  5080. return -1;
  5081. frozenset = PyFrozenSet_New(items);
  5082. Py_DECREF(items);
  5083. if (frozenset == NULL)
  5084. return -1;
  5085. PDATA_PUSH(self->stack, frozenset, -1);
  5086. return 0;
  5087. }
  5088. static PyObject *
  5089. instantiate(PyObject *cls, PyObject *args)
  5090. {
  5091. /* Caller must assure args are a tuple. Normally, args come from
  5092. Pdata_poptuple which packs objects from the top of the stack
  5093. into a newly created tuple. */
  5094. assert(PyTuple_Check(args));
  5095. if (!PyTuple_GET_SIZE(args) && PyType_Check(cls)) {
  5096. PyObject *func;
  5097. if (_PyObject_LookupAttr(cls, &_Py_ID(__getinitargs__), &func) < 0) {
  5098. return NULL;
  5099. }
  5100. if (func == NULL) {
  5101. return PyObject_CallMethodOneArg(cls, &_Py_ID(__new__), cls);
  5102. }
  5103. Py_DECREF(func);
  5104. }
  5105. return PyObject_CallObject(cls, args);
  5106. }
  5107. static int
  5108. load_obj(PickleState *state, UnpicklerObject *self)
  5109. {
  5110. PyObject *cls, *args, *obj = NULL;
  5111. Py_ssize_t i;
  5112. if ((i = marker(state, self)) < 0)
  5113. return -1;
  5114. if (Py_SIZE(self->stack) - i < 1)
  5115. return Pdata_stack_underflow(state, self->stack);
  5116. args = Pdata_poptuple(state, self->stack, i + 1);
  5117. if (args == NULL)
  5118. return -1;
  5119. PDATA_POP(state, self->stack, cls);
  5120. if (cls) {
  5121. obj = instantiate(cls, args);
  5122. Py_DECREF(cls);
  5123. }
  5124. Py_DECREF(args);
  5125. if (obj == NULL)
  5126. return -1;
  5127. PDATA_PUSH(self->stack, obj, -1);
  5128. return 0;
  5129. }
  5130. static int
  5131. load_inst(PickleState *state, UnpicklerObject *self)
  5132. {
  5133. PyObject *cls = NULL;
  5134. PyObject *args = NULL;
  5135. PyObject *obj = NULL;
  5136. PyObject *module_name;
  5137. PyObject *class_name;
  5138. Py_ssize_t len;
  5139. Py_ssize_t i;
  5140. char *s;
  5141. if ((i = marker(state, self)) < 0)
  5142. return -1;
  5143. if ((len = _Unpickler_Readline(state, self, &s)) < 0)
  5144. return -1;
  5145. if (len < 2)
  5146. return bad_readline(state);
  5147. /* Here it is safe to use PyUnicode_DecodeASCII(), even though non-ASCII
  5148. identifiers are permitted in Python 3.0, since the INST opcode is only
  5149. supported by older protocols on Python 2.x. */
  5150. module_name = PyUnicode_DecodeASCII(s, len - 1, "strict");
  5151. if (module_name == NULL)
  5152. return -1;
  5153. if ((len = _Unpickler_Readline(state, self, &s)) >= 0) {
  5154. if (len < 2) {
  5155. Py_DECREF(module_name);
  5156. return bad_readline(state);
  5157. }
  5158. class_name = PyUnicode_DecodeASCII(s, len - 1, "strict");
  5159. if (class_name != NULL) {
  5160. cls = find_class(self, module_name, class_name);
  5161. Py_DECREF(class_name);
  5162. }
  5163. }
  5164. Py_DECREF(module_name);
  5165. if (cls == NULL)
  5166. return -1;
  5167. if ((args = Pdata_poptuple(state, self->stack, i)) != NULL) {
  5168. obj = instantiate(cls, args);
  5169. Py_DECREF(args);
  5170. }
  5171. Py_DECREF(cls);
  5172. if (obj == NULL)
  5173. return -1;
  5174. PDATA_PUSH(self->stack, obj, -1);
  5175. return 0;
  5176. }
  5177. static void
  5178. newobj_unpickling_error(PickleState *st, const char *msg, int use_kwargs,
  5179. PyObject *arg)
  5180. {
  5181. PyErr_Format(st->UnpicklingError, msg,
  5182. use_kwargs ? "NEWOBJ_EX" : "NEWOBJ",
  5183. Py_TYPE(arg)->tp_name);
  5184. }
  5185. static int
  5186. load_newobj(PickleState *state, UnpicklerObject *self, int use_kwargs)
  5187. {
  5188. PyObject *cls, *args, *kwargs = NULL;
  5189. PyObject *obj;
  5190. /* Stack is ... cls args [kwargs], and we want to call
  5191. * cls.__new__(cls, *args, **kwargs).
  5192. */
  5193. if (use_kwargs) {
  5194. PDATA_POP(state, self->stack, kwargs);
  5195. if (kwargs == NULL) {
  5196. return -1;
  5197. }
  5198. }
  5199. PDATA_POP(state, self->stack, args);
  5200. if (args == NULL) {
  5201. Py_XDECREF(kwargs);
  5202. return -1;
  5203. }
  5204. PDATA_POP(state, self->stack, cls);
  5205. if (cls == NULL) {
  5206. Py_XDECREF(kwargs);
  5207. Py_DECREF(args);
  5208. return -1;
  5209. }
  5210. if (!PyType_Check(cls)) {
  5211. newobj_unpickling_error(state,
  5212. "%s class argument must be a type, not %.200s",
  5213. use_kwargs, cls);
  5214. goto error;
  5215. }
  5216. if (((PyTypeObject *)cls)->tp_new == NULL) {
  5217. newobj_unpickling_error(state,
  5218. "%s class argument '%.200s' doesn't have __new__",
  5219. use_kwargs, cls);
  5220. goto error;
  5221. }
  5222. if (!PyTuple_Check(args)) {
  5223. newobj_unpickling_error(state,
  5224. "%s args argument must be a tuple, not %.200s",
  5225. use_kwargs, args);
  5226. goto error;
  5227. }
  5228. if (use_kwargs && !PyDict_Check(kwargs)) {
  5229. newobj_unpickling_error(state,
  5230. "%s kwargs argument must be a dict, not %.200s",
  5231. use_kwargs, kwargs);
  5232. goto error;
  5233. }
  5234. obj = ((PyTypeObject *)cls)->tp_new((PyTypeObject *)cls, args, kwargs);
  5235. if (obj == NULL) {
  5236. goto error;
  5237. }
  5238. Py_XDECREF(kwargs);
  5239. Py_DECREF(args);
  5240. Py_DECREF(cls);
  5241. PDATA_PUSH(self->stack, obj, -1);
  5242. return 0;
  5243. error:
  5244. Py_XDECREF(kwargs);
  5245. Py_DECREF(args);
  5246. Py_DECREF(cls);
  5247. return -1;
  5248. }
  5249. static int
  5250. load_global(PickleState *state, UnpicklerObject *self)
  5251. {
  5252. PyObject *global = NULL;
  5253. PyObject *module_name;
  5254. PyObject *global_name;
  5255. Py_ssize_t len;
  5256. char *s;
  5257. if ((len = _Unpickler_Readline(state, self, &s)) < 0)
  5258. return -1;
  5259. if (len < 2)
  5260. return bad_readline(state);
  5261. module_name = PyUnicode_DecodeUTF8(s, len - 1, "strict");
  5262. if (!module_name)
  5263. return -1;
  5264. if ((len = _Unpickler_Readline(state, self, &s)) >= 0) {
  5265. if (len < 2) {
  5266. Py_DECREF(module_name);
  5267. return bad_readline(state);
  5268. }
  5269. global_name = PyUnicode_DecodeUTF8(s, len - 1, "strict");
  5270. if (global_name) {
  5271. global = find_class(self, module_name, global_name);
  5272. Py_DECREF(global_name);
  5273. }
  5274. }
  5275. Py_DECREF(module_name);
  5276. if (global == NULL)
  5277. return -1;
  5278. PDATA_PUSH(self->stack, global, -1);
  5279. return 0;
  5280. }
  5281. static int
  5282. load_stack_global(PickleState *st, UnpicklerObject *self)
  5283. {
  5284. PyObject *global;
  5285. PyObject *module_name;
  5286. PyObject *global_name;
  5287. PDATA_POP(st, self->stack, global_name);
  5288. if (global_name == NULL) {
  5289. return -1;
  5290. }
  5291. PDATA_POP(st, self->stack, module_name);
  5292. if (module_name == NULL) {
  5293. Py_DECREF(global_name);
  5294. return -1;
  5295. }
  5296. if (!PyUnicode_CheckExact(module_name) ||
  5297. !PyUnicode_CheckExact(global_name))
  5298. {
  5299. PyErr_SetString(st->UnpicklingError, "STACK_GLOBAL requires str");
  5300. Py_DECREF(global_name);
  5301. Py_DECREF(module_name);
  5302. return -1;
  5303. }
  5304. global = find_class(self, module_name, global_name);
  5305. Py_DECREF(global_name);
  5306. Py_DECREF(module_name);
  5307. if (global == NULL)
  5308. return -1;
  5309. PDATA_PUSH(self->stack, global, -1);
  5310. return 0;
  5311. }
  5312. static int
  5313. load_persid(PickleState *st, UnpicklerObject *self)
  5314. {
  5315. PyObject *pid, *obj;
  5316. Py_ssize_t len;
  5317. char *s;
  5318. if (self->pers_func) {
  5319. if ((len = _Unpickler_Readline(st, self, &s)) < 0)
  5320. return -1;
  5321. if (len < 1)
  5322. return bad_readline(st);
  5323. pid = PyUnicode_DecodeASCII(s, len - 1, "strict");
  5324. if (pid == NULL) {
  5325. if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
  5326. PyErr_SetString(st->UnpicklingError,
  5327. "persistent IDs in protocol 0 must be "
  5328. "ASCII strings");
  5329. }
  5330. return -1;
  5331. }
  5332. obj = call_method(self->pers_func, self->pers_func_self, pid);
  5333. Py_DECREF(pid);
  5334. if (obj == NULL)
  5335. return -1;
  5336. PDATA_PUSH(self->stack, obj, -1);
  5337. return 0;
  5338. }
  5339. else {
  5340. PyErr_SetString(st->UnpicklingError,
  5341. "A load persistent id instruction was encountered, "
  5342. "but no persistent_load function was specified.");
  5343. return -1;
  5344. }
  5345. }
  5346. static int
  5347. load_binpersid(PickleState *st, UnpicklerObject *self)
  5348. {
  5349. PyObject *pid, *obj;
  5350. if (self->pers_func) {
  5351. PDATA_POP(st, self->stack, pid);
  5352. if (pid == NULL)
  5353. return -1;
  5354. obj = call_method(self->pers_func, self->pers_func_self, pid);
  5355. Py_DECREF(pid);
  5356. if (obj == NULL)
  5357. return -1;
  5358. PDATA_PUSH(self->stack, obj, -1);
  5359. return 0;
  5360. }
  5361. else {
  5362. PyErr_SetString(st->UnpicklingError,
  5363. "A load persistent id instruction was encountered, "
  5364. "but no persistent_load function was specified.");
  5365. return -1;
  5366. }
  5367. }
  5368. static int
  5369. load_pop(PickleState *state, UnpicklerObject *self)
  5370. {
  5371. Py_ssize_t len = Py_SIZE(self->stack);
  5372. /* Note that we split the (pickle.py) stack into two stacks,
  5373. * an object stack and a mark stack. We have to be clever and
  5374. * pop the right one. We do this by looking at the top of the
  5375. * mark stack first, and only signalling a stack underflow if
  5376. * the object stack is empty and the mark stack doesn't match
  5377. * our expectations.
  5378. */
  5379. if (self->num_marks > 0 && self->marks[self->num_marks - 1] == len) {
  5380. self->num_marks--;
  5381. self->stack->mark_set = self->num_marks != 0;
  5382. self->stack->fence = self->num_marks ?
  5383. self->marks[self->num_marks - 1] : 0;
  5384. } else if (len <= self->stack->fence)
  5385. return Pdata_stack_underflow(state, self->stack);
  5386. else {
  5387. len--;
  5388. Py_DECREF(self->stack->data[len]);
  5389. Py_SET_SIZE(self->stack, len);
  5390. }
  5391. return 0;
  5392. }
  5393. static int
  5394. load_pop_mark(PickleState *state, UnpicklerObject *self)
  5395. {
  5396. Py_ssize_t i;
  5397. if ((i = marker(state, self)) < 0)
  5398. return -1;
  5399. Pdata_clear(self->stack, i);
  5400. return 0;
  5401. }
  5402. static int
  5403. load_dup(PickleState *state, UnpicklerObject *self)
  5404. {
  5405. PyObject *last;
  5406. Py_ssize_t len = Py_SIZE(self->stack);
  5407. if (len <= self->stack->fence)
  5408. return Pdata_stack_underflow(state, self->stack);
  5409. last = self->stack->data[len - 1];
  5410. PDATA_APPEND(self->stack, last, -1);
  5411. return 0;
  5412. }
  5413. static int
  5414. load_get(PickleState *st, UnpicklerObject *self)
  5415. {
  5416. PyObject *key, *value;
  5417. Py_ssize_t idx;
  5418. Py_ssize_t len;
  5419. char *s;
  5420. if ((len = _Unpickler_Readline(st, self, &s)) < 0)
  5421. return -1;
  5422. if (len < 2)
  5423. return bad_readline(st);
  5424. key = PyLong_FromString(s, NULL, 10);
  5425. if (key == NULL)
  5426. return -1;
  5427. idx = PyLong_AsSsize_t(key);
  5428. if (idx == -1 && PyErr_Occurred()) {
  5429. Py_DECREF(key);
  5430. return -1;
  5431. }
  5432. value = _Unpickler_MemoGet(self, idx);
  5433. if (value == NULL) {
  5434. if (!PyErr_Occurred()) {
  5435. PyErr_Format(st->UnpicklingError, "Memo value not found at index %ld", idx);
  5436. }
  5437. Py_DECREF(key);
  5438. return -1;
  5439. }
  5440. Py_DECREF(key);
  5441. PDATA_APPEND(self->stack, value, -1);
  5442. return 0;
  5443. }
  5444. static int
  5445. load_binget(PickleState *st, UnpicklerObject *self)
  5446. {
  5447. PyObject *value;
  5448. Py_ssize_t idx;
  5449. char *s;
  5450. if (_Unpickler_Read(self, st, &s, 1) < 0)
  5451. return -1;
  5452. idx = Py_CHARMASK(s[0]);
  5453. value = _Unpickler_MemoGet(self, idx);
  5454. if (value == NULL) {
  5455. PyObject *key = PyLong_FromSsize_t(idx);
  5456. if (key != NULL) {
  5457. PyErr_Format(st->UnpicklingError, "Memo value not found at index %ld", idx);
  5458. Py_DECREF(key);
  5459. }
  5460. return -1;
  5461. }
  5462. PDATA_APPEND(self->stack, value, -1);
  5463. return 0;
  5464. }
  5465. static int
  5466. load_long_binget(PickleState *st, UnpicklerObject *self)
  5467. {
  5468. PyObject *value;
  5469. Py_ssize_t idx;
  5470. char *s;
  5471. if (_Unpickler_Read(self, st, &s, 4) < 0)
  5472. return -1;
  5473. idx = calc_binsize(s, 4);
  5474. value = _Unpickler_MemoGet(self, idx);
  5475. if (value == NULL) {
  5476. PyObject *key = PyLong_FromSsize_t(idx);
  5477. if (key != NULL) {
  5478. PyErr_Format(st->UnpicklingError, "Memo value not found at index %ld", idx);
  5479. Py_DECREF(key);
  5480. }
  5481. return -1;
  5482. }
  5483. PDATA_APPEND(self->stack, value, -1);
  5484. return 0;
  5485. }
  5486. /* Push an object from the extension registry (EXT[124]). nbytes is
  5487. * the number of bytes following the opcode, holding the index (code) value.
  5488. */
  5489. static int
  5490. load_extension(PickleState *st, UnpicklerObject *self, int nbytes)
  5491. {
  5492. char *codebytes; /* the nbytes bytes after the opcode */
  5493. long code; /* calc_binint returns long */
  5494. PyObject *py_code; /* code as a Python int */
  5495. PyObject *obj; /* the object to push */
  5496. PyObject *pair; /* (module_name, class_name) */
  5497. PyObject *module_name, *class_name;
  5498. assert(nbytes == 1 || nbytes == 2 || nbytes == 4);
  5499. if (_Unpickler_Read(self, st, &codebytes, nbytes) < 0)
  5500. return -1;
  5501. code = calc_binint(codebytes, nbytes);
  5502. if (code <= 0) { /* note that 0 is forbidden */
  5503. /* Corrupt or hostile pickle. */
  5504. PyErr_SetString(st->UnpicklingError, "EXT specifies code <= 0");
  5505. return -1;
  5506. }
  5507. /* Look for the code in the cache. */
  5508. py_code = PyLong_FromLong(code);
  5509. if (py_code == NULL)
  5510. return -1;
  5511. obj = PyDict_GetItemWithError(st->extension_cache, py_code);
  5512. if (obj != NULL) {
  5513. /* Bingo. */
  5514. Py_DECREF(py_code);
  5515. PDATA_APPEND(self->stack, obj, -1);
  5516. return 0;
  5517. }
  5518. if (PyErr_Occurred()) {
  5519. Py_DECREF(py_code);
  5520. return -1;
  5521. }
  5522. /* Look up the (module_name, class_name) pair. */
  5523. pair = PyDict_GetItemWithError(st->inverted_registry, py_code);
  5524. if (pair == NULL) {
  5525. Py_DECREF(py_code);
  5526. if (!PyErr_Occurred()) {
  5527. PyErr_Format(PyExc_ValueError, "unregistered extension "
  5528. "code %ld", code);
  5529. }
  5530. return -1;
  5531. }
  5532. /* Since the extension registry is manipulable via Python code,
  5533. * confirm that pair is really a 2-tuple of strings.
  5534. */
  5535. if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2) {
  5536. goto error;
  5537. }
  5538. module_name = PyTuple_GET_ITEM(pair, 0);
  5539. if (!PyUnicode_Check(module_name)) {
  5540. goto error;
  5541. }
  5542. class_name = PyTuple_GET_ITEM(pair, 1);
  5543. if (!PyUnicode_Check(class_name)) {
  5544. goto error;
  5545. }
  5546. /* Load the object. */
  5547. obj = find_class(self, module_name, class_name);
  5548. if (obj == NULL) {
  5549. Py_DECREF(py_code);
  5550. return -1;
  5551. }
  5552. /* Cache code -> obj. */
  5553. code = PyDict_SetItem(st->extension_cache, py_code, obj);
  5554. Py_DECREF(py_code);
  5555. if (code < 0) {
  5556. Py_DECREF(obj);
  5557. return -1;
  5558. }
  5559. PDATA_PUSH(self->stack, obj, -1);
  5560. return 0;
  5561. error:
  5562. Py_DECREF(py_code);
  5563. PyErr_Format(PyExc_ValueError, "_inverted_registry[%ld] "
  5564. "isn't a 2-tuple of strings", code);
  5565. return -1;
  5566. }
  5567. static int
  5568. load_put(PickleState *state, UnpicklerObject *self)
  5569. {
  5570. PyObject *key, *value;
  5571. Py_ssize_t idx;
  5572. Py_ssize_t len;
  5573. char *s = NULL;
  5574. if ((len = _Unpickler_Readline(state, self, &s)) < 0)
  5575. return -1;
  5576. if (len < 2)
  5577. return bad_readline(state);
  5578. if (Py_SIZE(self->stack) <= self->stack->fence)
  5579. return Pdata_stack_underflow(state, self->stack);
  5580. value = self->stack->data[Py_SIZE(self->stack) - 1];
  5581. key = PyLong_FromString(s, NULL, 10);
  5582. if (key == NULL)
  5583. return -1;
  5584. idx = PyLong_AsSsize_t(key);
  5585. Py_DECREF(key);
  5586. if (idx < 0) {
  5587. if (!PyErr_Occurred())
  5588. PyErr_SetString(PyExc_ValueError,
  5589. "negative PUT argument");
  5590. return -1;
  5591. }
  5592. return _Unpickler_MemoPut(self, idx, value);
  5593. }
  5594. static int
  5595. load_binput(PickleState *state, UnpicklerObject *self)
  5596. {
  5597. PyObject *value;
  5598. Py_ssize_t idx;
  5599. char *s;
  5600. if (_Unpickler_Read(self, state, &s, 1) < 0)
  5601. return -1;
  5602. if (Py_SIZE(self->stack) <= self->stack->fence)
  5603. return Pdata_stack_underflow(state, self->stack);
  5604. value = self->stack->data[Py_SIZE(self->stack) - 1];
  5605. idx = Py_CHARMASK(s[0]);
  5606. return _Unpickler_MemoPut(self, idx, value);
  5607. }
  5608. static int
  5609. load_long_binput(PickleState *state, UnpicklerObject *self)
  5610. {
  5611. PyObject *value;
  5612. Py_ssize_t idx;
  5613. char *s;
  5614. if (_Unpickler_Read(self, state, &s, 4) < 0)
  5615. return -1;
  5616. if (Py_SIZE(self->stack) <= self->stack->fence)
  5617. return Pdata_stack_underflow(state, self->stack);
  5618. value = self->stack->data[Py_SIZE(self->stack) - 1];
  5619. idx = calc_binsize(s, 4);
  5620. if (idx < 0) {
  5621. PyErr_SetString(PyExc_ValueError,
  5622. "negative LONG_BINPUT argument");
  5623. return -1;
  5624. }
  5625. return _Unpickler_MemoPut(self, idx, value);
  5626. }
  5627. static int
  5628. load_memoize(PickleState *state, UnpicklerObject *self)
  5629. {
  5630. PyObject *value;
  5631. if (Py_SIZE(self->stack) <= self->stack->fence)
  5632. return Pdata_stack_underflow(state, self->stack);
  5633. value = self->stack->data[Py_SIZE(self->stack) - 1];
  5634. return _Unpickler_MemoPut(self, self->memo_len, value);
  5635. }
  5636. static int
  5637. do_append(PickleState *state, UnpicklerObject *self, Py_ssize_t x)
  5638. {
  5639. PyObject *value;
  5640. PyObject *slice;
  5641. PyObject *list;
  5642. PyObject *result;
  5643. Py_ssize_t len, i;
  5644. len = Py_SIZE(self->stack);
  5645. if (x > len || x <= self->stack->fence)
  5646. return Pdata_stack_underflow(state, self->stack);
  5647. if (len == x) /* nothing to do */
  5648. return 0;
  5649. list = self->stack->data[x - 1];
  5650. if (PyList_CheckExact(list)) {
  5651. Py_ssize_t list_len;
  5652. int ret;
  5653. slice = Pdata_poplist(self->stack, x);
  5654. if (!slice)
  5655. return -1;
  5656. list_len = PyList_GET_SIZE(list);
  5657. ret = PyList_SetSlice(list, list_len, list_len, slice);
  5658. Py_DECREF(slice);
  5659. return ret;
  5660. }
  5661. else {
  5662. PyObject *extend_func;
  5663. if (_PyObject_LookupAttr(list, &_Py_ID(extend), &extend_func) < 0) {
  5664. return -1;
  5665. }
  5666. if (extend_func != NULL) {
  5667. slice = Pdata_poplist(self->stack, x);
  5668. if (!slice) {
  5669. Py_DECREF(extend_func);
  5670. return -1;
  5671. }
  5672. result = _Pickle_FastCall(extend_func, slice);
  5673. Py_DECREF(extend_func);
  5674. if (result == NULL)
  5675. return -1;
  5676. Py_DECREF(result);
  5677. }
  5678. else {
  5679. PyObject *append_func;
  5680. /* Even if the PEP 307 requires extend() and append() methods,
  5681. fall back on append() if the object has no extend() method
  5682. for backward compatibility. */
  5683. append_func = PyObject_GetAttr(list, &_Py_ID(append));
  5684. if (append_func == NULL)
  5685. return -1;
  5686. for (i = x; i < len; i++) {
  5687. value = self->stack->data[i];
  5688. result = _Pickle_FastCall(append_func, value);
  5689. if (result == NULL) {
  5690. Pdata_clear(self->stack, i + 1);
  5691. Py_SET_SIZE(self->stack, x);
  5692. Py_DECREF(append_func);
  5693. return -1;
  5694. }
  5695. Py_DECREF(result);
  5696. }
  5697. Py_SET_SIZE(self->stack, x);
  5698. Py_DECREF(append_func);
  5699. }
  5700. }
  5701. return 0;
  5702. }
  5703. static int
  5704. load_append(PickleState *state, UnpicklerObject *self)
  5705. {
  5706. if (Py_SIZE(self->stack) - 1 <= self->stack->fence)
  5707. return Pdata_stack_underflow(state, self->stack);
  5708. return do_append(state, self, Py_SIZE(self->stack) - 1);
  5709. }
  5710. static int
  5711. load_appends(PickleState *state, UnpicklerObject *self)
  5712. {
  5713. Py_ssize_t i = marker(state, self);
  5714. if (i < 0)
  5715. return -1;
  5716. return do_append(state, self, i);
  5717. }
  5718. static int
  5719. do_setitems(PickleState *st, UnpicklerObject *self, Py_ssize_t x)
  5720. {
  5721. PyObject *value, *key;
  5722. PyObject *dict;
  5723. Py_ssize_t len, i;
  5724. int status = 0;
  5725. len = Py_SIZE(self->stack);
  5726. if (x > len || x <= self->stack->fence)
  5727. return Pdata_stack_underflow(st, self->stack);
  5728. if (len == x) /* nothing to do */
  5729. return 0;
  5730. if ((len - x) % 2 != 0) {
  5731. /* Corrupt or hostile pickle -- we never write one like this. */
  5732. PyErr_SetString(st->UnpicklingError,
  5733. "odd number of items for SETITEMS");
  5734. return -1;
  5735. }
  5736. /* Here, dict does not actually need to be a PyDict; it could be anything
  5737. that supports the __setitem__ attribute. */
  5738. dict = self->stack->data[x - 1];
  5739. for (i = x + 1; i < len; i += 2) {
  5740. key = self->stack->data[i - 1];
  5741. value = self->stack->data[i];
  5742. if (PyObject_SetItem(dict, key, value) < 0) {
  5743. status = -1;
  5744. break;
  5745. }
  5746. }
  5747. Pdata_clear(self->stack, x);
  5748. return status;
  5749. }
  5750. static int
  5751. load_setitem(PickleState *state, UnpicklerObject *self)
  5752. {
  5753. return do_setitems(state, self, Py_SIZE(self->stack) - 2);
  5754. }
  5755. static int
  5756. load_setitems(PickleState *state, UnpicklerObject *self)
  5757. {
  5758. Py_ssize_t i = marker(state, self);
  5759. if (i < 0)
  5760. return -1;
  5761. return do_setitems(state, self, i);
  5762. }
  5763. static int
  5764. load_additems(PickleState *state, UnpicklerObject *self)
  5765. {
  5766. PyObject *set;
  5767. Py_ssize_t mark, len, i;
  5768. mark = marker(state, self);
  5769. if (mark < 0)
  5770. return -1;
  5771. len = Py_SIZE(self->stack);
  5772. if (mark > len || mark <= self->stack->fence)
  5773. return Pdata_stack_underflow(state, self->stack);
  5774. if (len == mark) /* nothing to do */
  5775. return 0;
  5776. set = self->stack->data[mark - 1];
  5777. if (PySet_Check(set)) {
  5778. PyObject *items;
  5779. int status;
  5780. items = Pdata_poptuple(state, self->stack, mark);
  5781. if (items == NULL)
  5782. return -1;
  5783. status = _PySet_Update(set, items);
  5784. Py_DECREF(items);
  5785. return status;
  5786. }
  5787. else {
  5788. PyObject *add_func;
  5789. add_func = PyObject_GetAttr(set, &_Py_ID(add));
  5790. if (add_func == NULL)
  5791. return -1;
  5792. for (i = mark; i < len; i++) {
  5793. PyObject *result;
  5794. PyObject *item;
  5795. item = self->stack->data[i];
  5796. result = _Pickle_FastCall(add_func, item);
  5797. if (result == NULL) {
  5798. Pdata_clear(self->stack, i + 1);
  5799. Py_SET_SIZE(self->stack, mark);
  5800. Py_DECREF(add_func);
  5801. return -1;
  5802. }
  5803. Py_DECREF(result);
  5804. }
  5805. Py_SET_SIZE(self->stack, mark);
  5806. Py_DECREF(add_func);
  5807. }
  5808. return 0;
  5809. }
  5810. static int
  5811. load_build(PickleState *st, UnpicklerObject *self)
  5812. {
  5813. PyObject *inst, *slotstate;
  5814. PyObject *setstate;
  5815. int status = 0;
  5816. /* Stack is ... instance, state. We want to leave instance at
  5817. * the stack top, possibly mutated via instance.__setstate__(state).
  5818. */
  5819. if (Py_SIZE(self->stack) - 2 < self->stack->fence)
  5820. return Pdata_stack_underflow(st, self->stack);
  5821. PyObject *state;
  5822. PDATA_POP(st, self->stack, state);
  5823. if (state == NULL)
  5824. return -1;
  5825. inst = self->stack->data[Py_SIZE(self->stack) - 1];
  5826. if (_PyObject_LookupAttr(inst, &_Py_ID(__setstate__), &setstate) < 0) {
  5827. Py_DECREF(state);
  5828. return -1;
  5829. }
  5830. if (setstate != NULL) {
  5831. PyObject *result;
  5832. /* The explicit __setstate__ is responsible for everything. */
  5833. result = _Pickle_FastCall(setstate, state);
  5834. Py_DECREF(setstate);
  5835. if (result == NULL)
  5836. return -1;
  5837. Py_DECREF(result);
  5838. return 0;
  5839. }
  5840. /* A default __setstate__. First see whether state embeds a
  5841. * slot state dict too (a proto 2 addition).
  5842. */
  5843. if (PyTuple_Check(state) && PyTuple_GET_SIZE(state) == 2) {
  5844. PyObject *tmp = state;
  5845. state = PyTuple_GET_ITEM(tmp, 0);
  5846. slotstate = PyTuple_GET_ITEM(tmp, 1);
  5847. Py_INCREF(state);
  5848. Py_INCREF(slotstate);
  5849. Py_DECREF(tmp);
  5850. }
  5851. else
  5852. slotstate = NULL;
  5853. /* Set inst.__dict__ from the state dict (if any). */
  5854. if (state != Py_None) {
  5855. PyObject *dict;
  5856. PyObject *d_key, *d_value;
  5857. Py_ssize_t i;
  5858. if (!PyDict_Check(state)) {
  5859. PyErr_SetString(st->UnpicklingError, "state is not a dictionary");
  5860. goto error;
  5861. }
  5862. dict = PyObject_GetAttr(inst, &_Py_ID(__dict__));
  5863. if (dict == NULL)
  5864. goto error;
  5865. i = 0;
  5866. while (PyDict_Next(state, &i, &d_key, &d_value)) {
  5867. /* normally the keys for instance attributes are
  5868. interned. we should try to do that here. */
  5869. Py_INCREF(d_key);
  5870. if (PyUnicode_CheckExact(d_key)) {
  5871. PyInterpreterState *interp = _PyInterpreterState_GET();
  5872. _PyUnicode_InternMortal(interp, &d_key);
  5873. }
  5874. if (PyObject_SetItem(dict, d_key, d_value) < 0) {
  5875. Py_DECREF(d_key);
  5876. Py_DECREF(dict);
  5877. goto error;
  5878. }
  5879. Py_DECREF(d_key);
  5880. }
  5881. Py_DECREF(dict);
  5882. }
  5883. /* Also set instance attributes from the slotstate dict (if any). */
  5884. if (slotstate != NULL) {
  5885. PyObject *d_key, *d_value;
  5886. Py_ssize_t i;
  5887. if (!PyDict_Check(slotstate)) {
  5888. PyErr_SetString(st->UnpicklingError,
  5889. "slot state is not a dictionary");
  5890. goto error;
  5891. }
  5892. i = 0;
  5893. while (PyDict_Next(slotstate, &i, &d_key, &d_value)) {
  5894. if (PyObject_SetAttr(inst, d_key, d_value) < 0)
  5895. goto error;
  5896. }
  5897. }
  5898. if (0) {
  5899. error:
  5900. status = -1;
  5901. }
  5902. Py_DECREF(state);
  5903. Py_XDECREF(slotstate);
  5904. return status;
  5905. }
  5906. static int
  5907. load_mark(PickleState *state, UnpicklerObject *self)
  5908. {
  5909. /* Note that we split the (pickle.py) stack into two stacks, an
  5910. * object stack and a mark stack. Here we push a mark onto the
  5911. * mark stack.
  5912. */
  5913. if (self->num_marks >= self->marks_size) {
  5914. size_t alloc = ((size_t)self->num_marks << 1) + 20;
  5915. Py_ssize_t *marks_new = self->marks;
  5916. PyMem_RESIZE(marks_new, Py_ssize_t, alloc);
  5917. if (marks_new == NULL) {
  5918. PyErr_NoMemory();
  5919. return -1;
  5920. }
  5921. self->marks = marks_new;
  5922. self->marks_size = (Py_ssize_t)alloc;
  5923. }
  5924. self->stack->mark_set = 1;
  5925. self->marks[self->num_marks++] = self->stack->fence = Py_SIZE(self->stack);
  5926. return 0;
  5927. }
  5928. static int
  5929. load_reduce(PickleState *state, UnpicklerObject *self)
  5930. {
  5931. PyObject *callable = NULL;
  5932. PyObject *argtup = NULL;
  5933. PyObject *obj = NULL;
  5934. PDATA_POP(state, self->stack, argtup);
  5935. if (argtup == NULL)
  5936. return -1;
  5937. PDATA_POP(state, self->stack, callable);
  5938. if (callable) {
  5939. obj = PyObject_CallObject(callable, argtup);
  5940. Py_DECREF(callable);
  5941. }
  5942. Py_DECREF(argtup);
  5943. if (obj == NULL)
  5944. return -1;
  5945. PDATA_PUSH(self->stack, obj, -1);
  5946. return 0;
  5947. }
  5948. /* Just raises an error if we don't know the protocol specified. PROTO
  5949. * is the first opcode for protocols >= 2.
  5950. */
  5951. static int
  5952. load_proto(PickleState *state, UnpicklerObject *self)
  5953. {
  5954. char *s;
  5955. int i;
  5956. if (_Unpickler_Read(self, state, &s, 1) < 0)
  5957. return -1;
  5958. i = (unsigned char)s[0];
  5959. if (i <= HIGHEST_PROTOCOL) {
  5960. self->proto = i;
  5961. return 0;
  5962. }
  5963. PyErr_Format(PyExc_ValueError, "unsupported pickle protocol: %d", i);
  5964. return -1;
  5965. }
  5966. static int
  5967. load_frame(PickleState *state, UnpicklerObject *self)
  5968. {
  5969. char *s;
  5970. Py_ssize_t frame_len;
  5971. if (_Unpickler_Read(self, state, &s, 8) < 0)
  5972. return -1;
  5973. frame_len = calc_binsize(s, 8);
  5974. if (frame_len < 0) {
  5975. PyErr_Format(PyExc_OverflowError,
  5976. "FRAME length exceeds system's maximum of %zd bytes",
  5977. PY_SSIZE_T_MAX);
  5978. return -1;
  5979. }
  5980. if (_Unpickler_Read(self, state, &s, frame_len) < 0)
  5981. return -1;
  5982. /* Rewind to start of frame */
  5983. self->next_read_idx -= frame_len;
  5984. return 0;
  5985. }
  5986. static PyObject *
  5987. load(PickleState *st, UnpicklerObject *self)
  5988. {
  5989. PyObject *value = NULL;
  5990. char *s = NULL;
  5991. self->num_marks = 0;
  5992. self->stack->mark_set = 0;
  5993. self->stack->fence = 0;
  5994. self->proto = 0;
  5995. if (Py_SIZE(self->stack))
  5996. Pdata_clear(self->stack, 0);
  5997. /* Convenient macros for the dispatch while-switch loop just below. */
  5998. #define OP(opcode, load_func) \
  5999. case opcode: if (load_func(st, self) < 0) break; continue;
  6000. #define OP_ARG(opcode, load_func, arg) \
  6001. case opcode: if (load_func(st, self, (arg)) < 0) break; continue;
  6002. while (1) {
  6003. if (_Unpickler_Read(self, st, &s, 1) < 0) {
  6004. if (PyErr_ExceptionMatches(st->UnpicklingError)) {
  6005. PyErr_Format(PyExc_EOFError, "Ran out of input");
  6006. }
  6007. return NULL;
  6008. }
  6009. switch ((enum opcode)s[0]) {
  6010. OP(NONE, load_none)
  6011. OP(BININT, load_binint)
  6012. OP(BININT1, load_binint1)
  6013. OP(BININT2, load_binint2)
  6014. OP(INT, load_int)
  6015. OP(LONG, load_long)
  6016. OP_ARG(LONG1, load_counted_long, 1)
  6017. OP_ARG(LONG4, load_counted_long, 4)
  6018. OP(FLOAT, load_float)
  6019. OP(BINFLOAT, load_binfloat)
  6020. OP_ARG(SHORT_BINBYTES, load_counted_binbytes, 1)
  6021. OP_ARG(BINBYTES, load_counted_binbytes, 4)
  6022. OP_ARG(BINBYTES8, load_counted_binbytes, 8)
  6023. OP(BYTEARRAY8, load_counted_bytearray)
  6024. OP(NEXT_BUFFER, load_next_buffer)
  6025. OP(READONLY_BUFFER, load_readonly_buffer)
  6026. OP_ARG(SHORT_BINSTRING, load_counted_binstring, 1)
  6027. OP_ARG(BINSTRING, load_counted_binstring, 4)
  6028. OP(STRING, load_string)
  6029. OP(UNICODE, load_unicode)
  6030. OP_ARG(SHORT_BINUNICODE, load_counted_binunicode, 1)
  6031. OP_ARG(BINUNICODE, load_counted_binunicode, 4)
  6032. OP_ARG(BINUNICODE8, load_counted_binunicode, 8)
  6033. OP_ARG(EMPTY_TUPLE, load_counted_tuple, 0)
  6034. OP_ARG(TUPLE1, load_counted_tuple, 1)
  6035. OP_ARG(TUPLE2, load_counted_tuple, 2)
  6036. OP_ARG(TUPLE3, load_counted_tuple, 3)
  6037. OP(TUPLE, load_tuple)
  6038. OP(EMPTY_LIST, load_empty_list)
  6039. OP(LIST, load_list)
  6040. OP(EMPTY_DICT, load_empty_dict)
  6041. OP(DICT, load_dict)
  6042. OP(EMPTY_SET, load_empty_set)
  6043. OP(ADDITEMS, load_additems)
  6044. OP(FROZENSET, load_frozenset)
  6045. OP(OBJ, load_obj)
  6046. OP(INST, load_inst)
  6047. OP_ARG(NEWOBJ, load_newobj, 0)
  6048. OP_ARG(NEWOBJ_EX, load_newobj, 1)
  6049. OP(GLOBAL, load_global)
  6050. OP(STACK_GLOBAL, load_stack_global)
  6051. OP(APPEND, load_append)
  6052. OP(APPENDS, load_appends)
  6053. OP(BUILD, load_build)
  6054. OP(DUP, load_dup)
  6055. OP(BINGET, load_binget)
  6056. OP(LONG_BINGET, load_long_binget)
  6057. OP(GET, load_get)
  6058. OP(MARK, load_mark)
  6059. OP(BINPUT, load_binput)
  6060. OP(LONG_BINPUT, load_long_binput)
  6061. OP(PUT, load_put)
  6062. OP(MEMOIZE, load_memoize)
  6063. OP(POP, load_pop)
  6064. OP(POP_MARK, load_pop_mark)
  6065. OP(SETITEM, load_setitem)
  6066. OP(SETITEMS, load_setitems)
  6067. OP(PERSID, load_persid)
  6068. OP(BINPERSID, load_binpersid)
  6069. OP(REDUCE, load_reduce)
  6070. OP(PROTO, load_proto)
  6071. OP(FRAME, load_frame)
  6072. OP_ARG(EXT1, load_extension, 1)
  6073. OP_ARG(EXT2, load_extension, 2)
  6074. OP_ARG(EXT4, load_extension, 4)
  6075. OP_ARG(NEWTRUE, load_bool, Py_True)
  6076. OP_ARG(NEWFALSE, load_bool, Py_False)
  6077. case STOP:
  6078. break;
  6079. default:
  6080. {
  6081. unsigned char c = (unsigned char) *s;
  6082. if (0x20 <= c && c <= 0x7e && c != '\'' && c != '\\') {
  6083. PyErr_Format(st->UnpicklingError,
  6084. "invalid load key, '%c'.", c);
  6085. }
  6086. else {
  6087. PyErr_Format(st->UnpicklingError,
  6088. "invalid load key, '\\x%02x'.", c);
  6089. }
  6090. return NULL;
  6091. }
  6092. }
  6093. break; /* and we are done! */
  6094. }
  6095. if (PyErr_Occurred()) {
  6096. return NULL;
  6097. }
  6098. if (_Unpickler_SkipConsumed(self) < 0)
  6099. return NULL;
  6100. PDATA_POP(st, self->stack, value);
  6101. return value;
  6102. }
  6103. /*[clinic input]
  6104. _pickle.Unpickler.load
  6105. cls: defining_class
  6106. Load a pickle.
  6107. Read a pickled object representation from the open file object given
  6108. in the constructor, and return the reconstituted object hierarchy
  6109. specified therein.
  6110. [clinic start generated code]*/
  6111. static PyObject *
  6112. _pickle_Unpickler_load_impl(UnpicklerObject *self, PyTypeObject *cls)
  6113. /*[clinic end generated code: output=cc88168f608e3007 input=f5d2f87e61d5f07f]*/
  6114. {
  6115. UnpicklerObject *unpickler = (UnpicklerObject*)self;
  6116. PickleState *st = _Pickle_GetStateByClass(cls);
  6117. /* Check whether the Unpickler was initialized correctly. This prevents
  6118. segfaulting if a subclass overridden __init__ with a function that does
  6119. not call Unpickler.__init__(). Here, we simply ensure that self->read
  6120. is not NULL. */
  6121. if (unpickler->read == NULL) {
  6122. PyErr_Format(st->UnpicklingError,
  6123. "Unpickler.__init__() was not called by %s.__init__()",
  6124. Py_TYPE(unpickler)->tp_name);
  6125. return NULL;
  6126. }
  6127. return load(st, unpickler);
  6128. }
  6129. /* The name of find_class() is misleading. In newer pickle protocols, this
  6130. function is used for loading any global (i.e., functions), not just
  6131. classes. The name is kept only for backward compatibility. */
  6132. /*[clinic input]
  6133. _pickle.Unpickler.find_class
  6134. cls: defining_class
  6135. module_name: object
  6136. global_name: object
  6137. /
  6138. Return an object from a specified module.
  6139. If necessary, the module will be imported. Subclasses may override
  6140. this method (e.g. to restrict unpickling of arbitrary classes and
  6141. functions).
  6142. This method is called whenever a class or a function object is
  6143. needed. Both arguments passed are str objects.
  6144. [clinic start generated code]*/
  6145. static PyObject *
  6146. _pickle_Unpickler_find_class_impl(UnpicklerObject *self, PyTypeObject *cls,
  6147. PyObject *module_name,
  6148. PyObject *global_name)
  6149. /*[clinic end generated code: output=99577948abb0be81 input=9577745719219fc7]*/
  6150. {
  6151. PyObject *global;
  6152. PyObject *module;
  6153. if (PySys_Audit("pickle.find_class", "OO",
  6154. module_name, global_name) < 0) {
  6155. return NULL;
  6156. }
  6157. /* Try to map the old names used in Python 2.x to the new ones used in
  6158. Python 3.x. We do this only with old pickle protocols and when the
  6159. user has not disabled the feature. */
  6160. if (self->proto < 3 && self->fix_imports) {
  6161. PyObject *key;
  6162. PyObject *item;
  6163. PickleState *st = _Pickle_GetStateByClass(cls);
  6164. /* Check if the global (i.e., a function or a class) was renamed
  6165. or moved to another module. */
  6166. key = PyTuple_Pack(2, module_name, global_name);
  6167. if (key == NULL)
  6168. return NULL;
  6169. item = PyDict_GetItemWithError(st->name_mapping_2to3, key);
  6170. Py_DECREF(key);
  6171. if (item) {
  6172. if (!PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 2) {
  6173. PyErr_Format(PyExc_RuntimeError,
  6174. "_compat_pickle.NAME_MAPPING values should be "
  6175. "2-tuples, not %.200s", Py_TYPE(item)->tp_name);
  6176. return NULL;
  6177. }
  6178. module_name = PyTuple_GET_ITEM(item, 0);
  6179. global_name = PyTuple_GET_ITEM(item, 1);
  6180. if (!PyUnicode_Check(module_name) ||
  6181. !PyUnicode_Check(global_name)) {
  6182. PyErr_Format(PyExc_RuntimeError,
  6183. "_compat_pickle.NAME_MAPPING values should be "
  6184. "pairs of str, not (%.200s, %.200s)",
  6185. Py_TYPE(module_name)->tp_name,
  6186. Py_TYPE(global_name)->tp_name);
  6187. return NULL;
  6188. }
  6189. }
  6190. else if (PyErr_Occurred()) {
  6191. return NULL;
  6192. }
  6193. else {
  6194. /* Check if the module was renamed. */
  6195. item = PyDict_GetItemWithError(st->import_mapping_2to3, module_name);
  6196. if (item) {
  6197. if (!PyUnicode_Check(item)) {
  6198. PyErr_Format(PyExc_RuntimeError,
  6199. "_compat_pickle.IMPORT_MAPPING values should be "
  6200. "strings, not %.200s", Py_TYPE(item)->tp_name);
  6201. return NULL;
  6202. }
  6203. module_name = item;
  6204. }
  6205. else if (PyErr_Occurred()) {
  6206. return NULL;
  6207. }
  6208. }
  6209. }
  6210. /*
  6211. * we don't use PyImport_GetModule here, because it can return partially-
  6212. * initialised modules, which then cause the getattribute to fail.
  6213. */
  6214. module = PyImport_Import(module_name);
  6215. if (module == NULL) {
  6216. return NULL;
  6217. }
  6218. global = getattribute(module, global_name, self->proto >= 4);
  6219. Py_DECREF(module);
  6220. return global;
  6221. }
  6222. /*[clinic input]
  6223. _pickle.Unpickler.__sizeof__ -> size_t
  6224. Returns size in memory, in bytes.
  6225. [clinic start generated code]*/
  6226. static size_t
  6227. _pickle_Unpickler___sizeof___impl(UnpicklerObject *self)
  6228. /*[clinic end generated code: output=4648d84c228196df input=27180b2b6b524012]*/
  6229. {
  6230. size_t res = _PyObject_SIZE(Py_TYPE(self));
  6231. if (self->memo != NULL)
  6232. res += self->memo_size * sizeof(PyObject *);
  6233. if (self->marks != NULL)
  6234. res += (size_t)self->marks_size * sizeof(Py_ssize_t);
  6235. if (self->input_line != NULL)
  6236. res += strlen(self->input_line) + 1;
  6237. if (self->encoding != NULL)
  6238. res += strlen(self->encoding) + 1;
  6239. if (self->errors != NULL)
  6240. res += strlen(self->errors) + 1;
  6241. return res;
  6242. }
  6243. static struct PyMethodDef Unpickler_methods[] = {
  6244. _PICKLE_UNPICKLER_LOAD_METHODDEF
  6245. _PICKLE_UNPICKLER_FIND_CLASS_METHODDEF
  6246. _PICKLE_UNPICKLER___SIZEOF___METHODDEF
  6247. {NULL, NULL} /* sentinel */
  6248. };
  6249. static int
  6250. Unpickler_clear(UnpicklerObject *self)
  6251. {
  6252. Py_CLEAR(self->readline);
  6253. Py_CLEAR(self->readinto);
  6254. Py_CLEAR(self->read);
  6255. Py_CLEAR(self->peek);
  6256. Py_CLEAR(self->stack);
  6257. Py_CLEAR(self->pers_func);
  6258. Py_CLEAR(self->buffers);
  6259. if (self->buffer.buf != NULL) {
  6260. PyBuffer_Release(&self->buffer);
  6261. self->buffer.buf = NULL;
  6262. }
  6263. _Unpickler_MemoCleanup(self);
  6264. PyMem_Free(self->marks);
  6265. self->marks = NULL;
  6266. PyMem_Free(self->input_line);
  6267. self->input_line = NULL;
  6268. PyMem_Free(self->encoding);
  6269. self->encoding = NULL;
  6270. PyMem_Free(self->errors);
  6271. self->errors = NULL;
  6272. return 0;
  6273. }
  6274. static void
  6275. Unpickler_dealloc(UnpicklerObject *self)
  6276. {
  6277. PyTypeObject *tp = Py_TYPE(self);
  6278. PyObject_GC_UnTrack((PyObject *)self);
  6279. (void)Unpickler_clear(self);
  6280. tp->tp_free((PyObject *)self);
  6281. Py_DECREF(tp);
  6282. }
  6283. static int
  6284. Unpickler_traverse(UnpicklerObject *self, visitproc visit, void *arg)
  6285. {
  6286. Py_VISIT(Py_TYPE(self));
  6287. Py_VISIT(self->readline);
  6288. Py_VISIT(self->readinto);
  6289. Py_VISIT(self->read);
  6290. Py_VISIT(self->peek);
  6291. Py_VISIT(self->stack);
  6292. Py_VISIT(self->pers_func);
  6293. Py_VISIT(self->buffers);
  6294. PyObject **memo = self->memo;
  6295. if (memo) {
  6296. Py_ssize_t i = self->memo_size;
  6297. while (--i >= 0) {
  6298. Py_VISIT(memo[i]);
  6299. }
  6300. }
  6301. return 0;
  6302. }
  6303. /*[clinic input]
  6304. _pickle.Unpickler.__init__
  6305. file: object
  6306. *
  6307. fix_imports: bool = True
  6308. encoding: str = 'ASCII'
  6309. errors: str = 'strict'
  6310. buffers: object(c_default="NULL") = ()
  6311. This takes a binary file for reading a pickle data stream.
  6312. The protocol version of the pickle is detected automatically, so no
  6313. protocol argument is needed. Bytes past the pickled object's
  6314. representation are ignored.
  6315. The argument *file* must have two methods, a read() method that takes
  6316. an integer argument, and a readline() method that requires no
  6317. arguments. Both methods should return bytes. Thus *file* can be a
  6318. binary file object opened for reading, an io.BytesIO object, or any
  6319. other custom object that meets this interface.
  6320. Optional keyword arguments are *fix_imports*, *encoding* and *errors*,
  6321. which are used to control compatibility support for pickle stream
  6322. generated by Python 2. If *fix_imports* is True, pickle will try to
  6323. map the old Python 2 names to the new names used in Python 3. The
  6324. *encoding* and *errors* tell pickle how to decode 8-bit string
  6325. instances pickled by Python 2; these default to 'ASCII' and 'strict',
  6326. respectively. The *encoding* can be 'bytes' to read these 8-bit
  6327. string instances as bytes objects.
  6328. [clinic start generated code]*/
  6329. static int
  6330. _pickle_Unpickler___init___impl(UnpicklerObject *self, PyObject *file,
  6331. int fix_imports, const char *encoding,
  6332. const char *errors, PyObject *buffers)
  6333. /*[clinic end generated code: output=09f0192649ea3f85 input=ca4c1faea9553121]*/
  6334. {
  6335. /* In case of multiple __init__() calls, clear previous content. */
  6336. if (self->read != NULL)
  6337. (void)Unpickler_clear(self);
  6338. if (_Unpickler_SetInputStream(self, file) < 0)
  6339. return -1;
  6340. if (_Unpickler_SetInputEncoding(self, encoding, errors) < 0)
  6341. return -1;
  6342. if (_Unpickler_SetBuffers(self, buffers) < 0)
  6343. return -1;
  6344. self->fix_imports = fix_imports;
  6345. if (init_method_ref((PyObject *)self, &_Py_ID(persistent_load),
  6346. &self->pers_func, &self->pers_func_self) < 0)
  6347. {
  6348. return -1;
  6349. }
  6350. PyTypeObject *tp = Py_TYPE(self);
  6351. PickleState *state = _Pickle_FindStateByType(tp);
  6352. self->stack = (Pdata *)Pdata_New(state);
  6353. if (self->stack == NULL)
  6354. return -1;
  6355. self->memo_size = 32;
  6356. self->memo = _Unpickler_NewMemo(self->memo_size);
  6357. if (self->memo == NULL)
  6358. return -1;
  6359. self->proto = 0;
  6360. return 0;
  6361. }
  6362. /* Define a proxy object for the Unpickler's internal memo object. This is to
  6363. * avoid breaking code like:
  6364. * unpickler.memo.clear()
  6365. * and
  6366. * unpickler.memo = saved_memo
  6367. * Is this a good idea? Not really, but we don't want to break code that uses
  6368. * it. Note that we don't implement the entire mapping API here. This is
  6369. * intentional, as these should be treated as black-box implementation details.
  6370. *
  6371. * We do, however, have to implement pickling/unpickling support because of
  6372. * real-world code like cvs2svn.
  6373. */
  6374. /*[clinic input]
  6375. _pickle.UnpicklerMemoProxy.clear
  6376. Remove all items from memo.
  6377. [clinic start generated code]*/
  6378. static PyObject *
  6379. _pickle_UnpicklerMemoProxy_clear_impl(UnpicklerMemoProxyObject *self)
  6380. /*[clinic end generated code: output=d20cd43f4ba1fb1f input=b1df7c52e7afd9bd]*/
  6381. {
  6382. _Unpickler_MemoCleanup(self->unpickler);
  6383. self->unpickler->memo = _Unpickler_NewMemo(self->unpickler->memo_size);
  6384. if (self->unpickler->memo == NULL)
  6385. return NULL;
  6386. Py_RETURN_NONE;
  6387. }
  6388. /*[clinic input]
  6389. _pickle.UnpicklerMemoProxy.copy
  6390. Copy the memo to a new object.
  6391. [clinic start generated code]*/
  6392. static PyObject *
  6393. _pickle_UnpicklerMemoProxy_copy_impl(UnpicklerMemoProxyObject *self)
  6394. /*[clinic end generated code: output=e12af7e9bc1e4c77 input=97769247ce032c1d]*/
  6395. {
  6396. size_t i;
  6397. PyObject *new_memo = PyDict_New();
  6398. if (new_memo == NULL)
  6399. return NULL;
  6400. for (i = 0; i < self->unpickler->memo_size; i++) {
  6401. int status;
  6402. PyObject *key, *value;
  6403. value = self->unpickler->memo[i];
  6404. if (value == NULL)
  6405. continue;
  6406. key = PyLong_FromSsize_t(i);
  6407. if (key == NULL)
  6408. goto error;
  6409. status = PyDict_SetItem(new_memo, key, value);
  6410. Py_DECREF(key);
  6411. if (status < 0)
  6412. goto error;
  6413. }
  6414. return new_memo;
  6415. error:
  6416. Py_DECREF(new_memo);
  6417. return NULL;
  6418. }
  6419. /*[clinic input]
  6420. _pickle.UnpicklerMemoProxy.__reduce__
  6421. Implement pickling support.
  6422. [clinic start generated code]*/
  6423. static PyObject *
  6424. _pickle_UnpicklerMemoProxy___reduce___impl(UnpicklerMemoProxyObject *self)
  6425. /*[clinic end generated code: output=6da34ac048d94cca input=6920862413407199]*/
  6426. {
  6427. PyObject *reduce_value;
  6428. PyObject *constructor_args;
  6429. PyObject *contents = _pickle_UnpicklerMemoProxy_copy_impl(self);
  6430. if (contents == NULL)
  6431. return NULL;
  6432. reduce_value = PyTuple_New(2);
  6433. if (reduce_value == NULL) {
  6434. Py_DECREF(contents);
  6435. return NULL;
  6436. }
  6437. constructor_args = PyTuple_New(1);
  6438. if (constructor_args == NULL) {
  6439. Py_DECREF(contents);
  6440. Py_DECREF(reduce_value);
  6441. return NULL;
  6442. }
  6443. PyTuple_SET_ITEM(constructor_args, 0, contents);
  6444. PyTuple_SET_ITEM(reduce_value, 0, Py_NewRef(&PyDict_Type));
  6445. PyTuple_SET_ITEM(reduce_value, 1, constructor_args);
  6446. return reduce_value;
  6447. }
  6448. static PyMethodDef unpicklerproxy_methods[] = {
  6449. _PICKLE_UNPICKLERMEMOPROXY_CLEAR_METHODDEF
  6450. _PICKLE_UNPICKLERMEMOPROXY_COPY_METHODDEF
  6451. _PICKLE_UNPICKLERMEMOPROXY___REDUCE___METHODDEF
  6452. {NULL, NULL} /* sentinel */
  6453. };
  6454. static void
  6455. UnpicklerMemoProxy_dealloc(UnpicklerMemoProxyObject *self)
  6456. {
  6457. PyTypeObject *tp = Py_TYPE(self);
  6458. PyObject_GC_UnTrack(self);
  6459. Py_CLEAR(self->unpickler);
  6460. tp->tp_free((PyObject *)self);
  6461. Py_DECREF(tp);
  6462. }
  6463. static int
  6464. UnpicklerMemoProxy_traverse(UnpicklerMemoProxyObject *self,
  6465. visitproc visit, void *arg)
  6466. {
  6467. Py_VISIT(Py_TYPE(self));
  6468. Py_VISIT(self->unpickler);
  6469. return 0;
  6470. }
  6471. static int
  6472. UnpicklerMemoProxy_clear(UnpicklerMemoProxyObject *self)
  6473. {
  6474. Py_CLEAR(self->unpickler);
  6475. return 0;
  6476. }
  6477. static PyType_Slot unpickler_memoproxy_slots[] = {
  6478. {Py_tp_dealloc, UnpicklerMemoProxy_dealloc},
  6479. {Py_tp_traverse, UnpicklerMemoProxy_traverse},
  6480. {Py_tp_clear, UnpicklerMemoProxy_clear},
  6481. {Py_tp_methods, unpicklerproxy_methods},
  6482. {Py_tp_hash, PyObject_HashNotImplemented},
  6483. {0, NULL},
  6484. };
  6485. static PyType_Spec unpickler_memoproxy_spec = {
  6486. .name = "_pickle.UnpicklerMemoProxy",
  6487. .basicsize = sizeof(UnpicklerMemoProxyObject),
  6488. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  6489. Py_TPFLAGS_IMMUTABLETYPE),
  6490. .slots = unpickler_memoproxy_slots,
  6491. };
  6492. static PyObject *
  6493. UnpicklerMemoProxy_New(UnpicklerObject *unpickler)
  6494. {
  6495. PickleState *state = _Pickle_FindStateByType(Py_TYPE(unpickler));
  6496. UnpicklerMemoProxyObject *self;
  6497. self = PyObject_GC_New(UnpicklerMemoProxyObject,
  6498. state->UnpicklerMemoProxyType);
  6499. if (self == NULL)
  6500. return NULL;
  6501. self->unpickler = (UnpicklerObject*)Py_NewRef(unpickler);
  6502. PyObject_GC_Track(self);
  6503. return (PyObject *)self;
  6504. }
  6505. /*****************************************************************************/
  6506. static PyObject *
  6507. Unpickler_get_memo(UnpicklerObject *self, void *Py_UNUSED(ignored))
  6508. {
  6509. return UnpicklerMemoProxy_New(self);
  6510. }
  6511. static int
  6512. Unpickler_set_memo(UnpicklerObject *self, PyObject *obj, void *Py_UNUSED(ignored))
  6513. {
  6514. PyObject **new_memo;
  6515. size_t new_memo_size = 0;
  6516. if (obj == NULL) {
  6517. PyErr_SetString(PyExc_TypeError,
  6518. "attribute deletion is not supported");
  6519. return -1;
  6520. }
  6521. PickleState *state = _Pickle_FindStateByType(Py_TYPE(self));
  6522. if (Py_IS_TYPE(obj, state->UnpicklerMemoProxyType)) {
  6523. UnpicklerObject *unpickler =
  6524. ((UnpicklerMemoProxyObject *)obj)->unpickler;
  6525. new_memo_size = unpickler->memo_size;
  6526. new_memo = _Unpickler_NewMemo(new_memo_size);
  6527. if (new_memo == NULL)
  6528. return -1;
  6529. for (size_t i = 0; i < new_memo_size; i++) {
  6530. new_memo[i] = Py_XNewRef(unpickler->memo[i]);
  6531. }
  6532. }
  6533. else if (PyDict_Check(obj)) {
  6534. Py_ssize_t i = 0;
  6535. PyObject *key, *value;
  6536. new_memo_size = PyDict_GET_SIZE(obj);
  6537. new_memo = _Unpickler_NewMemo(new_memo_size);
  6538. if (new_memo == NULL)
  6539. return -1;
  6540. while (PyDict_Next(obj, &i, &key, &value)) {
  6541. Py_ssize_t idx;
  6542. if (!PyLong_Check(key)) {
  6543. PyErr_SetString(PyExc_TypeError,
  6544. "memo key must be integers");
  6545. goto error;
  6546. }
  6547. idx = PyLong_AsSsize_t(key);
  6548. if (idx == -1 && PyErr_Occurred())
  6549. goto error;
  6550. if (idx < 0) {
  6551. PyErr_SetString(PyExc_ValueError,
  6552. "memo key must be positive integers.");
  6553. goto error;
  6554. }
  6555. if (_Unpickler_MemoPut(self, idx, value) < 0)
  6556. goto error;
  6557. }
  6558. }
  6559. else {
  6560. PyErr_Format(PyExc_TypeError,
  6561. "'memo' attribute must be an UnpicklerMemoProxy object "
  6562. "or dict, not %.200s", Py_TYPE(obj)->tp_name);
  6563. return -1;
  6564. }
  6565. _Unpickler_MemoCleanup(self);
  6566. self->memo_size = new_memo_size;
  6567. self->memo = new_memo;
  6568. return 0;
  6569. error:
  6570. if (new_memo_size) {
  6571. for (size_t i = new_memo_size - 1; i != SIZE_MAX; i--) {
  6572. Py_XDECREF(new_memo[i]);
  6573. }
  6574. PyMem_Free(new_memo);
  6575. }
  6576. return -1;
  6577. }
  6578. static PyObject *
  6579. Unpickler_get_persload(UnpicklerObject *self, void *Py_UNUSED(ignored))
  6580. {
  6581. if (self->pers_func == NULL) {
  6582. PyErr_SetString(PyExc_AttributeError, "persistent_load");
  6583. return NULL;
  6584. }
  6585. return reconstruct_method(self->pers_func, self->pers_func_self);
  6586. }
  6587. static int
  6588. Unpickler_set_persload(UnpicklerObject *self, PyObject *value, void *Py_UNUSED(ignored))
  6589. {
  6590. if (value == NULL) {
  6591. PyErr_SetString(PyExc_TypeError,
  6592. "attribute deletion is not supported");
  6593. return -1;
  6594. }
  6595. if (!PyCallable_Check(value)) {
  6596. PyErr_SetString(PyExc_TypeError,
  6597. "persistent_load must be a callable taking "
  6598. "one argument");
  6599. return -1;
  6600. }
  6601. self->pers_func_self = NULL;
  6602. Py_XSETREF(self->pers_func, Py_NewRef(value));
  6603. return 0;
  6604. }
  6605. static PyGetSetDef Unpickler_getsets[] = {
  6606. {"memo", (getter)Unpickler_get_memo, (setter)Unpickler_set_memo},
  6607. {"persistent_load", (getter)Unpickler_get_persload,
  6608. (setter)Unpickler_set_persload},
  6609. {NULL}
  6610. };
  6611. static PyType_Slot unpickler_type_slots[] = {
  6612. {Py_tp_dealloc, Unpickler_dealloc},
  6613. {Py_tp_doc, (char *)_pickle_Unpickler___init____doc__},
  6614. {Py_tp_traverse, Unpickler_traverse},
  6615. {Py_tp_clear, Unpickler_clear},
  6616. {Py_tp_methods, Unpickler_methods},
  6617. {Py_tp_getset, Unpickler_getsets},
  6618. {Py_tp_init, _pickle_Unpickler___init__},
  6619. {Py_tp_alloc, PyType_GenericAlloc},
  6620. {Py_tp_new, PyType_GenericNew},
  6621. {Py_tp_free, PyObject_GC_Del},
  6622. {0, NULL},
  6623. };
  6624. static PyType_Spec unpickler_type_spec = {
  6625. .name = "_pickle.Unpickler",
  6626. .basicsize = sizeof(UnpicklerObject),
  6627. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  6628. Py_TPFLAGS_IMMUTABLETYPE),
  6629. .slots = unpickler_type_slots,
  6630. };
  6631. /*[clinic input]
  6632. _pickle.dump
  6633. obj: object
  6634. file: object
  6635. protocol: object = None
  6636. *
  6637. fix_imports: bool = True
  6638. buffer_callback: object = None
  6639. Write a pickled representation of obj to the open file object file.
  6640. This is equivalent to ``Pickler(file, protocol).dump(obj)``, but may
  6641. be more efficient.
  6642. The optional *protocol* argument tells the pickler to use the given
  6643. protocol; supported protocols are 0, 1, 2, 3, 4 and 5. The default
  6644. protocol is 4. It was introduced in Python 3.4, and is incompatible
  6645. with previous versions.
  6646. Specifying a negative protocol version selects the highest protocol
  6647. version supported. The higher the protocol used, the more recent the
  6648. version of Python needed to read the pickle produced.
  6649. The *file* argument must have a write() method that accepts a single
  6650. bytes argument. It can thus be a file object opened for binary
  6651. writing, an io.BytesIO instance, or any other custom object that meets
  6652. this interface.
  6653. If *fix_imports* is True and protocol is less than 3, pickle will try
  6654. to map the new Python 3 names to the old module names used in Python
  6655. 2, so that the pickle data stream is readable with Python 2.
  6656. If *buffer_callback* is None (the default), buffer views are serialized
  6657. into *file* as part of the pickle stream. It is an error if
  6658. *buffer_callback* is not None and *protocol* is None or smaller than 5.
  6659. [clinic start generated code]*/
  6660. static PyObject *
  6661. _pickle_dump_impl(PyObject *module, PyObject *obj, PyObject *file,
  6662. PyObject *protocol, int fix_imports,
  6663. PyObject *buffer_callback)
  6664. /*[clinic end generated code: output=706186dba996490c input=5ed6653da99cd97c]*/
  6665. {
  6666. PickleState *state = _Pickle_GetState(module);
  6667. PicklerObject *pickler = _Pickler_New(state);
  6668. if (pickler == NULL)
  6669. return NULL;
  6670. if (_Pickler_SetProtocol(pickler, protocol, fix_imports) < 0)
  6671. goto error;
  6672. if (_Pickler_SetOutputStream(pickler, file) < 0)
  6673. goto error;
  6674. if (_Pickler_SetBufferCallback(pickler, buffer_callback) < 0)
  6675. goto error;
  6676. if (dump(state, pickler, obj) < 0)
  6677. goto error;
  6678. if (_Pickler_FlushToFile(pickler) < 0)
  6679. goto error;
  6680. Py_DECREF(pickler);
  6681. Py_RETURN_NONE;
  6682. error:
  6683. Py_XDECREF(pickler);
  6684. return NULL;
  6685. }
  6686. /*[clinic input]
  6687. _pickle.dumps
  6688. obj: object
  6689. protocol: object = None
  6690. *
  6691. fix_imports: bool = True
  6692. buffer_callback: object = None
  6693. Return the pickled representation of the object as a bytes object.
  6694. The optional *protocol* argument tells the pickler to use the given
  6695. protocol; supported protocols are 0, 1, 2, 3, 4 and 5. The default
  6696. protocol is 4. It was introduced in Python 3.4, and is incompatible
  6697. with previous versions.
  6698. Specifying a negative protocol version selects the highest protocol
  6699. version supported. The higher the protocol used, the more recent the
  6700. version of Python needed to read the pickle produced.
  6701. If *fix_imports* is True and *protocol* is less than 3, pickle will
  6702. try to map the new Python 3 names to the old module names used in
  6703. Python 2, so that the pickle data stream is readable with Python 2.
  6704. If *buffer_callback* is None (the default), buffer views are serialized
  6705. into *file* as part of the pickle stream. It is an error if
  6706. *buffer_callback* is not None and *protocol* is None or smaller than 5.
  6707. [clinic start generated code]*/
  6708. static PyObject *
  6709. _pickle_dumps_impl(PyObject *module, PyObject *obj, PyObject *protocol,
  6710. int fix_imports, PyObject *buffer_callback)
  6711. /*[clinic end generated code: output=fbab0093a5580fdf input=e543272436c6f987]*/
  6712. {
  6713. PyObject *result;
  6714. PickleState *state = _Pickle_GetState(module);
  6715. PicklerObject *pickler = _Pickler_New(state);
  6716. if (pickler == NULL)
  6717. return NULL;
  6718. if (_Pickler_SetProtocol(pickler, protocol, fix_imports) < 0)
  6719. goto error;
  6720. if (_Pickler_SetBufferCallback(pickler, buffer_callback) < 0)
  6721. goto error;
  6722. if (dump(state, pickler, obj) < 0)
  6723. goto error;
  6724. result = _Pickler_GetString(pickler);
  6725. Py_DECREF(pickler);
  6726. return result;
  6727. error:
  6728. Py_XDECREF(pickler);
  6729. return NULL;
  6730. }
  6731. /*[clinic input]
  6732. _pickle.load
  6733. file: object
  6734. *
  6735. fix_imports: bool = True
  6736. encoding: str = 'ASCII'
  6737. errors: str = 'strict'
  6738. buffers: object(c_default="NULL") = ()
  6739. Read and return an object from the pickle data stored in a file.
  6740. This is equivalent to ``Unpickler(file).load()``, but may be more
  6741. efficient.
  6742. The protocol version of the pickle is detected automatically, so no
  6743. protocol argument is needed. Bytes past the pickled object's
  6744. representation are ignored.
  6745. The argument *file* must have two methods, a read() method that takes
  6746. an integer argument, and a readline() method that requires no
  6747. arguments. Both methods should return bytes. Thus *file* can be a
  6748. binary file object opened for reading, an io.BytesIO object, or any
  6749. other custom object that meets this interface.
  6750. Optional keyword arguments are *fix_imports*, *encoding* and *errors*,
  6751. which are used to control compatibility support for pickle stream
  6752. generated by Python 2. If *fix_imports* is True, pickle will try to
  6753. map the old Python 2 names to the new names used in Python 3. The
  6754. *encoding* and *errors* tell pickle how to decode 8-bit string
  6755. instances pickled by Python 2; these default to 'ASCII' and 'strict',
  6756. respectively. The *encoding* can be 'bytes' to read these 8-bit
  6757. string instances as bytes objects.
  6758. [clinic start generated code]*/
  6759. static PyObject *
  6760. _pickle_load_impl(PyObject *module, PyObject *file, int fix_imports,
  6761. const char *encoding, const char *errors,
  6762. PyObject *buffers)
  6763. /*[clinic end generated code: output=250452d141c23e76 input=46c7c31c92f4f371]*/
  6764. {
  6765. PyObject *result;
  6766. UnpicklerObject *unpickler = _Unpickler_New(module);
  6767. if (unpickler == NULL)
  6768. return NULL;
  6769. if (_Unpickler_SetInputStream(unpickler, file) < 0)
  6770. goto error;
  6771. if (_Unpickler_SetInputEncoding(unpickler, encoding, errors) < 0)
  6772. goto error;
  6773. if (_Unpickler_SetBuffers(unpickler, buffers) < 0)
  6774. goto error;
  6775. unpickler->fix_imports = fix_imports;
  6776. PickleState *state = _Pickle_GetState(module);
  6777. result = load(state, unpickler);
  6778. Py_DECREF(unpickler);
  6779. return result;
  6780. error:
  6781. Py_XDECREF(unpickler);
  6782. return NULL;
  6783. }
  6784. /*[clinic input]
  6785. _pickle.loads
  6786. data: object
  6787. /
  6788. *
  6789. fix_imports: bool = True
  6790. encoding: str = 'ASCII'
  6791. errors: str = 'strict'
  6792. buffers: object(c_default="NULL") = ()
  6793. Read and return an object from the given pickle data.
  6794. The protocol version of the pickle is detected automatically, so no
  6795. protocol argument is needed. Bytes past the pickled object's
  6796. representation are ignored.
  6797. Optional keyword arguments are *fix_imports*, *encoding* and *errors*,
  6798. which are used to control compatibility support for pickle stream
  6799. generated by Python 2. If *fix_imports* is True, pickle will try to
  6800. map the old Python 2 names to the new names used in Python 3. The
  6801. *encoding* and *errors* tell pickle how to decode 8-bit string
  6802. instances pickled by Python 2; these default to 'ASCII' and 'strict',
  6803. respectively. The *encoding* can be 'bytes' to read these 8-bit
  6804. string instances as bytes objects.
  6805. [clinic start generated code]*/
  6806. static PyObject *
  6807. _pickle_loads_impl(PyObject *module, PyObject *data, int fix_imports,
  6808. const char *encoding, const char *errors,
  6809. PyObject *buffers)
  6810. /*[clinic end generated code: output=82ac1e6b588e6d02 input=b3615540d0535087]*/
  6811. {
  6812. PyObject *result;
  6813. UnpicklerObject *unpickler = _Unpickler_New(module);
  6814. if (unpickler == NULL)
  6815. return NULL;
  6816. if (_Unpickler_SetStringInput(unpickler, data) < 0)
  6817. goto error;
  6818. if (_Unpickler_SetInputEncoding(unpickler, encoding, errors) < 0)
  6819. goto error;
  6820. if (_Unpickler_SetBuffers(unpickler, buffers) < 0)
  6821. goto error;
  6822. unpickler->fix_imports = fix_imports;
  6823. PickleState *state = _Pickle_GetState(module);
  6824. result = load(state, unpickler);
  6825. Py_DECREF(unpickler);
  6826. return result;
  6827. error:
  6828. Py_XDECREF(unpickler);
  6829. return NULL;
  6830. }
  6831. static struct PyMethodDef pickle_methods[] = {
  6832. _PICKLE_DUMP_METHODDEF
  6833. _PICKLE_DUMPS_METHODDEF
  6834. _PICKLE_LOAD_METHODDEF
  6835. _PICKLE_LOADS_METHODDEF
  6836. {NULL, NULL} /* sentinel */
  6837. };
  6838. static int
  6839. pickle_clear(PyObject *m)
  6840. {
  6841. _Pickle_ClearState(_Pickle_GetState(m));
  6842. return 0;
  6843. }
  6844. static void
  6845. pickle_free(PyObject *m)
  6846. {
  6847. _Pickle_ClearState(_Pickle_GetState(m));
  6848. }
  6849. static int
  6850. pickle_traverse(PyObject *m, visitproc visit, void *arg)
  6851. {
  6852. PickleState *st = _Pickle_GetState(m);
  6853. Py_VISIT(st->PickleError);
  6854. Py_VISIT(st->PicklingError);
  6855. Py_VISIT(st->UnpicklingError);
  6856. Py_VISIT(st->dispatch_table);
  6857. Py_VISIT(st->extension_registry);
  6858. Py_VISIT(st->extension_cache);
  6859. Py_VISIT(st->inverted_registry);
  6860. Py_VISIT(st->name_mapping_2to3);
  6861. Py_VISIT(st->import_mapping_2to3);
  6862. Py_VISIT(st->name_mapping_3to2);
  6863. Py_VISIT(st->import_mapping_3to2);
  6864. Py_VISIT(st->codecs_encode);
  6865. Py_VISIT(st->getattr);
  6866. Py_VISIT(st->partial);
  6867. Py_VISIT(st->Pickler_Type);
  6868. Py_VISIT(st->Unpickler_Type);
  6869. Py_VISIT(st->Pdata_Type);
  6870. Py_VISIT(st->PicklerMemoProxyType);
  6871. Py_VISIT(st->UnpicklerMemoProxyType);
  6872. return 0;
  6873. }
  6874. static int
  6875. _pickle_exec(PyObject *m)
  6876. {
  6877. PickleState *st = _Pickle_GetState(m);
  6878. #define CREATE_TYPE(mod, type, spec) \
  6879. do { \
  6880. type = (PyTypeObject *)PyType_FromMetaclass(NULL, mod, spec, NULL); \
  6881. if (type == NULL) { \
  6882. return -1; \
  6883. } \
  6884. } while (0)
  6885. CREATE_TYPE(m, st->Pdata_Type, &pdata_spec);
  6886. CREATE_TYPE(m, st->PicklerMemoProxyType, &memoproxy_spec);
  6887. CREATE_TYPE(m, st->UnpicklerMemoProxyType, &unpickler_memoproxy_spec);
  6888. CREATE_TYPE(m, st->Pickler_Type, &pickler_type_spec);
  6889. CREATE_TYPE(m, st->Unpickler_Type, &unpickler_type_spec);
  6890. #undef CREATE_TYPE
  6891. /* Add types */
  6892. if (PyModule_AddType(m, &PyPickleBuffer_Type) < 0) {
  6893. return -1;
  6894. }
  6895. if (PyModule_AddType(m, st->Pickler_Type) < 0) {
  6896. return -1;
  6897. }
  6898. if (PyModule_AddType(m, st->Unpickler_Type) < 0) {
  6899. return -1;
  6900. }
  6901. /* Initialize the exceptions. */
  6902. st->PickleError = PyErr_NewException("_pickle.PickleError", NULL, NULL);
  6903. if (st->PickleError == NULL)
  6904. return -1;
  6905. st->PicklingError = \
  6906. PyErr_NewException("_pickle.PicklingError", st->PickleError, NULL);
  6907. if (st->PicklingError == NULL)
  6908. return -1;
  6909. st->UnpicklingError = \
  6910. PyErr_NewException("_pickle.UnpicklingError", st->PickleError, NULL);
  6911. if (st->UnpicklingError == NULL)
  6912. return -1;
  6913. if (PyModule_AddObjectRef(m, "PickleError", st->PickleError) < 0) {
  6914. return -1;
  6915. }
  6916. if (PyModule_AddObjectRef(m, "PicklingError", st->PicklingError) < 0) {
  6917. return -1;
  6918. }
  6919. if (PyModule_AddObjectRef(m, "UnpicklingError", st->UnpicklingError) < 0) {
  6920. return -1;
  6921. }
  6922. if (_Pickle_InitState(st) < 0)
  6923. return -1;
  6924. return 0;
  6925. }
  6926. static PyModuleDef_Slot pickle_slots[] = {
  6927. {Py_mod_exec, _pickle_exec},
  6928. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  6929. {0, NULL},
  6930. };
  6931. static struct PyModuleDef _picklemodule = {
  6932. PyModuleDef_HEAD_INIT,
  6933. .m_name = "_pickle",
  6934. .m_doc = pickle_module_doc,
  6935. .m_size = sizeof(PickleState),
  6936. .m_methods = pickle_methods,
  6937. .m_slots = pickle_slots,
  6938. .m_traverse = pickle_traverse,
  6939. .m_clear = pickle_clear,
  6940. .m_free = (freefunc)pickle_free,
  6941. };
  6942. PyMODINIT_FUNC
  6943. PyInit__pickle(void)
  6944. {
  6945. return PyModuleDef_Init(&_picklemodule);
  6946. }