_pickle.c 227 KB

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