_cffi_backend.c 272 KB

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