_cffi_backend.c 270 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110
  1. #define PY_SSIZE_T_CLEAN
  2. #include <Python.h>
  3. #include "structmember.h"
  4. #define CFFI_VERSION "1.15.1"
  5. #ifdef MS_WIN32
  6. #include <windows.h>
  7. #include "misc_win32.h"
  8. #else
  9. #include <stddef.h>
  10. #include <stdint.h>
  11. #include <dlfcn.h>
  12. #include <errno.h>
  13. #include <ffi.h>
  14. #include <sys/mman.h>
  15. #endif
  16. /* this block of #ifs should be kept exactly identical between
  17. c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py */
  18. #if defined(_MSC_VER)
  19. # include <malloc.h> /* for alloca() */
  20. # if _MSC_VER < 1600 /* MSVC < 2010 */
  21. typedef __int8 int8_t;
  22. typedef __int16 int16_t;
  23. typedef __int32 int32_t;
  24. typedef __int64 int64_t;
  25. typedef unsigned __int8 uint8_t;
  26. typedef unsigned __int16 uint16_t;
  27. typedef unsigned __int32 uint32_t;
  28. typedef unsigned __int64 uint64_t;
  29. typedef __int8 int_least8_t;
  30. typedef __int16 int_least16_t;
  31. typedef __int32 int_least32_t;
  32. typedef __int64 int_least64_t;
  33. typedef unsigned __int8 uint_least8_t;
  34. typedef unsigned __int16 uint_least16_t;
  35. typedef unsigned __int32 uint_least32_t;
  36. typedef unsigned __int64 uint_least64_t;
  37. typedef __int8 int_fast8_t;
  38. typedef __int16 int_fast16_t;
  39. typedef __int32 int_fast32_t;
  40. typedef __int64 int_fast64_t;
  41. typedef unsigned __int8 uint_fast8_t;
  42. typedef unsigned __int16 uint_fast16_t;
  43. typedef unsigned __int32 uint_fast32_t;
  44. typedef unsigned __int64 uint_fast64_t;
  45. typedef __int64 intmax_t;
  46. typedef unsigned __int64 uintmax_t;
  47. # else
  48. # include <stdint.h>
  49. # endif
  50. # if _MSC_VER < 1800 /* MSVC < 2013 */
  51. typedef unsigned char _Bool;
  52. # endif
  53. #else
  54. # include <stdint.h>
  55. # if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
  56. # include <alloca.h>
  57. # endif
  58. #endif
  59. /* Define the following macro ONLY if you trust libffi's version of
  60. * ffi_closure_alloc() more than the code in malloc_closure.h.
  61. * IMPORTANT: DO NOT ENABLE THIS ON LINUX, unless you understand exactly
  62. * why I recommend against it and decide that you trust it more than my
  63. * analysis below.
  64. *
  65. * There are two versions of this code: one inside libffi itself, and
  66. * one inside malloc_closure.h here. Both should be fine as long as the
  67. * Linux distribution does _not_ enable extra security features. If it
  68. * does, then the code in malloc_closure.h will cleanly crash because
  69. * there is no reasonable way to obtain a read-write-execute memory
  70. * page. On the other hand, the code in libffi will appear to
  71. * work---but will actually randomly crash after a fork() if the child
  72. * does not immediately call exec(). This second crash is of the kind
  73. * that can be turned into an attack vector by a motivated attacker.
  74. * So, _enabling_ extra security features _opens_ an attack vector.
  75. * That sounds like a horribly bad idea to me, and is the reason for why
  76. * I prefer CFFI crashing cleanly.
  77. *
  78. * Currently, we use libffi's ffi_closure_alloc() on NetBSD. It is
  79. * known that on the NetBSD kernel, a different strategy is used which
  80. * should not be open to the fork() bug.
  81. *
  82. * This is also used on macOS, provided we are executing on macOS 10.15 or
  83. * above. It's a mess because it needs runtime checks in that case.
  84. */
  85. #ifdef __NetBSD__
  86. # define CFFI_CHECK_FFI_CLOSURE_ALLOC 1
  87. # define CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE 1
  88. # define CFFI_CHECK_FFI_PREP_CLOSURE_LOC 1
  89. # define CFFI_CHECK_FFI_PREP_CLOSURE_LOC_MAYBE 1
  90. # define CFFI_CHECK_FFI_PREP_CIF_VAR 0
  91. # define CFFI_CHECK_FFI_PREP_CIF_VAR_MAYBE 0
  92. #elif defined(__APPLE__) && defined(FFI_AVAILABLE_APPLE)
  93. # define CFFI_CHECK_FFI_CLOSURE_ALLOC __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
  94. # define CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE 1
  95. # define CFFI_CHECK_FFI_PREP_CLOSURE_LOC __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
  96. # define CFFI_CHECK_FFI_PREP_CLOSURE_LOC_MAYBE 1
  97. # define CFFI_CHECK_FFI_PREP_CIF_VAR __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
  98. # define CFFI_CHECK_FFI_PREP_CIF_VAR_MAYBE 1
  99. #else
  100. # define CFFI_CHECK_FFI_CLOSURE_ALLOC 0
  101. # define CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE 0
  102. # define CFFI_CHECK_FFI_PREP_CLOSURE_LOC 0
  103. # define CFFI_CHECK_FFI_PREP_CLOSURE_LOC_MAYBE 0
  104. # define CFFI_CHECK_FFI_PREP_CIF_VAR 0
  105. # define CFFI_CHECK_FFI_PREP_CIF_VAR_MAYBE 0
  106. #endif
  107. /* always includes this, even if it turns out not to be used on NetBSD
  108. because calls are behind "if (0)" */
  109. #include "malloc_closure.h"
  110. #if PY_MAJOR_VERSION >= 3
  111. # define STR_OR_BYTES "bytes"
  112. # define PyText_Type PyUnicode_Type
  113. # define PyText_Check PyUnicode_Check
  114. # define PyTextAny_Check PyUnicode_Check
  115. # define PyText_FromFormat PyUnicode_FromFormat
  116. # define PyText_AsUTF8 _PyUnicode_AsString /* PyUnicode_AsUTF8 in Py3.3 */
  117. # define PyText_AS_UTF8 _PyUnicode_AsString
  118. # if PY_VERSION_HEX >= 0x03030000
  119. # define PyText_GetSize PyUnicode_GetLength
  120. # else
  121. # define PyText_GetSize PyUnicode_GetSize
  122. # endif
  123. # define PyText_FromString PyUnicode_FromString
  124. # define PyText_FromStringAndSize PyUnicode_FromStringAndSize
  125. # define PyText_InternInPlace PyUnicode_InternInPlace
  126. # define PyText_InternFromString PyUnicode_InternFromString
  127. # define PyIntOrLong_Check PyLong_Check
  128. #else
  129. # define STR_OR_BYTES "str"
  130. # define PyText_Type PyString_Type
  131. # define PyText_Check PyString_Check
  132. # define PyTextAny_Check(op) (PyString_Check(op) || PyUnicode_Check(op))
  133. # define PyText_FromFormat PyString_FromFormat
  134. # define PyText_AsUTF8 PyString_AsString
  135. # define PyText_AS_UTF8 PyString_AS_STRING
  136. # define PyText_GetSize PyString_Size
  137. # define PyText_FromString PyString_FromString
  138. # define PyText_FromStringAndSize PyString_FromStringAndSize
  139. # define PyText_InternInPlace PyString_InternInPlace
  140. # define PyText_InternFromString PyString_InternFromString
  141. # define PyIntOrLong_Check(op) (PyInt_Check(op) || PyLong_Check(op))
  142. #endif
  143. #if PY_MAJOR_VERSION >= 3
  144. # define PyInt_FromLong PyLong_FromLong
  145. # define PyInt_FromSsize_t PyLong_FromSsize_t
  146. # define PyInt_AsSsize_t PyLong_AsSsize_t
  147. # define PyInt_AsLong PyLong_AsLong
  148. #endif
  149. #if PY_MAJOR_VERSION >= 3
  150. /* This is the default on Python3 and constant has been removed. */
  151. # define Py_TPFLAGS_CHECKTYPES 0
  152. #endif
  153. #if PY_MAJOR_VERSION < 3
  154. # undef PyCapsule_GetPointer
  155. # undef PyCapsule_New
  156. # define PyCapsule_GetPointer(capsule, name) \
  157. (PyCObject_AsVoidPtr(capsule))
  158. # define PyCapsule_New(pointer, name, destructor) \
  159. (PyCObject_FromVoidPtr(pointer, destructor))
  160. #endif
  161. #if PY_VERSION_HEX < 0x030900a4
  162. # define Py_SET_REFCNT(obj, val) (Py_REFCNT(obj) = (val))
  163. #endif
  164. #if PY_VERSION_HEX >= 0x03080000
  165. # define USE_WRITEUNRAISABLEMSG
  166. #endif
  167. /************************************************************/
  168. /* base type flag: exactly one of the following: */
  169. #define CT_PRIMITIVE_SIGNED 0x001 /* signed integer */
  170. #define CT_PRIMITIVE_UNSIGNED 0x002 /* unsigned integer */
  171. #define CT_PRIMITIVE_CHAR 0x004 /* char, wchar_t, charN_t */
  172. #define CT_PRIMITIVE_FLOAT 0x008 /* float, double, long double */
  173. #define CT_POINTER 0x010 /* pointer, excluding ptr-to-func */
  174. #define CT_ARRAY 0x020 /* array */
  175. #define CT_STRUCT 0x040 /* struct */
  176. #define CT_UNION 0x080 /* union */
  177. #define CT_FUNCTIONPTR 0x100 /* pointer to function */
  178. #define CT_VOID 0x200 /* void */
  179. #define CT_PRIMITIVE_COMPLEX 0x400 /* float _Complex, double _Complex */
  180. /* other flags that may also be set in addition to the base flag: */
  181. #define CT_IS_VOIDCHAR_PTR 0x00001000
  182. #define CT_PRIMITIVE_FITS_LONG 0x00002000
  183. #define CT_IS_OPAQUE 0x00004000
  184. #define CT_IS_ENUM 0x00008000
  185. #define CT_IS_PTR_TO_OWNED 0x00010000 /* only owned if CDataOwning_Type */
  186. #define CT_CUSTOM_FIELD_POS 0x00020000
  187. #define CT_IS_LONGDOUBLE 0x00040000
  188. #define CT_IS_BOOL 0x00080000
  189. #define CT_IS_FILE 0x00100000
  190. #define CT_IS_VOID_PTR 0x00200000
  191. #define CT_WITH_VAR_ARRAY 0x00400000 /* with open-ended array, anywhere */
  192. /* unused 0x00800000 */
  193. #define CT_LAZY_FIELD_LIST 0x01000000
  194. #define CT_WITH_PACKED_CHANGE 0x02000000
  195. #define CT_IS_SIGNED_WCHAR 0x04000000
  196. #define CT_PRIMITIVE_ANY (CT_PRIMITIVE_SIGNED | \
  197. CT_PRIMITIVE_UNSIGNED | \
  198. CT_PRIMITIVE_CHAR | \
  199. CT_PRIMITIVE_FLOAT | \
  200. CT_PRIMITIVE_COMPLEX)
  201. typedef struct _ctypedescr {
  202. PyObject_VAR_HEAD
  203. struct _ctypedescr *ct_itemdescr; /* ptrs and arrays: the item type */
  204. PyObject *ct_stuff; /* structs: dict of the fields
  205. arrays: ctypedescr of the ptr type
  206. function: tuple(abi, ctres, ctargs..)
  207. enum: pair {"name":x},{x:"name"}
  208. ptrs: lazily, ctypedescr of array */
  209. void *ct_extra; /* structs: first field (not a ref!)
  210. function types: cif_description
  211. primitives: prebuilt "cif" object */
  212. PyObject *ct_weakreflist; /* weakref support */
  213. PyObject *ct_unique_key; /* key in unique_cache (a string, but not
  214. human-readable) */
  215. Py_ssize_t ct_size; /* size of instances, or -1 if unknown */
  216. Py_ssize_t ct_length; /* length of arrays, or -1 if unknown;
  217. or alignment of primitive and struct types;
  218. always -1 for pointers */
  219. int ct_flags; /* CT_xxx flags */
  220. int ct_name_position; /* index in ct_name of where to put a var name */
  221. char ct_name[1]; /* string, e.g. "int *" for pointers to ints */
  222. } CTypeDescrObject;
  223. typedef struct {
  224. PyObject_HEAD
  225. CTypeDescrObject *c_type;
  226. char *c_data;
  227. PyObject *c_weakreflist;
  228. } CDataObject;
  229. typedef struct cfieldobject_s {
  230. PyObject_HEAD
  231. CTypeDescrObject *cf_type;
  232. Py_ssize_t cf_offset;
  233. short cf_bitshift; /* >= 0: bitshift; or BS_REGULAR or BS_EMPTY_ARRAY */
  234. short cf_bitsize;
  235. unsigned char cf_flags; /* BF_... */
  236. struct cfieldobject_s *cf_next;
  237. } CFieldObject;
  238. #define BS_REGULAR (-1) /* a regular field, not with bitshift */
  239. #define BS_EMPTY_ARRAY (-2) /* a field declared 'type[0]' or 'type[]' */
  240. #define BF_IGNORE_IN_CTOR 0x01 /* union field not in the first place */
  241. static PyTypeObject CTypeDescr_Type;
  242. static PyTypeObject CField_Type;
  243. static PyTypeObject CData_Type;
  244. static PyTypeObject CDataOwning_Type;
  245. static PyTypeObject CDataOwningGC_Type;
  246. static PyTypeObject CDataFromBuf_Type;
  247. static PyTypeObject CDataGCP_Type;
  248. #define CTypeDescr_Check(ob) (Py_TYPE(ob) == &CTypeDescr_Type)
  249. #define CData_Check(ob) (Py_TYPE(ob) == &CData_Type || \
  250. Py_TYPE(ob) == &CDataOwning_Type || \
  251. Py_TYPE(ob) == &CDataOwningGC_Type || \
  252. Py_TYPE(ob) == &CDataFromBuf_Type || \
  253. Py_TYPE(ob) == &CDataGCP_Type)
  254. #define CDataOwn_Check(ob) (Py_TYPE(ob) == &CDataOwning_Type || \
  255. Py_TYPE(ob) == &CDataOwningGC_Type)
  256. typedef union {
  257. unsigned char m_char;
  258. unsigned short m_short;
  259. unsigned int m_int;
  260. unsigned long m_long;
  261. unsigned long long m_longlong;
  262. float m_float;
  263. double m_double;
  264. } union_alignment;
  265. typedef struct {
  266. CDataObject head;
  267. union_alignment alignment;
  268. } CDataObject_casted_primitive;
  269. typedef struct {
  270. CDataObject head;
  271. union_alignment alignment;
  272. } CDataObject_own_nolength;
  273. typedef struct {
  274. CDataObject head;
  275. Py_ssize_t length;
  276. union_alignment alignment;
  277. } CDataObject_own_length;
  278. typedef struct {
  279. CDataObject head;
  280. PyObject *structobj; /* for ffi.new_handle() or ffi.new("struct *") */
  281. } CDataObject_own_structptr;
  282. typedef struct {
  283. CDataObject head;
  284. Py_ssize_t length; /* same as CDataObject_own_length up to here */
  285. Py_buffer *bufferview;
  286. } CDataObject_frombuf;
  287. typedef struct {
  288. CDataObject head;
  289. Py_ssize_t length; /* same as CDataObject_own_length up to here */
  290. PyObject *origobj;
  291. PyObject *destructor;
  292. } CDataObject_gcp;
  293. typedef struct {
  294. CDataObject head;
  295. ffi_closure *closure;
  296. } CDataObject_closure;
  297. typedef struct {
  298. ffi_cif cif;
  299. /* the following information is used when doing the call:
  300. - a buffer of size 'exchange_size' is malloced
  301. - the arguments are converted from Python objects to raw data
  302. - the i'th raw data is stored at 'buffer + exchange_offset_arg[1+i]'
  303. - the call is done
  304. - the result is read back from 'buffer + exchange_offset_arg[0]' */
  305. Py_ssize_t exchange_size;
  306. Py_ssize_t exchange_offset_arg[1];
  307. } cif_description_t;
  308. #define ADD_WRAPAROUND(x, y) ((Py_ssize_t)(((size_t)(x)) + ((size_t)(y))))
  309. #define MUL_WRAPAROUND(x, y) ((Py_ssize_t)(((size_t)(x)) * ((size_t)(y))))
  310. /* whenever running Python code, the errno is saved in this thread-local
  311. variable */
  312. #ifndef MS_WIN32
  313. # include "misc_thread_posix.h"
  314. #endif
  315. #include "minibuffer.h"
  316. #if PY_MAJOR_VERSION >= 3
  317. # include "file_emulator.h"
  318. #endif
  319. #ifdef PyUnicode_KIND /* Python >= 3.3 */
  320. # include "wchar_helper_3.h"
  321. #else
  322. # include "wchar_helper.h"
  323. #endif
  324. #include "../cffi/_cffi_errors.h"
  325. typedef struct _cffi_allocator_s {
  326. PyObject *ca_alloc, *ca_free;
  327. int ca_dont_clear;
  328. } cffi_allocator_t;
  329. static const cffi_allocator_t default_allocator = { NULL, NULL, 0 };
  330. static PyObject *FFIError;
  331. static PyObject *unique_cache;
  332. /************************************************************/
  333. static CTypeDescrObject *
  334. ctypedescr_new(int name_size)
  335. {
  336. CTypeDescrObject *ct = PyObject_GC_NewVar(CTypeDescrObject,
  337. &CTypeDescr_Type,
  338. name_size);
  339. if (ct == NULL)
  340. return NULL;
  341. ct->ct_itemdescr = NULL;
  342. ct->ct_stuff = NULL;
  343. ct->ct_weakreflist = NULL;
  344. ct->ct_unique_key = NULL;
  345. PyObject_GC_Track(ct);
  346. return ct;
  347. }
  348. static CTypeDescrObject *
  349. ctypedescr_new_on_top(CTypeDescrObject *ct_base, const char *extra_text,
  350. int extra_position)
  351. {
  352. int base_name_len = strlen(ct_base->ct_name);
  353. int extra_name_len = strlen(extra_text);
  354. CTypeDescrObject *ct = ctypedescr_new(base_name_len + extra_name_len + 1);
  355. char *p;
  356. if (ct == NULL)
  357. return NULL;
  358. Py_INCREF(ct_base);
  359. ct->ct_itemdescr = ct_base;
  360. ct->ct_name_position = ct_base->ct_name_position + extra_position;
  361. p = ct->ct_name;
  362. memcpy(p, ct_base->ct_name, ct_base->ct_name_position);
  363. p += ct_base->ct_name_position;
  364. memcpy(p, extra_text, extra_name_len);
  365. p += extra_name_len;
  366. memcpy(p, ct_base->ct_name + ct_base->ct_name_position,
  367. base_name_len - ct_base->ct_name_position + 1);
  368. return ct;
  369. }
  370. static PyObject *
  371. ctypedescr_repr(CTypeDescrObject *ct)
  372. {
  373. return PyText_FromFormat("<ctype '%s'>", ct->ct_name);
  374. }
  375. static void
  376. ctypedescr_dealloc(CTypeDescrObject *ct)
  377. {
  378. PyObject_GC_UnTrack(ct);
  379. if (ct->ct_weakreflist != NULL)
  380. PyObject_ClearWeakRefs((PyObject *) ct);
  381. if (ct->ct_unique_key != NULL) {
  382. /* revive dead object temporarily for DelItem */
  383. Py_SET_REFCNT(ct, 43);
  384. PyDict_DelItem(unique_cache, ct->ct_unique_key);
  385. assert(Py_REFCNT(ct) == 42);
  386. Py_SET_REFCNT(ct, 0);
  387. Py_DECREF(ct->ct_unique_key);
  388. }
  389. Py_XDECREF(ct->ct_itemdescr);
  390. Py_XDECREF(ct->ct_stuff);
  391. if (ct->ct_flags & CT_FUNCTIONPTR)
  392. PyObject_Free(ct->ct_extra);
  393. Py_TYPE(ct)->tp_free((PyObject *)ct);
  394. }
  395. static int
  396. ctypedescr_traverse(CTypeDescrObject *ct, visitproc visit, void *arg)
  397. {
  398. Py_VISIT(ct->ct_itemdescr);
  399. Py_VISIT(ct->ct_stuff);
  400. return 0;
  401. }
  402. static int
  403. ctypedescr_clear(CTypeDescrObject *ct)
  404. {
  405. Py_CLEAR(ct->ct_itemdescr);
  406. Py_CLEAR(ct->ct_stuff);
  407. return 0;
  408. }
  409. static PyObject *nosuchattr(const char *attr)
  410. {
  411. PyErr_SetString(PyExc_AttributeError, attr);
  412. return NULL;
  413. }
  414. static PyObject *ctypeget_kind(CTypeDescrObject *ct, void *context)
  415. {
  416. char *result;
  417. if (ct->ct_flags & CT_PRIMITIVE_ANY) {
  418. if (ct->ct_flags & CT_IS_ENUM)
  419. result = "enum";
  420. else
  421. result = "primitive";
  422. }
  423. else if (ct->ct_flags & CT_POINTER) {
  424. result = "pointer";
  425. }
  426. else if (ct->ct_flags & CT_ARRAY) {
  427. result = "array";
  428. }
  429. else if (ct->ct_flags & CT_VOID) {
  430. result = "void";
  431. }
  432. else if (ct->ct_flags & CT_STRUCT) {
  433. result = "struct";
  434. }
  435. else if (ct->ct_flags & CT_UNION) {
  436. result = "union";
  437. }
  438. else if (ct->ct_flags & CT_FUNCTIONPTR) {
  439. result = "function";
  440. }
  441. else
  442. result = "?";
  443. return PyText_FromString(result);
  444. }
  445. static PyObject *ctypeget_cname(CTypeDescrObject *ct, void *context)
  446. {
  447. return PyText_FromString(ct->ct_name);
  448. }
  449. static PyObject *ctypeget_item(CTypeDescrObject *ct, void *context)
  450. {
  451. if (ct->ct_flags & (CT_POINTER | CT_ARRAY)) {
  452. Py_INCREF(ct->ct_itemdescr);
  453. return (PyObject *)ct->ct_itemdescr;
  454. }
  455. return nosuchattr("item");
  456. }
  457. static PyObject *ctypeget_length(CTypeDescrObject *ct, void *context)
  458. {
  459. if (ct->ct_flags & CT_ARRAY) {
  460. if (ct->ct_length >= 0) {
  461. return PyInt_FromSsize_t(ct->ct_length);
  462. }
  463. else {
  464. Py_INCREF(Py_None);
  465. return Py_None;
  466. }
  467. }
  468. return nosuchattr("length");
  469. }
  470. static PyObject *
  471. get_field_name(CTypeDescrObject *ct, CFieldObject *cf); /* forward */
  472. /* returns 0 if the struct ctype is opaque, 1 if it is not, or -1 if
  473. an exception occurs */
  474. #define force_lazy_struct(ct) \
  475. ((ct)->ct_stuff != NULL ? 1 : do_realize_lazy_struct(ct))
  476. static int do_realize_lazy_struct(CTypeDescrObject *ct);
  477. /* forward, implemented in realize_c_type.c */
  478. static PyObject *ctypeget_fields(CTypeDescrObject *ct, void *context)
  479. {
  480. if (ct->ct_flags & (CT_STRUCT | CT_UNION)) {
  481. if (!(ct->ct_flags & CT_IS_OPAQUE)) {
  482. CFieldObject *cf;
  483. PyObject *res;
  484. if (force_lazy_struct(ct) < 0)
  485. return NULL;
  486. res = PyList_New(0);
  487. if (res == NULL)
  488. return NULL;
  489. for (cf = (CFieldObject *)ct->ct_extra;
  490. cf != NULL; cf = cf->cf_next) {
  491. PyObject *o = PyTuple_Pack(2, get_field_name(ct, cf),
  492. (PyObject *)cf);
  493. int err = (o != NULL) ? PyList_Append(res, o) : -1;
  494. Py_XDECREF(o);
  495. if (err < 0) {
  496. Py_DECREF(res);
  497. return NULL;
  498. }
  499. }
  500. return res;
  501. }
  502. else {
  503. Py_INCREF(Py_None);
  504. return Py_None;
  505. }
  506. }
  507. return nosuchattr("fields");
  508. }
  509. static PyObject *ctypeget_args(CTypeDescrObject *ct, void *context)
  510. {
  511. if (ct->ct_flags & CT_FUNCTIONPTR) {
  512. PyObject *t = ct->ct_stuff;
  513. return PyTuple_GetSlice(t, 2, PyTuple_GET_SIZE(t));
  514. }
  515. return nosuchattr("args");
  516. }
  517. static PyObject *ctypeget_result(CTypeDescrObject *ct, void *context)
  518. {
  519. if (ct->ct_flags & CT_FUNCTIONPTR) {
  520. PyObject *res = PyTuple_GetItem(ct->ct_stuff, 1);
  521. Py_XINCREF(res);
  522. return res;
  523. }
  524. return nosuchattr("result");
  525. }
  526. static PyObject *ctypeget_ellipsis(CTypeDescrObject *ct, void *context)
  527. {
  528. if (ct->ct_flags & CT_FUNCTIONPTR) {
  529. PyObject *res = ct->ct_extra ? Py_False : Py_True;
  530. Py_INCREF(res);
  531. return res;
  532. }
  533. return nosuchattr("ellipsis");
  534. }
  535. static PyObject *ctypeget_abi(CTypeDescrObject *ct, void *context)
  536. {
  537. if (ct->ct_flags & CT_FUNCTIONPTR) {
  538. PyObject *res = PyTuple_GetItem(ct->ct_stuff, 0);
  539. Py_XINCREF(res);
  540. return res;
  541. }
  542. return nosuchattr("abi");
  543. }
  544. static PyObject *ctypeget_elements(CTypeDescrObject *ct, void *context)
  545. {
  546. if (ct->ct_flags & CT_IS_ENUM) {
  547. PyObject *res = PyTuple_GetItem(ct->ct_stuff, 1);
  548. if (res) res = PyDict_Copy(res);
  549. return res;
  550. }
  551. return nosuchattr("elements");
  552. }
  553. static PyObject *ctypeget_relements(CTypeDescrObject *ct, void *context)
  554. {
  555. if (ct->ct_flags & CT_IS_ENUM) {
  556. PyObject *res = PyTuple_GetItem(ct->ct_stuff, 0);
  557. if (res) res = PyDict_Copy(res);
  558. return res;
  559. }
  560. return nosuchattr("relements");
  561. }
  562. static PyGetSetDef ctypedescr_getsets[] = {
  563. {"kind", (getter)ctypeget_kind, NULL, "kind"},
  564. {"cname", (getter)ctypeget_cname, NULL, "C name"},
  565. {"item", (getter)ctypeget_item, NULL, "pointer to, or array of"},
  566. {"length", (getter)ctypeget_length, NULL, "array length or None"},
  567. {"fields", (getter)ctypeget_fields, NULL, "struct or union fields"},
  568. {"args", (getter)ctypeget_args, NULL, "function argument types"},
  569. {"result", (getter)ctypeget_result, NULL, "function result type"},
  570. {"ellipsis", (getter)ctypeget_ellipsis, NULL, "function has '...'"},
  571. {"abi", (getter)ctypeget_abi, NULL, "function ABI"},
  572. {"elements", (getter)ctypeget_elements, NULL, "enum elements"},
  573. {"relements", (getter)ctypeget_relements, NULL, "enum elements, reverse"},
  574. {NULL} /* sentinel */
  575. };
  576. static PyObject *
  577. ctypedescr_dir(PyObject *ct, PyObject *noarg)
  578. {
  579. int err;
  580. struct PyGetSetDef *gsdef;
  581. PyObject *res = PyList_New(0);
  582. if (res == NULL)
  583. return NULL;
  584. for (gsdef = ctypedescr_getsets; gsdef->name; gsdef++) {
  585. PyObject *x = PyObject_GetAttrString(ct, gsdef->name);
  586. if (x == NULL) {
  587. PyErr_Clear();
  588. }
  589. else {
  590. Py_DECREF(x);
  591. x = PyText_FromString(gsdef->name);
  592. err = (x != NULL) ? PyList_Append(res, x) : -1;
  593. Py_XDECREF(x);
  594. if (err < 0) {
  595. Py_DECREF(res);
  596. return NULL;
  597. }
  598. }
  599. }
  600. return res;
  601. }
  602. static PyMethodDef ctypedescr_methods[] = {
  603. {"__dir__", ctypedescr_dir, METH_NOARGS},
  604. {NULL, NULL} /* sentinel */
  605. };
  606. static PyTypeObject CTypeDescr_Type = {
  607. PyVarObject_HEAD_INIT(NULL, 0)
  608. "_cffi_backend.CType",
  609. offsetof(CTypeDescrObject, ct_name),
  610. sizeof(char),
  611. (destructor)ctypedescr_dealloc, /* tp_dealloc */
  612. 0, /* tp_print */
  613. 0, /* tp_getattr */
  614. 0, /* tp_setattr */
  615. 0, /* tp_compare */
  616. (reprfunc)ctypedescr_repr, /* tp_repr */
  617. 0, /* tp_as_number */
  618. 0, /* tp_as_sequence */
  619. 0, /* tp_as_mapping */
  620. 0, /* tp_hash */
  621. 0, /* tp_call */
  622. 0, /* tp_str */
  623. PyObject_GenericGetAttr, /* tp_getattro */
  624. 0, /* tp_setattro */
  625. 0, /* tp_as_buffer */
  626. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  627. 0, /* tp_doc */
  628. (traverseproc)ctypedescr_traverse, /* tp_traverse */
  629. (inquiry)ctypedescr_clear, /* tp_clear */
  630. 0, /* tp_richcompare */
  631. offsetof(CTypeDescrObject, ct_weakreflist), /* tp_weaklistoffset */
  632. 0, /* tp_iter */
  633. 0, /* tp_iternext */
  634. ctypedescr_methods, /* tp_methods */
  635. 0, /* tp_members */
  636. ctypedescr_getsets, /* tp_getset */
  637. };
  638. /************************************************************/
  639. static PyObject *
  640. get_field_name(CTypeDescrObject *ct, CFieldObject *cf)
  641. {
  642. Py_ssize_t i = 0;
  643. PyObject *d_key, *d_value;
  644. while (PyDict_Next(ct->ct_stuff, &i, &d_key, &d_value)) {
  645. if (d_value == (PyObject *)cf)
  646. return d_key;
  647. }
  648. Py_FatalError("_cffi_backend: get_field_name()");
  649. return NULL;
  650. }
  651. static void
  652. cfield_dealloc(CFieldObject *cf)
  653. {
  654. Py_DECREF(cf->cf_type);
  655. PyObject_Del(cf);
  656. }
  657. #undef OFF
  658. #define OFF(x) offsetof(CFieldObject, x)
  659. static PyMemberDef cfield_members[] = {
  660. {"type", T_OBJECT, OFF(cf_type), READONLY},
  661. {"offset", T_PYSSIZET, OFF(cf_offset), READONLY},
  662. {"bitshift", T_SHORT, OFF(cf_bitshift), READONLY},
  663. {"bitsize", T_SHORT, OFF(cf_bitsize), READONLY},
  664. {"flags", T_UBYTE, OFF(cf_flags), READONLY},
  665. {NULL} /* Sentinel */
  666. };
  667. #undef OFF
  668. static PyTypeObject CField_Type = {
  669. PyVarObject_HEAD_INIT(NULL, 0)
  670. "_cffi_backend.CField",
  671. sizeof(CFieldObject),
  672. 0,
  673. (destructor)cfield_dealloc, /* tp_dealloc */
  674. 0, /* tp_print */
  675. 0, /* tp_getattr */
  676. 0, /* tp_setattr */
  677. 0, /* tp_compare */
  678. 0, /* tp_repr */
  679. 0, /* tp_as_number */
  680. 0, /* tp_as_sequence */
  681. 0, /* tp_as_mapping */
  682. 0, /* tp_hash */
  683. 0, /* tp_call */
  684. 0, /* tp_str */
  685. PyObject_GenericGetAttr, /* tp_getattro */
  686. 0, /* tp_setattro */
  687. 0, /* tp_as_buffer */
  688. Py_TPFLAGS_DEFAULT, /* tp_flags */
  689. 0, /* tp_doc */
  690. 0, /* tp_traverse */
  691. 0, /* tp_clear */
  692. 0, /* tp_richcompare */
  693. 0, /* tp_weaklistoffset */
  694. 0, /* tp_iter */
  695. 0, /* tp_iternext */
  696. 0, /* tp_methods */
  697. cfield_members, /* tp_members */
  698. };
  699. /************************************************************/
  700. static int
  701. CDataObject_Or_PyFloat_Check(PyObject *ob)
  702. {
  703. return (PyFloat_Check(ob) ||
  704. (CData_Check(ob) &&
  705. (((CDataObject *)ob)->c_type->ct_flags & CT_PRIMITIVE_FLOAT)));
  706. }
  707. static PY_LONG_LONG
  708. _my_PyLong_AsLongLong(PyObject *ob)
  709. {
  710. /* (possibly) convert and cast a Python object to a long long.
  711. Like PyLong_AsLongLong(), this version accepts a Python int too, and
  712. does convertions from other types of objects. The difference is that
  713. this version refuses floats. */
  714. #if PY_MAJOR_VERSION < 3
  715. if (PyInt_Check(ob)) {
  716. return PyInt_AS_LONG(ob);
  717. }
  718. else
  719. #endif
  720. if (PyLong_Check(ob)) {
  721. return PyLong_AsLongLong(ob);
  722. }
  723. else {
  724. PyObject *io;
  725. PY_LONG_LONG res;
  726. PyNumberMethods *nb = ob->ob_type->tp_as_number;
  727. if (CDataObject_Or_PyFloat_Check(ob) ||
  728. nb == NULL || nb->nb_int == NULL) {
  729. PyErr_SetString(PyExc_TypeError, "an integer is required");
  730. return -1;
  731. }
  732. io = (*nb->nb_int) (ob);
  733. if (io == NULL)
  734. return -1;
  735. if (PyIntOrLong_Check(io)) {
  736. res = _my_PyLong_AsLongLong(io);
  737. }
  738. else {
  739. PyErr_SetString(PyExc_TypeError, "integer conversion failed");
  740. res = -1;
  741. }
  742. Py_DECREF(io);
  743. return res;
  744. }
  745. }
  746. static unsigned PY_LONG_LONG
  747. _my_PyLong_AsUnsignedLongLong(PyObject *ob, int strict)
  748. {
  749. /* (possibly) convert and cast a Python object to an unsigned long long.
  750. Like PyLong_AsLongLong(), this version accepts a Python int too, and
  751. does convertions from other types of objects. If 'strict', complains
  752. with OverflowError and refuses floats. If '!strict', rounds floats
  753. and masks the result. */
  754. #if PY_MAJOR_VERSION < 3
  755. if (PyInt_Check(ob)) {
  756. long value1 = PyInt_AS_LONG(ob);
  757. if (strict && value1 < 0)
  758. goto negative;
  759. return (unsigned PY_LONG_LONG)(PY_LONG_LONG)value1;
  760. }
  761. else
  762. #endif
  763. if (PyLong_Check(ob)) {
  764. if (strict) {
  765. if (_PyLong_Sign(ob) < 0)
  766. goto negative;
  767. return PyLong_AsUnsignedLongLong(ob);
  768. }
  769. else {
  770. return PyLong_AsUnsignedLongLongMask(ob);
  771. }
  772. }
  773. else {
  774. PyObject *io;
  775. unsigned PY_LONG_LONG res;
  776. PyNumberMethods *nb = ob->ob_type->tp_as_number;
  777. if ((strict && CDataObject_Or_PyFloat_Check(ob)) ||
  778. nb == NULL || nb->nb_int == NULL) {
  779. PyErr_SetString(PyExc_TypeError, "an integer is required");
  780. return (unsigned PY_LONG_LONG)-1;
  781. }
  782. io = (*nb->nb_int) (ob);
  783. if (io == NULL)
  784. return (unsigned PY_LONG_LONG)-1;
  785. if (PyIntOrLong_Check(io)) {
  786. res = _my_PyLong_AsUnsignedLongLong(io, strict);
  787. }
  788. else {
  789. PyErr_SetString(PyExc_TypeError, "integer conversion failed");
  790. res = (unsigned PY_LONG_LONG)-1;
  791. }
  792. Py_DECREF(io);
  793. return res;
  794. }
  795. negative:
  796. PyErr_SetString(PyExc_OverflowError,
  797. "can't convert negative number to unsigned");
  798. return (unsigned PY_LONG_LONG)-1;
  799. }
  800. #define _read_raw_data(type) \
  801. do { \
  802. if (size == sizeof(type)) { \
  803. type r; \
  804. memcpy(&r, target, sizeof(type)); \
  805. return r; \
  806. } \
  807. } while(0)
  808. static PY_LONG_LONG
  809. read_raw_signed_data(char *target, int size)
  810. {
  811. _read_raw_data(signed char);
  812. _read_raw_data(short);
  813. _read_raw_data(int);
  814. _read_raw_data(long);
  815. _read_raw_data(PY_LONG_LONG);
  816. Py_FatalError("read_raw_signed_data: bad integer size");
  817. return 0;
  818. }
  819. static unsigned PY_LONG_LONG
  820. read_raw_unsigned_data(char *target, int size)
  821. {
  822. _read_raw_data(unsigned char);
  823. _read_raw_data(unsigned short);
  824. _read_raw_data(unsigned int);
  825. _read_raw_data(unsigned long);
  826. _read_raw_data(unsigned PY_LONG_LONG);
  827. Py_FatalError("read_raw_unsigned_data: bad integer size");
  828. return 0;
  829. }
  830. #ifdef __GNUC__
  831. /* This is a workaround for what I think is a GCC bug on several
  832. platforms. See issue #378. */
  833. __attribute__((noinline))
  834. #endif
  835. void _cffi_memcpy(char *target, const void *src, size_t size)
  836. {
  837. memcpy(target, src, size);
  838. }
  839. #define _write_raw_data(type) \
  840. do { \
  841. if (size == sizeof(type)) { \
  842. type r = (type)source; \
  843. _cffi_memcpy(target, &r, sizeof(type)); \
  844. return; \
  845. } \
  846. } while(0)
  847. static void
  848. write_raw_integer_data(char *target, unsigned PY_LONG_LONG source, int size)
  849. {
  850. _write_raw_data(unsigned char);
  851. _write_raw_data(unsigned short);
  852. _write_raw_data(unsigned int);
  853. _write_raw_data(unsigned long);
  854. _write_raw_data(unsigned PY_LONG_LONG);
  855. Py_FatalError("write_raw_integer_data: bad integer size");
  856. }
  857. static double
  858. read_raw_float_data(char *target, int size)
  859. {
  860. _read_raw_data(float);
  861. _read_raw_data(double);
  862. Py_FatalError("read_raw_float_data: bad float size");
  863. return 0;
  864. }
  865. static long double
  866. read_raw_longdouble_data(char *target)
  867. {
  868. int size = sizeof(long double);
  869. _read_raw_data(long double);
  870. Py_FatalError("read_raw_longdouble_data: bad long double size");
  871. return 0;
  872. }
  873. static Py_complex
  874. read_raw_complex_data(char *target, int size)
  875. {
  876. Py_complex r = {0.0, 0.0};
  877. if (size == 2*sizeof(float)) {
  878. float real_part, imag_part;
  879. memcpy(&real_part, target + 0, sizeof(float));
  880. memcpy(&imag_part, target + sizeof(float), sizeof(float));
  881. r.real = real_part;
  882. r.imag = imag_part;
  883. return r;
  884. }
  885. if (size == 2*sizeof(double)) {
  886. memcpy(&r, target, 2*sizeof(double));
  887. return r;
  888. }
  889. Py_FatalError("read_raw_complex_data: bad complex size");
  890. return r;
  891. }
  892. static void
  893. write_raw_float_data(char *target, double source, int size)
  894. {
  895. _write_raw_data(float);
  896. _write_raw_data(double);
  897. Py_FatalError("write_raw_float_data: bad float size");
  898. }
  899. static void
  900. write_raw_longdouble_data(char *target, long double source)
  901. {
  902. int size = sizeof(long double);
  903. _write_raw_data(long double);
  904. }
  905. #define _write_raw_complex_data(type) \
  906. do { \
  907. if (size == 2*sizeof(type)) { \
  908. type r = (type)source.real; \
  909. type i = (type)source.imag; \
  910. _cffi_memcpy(target, &r, sizeof(type)); \
  911. _cffi_memcpy(target+sizeof(type), &i, sizeof(type)); \
  912. return; \
  913. } \
  914. } while(0)
  915. static void
  916. write_raw_complex_data(char *target, Py_complex source, int size)
  917. {
  918. _write_raw_complex_data(float);
  919. _write_raw_complex_data(double);
  920. Py_FatalError("write_raw_complex_data: bad complex size");
  921. }
  922. static PyObject *
  923. new_simple_cdata(char *data, CTypeDescrObject *ct)
  924. {
  925. CDataObject *cd = PyObject_New(CDataObject, &CData_Type);
  926. if (cd == NULL)
  927. return NULL;
  928. Py_INCREF(ct);
  929. cd->c_data = data;
  930. cd->c_type = ct;
  931. cd->c_weakreflist = NULL;
  932. return (PyObject *)cd;
  933. }
  934. static PyObject *
  935. new_sized_cdata(char *data, CTypeDescrObject *ct, Py_ssize_t length)
  936. {
  937. CDataObject_own_length *scd;
  938. scd = (CDataObject_own_length *)PyObject_Malloc(
  939. offsetof(CDataObject_own_length, alignment));
  940. if (PyObject_Init((PyObject *)scd, &CData_Type) == NULL)
  941. return NULL;
  942. Py_INCREF(ct);
  943. scd->head.c_type = ct;
  944. scd->head.c_data = data;
  945. scd->head.c_weakreflist = NULL;
  946. scd->length = length;
  947. return (PyObject *)scd;
  948. }
  949. static CDataObject *_new_casted_primitive(CTypeDescrObject *ct); /*forward*/
  950. static PyObject *
  951. convert_to_object(char *data, CTypeDescrObject *ct)
  952. {
  953. if (!(ct->ct_flags & CT_PRIMITIVE_ANY)) {
  954. /* non-primitive types (check done just for performance) */
  955. if (ct->ct_flags & (CT_POINTER|CT_FUNCTIONPTR)) {
  956. char *ptrdata = *(char **)data;
  957. /*READ(data, sizeof(char *))*/
  958. return new_simple_cdata(ptrdata, ct);
  959. }
  960. else if (ct->ct_flags & CT_IS_OPAQUE) {
  961. PyErr_Format(PyExc_TypeError, "cdata '%s' is opaque",
  962. ct->ct_name);
  963. return NULL;
  964. }
  965. else if (ct->ct_flags & (CT_STRUCT|CT_UNION)) {
  966. return new_simple_cdata(data, ct);
  967. }
  968. else if (ct->ct_flags & CT_ARRAY) {
  969. if (ct->ct_length < 0) {
  970. /* we can't return a <cdata 'int[]'> here, because we don't
  971. know the length to give it. As a compromize, returns
  972. <cdata 'int *'> in this case. */
  973. ct = (CTypeDescrObject *)ct->ct_stuff;
  974. }
  975. return new_simple_cdata(data, ct);
  976. }
  977. }
  978. else if (ct->ct_flags & CT_PRIMITIVE_SIGNED) {
  979. PY_LONG_LONG value;
  980. /*READ(data, ct->ct_size)*/
  981. value = read_raw_signed_data(data, ct->ct_size);
  982. if (ct->ct_flags & CT_PRIMITIVE_FITS_LONG)
  983. return PyInt_FromLong((long)value);
  984. else
  985. return PyLong_FromLongLong(value);
  986. }
  987. else if (ct->ct_flags & CT_PRIMITIVE_UNSIGNED) {
  988. unsigned PY_LONG_LONG value;
  989. /*READ(data, ct->ct_size)*/
  990. value = read_raw_unsigned_data(data, ct->ct_size);
  991. if (ct->ct_flags & CT_PRIMITIVE_FITS_LONG) {
  992. if (ct->ct_flags & CT_IS_BOOL) {
  993. PyObject *x;
  994. switch ((int)value) {
  995. case 0: x = Py_False; break;
  996. case 1: x = Py_True; break;
  997. default:
  998. PyErr_Format(PyExc_ValueError,
  999. "got a _Bool of value %d, expected 0 or 1",
  1000. (int)value);
  1001. return NULL;
  1002. }
  1003. Py_INCREF(x);
  1004. return x;
  1005. }
  1006. return PyInt_FromLong((long)value);
  1007. }
  1008. else
  1009. return PyLong_FromUnsignedLongLong(value);
  1010. }
  1011. else if (ct->ct_flags & CT_PRIMITIVE_FLOAT) {
  1012. /*READ(data, ct->ct_size)*/
  1013. if (!(ct->ct_flags & CT_IS_LONGDOUBLE)) {
  1014. double value = read_raw_float_data(data, ct->ct_size);
  1015. return PyFloat_FromDouble(value);
  1016. }
  1017. else {
  1018. long double value = read_raw_longdouble_data(data);
  1019. CDataObject *cd = _new_casted_primitive(ct);
  1020. if (cd != NULL)
  1021. write_raw_longdouble_data(cd->c_data, value);
  1022. return (PyObject *)cd;
  1023. }
  1024. }
  1025. else if (ct->ct_flags & CT_PRIMITIVE_CHAR) {
  1026. /*READ(data, ct->ct_size)*/
  1027. switch (ct->ct_size) {
  1028. case sizeof(char):
  1029. return PyBytes_FromStringAndSize(data, 1);
  1030. case 2:
  1031. return _my_PyUnicode_FromChar16((cffi_char16_t *)data, 1);
  1032. case 4:
  1033. return _my_PyUnicode_FromChar32((cffi_char32_t *)data, 1);
  1034. }
  1035. }
  1036. else if (ct->ct_flags & CT_PRIMITIVE_COMPLEX) {
  1037. Py_complex value = read_raw_complex_data(data, ct->ct_size);
  1038. return PyComplex_FromCComplex(value);
  1039. }
  1040. PyErr_Format(PyExc_SystemError,
  1041. "convert_to_object: '%s'", ct->ct_name);
  1042. return NULL;
  1043. }
  1044. static PyObject *
  1045. convert_to_object_bitfield(char *data, CFieldObject *cf)
  1046. {
  1047. CTypeDescrObject *ct = cf->cf_type;
  1048. /*READ(data, ct->ct_size)*/
  1049. if (ct->ct_flags & CT_PRIMITIVE_SIGNED) {
  1050. unsigned PY_LONG_LONG value, valuemask, shiftforsign;
  1051. PY_LONG_LONG result;
  1052. value = (unsigned PY_LONG_LONG)read_raw_signed_data(data, ct->ct_size);
  1053. valuemask = (1ULL << cf->cf_bitsize) - 1ULL;
  1054. shiftforsign = 1ULL << (cf->cf_bitsize - 1);
  1055. value = ((value >> cf->cf_bitshift) + shiftforsign) & valuemask;
  1056. result = ((PY_LONG_LONG)value) - (PY_LONG_LONG)shiftforsign;
  1057. if (ct->ct_flags & CT_PRIMITIVE_FITS_LONG)
  1058. return PyInt_FromLong((long)result);
  1059. else
  1060. return PyLong_FromLongLong(result);
  1061. }
  1062. else {
  1063. unsigned PY_LONG_LONG value, valuemask;
  1064. value = read_raw_unsigned_data(data, ct->ct_size);
  1065. valuemask = (1ULL << cf->cf_bitsize) - 1ULL;
  1066. value = (value >> cf->cf_bitshift) & valuemask;
  1067. if (ct->ct_flags & CT_PRIMITIVE_FITS_LONG)
  1068. return PyInt_FromLong((long)value);
  1069. else
  1070. return PyLong_FromUnsignedLongLong(value);
  1071. }
  1072. }
  1073. static int _convert_overflow(PyObject *init, const char *ct_name)
  1074. {
  1075. PyObject *s;
  1076. if (PyErr_Occurred()) /* already an exception pending */
  1077. return -1;
  1078. s = PyObject_Str(init);
  1079. if (s == NULL)
  1080. return -1;
  1081. PyErr_Format(PyExc_OverflowError, "integer %s does not fit '%s'",
  1082. PyText_AS_UTF8(s), ct_name);
  1083. Py_DECREF(s);
  1084. return -1;
  1085. }
  1086. static int _convert_to_char(PyObject *init)
  1087. {
  1088. if (PyBytes_Check(init) && PyBytes_GET_SIZE(init) == 1) {
  1089. return (unsigned char)(PyBytes_AS_STRING(init)[0]);
  1090. }
  1091. if (CData_Check(init) &&
  1092. (((CDataObject *)init)->c_type->ct_flags & CT_PRIMITIVE_CHAR) &&
  1093. (((CDataObject *)init)->c_type->ct_size == sizeof(char))) {
  1094. char *data = ((CDataObject *)init)->c_data;
  1095. /*READ(data, 1)*/
  1096. return *(unsigned char *)data;
  1097. }
  1098. PyErr_Format(PyExc_TypeError,
  1099. "initializer for ctype 'char' must be a "STR_OR_BYTES
  1100. " of length 1, not %.200s", Py_TYPE(init)->tp_name);
  1101. return -1;
  1102. }
  1103. static cffi_char16_t _convert_to_char16_t(PyObject *init)
  1104. {
  1105. char err_got[80];
  1106. err_got[0] = 0;
  1107. if (PyUnicode_Check(init)) {
  1108. cffi_char16_t ordinal;
  1109. if (_my_PyUnicode_AsSingleChar16(init, &ordinal, err_got) == 0)
  1110. return ordinal;
  1111. }
  1112. if (CData_Check(init) &&
  1113. (((CDataObject *)init)->c_type->ct_flags & CT_PRIMITIVE_CHAR) &&
  1114. (((CDataObject *)init)->c_type->ct_size == 2)) {
  1115. char *data = ((CDataObject *)init)->c_data;
  1116. /*READ(data, 2)*/
  1117. return *(cffi_char16_t *)data;
  1118. }
  1119. PyErr_Format(PyExc_TypeError,
  1120. "initializer for ctype 'char16_t' must be a unicode string "
  1121. "of length 1, not %.200s",
  1122. err_got[0] == 0 ? Py_TYPE(init)->tp_name : err_got);
  1123. return (cffi_char16_t)-1;
  1124. }
  1125. static cffi_char32_t _convert_to_char32_t(PyObject *init)
  1126. {
  1127. char err_got[80];
  1128. err_got[0] = 0;
  1129. if (PyUnicode_Check(init)) {
  1130. cffi_char32_t ordinal;
  1131. if (_my_PyUnicode_AsSingleChar32(init, &ordinal, err_got) == 0)
  1132. return ordinal;
  1133. }
  1134. if (CData_Check(init) &&
  1135. (((CDataObject *)init)->c_type->ct_flags & CT_PRIMITIVE_CHAR) &&
  1136. (((CDataObject *)init)->c_type->ct_size == 4)) {
  1137. char *data = ((CDataObject *)init)->c_data;
  1138. /*READ(data, 4)*/
  1139. return *(cffi_char32_t *)data;
  1140. }
  1141. PyErr_Format(PyExc_TypeError,
  1142. "initializer for ctype 'char32_t' must be a unicode string "
  1143. "of length 1, not %.200s",
  1144. err_got[0] == 0 ? Py_TYPE(init)->tp_name : err_got);
  1145. return (cffi_char32_t)-1;
  1146. }
  1147. static int _convert_error(PyObject *init, CTypeDescrObject *ct,
  1148. const char *expected)
  1149. {
  1150. if (CData_Check(init)) {
  1151. CTypeDescrObject *ct2 = ((CDataObject *)init)->c_type;
  1152. if (strcmp(ct->ct_name, ct2->ct_name) != 0)
  1153. PyErr_Format(PyExc_TypeError,
  1154. "initializer for ctype '%s' must be a %s, "
  1155. "not cdata '%s'",
  1156. ct->ct_name, expected, ct2->ct_name);
  1157. else if (ct != ct2) {
  1158. /* in case we'd give the error message "initializer for
  1159. ctype 'A' must be a pointer to same type, not cdata
  1160. 'B'", but with A=B, then give instead a different error
  1161. message to try to clear up the confusion */
  1162. PyErr_Format(PyExc_TypeError,
  1163. "initializer for ctype '%s' appears indeed to be '%s',"
  1164. " but the types are different (check that you are not"
  1165. " e.g. mixing up different ffi instances)",
  1166. ct->ct_name, ct2->ct_name);
  1167. }
  1168. else
  1169. {
  1170. PyErr_Format(PyExc_SystemError,
  1171. "initializer for ctype '%s' is correct, but we get "
  1172. "an internal mismatch--please report a bug",
  1173. ct->ct_name);
  1174. }
  1175. }
  1176. else
  1177. PyErr_Format(PyExc_TypeError,
  1178. "initializer for ctype '%s' must be a %s, "
  1179. "not %.200s",
  1180. ct->ct_name, expected, Py_TYPE(init)->tp_name);
  1181. return -1;
  1182. }
  1183. static int /* forward */
  1184. convert_from_object(char *data, CTypeDescrObject *ct, PyObject *init);
  1185. static int /* forward */
  1186. convert_from_object_bitfield(char *data, CFieldObject *cf, PyObject *init);
  1187. static Py_ssize_t
  1188. get_new_array_length(CTypeDescrObject *ctitem, PyObject **pvalue)
  1189. {
  1190. PyObject *value = *pvalue;
  1191. if (PyList_Check(value) || PyTuple_Check(value)) {
  1192. return PySequence_Fast_GET_SIZE(value);
  1193. }
  1194. else if (PyBytes_Check(value)) {
  1195. /* from a string, we add the null terminator */
  1196. return PyBytes_GET_SIZE(value) + 1;
  1197. }
  1198. else if (PyUnicode_Check(value)) {
  1199. /* from a unicode, we add the null terminator */
  1200. int length;
  1201. if (ctitem->ct_size == 2)
  1202. length = _my_PyUnicode_SizeAsChar16(value);
  1203. else
  1204. length = _my_PyUnicode_SizeAsChar32(value);
  1205. return length + 1;
  1206. }
  1207. else {
  1208. Py_ssize_t explicitlength;
  1209. explicitlength = PyNumber_AsSsize_t(value, PyExc_OverflowError);
  1210. if (explicitlength < 0) {
  1211. if (PyErr_Occurred()) {
  1212. if (PyErr_ExceptionMatches(PyExc_TypeError))
  1213. PyErr_Format(PyExc_TypeError,
  1214. "expected new array length or list/tuple/str, "
  1215. "not %.200s", Py_TYPE(value)->tp_name);
  1216. }
  1217. else
  1218. PyErr_SetString(PyExc_ValueError, "negative array length");
  1219. return -1;
  1220. }
  1221. *pvalue = Py_None;
  1222. return explicitlength;
  1223. }
  1224. }
  1225. static int
  1226. convert_field_from_object(char *data, CFieldObject *cf, PyObject *value)
  1227. {
  1228. data += cf->cf_offset;
  1229. if (cf->cf_bitshift >= 0)
  1230. return convert_from_object_bitfield(data, cf, value);
  1231. else
  1232. return convert_from_object(data, cf->cf_type, value);
  1233. }
  1234. static int
  1235. add_varsize_length(Py_ssize_t offset, Py_ssize_t itemsize,
  1236. Py_ssize_t varsizelength, Py_ssize_t *optvarsize)
  1237. {
  1238. /* update '*optvarsize' to account for an array of 'varsizelength'
  1239. elements, each of size 'itemsize', that starts at 'offset'. */
  1240. Py_ssize_t size = ADD_WRAPAROUND(offset,
  1241. MUL_WRAPAROUND(itemsize, varsizelength));
  1242. if (size < 0 ||
  1243. ((size - offset) / itemsize) != varsizelength) {
  1244. PyErr_SetString(PyExc_OverflowError,
  1245. "array size would overflow a Py_ssize_t");
  1246. return -1;
  1247. }
  1248. if (size > *optvarsize)
  1249. *optvarsize = size;
  1250. return 0;
  1251. }
  1252. static int
  1253. convert_struct_from_object(char *data, CTypeDescrObject *ct, PyObject *init,
  1254. Py_ssize_t *optvarsize); /* forward */
  1255. static int
  1256. convert_vfield_from_object(char *data, CFieldObject *cf, PyObject *value,
  1257. Py_ssize_t *optvarsize)
  1258. {
  1259. /* a special case for var-sized C99 arrays */
  1260. if ((cf->cf_type->ct_flags & CT_ARRAY) && cf->cf_type->ct_size < 0) {
  1261. Py_ssize_t varsizelength = get_new_array_length(
  1262. cf->cf_type->ct_itemdescr, &value);
  1263. if (varsizelength < 0)
  1264. return -1;
  1265. if (optvarsize != NULL) {
  1266. /* in this mode, the only purpose of this function is to compute
  1267. the real size of the structure from a var-sized C99 array */
  1268. assert(data == NULL);
  1269. return add_varsize_length(cf->cf_offset,
  1270. cf->cf_type->ct_itemdescr->ct_size,
  1271. varsizelength,
  1272. optvarsize);
  1273. }
  1274. /* if 'value' was only an integer, get_new_array_length() returns
  1275. it and convert 'value' to be None. Detect if this was the case,
  1276. and if so, stop here, leaving the content uninitialized
  1277. (it should be zero-initialized from somewhere else). */
  1278. if (value == Py_None)
  1279. return 0;
  1280. }
  1281. if (optvarsize == NULL) {
  1282. return convert_field_from_object(data, cf, value);
  1283. }
  1284. else if ((cf->cf_type->ct_flags & CT_WITH_VAR_ARRAY) != 0 &&
  1285. !CData_Check(value)) {
  1286. Py_ssize_t subsize = cf->cf_type->ct_size;
  1287. if (convert_struct_from_object(NULL, cf->cf_type, value, &subsize) < 0)
  1288. return -1;
  1289. return add_varsize_length(cf->cf_offset, 1, subsize, optvarsize);
  1290. }
  1291. else
  1292. return 0;
  1293. }
  1294. static int
  1295. must_be_array_of_zero_or_one(const char *data, Py_ssize_t n)
  1296. {
  1297. Py_ssize_t i;
  1298. for (i = 0; i < n; i++) {
  1299. if (((unsigned char)data[i]) > 1) {
  1300. PyErr_SetString(PyExc_ValueError,
  1301. "an array of _Bool can only contain \\x00 or \\x01");
  1302. return -1;
  1303. }
  1304. }
  1305. return 0;
  1306. }
  1307. static Py_ssize_t
  1308. get_array_length(CDataObject *cd)
  1309. {
  1310. if (cd->c_type->ct_length < 0)
  1311. return ((CDataObject_own_length *)cd)->length;
  1312. else
  1313. return cd->c_type->ct_length;
  1314. }
  1315. static int
  1316. convert_array_from_object(char *data, CTypeDescrObject *ct, PyObject *init)
  1317. {
  1318. /* used by convert_from_object(), and also to decode lists/tuples/unicodes
  1319. passed as function arguments. 'ct' is an CT_ARRAY in the first case
  1320. and a CT_POINTER in the second case. */
  1321. const char *expected;
  1322. CTypeDescrObject *ctitem = ct->ct_itemdescr;
  1323. if (PyList_Check(init) || PyTuple_Check(init)) {
  1324. PyObject **items;
  1325. Py_ssize_t i, n;
  1326. n = PySequence_Fast_GET_SIZE(init);
  1327. if (ct->ct_length >= 0 && n > ct->ct_length) {
  1328. PyErr_Format(PyExc_IndexError,
  1329. "too many initializers for '%s' (got %zd)",
  1330. ct->ct_name, n);
  1331. return -1;
  1332. }
  1333. items = PySequence_Fast_ITEMS(init);
  1334. for (i=0; i<n; i++) {
  1335. if (convert_from_object(data, ctitem, items[i]) < 0)
  1336. return -1;
  1337. data += ctitem->ct_size;
  1338. }
  1339. return 0;
  1340. }
  1341. else if ((ctitem->ct_flags & CT_PRIMITIVE_CHAR) ||
  1342. ((ctitem->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_UNSIGNED))
  1343. && (ctitem->ct_size == sizeof(char)))) {
  1344. if (ctitem->ct_size == sizeof(char)) {
  1345. char *srcdata;
  1346. Py_ssize_t n;
  1347. if (!PyBytes_Check(init)) {
  1348. expected = STR_OR_BYTES" or list or tuple";
  1349. goto cannot_convert;
  1350. }
  1351. n = PyBytes_GET_SIZE(init);
  1352. if (ct->ct_length >= 0 && n > ct->ct_length) {
  1353. PyErr_Format(PyExc_IndexError,
  1354. "initializer "STR_OR_BYTES" is too long for '%s' "
  1355. "(got %zd characters)", ct->ct_name, n);
  1356. return -1;
  1357. }
  1358. if (n != ct->ct_length)
  1359. n++;
  1360. srcdata = PyBytes_AS_STRING(init);
  1361. if (ctitem->ct_flags & CT_IS_BOOL)
  1362. if (must_be_array_of_zero_or_one(srcdata, n) < 0)
  1363. return -1;
  1364. memcpy(data, srcdata, n);
  1365. return 0;
  1366. }
  1367. else {
  1368. Py_ssize_t n;
  1369. if (!PyUnicode_Check(init)) {
  1370. expected = "unicode or list or tuple";
  1371. goto cannot_convert;
  1372. }
  1373. if (ctitem->ct_size == 4)
  1374. n = _my_PyUnicode_SizeAsChar32(init);
  1375. else
  1376. n = _my_PyUnicode_SizeAsChar16(init);
  1377. if (ct->ct_length >= 0 && n > ct->ct_length) {
  1378. PyErr_Format(PyExc_IndexError,
  1379. "initializer unicode is too long for '%s' "
  1380. "(got %zd characters)", ct->ct_name, n);
  1381. return -1;
  1382. }
  1383. if (n != ct->ct_length)
  1384. n++;
  1385. if (ctitem->ct_size == 4)
  1386. return _my_PyUnicode_AsChar32(init, (cffi_char32_t *)data, n);
  1387. else
  1388. return _my_PyUnicode_AsChar16(init, (cffi_char16_t *)data, n);
  1389. }
  1390. }
  1391. else {
  1392. expected = "list or tuple";
  1393. goto cannot_convert;
  1394. }
  1395. cannot_convert:
  1396. if ((ct->ct_flags & CT_ARRAY) && CData_Check(init))
  1397. {
  1398. CDataObject *cd = (CDataObject *)init;
  1399. if (cd->c_type == ct)
  1400. {
  1401. Py_ssize_t n = get_array_length(cd);
  1402. memcpy(data, cd->c_data, n * ctitem->ct_size);
  1403. return 0;
  1404. }
  1405. }
  1406. return _convert_error(init, ct, expected);
  1407. }
  1408. static int
  1409. convert_struct_from_object(char *data, CTypeDescrObject *ct, PyObject *init,
  1410. Py_ssize_t *optvarsize)
  1411. {
  1412. /* does not accept 'init' being already a CData */
  1413. const char *expected;
  1414. if (force_lazy_struct(ct) <= 0) {
  1415. if (!PyErr_Occurred())
  1416. PyErr_Format(PyExc_TypeError, "'%s' is opaque", ct->ct_name);
  1417. return -1;
  1418. }
  1419. if (PyList_Check(init) || PyTuple_Check(init)) {
  1420. PyObject **items = PySequence_Fast_ITEMS(init);
  1421. Py_ssize_t i, n = PySequence_Fast_GET_SIZE(init);
  1422. CFieldObject *cf = (CFieldObject *)ct->ct_extra;
  1423. for (i=0; i<n; i++) {
  1424. while (cf != NULL && (cf->cf_flags & BF_IGNORE_IN_CTOR))
  1425. cf = cf->cf_next;
  1426. if (cf == NULL) {
  1427. PyErr_Format(PyExc_ValueError,
  1428. "too many initializers for '%s' (got %zd)",
  1429. ct->ct_name, n);
  1430. return -1;
  1431. }
  1432. if (convert_vfield_from_object(data, cf, items[i], optvarsize) < 0)
  1433. return -1;
  1434. cf = cf->cf_next;
  1435. }
  1436. return 0;
  1437. }
  1438. if (PyDict_Check(init)) {
  1439. PyObject *d_key, *d_value;
  1440. Py_ssize_t i = 0;
  1441. CFieldObject *cf;
  1442. while (PyDict_Next(init, &i, &d_key, &d_value)) {
  1443. cf = (CFieldObject *)PyDict_GetItem(ct->ct_stuff, d_key);
  1444. if (cf == NULL) {
  1445. PyErr_SetObject(PyExc_KeyError, d_key);
  1446. return -1;
  1447. }
  1448. if (convert_vfield_from_object(data, cf, d_value, optvarsize) < 0)
  1449. return -1;
  1450. }
  1451. return 0;
  1452. }
  1453. expected = optvarsize == NULL ? "list or tuple or dict or struct-cdata"
  1454. : "list or tuple or dict";
  1455. return _convert_error(init, ct, expected);
  1456. }
  1457. #ifdef __GNUC__
  1458. # if __GNUC__ >= 4
  1459. /* Don't go inlining this huge function. Needed because occasionally
  1460. it gets inlined in places where is causes a warning: call to
  1461. __builtin___memcpy_chk will always overflow destination buffer
  1462. (which is places where the 'ct' should never represent such a large
  1463. primitive type anyway). */
  1464. __attribute__((noinline))
  1465. # endif
  1466. #endif
  1467. static int
  1468. convert_from_object(char *data, CTypeDescrObject *ct, PyObject *init)
  1469. {
  1470. const char *expected;
  1471. char buf[sizeof(PY_LONG_LONG)];
  1472. /*if (ct->ct_size > 0)*/
  1473. /*WRITE(data, ct->ct_size)*/
  1474. if (ct->ct_flags & CT_ARRAY) {
  1475. return convert_array_from_object(data, ct, init);
  1476. }
  1477. if (ct->ct_flags & (CT_POINTER|CT_FUNCTIONPTR)) {
  1478. char *ptrdata;
  1479. CTypeDescrObject *ctinit;
  1480. if (!CData_Check(init)) {
  1481. expected = "cdata pointer";
  1482. goto cannot_convert;
  1483. }
  1484. ctinit = ((CDataObject *)init)->c_type;
  1485. if (!(ctinit->ct_flags & (CT_POINTER|CT_FUNCTIONPTR))) {
  1486. if (ctinit->ct_flags & CT_ARRAY)
  1487. ctinit = (CTypeDescrObject *)ctinit->ct_stuff;
  1488. else {
  1489. expected = "pointer or array";
  1490. goto cannot_convert;
  1491. }
  1492. }
  1493. if (ctinit != ct) {
  1494. int combined_flags = ct->ct_flags | ctinit->ct_flags;
  1495. if (combined_flags & CT_IS_VOID_PTR)
  1496. ; /* accept "void *" as either source or target */
  1497. else if (combined_flags & CT_IS_VOIDCHAR_PTR) {
  1498. /* for backward compatibility, accept "char *" as either
  1499. source of target. This is not what C does, though,
  1500. so emit a warning that will eventually turn into an
  1501. error. The warning is turned off if both types are
  1502. pointers to single bytes. */
  1503. char *msg = (ct->ct_flags & CT_IS_VOIDCHAR_PTR ?
  1504. "implicit cast to 'char *' from a different pointer type: "
  1505. "will be forbidden in the future (check that the types "
  1506. "are as you expect; use an explicit ffi.cast() if they "
  1507. "are correct)" :
  1508. "implicit cast from 'char *' to a different pointer type: "
  1509. "will be forbidden in the future (check that the types "
  1510. "are as you expect; use an explicit ffi.cast() if they "
  1511. "are correct)");
  1512. if ((ct->ct_flags & ctinit->ct_flags & CT_POINTER) &&
  1513. ct->ct_itemdescr->ct_size == 1 &&
  1514. ctinit->ct_itemdescr->ct_size == 1) {
  1515. /* no warning */
  1516. }
  1517. else if (PyErr_WarnEx(PyExc_UserWarning, msg, 1))
  1518. return -1;
  1519. }
  1520. else {
  1521. expected = "pointer to same type";
  1522. goto cannot_convert;
  1523. }
  1524. }
  1525. ptrdata = ((CDataObject *)init)->c_data;
  1526. *(char **)data = ptrdata;
  1527. return 0;
  1528. }
  1529. if (ct->ct_flags & CT_PRIMITIVE_SIGNED) {
  1530. PY_LONG_LONG value = _my_PyLong_AsLongLong(init);
  1531. if (value == -1 && PyErr_Occurred())
  1532. return -1;
  1533. write_raw_integer_data(buf, value, ct->ct_size);
  1534. if (value != read_raw_signed_data(buf, ct->ct_size))
  1535. goto overflow;
  1536. write_raw_integer_data(data, value, ct->ct_size);
  1537. return 0;
  1538. }
  1539. if (ct->ct_flags & CT_PRIMITIVE_UNSIGNED) {
  1540. unsigned PY_LONG_LONG value = _my_PyLong_AsUnsignedLongLong(init, 1);
  1541. if (value == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
  1542. return -1;
  1543. if (ct->ct_flags & CT_IS_BOOL) {
  1544. if (value > 1ULL) /* value != 0 && value != 1 */
  1545. goto overflow;
  1546. }
  1547. else {
  1548. write_raw_integer_data(buf, value, ct->ct_size);
  1549. if (value != read_raw_unsigned_data(buf, ct->ct_size))
  1550. goto overflow;
  1551. }
  1552. write_raw_integer_data(data, value, ct->ct_size);
  1553. return 0;
  1554. }
  1555. if (ct->ct_flags & CT_PRIMITIVE_FLOAT) {
  1556. double value;
  1557. if ((ct->ct_flags & CT_IS_LONGDOUBLE) &&
  1558. CData_Check(init) &&
  1559. (((CDataObject *)init)->c_type->ct_flags & CT_IS_LONGDOUBLE)) {
  1560. long double lvalue;
  1561. char *initdata = ((CDataObject *)init)->c_data;
  1562. /*READ(initdata, sizeof(long double))*/
  1563. lvalue = read_raw_longdouble_data(initdata);
  1564. write_raw_longdouble_data(data, lvalue);
  1565. return 0;
  1566. }
  1567. value = PyFloat_AsDouble(init);
  1568. if (value == -1.0 && PyErr_Occurred())
  1569. return -1;
  1570. if (!(ct->ct_flags & CT_IS_LONGDOUBLE))
  1571. write_raw_float_data(data, value, ct->ct_size);
  1572. else
  1573. write_raw_longdouble_data(data, (long double)value);
  1574. return 0;
  1575. }
  1576. if (ct->ct_flags & CT_PRIMITIVE_CHAR) {
  1577. switch (ct->ct_size) {
  1578. case sizeof(char): {
  1579. int res = _convert_to_char(init);
  1580. if (res < 0)
  1581. return -1;
  1582. data[0] = res;
  1583. return 0;
  1584. }
  1585. case 2: {
  1586. cffi_char16_t res = _convert_to_char16_t(init);
  1587. if (res == (cffi_char16_t)-1 && PyErr_Occurred())
  1588. return -1;
  1589. *(cffi_char16_t *)data = res;
  1590. return 0;
  1591. }
  1592. case 4: {
  1593. cffi_char32_t res = _convert_to_char32_t(init);
  1594. if (res == (cffi_char32_t)-1 && PyErr_Occurred())
  1595. return -1;
  1596. *(cffi_char32_t *)data = res;
  1597. return 0;
  1598. }
  1599. }
  1600. }
  1601. if (ct->ct_flags & (CT_STRUCT|CT_UNION)) {
  1602. if (CData_Check(init)) {
  1603. if (((CDataObject *)init)->c_type == ct && ct->ct_size >= 0) {
  1604. memcpy(data, ((CDataObject *)init)->c_data, ct->ct_size);
  1605. return 0;
  1606. }
  1607. }
  1608. return convert_struct_from_object(data, ct, init, NULL);
  1609. }
  1610. if (ct->ct_flags & CT_PRIMITIVE_COMPLEX) {
  1611. Py_complex value = PyComplex_AsCComplex(init);
  1612. if (PyErr_Occurred())
  1613. return -1;
  1614. write_raw_complex_data(data, value, ct->ct_size);
  1615. return 0;
  1616. }
  1617. PyErr_Format(PyExc_SystemError,
  1618. "convert_from_object: '%s'", ct->ct_name);
  1619. return -1;
  1620. overflow:
  1621. return _convert_overflow(init, ct->ct_name);
  1622. cannot_convert:
  1623. return _convert_error(init, ct, expected);
  1624. }
  1625. static int
  1626. convert_from_object_bitfield(char *data, CFieldObject *cf, PyObject *init)
  1627. {
  1628. CTypeDescrObject *ct = cf->cf_type;
  1629. PY_LONG_LONG fmin, fmax, value = PyLong_AsLongLong(init);
  1630. unsigned PY_LONG_LONG rawfielddata, rawvalue, rawmask;
  1631. if (value == -1 && PyErr_Occurred())
  1632. return -1;
  1633. if (ct->ct_flags & CT_PRIMITIVE_SIGNED) {
  1634. fmin = -(1LL << (cf->cf_bitsize-1));
  1635. fmax = (1LL << (cf->cf_bitsize-1)) - 1LL;
  1636. if (fmax == 0)
  1637. fmax = 1; /* special case to let "int x:1" receive "1" */
  1638. }
  1639. else {
  1640. fmin = 0LL;
  1641. fmax = (PY_LONG_LONG)((1ULL << cf->cf_bitsize) - 1ULL);
  1642. }
  1643. if (value < fmin || value > fmax) {
  1644. /* phew, PyErr_Format does not support "%lld" in Python 2.6 */
  1645. PyObject *svalue = NULL, *sfmin = NULL, *sfmax = NULL;
  1646. PyObject *lfmin = NULL, *lfmax = NULL;
  1647. svalue = PyObject_Str(init);
  1648. if (svalue == NULL) goto skip;
  1649. lfmin = PyLong_FromLongLong(fmin);
  1650. if (lfmin == NULL) goto skip;
  1651. sfmin = PyObject_Str(lfmin);
  1652. if (sfmin == NULL) goto skip;
  1653. lfmax = PyLong_FromLongLong(fmax);
  1654. if (lfmax == NULL) goto skip;
  1655. sfmax = PyObject_Str(lfmax);
  1656. if (sfmax == NULL) goto skip;
  1657. PyErr_Format(PyExc_OverflowError,
  1658. "value %s outside the range allowed by the "
  1659. "bit field width: %s <= x <= %s",
  1660. PyText_AS_UTF8(svalue),
  1661. PyText_AS_UTF8(sfmin),
  1662. PyText_AS_UTF8(sfmax));
  1663. skip:
  1664. Py_XDECREF(svalue);
  1665. Py_XDECREF(sfmin);
  1666. Py_XDECREF(sfmax);
  1667. Py_XDECREF(lfmin);
  1668. Py_XDECREF(lfmax);
  1669. return -1;
  1670. }
  1671. rawmask = ((1ULL << cf->cf_bitsize) - 1ULL) << cf->cf_bitshift;
  1672. rawvalue = ((unsigned PY_LONG_LONG)value) << cf->cf_bitshift;
  1673. /*WRITE(data, ct->ct_size)*/
  1674. rawfielddata = read_raw_unsigned_data(data, ct->ct_size);
  1675. rawfielddata = (rawfielddata & ~rawmask) | (rawvalue & rawmask);
  1676. write_raw_integer_data(data, rawfielddata, ct->ct_size);
  1677. return 0;
  1678. }
  1679. static int
  1680. get_alignment(CTypeDescrObject *ct)
  1681. {
  1682. int align;
  1683. retry:
  1684. if ((ct->ct_flags & (CT_PRIMITIVE_ANY|CT_STRUCT|CT_UNION)) &&
  1685. !(ct->ct_flags & CT_IS_OPAQUE)) {
  1686. align = ct->ct_length;
  1687. if (align == -1 && (ct->ct_flags & CT_LAZY_FIELD_LIST)) {
  1688. force_lazy_struct(ct);
  1689. align = ct->ct_length;
  1690. }
  1691. }
  1692. else if (ct->ct_flags & (CT_POINTER|CT_FUNCTIONPTR)) {
  1693. struct aligncheck_ptr { char x; char *y; };
  1694. align = offsetof(struct aligncheck_ptr, y);
  1695. }
  1696. else if (ct->ct_flags & CT_ARRAY) {
  1697. ct = ct->ct_itemdescr;
  1698. goto retry;
  1699. }
  1700. else {
  1701. PyErr_Format(PyExc_ValueError, "ctype '%s' is of unknown alignment",
  1702. ct->ct_name);
  1703. return -1;
  1704. }
  1705. if ((align < 1) || (align & (align-1))) {
  1706. PyErr_Format(PyExc_SystemError,
  1707. "found for ctype '%s' bogus alignment '%d'",
  1708. ct->ct_name, align);
  1709. return -1;
  1710. }
  1711. return align;
  1712. }
  1713. static void cdata_dealloc(CDataObject *cd)
  1714. {
  1715. if (cd->c_weakreflist != NULL)
  1716. PyObject_ClearWeakRefs((PyObject *) cd);
  1717. Py_DECREF(cd->c_type);
  1718. #ifndef CFFI_MEM_LEAK /* never release anything, tests only */
  1719. Py_TYPE(cd)->tp_free((PyObject *)cd);
  1720. #endif
  1721. }
  1722. static void cdataowning_dealloc(CDataObject *cd)
  1723. {
  1724. assert(!(cd->c_type->ct_flags & (CT_IS_VOID_PTR | CT_FUNCTIONPTR)));
  1725. if (cd->c_type->ct_flags & CT_IS_PTR_TO_OWNED) {
  1726. /* for ffi.new("struct *") */
  1727. Py_DECREF(((CDataObject_own_structptr *)cd)->structobj);
  1728. }
  1729. #if defined(CFFI_MEM_DEBUG) || defined(CFFI_MEM_LEAK)
  1730. if (cd->c_type->ct_flags & (CT_PRIMITIVE_ANY | CT_STRUCT | CT_UNION)) {
  1731. assert(cd->c_type->ct_size >= 0);
  1732. memset(cd->c_data, 0xDD, cd->c_type->ct_size);
  1733. }
  1734. else if (cd->c_type->ct_flags & CT_ARRAY) {
  1735. Py_ssize_t x = get_array_length(cd);
  1736. assert(x >= 0);
  1737. x *= cd->c_type->ct_itemdescr->ct_size;
  1738. assert(x >= 0);
  1739. memset(cd->c_data, 0xDD, x);
  1740. }
  1741. #endif
  1742. cdata_dealloc(cd);
  1743. }
  1744. static void cdataowninggc_dealloc(CDataObject *cd)
  1745. {
  1746. PyObject_GC_UnTrack(cd);
  1747. if (cd->c_type->ct_flags & CT_IS_VOID_PTR) { /* a handle */
  1748. PyObject *x = ((CDataObject_own_structptr *)cd)->structobj;
  1749. Py_DECREF(x);
  1750. }
  1751. else if (cd->c_type->ct_flags & CT_FUNCTIONPTR) { /* a callback */
  1752. ffi_closure *closure = ((CDataObject_closure *)cd)->closure;
  1753. PyObject *args = (PyObject *)(closure->user_data);
  1754. Py_XDECREF(args);
  1755. #if CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE
  1756. if (CFFI_CHECK_FFI_CLOSURE_ALLOC) {
  1757. ffi_closure_free(closure);
  1758. } else
  1759. #endif
  1760. cffi_closure_free(closure);
  1761. }
  1762. else {
  1763. Py_FatalError("cdata CDataOwningGC_Type with unexpected type flags");
  1764. }
  1765. cdata_dealloc(cd);
  1766. }
  1767. static void cdatafrombuf_dealloc(CDataObject *cd)
  1768. {
  1769. Py_buffer *view = ((CDataObject_frombuf *)cd)->bufferview;
  1770. cdata_dealloc(cd);
  1771. PyBuffer_Release(view);
  1772. PyObject_Free(view);
  1773. }
  1774. static int cdataowninggc_traverse(CDataObject *cd, visitproc visit, void *arg)
  1775. {
  1776. if (cd->c_type->ct_flags & CT_IS_VOID_PTR) { /* a handle */
  1777. PyObject *x = ((CDataObject_own_structptr *)cd)->structobj;
  1778. Py_VISIT(x);
  1779. }
  1780. else if (cd->c_type->ct_flags & CT_FUNCTIONPTR) { /* a callback */
  1781. ffi_closure *closure = ((CDataObject_closure *)cd)->closure;
  1782. PyObject *args = (PyObject *)(closure->user_data);
  1783. Py_VISIT(args);
  1784. }
  1785. return 0;
  1786. }
  1787. static int cdatafrombuf_traverse(CDataObject *cd, visitproc visit, void *arg)
  1788. {
  1789. Py_buffer *view = ((CDataObject_frombuf *)cd)->bufferview;
  1790. Py_VISIT(view->obj);
  1791. return 0;
  1792. }
  1793. static int cdataowninggc_clear(CDataObject *cd)
  1794. {
  1795. if (cd->c_type->ct_flags & CT_IS_VOID_PTR) { /* a handle */
  1796. CDataObject_own_structptr *cd1 = (CDataObject_own_structptr *)cd;
  1797. PyObject *x = cd1->structobj;
  1798. Py_INCREF(Py_None);
  1799. cd1->structobj = Py_None;
  1800. Py_DECREF(x);
  1801. }
  1802. else if (cd->c_type->ct_flags & CT_FUNCTIONPTR) { /* a callback */
  1803. ffi_closure *closure = ((CDataObject_closure *)cd)->closure;
  1804. PyObject *args = (PyObject *)(closure->user_data);
  1805. closure->user_data = NULL;
  1806. Py_XDECREF(args);
  1807. }
  1808. return 0;
  1809. }
  1810. static int cdatafrombuf_clear(CDataObject *cd)
  1811. {
  1812. Py_buffer *view = ((CDataObject_frombuf *)cd)->bufferview;
  1813. PyBuffer_Release(view);
  1814. return 0;
  1815. }
  1816. /* forward */
  1817. static void _my_PyErr_WriteUnraisable(PyObject *t, PyObject *v, PyObject *tb,
  1818. char *objdescr, PyObject *obj,
  1819. char *extra_error_line);
  1820. static void gcp_finalize(PyObject *destructor, PyObject *origobj)
  1821. {
  1822. /* NOTE: this decrements the reference count of the two arguments */
  1823. if (destructor != NULL) {
  1824. PyObject *result;
  1825. PyObject *error_type, *error_value, *error_traceback;
  1826. /* Save the current exception */
  1827. PyErr_Fetch(&error_type, &error_value, &error_traceback);
  1828. result = PyObject_CallFunctionObjArgs(destructor, origobj, NULL);
  1829. if (result != NULL) {
  1830. Py_DECREF(result);
  1831. }
  1832. else {
  1833. PyObject *t, *v, *tb;
  1834. PyErr_Fetch(&t, &v, &tb);
  1835. /* Don't use error capture here, because it is very much
  1836. * like errors at __del__(), and these ones are not captured
  1837. * either */
  1838. /* ecap = _cffi_start_error_capture(); */
  1839. _my_PyErr_WriteUnraisable(t, v, tb, "From callback for ffi.gc ",
  1840. origobj, NULL);
  1841. /* _cffi_stop_error_capture(ecap); */
  1842. }
  1843. Py_DECREF(destructor);
  1844. /* Restore the saved exception */
  1845. PyErr_Restore(error_type, error_value, error_traceback);
  1846. }
  1847. Py_XDECREF(origobj);
  1848. }
  1849. static void cdatagcp_finalize(CDataObject_gcp *cd)
  1850. {
  1851. PyObject *destructor = cd->destructor;
  1852. PyObject *origobj = cd->origobj;
  1853. cd->destructor = NULL;
  1854. cd->origobj = NULL;
  1855. gcp_finalize(destructor, origobj);
  1856. }
  1857. static void cdatagcp_dealloc(CDataObject_gcp *cd)
  1858. {
  1859. PyObject *destructor = cd->destructor;
  1860. PyObject *origobj = cd->origobj;
  1861. cdata_dealloc((CDataObject *)cd);
  1862. gcp_finalize(destructor, origobj);
  1863. }
  1864. static int cdatagcp_traverse(CDataObject_gcp *cd, visitproc visit, void *arg)
  1865. {
  1866. Py_VISIT(cd->destructor);
  1867. Py_VISIT(cd->origobj);
  1868. return 0;
  1869. }
  1870. static PyObject *cdata_float(CDataObject *cd); /*forward*/
  1871. static PyObject *convert_cdata_to_enum_string(CDataObject *cd, int both)
  1872. {
  1873. PyObject *d_key, *d_value;
  1874. CTypeDescrObject *ct = cd->c_type;
  1875. assert(ct->ct_flags & CT_IS_ENUM);
  1876. d_key = convert_to_object(cd->c_data, ct);
  1877. if (d_key == NULL)
  1878. return NULL;
  1879. d_value = PyDict_GetItem(PyTuple_GET_ITEM(ct->ct_stuff, 1), d_key);
  1880. if (d_value != NULL) {
  1881. if (both) {
  1882. PyObject *o = PyObject_Str(d_key);
  1883. if (o == NULL)
  1884. d_value = NULL;
  1885. else {
  1886. d_value = PyText_FromFormat("%s: %s",
  1887. PyText_AS_UTF8(o),
  1888. PyText_AS_UTF8(d_value));
  1889. Py_DECREF(o);
  1890. }
  1891. }
  1892. else
  1893. Py_INCREF(d_value);
  1894. }
  1895. else
  1896. d_value = PyObject_Str(d_key);
  1897. Py_DECREF(d_key);
  1898. return d_value;
  1899. }
  1900. static PyObject *cdata_repr(CDataObject *cd)
  1901. {
  1902. char *extra;
  1903. PyObject *result, *s;
  1904. if (cd->c_type->ct_flags & CT_PRIMITIVE_ANY) {
  1905. if (cd->c_type->ct_flags & CT_IS_ENUM) {
  1906. s = convert_cdata_to_enum_string(cd, 1);
  1907. }
  1908. else if (cd->c_type->ct_flags & CT_IS_LONGDOUBLE) {
  1909. long double lvalue;
  1910. char buffer[128]; /* big enough */
  1911. /*READ(cd->c_data, sizeof(long double)*/
  1912. lvalue = read_raw_longdouble_data(cd->c_data);
  1913. sprintf(buffer, "%LE", lvalue);
  1914. s = PyText_FromString(buffer);
  1915. }
  1916. else {
  1917. PyObject *o = convert_to_object(cd->c_data, cd->c_type);
  1918. if (o == NULL)
  1919. return NULL;
  1920. s = PyObject_Repr(o);
  1921. Py_DECREF(o);
  1922. }
  1923. }
  1924. else if ((cd->c_type->ct_flags & CT_ARRAY) && cd->c_type->ct_length < 0) {
  1925. s = PyText_FromFormat("sliced length %zd", get_array_length(cd));
  1926. }
  1927. else {
  1928. if (cd->c_data != NULL) {
  1929. s = PyText_FromFormat("%p", cd->c_data);
  1930. }
  1931. else
  1932. s = PyText_FromString("NULL");
  1933. }
  1934. if (s == NULL)
  1935. return NULL;
  1936. /* it's slightly confusing to get "<cdata 'struct foo' 0x...>" because the
  1937. struct foo is not owned. Trying to make it clearer, write in this
  1938. case "<cdata 'struct foo &' 0x...>". */
  1939. if (cd->c_type->ct_flags & (CT_STRUCT|CT_UNION))
  1940. extra = " &";
  1941. else
  1942. extra = "";
  1943. result = PyText_FromFormat("<cdata '%s%s' %s>",
  1944. cd->c_type->ct_name, extra,
  1945. PyText_AsUTF8(s));
  1946. Py_DECREF(s);
  1947. return result;
  1948. }
  1949. static PyObject *_cdata_repr2(CDataObject *cd, char *text, PyObject *x)
  1950. {
  1951. PyObject *res, *s = PyObject_Repr(x);
  1952. if (s == NULL)
  1953. return NULL;
  1954. res = PyText_FromFormat("<cdata '%s' %s %s>",
  1955. cd->c_type->ct_name, text, PyText_AsUTF8(s));
  1956. Py_DECREF(s);
  1957. return res;
  1958. }
  1959. static Py_ssize_t _cdata_var_byte_size(CDataObject *cd)
  1960. {
  1961. /* If 'cd' is a 'struct foo' or 'struct foo *' allocated with
  1962. ffi.new(), and if the struct foo contains a varsize array,
  1963. then return the real allocated size. Otherwise, return -1. */
  1964. if (!CDataOwn_Check(cd))
  1965. return -1;
  1966. if (cd->c_type->ct_flags & CT_IS_PTR_TO_OWNED) {
  1967. cd = (CDataObject *)((CDataObject_own_structptr *)cd)->structobj;
  1968. }
  1969. if (cd->c_type->ct_flags & CT_WITH_VAR_ARRAY) {
  1970. return ((CDataObject_own_length *)cd)->length;
  1971. }
  1972. return -1;
  1973. }
  1974. static PyObject *_frombuf_repr(CDataObject *cd, const char *cd_type_name)
  1975. {
  1976. Py_buffer *view = ((CDataObject_frombuf *)cd)->bufferview;
  1977. const char *obj_tp_name;
  1978. if (view->obj == NULL) {
  1979. return PyText_FromFormat(
  1980. "<cdata '%s' buffer RELEASED>",
  1981. cd_type_name);
  1982. }
  1983. obj_tp_name = Py_TYPE(view->obj)->tp_name;
  1984. if (cd->c_type->ct_flags & CT_ARRAY)
  1985. {
  1986. Py_ssize_t buflen = get_array_length(cd);
  1987. return PyText_FromFormat(
  1988. "<cdata '%s' buffer len %zd from '%.200s' object>",
  1989. cd_type_name,
  1990. buflen,
  1991. obj_tp_name);
  1992. }
  1993. else
  1994. {
  1995. return PyText_FromFormat(
  1996. "<cdata '%s' buffer from '%.200s' object>",
  1997. cd_type_name,
  1998. obj_tp_name);
  1999. }
  2000. }
  2001. static Py_ssize_t cdataowning_size_bytes(CDataObject *cd)
  2002. {
  2003. Py_ssize_t size = _cdata_var_byte_size(cd);
  2004. if (size < 0) {
  2005. if (cd->c_type->ct_flags & CT_POINTER)
  2006. size = cd->c_type->ct_itemdescr->ct_size;
  2007. else if (cd->c_type->ct_flags & CT_ARRAY)
  2008. size = get_array_length(cd) * cd->c_type->ct_itemdescr->ct_size;
  2009. else
  2010. size = cd->c_type->ct_size;
  2011. }
  2012. return size;
  2013. }
  2014. static PyObject *cdataowning_repr(CDataObject *cd)
  2015. {
  2016. Py_ssize_t size = cdataowning_size_bytes(cd);
  2017. return PyText_FromFormat("<cdata '%s' owning %zd bytes>",
  2018. cd->c_type->ct_name, size);
  2019. }
  2020. static PyObject *cdataowninggc_repr(CDataObject *cd)
  2021. {
  2022. if (cd->c_type->ct_flags & CT_IS_VOID_PTR) { /* a handle */
  2023. PyObject *x = ((CDataObject_own_structptr *)cd)->structobj;
  2024. return _cdata_repr2(cd, "handle to", x);
  2025. }
  2026. else if (cd->c_type->ct_flags & CT_FUNCTIONPTR) { /* a callback */
  2027. ffi_closure *closure = ((CDataObject_closure *)cd)->closure;
  2028. PyObject *args = (PyObject *)closure->user_data;
  2029. if (args == NULL)
  2030. return cdata_repr(cd);
  2031. else
  2032. return _cdata_repr2(cd, "calling", PyTuple_GET_ITEM(args, 1));
  2033. }
  2034. return cdataowning_repr(cd); /* but should be unreachable */
  2035. }
  2036. static PyObject *cdatafrombuf_repr(CDataObject *cd)
  2037. {
  2038. return _frombuf_repr(cd, cd->c_type->ct_name);
  2039. }
  2040. static int cdata_nonzero(CDataObject *cd)
  2041. {
  2042. if (cd->c_type->ct_flags & CT_PRIMITIVE_ANY) {
  2043. if (cd->c_type->ct_flags & (CT_PRIMITIVE_SIGNED |
  2044. CT_PRIMITIVE_UNSIGNED |
  2045. CT_PRIMITIVE_CHAR))
  2046. return read_raw_unsigned_data(cd->c_data, cd->c_type->ct_size) != 0;
  2047. if (cd->c_type->ct_flags & CT_PRIMITIVE_FLOAT) {
  2048. if (cd->c_type->ct_flags & CT_IS_LONGDOUBLE)
  2049. return read_raw_longdouble_data(cd->c_data) != 0.0;
  2050. return read_raw_float_data(cd->c_data, cd->c_type->ct_size) != 0.0;
  2051. }
  2052. if (cd->c_type->ct_flags & CT_PRIMITIVE_COMPLEX) {
  2053. Py_complex value = read_raw_complex_data(cd->c_data,
  2054. cd->c_type->ct_size);
  2055. return value.real != 0.0 || value.imag != 0.0;
  2056. }
  2057. }
  2058. return cd->c_data != NULL;
  2059. }
  2060. static PyObject *cdata_int(CDataObject *cd)
  2061. {
  2062. if ((cd->c_type->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_FITS_LONG))
  2063. == (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_FITS_LONG)) {
  2064. /* this case is to handle enums, but also serves as a slight
  2065. performance improvement for some other primitive types */
  2066. long value;
  2067. /*READ(cd->c_data, cd->c_type->ct_size)*/
  2068. value = (long)read_raw_signed_data(cd->c_data, cd->c_type->ct_size);
  2069. return PyInt_FromLong(value);
  2070. }
  2071. if (cd->c_type->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_UNSIGNED)) {
  2072. PyObject *result = convert_to_object(cd->c_data, cd->c_type);
  2073. if (result != NULL && PyBool_Check(result))
  2074. result = PyInt_FromLong(PyInt_AsLong(result));
  2075. return result;
  2076. }
  2077. else if (cd->c_type->ct_flags & CT_PRIMITIVE_CHAR) {
  2078. /*READ(cd->c_data, cd->c_type->ct_size)*/
  2079. switch (cd->c_type->ct_size) {
  2080. case sizeof(char):
  2081. return PyInt_FromLong((unsigned char)cd->c_data[0]);
  2082. case 2:
  2083. return PyInt_FromLong((long)*(cffi_char16_t *)cd->c_data);
  2084. case 4:
  2085. if (cd->c_type->ct_flags & CT_IS_SIGNED_WCHAR)
  2086. return PyInt_FromLong((long)*(int32_t *)cd->c_data);
  2087. else if (sizeof(long) > 4)
  2088. return PyInt_FromLong(*(uint32_t *)cd->c_data);
  2089. else
  2090. return PyLong_FromUnsignedLong(*(uint32_t *)cd->c_data);
  2091. }
  2092. }
  2093. else if (cd->c_type->ct_flags & CT_PRIMITIVE_FLOAT) {
  2094. PyObject *o = cdata_float(cd);
  2095. #if PY_MAJOR_VERSION < 3
  2096. PyObject *r = o ? PyNumber_Int(o) : NULL;
  2097. #else
  2098. PyObject *r = o ? PyNumber_Long(o) : NULL;
  2099. #endif
  2100. Py_XDECREF(o);
  2101. return r;
  2102. }
  2103. PyErr_Format(PyExc_TypeError, "int() not supported on cdata '%s'",
  2104. cd->c_type->ct_name);
  2105. return NULL;
  2106. }
  2107. #if PY_MAJOR_VERSION < 3
  2108. static PyObject *cdata_long(CDataObject *cd)
  2109. {
  2110. PyObject *res = cdata_int(cd);
  2111. if (res != NULL && PyInt_CheckExact(res)) {
  2112. PyObject *o = PyLong_FromLong(PyInt_AS_LONG(res));
  2113. Py_DECREF(res);
  2114. res = o;
  2115. }
  2116. return res;
  2117. }
  2118. #endif
  2119. static PyObject *cdata_float(CDataObject *cd)
  2120. {
  2121. if (cd->c_type->ct_flags & CT_PRIMITIVE_FLOAT) {
  2122. double value;
  2123. /*READ(cd->c_data, cd->c_type->ct_size)*/
  2124. if (!(cd->c_type->ct_flags & CT_IS_LONGDOUBLE)) {
  2125. value = read_raw_float_data(cd->c_data, cd->c_type->ct_size);
  2126. }
  2127. else {
  2128. value = (double)read_raw_longdouble_data(cd->c_data);
  2129. }
  2130. return PyFloat_FromDouble(value);
  2131. }
  2132. PyErr_Format(PyExc_TypeError, "float() not supported on cdata '%s'",
  2133. cd->c_type->ct_name);
  2134. return NULL;
  2135. }
  2136. static PyObject *cdata_richcompare(PyObject *v, PyObject *w, int op)
  2137. {
  2138. int v_is_ptr, w_is_ptr;
  2139. PyObject *pyres;
  2140. assert(CData_Check(v));
  2141. /* Comparisons involving a primitive cdata work differently than
  2142. * comparisons involving a struct/array/pointer.
  2143. *
  2144. * If v or w is a struct/array/pointer, then the other must be too
  2145. * (otherwise we return NotImplemented and leave the case to
  2146. * Python). If both are, then we compare the addresses.
  2147. *
  2148. * If v and/or w is a primitive cdata, then we convert the cdata(s)
  2149. * to regular Python objects and redo the comparison there.
  2150. */
  2151. v_is_ptr = !(((CDataObject *)v)->c_type->ct_flags & CT_PRIMITIVE_ANY);
  2152. w_is_ptr = CData_Check(w) &&
  2153. !(((CDataObject *)w)->c_type->ct_flags & CT_PRIMITIVE_ANY);
  2154. if (v_is_ptr && w_is_ptr) {
  2155. int res;
  2156. char *v_cdata = ((CDataObject *)v)->c_data;
  2157. char *w_cdata = ((CDataObject *)w)->c_data;
  2158. switch (op) {
  2159. case Py_EQ: res = (v_cdata == w_cdata); break;
  2160. case Py_NE: res = (v_cdata != w_cdata); break;
  2161. case Py_LT: res = (v_cdata < w_cdata); break;
  2162. case Py_LE: res = (v_cdata <= w_cdata); break;
  2163. case Py_GT: res = (v_cdata > w_cdata); break;
  2164. case Py_GE: res = (v_cdata >= w_cdata); break;
  2165. default: res = -1;
  2166. }
  2167. pyres = res ? Py_True : Py_False;
  2168. }
  2169. else if (v_is_ptr || w_is_ptr) {
  2170. pyres = Py_NotImplemented;
  2171. }
  2172. else {
  2173. PyObject *aa[2];
  2174. int i;
  2175. aa[0] = v; Py_INCREF(v);
  2176. aa[1] = w; Py_INCREF(w);
  2177. pyres = NULL;
  2178. for (i = 0; i < 2; i++) {
  2179. v = aa[i];
  2180. if (!CData_Check(v))
  2181. continue;
  2182. w = convert_to_object(((CDataObject *)v)->c_data,
  2183. ((CDataObject *)v)->c_type);
  2184. if (w == NULL)
  2185. goto error;
  2186. if (CData_Check(w)) {
  2187. Py_DECREF(w);
  2188. PyErr_Format(PyExc_NotImplementedError,
  2189. "cannot use <cdata '%s'> in a comparison",
  2190. ((CDataObject *)v)->c_type->ct_name);
  2191. goto error;
  2192. }
  2193. aa[i] = w;
  2194. Py_DECREF(v);
  2195. }
  2196. pyres = PyObject_RichCompare(aa[0], aa[1], op);
  2197. error:
  2198. Py_DECREF(aa[1]);
  2199. Py_DECREF(aa[0]);
  2200. return pyres;
  2201. }
  2202. Py_INCREF(pyres);
  2203. return pyres;
  2204. }
  2205. #if PY_MAJOR_VERSION < 3
  2206. typedef long Py_hash_t;
  2207. #endif
  2208. static Py_hash_t cdata_hash(PyObject *v)
  2209. {
  2210. if (((CDataObject *)v)->c_type->ct_flags & CT_PRIMITIVE_ANY) {
  2211. PyObject *vv = convert_to_object(((CDataObject *)v)->c_data,
  2212. ((CDataObject *)v)->c_type);
  2213. if (vv == NULL)
  2214. return -1;
  2215. if (!CData_Check(vv)) {
  2216. Py_hash_t hash = PyObject_Hash(vv);
  2217. Py_DECREF(vv);
  2218. return hash;
  2219. }
  2220. Py_DECREF(vv);
  2221. }
  2222. return _Py_HashPointer(((CDataObject *)v)->c_data);
  2223. }
  2224. static Py_ssize_t
  2225. cdata_length(CDataObject *cd)
  2226. {
  2227. if (cd->c_type->ct_flags & CT_ARRAY) {
  2228. return get_array_length(cd);
  2229. }
  2230. PyErr_Format(PyExc_TypeError, "cdata of type '%s' has no len()",
  2231. cd->c_type->ct_name);
  2232. return -1;
  2233. }
  2234. static char *
  2235. _cdata_get_indexed_ptr(CDataObject *cd, PyObject *key)
  2236. {
  2237. Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
  2238. if (i == -1 && PyErr_Occurred())
  2239. return NULL;
  2240. if (cd->c_type->ct_flags & CT_POINTER) {
  2241. if (CDataOwn_Check(cd)) {
  2242. if (i != 0) {
  2243. PyErr_Format(PyExc_IndexError,
  2244. "cdata '%s' can only be indexed by 0",
  2245. cd->c_type->ct_name);
  2246. return NULL;
  2247. }
  2248. }
  2249. else {
  2250. if (cd->c_data == NULL) {
  2251. PyErr_Format(PyExc_RuntimeError,
  2252. "cannot dereference null pointer from cdata '%s'",
  2253. cd->c_type->ct_name);
  2254. return NULL;
  2255. }
  2256. }
  2257. }
  2258. else if (cd->c_type->ct_flags & CT_ARRAY) {
  2259. if (i < 0) {
  2260. PyErr_SetString(PyExc_IndexError,
  2261. "negative index");
  2262. return NULL;
  2263. }
  2264. if (i >= get_array_length(cd)) {
  2265. PyErr_Format(PyExc_IndexError,
  2266. "index too large for cdata '%s' (expected %zd < %zd)",
  2267. cd->c_type->ct_name,
  2268. i, get_array_length(cd));
  2269. return NULL;
  2270. }
  2271. }
  2272. else {
  2273. PyErr_Format(PyExc_TypeError, "cdata of type '%s' cannot be indexed",
  2274. cd->c_type->ct_name);
  2275. return NULL;
  2276. }
  2277. return cd->c_data + i * cd->c_type->ct_itemdescr->ct_size;
  2278. }
  2279. static PyObject *
  2280. new_array_type(CTypeDescrObject *ctptr, Py_ssize_t length); /* forward */
  2281. static CTypeDescrObject *
  2282. _cdata_getslicearg(CDataObject *cd, PySliceObject *slice, Py_ssize_t bounds[])
  2283. {
  2284. Py_ssize_t start, stop;
  2285. CTypeDescrObject *ct;
  2286. start = PyInt_AsSsize_t(slice->start);
  2287. if (start == -1 && PyErr_Occurred()) {
  2288. if (slice->start == Py_None)
  2289. PyErr_SetString(PyExc_IndexError, "slice start must be specified");
  2290. return NULL;
  2291. }
  2292. stop = PyInt_AsSsize_t(slice->stop);
  2293. if (stop == -1 && PyErr_Occurred()) {
  2294. if (slice->stop == Py_None)
  2295. PyErr_SetString(PyExc_IndexError, "slice stop must be specified");
  2296. return NULL;
  2297. }
  2298. if (slice->step != Py_None) {
  2299. PyErr_SetString(PyExc_IndexError, "slice with step not supported");
  2300. return NULL;
  2301. }
  2302. if (start > stop) {
  2303. PyErr_SetString(PyExc_IndexError, "slice start > stop");
  2304. return NULL;
  2305. }
  2306. ct = cd->c_type;
  2307. if (ct->ct_flags & CT_ARRAY) {
  2308. if (start < 0) {
  2309. PyErr_SetString(PyExc_IndexError,
  2310. "negative index");
  2311. return NULL;
  2312. }
  2313. if (stop > get_array_length(cd)) {
  2314. PyErr_Format(PyExc_IndexError,
  2315. "index too large (expected %zd <= %zd)",
  2316. stop, get_array_length(cd));
  2317. return NULL;
  2318. }
  2319. ct = (CTypeDescrObject *)ct->ct_stuff;
  2320. }
  2321. else if (!(ct->ct_flags & CT_POINTER)) {
  2322. PyErr_Format(PyExc_TypeError, "cdata of type '%s' cannot be indexed",
  2323. ct->ct_name);
  2324. return NULL;
  2325. }
  2326. bounds[0] = start;
  2327. bounds[1] = stop - start;
  2328. return ct;
  2329. }
  2330. static PyObject *
  2331. cdata_slice(CDataObject *cd, PySliceObject *slice)
  2332. {
  2333. char *cdata;
  2334. Py_ssize_t bounds[2];
  2335. CTypeDescrObject *ct = _cdata_getslicearg(cd, slice, bounds);
  2336. if (ct == NULL)
  2337. return NULL;
  2338. if (ct->ct_stuff == NULL) {
  2339. ct->ct_stuff = new_array_type(ct, -1);
  2340. if (ct->ct_stuff == NULL)
  2341. return NULL;
  2342. }
  2343. ct = (CTypeDescrObject *)ct->ct_stuff;
  2344. cdata = cd->c_data + ct->ct_itemdescr->ct_size * bounds[0];
  2345. return new_sized_cdata(cdata, ct, bounds[1]);
  2346. }
  2347. static int
  2348. cdata_ass_slice(CDataObject *cd, PySliceObject *slice, PyObject *v)
  2349. {
  2350. Py_ssize_t bounds[2], i, length, itemsize;
  2351. PyObject *it, *item;
  2352. PyObject *(*iternext)(PyObject *);
  2353. char *cdata;
  2354. int err;
  2355. CTypeDescrObject *ct = _cdata_getslicearg(cd, slice, bounds);
  2356. if (ct == NULL)
  2357. return -1;
  2358. ct = ct->ct_itemdescr;
  2359. itemsize = ct->ct_size;
  2360. cdata = cd->c_data + itemsize * bounds[0];
  2361. length = bounds[1];
  2362. if (CData_Check(v)) {
  2363. CTypeDescrObject *ctv = ((CDataObject *)v)->c_type;
  2364. if ((ctv->ct_flags & CT_ARRAY) && (ctv->ct_itemdescr == ct) &&
  2365. (get_array_length((CDataObject *)v) == length)) {
  2366. /* fast path: copying from exactly the correct type */
  2367. memmove(cdata, ((CDataObject *)v)->c_data, itemsize * length);
  2368. return 0;
  2369. }
  2370. }
  2371. /* A fast path for <char[]>[0:N] = b"somestring" or bytearray, which
  2372. also adds support for Python 3: otherwise, you get integers while
  2373. enumerating the string, and you can't set them to characters :-/
  2374. */
  2375. if ((ct->ct_flags & CT_PRIMITIVE_CHAR) && itemsize == sizeof(char)) {
  2376. char *src;
  2377. Py_ssize_t srclen;
  2378. if (PyBytes_Check(v)) {
  2379. srclen = PyBytes_GET_SIZE(v);
  2380. src = PyBytes_AS_STRING(v);
  2381. }
  2382. else if (PyByteArray_Check(v)) {
  2383. srclen = PyByteArray_GET_SIZE(v);
  2384. src = PyByteArray_AS_STRING(v);
  2385. }
  2386. else
  2387. goto other_types;
  2388. if (srclen != length) {
  2389. PyErr_Format(PyExc_ValueError,
  2390. "need a string of length %zd, got %zd",
  2391. length, srclen);
  2392. return -1;
  2393. }
  2394. memcpy(cdata, src, length);
  2395. return 0;
  2396. }
  2397. other_types:
  2398. it = PyObject_GetIter(v);
  2399. if (it == NULL)
  2400. return -1;
  2401. iternext = *it->ob_type->tp_iternext;
  2402. for (i = 0; i < length; i++) {
  2403. item = iternext(it);
  2404. if (item == NULL) {
  2405. if (!PyErr_Occurred())
  2406. PyErr_Format(PyExc_ValueError,
  2407. "need %zd values to unpack, got %zd",
  2408. length, i);
  2409. goto error;
  2410. }
  2411. err = convert_from_object(cdata, ct, item);
  2412. Py_DECREF(item);
  2413. if (err < 0)
  2414. goto error;
  2415. cdata += itemsize;
  2416. }
  2417. item = iternext(it);
  2418. if (item != NULL) {
  2419. Py_DECREF(item);
  2420. PyErr_Format(PyExc_ValueError,
  2421. "got more than %zd values to unpack", length);
  2422. }
  2423. error:
  2424. Py_DECREF(it);
  2425. return PyErr_Occurred() ? -1 : 0;
  2426. }
  2427. static PyObject *
  2428. cdataowning_subscript(CDataObject *cd, PyObject *key)
  2429. {
  2430. char *c;
  2431. if (PySlice_Check(key))
  2432. return cdata_slice(cd, (PySliceObject *)key);
  2433. c = _cdata_get_indexed_ptr(cd, key);
  2434. /* use 'mp_subscript' instead of 'sq_item' because we don't want
  2435. negative indexes to be corrected automatically */
  2436. if (c == NULL && PyErr_Occurred())
  2437. return NULL;
  2438. if (cd->c_type->ct_flags & CT_IS_PTR_TO_OWNED) {
  2439. PyObject *res = ((CDataObject_own_structptr *)cd)->structobj;
  2440. Py_INCREF(res);
  2441. return res;
  2442. }
  2443. else {
  2444. return convert_to_object(c, cd->c_type->ct_itemdescr);
  2445. }
  2446. }
  2447. static PyObject *
  2448. cdata_subscript(CDataObject *cd, PyObject *key)
  2449. {
  2450. char *c;
  2451. if (PySlice_Check(key))
  2452. return cdata_slice(cd, (PySliceObject *)key);
  2453. c = _cdata_get_indexed_ptr(cd, key);
  2454. /* use 'mp_subscript' instead of 'sq_item' because we don't want
  2455. negative indexes to be corrected automatically */
  2456. if (c == NULL && PyErr_Occurred())
  2457. return NULL;
  2458. return convert_to_object(c, cd->c_type->ct_itemdescr);
  2459. }
  2460. static int
  2461. cdata_ass_sub(CDataObject *cd, PyObject *key, PyObject *v)
  2462. {
  2463. char *c;
  2464. CTypeDescrObject *ctitem;
  2465. if (PySlice_Check(key))
  2466. return cdata_ass_slice(cd, (PySliceObject *)key, v);
  2467. c = _cdata_get_indexed_ptr(cd, key);
  2468. ctitem = cd->c_type->ct_itemdescr;
  2469. /* use 'mp_ass_subscript' instead of 'sq_ass_item' because we don't want
  2470. negative indexes to be corrected automatically */
  2471. if (c == NULL && PyErr_Occurred())
  2472. return -1;
  2473. if (v == NULL) {
  2474. PyErr_SetString(PyExc_TypeError,
  2475. "'del x[n]' not supported for cdata objects");
  2476. return -1;
  2477. }
  2478. return convert_from_object(c, ctitem, v);
  2479. }
  2480. static PyObject *
  2481. _cdata_add_or_sub(PyObject *v, PyObject *w, int sign)
  2482. {
  2483. Py_ssize_t i, itemsize;
  2484. CDataObject *cd;
  2485. CTypeDescrObject *ctptr;
  2486. if (!CData_Check(v)) {
  2487. PyObject *swap;
  2488. assert(CData_Check(w));
  2489. if (sign != 1)
  2490. goto not_implemented;
  2491. swap = v;
  2492. v = w;
  2493. w = swap;
  2494. }
  2495. i = PyNumber_AsSsize_t(w, PyExc_OverflowError);
  2496. if (i == -1 && PyErr_Occurred())
  2497. return NULL;
  2498. i *= sign;
  2499. cd = (CDataObject *)v;
  2500. if (cd->c_type->ct_flags & CT_POINTER)
  2501. ctptr = cd->c_type;
  2502. else if (cd->c_type->ct_flags & CT_ARRAY) {
  2503. ctptr = (CTypeDescrObject *)cd->c_type->ct_stuff;
  2504. }
  2505. else {
  2506. PyErr_Format(PyExc_TypeError, "cannot add a cdata '%s' and a number",
  2507. cd->c_type->ct_name);
  2508. return NULL;
  2509. }
  2510. itemsize = ctptr->ct_itemdescr->ct_size;
  2511. if (itemsize < 0) {
  2512. if (ctptr->ct_flags & CT_IS_VOID_PTR) {
  2513. itemsize = 1;
  2514. }
  2515. else {
  2516. PyErr_Format(PyExc_TypeError,
  2517. "ctype '%s' points to items of unknown size",
  2518. cd->c_type->ct_name);
  2519. return NULL;
  2520. }
  2521. }
  2522. return new_simple_cdata(cd->c_data + i * itemsize, ctptr);
  2523. not_implemented:
  2524. Py_INCREF(Py_NotImplemented);
  2525. return Py_NotImplemented;
  2526. }
  2527. static PyObject *
  2528. cdata_add(PyObject *v, PyObject *w)
  2529. {
  2530. return _cdata_add_or_sub(v, w, +1);
  2531. }
  2532. static PyObject *
  2533. cdata_sub(PyObject *v, PyObject *w)
  2534. {
  2535. if (CData_Check(v) && CData_Check(w)) {
  2536. CDataObject *cdv = (CDataObject *)v;
  2537. CDataObject *cdw = (CDataObject *)w;
  2538. CTypeDescrObject *ct = cdw->c_type;
  2539. Py_ssize_t diff, itemsize;
  2540. if (ct->ct_flags & CT_ARRAY) /* ptr_to_T - array_of_T: ok */
  2541. ct = (CTypeDescrObject *)ct->ct_stuff;
  2542. if (ct != cdv->c_type || !(ct->ct_flags & CT_POINTER) ||
  2543. (ct->ct_itemdescr->ct_size <= 0 &&
  2544. !(ct->ct_flags & CT_IS_VOID_PTR))) {
  2545. PyErr_Format(PyExc_TypeError,
  2546. "cannot subtract cdata '%s' and cdata '%s'",
  2547. cdv->c_type->ct_name, ct->ct_name);
  2548. return NULL;
  2549. }
  2550. itemsize = ct->ct_itemdescr->ct_size;
  2551. diff = cdv->c_data - cdw->c_data;
  2552. if (itemsize > 1) {
  2553. if (diff % itemsize) {
  2554. PyErr_SetString(PyExc_ValueError,
  2555. "pointer subtraction: the distance between the two "
  2556. "pointers is not a multiple of the item size");
  2557. return NULL;
  2558. }
  2559. diff = diff / itemsize;
  2560. }
  2561. #if PY_MAJOR_VERSION < 3
  2562. return PyInt_FromSsize_t(diff);
  2563. #else
  2564. return PyLong_FromSsize_t(diff);
  2565. #endif
  2566. }
  2567. return _cdata_add_or_sub(v, w, -1);
  2568. }
  2569. static void
  2570. _cdata_attr_errmsg(char *errmsg, CDataObject *cd, PyObject *attr)
  2571. {
  2572. const char *text;
  2573. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  2574. return;
  2575. PyErr_Clear();
  2576. text = PyText_AsUTF8(attr);
  2577. if (text == NULL)
  2578. return;
  2579. PyErr_Format(PyExc_AttributeError, errmsg, cd->c_type->ct_name, text);
  2580. }
  2581. static PyObject *
  2582. cdata_getattro(CDataObject *cd, PyObject *attr)
  2583. {
  2584. CFieldObject *cf;
  2585. CTypeDescrObject *ct = cd->c_type;
  2586. char *errmsg = "cdata '%s' has no attribute '%s'";
  2587. PyObject *x;
  2588. if (ct->ct_flags & CT_POINTER)
  2589. ct = ct->ct_itemdescr;
  2590. if (ct->ct_flags & (CT_STRUCT|CT_UNION)) {
  2591. switch (force_lazy_struct(ct)) {
  2592. case 1:
  2593. cf = (CFieldObject *)PyDict_GetItem(ct->ct_stuff, attr);
  2594. if (cf != NULL) {
  2595. /* read the field 'cf' */
  2596. char *data = cd->c_data + cf->cf_offset;
  2597. Py_ssize_t array_len, size;
  2598. if (cf->cf_bitshift == BS_REGULAR) {
  2599. return convert_to_object(data, cf->cf_type);
  2600. }
  2601. else if (cf->cf_bitshift != BS_EMPTY_ARRAY) {
  2602. return convert_to_object_bitfield(data, cf);
  2603. }
  2604. /* variable-length array: */
  2605. /* if reading variable length array from variable length
  2606. struct, calculate array type from allocated length */
  2607. size = _cdata_var_byte_size(cd) - cf->cf_offset;
  2608. if (size >= 0) {
  2609. array_len = size / cf->cf_type->ct_itemdescr->ct_size;
  2610. return new_sized_cdata(data, cf->cf_type, array_len);
  2611. }
  2612. return new_simple_cdata(data,
  2613. (CTypeDescrObject *)cf->cf_type->ct_stuff);
  2614. }
  2615. errmsg = "cdata '%s' has no field '%s'";
  2616. break;
  2617. case -1:
  2618. return NULL;
  2619. default:
  2620. errmsg = "cdata '%s' points to an opaque type: cannot read fields";
  2621. break;
  2622. }
  2623. }
  2624. x = PyObject_GenericGetAttr((PyObject *)cd, attr);
  2625. if (x == NULL)
  2626. _cdata_attr_errmsg(errmsg, cd, attr);
  2627. return x;
  2628. }
  2629. static int
  2630. cdata_setattro(CDataObject *cd, PyObject *attr, PyObject *value)
  2631. {
  2632. CFieldObject *cf;
  2633. CTypeDescrObject *ct = cd->c_type;
  2634. char *errmsg = "cdata '%s' has no attribute '%s'";
  2635. int x;
  2636. if (ct->ct_flags & CT_POINTER)
  2637. ct = ct->ct_itemdescr;
  2638. if (ct->ct_flags & (CT_STRUCT|CT_UNION)) {
  2639. switch (force_lazy_struct(ct)) {
  2640. case 1:
  2641. cf = (CFieldObject *)PyDict_GetItem(ct->ct_stuff, attr);
  2642. if (cf != NULL) {
  2643. /* write the field 'cf' */
  2644. if (value != NULL) {
  2645. return convert_field_from_object(cd->c_data, cf, value);
  2646. }
  2647. else {
  2648. PyErr_SetString(PyExc_AttributeError,
  2649. "cannot delete struct field");
  2650. return -1;
  2651. }
  2652. }
  2653. errmsg = "cdata '%s' has no field '%s'";
  2654. break;
  2655. case -1:
  2656. return -1;
  2657. default:
  2658. errmsg = "cdata '%s' points to an opaque type: cannot write fields";
  2659. break;
  2660. }
  2661. }
  2662. x = PyObject_GenericSetAttr((PyObject *)cd, attr, value);
  2663. if (x < 0)
  2664. _cdata_attr_errmsg(errmsg, cd, attr);
  2665. return x;
  2666. }
  2667. static PyObject *
  2668. convert_struct_to_owning_object(char *data, CTypeDescrObject *ct); /*forward*/
  2669. static cif_description_t *
  2670. fb_prepare_cif(PyObject *fargs, CTypeDescrObject *, Py_ssize_t, ffi_abi);
  2671. /*forward*/
  2672. static PyObject *new_primitive_type(const char *name); /*forward*/
  2673. static CTypeDescrObject *_get_ct_int(void)
  2674. {
  2675. static CTypeDescrObject *ct_int = NULL;
  2676. if (ct_int == NULL) {
  2677. ct_int = (CTypeDescrObject *)new_primitive_type("int");
  2678. }
  2679. return ct_int;
  2680. }
  2681. static Py_ssize_t
  2682. _prepare_pointer_call_argument(CTypeDescrObject *ctptr, PyObject *init,
  2683. char **output_data)
  2684. {
  2685. /* 'ctptr' is here a pointer type 'ITEM *'. Accept as argument an
  2686. initializer for an array 'ITEM[]'. This includes the case of
  2687. passing a Python byte string to a 'char *' argument.
  2688. This function returns -1 if an error occurred,
  2689. 0 if conversion succeeded (into *output_data),
  2690. or N > 0 if conversion would require N bytes of storage.
  2691. */
  2692. Py_ssize_t length, datasize;
  2693. CTypeDescrObject *ctitem;
  2694. if (CData_Check(init))
  2695. goto convert_default;
  2696. ctitem = ctptr->ct_itemdescr;
  2697. /* XXX some code duplication, how to avoid it? */
  2698. if (PyBytes_Check(init)) {
  2699. /* from a string: just returning the string here is fine.
  2700. We assume that the C code won't modify the 'char *' data. */
  2701. if ((ctptr->ct_flags & CT_IS_VOIDCHAR_PTR) ||
  2702. ((ctitem->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_UNSIGNED))
  2703. && (ctitem->ct_size == sizeof(char)))) {
  2704. #if defined(CFFI_MEM_DEBUG) || defined(CFFI_MEM_LEAK)
  2705. length = PyBytes_GET_SIZE(init) + 1;
  2706. #else
  2707. *output_data = PyBytes_AS_STRING(init);
  2708. if (ctitem->ct_flags & CT_IS_BOOL)
  2709. if (must_be_array_of_zero_or_one(*output_data,
  2710. PyBytes_GET_SIZE(init)) < 0)
  2711. return -1;
  2712. return 0;
  2713. #endif
  2714. }
  2715. else
  2716. goto convert_default;
  2717. }
  2718. else if (PyList_Check(init) || PyTuple_Check(init)) {
  2719. length = PySequence_Fast_GET_SIZE(init);
  2720. }
  2721. else if (PyUnicode_Check(init)) {
  2722. /* from a unicode, we add the null terminator */
  2723. if (ctitem->ct_size == 2)
  2724. length = _my_PyUnicode_SizeAsChar16(init);
  2725. else
  2726. length = _my_PyUnicode_SizeAsChar32(init);
  2727. length += 1;
  2728. }
  2729. else if ((ctitem->ct_flags & CT_IS_FILE) && PyFile_Check(init)) {
  2730. *output_data = (char *)PyFile_AsFile(init);
  2731. if (*output_data == NULL && PyErr_Occurred())
  2732. return -1;
  2733. return 0;
  2734. }
  2735. else {
  2736. /* refuse to receive just an integer (and interpret it
  2737. as the array size) */
  2738. goto convert_default;
  2739. }
  2740. if (ctitem->ct_size <= 0)
  2741. goto convert_default;
  2742. datasize = MUL_WRAPAROUND(length, ctitem->ct_size);
  2743. if ((datasize / ctitem->ct_size) != length) {
  2744. PyErr_SetString(PyExc_OverflowError,
  2745. "array size would overflow a Py_ssize_t");
  2746. return -1;
  2747. }
  2748. if (datasize <= 0)
  2749. datasize = 1;
  2750. return datasize;
  2751. convert_default:
  2752. return convert_from_object((char *)output_data, ctptr, init);
  2753. }
  2754. static PyObject*
  2755. cdata_call(CDataObject *cd, PyObject *args, PyObject *kwds)
  2756. {
  2757. char *buffer;
  2758. void** buffer_array;
  2759. cif_description_t *cif_descr;
  2760. Py_ssize_t i, nargs, nargs_declared;
  2761. PyObject *signature, *res = NULL, *fvarargs;
  2762. CTypeDescrObject *fresult;
  2763. char *resultdata;
  2764. char *errormsg;
  2765. struct freeme_s {
  2766. struct freeme_s *next;
  2767. union_alignment alignment;
  2768. } *freeme = NULL;
  2769. if (!(cd->c_type->ct_flags & CT_FUNCTIONPTR)) {
  2770. PyErr_Format(PyExc_TypeError, "cdata '%s' is not callable",
  2771. cd->c_type->ct_name);
  2772. return NULL;
  2773. }
  2774. if (cd->c_data == NULL) {
  2775. PyErr_Format(PyExc_RuntimeError,
  2776. "cannot call null pointer pointer from cdata '%s'",
  2777. cd->c_type->ct_name);
  2778. return NULL;
  2779. }
  2780. if (kwds != NULL && PyDict_Size(kwds) != 0) {
  2781. PyErr_SetString(PyExc_TypeError,
  2782. "a cdata function cannot be called with keyword arguments");
  2783. return NULL;
  2784. }
  2785. signature = cd->c_type->ct_stuff;
  2786. nargs = PyTuple_Size(args);
  2787. if (nargs < 0)
  2788. return NULL;
  2789. nargs_declared = PyTuple_GET_SIZE(signature) - 2;
  2790. fresult = (CTypeDescrObject *)PyTuple_GET_ITEM(signature, 1);
  2791. fvarargs = NULL;
  2792. buffer = NULL;
  2793. cif_descr = (cif_description_t *)cd->c_type->ct_extra;
  2794. if (cif_descr != NULL) {
  2795. /* regular case: this function does not take '...' arguments */
  2796. if (nargs != nargs_declared) {
  2797. errormsg = "'%s' expects %zd arguments, got %zd";
  2798. bad_number_of_arguments:
  2799. PyErr_Format(PyExc_TypeError, errormsg,
  2800. cd->c_type->ct_name, nargs_declared, nargs);
  2801. goto error;
  2802. }
  2803. }
  2804. else {
  2805. /* call of a variadic function */
  2806. ffi_abi fabi;
  2807. if (nargs < nargs_declared) {
  2808. errormsg = "'%s' expects at least %zd arguments, got %zd";
  2809. goto bad_number_of_arguments;
  2810. }
  2811. fvarargs = PyTuple_New(nargs);
  2812. if (fvarargs == NULL)
  2813. goto error;
  2814. for (i = 0; i < nargs_declared; i++) {
  2815. PyObject *o = PyTuple_GET_ITEM(signature, 2 + i);
  2816. Py_INCREF(o);
  2817. PyTuple_SET_ITEM(fvarargs, i, o);
  2818. }
  2819. for (i = nargs_declared; i < nargs; i++) {
  2820. PyObject *obj = PyTuple_GET_ITEM(args, i);
  2821. CTypeDescrObject *ct;
  2822. if (CData_Check(obj)) {
  2823. ct = ((CDataObject *)obj)->c_type;
  2824. if (ct->ct_flags & (CT_PRIMITIVE_CHAR | CT_PRIMITIVE_UNSIGNED |
  2825. CT_PRIMITIVE_SIGNED)) {
  2826. if (ct->ct_size < (Py_ssize_t)sizeof(int)) {
  2827. ct = _get_ct_int();
  2828. if (ct == NULL)
  2829. goto error;
  2830. }
  2831. }
  2832. else if (ct->ct_flags & CT_ARRAY) {
  2833. ct = (CTypeDescrObject *)ct->ct_stuff;
  2834. }
  2835. Py_INCREF(ct);
  2836. }
  2837. else {
  2838. PyErr_Format(PyExc_TypeError,
  2839. "argument %zd passed in the variadic part "
  2840. "needs to be a cdata object (got %.200s)",
  2841. i + 1, Py_TYPE(obj)->tp_name);
  2842. goto error;
  2843. }
  2844. PyTuple_SET_ITEM(fvarargs, i, (PyObject *)ct);
  2845. }
  2846. #if PY_MAJOR_VERSION < 3
  2847. fabi = PyInt_AS_LONG(PyTuple_GET_ITEM(signature, 0));
  2848. #else
  2849. fabi = PyLong_AS_LONG(PyTuple_GET_ITEM(signature, 0));
  2850. #endif
  2851. cif_descr = fb_prepare_cif(fvarargs, fresult, nargs_declared, fabi);
  2852. if (cif_descr == NULL)
  2853. goto error;
  2854. }
  2855. buffer = PyObject_Malloc(cif_descr->exchange_size);
  2856. if (buffer == NULL) {
  2857. PyErr_NoMemory();
  2858. goto error;
  2859. }
  2860. buffer_array = (void **)buffer;
  2861. for (i=0; i<nargs; i++) {
  2862. CTypeDescrObject *argtype;
  2863. char *data = buffer + cif_descr->exchange_offset_arg[1 + i];
  2864. PyObject *obj = PyTuple_GET_ITEM(args, i);
  2865. buffer_array[i] = data;
  2866. if (i < nargs_declared)
  2867. argtype = (CTypeDescrObject *)PyTuple_GET_ITEM(signature, 2 + i);
  2868. else
  2869. argtype = (CTypeDescrObject *)PyTuple_GET_ITEM(fvarargs, i);
  2870. if (argtype->ct_flags & CT_POINTER) {
  2871. char *tmpbuf;
  2872. Py_ssize_t datasize = _prepare_pointer_call_argument(
  2873. argtype, obj, (char **)data);
  2874. if (datasize == 0)
  2875. ; /* successfully filled '*data' */
  2876. else if (datasize < 0)
  2877. goto error;
  2878. else {
  2879. if (datasize <= 512) {
  2880. tmpbuf = alloca(datasize);
  2881. }
  2882. else {
  2883. struct freeme_s *fp = (struct freeme_s *)PyObject_Malloc(
  2884. offsetof(struct freeme_s, alignment) +
  2885. (size_t)datasize);
  2886. if (fp == NULL) {
  2887. PyErr_NoMemory();
  2888. goto error;
  2889. }
  2890. fp->next = freeme;
  2891. freeme = fp;
  2892. tmpbuf = (char *)&fp->alignment;
  2893. }
  2894. memset(tmpbuf, 0, datasize);
  2895. *(char **)data = tmpbuf;
  2896. if (convert_array_from_object(tmpbuf, argtype, obj) < 0)
  2897. goto error;
  2898. }
  2899. }
  2900. else if (convert_from_object(data, argtype, obj) < 0)
  2901. goto error;
  2902. }
  2903. resultdata = buffer + cif_descr->exchange_offset_arg[0];
  2904. /*READ(cd->c_data, sizeof(void(*)(void)))*/
  2905. Py_BEGIN_ALLOW_THREADS
  2906. restore_errno();
  2907. ffi_call(&cif_descr->cif, (void (*)(void))(cd->c_data),
  2908. resultdata, buffer_array);
  2909. save_errno();
  2910. Py_END_ALLOW_THREADS
  2911. if (fresult->ct_flags & (CT_PRIMITIVE_CHAR | CT_PRIMITIVE_SIGNED |
  2912. CT_PRIMITIVE_UNSIGNED)) {
  2913. #ifdef WORDS_BIGENDIAN
  2914. /* For results of precisely these types, libffi has a strange
  2915. rule that they will be returned as a whole 'ffi_arg' if they
  2916. are smaller. The difference only matters on big-endian. */
  2917. if (fresult->ct_size < sizeof(ffi_arg))
  2918. resultdata += (sizeof(ffi_arg) - fresult->ct_size);
  2919. #endif
  2920. res = convert_to_object(resultdata, fresult);
  2921. }
  2922. else if (fresult->ct_flags & CT_VOID) {
  2923. res = Py_None;
  2924. Py_INCREF(res);
  2925. }
  2926. else if (fresult->ct_flags & CT_STRUCT) {
  2927. res = convert_struct_to_owning_object(resultdata, fresult);
  2928. }
  2929. else {
  2930. res = convert_to_object(resultdata, fresult);
  2931. }
  2932. /* fall-through */
  2933. error:
  2934. while (freeme != NULL) {
  2935. void *p = (void *)freeme;
  2936. freeme = freeme->next;
  2937. PyObject_Free(p);
  2938. }
  2939. if (buffer)
  2940. PyObject_Free(buffer);
  2941. if (fvarargs != NULL) {
  2942. Py_DECREF(fvarargs);
  2943. if (cif_descr != NULL) /* but only if fvarargs != NULL, if variadic */
  2944. PyObject_Free(cif_descr);
  2945. }
  2946. return res;
  2947. }
  2948. static PyObject *cdata_dir(PyObject *cd, PyObject *noarg)
  2949. {
  2950. CTypeDescrObject *ct = ((CDataObject *)cd)->c_type;
  2951. /* replace the type 'pointer-to-t' with just 't' */
  2952. if (ct->ct_flags & CT_POINTER) {
  2953. ct = ct->ct_itemdescr;
  2954. }
  2955. if ((ct->ct_flags & (CT_STRUCT | CT_UNION)) &&
  2956. !(ct->ct_flags & CT_IS_OPAQUE)) {
  2957. /* for non-opaque structs or unions */
  2958. if (force_lazy_struct(ct) < 0)
  2959. return NULL;
  2960. return PyDict_Keys(ct->ct_stuff);
  2961. }
  2962. else {
  2963. return PyList_New(0); /* empty list for the other cases */
  2964. }
  2965. }
  2966. static PyObject *cdata_complex(PyObject *cd_, PyObject *noarg)
  2967. {
  2968. CDataObject *cd = (CDataObject *)cd_;
  2969. if (cd->c_type->ct_flags & CT_PRIMITIVE_COMPLEX) {
  2970. Py_complex value = read_raw_complex_data(cd->c_data, cd->c_type->ct_size);
  2971. PyObject *op = PyComplex_FromCComplex(value);
  2972. return op;
  2973. }
  2974. /* <cdata 'float'> or <cdata 'int'> cannot be directly converted by
  2975. calling complex(), just like <cdata 'int'> cannot be directly
  2976. converted by calling float() */
  2977. PyErr_Format(PyExc_TypeError, "complex() not supported on cdata '%s'",
  2978. cd->c_type->ct_name);
  2979. return NULL;
  2980. }
  2981. static int explicit_release_case(PyObject *cd)
  2982. {
  2983. CTypeDescrObject *ct = ((CDataObject *)cd)->c_type;
  2984. if (Py_TYPE(cd) == &CDataOwning_Type) {
  2985. if ((ct->ct_flags & (CT_POINTER | CT_ARRAY)) != 0) /* ffi.new() */
  2986. return 0;
  2987. }
  2988. else if (Py_TYPE(cd) == &CDataFromBuf_Type) {
  2989. return 1; /* ffi.from_buffer() */
  2990. }
  2991. else if (Py_TYPE(cd) == &CDataGCP_Type) {
  2992. return 2; /* ffi.gc() */
  2993. }
  2994. PyErr_SetString(PyExc_ValueError,
  2995. "only 'cdata' object from ffi.new(), ffi.gc(), ffi.from_buffer() "
  2996. "or ffi.new_allocator()() can be used with the 'with' keyword or "
  2997. "ffi.release()");
  2998. return -1;
  2999. }
  3000. static PyObject *cdata_enter(PyObject *cd, PyObject *noarg)
  3001. {
  3002. if (explicit_release_case(cd) < 0) /* only to check the ctype */
  3003. return NULL;
  3004. Py_INCREF(cd);
  3005. return cd;
  3006. }
  3007. static PyObject *cdata_exit(PyObject *cd, PyObject *args)
  3008. {
  3009. /* 'args' ignored */
  3010. CTypeDescrObject *ct;
  3011. Py_buffer *view;
  3012. switch (explicit_release_case(cd))
  3013. {
  3014. case 0: /* ffi.new() */
  3015. /* no effect on CPython: raw memory is allocated with the
  3016. same malloc() as the object itself, so it can't be
  3017. released independently. If we use a custom allocator,
  3018. then it's implemented with ffi.gc(). */
  3019. ct = ((CDataObject *)cd)->c_type;
  3020. if (ct->ct_flags & CT_IS_PTR_TO_OWNED) {
  3021. PyObject *x = ((CDataObject_own_structptr *)cd)->structobj;
  3022. if (Py_TYPE(x) == &CDataGCP_Type) {
  3023. /* this is a special case for
  3024. ffi.new_allocator()("struct-or-union *") */
  3025. cdatagcp_finalize((CDataObject_gcp *)x);
  3026. }
  3027. }
  3028. break;
  3029. case 1: /* ffi.from_buffer() */
  3030. view = ((CDataObject_frombuf *)cd)->bufferview;
  3031. PyBuffer_Release(view);
  3032. break;
  3033. case 2: /* ffi.gc() or ffi.new_allocator()("not-struct-nor-union") */
  3034. /* call the destructor immediately */
  3035. cdatagcp_finalize((CDataObject_gcp *)cd);
  3036. break;
  3037. default:
  3038. return NULL;
  3039. }
  3040. Py_INCREF(Py_None);
  3041. return Py_None;
  3042. }
  3043. static PyObject *cdata_iter(CDataObject *);
  3044. static PyNumberMethods CData_as_number = {
  3045. (binaryfunc)cdata_add, /*nb_add*/
  3046. (binaryfunc)cdata_sub, /*nb_subtract*/
  3047. 0, /*nb_multiply*/
  3048. #if PY_MAJOR_VERSION < 3
  3049. 0, /*nb_divide*/
  3050. #endif
  3051. 0, /*nb_remainder*/
  3052. 0, /*nb_divmod*/
  3053. 0, /*nb_power*/
  3054. 0, /*nb_negative*/
  3055. 0, /*nb_positive*/
  3056. 0, /*nb_absolute*/
  3057. (inquiry)cdata_nonzero, /*nb_nonzero*/
  3058. 0, /*nb_invert*/
  3059. 0, /*nb_lshift*/
  3060. 0, /*nb_rshift*/
  3061. 0, /*nb_and*/
  3062. 0, /*nb_xor*/
  3063. 0, /*nb_or*/
  3064. #if PY_MAJOR_VERSION < 3
  3065. 0, /*nb_coerce*/
  3066. #endif
  3067. (unaryfunc)cdata_int, /*nb_int*/
  3068. #if PY_MAJOR_VERSION < 3
  3069. (unaryfunc)cdata_long, /*nb_long*/
  3070. #else
  3071. 0,
  3072. #endif
  3073. (unaryfunc)cdata_float, /*nb_float*/
  3074. 0, /*nb_oct*/
  3075. 0, /*nb_hex*/
  3076. };
  3077. static PyMappingMethods CData_as_mapping = {
  3078. (lenfunc)cdata_length, /*mp_length*/
  3079. (binaryfunc)cdata_subscript, /*mp_subscript*/
  3080. (objobjargproc)cdata_ass_sub, /*mp_ass_subscript*/
  3081. };
  3082. static PyMappingMethods CDataOwn_as_mapping = {
  3083. (lenfunc)cdata_length, /*mp_length*/
  3084. (binaryfunc)cdataowning_subscript, /*mp_subscript*/
  3085. (objobjargproc)cdata_ass_sub, /*mp_ass_subscript*/
  3086. };
  3087. static PyMethodDef cdata_methods[] = {
  3088. {"__dir__", cdata_dir, METH_NOARGS},
  3089. {"__complex__", cdata_complex, METH_NOARGS},
  3090. {"__enter__", cdata_enter, METH_NOARGS},
  3091. {"__exit__", cdata_exit, METH_VARARGS},
  3092. {NULL, NULL} /* sentinel */
  3093. };
  3094. static PyTypeObject CData_Type = {
  3095. PyVarObject_HEAD_INIT(NULL, 0)
  3096. "_cffi_backend._CDataBase",
  3097. sizeof(CDataObject),
  3098. 0,
  3099. (destructor)cdata_dealloc, /* tp_dealloc */
  3100. 0, /* tp_print */
  3101. 0, /* tp_getattr */
  3102. 0, /* tp_setattr */
  3103. 0, /* tp_compare */
  3104. (reprfunc)cdata_repr, /* tp_repr */
  3105. &CData_as_number, /* tp_as_number */
  3106. 0, /* tp_as_sequence */
  3107. &CData_as_mapping, /* tp_as_mapping */
  3108. cdata_hash, /* tp_hash */
  3109. (ternaryfunc)cdata_call, /* tp_call */
  3110. 0, /* tp_str */
  3111. (getattrofunc)cdata_getattro, /* tp_getattro */
  3112. (setattrofunc)cdata_setattro, /* tp_setattro */
  3113. 0, /* tp_as_buffer */
  3114. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, /* tp_flags */
  3115. "The internal base type for CData objects. Use FFI.CData to access "
  3116. "it. Always check with isinstance(): subtypes are sometimes returned "
  3117. "on CPython, for performance reasons.", /* tp_doc */
  3118. 0, /* tp_traverse */
  3119. 0, /* tp_clear */
  3120. cdata_richcompare, /* tp_richcompare */
  3121. offsetof(CDataObject, c_weakreflist), /* tp_weaklistoffset */
  3122. (getiterfunc)cdata_iter, /* tp_iter */
  3123. 0, /* tp_iternext */
  3124. cdata_methods, /* tp_methods */
  3125. 0, /* tp_members */
  3126. 0, /* tp_getset */
  3127. 0, /* tp_base */
  3128. 0, /* tp_dict */
  3129. 0, /* tp_descr_get */
  3130. 0, /* tp_descr_set */
  3131. 0, /* tp_dictoffset */
  3132. 0, /* tp_init */
  3133. 0, /* tp_alloc */
  3134. 0, /* tp_new */
  3135. PyObject_Del, /* tp_free */
  3136. };
  3137. static PyTypeObject CDataOwning_Type = {
  3138. PyVarObject_HEAD_INIT(NULL, 0)
  3139. "_cffi_backend.__CDataOwn",
  3140. sizeof(CDataObject),
  3141. 0,
  3142. (destructor)cdataowning_dealloc, /* tp_dealloc */
  3143. 0, /* tp_print */
  3144. 0, /* tp_getattr */
  3145. 0, /* tp_setattr */
  3146. 0, /* tp_compare */
  3147. (reprfunc)cdataowning_repr, /* tp_repr */
  3148. 0, /* inherited */ /* tp_as_number */
  3149. 0, /* tp_as_sequence */
  3150. &CDataOwn_as_mapping, /* tp_as_mapping */
  3151. 0, /* inherited */ /* tp_hash */
  3152. 0, /* inherited */ /* tp_call */
  3153. 0, /* tp_str */
  3154. 0, /* inherited */ /* tp_getattro */
  3155. 0, /* inherited */ /* tp_setattro */
  3156. 0, /* tp_as_buffer */
  3157. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, /* tp_flags */
  3158. "This is an internal subtype of _CDataBase for performance only on "
  3159. "CPython. Check with isinstance(x, ffi.CData).", /* tp_doc */
  3160. 0, /* tp_traverse */
  3161. 0, /* tp_clear */
  3162. 0, /* inherited */ /* tp_richcompare */
  3163. 0, /* inherited */ /* tp_weaklistoffset */
  3164. 0, /* inherited */ /* tp_iter */
  3165. 0, /* tp_iternext */
  3166. 0, /* inherited */ /* tp_methods */
  3167. 0, /* tp_members */
  3168. 0, /* tp_getset */
  3169. &CData_Type, /* tp_base */
  3170. 0, /* tp_dict */
  3171. 0, /* tp_descr_get */
  3172. 0, /* tp_descr_set */
  3173. 0, /* tp_dictoffset */
  3174. 0, /* tp_init */
  3175. 0, /* tp_alloc */
  3176. 0, /* tp_new */
  3177. free, /* tp_free */
  3178. };
  3179. static PyTypeObject CDataOwningGC_Type = {
  3180. PyVarObject_HEAD_INIT(NULL, 0)
  3181. "_cffi_backend.__CDataOwnGC",
  3182. sizeof(CDataObject_own_structptr),
  3183. 0,
  3184. (destructor)cdataowninggc_dealloc, /* tp_dealloc */
  3185. 0, /* tp_print */
  3186. 0, /* tp_getattr */
  3187. 0, /* tp_setattr */
  3188. 0, /* tp_compare */
  3189. (reprfunc)cdataowninggc_repr, /* tp_repr */
  3190. 0, /* inherited */ /* tp_as_number */
  3191. 0, /* tp_as_sequence */
  3192. 0, /* inherited */ /* tp_as_mapping */
  3193. 0, /* inherited */ /* tp_hash */
  3194. 0, /* inherited */ /* tp_call */
  3195. 0, /* tp_str */
  3196. 0, /* inherited */ /* tp_getattro */
  3197. 0, /* inherited */ /* tp_setattro */
  3198. 0, /* tp_as_buffer */
  3199. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES /* tp_flags */
  3200. | Py_TPFLAGS_HAVE_GC,
  3201. "This is an internal subtype of _CDataBase for performance only on "
  3202. "CPython. Check with isinstance(x, ffi.CData).", /* tp_doc */
  3203. (traverseproc)cdataowninggc_traverse, /* tp_traverse */
  3204. (inquiry)cdataowninggc_clear, /* tp_clear */
  3205. 0, /* inherited */ /* tp_richcompare */
  3206. 0, /* inherited */ /* tp_weaklistoffset */
  3207. 0, /* inherited */ /* tp_iter */
  3208. 0, /* tp_iternext */
  3209. 0, /* inherited */ /* tp_methods */
  3210. 0, /* tp_members */
  3211. 0, /* tp_getset */
  3212. &CDataOwning_Type, /* tp_base */
  3213. 0, /* tp_dict */
  3214. 0, /* tp_descr_get */
  3215. 0, /* tp_descr_set */
  3216. 0, /* tp_dictoffset */
  3217. 0, /* tp_init */
  3218. 0, /* tp_alloc */
  3219. 0, /* tp_new */
  3220. PyObject_GC_Del, /* tp_free */
  3221. };
  3222. static PyTypeObject CDataFromBuf_Type = {
  3223. PyVarObject_HEAD_INIT(NULL, 0)
  3224. "_cffi_backend.__CDataFromBuf",
  3225. sizeof(CDataObject_frombuf),
  3226. 0,
  3227. (destructor)cdatafrombuf_dealloc, /* tp_dealloc */
  3228. 0, /* tp_print */
  3229. 0, /* tp_getattr */
  3230. 0, /* tp_setattr */
  3231. 0, /* tp_compare */
  3232. (reprfunc)cdatafrombuf_repr, /* tp_repr */
  3233. 0, /* inherited */ /* tp_as_number */
  3234. 0, /* tp_as_sequence */
  3235. 0, /* inherited */ /* tp_as_mapping */
  3236. 0, /* inherited */ /* tp_hash */
  3237. 0, /* inherited */ /* tp_call */
  3238. 0, /* tp_str */
  3239. 0, /* inherited */ /* tp_getattro */
  3240. 0, /* inherited */ /* tp_setattro */
  3241. 0, /* tp_as_buffer */
  3242. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES /* tp_flags */
  3243. | Py_TPFLAGS_HAVE_GC,
  3244. "This is an internal subtype of _CDataBase for performance only on "
  3245. "CPython. Check with isinstance(x, ffi.CData).", /* tp_doc */
  3246. (traverseproc)cdatafrombuf_traverse, /* tp_traverse */
  3247. (inquiry)cdatafrombuf_clear, /* tp_clear */
  3248. 0, /* inherited */ /* tp_richcompare */
  3249. 0, /* inherited */ /* tp_weaklistoffset */
  3250. 0, /* inherited */ /* tp_iter */
  3251. 0, /* tp_iternext */
  3252. 0, /* inherited */ /* tp_methods */
  3253. 0, /* tp_members */
  3254. 0, /* tp_getset */
  3255. &CData_Type, /* tp_base */
  3256. 0, /* tp_dict */
  3257. 0, /* tp_descr_get */
  3258. 0, /* tp_descr_set */
  3259. 0, /* tp_dictoffset */
  3260. 0, /* tp_init */
  3261. 0, /* tp_alloc */
  3262. 0, /* tp_new */
  3263. PyObject_GC_Del, /* tp_free */
  3264. };
  3265. static PyTypeObject CDataGCP_Type = {
  3266. PyVarObject_HEAD_INIT(NULL, 0)
  3267. "_cffi_backend.__CDataGCP",
  3268. sizeof(CDataObject_gcp),
  3269. 0,
  3270. (destructor)cdatagcp_dealloc, /* tp_dealloc */
  3271. 0, /* tp_print */
  3272. 0, /* tp_getattr */
  3273. 0, /* tp_setattr */
  3274. 0, /* tp_compare */
  3275. 0, /* inherited */ /* tp_repr */
  3276. 0, /* inherited */ /* tp_as_number */
  3277. 0, /* tp_as_sequence */
  3278. 0, /* inherited */ /* tp_as_mapping */
  3279. 0, /* inherited */ /* tp_hash */
  3280. 0, /* inherited */ /* tp_call */
  3281. 0, /* tp_str */
  3282. 0, /* inherited */ /* tp_getattro */
  3283. 0, /* inherited */ /* tp_setattro */
  3284. 0, /* tp_as_buffer */
  3285. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES /* tp_flags */
  3286. #ifdef Py_TPFLAGS_HAVE_FINALIZE
  3287. | Py_TPFLAGS_HAVE_FINALIZE
  3288. #endif
  3289. | Py_TPFLAGS_HAVE_GC,
  3290. "This is an internal subtype of _CDataBase for performance only on "
  3291. "CPython. Check with isinstance(x, ffi.CData).", /* tp_doc */
  3292. (traverseproc)cdatagcp_traverse, /* tp_traverse */
  3293. 0, /* tp_clear */
  3294. 0, /* inherited */ /* tp_richcompare */
  3295. 0, /* inherited */ /* tp_weaklistoffset */
  3296. 0, /* inherited */ /* tp_iter */
  3297. 0, /* tp_iternext */
  3298. 0, /* inherited */ /* tp_methods */
  3299. 0, /* tp_members */
  3300. 0, /* tp_getset */
  3301. &CData_Type, /* tp_base */
  3302. #ifdef Py_TPFLAGS_HAVE_FINALIZE /* CPython >= 3.4 */
  3303. 0, /* tp_dict */
  3304. 0, /* tp_descr_get */
  3305. 0, /* tp_descr_set */
  3306. 0, /* tp_dictoffset */
  3307. 0, /* tp_init */
  3308. 0, /* tp_alloc */
  3309. 0, /* tp_new */
  3310. 0, /* inherited */ /* tp_free */
  3311. 0, /* tp_is_gc */
  3312. 0, /* tp_bases */
  3313. 0, /* tp_mro */
  3314. 0, /* tp_cache */
  3315. 0, /* tp_subclasses */
  3316. 0, /* tp_weaklist */
  3317. 0, /* tp_del */
  3318. 0, /* version_tag */
  3319. (destructor)cdatagcp_finalize, /* tp_finalize */
  3320. #endif
  3321. };
  3322. /************************************************************/
  3323. typedef struct {
  3324. PyObject_HEAD
  3325. char *di_next, *di_stop;
  3326. CDataObject *di_object;
  3327. CTypeDescrObject *di_itemtype;
  3328. } CDataIterObject;
  3329. static PyObject *
  3330. cdataiter_next(CDataIterObject *it)
  3331. {
  3332. char *result = it->di_next;
  3333. if (result != it->di_stop) {
  3334. it->di_next = result + it->di_itemtype->ct_size;
  3335. return convert_to_object(result, it->di_itemtype);
  3336. }
  3337. return NULL;
  3338. }
  3339. static void
  3340. cdataiter_dealloc(CDataIterObject *it)
  3341. {
  3342. Py_DECREF(it->di_object);
  3343. PyObject_Del(it);
  3344. }
  3345. static PyTypeObject CDataIter_Type = {
  3346. PyVarObject_HEAD_INIT(NULL, 0)
  3347. "_cffi_backend.__CData_iterator", /* tp_name */
  3348. sizeof(CDataIterObject), /* tp_basicsize */
  3349. 0, /* tp_itemsize */
  3350. /* methods */
  3351. (destructor)cdataiter_dealloc, /* tp_dealloc */
  3352. 0, /* tp_print */
  3353. 0, /* tp_getattr */
  3354. 0, /* tp_setattr */
  3355. 0, /* tp_compare */
  3356. 0, /* tp_repr */
  3357. 0, /* tp_as_number */
  3358. 0, /* tp_as_sequence */
  3359. 0, /* tp_as_mapping */
  3360. 0, /* tp_hash */
  3361. 0, /* tp_call */
  3362. 0, /* tp_str */
  3363. PyObject_GenericGetAttr, /* tp_getattro */
  3364. 0, /* tp_setattro */
  3365. 0, /* tp_as_buffer */
  3366. Py_TPFLAGS_DEFAULT, /* tp_flags */
  3367. 0, /* tp_doc */
  3368. 0, /* tp_traverse */
  3369. 0, /* tp_clear */
  3370. 0, /* tp_richcompare */
  3371. 0, /* tp_weaklistoffset */
  3372. PyObject_SelfIter, /* tp_iter */
  3373. (iternextfunc)cdataiter_next, /* tp_iternext */
  3374. };
  3375. static PyObject *
  3376. cdata_iter(CDataObject *cd)
  3377. {
  3378. CDataIterObject *it;
  3379. if (!(cd->c_type->ct_flags & CT_ARRAY)) {
  3380. PyErr_Format(PyExc_TypeError, "cdata '%s' does not support iteration",
  3381. cd->c_type->ct_name);
  3382. return NULL;
  3383. }
  3384. it = PyObject_New(CDataIterObject, &CDataIter_Type);
  3385. if (it == NULL)
  3386. return NULL;
  3387. Py_INCREF(cd);
  3388. it->di_object = cd;
  3389. it->di_itemtype = cd->c_type->ct_itemdescr;
  3390. it->di_next = cd->c_data;
  3391. it->di_stop = cd->c_data + get_array_length(cd) * it->di_itemtype->ct_size;
  3392. return (PyObject *)it;
  3393. }
  3394. /************************************************************/
  3395. static CDataObject *allocate_owning_object(Py_ssize_t size,
  3396. CTypeDescrObject *ct,
  3397. int dont_clear)
  3398. {
  3399. /* note: objects with &CDataOwning_Type are always allocated with
  3400. either a plain malloc() or calloc(), and freed with free(). */
  3401. CDataObject *cd;
  3402. if (dont_clear)
  3403. cd = malloc(size);
  3404. else
  3405. cd = calloc(size, 1);
  3406. if (PyObject_Init((PyObject *)cd, &CDataOwning_Type) == NULL)
  3407. return NULL;
  3408. Py_INCREF(ct);
  3409. cd->c_type = ct;
  3410. cd->c_weakreflist = NULL;
  3411. return cd;
  3412. }
  3413. static PyObject *
  3414. convert_struct_to_owning_object(char *data, CTypeDescrObject *ct)
  3415. {
  3416. /* also accepts unions, for the API mode */
  3417. CDataObject *cd;
  3418. Py_ssize_t dataoffset = offsetof(CDataObject_own_nolength, alignment);
  3419. Py_ssize_t datasize = ct->ct_size;
  3420. if (datasize < 0) {
  3421. PyErr_SetString(PyExc_TypeError,
  3422. "return type is an opaque structure or union");
  3423. return NULL;
  3424. }
  3425. if (ct->ct_flags & CT_WITH_VAR_ARRAY) {
  3426. PyErr_SetString(PyExc_TypeError,
  3427. "return type is a struct/union with a varsize array member");
  3428. return NULL;
  3429. }
  3430. cd = allocate_owning_object(dataoffset + datasize, ct, /*dont_clear=*/1);
  3431. if (cd == NULL)
  3432. return NULL;
  3433. cd->c_data = ((char *)cd) + dataoffset;
  3434. memcpy(cd->c_data, data, datasize);
  3435. return (PyObject *)cd;
  3436. }
  3437. static CDataObject *allocate_gcp_object(CDataObject *origobj,
  3438. CTypeDescrObject *ct,
  3439. PyObject *destructor)
  3440. {
  3441. CDataObject_gcp *cd = PyObject_GC_New(CDataObject_gcp, &CDataGCP_Type);
  3442. if (cd == NULL)
  3443. return NULL;
  3444. Py_XINCREF(destructor);
  3445. Py_INCREF(origobj);
  3446. Py_INCREF(ct);
  3447. cd->head.c_data = origobj->c_data;
  3448. cd->head.c_type = ct;
  3449. cd->head.c_weakreflist = NULL;
  3450. cd->origobj = (PyObject *)origobj;
  3451. cd->destructor = destructor;
  3452. PyObject_GC_Track(cd);
  3453. return (CDataObject *)cd;
  3454. }
  3455. static CDataObject *allocate_with_allocator(Py_ssize_t basesize,
  3456. Py_ssize_t datasize,
  3457. CTypeDescrObject *ct,
  3458. const cffi_allocator_t *allocator)
  3459. {
  3460. CDataObject *cd;
  3461. if (allocator->ca_alloc == NULL) {
  3462. cd = allocate_owning_object(basesize + datasize, ct,
  3463. allocator->ca_dont_clear);
  3464. if (cd == NULL)
  3465. return NULL;
  3466. cd->c_data = ((char *)cd) + basesize;
  3467. }
  3468. else {
  3469. PyObject *res = PyObject_CallFunction(allocator->ca_alloc, "n", datasize);
  3470. if (res == NULL)
  3471. return NULL;
  3472. if (!CData_Check(res)) {
  3473. PyErr_Format(PyExc_TypeError,
  3474. "alloc() must return a cdata object (got %.200s)",
  3475. Py_TYPE(res)->tp_name);
  3476. Py_DECREF(res);
  3477. return NULL;
  3478. }
  3479. cd = (CDataObject *)res;
  3480. if (!(cd->c_type->ct_flags & (CT_POINTER|CT_ARRAY))) {
  3481. PyErr_Format(PyExc_TypeError,
  3482. "alloc() must return a cdata pointer, not '%s'",
  3483. cd->c_type->ct_name);
  3484. Py_DECREF(res);
  3485. return NULL;
  3486. }
  3487. if (!cd->c_data) {
  3488. PyErr_SetString(PyExc_MemoryError, "alloc() returned NULL");
  3489. Py_DECREF(res);
  3490. return NULL;
  3491. }
  3492. cd = allocate_gcp_object(cd, ct, allocator->ca_free);
  3493. Py_DECREF(res);
  3494. if (!allocator->ca_dont_clear)
  3495. memset(cd->c_data, 0, datasize);
  3496. }
  3497. return cd;
  3498. }
  3499. static PyObject *direct_newp(CTypeDescrObject *ct, PyObject *init,
  3500. const cffi_allocator_t *allocator)
  3501. {
  3502. CTypeDescrObject *ctitem;
  3503. CDataObject *cd;
  3504. Py_ssize_t dataoffset, datasize, explicitlength;
  3505. explicitlength = -1;
  3506. if (ct->ct_flags & CT_POINTER) {
  3507. dataoffset = offsetof(CDataObject_own_nolength, alignment);
  3508. ctitem = ct->ct_itemdescr;
  3509. datasize = ctitem->ct_size;
  3510. if (datasize < 0) {
  3511. PyErr_Format(PyExc_TypeError,
  3512. "cannot instantiate ctype '%s' of unknown size",
  3513. ctitem->ct_name);
  3514. return NULL;
  3515. }
  3516. if (ctitem->ct_flags & CT_PRIMITIVE_CHAR)
  3517. datasize *= 2; /* forcefully add another character: a null */
  3518. if (ctitem->ct_flags & (CT_STRUCT | CT_UNION)) {
  3519. if (force_lazy_struct(ctitem) < 0) /* for CT_WITH_VAR_ARRAY */
  3520. return NULL;
  3521. if (ctitem->ct_flags & CT_WITH_VAR_ARRAY) {
  3522. assert(ct->ct_flags & CT_IS_PTR_TO_OWNED);
  3523. dataoffset = offsetof(CDataObject_own_length, alignment);
  3524. if (init != Py_None) {
  3525. Py_ssize_t optvarsize = datasize;
  3526. if (convert_struct_from_object(NULL, ctitem, init,
  3527. &optvarsize) < 0)
  3528. return NULL;
  3529. datasize = optvarsize;
  3530. }
  3531. }
  3532. }
  3533. }
  3534. else if (ct->ct_flags & CT_ARRAY) {
  3535. dataoffset = offsetof(CDataObject_own_nolength, alignment);
  3536. datasize = ct->ct_size;
  3537. if (datasize < 0) {
  3538. explicitlength = get_new_array_length(ct->ct_itemdescr, &init);
  3539. if (explicitlength < 0)
  3540. return NULL;
  3541. ctitem = ct->ct_itemdescr;
  3542. dataoffset = offsetof(CDataObject_own_length, alignment);
  3543. datasize = MUL_WRAPAROUND(explicitlength, ctitem->ct_size);
  3544. if (explicitlength > 0 &&
  3545. (datasize / explicitlength) != ctitem->ct_size) {
  3546. PyErr_SetString(PyExc_OverflowError,
  3547. "array size would overflow a Py_ssize_t");
  3548. return NULL;
  3549. }
  3550. }
  3551. }
  3552. else {
  3553. PyErr_Format(PyExc_TypeError,
  3554. "expected a pointer or array ctype, got '%s'",
  3555. ct->ct_name);
  3556. return NULL;
  3557. }
  3558. if (ct->ct_flags & CT_IS_PTR_TO_OWNED) {
  3559. /* common case of ptr-to-struct (or ptr-to-union): for this case
  3560. we build two objects instead of one, with the memory-owning
  3561. one being really the struct (or union) and the returned one
  3562. having a strong reference to it */
  3563. CDataObject *cds;
  3564. cds = allocate_with_allocator(dataoffset, datasize, ct->ct_itemdescr,
  3565. allocator);
  3566. if (cds == NULL)
  3567. return NULL;
  3568. cd = allocate_owning_object(sizeof(CDataObject_own_structptr), ct,
  3569. /*dont_clear=*/1);
  3570. if (cd == NULL) {
  3571. Py_DECREF(cds);
  3572. return NULL;
  3573. }
  3574. /* store the only reference to cds into cd */
  3575. ((CDataObject_own_structptr *)cd)->structobj = (PyObject *)cds;
  3576. /* store information about the allocated size of the struct */
  3577. if (dataoffset == offsetof(CDataObject_own_length, alignment)) {
  3578. ((CDataObject_own_length *)cds)->length = datasize;
  3579. }
  3580. assert(explicitlength < 0);
  3581. cd->c_data = cds->c_data;
  3582. }
  3583. else {
  3584. cd = allocate_with_allocator(dataoffset, datasize, ct, allocator);
  3585. if (cd == NULL)
  3586. return NULL;
  3587. if (explicitlength >= 0)
  3588. ((CDataObject_own_length*)cd)->length = explicitlength;
  3589. }
  3590. if (init != Py_None) {
  3591. if (convert_from_object(cd->c_data,
  3592. (ct->ct_flags & CT_POINTER) ? ct->ct_itemdescr : ct, init) < 0) {
  3593. Py_DECREF(cd);
  3594. return NULL;
  3595. }
  3596. }
  3597. return (PyObject *)cd;
  3598. }
  3599. static PyObject *b_newp(PyObject *self, PyObject *args)
  3600. {
  3601. CTypeDescrObject *ct;
  3602. PyObject *init = Py_None;
  3603. if (!PyArg_ParseTuple(args, "O!|O:newp", &CTypeDescr_Type, &ct, &init))
  3604. return NULL;
  3605. return direct_newp(ct, init, &default_allocator);
  3606. }
  3607. static int
  3608. _my_PyObject_AsBool(PyObject *ob)
  3609. {
  3610. /* convert and cast a Python object to a boolean. Accept an integer
  3611. or a float object, up to a CData 'long double'. */
  3612. PyObject *io;
  3613. PyNumberMethods *nb;
  3614. int res;
  3615. #if PY_MAJOR_VERSION < 3
  3616. if (PyInt_Check(ob)) {
  3617. return PyInt_AS_LONG(ob) != 0;
  3618. }
  3619. else
  3620. #endif
  3621. if (PyLong_Check(ob)) {
  3622. return _PyLong_Sign(ob) != 0;
  3623. }
  3624. else if (PyFloat_Check(ob)) {
  3625. return PyFloat_AS_DOUBLE(ob) != 0.0;
  3626. }
  3627. else if (CData_Check(ob)) {
  3628. CDataObject *cd = (CDataObject *)ob;
  3629. if (cd->c_type->ct_flags & CT_PRIMITIVE_FLOAT) {
  3630. /*READ(cd->c_data, cd->c_type->ct_size)*/
  3631. if (cd->c_type->ct_flags & CT_IS_LONGDOUBLE) {
  3632. /* 'long double' objects: return the answer directly */
  3633. return read_raw_longdouble_data(cd->c_data) != 0.0;
  3634. }
  3635. else {
  3636. /* 'float'/'double' objects: return the answer directly */
  3637. return read_raw_float_data(cd->c_data,
  3638. cd->c_type->ct_size) != 0.0;
  3639. }
  3640. }
  3641. }
  3642. nb = ob->ob_type->tp_as_number;
  3643. if (nb == NULL || (nb->nb_float == NULL && nb->nb_int == NULL)) {
  3644. PyErr_SetString(PyExc_TypeError, "integer/float expected");
  3645. return -1;
  3646. }
  3647. if (nb->nb_float && !CData_Check(ob))
  3648. io = (*nb->nb_float) (ob);
  3649. else
  3650. io = (*nb->nb_int) (ob);
  3651. if (io == NULL)
  3652. return -1;
  3653. if (PyIntOrLong_Check(io) || PyFloat_Check(io)) {
  3654. res = _my_PyObject_AsBool(io);
  3655. }
  3656. else {
  3657. PyErr_SetString(PyExc_TypeError, "integer/float conversion failed");
  3658. res = -1;
  3659. }
  3660. Py_DECREF(io);
  3661. return res;
  3662. }
  3663. static CDataObject *_new_casted_primitive(CTypeDescrObject *ct)
  3664. {
  3665. int dataoffset = offsetof(CDataObject_casted_primitive, alignment);
  3666. CDataObject *cd = (CDataObject *)PyObject_Malloc(dataoffset + ct->ct_size);
  3667. if (PyObject_Init((PyObject *)cd, &CData_Type) == NULL)
  3668. return NULL;
  3669. Py_INCREF(ct);
  3670. cd->c_type = ct;
  3671. cd->c_data = ((char*)cd) + dataoffset;
  3672. cd->c_weakreflist = NULL;
  3673. return cd;
  3674. }
  3675. static CDataObject *cast_to_integer_or_char(CTypeDescrObject *ct, PyObject *ob)
  3676. {
  3677. unsigned PY_LONG_LONG value;
  3678. CDataObject *cd;
  3679. if (CData_Check(ob) &&
  3680. ((CDataObject *)ob)->c_type->ct_flags &
  3681. (CT_POINTER|CT_FUNCTIONPTR|CT_ARRAY)) {
  3682. value = (Py_intptr_t)((CDataObject *)ob)->c_data;
  3683. }
  3684. #if PY_MAJOR_VERSION < 3
  3685. else if (PyString_Check(ob)) {
  3686. if (PyString_GET_SIZE(ob) != 1) {
  3687. PyErr_Format(PyExc_TypeError,
  3688. "cannot cast string of length %zd to ctype '%s'",
  3689. PyString_GET_SIZE(ob), ct->ct_name);
  3690. return NULL;
  3691. }
  3692. value = (unsigned char)PyString_AS_STRING(ob)[0];
  3693. }
  3694. #endif
  3695. else if (PyUnicode_Check(ob)) {
  3696. char err_buf[80];
  3697. cffi_char32_t ordinal;
  3698. if (_my_PyUnicode_AsSingleChar32(ob, &ordinal, err_buf) < 0) {
  3699. PyErr_Format(PyExc_TypeError,
  3700. "cannot cast %s to ctype '%s'", err_buf, ct->ct_name);
  3701. return NULL;
  3702. }
  3703. /* the types char16_t and char32_t are both unsigned. However,
  3704. wchar_t might be signed. In theory it does not matter,
  3705. because 'ordinal' comes from a regular Python unicode. */
  3706. #ifdef HAVE_WCHAR_H
  3707. if (ct->ct_flags & CT_IS_SIGNED_WCHAR)
  3708. value = (wchar_t)ordinal;
  3709. else
  3710. #endif
  3711. value = ordinal;
  3712. }
  3713. else if (PyBytes_Check(ob)) {
  3714. int res = _convert_to_char(ob);
  3715. if (res < 0)
  3716. return NULL;
  3717. value = (unsigned char)res;
  3718. }
  3719. else if (ct->ct_flags & CT_IS_BOOL) {
  3720. int res = _my_PyObject_AsBool(ob);
  3721. if (res < 0)
  3722. return NULL;
  3723. value = res;
  3724. }
  3725. else {
  3726. value = _my_PyLong_AsUnsignedLongLong(ob, 0);
  3727. if (value == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
  3728. return NULL;
  3729. }
  3730. if (ct->ct_flags & CT_IS_BOOL)
  3731. value = !!value;
  3732. cd = _new_casted_primitive(ct);
  3733. if (cd != NULL)
  3734. write_raw_integer_data(cd->c_data, value, ct->ct_size);
  3735. return cd;
  3736. }
  3737. /* returns -1 if cannot cast, 0 if we don't get a value, 1 if we do */
  3738. static int check_bytes_for_float_compatible(PyObject *io, double *out_value)
  3739. {
  3740. if (PyBytes_Check(io)) {
  3741. if (PyBytes_GET_SIZE(io) != 1)
  3742. goto error;
  3743. *out_value = (unsigned char)PyBytes_AS_STRING(io)[0];
  3744. return 1;
  3745. }
  3746. else if (PyUnicode_Check(io)) {
  3747. char ignored[80];
  3748. cffi_char32_t ordinal;
  3749. if (_my_PyUnicode_AsSingleChar32(io, &ordinal, ignored) < 0)
  3750. goto error;
  3751. /* the signness of the 32-bit version of wide chars should not
  3752. * matter here, because 'ordinal' comes from a normal Python
  3753. * unicode string */
  3754. *out_value = ordinal;
  3755. return 1;
  3756. }
  3757. *out_value = 0; /* silence a gcc warning if this function is inlined */
  3758. return 0;
  3759. error:
  3760. Py_DECREF(io);
  3761. *out_value = 0; /* silence a gcc warning if this function is inlined */
  3762. return -1;
  3763. }
  3764. static PyObject *do_cast(CTypeDescrObject *ct, PyObject *ob)
  3765. {
  3766. CDataObject *cd;
  3767. if (ct->ct_flags & (CT_POINTER|CT_FUNCTIONPTR|CT_ARRAY) &&
  3768. ct->ct_size >= 0) {
  3769. /* cast to a pointer, to a funcptr, or to an array.
  3770. Note that casting to an array is an extension to the C language,
  3771. which seems to be necessary in order to sanely get a
  3772. <cdata 'int[3]'> at some address. */
  3773. unsigned PY_LONG_LONG value;
  3774. if (CData_Check(ob)) {
  3775. CDataObject *cdsrc = (CDataObject *)ob;
  3776. if (cdsrc->c_type->ct_flags &
  3777. (CT_POINTER|CT_FUNCTIONPTR|CT_ARRAY)) {
  3778. return new_simple_cdata(cdsrc->c_data, ct);
  3779. }
  3780. }
  3781. if ((ct->ct_flags & CT_POINTER) &&
  3782. (ct->ct_itemdescr->ct_flags & CT_IS_FILE) &&
  3783. PyFile_Check(ob)) {
  3784. FILE *f = PyFile_AsFile(ob);
  3785. if (f == NULL && PyErr_Occurred())
  3786. return NULL;
  3787. return new_simple_cdata((char *)f, ct);
  3788. }
  3789. value = _my_PyLong_AsUnsignedLongLong(ob, 0);
  3790. if (value == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
  3791. return NULL;
  3792. return new_simple_cdata((char *)(Py_intptr_t)value, ct);
  3793. }
  3794. else if (ct->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_UNSIGNED
  3795. |CT_PRIMITIVE_CHAR)) {
  3796. /* cast to an integer type or a char */
  3797. return (PyObject *)cast_to_integer_or_char(ct, ob);
  3798. }
  3799. else if (ct->ct_flags & CT_PRIMITIVE_FLOAT) {
  3800. /* cast to a float */
  3801. double value;
  3802. PyObject *io;
  3803. int res;
  3804. if (CData_Check(ob)) {
  3805. CDataObject *cdsrc = (CDataObject *)ob;
  3806. if (!(cdsrc->c_type->ct_flags & CT_PRIMITIVE_ANY))
  3807. goto cannot_cast;
  3808. io = convert_to_object(cdsrc->c_data, cdsrc->c_type);
  3809. if (io == NULL)
  3810. return NULL;
  3811. }
  3812. else {
  3813. io = ob;
  3814. Py_INCREF(io);
  3815. }
  3816. res = check_bytes_for_float_compatible(io, &value);
  3817. if (res == -1)
  3818. goto cannot_cast;
  3819. if (res == 0) {
  3820. if ((ct->ct_flags & CT_IS_LONGDOUBLE) &&
  3821. CData_Check(io) &&
  3822. (((CDataObject *)io)->c_type->ct_flags & CT_IS_LONGDOUBLE)) {
  3823. long double lvalue;
  3824. char *data = ((CDataObject *)io)->c_data;
  3825. /*READ(data, sizeof(long double)*/
  3826. lvalue = read_raw_longdouble_data(data);
  3827. Py_DECREF(io);
  3828. cd = _new_casted_primitive(ct);
  3829. if (cd != NULL)
  3830. write_raw_longdouble_data(cd->c_data, lvalue);
  3831. return (PyObject *)cd;
  3832. }
  3833. value = PyFloat_AsDouble(io);
  3834. }
  3835. Py_DECREF(io);
  3836. if (value == -1.0 && PyErr_Occurred())
  3837. return NULL;
  3838. cd = _new_casted_primitive(ct);
  3839. if (cd != NULL) {
  3840. if (!(ct->ct_flags & CT_IS_LONGDOUBLE))
  3841. write_raw_float_data(cd->c_data, value, ct->ct_size);
  3842. else
  3843. write_raw_longdouble_data(cd->c_data, (long double)value);
  3844. }
  3845. return (PyObject *)cd;
  3846. }
  3847. else if (ct->ct_flags & CT_PRIMITIVE_COMPLEX) {
  3848. /* cast to a complex */
  3849. Py_complex value;
  3850. PyObject *io;
  3851. int res;
  3852. if (CData_Check(ob)) {
  3853. CDataObject *cdsrc = (CDataObject *)ob;
  3854. if (!(cdsrc->c_type->ct_flags & CT_PRIMITIVE_ANY))
  3855. goto cannot_cast;
  3856. io = convert_to_object(cdsrc->c_data, cdsrc->c_type);
  3857. if (io == NULL)
  3858. return NULL;
  3859. }
  3860. else {
  3861. io = ob;
  3862. Py_INCREF(io);
  3863. }
  3864. res = check_bytes_for_float_compatible(io, &value.real);
  3865. if (res == -1)
  3866. goto cannot_cast;
  3867. if (res == 1) {
  3868. // got it from string
  3869. value.imag = 0.0;
  3870. } else {
  3871. value = PyComplex_AsCComplex(io);
  3872. }
  3873. Py_DECREF(io);
  3874. if (PyErr_Occurred()) {
  3875. return NULL;
  3876. }
  3877. cd = _new_casted_primitive(ct);
  3878. if (cd != NULL) {
  3879. write_raw_complex_data(cd->c_data, value, ct->ct_size);
  3880. }
  3881. return (PyObject *)cd;
  3882. }
  3883. else {
  3884. PyErr_Format(PyExc_TypeError, "cannot cast to ctype '%s'",
  3885. ct->ct_name);
  3886. return NULL;
  3887. }
  3888. cannot_cast:
  3889. if (CData_Check(ob))
  3890. PyErr_Format(PyExc_TypeError, "cannot cast ctype '%s' to ctype '%s'",
  3891. ((CDataObject *)ob)->c_type->ct_name, ct->ct_name);
  3892. else
  3893. PyErr_Format(PyExc_TypeError,
  3894. "cannot cast %.200s object to ctype '%s'",
  3895. Py_TYPE(ob)->tp_name, ct->ct_name);
  3896. return NULL;
  3897. }
  3898. static PyObject *b_cast(PyObject *self, PyObject *args)
  3899. {
  3900. CTypeDescrObject *ct;
  3901. PyObject *ob;
  3902. if (!PyArg_ParseTuple(args, "O!O:cast", &CTypeDescr_Type, &ct, &ob))
  3903. return NULL;
  3904. return do_cast(ct, ob);
  3905. }
  3906. /************************************************************/
  3907. typedef struct {
  3908. PyObject_HEAD
  3909. void *dl_handle;
  3910. char *dl_name;
  3911. int dl_auto_close;
  3912. } DynLibObject;
  3913. static void dl_dealloc(DynLibObject *dlobj)
  3914. {
  3915. if (dlobj->dl_handle != NULL && dlobj->dl_auto_close)
  3916. dlclose(dlobj->dl_handle);
  3917. free(dlobj->dl_name);
  3918. PyObject_Del(dlobj);
  3919. }
  3920. static PyObject *dl_repr(DynLibObject *dlobj)
  3921. {
  3922. return PyText_FromFormat("<clibrary '%s'>", dlobj->dl_name);
  3923. }
  3924. static int dl_check_closed(DynLibObject *dlobj)
  3925. {
  3926. if (dlobj->dl_handle == NULL)
  3927. {
  3928. PyErr_Format(PyExc_ValueError, "library '%s' has already been closed",
  3929. dlobj->dl_name);
  3930. return -1;
  3931. }
  3932. return 0;
  3933. }
  3934. static PyObject *dl_load_function(DynLibObject *dlobj, PyObject *args)
  3935. {
  3936. CTypeDescrObject *ct;
  3937. char *funcname;
  3938. void *funcptr;
  3939. if (!PyArg_ParseTuple(args, "O!s:load_function",
  3940. &CTypeDescr_Type, &ct, &funcname))
  3941. return NULL;
  3942. if (dl_check_closed(dlobj) < 0)
  3943. return NULL;
  3944. if (!(ct->ct_flags & (CT_FUNCTIONPTR | CT_POINTER | CT_ARRAY))) {
  3945. PyErr_Format(PyExc_TypeError,
  3946. "function or pointer or array cdata expected, got '%s'",
  3947. ct->ct_name);
  3948. return NULL;
  3949. }
  3950. dlerror(); /* clear error condition */
  3951. funcptr = dlsym(dlobj->dl_handle, funcname);
  3952. if (funcptr == NULL) {
  3953. const char *error = dlerror();
  3954. PyErr_Format(PyExc_AttributeError,
  3955. "function/symbol '%s' not found in library '%s': %s",
  3956. funcname, dlobj->dl_name, error);
  3957. return NULL;
  3958. }
  3959. if ((ct->ct_flags & CT_ARRAY) && ct->ct_length < 0) {
  3960. ct = (CTypeDescrObject *)ct->ct_stuff;
  3961. }
  3962. return new_simple_cdata(funcptr, ct);
  3963. }
  3964. static PyObject *dl_read_variable(DynLibObject *dlobj, PyObject *args)
  3965. {
  3966. CTypeDescrObject *ct;
  3967. char *varname;
  3968. char *data;
  3969. if (!PyArg_ParseTuple(args, "O!s:read_variable",
  3970. &CTypeDescr_Type, &ct, &varname))
  3971. return NULL;
  3972. if (dl_check_closed(dlobj) < 0)
  3973. return NULL;
  3974. dlerror(); /* clear error condition */
  3975. data = dlsym(dlobj->dl_handle, varname);
  3976. if (data == NULL) {
  3977. const char *error = dlerror();
  3978. if (error != NULL) {
  3979. PyErr_Format(PyExc_KeyError,
  3980. "variable '%s' not found in library '%s': %s",
  3981. varname, dlobj->dl_name, error);
  3982. return NULL;
  3983. }
  3984. }
  3985. return convert_to_object(data, ct);
  3986. }
  3987. static PyObject *dl_write_variable(DynLibObject *dlobj, PyObject *args)
  3988. {
  3989. CTypeDescrObject *ct;
  3990. PyObject *value;
  3991. char *varname;
  3992. char *data;
  3993. if (!PyArg_ParseTuple(args, "O!sO:write_variable",
  3994. &CTypeDescr_Type, &ct, &varname, &value))
  3995. return NULL;
  3996. if (dl_check_closed(dlobj) < 0)
  3997. return NULL;
  3998. dlerror(); /* clear error condition */
  3999. data = dlsym(dlobj->dl_handle, varname);
  4000. if (data == NULL) {
  4001. const char *error = dlerror();
  4002. PyErr_Format(PyExc_KeyError,
  4003. "variable '%s' not found in library '%s': %s",
  4004. varname, dlobj->dl_name, error);
  4005. return NULL;
  4006. }
  4007. if (convert_from_object(data, ct, value) < 0)
  4008. return NULL;
  4009. Py_INCREF(Py_None);
  4010. return Py_None;
  4011. }
  4012. static PyObject *dl_close_lib(DynLibObject *dlobj, PyObject *no_args)
  4013. {
  4014. if (dlobj->dl_handle != NULL)
  4015. {
  4016. dlclose(dlobj->dl_handle);
  4017. dlobj->dl_handle = NULL;
  4018. }
  4019. Py_INCREF(Py_None);
  4020. return Py_None;
  4021. }
  4022. static PyMethodDef dl_methods[] = {
  4023. {"load_function", (PyCFunction)dl_load_function, METH_VARARGS},
  4024. {"read_variable", (PyCFunction)dl_read_variable, METH_VARARGS},
  4025. {"write_variable", (PyCFunction)dl_write_variable, METH_VARARGS},
  4026. {"close_lib", (PyCFunction)dl_close_lib, METH_NOARGS},
  4027. {NULL, NULL} /* sentinel */
  4028. };
  4029. static PyTypeObject dl_type = {
  4030. PyVarObject_HEAD_INIT(NULL, 0)
  4031. "_cffi_backend.CLibrary", /* tp_name */
  4032. sizeof(DynLibObject), /* tp_basicsize */
  4033. 0, /* tp_itemsize */
  4034. /* methods */
  4035. (destructor)dl_dealloc, /* tp_dealloc */
  4036. 0, /* tp_print */
  4037. 0, /* tp_getattr */
  4038. 0, /* tp_setattr */
  4039. 0, /* tp_compare */
  4040. (reprfunc)dl_repr, /* tp_repr */
  4041. 0, /* tp_as_number */
  4042. 0, /* tp_as_sequence */
  4043. 0, /* tp_as_mapping */
  4044. 0, /* tp_hash */
  4045. 0, /* tp_call */
  4046. 0, /* tp_str */
  4047. PyObject_GenericGetAttr, /* tp_getattro */
  4048. 0, /* tp_setattro */
  4049. 0, /* tp_as_buffer */
  4050. Py_TPFLAGS_DEFAULT, /* tp_flags */
  4051. 0, /* tp_doc */
  4052. 0, /* tp_traverse */
  4053. 0, /* tp_clear */
  4054. 0, /* tp_richcompare */
  4055. 0, /* tp_weaklistoffset */
  4056. 0, /* tp_iter */
  4057. 0, /* tp_iternext */
  4058. dl_methods, /* tp_methods */
  4059. };
  4060. static void *b_do_dlopen(PyObject *args, const char **p_printable_filename,
  4061. PyObject **p_temp, int *auto_close)
  4062. {
  4063. /* Logic to call the correct version of dlopen(). Returns NULL in case of error.
  4064. Otherwise, '*p_printable_filename' will point to a printable char version of
  4065. the filename (maybe utf-8-encoded). '*p_temp' will be set either to NULL or
  4066. to a temporary object that must be freed after looking at printable_filename.
  4067. */
  4068. void *handle;
  4069. char *filename_or_null;
  4070. int flags = 0;
  4071. *p_temp = NULL;
  4072. *auto_close = 1;
  4073. if (PyTuple_GET_SIZE(args) == 0 || PyTuple_GET_ITEM(args, 0) == Py_None) {
  4074. PyObject *dummy;
  4075. if (!PyArg_ParseTuple(args, "|Oi:load_library",
  4076. &dummy, &flags))
  4077. return NULL;
  4078. filename_or_null = NULL;
  4079. *p_printable_filename = "<None>";
  4080. }
  4081. else if (CData_Check(PyTuple_GET_ITEM(args, 0)))
  4082. {
  4083. CDataObject *cd;
  4084. if (!PyArg_ParseTuple(args, "O|i:load_library", &cd, &flags))
  4085. return NULL;
  4086. /* 'flags' is accepted but ignored in this case */
  4087. if ((cd->c_type->ct_flags & CT_IS_VOID_PTR) == 0) {
  4088. PyErr_Format(PyExc_TypeError,
  4089. "dlopen() takes a file name or 'void *' handle, not '%s'",
  4090. cd->c_type->ct_name);
  4091. return NULL;
  4092. }
  4093. handle = cd->c_data;
  4094. if (handle == NULL) {
  4095. PyErr_Format(PyExc_RuntimeError, "cannot call dlopen(NULL)");
  4096. return NULL;
  4097. }
  4098. *p_temp = PyText_FromFormat("%p", handle);
  4099. *p_printable_filename = PyText_AsUTF8(*p_temp);
  4100. *auto_close = 0;
  4101. return handle;
  4102. }
  4103. else
  4104. {
  4105. PyObject *s = PyTuple_GET_ITEM(args, 0);
  4106. #ifdef MS_WIN32
  4107. PyObject *filename_unicode;
  4108. if (PyArg_ParseTuple(args, "U|i:load_library", &filename_unicode, &flags))
  4109. {
  4110. Py_ssize_t sz1;
  4111. wchar_t *w1;
  4112. #if PY_MAJOR_VERSION < 3
  4113. s = PyUnicode_AsUTF8String(s);
  4114. if (s == NULL)
  4115. return NULL;
  4116. *p_temp = s;
  4117. #endif
  4118. *p_printable_filename = PyText_AsUTF8(s);
  4119. if (*p_printable_filename == NULL)
  4120. return NULL;
  4121. sz1 = PyUnicode_GetSize(filename_unicode) + 1;
  4122. sz1 *= 2; /* should not be needed, but you never know */
  4123. w1 = alloca(sizeof(wchar_t) * sz1);
  4124. sz1 = PyUnicode_AsWideChar((PyUnicodeObject *)filename_unicode,
  4125. w1, sz1 - 1);
  4126. if (sz1 < 0)
  4127. return NULL;
  4128. w1[sz1] = 0;
  4129. handle = dlopenW(w1);
  4130. goto got_handle;
  4131. }
  4132. PyErr_Clear();
  4133. #endif
  4134. if (!PyArg_ParseTuple(args, "et|i:load_library",
  4135. Py_FileSystemDefaultEncoding, &filename_or_null, &flags))
  4136. return NULL;
  4137. #if PY_MAJOR_VERSION < 3
  4138. if (PyUnicode_Check(s))
  4139. {
  4140. s = PyUnicode_AsUTF8String(s);
  4141. if (s == NULL) {
  4142. PyMem_Free(filename_or_null);
  4143. return NULL;
  4144. }
  4145. *p_temp = s;
  4146. }
  4147. #endif
  4148. *p_printable_filename = PyText_AsUTF8(s);
  4149. if (*p_printable_filename == NULL) {
  4150. PyMem_Free(filename_or_null);
  4151. return NULL;
  4152. }
  4153. }
  4154. if ((flags & (RTLD_NOW | RTLD_LAZY)) == 0)
  4155. flags |= RTLD_NOW;
  4156. #ifdef MS_WIN32
  4157. if (filename_or_null == NULL) {
  4158. PyErr_SetString(PyExc_OSError, "dlopen(None) not supported on Windows");
  4159. return NULL;
  4160. }
  4161. #endif
  4162. handle = dlopen(filename_or_null, flags);
  4163. PyMem_Free(filename_or_null);
  4164. #ifdef MS_WIN32
  4165. got_handle:
  4166. #endif
  4167. if (handle == NULL) {
  4168. const char *error = dlerror();
  4169. PyErr_Format(PyExc_OSError, "cannot load library '%s': %s",
  4170. *p_printable_filename, error);
  4171. return NULL;
  4172. }
  4173. return handle;
  4174. }
  4175. static PyObject *b_load_library(PyObject *self, PyObject *args)
  4176. {
  4177. const char *printable_filename;
  4178. PyObject *temp;
  4179. void *handle;
  4180. DynLibObject *dlobj = NULL;
  4181. int auto_close;
  4182. handle = b_do_dlopen(args, &printable_filename, &temp, &auto_close);
  4183. if (handle == NULL)
  4184. goto error;
  4185. dlobj = PyObject_New(DynLibObject, &dl_type);
  4186. if (dlobj == NULL) {
  4187. dlclose(handle);
  4188. goto error;
  4189. }
  4190. dlobj->dl_handle = handle;
  4191. dlobj->dl_name = strdup(printable_filename);
  4192. dlobj->dl_auto_close = auto_close;
  4193. error:
  4194. Py_XDECREF(temp);
  4195. return (PyObject *)dlobj;
  4196. }
  4197. /************************************************************/
  4198. static PyObject *get_unique_type(CTypeDescrObject *x,
  4199. const void *unique_key[], long keylength)
  4200. {
  4201. /* Replace the CTypeDescrObject 'x' with a standardized one.
  4202. This either just returns x, or x is decrefed and a new reference
  4203. to the already-existing equivalent is returned.
  4204. In this function, 'x' always contains a reference that must be
  4205. either decrefed or returned.
  4206. Keys:
  4207. void ["void"]
  4208. primitive [&static_struct]
  4209. pointer [ctype]
  4210. array [ctype, length]
  4211. funcptr [ctresult, ellipsis+abi, num_args, ctargs...]
  4212. */
  4213. PyObject *key, *y, *res;
  4214. void *pkey;
  4215. key = PyBytes_FromStringAndSize(NULL, keylength * sizeof(void *));
  4216. if (key == NULL)
  4217. goto error;
  4218. pkey = PyBytes_AS_STRING(key);
  4219. memcpy(pkey, unique_key, keylength * sizeof(void *));
  4220. y = PyDict_GetItem(unique_cache, key);
  4221. if (y != NULL) {
  4222. Py_DECREF(key);
  4223. Py_INCREF(y);
  4224. Py_DECREF(x);
  4225. return y;
  4226. }
  4227. if (PyDict_SetItem(unique_cache, key, (PyObject *)x) < 0) {
  4228. Py_DECREF(key);
  4229. goto error;
  4230. }
  4231. /* Haaaack for our reference count hack: gcmodule.c must not see this
  4232. dictionary. The problem is that any PyDict_SetItem() notices that
  4233. 'x' is tracked and re-tracks the unique_cache dictionary. So here
  4234. we re-untrack it again... */
  4235. PyObject_GC_UnTrack(unique_cache);
  4236. assert(x->ct_unique_key == NULL);
  4237. x->ct_unique_key = key; /* the key will be freed in ctypedescr_dealloc() */
  4238. /* the 'value' in unique_cache doesn't count as 1, but don't use
  4239. Py_DECREF(x) here because it will confuse debug builds into thinking
  4240. there was an extra DECREF in total. */
  4241. res = (PyObject *)x;
  4242. Py_SET_REFCNT(res, Py_REFCNT(res) - 1);
  4243. return res;
  4244. error:
  4245. Py_DECREF(x);
  4246. return NULL;
  4247. }
  4248. /* according to the C standard, these types should be equivalent to the
  4249. _Complex types for the purposes of storage (not arguments in calls!) */
  4250. typedef float cffi_float_complex_t[2];
  4251. typedef double cffi_double_complex_t[2];
  4252. static PyObject *new_primitive_type(const char *name)
  4253. {
  4254. #define ENUM_PRIMITIVE_TYPES \
  4255. EPTYPE(c, char, CT_PRIMITIVE_CHAR) \
  4256. EPTYPE(s, short, CT_PRIMITIVE_SIGNED ) \
  4257. EPTYPE(i, int, CT_PRIMITIVE_SIGNED ) \
  4258. EPTYPE(l, long, CT_PRIMITIVE_SIGNED ) \
  4259. EPTYPE(ll, long long, CT_PRIMITIVE_SIGNED ) \
  4260. EPTYPE(sc, signed char, CT_PRIMITIVE_SIGNED ) \
  4261. EPTYPE(uc, unsigned char, CT_PRIMITIVE_UNSIGNED ) \
  4262. EPTYPE(us, unsigned short, CT_PRIMITIVE_UNSIGNED ) \
  4263. EPTYPE(ui, unsigned int, CT_PRIMITIVE_UNSIGNED ) \
  4264. EPTYPE(ul, unsigned long, CT_PRIMITIVE_UNSIGNED ) \
  4265. EPTYPE(ull, unsigned long long, CT_PRIMITIVE_UNSIGNED ) \
  4266. EPTYPE(f, float, CT_PRIMITIVE_FLOAT ) \
  4267. EPTYPE(d, double, CT_PRIMITIVE_FLOAT ) \
  4268. EPTYPE(ld, long double, CT_PRIMITIVE_FLOAT | CT_IS_LONGDOUBLE ) \
  4269. EPTYPE2(fc, "float _Complex", cffi_float_complex_t, CT_PRIMITIVE_COMPLEX ) \
  4270. EPTYPE2(dc, "double _Complex", cffi_double_complex_t, CT_PRIMITIVE_COMPLEX ) \
  4271. ENUM_PRIMITIVE_TYPES_WCHAR \
  4272. EPTYPE2(c16, "char16_t", cffi_char16_t, CT_PRIMITIVE_CHAR ) \
  4273. EPTYPE2(c32, "char32_t", cffi_char32_t, CT_PRIMITIVE_CHAR ) \
  4274. EPTYPE(b, _Bool, CT_PRIMITIVE_UNSIGNED | CT_IS_BOOL ) \
  4275. /* the following types are not primitive in the C sense */ \
  4276. EPTYPE(i8, int8_t, CT_PRIMITIVE_SIGNED) \
  4277. EPTYPE(u8, uint8_t, CT_PRIMITIVE_UNSIGNED) \
  4278. EPTYPE(i16, int16_t, CT_PRIMITIVE_SIGNED) \
  4279. EPTYPE(u16, uint16_t, CT_PRIMITIVE_UNSIGNED) \
  4280. EPTYPE(i32, int32_t, CT_PRIMITIVE_SIGNED) \
  4281. EPTYPE(u32, uint32_t, CT_PRIMITIVE_UNSIGNED) \
  4282. EPTYPE(i64, int64_t, CT_PRIMITIVE_SIGNED) \
  4283. EPTYPE(u64, uint64_t, CT_PRIMITIVE_UNSIGNED) \
  4284. EPTYPE(il8, int_least8_t, CT_PRIMITIVE_SIGNED) \
  4285. EPTYPE(ul8, uint_least8_t, CT_PRIMITIVE_UNSIGNED) \
  4286. EPTYPE(il16, int_least16_t, CT_PRIMITIVE_SIGNED) \
  4287. EPTYPE(ul16, uint_least16_t, CT_PRIMITIVE_UNSIGNED) \
  4288. EPTYPE(il32, int_least32_t, CT_PRIMITIVE_SIGNED) \
  4289. EPTYPE(ul32, uint_least32_t, CT_PRIMITIVE_UNSIGNED) \
  4290. EPTYPE(il64, int_least64_t, CT_PRIMITIVE_SIGNED) \
  4291. EPTYPE(ul64, uint_least64_t, CT_PRIMITIVE_UNSIGNED) \
  4292. EPTYPE(if8, int_fast8_t, CT_PRIMITIVE_SIGNED) \
  4293. EPTYPE(uf8, uint_fast8_t, CT_PRIMITIVE_UNSIGNED) \
  4294. EPTYPE(if16, int_fast16_t, CT_PRIMITIVE_SIGNED) \
  4295. EPTYPE(uf16, uint_fast16_t, CT_PRIMITIVE_UNSIGNED) \
  4296. EPTYPE(if32, int_fast32_t, CT_PRIMITIVE_SIGNED) \
  4297. EPTYPE(uf32, uint_fast32_t, CT_PRIMITIVE_UNSIGNED) \
  4298. EPTYPE(if64, int_fast64_t, CT_PRIMITIVE_SIGNED) \
  4299. EPTYPE(uf64, uint_fast64_t, CT_PRIMITIVE_UNSIGNED) \
  4300. EPTYPE(ip, intptr_t, CT_PRIMITIVE_SIGNED) \
  4301. EPTYPE(up, uintptr_t, CT_PRIMITIVE_UNSIGNED) \
  4302. EPTYPE(im, intmax_t, CT_PRIMITIVE_SIGNED) \
  4303. EPTYPE(um, uintmax_t, CT_PRIMITIVE_UNSIGNED) \
  4304. EPTYPE(pd, ptrdiff_t, CT_PRIMITIVE_SIGNED) \
  4305. EPTYPE(sz, size_t, CT_PRIMITIVE_UNSIGNED) \
  4306. EPTYPE2(ssz, "ssize_t", Py_ssize_t, CT_PRIMITIVE_SIGNED)
  4307. #ifdef HAVE_WCHAR_H
  4308. # define ENUM_PRIMITIVE_TYPES_WCHAR \
  4309. EPTYPE(wc, wchar_t, CT_PRIMITIVE_CHAR | \
  4310. (((wchar_t)-1) > 0 ? 0 : CT_IS_SIGNED_WCHAR))
  4311. #else
  4312. # define ENUM_PRIMITIVE_TYPES_WCHAR /* nothing */
  4313. #endif
  4314. #define EPTYPE(code, typename, flags) EPTYPE2(code, #typename, typename, flags)
  4315. #define EPTYPE2(code, export_name, typename, flags) \
  4316. struct aligncheck_##code { char x; typename y; };
  4317. ENUM_PRIMITIVE_TYPES
  4318. #undef EPTYPE2
  4319. CTypeDescrObject *td;
  4320. static const struct descr_s { const char *name; int size, align, flags; }
  4321. types[] = {
  4322. #define EPTYPE2(code, export_name, typename, flags) \
  4323. { export_name, \
  4324. sizeof(typename), \
  4325. offsetof(struct aligncheck_##code, y), \
  4326. flags \
  4327. },
  4328. ENUM_PRIMITIVE_TYPES
  4329. #undef EPTYPE2
  4330. #undef EPTYPE
  4331. #undef ENUM_PRIMITIVE_TYPES_WCHAR
  4332. #undef ENUM_PRIMITIVE_TYPES
  4333. { NULL }
  4334. };
  4335. const struct descr_s *ptypes;
  4336. const void *unique_key[1];
  4337. int name_size;
  4338. ffi_type *ffitype;
  4339. for (ptypes=types; ; ptypes++) {
  4340. if (ptypes->name == NULL) {
  4341. #ifndef HAVE_WCHAR_H
  4342. if (strcmp(name, "wchar_t"))
  4343. PyErr_SetString(PyExc_NotImplementedError, name);
  4344. else
  4345. #endif
  4346. PyErr_SetString(PyExc_KeyError, name);
  4347. return NULL;
  4348. }
  4349. if (strcmp(name, ptypes->name) == 0)
  4350. break;
  4351. }
  4352. if (ptypes->flags & CT_PRIMITIVE_SIGNED) {
  4353. switch (ptypes->size) {
  4354. case 1: ffitype = &ffi_type_sint8; break;
  4355. case 2: ffitype = &ffi_type_sint16; break;
  4356. case 4: ffitype = &ffi_type_sint32; break;
  4357. case 8: ffitype = &ffi_type_sint64; break;
  4358. default: goto bad_ffi_type;
  4359. }
  4360. }
  4361. else if (ptypes->flags & CT_PRIMITIVE_FLOAT) {
  4362. if (strcmp(ptypes->name, "float") == 0)
  4363. ffitype = &ffi_type_float;
  4364. else if (strcmp(ptypes->name, "double") == 0)
  4365. ffitype = &ffi_type_double;
  4366. else if (strcmp(ptypes->name, "long double") == 0) {
  4367. /* assume that if sizeof(double) == sizeof(long double), then
  4368. the two types are equivalent for C. libffi bugs on Win64
  4369. if a function's return type is ffi_type_longdouble... */
  4370. if (sizeof(double) == sizeof(long double))
  4371. ffitype = &ffi_type_double;
  4372. else
  4373. ffitype = &ffi_type_longdouble;
  4374. }
  4375. else
  4376. goto bad_ffi_type;
  4377. }
  4378. else if (ptypes->flags & CT_PRIMITIVE_COMPLEX) {
  4379. /* As of March 2017, still no libffi support for complex.
  4380. It fails silently if we try to use ffi_type_complex_float
  4381. or ffi_type_complex_double. Better not use it at all.
  4382. */
  4383. ffitype = NULL;
  4384. }
  4385. else {
  4386. switch (ptypes->size) {
  4387. case 1: ffitype = &ffi_type_uint8; break;
  4388. case 2: ffitype = &ffi_type_uint16; break;
  4389. case 4: ffitype = &ffi_type_uint32; break;
  4390. case 8: ffitype = &ffi_type_uint64; break;
  4391. default: goto bad_ffi_type;
  4392. }
  4393. }
  4394. name_size = strlen(ptypes->name) + 1;
  4395. td = ctypedescr_new(name_size);
  4396. if (td == NULL)
  4397. return NULL;
  4398. memcpy(td->ct_name, name, name_size);
  4399. td->ct_size = ptypes->size;
  4400. td->ct_length = ptypes->align;
  4401. td->ct_extra = ffitype;
  4402. td->ct_flags = ptypes->flags;
  4403. if (td->ct_flags & (CT_PRIMITIVE_SIGNED | CT_PRIMITIVE_CHAR)) {
  4404. if (td->ct_size <= (Py_ssize_t)sizeof(long))
  4405. td->ct_flags |= CT_PRIMITIVE_FITS_LONG;
  4406. }
  4407. else if (td->ct_flags & CT_PRIMITIVE_UNSIGNED) {
  4408. if (td->ct_size < (Py_ssize_t)sizeof(long))
  4409. td->ct_flags |= CT_PRIMITIVE_FITS_LONG;
  4410. }
  4411. td->ct_name_position = strlen(td->ct_name);
  4412. unique_key[0] = ptypes;
  4413. return get_unique_type(td, unique_key, 1);
  4414. bad_ffi_type:
  4415. PyErr_Format(PyExc_NotImplementedError,
  4416. "primitive type '%s' has size %d; "
  4417. "the supported sizes are 1, 2, 4, 8",
  4418. name, (int)ptypes->size);
  4419. return NULL;
  4420. }
  4421. static PyObject *b_new_primitive_type(PyObject *self, PyObject *args)
  4422. {
  4423. char *name;
  4424. if (!PyArg_ParseTuple(args, "s:new_primitive_type", &name))
  4425. return NULL;
  4426. return new_primitive_type(name);
  4427. }
  4428. static PyObject *new_pointer_type(CTypeDescrObject *ctitem)
  4429. {
  4430. CTypeDescrObject *td;
  4431. const char *extra;
  4432. const void *unique_key[1];
  4433. if (ctitem->ct_flags & CT_ARRAY)
  4434. extra = "(*)"; /* obscure case: see test_array_add */
  4435. else
  4436. extra = " *";
  4437. td = ctypedescr_new_on_top(ctitem, extra, 2);
  4438. if (td == NULL)
  4439. return NULL;
  4440. td->ct_size = sizeof(void *);
  4441. td->ct_length = -1;
  4442. td->ct_flags = CT_POINTER;
  4443. if (ctitem->ct_flags & (CT_STRUCT|CT_UNION))
  4444. td->ct_flags |= CT_IS_PTR_TO_OWNED;
  4445. if (ctitem->ct_flags & CT_VOID)
  4446. td->ct_flags |= CT_IS_VOID_PTR;
  4447. if ((ctitem->ct_flags & CT_VOID) ||
  4448. ((ctitem->ct_flags & CT_PRIMITIVE_CHAR) &&
  4449. ctitem->ct_size == sizeof(char)))
  4450. td->ct_flags |= CT_IS_VOIDCHAR_PTR; /* 'void *' or 'char *' only */
  4451. unique_key[0] = ctitem;
  4452. return get_unique_type(td, unique_key, 1);
  4453. }
  4454. static PyObject *b_new_pointer_type(PyObject *self, PyObject *args)
  4455. {
  4456. CTypeDescrObject *ctitem;
  4457. if (!PyArg_ParseTuple(args, "O!:new_pointer_type",
  4458. &CTypeDescr_Type, &ctitem))
  4459. return NULL;
  4460. return new_pointer_type(ctitem);
  4461. }
  4462. static PyObject *b_new_array_type(PyObject *self, PyObject *args)
  4463. {
  4464. PyObject *lengthobj;
  4465. Py_ssize_t length;
  4466. CTypeDescrObject *ctptr;
  4467. if (!PyArg_ParseTuple(args, "O!O:new_array_type",
  4468. &CTypeDescr_Type, &ctptr, &lengthobj))
  4469. return NULL;
  4470. if (lengthobj == Py_None) {
  4471. length = -1;
  4472. }
  4473. else {
  4474. length = PyNumber_AsSsize_t(lengthobj, PyExc_OverflowError);
  4475. if (length < 0) {
  4476. if (!PyErr_Occurred())
  4477. PyErr_SetString(PyExc_ValueError, "negative array length");
  4478. return NULL;
  4479. }
  4480. }
  4481. return new_array_type(ctptr, length);
  4482. }
  4483. static PyObject *
  4484. new_array_type(CTypeDescrObject *ctptr, Py_ssize_t length)
  4485. {
  4486. CTypeDescrObject *td, *ctitem;
  4487. char extra_text[32];
  4488. Py_ssize_t arraysize;
  4489. int flags = CT_ARRAY;
  4490. const void *unique_key[2];
  4491. if (!(ctptr->ct_flags & CT_POINTER)) {
  4492. PyErr_SetString(PyExc_TypeError, "first arg must be a pointer ctype");
  4493. return NULL;
  4494. }
  4495. ctitem = ctptr->ct_itemdescr;
  4496. if (ctitem->ct_size < 0) {
  4497. PyErr_Format(PyExc_ValueError, "array item of unknown size: '%s'",
  4498. ctitem->ct_name);
  4499. return NULL;
  4500. }
  4501. if (length < 0) {
  4502. sprintf(extra_text, "[]");
  4503. length = -1;
  4504. arraysize = -1;
  4505. }
  4506. else {
  4507. sprintf(extra_text, "[%llu]", (unsigned PY_LONG_LONG)length);
  4508. arraysize = MUL_WRAPAROUND(length, ctitem->ct_size);
  4509. if (length > 0 && (arraysize / length) != ctitem->ct_size) {
  4510. PyErr_SetString(PyExc_OverflowError,
  4511. "array size would overflow a Py_ssize_t");
  4512. return NULL;
  4513. }
  4514. }
  4515. td = ctypedescr_new_on_top(ctitem, extra_text, 0);
  4516. if (td == NULL)
  4517. return NULL;
  4518. Py_INCREF(ctptr);
  4519. td->ct_stuff = (PyObject *)ctptr;
  4520. td->ct_size = arraysize;
  4521. td->ct_length = length;
  4522. td->ct_flags = flags;
  4523. unique_key[0] = ctptr;
  4524. unique_key[1] = (void *)length;
  4525. return get_unique_type(td, unique_key, 2);
  4526. }
  4527. static PyObject *new_void_type(void)
  4528. {
  4529. int name_size = strlen("void") + 1;
  4530. const void *unique_key[1];
  4531. CTypeDescrObject *td = ctypedescr_new(name_size);
  4532. if (td == NULL)
  4533. return NULL;
  4534. memcpy(td->ct_name, "void", name_size);
  4535. td->ct_size = -1;
  4536. td->ct_flags = CT_VOID | CT_IS_OPAQUE;
  4537. td->ct_name_position = strlen("void");
  4538. unique_key[0] = "void";
  4539. return get_unique_type(td, unique_key, 1);
  4540. }
  4541. static PyObject *b_new_void_type(PyObject *self, PyObject *args)
  4542. {
  4543. return new_void_type();
  4544. }
  4545. static PyObject *new_struct_or_union_type(const char *name, int flag)
  4546. {
  4547. int namelen = strlen(name);
  4548. CTypeDescrObject *td = ctypedescr_new(namelen + 1);
  4549. if (td == NULL)
  4550. return NULL;
  4551. td->ct_size = -1;
  4552. td->ct_length = -1;
  4553. td->ct_flags = flag | CT_IS_OPAQUE;
  4554. td->ct_extra = NULL;
  4555. memcpy(td->ct_name, name, namelen + 1);
  4556. td->ct_name_position = namelen;
  4557. return (PyObject *)td;
  4558. }
  4559. static PyObject *b_new_struct_type(PyObject *self, PyObject *args)
  4560. {
  4561. char *name;
  4562. int flag;
  4563. if (!PyArg_ParseTuple(args, "s:new_struct_type", &name))
  4564. return NULL;
  4565. flag = CT_STRUCT;
  4566. if (strcmp(name, "struct _IO_FILE") == 0 || strcmp(name, "FILE") == 0)
  4567. flag |= CT_IS_FILE;
  4568. return new_struct_or_union_type(name, flag);
  4569. }
  4570. static PyObject *b_new_union_type(PyObject *self, PyObject *args)
  4571. {
  4572. char *name;
  4573. if (!PyArg_ParseTuple(args, "s:new_union_type", &name))
  4574. return NULL;
  4575. return new_struct_or_union_type(name, CT_UNION);
  4576. }
  4577. static CFieldObject *
  4578. _add_field(PyObject *interned_fields, PyObject *fname, CTypeDescrObject *ftype,
  4579. Py_ssize_t offset, int bitshift, int fbitsize, int flags)
  4580. {
  4581. int err;
  4582. Py_ssize_t prev_size;
  4583. CFieldObject *cf = PyObject_New(CFieldObject, &CField_Type);
  4584. if (cf == NULL)
  4585. return NULL;
  4586. Py_INCREF(ftype);
  4587. cf->cf_type = ftype;
  4588. cf->cf_offset = offset;
  4589. cf->cf_bitshift = bitshift;
  4590. cf->cf_bitsize = fbitsize;
  4591. cf->cf_flags = flags;
  4592. Py_INCREF(fname);
  4593. PyText_InternInPlace(&fname);
  4594. prev_size = PyDict_Size(interned_fields);
  4595. err = PyDict_SetItem(interned_fields, fname, (PyObject *)cf);
  4596. Py_DECREF(fname);
  4597. Py_DECREF(cf);
  4598. if (err < 0)
  4599. return NULL;
  4600. if (PyDict_Size(interned_fields) != prev_size + 1) {
  4601. PyErr_Format(PyExc_KeyError, "duplicate field name '%s'",
  4602. PyText_AS_UTF8(fname));
  4603. return NULL;
  4604. }
  4605. return cf; /* borrowed reference */
  4606. }
  4607. #define SF_MSVC_BITFIELDS 0x01
  4608. #define SF_GCC_ARM_BITFIELDS 0x02
  4609. #define SF_GCC_X86_BITFIELDS 0x10
  4610. #define SF_GCC_BIG_ENDIAN 0x04
  4611. #define SF_GCC_LITTLE_ENDIAN 0x40
  4612. #define SF_PACKED 0x08
  4613. #define SF_STD_FIELD_POS 0x80
  4614. #ifdef MS_WIN32
  4615. # define SF_DEFAULT_PACKING 8
  4616. #else
  4617. # define SF_DEFAULT_PACKING 0x40000000 /* a huge power of two */
  4618. #endif
  4619. static int complete_sflags(int sflags)
  4620. {
  4621. /* add one of the SF_xxx_BITFIELDS flags if none is specified */
  4622. if (!(sflags & (SF_MSVC_BITFIELDS | SF_GCC_ARM_BITFIELDS |
  4623. SF_GCC_X86_BITFIELDS))) {
  4624. #ifdef MS_WIN32
  4625. sflags |= SF_MSVC_BITFIELDS;
  4626. #else
  4627. # if defined(__APPLE__) && defined(__arm64__)
  4628. sflags |= SF_GCC_X86_BITFIELDS;
  4629. # elif defined(__arm__) || defined(__aarch64__)
  4630. sflags |= SF_GCC_ARM_BITFIELDS;
  4631. # else
  4632. sflags |= SF_GCC_X86_BITFIELDS;
  4633. # endif
  4634. #endif
  4635. }
  4636. /* add one of SF_GCC_xx_ENDIAN if none is specified */
  4637. if (!(sflags & (SF_GCC_BIG_ENDIAN | SF_GCC_LITTLE_ENDIAN))) {
  4638. int _check_endian = 1;
  4639. if (*(char *)&_check_endian == 0)
  4640. sflags |= SF_GCC_BIG_ENDIAN;
  4641. else
  4642. sflags |= SF_GCC_LITTLE_ENDIAN;
  4643. }
  4644. return sflags;
  4645. }
  4646. static int detect_custom_layout(CTypeDescrObject *ct, int sflags,
  4647. Py_ssize_t cdef_value,
  4648. Py_ssize_t compiler_value,
  4649. const char *msg1, const char *txt,
  4650. const char *msg2)
  4651. {
  4652. if (compiler_value != cdef_value) {
  4653. if (sflags & SF_STD_FIELD_POS) {
  4654. PyErr_Format(FFIError,
  4655. "%s: %s%s%s (cdef says %zd, but C compiler says %zd)."
  4656. " fix it or use \"...;\" as the last field in the "
  4657. "cdef for %s to make it flexible",
  4658. ct->ct_name, msg1, txt, msg2,
  4659. cdef_value, compiler_value,
  4660. ct->ct_name);
  4661. return -1;
  4662. }
  4663. ct->ct_flags |= CT_CUSTOM_FIELD_POS;
  4664. }
  4665. return 0;
  4666. }
  4667. #define ROUNDUP_BYTES(bytes, bits) ((bytes) + ((bits) > 0))
  4668. static PyObject *b_complete_struct_or_union(PyObject *self, PyObject *args)
  4669. {
  4670. CTypeDescrObject *ct;
  4671. PyObject *fields, *interned_fields, *ignored;
  4672. int is_union, alignment;
  4673. Py_ssize_t byteoffset, i, nb_fields, byteoffsetmax, alignedsize;
  4674. int bitoffset;
  4675. Py_ssize_t byteoffsetorg;
  4676. Py_ssize_t totalsize = -1;
  4677. int totalalignment = -1;
  4678. CFieldObject **previous;
  4679. int prev_bitfield_size, prev_bitfield_free;
  4680. int sflags = 0, fflags;
  4681. int pack = 0;
  4682. if (!PyArg_ParseTuple(args, "O!O!|Oniii:complete_struct_or_union",
  4683. &CTypeDescr_Type, &ct,
  4684. &PyList_Type, &fields,
  4685. &ignored, &totalsize, &totalalignment, &sflags,
  4686. &pack))
  4687. return NULL;
  4688. sflags = complete_sflags(sflags);
  4689. if (sflags & SF_PACKED)
  4690. pack = 1;
  4691. else if (pack <= 0)
  4692. pack = SF_DEFAULT_PACKING;
  4693. else
  4694. sflags |= SF_PACKED;
  4695. if ((ct->ct_flags & (CT_STRUCT|CT_IS_OPAQUE)) ==
  4696. (CT_STRUCT|CT_IS_OPAQUE)) {
  4697. is_union = 0;
  4698. }
  4699. else if ((ct->ct_flags & (CT_UNION|CT_IS_OPAQUE)) ==
  4700. (CT_UNION|CT_IS_OPAQUE)) {
  4701. is_union = 1;
  4702. }
  4703. else {
  4704. PyErr_SetString(PyExc_TypeError,
  4705. "first arg must be a non-initialized struct or union ctype");
  4706. return NULL;
  4707. }
  4708. ct->ct_flags &= ~(CT_CUSTOM_FIELD_POS | CT_WITH_PACKED_CHANGE);
  4709. alignment = 1;
  4710. byteoffset = 0; /* the real value is 'byteoffset+bitoffset*8', which */
  4711. bitoffset = 0; /* counts the offset in bits */
  4712. byteoffsetmax = 0; /* the maximum value of byteoffset-rounded-up-to-byte */
  4713. prev_bitfield_size = 0;
  4714. prev_bitfield_free = 0;
  4715. nb_fields = PyList_GET_SIZE(fields);
  4716. interned_fields = PyDict_New();
  4717. if (interned_fields == NULL)
  4718. return NULL;
  4719. previous = (CFieldObject **)&ct->ct_extra;
  4720. for (i=0; i<nb_fields; i++) {
  4721. PyObject *fname;
  4722. CTypeDescrObject *ftype;
  4723. int fbitsize = -1, falign, falignorg, do_align;
  4724. Py_ssize_t foffset = -1;
  4725. if (!PyArg_ParseTuple(PyList_GET_ITEM(fields, i), "O!O!|in:list item",
  4726. &PyText_Type, &fname,
  4727. &CTypeDescr_Type, &ftype,
  4728. &fbitsize, &foffset))
  4729. goto error;
  4730. if (ftype->ct_size < 0) {
  4731. if ((ftype->ct_flags & CT_ARRAY) && fbitsize < 0
  4732. && (i == nb_fields - 1 || foffset != -1)) {
  4733. ct->ct_flags |= CT_WITH_VAR_ARRAY;
  4734. }
  4735. else {
  4736. PyErr_Format(PyExc_TypeError,
  4737. "field '%s.%s' has ctype '%s' of unknown size",
  4738. ct->ct_name, PyText_AS_UTF8(fname),
  4739. ftype->ct_name);
  4740. goto error;
  4741. }
  4742. }
  4743. else if (ftype->ct_flags & (CT_STRUCT|CT_UNION)) {
  4744. if (force_lazy_struct(ftype) < 0) /* for CT_WITH_VAR_ARRAY */
  4745. return NULL;
  4746. /* GCC (or maybe C99) accepts var-sized struct fields that are not
  4747. the last field of a larger struct. That's why there is no
  4748. check here for "last field": we propagate the flag
  4749. CT_WITH_VAR_ARRAY to any struct that contains either an open-
  4750. ended array or another struct that recursively contains an
  4751. open-ended array. */
  4752. if (ftype->ct_flags & CT_WITH_VAR_ARRAY)
  4753. ct->ct_flags |= CT_WITH_VAR_ARRAY;
  4754. }
  4755. if (is_union)
  4756. byteoffset = bitoffset = 0; /* reset each field at offset 0 */
  4757. /* update the total alignment requirement, but skip it if the
  4758. field is an anonymous bitfield or if SF_PACKED */
  4759. falignorg = get_alignment(ftype);
  4760. if (falignorg < 0)
  4761. goto error;
  4762. falign = (pack < falignorg) ? pack : falignorg;
  4763. do_align = 1;
  4764. if (!(sflags & SF_GCC_ARM_BITFIELDS) && fbitsize >= 0) {
  4765. if (!(sflags & SF_MSVC_BITFIELDS)) {
  4766. /* GCC: anonymous bitfields (of any size) don't cause alignment */
  4767. do_align = PyText_GetSize(fname) > 0;
  4768. }
  4769. else {
  4770. /* MSVC: zero-sized bitfields don't cause alignment */
  4771. do_align = fbitsize > 0;
  4772. }
  4773. }
  4774. if (alignment < falign && do_align)
  4775. alignment = falign;
  4776. fflags = (is_union && i > 0) ? BF_IGNORE_IN_CTOR : 0;
  4777. if (fbitsize < 0) {
  4778. /* not a bitfield: common case */
  4779. int bs_flag;
  4780. if ((ftype->ct_flags & CT_ARRAY) && ftype->ct_length <= 0)
  4781. bs_flag = BS_EMPTY_ARRAY;
  4782. else
  4783. bs_flag = BS_REGULAR;
  4784. /* align this field to its own 'falign' by inserting padding */
  4785. /* first, pad to the next byte,
  4786. * then pad to 'falign' or 'falignorg' bytes */
  4787. byteoffset = ROUNDUP_BYTES(byteoffset, bitoffset);
  4788. bitoffset = 0;
  4789. byteoffsetorg = (byteoffset + falignorg-1) & ~(falignorg-1);
  4790. byteoffset = (byteoffset + falign-1) & ~(falign-1);
  4791. if (byteoffsetorg != byteoffset) {
  4792. ct->ct_flags |= CT_WITH_PACKED_CHANGE;
  4793. }
  4794. if (foffset >= 0) {
  4795. /* a forced field position: ignore the offset just computed,
  4796. except to know if we must set CT_CUSTOM_FIELD_POS */
  4797. if (detect_custom_layout(ct, sflags, byteoffset, foffset,
  4798. "wrong offset for field '",
  4799. PyText_AS_UTF8(fname), "'") < 0)
  4800. goto error;
  4801. byteoffset = foffset;
  4802. }
  4803. if (PyText_GetSize(fname) == 0 &&
  4804. ftype->ct_flags & (CT_STRUCT|CT_UNION)) {
  4805. /* a nested anonymous struct or union */
  4806. CFieldObject *cfsrc = (CFieldObject *)ftype->ct_extra;
  4807. for (; cfsrc != NULL; cfsrc = cfsrc->cf_next) {
  4808. /* broken complexity in the call to get_field_name(),
  4809. but we'll assume you never do that with nested
  4810. anonymous structures with thousand of fields */
  4811. *previous = _add_field(interned_fields,
  4812. get_field_name(ftype, cfsrc),
  4813. cfsrc->cf_type,
  4814. byteoffset + cfsrc->cf_offset,
  4815. cfsrc->cf_bitshift,
  4816. cfsrc->cf_bitsize,
  4817. cfsrc->cf_flags | fflags);
  4818. if (*previous == NULL)
  4819. goto error;
  4820. previous = &(*previous)->cf_next;
  4821. }
  4822. /* always forbid such structures from being passed by value */
  4823. ct->ct_flags |= CT_CUSTOM_FIELD_POS;
  4824. }
  4825. else {
  4826. *previous = _add_field(interned_fields, fname, ftype,
  4827. byteoffset, bs_flag, -1, fflags);
  4828. if (*previous == NULL)
  4829. goto error;
  4830. previous = &(*previous)->cf_next;
  4831. }
  4832. if (ftype->ct_size >= 0)
  4833. byteoffset += ftype->ct_size;
  4834. prev_bitfield_size = 0;
  4835. }
  4836. else {
  4837. /* this is the case of a bitfield */
  4838. Py_ssize_t field_offset_bytes;
  4839. int bits_already_occupied, bitshift;
  4840. if (foffset >= 0) {
  4841. PyErr_Format(PyExc_TypeError,
  4842. "field '%s.%s' is a bitfield, "
  4843. "but a fixed offset is specified",
  4844. ct->ct_name, PyText_AS_UTF8(fname));
  4845. goto error;
  4846. }
  4847. if (!(ftype->ct_flags & (CT_PRIMITIVE_SIGNED |
  4848. CT_PRIMITIVE_UNSIGNED |
  4849. CT_PRIMITIVE_CHAR))) {
  4850. PyErr_Format(PyExc_TypeError,
  4851. "field '%s.%s' declared as '%s' cannot be a bit field",
  4852. ct->ct_name, PyText_AS_UTF8(fname),
  4853. ftype->ct_name);
  4854. goto error;
  4855. }
  4856. if (fbitsize > 8 * ftype->ct_size) {
  4857. PyErr_Format(PyExc_TypeError,
  4858. "bit field '%s.%s' is declared '%s:%d', which "
  4859. "exceeds the width of the type",
  4860. ct->ct_name, PyText_AS_UTF8(fname),
  4861. ftype->ct_name, fbitsize);
  4862. goto error;
  4863. }
  4864. /* compute the starting position of the theoretical field
  4865. that covers a complete 'ftype', inside of which we will
  4866. locate the real bitfield */
  4867. field_offset_bytes = byteoffset;
  4868. field_offset_bytes &= ~(falign - 1);
  4869. if (fbitsize == 0) {
  4870. if (PyText_GetSize(fname) > 0) {
  4871. PyErr_Format(PyExc_TypeError,
  4872. "field '%s.%s' is declared with :0",
  4873. ct->ct_name, PyText_AS_UTF8(fname));
  4874. goto error;
  4875. }
  4876. if (!(sflags & SF_MSVC_BITFIELDS)) {
  4877. /* GCC's notion of "ftype :0;" */
  4878. /* pad byteoffset to a value aligned for "ftype" */
  4879. if (ROUNDUP_BYTES(byteoffset, bitoffset) > field_offset_bytes) {
  4880. field_offset_bytes += falign;
  4881. assert(byteoffset < field_offset_bytes);
  4882. }
  4883. byteoffset = field_offset_bytes;
  4884. bitoffset = 0;
  4885. }
  4886. else {
  4887. /* MSVC's notion of "ftype :0;" */
  4888. /* Mostly ignored. It seems they only serve as
  4889. separator between other bitfields, to force them
  4890. into separate words. */
  4891. }
  4892. prev_bitfield_size = 0;
  4893. }
  4894. else {
  4895. if (!(sflags & SF_MSVC_BITFIELDS)) {
  4896. /* GCC's algorithm */
  4897. /* Can the field start at the offset given by 'boffset'? It
  4898. can if it would entirely fit into an aligned ftype field. */
  4899. bits_already_occupied = (byteoffset-field_offset_bytes) * 8
  4900. + bitoffset;
  4901. if (bits_already_occupied + fbitsize > 8 * ftype->ct_size) {
  4902. /* it would not fit, we need to start at the next
  4903. allowed position */
  4904. if ((sflags & SF_PACKED) &&
  4905. (bits_already_occupied & 7)) {
  4906. PyErr_Format(PyExc_NotImplementedError,
  4907. "with 'packed', gcc would compile field "
  4908. "'%s.%s' to reuse some bits in the previous "
  4909. "field", ct->ct_name, PyText_AS_UTF8(fname));
  4910. goto error;
  4911. }
  4912. field_offset_bytes += falign;
  4913. assert(byteoffset < field_offset_bytes);
  4914. byteoffset = field_offset_bytes;
  4915. bitoffset = 0;
  4916. bitshift = 0;
  4917. }
  4918. else {
  4919. bitshift = bits_already_occupied;
  4920. assert(bitshift >= 0);
  4921. }
  4922. bitoffset += fbitsize;
  4923. byteoffset += (bitoffset >> 3);
  4924. bitoffset &= 7;
  4925. }
  4926. else {
  4927. /* MSVC's algorithm */
  4928. /* A bitfield is considered as taking the full width
  4929. of their declared type. It can share some bits
  4930. with the previous field only if it was also a
  4931. bitfield and used a type of the same size. */
  4932. if (prev_bitfield_size == ftype->ct_size &&
  4933. prev_bitfield_free >= fbitsize) {
  4934. /* yes: reuse */
  4935. bitshift = 8 * prev_bitfield_size - prev_bitfield_free;
  4936. }
  4937. else {
  4938. /* no: start a new full field */
  4939. byteoffset = ROUNDUP_BYTES(byteoffset, bitoffset);
  4940. bitoffset = 0;
  4941. /* align */
  4942. byteoffset = (byteoffset + falign-1) & ~(falign-1);
  4943. byteoffset += ftype->ct_size;
  4944. bitshift = 0;
  4945. prev_bitfield_size = ftype->ct_size;
  4946. prev_bitfield_free = 8 * prev_bitfield_size;
  4947. }
  4948. prev_bitfield_free -= fbitsize;
  4949. field_offset_bytes = byteoffset - ftype->ct_size;
  4950. }
  4951. if (sflags & SF_GCC_BIG_ENDIAN)
  4952. bitshift = 8 * ftype->ct_size - fbitsize - bitshift;
  4953. if (PyText_GetSize(fname) > 0) {
  4954. *previous = _add_field(interned_fields, fname, ftype,
  4955. field_offset_bytes, bitshift, fbitsize,
  4956. fflags);
  4957. if (*previous == NULL)
  4958. goto error;
  4959. previous = &(*previous)->cf_next;
  4960. }
  4961. }
  4962. }
  4963. assert(bitoffset == (bitoffset & 7));
  4964. if (ROUNDUP_BYTES(byteoffset, bitoffset) > byteoffsetmax)
  4965. byteoffsetmax = ROUNDUP_BYTES(byteoffset, bitoffset);
  4966. }
  4967. *previous = NULL;
  4968. /* Like C, if the size of this structure would be zero, we compute it
  4969. as 1 instead. But for ctypes support, we allow the manually-
  4970. specified totalsize to be zero in this case. */
  4971. alignedsize = (byteoffsetmax + alignment - 1) & ~(alignment-1);
  4972. if (alignedsize == 0)
  4973. alignedsize = 1;
  4974. if (totalsize < 0) {
  4975. totalsize = alignedsize;
  4976. }
  4977. else {
  4978. if (detect_custom_layout(ct, sflags, alignedsize,
  4979. totalsize, "wrong total size", "", "") < 0)
  4980. goto error;
  4981. if (totalsize < byteoffsetmax) {
  4982. PyErr_Format(PyExc_TypeError,
  4983. "%s cannot be of size %zd: there are fields at least "
  4984. "up to %zd", ct->ct_name, totalsize, byteoffsetmax);
  4985. goto error;
  4986. }
  4987. }
  4988. if (totalalignment < 0) {
  4989. totalalignment = alignment;
  4990. }
  4991. else {
  4992. if (detect_custom_layout(ct, sflags, alignment, totalalignment,
  4993. "wrong total alignment", "", "") < 0)
  4994. goto error;
  4995. }
  4996. ct->ct_size = totalsize;
  4997. ct->ct_length = totalalignment;
  4998. ct->ct_stuff = interned_fields;
  4999. ct->ct_flags &= ~CT_IS_OPAQUE;
  5000. Py_INCREF(Py_None);
  5001. return Py_None;
  5002. error:
  5003. ct->ct_extra = NULL;
  5004. Py_DECREF(interned_fields);
  5005. return NULL;
  5006. }
  5007. struct funcbuilder_s {
  5008. Py_ssize_t nb_bytes;
  5009. char *bufferp;
  5010. ffi_type **atypes;
  5011. ffi_type *rtype;
  5012. Py_ssize_t nargs;
  5013. CTypeDescrObject *fct;
  5014. };
  5015. static void *fb_alloc(struct funcbuilder_s *fb, Py_ssize_t size)
  5016. {
  5017. if (fb->bufferp == NULL) {
  5018. fb->nb_bytes += size;
  5019. return NULL;
  5020. }
  5021. else {
  5022. char *result = fb->bufferp;
  5023. fb->bufferp += size;
  5024. return result;
  5025. }
  5026. }
  5027. #define SUPPORTED_IN_API_MODE \
  5028. " are only supported as %s if the function is " \
  5029. "'API mode' and non-variadic (i.e. declared inside ffibuilder" \
  5030. ".cdef()+ffibuilder.set_source() and not taking a final '...' " \
  5031. "argument)"
  5032. static ffi_type *fb_unsupported(CTypeDescrObject *ct, const char *place,
  5033. const char *detail)
  5034. {
  5035. PyErr_Format(PyExc_NotImplementedError,
  5036. "ctype '%s' not supported as %s. %s. "
  5037. "Such structs" SUPPORTED_IN_API_MODE,
  5038. ct->ct_name, place, detail, place);
  5039. return NULL;
  5040. }
  5041. static ffi_type *fb_fill_type(struct funcbuilder_s *fb, CTypeDescrObject *ct,
  5042. int is_result_type)
  5043. {
  5044. const char *place = is_result_type ? "return value" : "argument";
  5045. if (ct->ct_flags & (CT_PRIMITIVE_ANY & ~CT_PRIMITIVE_COMPLEX)) {
  5046. return (ffi_type *)ct->ct_extra;
  5047. }
  5048. else if (ct->ct_flags & (CT_POINTER|CT_FUNCTIONPTR)) {
  5049. return &ffi_type_pointer;
  5050. }
  5051. else if ((ct->ct_flags & CT_VOID) && is_result_type) {
  5052. return &ffi_type_void;
  5053. }
  5054. if (ct->ct_size <= 0) {
  5055. PyErr_Format(PyExc_TypeError,
  5056. ct->ct_size < 0 ? "ctype '%s' has incomplete type"
  5057. : "ctype '%s' has size 0",
  5058. ct->ct_name);
  5059. return NULL;
  5060. }
  5061. if (ct->ct_flags & CT_STRUCT) {
  5062. ffi_type *ffistruct, *ffifield;
  5063. ffi_type **elements;
  5064. Py_ssize_t i, n, nflat;
  5065. CFieldObject *cf;
  5066. /* We can't pass a struct that was completed by verify().
  5067. Issue: assume verify() is given "struct { long b; ...; }".
  5068. Then it will complete it in the same way whether it is actually
  5069. "struct { long a, b; }" or "struct { double a; long b; }".
  5070. But on 64-bit UNIX, these two structs are passed by value
  5071. differently: e.g. on x86-64, "b" ends up in register "rsi" in
  5072. the first case and "rdi" in the second case.
  5073. Another reason for CT_CUSTOM_FIELD_POS would be anonymous
  5074. nested structures: we lost the information about having it
  5075. here, so better safe (and forbid it) than sorry (and maybe
  5076. crash). Note: it seems we only get in this case with
  5077. ffi.verify().
  5078. */
  5079. if (force_lazy_struct(ct) < 0)
  5080. return NULL;
  5081. if (ct->ct_flags & CT_CUSTOM_FIELD_POS) {
  5082. /* these NotImplementedErrors may be caught and ignored until
  5083. a real call is made to a function of this type */
  5084. return fb_unsupported(ct, place,
  5085. "It is a struct declared with \"...;\", but the C "
  5086. "calling convention may depend on the missing fields; "
  5087. "or, it contains anonymous struct/unions");
  5088. }
  5089. /* Another reason: __attribute__((packed)) is not supported by libffi.
  5090. */
  5091. if (ct->ct_flags & CT_WITH_PACKED_CHANGE) {
  5092. return fb_unsupported(ct, place,
  5093. "It is a 'packed' structure, with a different layout than "
  5094. "expected by libffi");
  5095. }
  5096. n = PyDict_Size(ct->ct_stuff);
  5097. nflat = 0;
  5098. /* walk the fields, expanding arrays into repetitions; first,
  5099. only count how many flattened fields there are */
  5100. cf = (CFieldObject *)ct->ct_extra;
  5101. for (i=0; i<n; i++) {
  5102. Py_ssize_t flat;
  5103. CTypeDescrObject *ct1;
  5104. assert(cf != NULL);
  5105. if (cf->cf_bitshift >= 0) {
  5106. return fb_unsupported(ct, place,
  5107. "It is a struct with bit fields, which libffi does not "
  5108. "support");
  5109. }
  5110. flat = 1;
  5111. ct1 = cf->cf_type;
  5112. while (ct1->ct_flags & CT_ARRAY) {
  5113. flat *= ct1->ct_length;
  5114. ct1 = ct1->ct_itemdescr;
  5115. }
  5116. if (flat <= 0) {
  5117. return fb_unsupported(ct, place,
  5118. "It is a struct with a zero-length array, which libffi "
  5119. "does not support");
  5120. }
  5121. nflat += flat;
  5122. cf = cf->cf_next;
  5123. }
  5124. assert(cf == NULL);
  5125. /* next, allocate and fill the flattened list */
  5126. elements = fb_alloc(fb, (nflat + 1) * sizeof(ffi_type*));
  5127. nflat = 0;
  5128. cf = (CFieldObject *)ct->ct_extra;
  5129. for (i=0; i<n; i++) {
  5130. Py_ssize_t j, flat = 1;
  5131. CTypeDescrObject *ct = cf->cf_type;
  5132. while (ct->ct_flags & CT_ARRAY) {
  5133. flat *= ct->ct_length;
  5134. ct = ct->ct_itemdescr;
  5135. }
  5136. ffifield = fb_fill_type(fb, ct, 0);
  5137. if (PyErr_Occurred())
  5138. return NULL;
  5139. if (elements != NULL) {
  5140. for (j=0; j<flat; j++)
  5141. elements[nflat++] = ffifield;
  5142. }
  5143. cf = cf->cf_next;
  5144. }
  5145. /* finally, allocate the FFI_TYPE_STRUCT */
  5146. ffistruct = fb_alloc(fb, sizeof(ffi_type));
  5147. if (ffistruct != NULL) {
  5148. elements[nflat] = NULL;
  5149. ffistruct->size = ct->ct_size;
  5150. ffistruct->alignment = ct->ct_length;
  5151. ffistruct->type = FFI_TYPE_STRUCT;
  5152. ffistruct->elements = elements;
  5153. }
  5154. return ffistruct;
  5155. }
  5156. else if (ct->ct_flags & CT_UNION) {
  5157. PyErr_Format(PyExc_NotImplementedError,
  5158. "ctype '%s' not supported as %s by libffi. "
  5159. "Unions" SUPPORTED_IN_API_MODE,
  5160. ct->ct_name, place, place);
  5161. return NULL;
  5162. }
  5163. else {
  5164. char *extra = "";
  5165. if (ct->ct_flags & CT_PRIMITIVE_COMPLEX)
  5166. extra = " (the support for complex types inside libffi "
  5167. "is mostly missing at this point, so CFFI only "
  5168. "supports complex types as arguments or return "
  5169. "value in API-mode functions)";
  5170. PyErr_Format(PyExc_NotImplementedError,
  5171. "ctype '%s' (size %zd) not supported as %s%s",
  5172. ct->ct_name, ct->ct_size, place, extra);
  5173. return NULL;
  5174. }
  5175. }
  5176. #define ALIGN_TO(n, a) ((n) + ((a)-1)) & ~((a)-1)
  5177. #define ALIGN_ARG(n) ALIGN_TO(n, 8)
  5178. static int fb_build(struct funcbuilder_s *fb, PyObject *fargs,
  5179. CTypeDescrObject *fresult)
  5180. {
  5181. Py_ssize_t i, nargs = PyTuple_GET_SIZE(fargs);
  5182. Py_ssize_t exchange_offset;
  5183. cif_description_t *cif_descr;
  5184. /* ffi buffer: start with a cif_description */
  5185. cif_descr = fb_alloc(fb, sizeof(cif_description_t) +
  5186. nargs * sizeof(Py_ssize_t));
  5187. /* ffi buffer: next comes an array of 'ffi_type*', one per argument */
  5188. fb->atypes = fb_alloc(fb, nargs * sizeof(ffi_type*));
  5189. fb->nargs = nargs;
  5190. /* ffi buffer: next comes the result type */
  5191. fb->rtype = fb_fill_type(fb, fresult, 1);
  5192. if (PyErr_Occurred())
  5193. return -1;
  5194. if (cif_descr != NULL) {
  5195. /* exchange data size */
  5196. /* first, enough room for an array of 'nargs' pointers */
  5197. exchange_offset = nargs * sizeof(void*);
  5198. /* then enough room for the result --- which means at least
  5199. sizeof(ffi_arg), according to the ffi docs, but we also
  5200. align according to the result type, for issue #531 */
  5201. exchange_offset = ALIGN_TO(exchange_offset, fb->rtype->alignment);
  5202. exchange_offset = ALIGN_ARG(exchange_offset);
  5203. cif_descr->exchange_offset_arg[0] = exchange_offset;
  5204. i = fb->rtype->size;
  5205. if (i < (Py_ssize_t)sizeof(ffi_arg))
  5206. i = sizeof(ffi_arg);
  5207. exchange_offset += i;
  5208. }
  5209. else
  5210. exchange_offset = 0; /* not used */
  5211. /* loop over the arguments */
  5212. for (i=0; i<nargs; i++) {
  5213. CTypeDescrObject *farg;
  5214. ffi_type *atype;
  5215. farg = (CTypeDescrObject *)PyTuple_GET_ITEM(fargs, i);
  5216. /* convert arrays to pointers */
  5217. if (farg->ct_flags & CT_ARRAY)
  5218. farg = (CTypeDescrObject *)farg->ct_stuff;
  5219. /* ffi buffer: fill in the ffi for the i'th argument */
  5220. assert(farg != NULL);
  5221. atype = fb_fill_type(fb, farg, 0);
  5222. if (PyErr_Occurred())
  5223. return -1;
  5224. if (fb->atypes != NULL) {
  5225. fb->atypes[i] = atype;
  5226. /* exchange data size */
  5227. exchange_offset = ALIGN_TO(exchange_offset, atype->alignment);
  5228. exchange_offset = ALIGN_ARG(exchange_offset);
  5229. cif_descr->exchange_offset_arg[1 + i] = exchange_offset;
  5230. exchange_offset += atype->size;
  5231. }
  5232. }
  5233. if (cif_descr != NULL) {
  5234. /* exchange data size */
  5235. /* we also align it to the next multiple of 8, in an attempt to
  5236. work around bugs(?) of libffi like #241 */
  5237. cif_descr->exchange_size = ALIGN_ARG(exchange_offset);
  5238. }
  5239. return 0;
  5240. }
  5241. #undef ALIGN_ARG
  5242. #undef ALIGN_TO
  5243. static void fb_cat_name(struct funcbuilder_s *fb, const char *piece,
  5244. int piecelen)
  5245. {
  5246. if (fb->bufferp == NULL) {
  5247. fb->nb_bytes += piecelen;
  5248. }
  5249. else {
  5250. memcpy(fb->bufferp, piece, piecelen);
  5251. fb->bufferp += piecelen;
  5252. }
  5253. }
  5254. static int fb_build_name(struct funcbuilder_s *fb, const char *repl,
  5255. CTypeDescrObject **pfargs, Py_ssize_t nargs,
  5256. CTypeDescrObject *fresult, int ellipsis)
  5257. {
  5258. Py_ssize_t i;
  5259. fb->nargs = nargs;
  5260. /* name: the function type name we build here is, like in C, made
  5261. as follows:
  5262. RESULT_TYPE_HEAD (*)(ARG_1_TYPE, ARG_2_TYPE, etc) RESULT_TYPE_TAIL
  5263. */
  5264. fb_cat_name(fb, fresult->ct_name, fresult->ct_name_position);
  5265. if (repl[0] != '(' &&
  5266. fresult->ct_name[fresult->ct_name_position - 1] != '*')
  5267. fb_cat_name(fb, " ", 1); /* add a space */
  5268. fb_cat_name(fb, repl, strlen(repl));
  5269. if (fb->fct) {
  5270. i = strlen(repl) - 1; /* between '(*' and ')' */
  5271. assert(repl[i] == ')');
  5272. fb->fct->ct_name_position = fresult->ct_name_position + i;
  5273. }
  5274. fb_cat_name(fb, "(", 1);
  5275. /* loop over the arguments */
  5276. for (i=0; i<nargs; i++) {
  5277. CTypeDescrObject *farg;
  5278. farg = pfargs[i];
  5279. if (!CTypeDescr_Check(farg)) {
  5280. PyErr_SetString(PyExc_TypeError, "expected a tuple of ctypes");
  5281. return -1;
  5282. }
  5283. /* name: concatenate the name of the i'th argument's type */
  5284. if (i > 0)
  5285. fb_cat_name(fb, ", ", 2);
  5286. fb_cat_name(fb, farg->ct_name, strlen(farg->ct_name));
  5287. }
  5288. /* name: add the '...' if needed */
  5289. if (ellipsis) {
  5290. if (nargs > 0)
  5291. fb_cat_name(fb, ", ", 2);
  5292. fb_cat_name(fb, "...", 3);
  5293. }
  5294. /* name: concatenate the tail of the result type */
  5295. fb_cat_name(fb, ")", 1);
  5296. fb_cat_name(fb, fresult->ct_name + fresult->ct_name_position,
  5297. strlen(fresult->ct_name) - fresult->ct_name_position + 1);
  5298. return 0;
  5299. }
  5300. static CTypeDescrObject *fb_prepare_ctype(struct funcbuilder_s *fb,
  5301. PyObject *fargs,
  5302. CTypeDescrObject *fresult,
  5303. int ellipsis, int fabi)
  5304. {
  5305. CTypeDescrObject *fct, **pfargs;
  5306. Py_ssize_t nargs;
  5307. char *repl = "(*)";
  5308. fb->nb_bytes = 0;
  5309. fb->bufferp = NULL;
  5310. fb->fct = NULL;
  5311. pfargs = (CTypeDescrObject **)&PyTuple_GET_ITEM(fargs, 0);
  5312. nargs = PyTuple_GET_SIZE(fargs);
  5313. #if defined(MS_WIN32) && !defined(_WIN64)
  5314. if (fabi == FFI_STDCALL)
  5315. repl = "(__stdcall *)";
  5316. #endif
  5317. /* compute the total size needed for the name */
  5318. if (fb_build_name(fb, repl, pfargs, nargs, fresult, ellipsis) < 0)
  5319. return NULL;
  5320. /* allocate the function type */
  5321. fct = ctypedescr_new(fb->nb_bytes);
  5322. if (fct == NULL)
  5323. return NULL;
  5324. fb->fct = fct;
  5325. /* call again fb_build_name() to really build the ct_name */
  5326. fb->bufferp = fct->ct_name;
  5327. if (fb_build_name(fb, repl, pfargs, nargs, fresult, ellipsis) < 0)
  5328. goto error;
  5329. assert(fb->bufferp == fct->ct_name + fb->nb_bytes);
  5330. fct->ct_extra = NULL;
  5331. fct->ct_size = sizeof(void(*)(void));
  5332. fct->ct_flags = CT_FUNCTIONPTR;
  5333. return fct;
  5334. error:
  5335. Py_DECREF(fct);
  5336. return NULL;
  5337. }
  5338. static cif_description_t *fb_prepare_cif(PyObject *fargs,
  5339. CTypeDescrObject *fresult,
  5340. Py_ssize_t variadic_nargs_declared,
  5341. ffi_abi fabi)
  5342. {
  5343. char *buffer;
  5344. cif_description_t *cif_descr;
  5345. struct funcbuilder_s funcbuffer;
  5346. ffi_status status = (ffi_status)-1;
  5347. funcbuffer.nb_bytes = 0;
  5348. funcbuffer.bufferp = NULL;
  5349. /* compute the total size needed in the buffer for libffi */
  5350. if (fb_build(&funcbuffer, fargs, fresult) < 0)
  5351. return NULL;
  5352. /* allocate the buffer */
  5353. buffer = PyObject_Malloc(funcbuffer.nb_bytes);
  5354. if (buffer == NULL) {
  5355. PyErr_NoMemory();
  5356. return NULL;
  5357. }
  5358. /* call again fb_build() to really build the libffi data structures */
  5359. funcbuffer.bufferp = buffer;
  5360. if (fb_build(&funcbuffer, fargs, fresult) < 0)
  5361. goto error;
  5362. assert(funcbuffer.bufferp == buffer + funcbuffer.nb_bytes);
  5363. cif_descr = (cif_description_t *)buffer;
  5364. /* use `ffi_prep_cif_var` if necessary and available */
  5365. #if CFFI_CHECK_FFI_PREP_CIF_VAR_MAYBE
  5366. if (variadic_nargs_declared >= 0) {
  5367. if (CFFI_CHECK_FFI_PREP_CIF_VAR) {
  5368. status = ffi_prep_cif_var(&cif_descr->cif, fabi,
  5369. variadic_nargs_declared, funcbuffer.nargs,
  5370. funcbuffer.rtype, funcbuffer.atypes);
  5371. }
  5372. }
  5373. #endif
  5374. if (status == (ffi_status)-1) {
  5375. status = ffi_prep_cif(&cif_descr->cif, fabi, funcbuffer.nargs,
  5376. funcbuffer.rtype, funcbuffer.atypes);
  5377. }
  5378. if (status != FFI_OK) {
  5379. PyErr_SetString(PyExc_SystemError,
  5380. "libffi failed to build this function type");
  5381. goto error;
  5382. }
  5383. return cif_descr;
  5384. error:
  5385. PyObject_Free(buffer);
  5386. return NULL;
  5387. }
  5388. static PyObject *new_function_type(PyObject *fargs, /* tuple */
  5389. CTypeDescrObject *fresult,
  5390. int ellipsis, int fabi)
  5391. {
  5392. PyObject *fabiobj;
  5393. CTypeDescrObject *fct;
  5394. struct funcbuilder_s funcbuilder;
  5395. Py_ssize_t i;
  5396. const void **unique_key;
  5397. if ((fresult->ct_size < 0 && !(fresult->ct_flags & CT_VOID)) ||
  5398. (fresult->ct_flags & CT_ARRAY)) {
  5399. char *msg;
  5400. if (fresult->ct_flags & CT_IS_OPAQUE)
  5401. msg = "result type '%s' is opaque";
  5402. else
  5403. msg = "invalid result type: '%s'";
  5404. PyErr_Format(PyExc_TypeError, msg, fresult->ct_name);
  5405. return NULL;
  5406. }
  5407. fct = fb_prepare_ctype(&funcbuilder, fargs, fresult, ellipsis, fabi);
  5408. if (fct == NULL)
  5409. return NULL;
  5410. if (!ellipsis) {
  5411. /* Functions with '...' varargs are stored without a cif_descr
  5412. at all. The cif is computed on every call from the actual
  5413. types passed in. For all other functions, the cif_descr
  5414. is computed here. */
  5415. cif_description_t *cif_descr;
  5416. cif_descr = fb_prepare_cif(fargs, fresult, -1, fabi);
  5417. if (cif_descr == NULL) {
  5418. if (PyErr_ExceptionMatches(PyExc_NotImplementedError)) {
  5419. PyErr_Clear(); /* will get the exception if we see an
  5420. actual call */
  5421. }
  5422. else
  5423. goto error;
  5424. }
  5425. fct->ct_extra = (char *)cif_descr;
  5426. }
  5427. /* build the signature, given by a tuple of ctype objects */
  5428. fct->ct_stuff = PyTuple_New(2 + funcbuilder.nargs);
  5429. if (fct->ct_stuff == NULL)
  5430. goto error;
  5431. fabiobj = PyInt_FromLong(fabi);
  5432. if (fabiobj == NULL)
  5433. goto error;
  5434. PyTuple_SET_ITEM(fct->ct_stuff, 0, fabiobj);
  5435. Py_INCREF(fresult);
  5436. PyTuple_SET_ITEM(fct->ct_stuff, 1, (PyObject *)fresult);
  5437. for (i=0; i<funcbuilder.nargs; i++) {
  5438. PyObject *o = PyTuple_GET_ITEM(fargs, i);
  5439. /* convert arrays into pointers */
  5440. if (((CTypeDescrObject *)o)->ct_flags & CT_ARRAY)
  5441. o = ((CTypeDescrObject *)o)->ct_stuff;
  5442. Py_INCREF(o);
  5443. PyTuple_SET_ITEM(fct->ct_stuff, 2 + i, o);
  5444. }
  5445. /* [ctresult, ellipsis+abi, num_args, ctargs...] */
  5446. unique_key = alloca((3 + funcbuilder.nargs) * sizeof(void *));
  5447. unique_key[0] = fresult;
  5448. unique_key[1] = (const void *)(Py_ssize_t)((fabi << 1) | !!ellipsis);
  5449. unique_key[2] = (const void *)(Py_ssize_t)(funcbuilder.nargs);
  5450. for (i=0; i<funcbuilder.nargs; i++)
  5451. unique_key[3 + i] = PyTuple_GET_ITEM(fct->ct_stuff, 2 + i);
  5452. return get_unique_type(fct, unique_key, 3 + funcbuilder.nargs);
  5453. error:
  5454. Py_DECREF(fct);
  5455. return NULL;
  5456. }
  5457. static PyObject *b_new_function_type(PyObject *self, PyObject *args)
  5458. {
  5459. PyObject *fargs;
  5460. CTypeDescrObject *fresult;
  5461. int ellipsis = 0, fabi = FFI_DEFAULT_ABI;
  5462. if (!PyArg_ParseTuple(args, "O!O!|ii:new_function_type",
  5463. &PyTuple_Type, &fargs,
  5464. &CTypeDescr_Type, &fresult,
  5465. &ellipsis,
  5466. &fabi))
  5467. return NULL;
  5468. return new_function_type(fargs, fresult, ellipsis, fabi);
  5469. }
  5470. static int convert_from_object_fficallback(char *result,
  5471. CTypeDescrObject *ctype,
  5472. PyObject *pyobj,
  5473. int encode_result_for_libffi)
  5474. {
  5475. /* work work work around a libffi irregularity: for integer return
  5476. types we have to fill at least a complete 'ffi_arg'-sized result
  5477. buffer. */
  5478. if (ctype->ct_size < (Py_ssize_t)sizeof(ffi_arg)) {
  5479. if (ctype->ct_flags & CT_VOID) {
  5480. if (pyobj == Py_None) {
  5481. return 0;
  5482. }
  5483. else {
  5484. PyErr_SetString(PyExc_TypeError,
  5485. "callback with the return type 'void' must return None");
  5486. return -1;
  5487. }
  5488. }
  5489. if (!encode_result_for_libffi)
  5490. goto skip;
  5491. if (ctype->ct_flags & CT_PRIMITIVE_SIGNED) {
  5492. PY_LONG_LONG value;
  5493. /* It's probably fine to always zero-extend, but you never
  5494. know: maybe some code somewhere expects a negative
  5495. 'short' result to be returned into EAX as a 32-bit
  5496. negative number. Better safe than sorry. This code
  5497. is about that case. Let's ignore this for enums.
  5498. */
  5499. /* do a first conversion only to detect overflows. This
  5500. conversion produces stuff that is otherwise ignored. */
  5501. if (convert_from_object(result, ctype, pyobj) < 0)
  5502. return -1;
  5503. /* manual inlining and tweaking of convert_from_object()
  5504. in order to write a whole 'ffi_arg'. */
  5505. value = _my_PyLong_AsLongLong(pyobj);
  5506. if (value == -1 && PyErr_Occurred())
  5507. return -1;
  5508. write_raw_integer_data(result, value, sizeof(ffi_arg));
  5509. return 0;
  5510. }
  5511. else if (ctype->ct_flags & (CT_PRIMITIVE_CHAR | CT_PRIMITIVE_SIGNED |
  5512. CT_PRIMITIVE_UNSIGNED |
  5513. CT_POINTER | CT_FUNCTIONPTR)) {
  5514. /* zero extension: fill the '*result' with zeros, and (on big-
  5515. endian machines) correct the 'result' pointer to write to.
  5516. We also do that for pointers, even though we're normally not
  5517. in this branch because ctype->ct_size == sizeof(ffi_arg) for
  5518. pointers---except on some architectures like x32 (issue #372).
  5519. */
  5520. memset(result, 0, sizeof(ffi_arg));
  5521. #ifdef WORDS_BIGENDIAN
  5522. result += (sizeof(ffi_arg) - ctype->ct_size);
  5523. #endif
  5524. }
  5525. }
  5526. skip:
  5527. return convert_from_object(result, ctype, pyobj);
  5528. }
  5529. static void _my_PyErr_WriteUnraisable(PyObject *t, PyObject *v, PyObject *tb,
  5530. char *objdescr, PyObject *obj,
  5531. char *extra_error_line)
  5532. {
  5533. /* like PyErr_WriteUnraisable(), but write a full traceback */
  5534. #ifdef USE_WRITEUNRAISABLEMSG
  5535. /* PyErr_WriteUnraisable actually writes the full traceback anyway
  5536. from Python 3.4, but we can't really get the formatting of the
  5537. custom text to be what we want. We can do better from Python
  5538. 3.8 by calling the new _PyErr_WriteUnraisableMsg().
  5539. Luckily it's also Python 3.8 that adds new functionality that
  5540. people might want: the new sys.unraisablehook().
  5541. */
  5542. PyObject *s;
  5543. int first_char;
  5544. assert(objdescr != NULL && objdescr[0] != 0); /* non-empty */
  5545. first_char = objdescr[0];
  5546. if (first_char >= 'A' && first_char <= 'Z')
  5547. first_char += 'a' - 'A'; /* lower() the very first character */
  5548. if (extra_error_line == NULL)
  5549. extra_error_line = "";
  5550. if (obj != NULL)
  5551. s = PyUnicode_FromFormat("%c%s%R%s",
  5552. first_char, objdescr + 1, obj, extra_error_line);
  5553. else
  5554. s = PyUnicode_FromFormat("%c%s%s",
  5555. first_char, objdescr + 1, extra_error_line);
  5556. PyErr_Restore(t, v, tb);
  5557. if (s != NULL) {
  5558. _PyErr_WriteUnraisableMsg(PyText_AS_UTF8(s), NULL);
  5559. Py_DECREF(s);
  5560. }
  5561. else
  5562. PyErr_WriteUnraisable(obj); /* best effort */
  5563. PyErr_Clear();
  5564. #else
  5565. /* version for Python 2.7 and < 3.8 */
  5566. PyObject *f;
  5567. #if PY_MAJOR_VERSION >= 3
  5568. /* jump through hoops to ensure the tb is attached to v, on Python 3 */
  5569. PyErr_NormalizeException(&t, &v, &tb);
  5570. if (tb == NULL) {
  5571. tb = Py_None;
  5572. Py_INCREF(tb);
  5573. }
  5574. PyException_SetTraceback(v, tb);
  5575. #endif
  5576. f = PySys_GetObject("stderr");
  5577. if (f != NULL) {
  5578. if (obj != NULL) {
  5579. PyFile_WriteString(objdescr, f);
  5580. PyFile_WriteObject(obj, f, 0);
  5581. PyFile_WriteString(":\n", f);
  5582. }
  5583. if (extra_error_line != NULL)
  5584. PyFile_WriteString(extra_error_line, f);
  5585. PyErr_Display(t, v, tb);
  5586. }
  5587. Py_XDECREF(t);
  5588. Py_XDECREF(v);
  5589. Py_XDECREF(tb);
  5590. #endif
  5591. }
  5592. static void general_invoke_callback(int decode_args_from_libffi,
  5593. void *result, char *args, void *userdata)
  5594. {
  5595. PyObject *cb_args = (PyObject *)userdata;
  5596. CTypeDescrObject *ct = (CTypeDescrObject *)PyTuple_GET_ITEM(cb_args, 0);
  5597. PyObject *signature = ct->ct_stuff;
  5598. PyObject *py_ob = PyTuple_GET_ITEM(cb_args, 1);
  5599. PyObject *py_args = NULL;
  5600. PyObject *py_res = NULL;
  5601. PyObject *py_rawerr;
  5602. PyObject *onerror_cb;
  5603. Py_ssize_t i, n;
  5604. char *extra_error_line = NULL;
  5605. #define SIGNATURE(i) ((CTypeDescrObject *)PyTuple_GET_ITEM(signature, i))
  5606. Py_INCREF(cb_args);
  5607. n = PyTuple_GET_SIZE(signature) - 2;
  5608. py_args = PyTuple_New(n);
  5609. if (py_args == NULL)
  5610. goto error;
  5611. for (i=0; i<n; i++) {
  5612. char *a_src;
  5613. PyObject *a;
  5614. CTypeDescrObject *a_ct = SIGNATURE(2 + i);
  5615. if (decode_args_from_libffi) {
  5616. a_src = ((void **)args)[i];
  5617. }
  5618. else {
  5619. a_src = args + i * 8;
  5620. if (a_ct->ct_flags & (CT_IS_LONGDOUBLE | CT_STRUCT | CT_UNION))
  5621. a_src = *(char **)a_src;
  5622. }
  5623. a = convert_to_object(a_src, a_ct);
  5624. if (a == NULL)
  5625. goto error;
  5626. PyTuple_SET_ITEM(py_args, i, a);
  5627. }
  5628. py_res = PyObject_Call(py_ob, py_args, NULL);
  5629. if (py_res == NULL)
  5630. goto error;
  5631. if (convert_from_object_fficallback(result, SIGNATURE(1), py_res,
  5632. decode_args_from_libffi) < 0) {
  5633. #ifdef USE_WRITEUNRAISABLEMSG
  5634. extra_error_line = ", trying to convert the result back to C";
  5635. #else
  5636. extra_error_line = "Trying to convert the result back to C:\n";
  5637. #endif
  5638. goto error;
  5639. }
  5640. done:
  5641. Py_XDECREF(py_args);
  5642. Py_XDECREF(py_res);
  5643. Py_DECREF(cb_args);
  5644. return;
  5645. error:
  5646. if (SIGNATURE(1)->ct_size > 0) {
  5647. py_rawerr = PyTuple_GET_ITEM(cb_args, 2);
  5648. memcpy(result, PyBytes_AS_STRING(py_rawerr),
  5649. PyBytes_GET_SIZE(py_rawerr));
  5650. }
  5651. onerror_cb = PyTuple_GET_ITEM(cb_args, 3);
  5652. if (onerror_cb == Py_None) {
  5653. PyObject *ecap, *t, *v, *tb;
  5654. PyErr_Fetch(&t, &v, &tb);
  5655. ecap = _cffi_start_error_capture();
  5656. _my_PyErr_WriteUnraisable(t, v, tb, "From cffi callback ", py_ob,
  5657. extra_error_line);
  5658. _cffi_stop_error_capture(ecap);
  5659. }
  5660. else {
  5661. PyObject *exc1, *val1, *tb1, *res1, *exc2, *val2, *tb2;
  5662. PyErr_Fetch(&exc1, &val1, &tb1);
  5663. PyErr_NormalizeException(&exc1, &val1, &tb1);
  5664. res1 = PyObject_CallFunctionObjArgs(onerror_cb,
  5665. exc1 ? exc1 : Py_None,
  5666. val1 ? val1 : Py_None,
  5667. tb1 ? tb1 : Py_None,
  5668. NULL);
  5669. if (res1 != NULL) {
  5670. if (res1 != Py_None)
  5671. convert_from_object_fficallback(result, SIGNATURE(1), res1,
  5672. decode_args_from_libffi);
  5673. Py_DECREF(res1);
  5674. }
  5675. if (!PyErr_Occurred()) {
  5676. Py_XDECREF(exc1);
  5677. Py_XDECREF(val1);
  5678. Py_XDECREF(tb1);
  5679. }
  5680. else {
  5681. /* double exception! print a double-traceback... */
  5682. PyObject *ecap;
  5683. PyErr_Fetch(&exc2, &val2, &tb2);
  5684. ecap = _cffi_start_error_capture();
  5685. _my_PyErr_WriteUnraisable(exc1, val1, tb1,
  5686. "From cffi callback ", py_ob,
  5687. extra_error_line);
  5688. #ifdef USE_WRITEUNRAISABLEMSG
  5689. _my_PyErr_WriteUnraisable(exc2, val2, tb2,
  5690. "during handling of the above exception by 'onerror'",
  5691. NULL, NULL);
  5692. #else
  5693. extra_error_line = ("\nDuring the call to 'onerror', "
  5694. "another exception occurred:\n\n");
  5695. _my_PyErr_WriteUnraisable(exc2, val2, tb2,
  5696. NULL, NULL, extra_error_line);
  5697. #endif
  5698. _cffi_stop_error_capture(ecap);
  5699. }
  5700. }
  5701. goto done;
  5702. #undef SIGNATURE
  5703. }
  5704. static void invoke_callback(ffi_cif *cif, void *result, void **args,
  5705. void *userdata)
  5706. {
  5707. save_errno();
  5708. {
  5709. PyGILState_STATE state = gil_ensure();
  5710. general_invoke_callback(1, result, (char *)args, userdata);
  5711. gil_release(state);
  5712. }
  5713. restore_errno();
  5714. }
  5715. static PyObject *prepare_callback_info_tuple(CTypeDescrObject *ct,
  5716. PyObject *ob,
  5717. PyObject *error_ob,
  5718. PyObject *onerror_ob,
  5719. int decode_args_from_libffi)
  5720. {
  5721. CTypeDescrObject *ctresult;
  5722. PyObject *py_rawerr, *infotuple;
  5723. Py_ssize_t size;
  5724. if (!(ct->ct_flags & CT_FUNCTIONPTR)) {
  5725. PyErr_Format(PyExc_TypeError, "expected a function ctype, got '%s'",
  5726. ct->ct_name);
  5727. return NULL;
  5728. }
  5729. if (!PyCallable_Check(ob)) {
  5730. PyErr_Format(PyExc_TypeError,
  5731. "expected a callable object, not %.200s",
  5732. Py_TYPE(ob)->tp_name);
  5733. return NULL;
  5734. }
  5735. if (onerror_ob != Py_None && !PyCallable_Check(onerror_ob)) {
  5736. PyErr_Format(PyExc_TypeError,
  5737. "expected a callable object for 'onerror', not %.200s",
  5738. Py_TYPE(onerror_ob)->tp_name);
  5739. return NULL;
  5740. }
  5741. ctresult = (CTypeDescrObject *)PyTuple_GET_ITEM(ct->ct_stuff, 1);
  5742. size = ctresult->ct_size;
  5743. if (size < (Py_ssize_t)sizeof(ffi_arg))
  5744. size = sizeof(ffi_arg);
  5745. py_rawerr = PyBytes_FromStringAndSize(NULL, size);
  5746. if (py_rawerr == NULL)
  5747. return NULL;
  5748. memset(PyBytes_AS_STRING(py_rawerr), 0, size);
  5749. if (error_ob != Py_None) {
  5750. if (convert_from_object_fficallback(
  5751. PyBytes_AS_STRING(py_rawerr), ctresult, error_ob,
  5752. decode_args_from_libffi) < 0) {
  5753. Py_DECREF(py_rawerr);
  5754. return NULL;
  5755. }
  5756. }
  5757. infotuple = Py_BuildValue("OOOO", ct, ob, py_rawerr, onerror_ob);
  5758. Py_DECREF(py_rawerr);
  5759. #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x03070000
  5760. /* We must setup the GIL here, in case the callback is invoked in
  5761. some other non-Pythonic thread. This is the same as ctypes.
  5762. But PyEval_InitThreads() is always a no-op from CPython 3.7
  5763. (the call from ctypes was removed some time later I think). */
  5764. PyEval_InitThreads();
  5765. #endif
  5766. return infotuple;
  5767. }
  5768. /* messily try to silence a gcc/clang deprecation warning for
  5769. ffi_prep_closure. Don't miss the "pragma pop" after the function.
  5770. This is done around the whole function because very old GCCs don't
  5771. support it inside a function. */
  5772. #if defined(__clang__)
  5773. # pragma clang diagnostic push
  5774. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  5775. #elif defined(__GNUC__)
  5776. # pragma GCC diagnostic push
  5777. # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  5778. #endif
  5779. static PyObject *b_callback(PyObject *self, PyObject *args)
  5780. {
  5781. CTypeDescrObject *ct;
  5782. CDataObject_closure *cd;
  5783. PyObject *ob, *error_ob = Py_None, *onerror_ob = Py_None;
  5784. PyObject *infotuple;
  5785. cif_description_t *cif_descr;
  5786. ffi_closure *closure;
  5787. ffi_status status;
  5788. void *closure_exec;
  5789. if (!PyArg_ParseTuple(args, "O!O|OO:callback", &CTypeDescr_Type, &ct, &ob,
  5790. &error_ob, &onerror_ob))
  5791. return NULL;
  5792. infotuple = prepare_callback_info_tuple(ct, ob, error_ob, onerror_ob, 1);
  5793. if (infotuple == NULL)
  5794. return NULL;
  5795. #if CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE
  5796. if (CFFI_CHECK_FFI_CLOSURE_ALLOC) {
  5797. closure = ffi_closure_alloc(sizeof(ffi_closure), &closure_exec);
  5798. } else
  5799. #endif
  5800. {
  5801. closure = cffi_closure_alloc();
  5802. closure_exec = closure;
  5803. }
  5804. if (closure == NULL) {
  5805. Py_DECREF(infotuple);
  5806. PyErr_SetString(PyExc_MemoryError,
  5807. "Cannot allocate write+execute memory for ffi.callback(). "
  5808. "You might be running on a system that prevents this. "
  5809. "For more information, see "
  5810. "https://cffi.readthedocs.io/en/latest/using.html#callbacks");
  5811. return NULL;
  5812. }
  5813. cd = PyObject_GC_New(CDataObject_closure, &CDataOwningGC_Type);
  5814. if (cd == NULL)
  5815. goto error;
  5816. Py_INCREF(ct);
  5817. cd->head.c_type = ct;
  5818. cd->head.c_data = (char *)closure_exec;
  5819. cd->head.c_weakreflist = NULL;
  5820. closure->user_data = NULL;
  5821. cd->closure = closure;
  5822. cif_descr = (cif_description_t *)ct->ct_extra;
  5823. if (cif_descr == NULL) {
  5824. PyErr_Format(PyExc_NotImplementedError,
  5825. "%s: callback with unsupported argument or "
  5826. "return type or with '...'", ct->ct_name);
  5827. goto error;
  5828. }
  5829. #if CFFI_CHECK_FFI_PREP_CLOSURE_LOC_MAYBE
  5830. if (CFFI_CHECK_FFI_PREP_CLOSURE_LOC) {
  5831. status = ffi_prep_closure_loc(closure, &cif_descr->cif,
  5832. invoke_callback, infotuple, closure_exec);
  5833. }
  5834. else
  5835. #endif
  5836. {
  5837. #if defined(__APPLE__) && defined(FFI_AVAILABLE_APPLE) && !FFI_LEGACY_CLOSURE_API
  5838. PyErr_Format(PyExc_SystemError, "ffi_prep_closure_loc() is missing");
  5839. goto error;
  5840. #else
  5841. status = ffi_prep_closure(closure, &cif_descr->cif,
  5842. invoke_callback, infotuple);
  5843. #endif
  5844. }
  5845. if (status != FFI_OK) {
  5846. PyErr_SetString(PyExc_SystemError,
  5847. "libffi failed to build this callback");
  5848. goto error;
  5849. }
  5850. if (closure->user_data != infotuple) {
  5851. /* Issue #266. Should not occur, but could, if we are using
  5852. at runtime a version of libffi compiled with a different
  5853. 'ffi_closure' structure than the one we expect from ffi.h
  5854. (e.g. difference in details of the platform): a difference
  5855. in FFI_TRAMPOLINE_SIZE means that the 'user_data' field
  5856. ends up somewhere else, and so the test above fails.
  5857. */
  5858. PyErr_SetString(PyExc_SystemError,
  5859. "ffi_prep_closure(): bad user_data (it seems that the "
  5860. "version of the libffi library seen at runtime is "
  5861. "different from the 'ffi.h' file seen at compile-time)");
  5862. goto error;
  5863. }
  5864. PyObject_GC_Track(cd);
  5865. return (PyObject *)cd;
  5866. error:
  5867. closure->user_data = NULL;
  5868. if (cd == NULL) {
  5869. #if CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE
  5870. if (CFFI_CHECK_FFI_CLOSURE_ALLOC) {
  5871. ffi_closure_free(closure);
  5872. }
  5873. else
  5874. #endif
  5875. cffi_closure_free(closure);
  5876. }
  5877. else
  5878. Py_DECREF(cd);
  5879. Py_XDECREF(infotuple);
  5880. return NULL;
  5881. }
  5882. #if defined(__clang__)
  5883. # pragma clang diagnostic pop
  5884. #elif defined(__GNUC__)
  5885. # pragma GCC diagnostic pop
  5886. #endif
  5887. static PyObject *b_new_enum_type(PyObject *self, PyObject *args)
  5888. {
  5889. char *ename;
  5890. PyObject *enumerators, *enumvalues;
  5891. PyObject *dict1 = NULL, *dict2 = NULL, *combined = NULL, *tmpkey = NULL;
  5892. int name_size;
  5893. CTypeDescrObject *td, *basetd;
  5894. Py_ssize_t i, n;
  5895. if (!PyArg_ParseTuple(args, "sO!O!O!:new_enum_type",
  5896. &ename,
  5897. &PyTuple_Type, &enumerators,
  5898. &PyTuple_Type, &enumvalues,
  5899. &CTypeDescr_Type, &basetd))
  5900. return NULL;
  5901. n = PyTuple_GET_SIZE(enumerators);
  5902. if (n != PyTuple_GET_SIZE(enumvalues)) {
  5903. PyErr_SetString(PyExc_ValueError,
  5904. "tuple args must have the same size");
  5905. return NULL;
  5906. }
  5907. if (!(basetd->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_UNSIGNED))) {
  5908. PyErr_SetString(PyExc_TypeError,
  5909. "expected a primitive signed or unsigned base type");
  5910. return NULL;
  5911. }
  5912. dict1 = PyDict_New();
  5913. if (dict1 == NULL)
  5914. goto error;
  5915. dict2 = PyDict_New();
  5916. if (dict2 == NULL)
  5917. goto error;
  5918. for (i=n; --i >= 0; ) {
  5919. long long lvalue;
  5920. PyObject *value = PyTuple_GET_ITEM(enumvalues, i);
  5921. tmpkey = PyTuple_GET_ITEM(enumerators, i);
  5922. Py_INCREF(tmpkey);
  5923. if (!PyText_Check(tmpkey)) {
  5924. #if PY_MAJOR_VERSION < 3
  5925. if (PyUnicode_Check(tmpkey)) {
  5926. const char *text = PyText_AsUTF8(tmpkey);
  5927. if (text == NULL)
  5928. goto error;
  5929. Py_DECREF(tmpkey);
  5930. tmpkey = PyString_FromString(text);
  5931. if (tmpkey == NULL)
  5932. goto error;
  5933. }
  5934. else
  5935. #endif
  5936. {
  5937. PyErr_SetString(PyExc_TypeError,
  5938. "enumerators must be a list of strings");
  5939. goto error;
  5940. }
  5941. }
  5942. if (convert_from_object((char*)&lvalue, basetd, value) < 0)
  5943. goto error; /* out-of-range or badly typed 'value' */
  5944. if (PyDict_SetItem(dict1, tmpkey, value) < 0)
  5945. goto error;
  5946. if (PyDict_SetItem(dict2, value, tmpkey) < 0)
  5947. goto error;
  5948. Py_DECREF(tmpkey);
  5949. tmpkey = NULL;
  5950. }
  5951. combined = PyTuple_Pack(2, dict1, dict2);
  5952. if (combined == NULL)
  5953. goto error;
  5954. Py_CLEAR(dict2);
  5955. Py_CLEAR(dict1);
  5956. name_size = strlen(ename) + 1;
  5957. td = ctypedescr_new(name_size);
  5958. if (td == NULL)
  5959. goto error;
  5960. memcpy(td->ct_name, ename, name_size);
  5961. td->ct_stuff = combined;
  5962. td->ct_size = basetd->ct_size;
  5963. td->ct_length = basetd->ct_length; /* alignment */
  5964. td->ct_extra = basetd->ct_extra; /* ffi type */
  5965. td->ct_flags = basetd->ct_flags | CT_IS_ENUM;
  5966. td->ct_name_position = name_size - 1;
  5967. return (PyObject *)td;
  5968. error:
  5969. Py_XDECREF(tmpkey);
  5970. Py_XDECREF(combined);
  5971. Py_XDECREF(dict2);
  5972. Py_XDECREF(dict1);
  5973. return NULL;
  5974. }
  5975. static PyObject *b_alignof(PyObject *self, PyObject *arg)
  5976. {
  5977. int align;
  5978. if (!CTypeDescr_Check(arg)) {
  5979. PyErr_SetString(PyExc_TypeError, "expected a 'ctype' object");
  5980. return NULL;
  5981. }
  5982. align = get_alignment((CTypeDescrObject *)arg);
  5983. if (align < 0)
  5984. return NULL;
  5985. return PyInt_FromLong(align);
  5986. }
  5987. static Py_ssize_t direct_sizeof_cdata(CDataObject *cd)
  5988. {
  5989. Py_ssize_t size;
  5990. if (cd->c_type->ct_flags & CT_ARRAY)
  5991. size = get_array_length(cd) * cd->c_type->ct_itemdescr->ct_size;
  5992. else {
  5993. size = -1;
  5994. if (cd->c_type->ct_flags & (CT_STRUCT | CT_UNION))
  5995. size = _cdata_var_byte_size(cd);
  5996. if (size < 0)
  5997. size = cd->c_type->ct_size;
  5998. }
  5999. return size;
  6000. }
  6001. static PyObject *b_sizeof(PyObject *self, PyObject *arg)
  6002. {
  6003. Py_ssize_t size;
  6004. if (CData_Check(arg)) {
  6005. size = direct_sizeof_cdata((CDataObject *)arg);
  6006. }
  6007. else if (CTypeDescr_Check(arg)) {
  6008. size = ((CTypeDescrObject *)arg)->ct_size;
  6009. if (size < 0) {
  6010. PyErr_Format(PyExc_ValueError, "ctype '%s' is of unknown size",
  6011. ((CTypeDescrObject *)arg)->ct_name);
  6012. return NULL;
  6013. }
  6014. }
  6015. else {
  6016. PyErr_SetString(PyExc_TypeError,
  6017. "expected a 'cdata' or 'ctype' object");
  6018. return NULL;
  6019. }
  6020. return PyInt_FromSsize_t(size);
  6021. }
  6022. static PyObject *b_typeof(PyObject *self, PyObject *arg)
  6023. {
  6024. PyObject *res;
  6025. if (!CData_Check(arg)) {
  6026. PyErr_SetString(PyExc_TypeError, "expected a 'cdata' object");
  6027. return NULL;
  6028. }
  6029. res = (PyObject *)((CDataObject *)arg)->c_type;
  6030. Py_INCREF(res);
  6031. return res;
  6032. }
  6033. static CTypeDescrObject *direct_typeoffsetof(CTypeDescrObject *ct,
  6034. PyObject *fieldname,
  6035. int following, Py_ssize_t *offset)
  6036. {
  6037. /* Does not return a new reference! */
  6038. CTypeDescrObject *res;
  6039. CFieldObject *cf;
  6040. if (PyTextAny_Check(fieldname)) {
  6041. if (!following && (ct->ct_flags & CT_POINTER))
  6042. ct = ct->ct_itemdescr;
  6043. if (!(ct->ct_flags & (CT_STRUCT|CT_UNION))) {
  6044. PyErr_SetString(PyExc_TypeError,
  6045. "with a field name argument, expected a "
  6046. "struct or union ctype");
  6047. return NULL;
  6048. }
  6049. if (force_lazy_struct(ct) <= 0) {
  6050. if (!PyErr_Occurred())
  6051. PyErr_SetString(PyExc_TypeError, "struct/union is opaque");
  6052. return NULL;
  6053. }
  6054. cf = (CFieldObject *)PyDict_GetItem(ct->ct_stuff, fieldname);
  6055. if (cf == NULL) {
  6056. PyErr_SetObject(PyExc_KeyError, fieldname);
  6057. return NULL;
  6058. }
  6059. if (cf->cf_bitshift >= 0) {
  6060. PyErr_SetString(PyExc_TypeError, "not supported for bitfields");
  6061. return NULL;
  6062. }
  6063. res = cf->cf_type;
  6064. *offset = cf->cf_offset;
  6065. }
  6066. else {
  6067. Py_ssize_t index = PyInt_AsSsize_t(fieldname);
  6068. if (index < 0 && PyErr_Occurred()) {
  6069. PyErr_SetString(PyExc_TypeError,
  6070. "field name or array index expected");
  6071. return NULL;
  6072. }
  6073. if (!(ct->ct_flags & (CT_ARRAY|CT_POINTER)) ||
  6074. ct->ct_itemdescr->ct_size < 0) {
  6075. PyErr_SetString(PyExc_TypeError, "with an integer argument, "
  6076. "expected an array ctype or a "
  6077. "pointer to non-opaque");
  6078. return NULL;
  6079. }
  6080. res = ct->ct_itemdescr;
  6081. *offset = MUL_WRAPAROUND(index, ct->ct_itemdescr->ct_size);
  6082. if ((*offset / ct->ct_itemdescr->ct_size) != index) {
  6083. PyErr_SetString(PyExc_OverflowError,
  6084. "array offset would overflow a Py_ssize_t");
  6085. return NULL;
  6086. }
  6087. }
  6088. return res;
  6089. }
  6090. static PyObject *b_typeoffsetof(PyObject *self, PyObject *args)
  6091. {
  6092. PyObject *res, *fieldname;
  6093. CTypeDescrObject *ct;
  6094. Py_ssize_t offset;
  6095. int following = 0;
  6096. if (!PyArg_ParseTuple(args, "O!O|i:typeoffsetof",
  6097. &CTypeDescr_Type, &ct, &fieldname, &following))
  6098. return NULL;
  6099. res = (PyObject *)direct_typeoffsetof(ct, fieldname, following, &offset);
  6100. if (res == NULL)
  6101. return NULL;
  6102. return Py_BuildValue("(On)", res, offset);
  6103. }
  6104. static PyObject *b_rawaddressof(PyObject *self, PyObject *args)
  6105. {
  6106. CTypeDescrObject *ct;
  6107. CDataObject *cd;
  6108. Py_ssize_t offset;
  6109. int accepted_flags;
  6110. if (!PyArg_ParseTuple(args, "O!O!n:rawaddressof",
  6111. &CTypeDescr_Type, &ct,
  6112. &CData_Type, &cd,
  6113. &offset))
  6114. return NULL;
  6115. accepted_flags = CT_STRUCT | CT_UNION | CT_ARRAY | CT_POINTER;
  6116. if ((cd->c_type->ct_flags & accepted_flags) == 0) {
  6117. PyErr_SetString(PyExc_TypeError,
  6118. "expected a cdata struct/union/array/pointer object");
  6119. return NULL;
  6120. }
  6121. if ((ct->ct_flags & CT_POINTER) == 0) {
  6122. PyErr_SetString(PyExc_TypeError,
  6123. "expected a pointer ctype");
  6124. return NULL;
  6125. }
  6126. return new_simple_cdata(cd->c_data + offset, ct);
  6127. }
  6128. static PyObject *b_getcname(PyObject *self, PyObject *args)
  6129. {
  6130. CTypeDescrObject *ct;
  6131. char *replace_with, *p, *s;
  6132. Py_ssize_t namelen, replacelen;
  6133. if (!PyArg_ParseTuple(args, "O!s:getcname",
  6134. &CTypeDescr_Type, &ct, &replace_with))
  6135. return NULL;
  6136. namelen = strlen(ct->ct_name);
  6137. replacelen = strlen(replace_with);
  6138. s = p = alloca(namelen + replacelen + 1);
  6139. memcpy(p, ct->ct_name, ct->ct_name_position);
  6140. p += ct->ct_name_position;
  6141. memcpy(p, replace_with, replacelen);
  6142. p += replacelen;
  6143. memcpy(p, ct->ct_name + ct->ct_name_position,
  6144. namelen - ct->ct_name_position);
  6145. return PyText_FromStringAndSize(s, namelen + replacelen);
  6146. }
  6147. static PyObject *b_string(PyObject *self, PyObject *args, PyObject *kwds)
  6148. {
  6149. CDataObject *cd;
  6150. Py_ssize_t maxlen = -1;
  6151. static char *keywords[] = {"cdata", "maxlen", NULL};
  6152. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|n:string", keywords,
  6153. &CData_Type, &cd, &maxlen))
  6154. return NULL;
  6155. if (cd->c_type->ct_itemdescr != NULL &&
  6156. cd->c_type->ct_itemdescr->ct_flags & (CT_PRIMITIVE_CHAR |
  6157. CT_PRIMITIVE_SIGNED |
  6158. CT_PRIMITIVE_UNSIGNED) &&
  6159. !(cd->c_type->ct_itemdescr->ct_flags & CT_IS_BOOL)) {
  6160. Py_ssize_t length = maxlen;
  6161. if (cd->c_data == NULL) {
  6162. PyObject *s = cdata_repr(cd);
  6163. if (s != NULL) {
  6164. PyErr_Format(PyExc_RuntimeError,
  6165. "cannot use string() on %s",
  6166. PyText_AS_UTF8(s));
  6167. Py_DECREF(s);
  6168. }
  6169. return NULL;
  6170. }
  6171. if (length < 0 && cd->c_type->ct_flags & CT_ARRAY) {
  6172. length = get_array_length(cd);
  6173. }
  6174. if (cd->c_type->ct_itemdescr->ct_size == sizeof(char)) {
  6175. const char *start = cd->c_data;
  6176. if (length < 0) {
  6177. /*READ(start, 1)*/
  6178. length = strlen(start);
  6179. /*READ(start, length)*/
  6180. }
  6181. else {
  6182. const char *end;
  6183. /*READ(start, length)*/
  6184. end = (const char *)memchr(start, 0, length);
  6185. if (end != NULL)
  6186. length = end - start;
  6187. }
  6188. return PyBytes_FromStringAndSize(start, length);
  6189. }
  6190. else if (cd->c_type->ct_itemdescr->ct_flags & CT_PRIMITIVE_CHAR) {
  6191. switch (cd->c_type->ct_itemdescr->ct_size) {
  6192. case 2: {
  6193. const cffi_char16_t *start = (cffi_char16_t *)cd->c_data;
  6194. if (length < 0) {
  6195. /*READ(start, 2)*/
  6196. length = 0;
  6197. while (start[length])
  6198. length++;
  6199. /*READ(start, 2 * length)*/
  6200. }
  6201. else {
  6202. /*READ(start, 2 * length)*/
  6203. maxlen = length;
  6204. length = 0;
  6205. while (length < maxlen && start[length])
  6206. length++;
  6207. }
  6208. return _my_PyUnicode_FromChar16(start, length);
  6209. }
  6210. case 4: {
  6211. const cffi_char32_t *start = (cffi_char32_t *)cd->c_data;
  6212. if (length < 0) {
  6213. /*READ(start, 4)*/
  6214. length = 0;
  6215. while (start[length])
  6216. length++;
  6217. /*READ(start, 4 * length)*/
  6218. }
  6219. else {
  6220. /*READ(start, 4 * length)*/
  6221. maxlen = length;
  6222. length = 0;
  6223. while (length < maxlen && start[length])
  6224. length++;
  6225. }
  6226. return _my_PyUnicode_FromChar32(start, length);
  6227. }
  6228. }
  6229. }
  6230. }
  6231. else if (cd->c_type->ct_flags & CT_IS_ENUM) {
  6232. return convert_cdata_to_enum_string(cd, 0);
  6233. }
  6234. else if (cd->c_type->ct_flags & CT_IS_BOOL) {
  6235. /* fall through to TypeError */
  6236. }
  6237. else if (cd->c_type->ct_flags & (CT_PRIMITIVE_CHAR |
  6238. CT_PRIMITIVE_SIGNED |
  6239. CT_PRIMITIVE_UNSIGNED)) {
  6240. /*READ(cd->c_data, cd->c_type->ct_size)*/
  6241. if (cd->c_type->ct_size == sizeof(char))
  6242. return PyBytes_FromStringAndSize(cd->c_data, 1);
  6243. else if (cd->c_type->ct_flags & CT_PRIMITIVE_CHAR) {
  6244. switch (cd->c_type->ct_size) {
  6245. case 2:
  6246. return _my_PyUnicode_FromChar16((cffi_char16_t *)cd->c_data, 1);
  6247. case 4:
  6248. return _my_PyUnicode_FromChar32((cffi_char32_t *)cd->c_data, 1);
  6249. }
  6250. }
  6251. }
  6252. PyErr_Format(PyExc_TypeError, "string(): unexpected cdata '%s' argument",
  6253. cd->c_type->ct_name);
  6254. return NULL;
  6255. }
  6256. static PyObject *b_unpack(PyObject *self, PyObject *args, PyObject *kwds)
  6257. {
  6258. CDataObject *cd;
  6259. CTypeDescrObject *ctitem;
  6260. Py_ssize_t i, length, itemsize;
  6261. PyObject *result;
  6262. char *src;
  6263. int casenum;
  6264. static char *keywords[] = {"cdata", "length", NULL};
  6265. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!n:unpack", keywords,
  6266. &CData_Type, &cd, &length))
  6267. return NULL;
  6268. if (!(cd->c_type->ct_flags & (CT_ARRAY|CT_POINTER))) {
  6269. PyErr_Format(PyExc_TypeError,
  6270. "expected a pointer or array, got '%s'",
  6271. cd->c_type->ct_name);
  6272. return NULL;
  6273. }
  6274. if (length < 0) {
  6275. PyErr_SetString(PyExc_ValueError, "'length' cannot be negative");
  6276. return NULL;
  6277. }
  6278. if (cd->c_data == NULL) {
  6279. PyObject *s = cdata_repr(cd);
  6280. if (s != NULL) {
  6281. PyErr_Format(PyExc_RuntimeError,
  6282. "cannot use unpack() on %s",
  6283. PyText_AS_UTF8(s));
  6284. Py_DECREF(s);
  6285. }
  6286. return NULL;
  6287. }
  6288. /* byte- and unicode strings */
  6289. ctitem = cd->c_type->ct_itemdescr;
  6290. if (ctitem->ct_flags & CT_PRIMITIVE_CHAR) {
  6291. switch (ctitem->ct_size) {
  6292. case sizeof(char):
  6293. return PyBytes_FromStringAndSize(cd->c_data, length);
  6294. case 2:
  6295. return _my_PyUnicode_FromChar16((cffi_char16_t *)cd->c_data,length);
  6296. case 4:
  6297. return _my_PyUnicode_FromChar32((cffi_char32_t *)cd->c_data,length);
  6298. }
  6299. }
  6300. /* else, the result is a list. This implementation should be
  6301. equivalent to but much faster than '[p[i] for i in range(length)]'.
  6302. (Note that on PyPy, 'list(p[0:length])' should be equally fast,
  6303. but arguably, finding out that there *is* such an unexpected way
  6304. to write things down is the real problem.)
  6305. */
  6306. result = PyList_New(length);
  6307. if (result == NULL)
  6308. return NULL;
  6309. src = cd->c_data;
  6310. itemsize = ctitem->ct_size;
  6311. if (itemsize < 0) {
  6312. Py_DECREF(result);
  6313. PyErr_Format(PyExc_ValueError, "'%s' points to items of unknown size",
  6314. cd->c_type->ct_name);
  6315. return NULL;
  6316. }
  6317. /* Determine some common fast-paths for the loop below. The case -1
  6318. is the fall-back, which always gives the right answer. */
  6319. #define ALIGNMENT_CHECK(align) \
  6320. (((align) & ((align) - 1)) == 0 && \
  6321. (((uintptr_t)src) & ((align) - 1)) == 0)
  6322. casenum = -1;
  6323. if ((ctitem->ct_flags & CT_PRIMITIVE_ANY) &&
  6324. ALIGNMENT_CHECK(ctitem->ct_length)) {
  6325. /* Source data is fully aligned; we can directly read without
  6326. memcpy(). The unaligned case is expected to be rare; in
  6327. this situation it is ok to fall back to the general
  6328. convert_to_object() in the loop. For now we also use this
  6329. fall-back for types that are too large.
  6330. */
  6331. if (ctitem->ct_flags & CT_PRIMITIVE_SIGNED) {
  6332. if (itemsize == sizeof(long)) casenum = 3;
  6333. else if (itemsize == sizeof(int)) casenum = 2;
  6334. else if (itemsize == sizeof(short)) casenum = 1;
  6335. else if (itemsize == sizeof(signed char)) casenum = 0;
  6336. }
  6337. else if (ctitem->ct_flags & CT_PRIMITIVE_UNSIGNED) {
  6338. /* Note: we never pick case 6 if sizeof(int) == sizeof(long),
  6339. so that case 6 below can assume that the 'unsigned int' result
  6340. would always fit in a 'signed long'. */
  6341. if (ctitem->ct_flags & CT_IS_BOOL) casenum = 11;
  6342. else if (itemsize == sizeof(unsigned long)) casenum = 7;
  6343. else if (itemsize == sizeof(unsigned int)) casenum = 6;
  6344. else if (itemsize == sizeof(unsigned short)) casenum = 5;
  6345. else if (itemsize == sizeof(unsigned char)) casenum = 4;
  6346. }
  6347. else if (ctitem->ct_flags & CT_PRIMITIVE_FLOAT) {
  6348. if (itemsize == sizeof(double)) casenum = 9;
  6349. else if (itemsize == sizeof(float)) casenum = 8;
  6350. }
  6351. }
  6352. else if (ctitem->ct_flags & (CT_POINTER | CT_FUNCTIONPTR)) {
  6353. casenum = 10; /* any pointer */
  6354. }
  6355. #undef ALIGNMENT_CHECK
  6356. for (i = 0; i < length; i++) {
  6357. PyObject *x;
  6358. switch (casenum) {
  6359. /* general case */
  6360. default: x = convert_to_object(src, ctitem); break;
  6361. /* special cases for performance only */
  6362. case 0: x = PyInt_FromLong(*(signed char *)src); break;
  6363. case 1: x = PyInt_FromLong(*(short *)src); break;
  6364. case 2: x = PyInt_FromLong(*(int *)src); break;
  6365. case 3: x = PyInt_FromLong(*(long *)src); break;
  6366. case 4: x = PyInt_FromLong(*(unsigned char *)src); break;
  6367. case 5: x = PyInt_FromLong(*(unsigned short *)src); break;
  6368. case 6: x = PyInt_FromLong((long)*(unsigned int *)src); break;
  6369. case 7: x = PyLong_FromUnsignedLong(*(unsigned long *)src); break;
  6370. case 8: x = PyFloat_FromDouble(*(float *)src); break;
  6371. case 9: x = PyFloat_FromDouble(*(double *)src); break;
  6372. case 10: x = new_simple_cdata(*(char **)src, ctitem); break;
  6373. case 11:
  6374. switch (*(unsigned char *)src) {
  6375. case 0: x = Py_False; Py_INCREF(x); break;
  6376. case 1: x = Py_True; Py_INCREF(x); break;
  6377. default: x = convert_to_object(src, ctitem); /* error */
  6378. }
  6379. break;
  6380. }
  6381. if (x == NULL) {
  6382. Py_DECREF(result);
  6383. return NULL;
  6384. }
  6385. PyList_SET_ITEM(result, i, x);
  6386. src += itemsize;
  6387. }
  6388. return result;
  6389. }
  6390. static PyObject *
  6391. b_buffer_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  6392. {
  6393. /* this is the constructor of the type implemented in minibuffer.h */
  6394. CDataObject *cd;
  6395. Py_ssize_t size = -1;
  6396. int explicit_size;
  6397. static char *keywords[] = {"cdata", "size", NULL};
  6398. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|n:buffer", keywords,
  6399. &CData_Type, &cd, &size))
  6400. return NULL;
  6401. explicit_size = size >= 0;
  6402. if (size < 0)
  6403. size = _cdata_var_byte_size(cd);
  6404. if (cd->c_type->ct_flags & CT_POINTER) {
  6405. if (size < 0)
  6406. size = cd->c_type->ct_itemdescr->ct_size;
  6407. }
  6408. else if (cd->c_type->ct_flags & CT_ARRAY) {
  6409. if (size < 0)
  6410. size = get_array_length(cd) * cd->c_type->ct_itemdescr->ct_size;
  6411. }
  6412. else {
  6413. PyErr_Format(PyExc_TypeError,
  6414. "expected a pointer or array cdata, got '%s'",
  6415. cd->c_type->ct_name);
  6416. return NULL;
  6417. }
  6418. if (size < 0) {
  6419. PyErr_Format(PyExc_TypeError,
  6420. "don't know the size pointed to by '%s'",
  6421. cd->c_type->ct_name);
  6422. return NULL;
  6423. }
  6424. if (explicit_size && CDataOwn_Check(cd)) {
  6425. Py_ssize_t size_max = cdataowning_size_bytes(cd);
  6426. if (size > size_max) {
  6427. char msg[256];
  6428. sprintf(msg, "ffi.buffer(cdata, bytes): creating a buffer of %llu "
  6429. "bytes over a cdata that owns only %llu bytes. This "
  6430. "will crash if you access the extra memory",
  6431. (unsigned PY_LONG_LONG)size,
  6432. (unsigned PY_LONG_LONG)size_max);
  6433. if (PyErr_WarnEx(PyExc_UserWarning, msg, 1))
  6434. return NULL;
  6435. }
  6436. }
  6437. /*WRITE(cd->c_data, size)*/
  6438. return minibuffer_new(cd->c_data, size, (PyObject *)cd);
  6439. }
  6440. static PyObject *b_get_errno(PyObject *self, PyObject *noarg)
  6441. {
  6442. int err;
  6443. restore_errno_only();
  6444. err = errno;
  6445. errno = 0;
  6446. return PyInt_FromLong(err);
  6447. }
  6448. static PyObject *b_set_errno(PyObject *self, PyObject *arg)
  6449. {
  6450. long ival = PyInt_AsLong(arg);
  6451. if (ival == -1 && PyErr_Occurred())
  6452. return NULL;
  6453. else if (ival < INT_MIN || ival > INT_MAX) {
  6454. PyErr_SetString(PyExc_OverflowError, "errno value too large");
  6455. return NULL;
  6456. }
  6457. errno = (int)ival;
  6458. save_errno_only();
  6459. errno = 0;
  6460. Py_INCREF(Py_None);
  6461. return Py_None;
  6462. }
  6463. static PyObject *newp_handle(CTypeDescrObject *ct_voidp, PyObject *x)
  6464. {
  6465. CDataObject_own_structptr *cd;
  6466. cd = (CDataObject_own_structptr *)PyObject_GC_New(CDataObject_own_structptr,
  6467. &CDataOwningGC_Type);
  6468. if (cd == NULL)
  6469. return NULL;
  6470. Py_INCREF(ct_voidp); /* must be "void *" */
  6471. cd->head.c_type = ct_voidp;
  6472. cd->head.c_data = (char *)cd;
  6473. cd->head.c_weakreflist = NULL;
  6474. Py_INCREF(x);
  6475. cd->structobj = x;
  6476. PyObject_GC_Track(cd);
  6477. return (PyObject *)cd;
  6478. }
  6479. static PyObject *b_newp_handle(PyObject *self, PyObject *args)
  6480. {
  6481. CTypeDescrObject *ct;
  6482. PyObject *x;
  6483. if (!PyArg_ParseTuple(args, "O!O", &CTypeDescr_Type, &ct, &x))
  6484. return NULL;
  6485. if (!(ct->ct_flags & CT_IS_VOID_PTR)) {
  6486. PyErr_Format(PyExc_TypeError, "needs 'void *', got '%s'", ct->ct_name);
  6487. return NULL;
  6488. }
  6489. return newp_handle(ct, x);
  6490. }
  6491. static PyObject *b_from_handle(PyObject *self, PyObject *arg)
  6492. {
  6493. CTypeDescrObject *ct;
  6494. CDataObject_own_structptr *orgcd;
  6495. PyObject *x;
  6496. if (!CData_Check(arg)) {
  6497. PyErr_SetString(PyExc_TypeError, "expected a 'cdata' object");
  6498. return NULL;
  6499. }
  6500. ct = ((CDataObject *)arg)->c_type;
  6501. if (!(ct->ct_flags & CT_IS_VOIDCHAR_PTR)) {
  6502. PyErr_Format(PyExc_TypeError,
  6503. "expected a 'cdata' object with a 'void *' out of "
  6504. "new_handle(), got '%s'", ct->ct_name);
  6505. return NULL;
  6506. }
  6507. orgcd = (CDataObject_own_structptr *)((CDataObject *)arg)->c_data;
  6508. if (!orgcd) {
  6509. PyErr_SetString(PyExc_RuntimeError,
  6510. "cannot use from_handle() on NULL pointer");
  6511. return NULL;
  6512. }
  6513. if (Py_REFCNT(orgcd) <= 0 || Py_TYPE(orgcd) != &CDataOwningGC_Type) {
  6514. Py_FatalError("ffi.from_handle() detected that the address passed "
  6515. "points to garbage. If it is really the result of "
  6516. "ffi.new_handle(), then the Python object has already "
  6517. "been garbage collected");
  6518. }
  6519. x = orgcd->structobj;
  6520. Py_INCREF(x);
  6521. return x;
  6522. }
  6523. static int _my_PyObject_GetContiguousBuffer(PyObject *x, Py_buffer *view,
  6524. int writable_only)
  6525. {
  6526. #if PY_MAJOR_VERSION < 3
  6527. /* Some objects only support the buffer interface and CPython doesn't
  6528. translate it into the memoryview interface, mess. Hack a very
  6529. minimal content for 'view'. Don't care if the other fields are
  6530. uninitialized: we only call PyBuffer_Release(), which only reads
  6531. 'view->obj'. */
  6532. PyBufferProcs *pb = x->ob_type->tp_as_buffer;
  6533. if (pb && !pb->bf_releasebuffer) {
  6534. /* we used to try all three in some vaguely sensible order,
  6535. i.e. first the write. But trying to call the write on a
  6536. read-only buffer fails with TypeError. So we use a less-
  6537. sensible order now. See test_from_buffer_more_cases.
  6538. If 'writable_only', we only try bf_getwritebuffer.
  6539. */
  6540. readbufferproc proc = NULL;
  6541. if (!writable_only) {
  6542. proc = (readbufferproc)pb->bf_getreadbuffer;
  6543. if (!proc)
  6544. proc = (readbufferproc)pb->bf_getcharbuffer;
  6545. }
  6546. if (!proc)
  6547. proc = (readbufferproc)pb->bf_getwritebuffer;
  6548. if (proc && pb->bf_getsegcount) {
  6549. if ((*pb->bf_getsegcount)(x, NULL) != 1) {
  6550. PyErr_SetString(PyExc_TypeError,
  6551. "expected a single-segment buffer object");
  6552. return -1;
  6553. }
  6554. view->len = (*proc)(x, 0, &view->buf);
  6555. if (view->len < 0)
  6556. return -1;
  6557. view->obj = x;
  6558. Py_INCREF(x);
  6559. return 0;
  6560. }
  6561. }
  6562. #endif
  6563. if (PyObject_GetBuffer(x, view, writable_only ? PyBUF_WRITABLE
  6564. : PyBUF_SIMPLE) < 0)
  6565. return -1;
  6566. if (!PyBuffer_IsContiguous(view, 'A')) {
  6567. PyBuffer_Release(view);
  6568. PyErr_SetString(PyExc_TypeError, "contiguous buffer expected");
  6569. return -1;
  6570. }
  6571. return 0;
  6572. }
  6573. static PyObject *direct_from_buffer(CTypeDescrObject *ct, PyObject *x,
  6574. int require_writable)
  6575. {
  6576. CDataObject *cd;
  6577. Py_buffer *view;
  6578. Py_ssize_t arraylength, minimumlength = 0;
  6579. if (!(ct->ct_flags & (CT_ARRAY | CT_POINTER))) {
  6580. PyErr_Format(PyExc_TypeError,
  6581. "expected a pointer or array ctype, got '%s'",
  6582. ct->ct_name);
  6583. return NULL;
  6584. }
  6585. /* PyPy 5.7 can obtain buffers for string (python 2)
  6586. or bytes (python 3). from_buffer(u"foo") is disallowed.
  6587. */
  6588. if (PyUnicode_Check(x)) {
  6589. PyErr_SetString(PyExc_TypeError,
  6590. "from_buffer() cannot return the address "
  6591. "of a unicode object");
  6592. return NULL;
  6593. }
  6594. view = PyObject_Malloc(sizeof(Py_buffer));
  6595. if (view == NULL) {
  6596. PyErr_NoMemory();
  6597. return NULL;
  6598. }
  6599. if (_my_PyObject_GetContiguousBuffer(x, view, require_writable) < 0)
  6600. goto error1;
  6601. if (ct->ct_flags & CT_POINTER)
  6602. {
  6603. arraylength = view->len; /* number of bytes, not used so far */
  6604. }
  6605. else {
  6606. /* ct->ct_flags & CT_ARRAY */
  6607. if (ct->ct_length >= 0) {
  6608. /* it's an array with a fixed length; make sure that the
  6609. buffer contains enough bytes. */
  6610. minimumlength = ct->ct_size;
  6611. arraylength = ct->ct_length;
  6612. }
  6613. else {
  6614. /* it's an open 'array[]' */
  6615. if (ct->ct_itemdescr->ct_size == 1) {
  6616. /* fast path, performance only */
  6617. arraylength = view->len;
  6618. }
  6619. else if (ct->ct_itemdescr->ct_size > 0) {
  6620. /* give it as many items as fit the buffer. Ignore a
  6621. partial last element. */
  6622. arraylength = view->len / ct->ct_itemdescr->ct_size;
  6623. }
  6624. else {
  6625. /* it's an array 'empty[]'. Unsupported obscure case:
  6626. the problem is that setting the length of the result
  6627. to anything large (like SSIZE_T_MAX) is dangerous,
  6628. because if someone tries to loop over it, it will
  6629. turn effectively into an infinite loop. */
  6630. PyErr_Format(PyExc_ZeroDivisionError,
  6631. "from_buffer('%s', ..): the actual length of the array "
  6632. "cannot be computed", ct->ct_name);
  6633. goto error2;
  6634. }
  6635. }
  6636. }
  6637. if (view->len < minimumlength) {
  6638. PyErr_Format(PyExc_ValueError,
  6639. "buffer is too small (%zd bytes) for '%s' (%zd bytes)",
  6640. view->len, ct->ct_name, minimumlength);
  6641. goto error2;
  6642. }
  6643. cd = (CDataObject *)PyObject_GC_New(CDataObject_frombuf,
  6644. &CDataFromBuf_Type);
  6645. if (cd == NULL)
  6646. goto error2;
  6647. Py_INCREF(ct);
  6648. cd->c_type = ct;
  6649. cd->c_data = view->buf;
  6650. cd->c_weakreflist = NULL;
  6651. ((CDataObject_frombuf *)cd)->length = arraylength;
  6652. ((CDataObject_frombuf *)cd)->bufferview = view;
  6653. PyObject_GC_Track(cd);
  6654. return (PyObject *)cd;
  6655. error2:
  6656. PyBuffer_Release(view);
  6657. error1:
  6658. PyObject_Free(view);
  6659. return NULL;
  6660. }
  6661. static PyObject *b_from_buffer(PyObject *self, PyObject *args)
  6662. {
  6663. CTypeDescrObject *ct;
  6664. PyObject *x;
  6665. int require_writable = 0;
  6666. if (!PyArg_ParseTuple(args, "O!O|i", &CTypeDescr_Type, &ct, &x,
  6667. &require_writable))
  6668. return NULL;
  6669. return direct_from_buffer(ct, x, require_writable);
  6670. }
  6671. static int _fetch_as_buffer(PyObject *x, Py_buffer *view, int writable_only)
  6672. {
  6673. if (CData_Check(x)) {
  6674. CTypeDescrObject *ct = ((CDataObject *)x)->c_type;
  6675. if (!(ct->ct_flags & (CT_POINTER|CT_ARRAY))) {
  6676. PyErr_Format(PyExc_TypeError,
  6677. "expected a pointer or array ctype, got '%s'",
  6678. ct->ct_name);
  6679. return -1;
  6680. }
  6681. view->buf = ((CDataObject *)x)->c_data;
  6682. view->obj = NULL;
  6683. return 0;
  6684. }
  6685. else {
  6686. return _my_PyObject_GetContiguousBuffer(x, view, writable_only);
  6687. }
  6688. }
  6689. static PyObject *b_memmove(PyObject *self, PyObject *args, PyObject *kwds)
  6690. {
  6691. PyObject *dest_obj, *src_obj;
  6692. Py_buffer dest_view, src_view;
  6693. Py_ssize_t n;
  6694. static char *keywords[] = {"dest", "src", "n", NULL};
  6695. if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOn", keywords,
  6696. &dest_obj, &src_obj, &n))
  6697. return NULL;
  6698. if (n < 0) {
  6699. PyErr_SetString(PyExc_ValueError, "negative size");
  6700. return NULL;
  6701. }
  6702. if (_fetch_as_buffer(src_obj, &src_view, 0) < 0) {
  6703. return NULL;
  6704. }
  6705. if (_fetch_as_buffer(dest_obj, &dest_view, 1) < 0) {
  6706. PyBuffer_Release(&src_view);
  6707. return NULL;
  6708. }
  6709. memmove(dest_view.buf, src_view.buf, n);
  6710. PyBuffer_Release(&dest_view);
  6711. PyBuffer_Release(&src_view);
  6712. Py_INCREF(Py_None);
  6713. return Py_None;
  6714. }
  6715. static PyObject *b__get_types(PyObject *self, PyObject *noarg)
  6716. {
  6717. return PyTuple_Pack(2, (PyObject *)&CData_Type,
  6718. (PyObject *)&CTypeDescr_Type);
  6719. }
  6720. /* forward, in commontypes.c */
  6721. static PyObject *b__get_common_types(PyObject *self, PyObject *arg);
  6722. static PyObject *b_gcp(PyObject *self, PyObject *args, PyObject *kwds)
  6723. {
  6724. CDataObject *cd;
  6725. CDataObject *origobj;
  6726. PyObject *destructor;
  6727. Py_ssize_t ignored; /* for pypy */
  6728. static char *keywords[] = {"cdata", "destructor", "size", NULL};
  6729. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O|n:gc", keywords,
  6730. &CData_Type, &origobj, &destructor,
  6731. &ignored))
  6732. return NULL;
  6733. if (destructor == Py_None) {
  6734. if (!PyObject_TypeCheck(origobj, &CDataGCP_Type)) {
  6735. PyErr_SetString(PyExc_TypeError,
  6736. "Can remove destructor only on a object "
  6737. "previously returned by ffi.gc()");
  6738. return NULL;
  6739. }
  6740. Py_CLEAR(((CDataObject_gcp *)origobj)->destructor);
  6741. Py_RETURN_NONE;
  6742. }
  6743. cd = allocate_gcp_object(origobj, origobj->c_type, destructor);
  6744. return (PyObject *)cd;
  6745. }
  6746. static PyObject *b_release(PyObject *self, PyObject *arg)
  6747. {
  6748. if (!CData_Check(arg)) {
  6749. PyErr_SetString(PyExc_TypeError, "expected a 'cdata' object");
  6750. return NULL;
  6751. }
  6752. return cdata_exit(arg, NULL);
  6753. }
  6754. /************************************************************/
  6755. static char _testfunc0(char a, char b)
  6756. {
  6757. return a + b;
  6758. }
  6759. static long _testfunc1(int a, long b)
  6760. {
  6761. return (long)a + b;
  6762. }
  6763. static PY_LONG_LONG _testfunc2(PY_LONG_LONG a, PY_LONG_LONG b)
  6764. {
  6765. return a + b;
  6766. }
  6767. static double _testfunc3(float a, double b)
  6768. {
  6769. return a + b;
  6770. }
  6771. static float _testfunc4(float a, double b)
  6772. {
  6773. return (float)(a + b);
  6774. }
  6775. static void _testfunc5(void)
  6776. {
  6777. errno = errno + 15;
  6778. }
  6779. static int *_testfunc6(int *x)
  6780. {
  6781. static int y;
  6782. y = *x - 1000;
  6783. return &y;
  6784. }
  6785. struct _testfunc7_s { unsigned char a1; short a2; };
  6786. static short _testfunc7(struct _testfunc7_s inlined)
  6787. {
  6788. return inlined.a1 + inlined.a2;
  6789. }
  6790. static int _testfunc9(int num, ...)
  6791. {
  6792. va_list vargs;
  6793. int i, total = 0;
  6794. va_start(vargs, num);
  6795. for (i=0; i<num; i++) {
  6796. int value = va_arg(vargs, int);
  6797. if (value == 0)
  6798. value = -66666666;
  6799. total += value;
  6800. }
  6801. va_end(vargs);
  6802. return total;
  6803. }
  6804. static struct _testfunc7_s _testfunc10(int n)
  6805. {
  6806. struct _testfunc7_s result;
  6807. result.a1 = n;
  6808. result.a2 = n * n;
  6809. return result;
  6810. }
  6811. struct _testfunc11_s { int a1, a2; };
  6812. static struct _testfunc11_s _testfunc11(int n)
  6813. {
  6814. struct _testfunc11_s result;
  6815. result.a1 = n;
  6816. result.a2 = n * n;
  6817. return result;
  6818. }
  6819. struct _testfunc12_s { double a1; };
  6820. static struct _testfunc12_s _testfunc12(int n)
  6821. {
  6822. struct _testfunc12_s result;
  6823. result.a1 = n;
  6824. return result;
  6825. }
  6826. struct _testfunc13_s { int a1, a2, a3; };
  6827. static struct _testfunc13_s _testfunc13(int n)
  6828. {
  6829. struct _testfunc13_s result;
  6830. result.a1 = n;
  6831. result.a2 = n * n;
  6832. result.a3 = n * n * n;
  6833. return result;
  6834. }
  6835. struct _testfunc14_s { float a1; };
  6836. static struct _testfunc14_s _testfunc14(int n)
  6837. {
  6838. struct _testfunc14_s result;
  6839. result.a1 = (float)n;
  6840. return result;
  6841. }
  6842. struct _testfunc15_s { float a1; int a2; };
  6843. static struct _testfunc15_s _testfunc15(int n)
  6844. {
  6845. struct _testfunc15_s result;
  6846. result.a1 = (float)n;
  6847. result.a2 = n * n;
  6848. return result;
  6849. }
  6850. struct _testfunc16_s { float a1, a2; };
  6851. static struct _testfunc16_s _testfunc16(int n)
  6852. {
  6853. struct _testfunc16_s result;
  6854. result.a1 = (float)n;
  6855. result.a2 = -(float)n;
  6856. return result;
  6857. }
  6858. struct _testfunc17_s { int a1; float a2; };
  6859. static struct _testfunc17_s _testfunc17(int n)
  6860. {
  6861. struct _testfunc17_s result;
  6862. result.a1 = n;
  6863. result.a2 = (float)n * (float)n;
  6864. return result;
  6865. }
  6866. static int _testfunc18(struct _testfunc17_s *ptr)
  6867. {
  6868. return ptr->a1 + (int)ptr->a2;
  6869. }
  6870. static long double _testfunc19(long double x, int count)
  6871. {
  6872. int i;
  6873. for (i=0; i<count; i++) {
  6874. x = 4*x - x*x;
  6875. }
  6876. return x;
  6877. }
  6878. static short _testfunc20(struct _testfunc7_s *ptr)
  6879. {
  6880. return ptr->a1 + ptr->a2;
  6881. }
  6882. struct _testfunc21_s { int a, b, c, d, e, f, g, h, i, j; };
  6883. static int _testfunc21(struct _testfunc21_s inlined)
  6884. {
  6885. return ((inlined.a << 0) +
  6886. (inlined.b << 1) +
  6887. (inlined.c << 2) +
  6888. (inlined.d << 3) +
  6889. (inlined.e << 4) +
  6890. (inlined.f << 5) +
  6891. (inlined.g << 6) +
  6892. (inlined.h << 7) +
  6893. (inlined.i << 8) +
  6894. (inlined.j << 9));
  6895. }
  6896. struct _testfunc22_s { int a[10]; };
  6897. static struct _testfunc22_s _testfunc22(struct _testfunc22_s s1,
  6898. struct _testfunc22_s s2)
  6899. {
  6900. struct _testfunc22_s result;
  6901. int i;
  6902. for (i=0; i<10; i++)
  6903. result.a[i] = s1.a[i] - s2.a[i];
  6904. return result;
  6905. }
  6906. static int _testfunc23(char *p)
  6907. {
  6908. if (p)
  6909. return 1000 * p[0];
  6910. return -42;
  6911. }
  6912. #if 0 /* libffi doesn't properly support complexes currently */
  6913. /* also, MSVC might not support _Complex... */
  6914. /* if this is enabled one day, remember to also add _Complex
  6915. * arguments in addition to return values. */
  6916. static float _Complex _testfunc24(float a, float b)
  6917. {
  6918. return a + I*2.0*b;
  6919. }
  6920. static double _Complex _testfunc25(double a, double b)
  6921. {
  6922. return a + I*2.0*b;
  6923. }
  6924. #endif
  6925. static PyObject *b__testfunc(PyObject *self, PyObject *args)
  6926. {
  6927. /* for testing only */
  6928. int i;
  6929. void *f;
  6930. if (!PyArg_ParseTuple(args, "i:_testfunc", &i))
  6931. return NULL;
  6932. switch (i) {
  6933. case 0: f = &_testfunc0; break;
  6934. case 1: f = &_testfunc1; break;
  6935. case 2: f = &_testfunc2; break;
  6936. case 3: f = &_testfunc3; break;
  6937. case 4: f = &_testfunc4; break;
  6938. case 5: f = &_testfunc5; break;
  6939. case 6: f = &_testfunc6; break;
  6940. case 7: f = &_testfunc7; break;
  6941. case 8: f = stderr; break;
  6942. case 9: f = &_testfunc9; break;
  6943. case 10: f = &_testfunc10; break;
  6944. case 11: f = &_testfunc11; break;
  6945. case 12: f = &_testfunc12; break;
  6946. case 13: f = &_testfunc13; break;
  6947. case 14: f = &_testfunc14; break;
  6948. case 15: f = &_testfunc15; break;
  6949. case 16: f = &_testfunc16; break;
  6950. case 17: f = &_testfunc17; break;
  6951. case 18: f = &_testfunc18; break;
  6952. case 19: f = &_testfunc19; break;
  6953. case 20: f = &_testfunc20; break;
  6954. case 21: f = &_testfunc21; break;
  6955. case 22: f = &_testfunc22; break;
  6956. case 23: f = &_testfunc23; break;
  6957. #if 0
  6958. case 24: f = &_testfunc24; break;
  6959. case 25: f = &_testfunc25; break;
  6960. #endif
  6961. default:
  6962. PyErr_SetNone(PyExc_ValueError);
  6963. return NULL;
  6964. }
  6965. return PyLong_FromVoidPtr(f);
  6966. }
  6967. #if PY_MAJOR_VERSION < 3
  6968. static Py_ssize_t _test_segcountproc(PyObject *o, Py_ssize_t *ignored)
  6969. {
  6970. return 1;
  6971. }
  6972. static Py_ssize_t _test_getreadbuf(PyObject *o, Py_ssize_t i, void **r)
  6973. {
  6974. static char buf[] = "RDB";
  6975. *r = buf;
  6976. return 3;
  6977. }
  6978. static Py_ssize_t _test_getwritebuf(PyObject *o, Py_ssize_t i, void **r)
  6979. {
  6980. static char buf[] = "WRB";
  6981. *r = buf;
  6982. return 3;
  6983. }
  6984. static Py_ssize_t _test_getcharbuf(PyObject *o, Py_ssize_t i, char **r)
  6985. {
  6986. static char buf[] = "CHB";
  6987. *r = buf;
  6988. return 3;
  6989. }
  6990. #endif
  6991. static int _test_getbuf(PyObject *self, Py_buffer *view, int flags)
  6992. {
  6993. static char buf[] = "GTB";
  6994. return PyBuffer_FillInfo(view, self, buf, 3, /*readonly=*/0, flags);
  6995. }
  6996. static int _test_getbuf_ro(PyObject *self, Py_buffer *view, int flags)
  6997. {
  6998. static char buf[] = "ROB";
  6999. return PyBuffer_FillInfo(view, self, buf, 3, /*readonly=*/1, flags);
  7000. }
  7001. static PyObject *b__testbuff(PyObject *self, PyObject *args)
  7002. {
  7003. /* for testing only */
  7004. int methods;
  7005. PyTypeObject *obj;
  7006. if (!PyArg_ParseTuple(args, "O!i|_testbuff", &PyType_Type, &obj, &methods))
  7007. return NULL;
  7008. assert(obj->tp_as_buffer != NULL);
  7009. #if PY_MAJOR_VERSION < 3
  7010. obj->tp_as_buffer->bf_getsegcount = &_test_segcountproc;
  7011. obj->tp_flags |= Py_TPFLAGS_HAVE_GETCHARBUFFER;
  7012. obj->tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
  7013. if (methods & 1) obj->tp_as_buffer->bf_getreadbuffer = &_test_getreadbuf;
  7014. if (methods & 2) obj->tp_as_buffer->bf_getwritebuffer = &_test_getwritebuf;
  7015. if (methods & 4) obj->tp_as_buffer->bf_getcharbuffer = &_test_getcharbuf;
  7016. #endif
  7017. if (methods & 8) obj->tp_as_buffer->bf_getbuffer = &_test_getbuf;
  7018. if (methods & 16) obj->tp_as_buffer->bf_getbuffer = &_test_getbuf_ro;
  7019. Py_INCREF(Py_None);
  7020. return Py_None;
  7021. }
  7022. static PyObject *b_init_cffi_1_0_external_module(PyObject *, PyObject *);
  7023. /* forward, see cffi1_module.c */
  7024. static PyMethodDef FFIBackendMethods[] = {
  7025. {"load_library", b_load_library, METH_VARARGS},
  7026. {"new_primitive_type", b_new_primitive_type, METH_VARARGS},
  7027. {"new_pointer_type", b_new_pointer_type, METH_VARARGS},
  7028. {"new_array_type", b_new_array_type, METH_VARARGS},
  7029. {"new_void_type", b_new_void_type, METH_NOARGS},
  7030. {"new_struct_type", b_new_struct_type, METH_VARARGS},
  7031. {"new_union_type", b_new_union_type, METH_VARARGS},
  7032. {"complete_struct_or_union", b_complete_struct_or_union, METH_VARARGS},
  7033. {"new_function_type", b_new_function_type, METH_VARARGS},
  7034. {"new_enum_type", b_new_enum_type, METH_VARARGS},
  7035. {"newp", b_newp, METH_VARARGS},
  7036. {"cast", b_cast, METH_VARARGS},
  7037. {"callback", b_callback, METH_VARARGS},
  7038. {"alignof", b_alignof, METH_O},
  7039. {"sizeof", b_sizeof, METH_O},
  7040. {"typeof", b_typeof, METH_O},
  7041. {"typeoffsetof", b_typeoffsetof, METH_VARARGS},
  7042. {"rawaddressof", b_rawaddressof, METH_VARARGS},
  7043. {"getcname", b_getcname, METH_VARARGS},
  7044. {"string", (PyCFunction)b_string, METH_VARARGS | METH_KEYWORDS},
  7045. {"unpack", (PyCFunction)b_unpack, METH_VARARGS | METH_KEYWORDS},
  7046. {"get_errno", b_get_errno, METH_NOARGS},
  7047. {"set_errno", b_set_errno, METH_O},
  7048. {"newp_handle", b_newp_handle, METH_VARARGS},
  7049. {"from_handle", b_from_handle, METH_O},
  7050. {"from_buffer", b_from_buffer, METH_VARARGS},
  7051. {"memmove", (PyCFunction)b_memmove, METH_VARARGS | METH_KEYWORDS},
  7052. {"gcp", (PyCFunction)b_gcp, METH_VARARGS | METH_KEYWORDS},
  7053. {"release", b_release, METH_O},
  7054. #ifdef MS_WIN32
  7055. {"getwinerror", (PyCFunction)b_getwinerror, METH_VARARGS | METH_KEYWORDS},
  7056. #endif
  7057. {"_get_types", b__get_types, METH_NOARGS},
  7058. {"_get_common_types", b__get_common_types, METH_O},
  7059. {"_testfunc", b__testfunc, METH_VARARGS},
  7060. {"_testbuff", b__testbuff, METH_VARARGS},
  7061. {"_init_cffi_1_0_external_module", b_init_cffi_1_0_external_module, METH_O},
  7062. {NULL, NULL} /* Sentinel */
  7063. };
  7064. /************************************************************/
  7065. /* Functions used by '_cffi_N.so', the generated modules */
  7066. #define _cffi_to_c_SIGNED_FN(RETURNTYPE, SIZE) \
  7067. static RETURNTYPE _cffi_to_c_i##SIZE(PyObject *obj) { \
  7068. PY_LONG_LONG tmp = _my_PyLong_AsLongLong(obj); \
  7069. if ((tmp > (PY_LONG_LONG)((1ULL<<(SIZE-1)) - 1)) || \
  7070. (tmp < (PY_LONG_LONG)(0ULL-(1ULL<<(SIZE-1))))) \
  7071. if (!PyErr_Occurred()) \
  7072. return (RETURNTYPE)_convert_overflow(obj, #SIZE "-bit int"); \
  7073. return (RETURNTYPE)tmp; \
  7074. }
  7075. #define _cffi_to_c_UNSIGNED_FN(RETURNTYPE, SIZE) \
  7076. static RETURNTYPE _cffi_to_c_u##SIZE(PyObject *obj) { \
  7077. unsigned PY_LONG_LONG tmp = _my_PyLong_AsUnsignedLongLong(obj, 1); \
  7078. if (tmp > ~(((unsigned PY_LONG_LONG)-2) << (SIZE-1))) \
  7079. if (!PyErr_Occurred()) \
  7080. return (RETURNTYPE)_convert_overflow(obj, \
  7081. #SIZE "-bit unsigned int"); \
  7082. return (RETURNTYPE)tmp; \
  7083. }
  7084. _cffi_to_c_SIGNED_FN(int, 8)
  7085. _cffi_to_c_SIGNED_FN(int, 16)
  7086. _cffi_to_c_SIGNED_FN(int, 32)
  7087. _cffi_to_c_SIGNED_FN(PY_LONG_LONG, 64)
  7088. _cffi_to_c_UNSIGNED_FN(int, 8)
  7089. _cffi_to_c_UNSIGNED_FN(int, 16)
  7090. _cffi_to_c_UNSIGNED_FN(unsigned int, 32)
  7091. _cffi_to_c_UNSIGNED_FN(unsigned PY_LONG_LONG, 64)
  7092. static PyObject *_cffi_from_c_pointer(char *ptr, CTypeDescrObject *ct)
  7093. {
  7094. return convert_to_object((char *)&ptr, ct);
  7095. }
  7096. static char *_cffi_to_c_pointer(PyObject *obj, CTypeDescrObject *ct)
  7097. {
  7098. char *result;
  7099. if (convert_from_object((char *)&result, ct, obj) < 0) {
  7100. if ((ct->ct_flags & CT_POINTER) &&
  7101. (ct->ct_itemdescr->ct_flags & CT_IS_FILE) &&
  7102. PyFile_Check(obj)) {
  7103. PyErr_Clear();
  7104. return (char *)PyFile_AsFile(obj);
  7105. }
  7106. return NULL;
  7107. }
  7108. return result;
  7109. }
  7110. static long double _cffi_to_c_long_double(PyObject *obj)
  7111. {
  7112. if (CData_Check(obj) &&
  7113. (((CDataObject *)obj)->c_type->ct_flags & CT_IS_LONGDOUBLE)) {
  7114. char *data = ((CDataObject *)obj)->c_data;
  7115. /*READ(data, sizeof(long double))*/
  7116. return read_raw_longdouble_data(data);
  7117. }
  7118. else
  7119. return PyFloat_AsDouble(obj);
  7120. }
  7121. static _Bool _cffi_to_c__Bool(PyObject *obj)
  7122. {
  7123. PY_LONG_LONG tmp = _my_PyLong_AsLongLong(obj);
  7124. if (tmp == 0)
  7125. return 0;
  7126. else if (tmp == 1)
  7127. return 1;
  7128. else if (PyErr_Occurred())
  7129. return (_Bool)-1;
  7130. else
  7131. return (_Bool)_convert_overflow(obj, "_Bool");
  7132. }
  7133. static PyObject *_cffi_get_struct_layout(Py_ssize_t nums[])
  7134. {
  7135. PyObject *result;
  7136. int count = 0;
  7137. while (nums[count] >= 0)
  7138. count++;
  7139. result = PyList_New(count);
  7140. if (result == NULL)
  7141. return NULL;
  7142. while (--count >= 0) {
  7143. PyObject *o = PyInt_FromSsize_t(nums[count]);
  7144. if (o == NULL) {
  7145. Py_DECREF(result);
  7146. return NULL;
  7147. }
  7148. PyList_SET_ITEM(result, count, o);
  7149. }
  7150. return result;
  7151. }
  7152. static PyObject *_cffi_from_c_char(char x) {
  7153. return PyBytes_FromStringAndSize(&x, 1);
  7154. }
  7155. /* backward-compatibility hack: instead of _cffi_to_c_char16_t() and
  7156. * _cffi_to_c_char32_t(), we have _cffi_to_c_wchar_t() handling whatever
  7157. * size is wchar_t, and _cffi_to_c_wchar3216_t() handling the opposite.
  7158. */
  7159. #ifdef HAVE_WCHAR_H
  7160. typedef wchar_t cffi_wchar_t;
  7161. #else
  7162. typedef uint16_t cffi_wchar_t; /* random pick... */
  7163. #endif
  7164. static cffi_wchar_t _cffi_to_c_wchar_t(PyObject *init)
  7165. {
  7166. if (sizeof(cffi_wchar_t) == 2)
  7167. return (cffi_wchar_t)_convert_to_char16_t(init);
  7168. else
  7169. return (cffi_wchar_t)_convert_to_char32_t(init);
  7170. }
  7171. static PyObject *_cffi_from_c_wchar_t(cffi_wchar_t x) {
  7172. if (sizeof(cffi_wchar_t) == 2) {
  7173. cffi_char16_t input = x;
  7174. return _my_PyUnicode_FromChar16(&input, 1);
  7175. }
  7176. else {
  7177. cffi_char32_t input = x;
  7178. return _my_PyUnicode_FromChar32(&input, 1);
  7179. }
  7180. }
  7181. static int _cffi_to_c_wchar3216_t(PyObject *init)
  7182. {
  7183. if (sizeof(cffi_wchar_t) == 4)
  7184. return (int)_convert_to_char16_t(init);
  7185. else
  7186. return (int)_convert_to_char32_t(init);
  7187. }
  7188. static PyObject *_cffi_from_c_wchar3216_t(int x) {
  7189. if (sizeof(cffi_wchar_t) == 4) {
  7190. cffi_char16_t input = x;
  7191. return _my_PyUnicode_FromChar16(&input, 1);
  7192. }
  7193. else {
  7194. cffi_char32_t input = x;
  7195. return _my_PyUnicode_FromChar32(&input, 1);
  7196. }
  7197. }
  7198. struct _cffi_externpy_s; /* forward declaration */
  7199. static void cffi_call_python(struct _cffi_externpy_s *, char *args);
  7200. static void *cffi_exports[] = {
  7201. NULL,
  7202. _cffi_to_c_i8,
  7203. _cffi_to_c_u8,
  7204. _cffi_to_c_i16,
  7205. _cffi_to_c_u16,
  7206. _cffi_to_c_i32,
  7207. _cffi_to_c_u32,
  7208. _cffi_to_c_i64,
  7209. _cffi_to_c_u64,
  7210. _convert_to_char,
  7211. _cffi_from_c_pointer,
  7212. _cffi_to_c_pointer,
  7213. _cffi_get_struct_layout,
  7214. restore_errno,
  7215. save_errno,
  7216. _cffi_from_c_char,
  7217. convert_to_object,
  7218. convert_from_object,
  7219. convert_struct_to_owning_object,
  7220. _cffi_to_c_wchar_t,
  7221. _cffi_from_c_wchar_t,
  7222. _cffi_to_c_long_double,
  7223. _cffi_to_c__Bool,
  7224. _prepare_pointer_call_argument,
  7225. convert_array_from_object,
  7226. cffi_call_python,
  7227. _cffi_to_c_wchar3216_t,
  7228. _cffi_from_c_wchar3216_t,
  7229. };
  7230. static struct { const char *name; int value; } all_dlopen_flags[] = {
  7231. { "RTLD_LAZY", RTLD_LAZY },
  7232. { "RTLD_NOW", RTLD_NOW },
  7233. { "RTLD_GLOBAL", RTLD_GLOBAL },
  7234. #ifdef RTLD_LOCAL
  7235. { "RTLD_LOCAL", RTLD_LOCAL },
  7236. #else
  7237. { "RTLD_LOCAL", 0 },
  7238. #endif
  7239. #ifdef RTLD_NODELETE
  7240. { "RTLD_NODELETE", RTLD_NODELETE },
  7241. #endif
  7242. #ifdef RTLD_NOLOAD
  7243. { "RTLD_NOLOAD", RTLD_NOLOAD },
  7244. #endif
  7245. #ifdef RTLD_DEEPBIND
  7246. { "RTLD_DEEPBIND", RTLD_DEEPBIND },
  7247. #endif
  7248. { NULL, 0 }
  7249. };
  7250. /************************************************************/
  7251. #include "cffi1_module.c"
  7252. /************************************************************/
  7253. #if PY_MAJOR_VERSION >= 3
  7254. static struct PyModuleDef FFIBackendModuleDef = {
  7255. PyModuleDef_HEAD_INIT,
  7256. "_cffi_backend",
  7257. NULL,
  7258. -1,
  7259. FFIBackendMethods,
  7260. NULL, NULL, NULL, NULL
  7261. };
  7262. #define INITERROR return NULL
  7263. PyMODINIT_FUNC
  7264. PyInit__cffi_backend(void)
  7265. #else
  7266. #define INITERROR return
  7267. PyMODINIT_FUNC
  7268. init_cffi_backend(void)
  7269. #endif
  7270. {
  7271. PyObject *m, *v;
  7272. int i;
  7273. static char init_done = 0;
  7274. static PyTypeObject *all_types[] = {
  7275. &dl_type,
  7276. &CTypeDescr_Type,
  7277. &CField_Type,
  7278. &CData_Type,
  7279. &CDataOwning_Type,
  7280. &CDataOwningGC_Type,
  7281. &CDataFromBuf_Type,
  7282. &CDataGCP_Type,
  7283. &CDataIter_Type,
  7284. &MiniBuffer_Type,
  7285. &FFI_Type,
  7286. &Lib_Type,
  7287. &GlobSupport_Type,
  7288. NULL
  7289. };
  7290. v = PySys_GetObject("version");
  7291. if (v == NULL || !PyText_Check(v) ||
  7292. strncmp(PyText_AS_UTF8(v), PY_VERSION, 3) != 0) {
  7293. PyErr_Format(PyExc_ImportError,
  7294. "this module was compiled for Python %c%c%c",
  7295. PY_VERSION[0], PY_VERSION[1], PY_VERSION[2]);
  7296. INITERROR;
  7297. }
  7298. #if PY_MAJOR_VERSION >= 3
  7299. m = PyModule_Create(&FFIBackendModuleDef);
  7300. #else
  7301. m = Py_InitModule("_cffi_backend", FFIBackendMethods);
  7302. #endif
  7303. if (m == NULL)
  7304. INITERROR;
  7305. if (unique_cache == NULL) {
  7306. unique_cache = PyDict_New();
  7307. if (unique_cache == NULL)
  7308. INITERROR;
  7309. }
  7310. /* readify all types and add them to the module */
  7311. for (i = 0; all_types[i] != NULL; i++) {
  7312. PyTypeObject *tp = all_types[i];
  7313. PyObject *tpo = (PyObject *)tp;
  7314. if (strncmp(tp->tp_name, "_cffi_backend.", 14) != 0) {
  7315. PyErr_Format(PyExc_ImportError,
  7316. "'%s' is an ill-formed type name", tp->tp_name);
  7317. INITERROR;
  7318. }
  7319. if (PyType_Ready(tp) < 0)
  7320. INITERROR;
  7321. Py_INCREF(tpo);
  7322. if (PyModule_AddObject(m, tp->tp_name + 14, tpo) < 0)
  7323. INITERROR;
  7324. }
  7325. if (!init_done) {
  7326. v = PyText_FromString("_cffi_backend");
  7327. if (v == NULL || PyDict_SetItemString(CData_Type.tp_dict,
  7328. "__module__", v) < 0)
  7329. INITERROR;
  7330. v = PyText_FromString("<cdata>");
  7331. if (v == NULL || PyDict_SetItemString(CData_Type.tp_dict,
  7332. "__name__", v) < 0)
  7333. INITERROR;
  7334. init_done = 1;
  7335. }
  7336. /* this is for backward compatibility only */
  7337. v = PyCapsule_New((void *)cffi_exports, "cffi", NULL);
  7338. if (v == NULL || PyModule_AddObject(m, "_C_API", v) < 0)
  7339. INITERROR;
  7340. v = PyText_FromString(CFFI_VERSION);
  7341. if (v == NULL || PyModule_AddObject(m, "__version__", v) < 0)
  7342. INITERROR;
  7343. if (PyModule_AddIntConstant(m, "FFI_DEFAULT_ABI", FFI_DEFAULT_ABI) < 0 ||
  7344. #if defined(MS_WIN32) && !defined(_WIN64)
  7345. PyModule_AddIntConstant(m, "FFI_STDCALL", FFI_STDCALL) < 0 ||
  7346. #endif
  7347. PyModule_AddIntConstant(m, "FFI_CDECL", FFI_DEFAULT_ABI) < 0 ||
  7348. #ifdef MS_WIN32
  7349. # ifdef _WIN64
  7350. PyModule_AddIntConstant(m, "_WIN", 64) < 0 || /* win64 */
  7351. # else
  7352. PyModule_AddIntConstant(m, "_WIN", 32) < 0 || /* win32 */
  7353. # endif
  7354. #endif
  7355. 0)
  7356. INITERROR;
  7357. for (i = 0; all_dlopen_flags[i].name != NULL; i++) {
  7358. if (PyModule_AddIntConstant(m,
  7359. all_dlopen_flags[i].name,
  7360. all_dlopen_flags[i].value) < 0)
  7361. INITERROR;
  7362. }
  7363. init_cffi_tls();
  7364. if (PyErr_Occurred())
  7365. INITERROR;
  7366. init_cffi_tls_zombie();
  7367. if (PyErr_Occurred())
  7368. INITERROR;
  7369. if (init_ffi_lib(m) < 0)
  7370. INITERROR;
  7371. #if PY_MAJOR_VERSION >= 3
  7372. if (init_file_emulator() < 0)
  7373. INITERROR;
  7374. return m;
  7375. #endif
  7376. }