as_restore.cpp 154 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2020 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. //
  24. // as_restore.cpp
  25. //
  26. // Functions for saving and restoring module bytecode
  27. // asCRestore was originally written by Dennis Bollyn, [email protected]
  28. #include "as_config.h"
  29. #include "as_restore.h"
  30. #include "as_bytecode.h"
  31. #include "as_scriptobject.h"
  32. #include "as_texts.h"
  33. #include "as_debug.h"
  34. BEGIN_AS_NAMESPACE
  35. // Macros for doing endianess agnostic bitmask serialization
  36. #define SAVE_TO_BIT(dst, val, bit) ((dst) |= ((val) << (bit)))
  37. #define LOAD_FROM_BIT(dst, val, bit) ((dst) = ((val) >> (bit)) & 1)
  38. asCReader::asCReader(asCModule* _module, asIBinaryStream* _stream, asCScriptEngine* _engine)
  39. : module(_module), stream(_stream), engine(_engine)
  40. {
  41. error = false;
  42. bytesRead = 0;
  43. }
  44. int asCReader::ReadData(void *data, asUINT size)
  45. {
  46. asASSERT(size == 1 || size == 2 || size == 4 || size == 8);
  47. int ret = 0;
  48. #if defined(AS_BIG_ENDIAN)
  49. for( asUINT n = 0; ret >= 0 && n < size; n++ )
  50. ret = stream->Read(((asBYTE*)data)+n, 1);
  51. #else
  52. for( int n = size-1; ret >= 0 && n >= 0; n-- )
  53. ret = stream->Read(((asBYTE*)data)+n, 1);
  54. #endif
  55. if (ret < 0)
  56. Error(TXT_UNEXPECTED_END_OF_FILE);
  57. bytesRead += size;
  58. return ret;
  59. }
  60. int asCReader::Read(bool *wasDebugInfoStripped)
  61. {
  62. TimeIt("asCReader::Read");
  63. // Before starting the load, make sure that
  64. // any existing resources have been freed
  65. module->InternalReset();
  66. // Call the inner method to do the actual loading
  67. int r = ReadInner();
  68. if( r < 0 )
  69. {
  70. // Something went wrong while loading the bytecode, so we need
  71. // to clean-up whatever has been created during the process.
  72. // Make sure none of the loaded functions attempt to release
  73. // references that have not yet been increased
  74. asUINT i;
  75. for( i = 0; i < module->m_scriptFunctions.GetLength(); i++ )
  76. if( !dontTranslate.MoveTo(0, module->m_scriptFunctions[i]) )
  77. if( module->m_scriptFunctions[i]->scriptData )
  78. module->m_scriptFunctions[i]->scriptData->byteCode.SetLength(0);
  79. asCSymbolTable<asCGlobalProperty>::iterator it = module->m_scriptGlobals.List();
  80. for( ; it; it++ )
  81. if( (*it)->GetInitFunc() )
  82. if( (*it)->GetInitFunc()->scriptData )
  83. (*it)->GetInitFunc()->scriptData->byteCode.SetLength(0);
  84. module->InternalReset();
  85. }
  86. else
  87. {
  88. // Init system functions properly
  89. engine->PrepareEngine();
  90. // Initialize the global variables (unless requested not to)
  91. if( engine->ep.initGlobalVarsAfterBuild )
  92. r = module->ResetGlobalVars(0);
  93. if( wasDebugInfoStripped )
  94. *wasDebugInfoStripped = noDebugInfo;
  95. }
  96. // Clean up the loaded string constants
  97. for (asUINT n = 0; n < usedStringConstants.GetLength(); n++)
  98. engine->stringFactory->ReleaseStringConstant(usedStringConstants[n]);
  99. usedStringConstants.SetLength(0);
  100. return r;
  101. }
  102. int asCReader::Error(const char *msg)
  103. {
  104. // Don't write if it has already been reported an error earlier
  105. if( !error )
  106. {
  107. asCString str;
  108. str.Format(msg, bytesRead);
  109. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  110. error = true;
  111. }
  112. return asERROR;
  113. }
  114. int asCReader::ReadInner()
  115. {
  116. TimeIt("asCReader::ReadInner");
  117. // This function will load each entity one by one from the stream.
  118. // If any error occurs, it will return to the caller who is
  119. // responsible for cleaning up the partially loaded entities.
  120. engine->deferValidationOfTemplateTypes = true;
  121. unsigned long i, count;
  122. asCScriptFunction* func;
  123. // Read the flag as 1 byte even on platforms with 4byte booleans
  124. noDebugInfo = ReadEncodedUInt() ? VALUE_OF_BOOLEAN_TRUE : 0;
  125. // Read enums
  126. count = ReadEncodedUInt();
  127. module->m_enumTypes.Allocate(count, false);
  128. for( i = 0; i < count && !error; i++ )
  129. {
  130. asCEnumType *et = asNEW(asCEnumType)(engine);
  131. if( et == 0 )
  132. {
  133. error = true;
  134. return asOUT_OF_MEMORY;
  135. }
  136. bool isExternal = false;
  137. ReadTypeDeclaration(et, 1, &isExternal);
  138. // If the type is shared then we should use the original if it exists
  139. bool sharedExists = false;
  140. if( et->IsShared() )
  141. {
  142. for( asUINT n = 0; n < engine->sharedScriptTypes.GetLength(); n++ )
  143. {
  144. asCTypeInfo *t = engine->sharedScriptTypes[n];
  145. if( t &&
  146. t->IsShared() &&
  147. t->name == et->name &&
  148. t->nameSpace == et->nameSpace &&
  149. (t->flags & asOBJ_ENUM) )
  150. {
  151. asDELETE(et, asCEnumType);
  152. et = CastToEnumType(t);
  153. sharedExists = true;
  154. break;
  155. }
  156. }
  157. }
  158. if (isExternal && !sharedExists)
  159. {
  160. asCString msg;
  161. msg.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, et->name.AddressOf());
  162. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, msg.AddressOf());
  163. asDELETE(et, asCEnumType);
  164. error = true;
  165. return asERROR;
  166. }
  167. if( sharedExists )
  168. {
  169. existingShared.Insert(et, true);
  170. et->AddRefInternal();
  171. }
  172. else
  173. {
  174. if( et->IsShared() )
  175. {
  176. engine->sharedScriptTypes.PushLast(et);
  177. et->AddRefInternal();
  178. }
  179. // Set this module as the owner
  180. et->module = module;
  181. }
  182. module->AddEnumType(et);
  183. if (isExternal)
  184. module->m_externalTypes.PushLast(et);
  185. ReadTypeDeclaration(et, 2);
  186. }
  187. if( error ) return asERROR;
  188. // classTypes[]
  189. // First restore the structure names, then the properties
  190. count = ReadEncodedUInt();
  191. module->m_classTypes.Allocate(count, false);
  192. for( i = 0; i < count && !error; ++i )
  193. {
  194. asCObjectType *ot = asNEW(asCObjectType)(engine);
  195. if( ot == 0 )
  196. {
  197. error = true;
  198. return asOUT_OF_MEMORY;
  199. }
  200. bool isExternal = false;
  201. ReadTypeDeclaration(ot, 1, &isExternal);
  202. // If the type is shared, then we should use the original if it exists
  203. bool sharedExists = false;
  204. if( ot->IsShared() )
  205. {
  206. for( asUINT n = 0; n < engine->sharedScriptTypes.GetLength(); n++ )
  207. {
  208. asCTypeInfo *ti = engine->sharedScriptTypes[n];
  209. asCObjectType *t = CastToObjectType(ti);
  210. if( t &&
  211. t->IsShared() &&
  212. t->name == ot->name &&
  213. t->nameSpace == ot->nameSpace &&
  214. t->IsInterface() == ot->IsInterface() )
  215. {
  216. asDELETE(ot, asCObjectType);
  217. ot = CastToObjectType(t);
  218. sharedExists = true;
  219. break;
  220. }
  221. }
  222. }
  223. if (isExternal && !sharedExists)
  224. {
  225. asCString msg;
  226. msg.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, ot->name.AddressOf());
  227. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, msg.AddressOf());
  228. asDELETE(ot, asCObjectType);
  229. error = true;
  230. return asERROR;
  231. }
  232. if( sharedExists )
  233. {
  234. existingShared.Insert(ot, true);
  235. ot->AddRefInternal();
  236. }
  237. else
  238. {
  239. if( ot->IsShared() )
  240. {
  241. engine->sharedScriptTypes.PushLast(ot);
  242. ot->AddRefInternal();
  243. }
  244. // Set this module as the owner
  245. ot->module = module;
  246. }
  247. module->AddClassType(ot);
  248. if (isExternal)
  249. module->m_externalTypes.PushLast(ot);
  250. }
  251. if( error ) return asERROR;
  252. // Read func defs
  253. count = ReadEncodedUInt();
  254. module->m_funcDefs.Allocate(count, false);
  255. for( i = 0; i < count && !error; i++ )
  256. {
  257. bool isNew, isExternal;
  258. asCScriptFunction *funcDef = ReadFunction(isNew, false, true, true, &isExternal);
  259. if(funcDef)
  260. {
  261. funcDef->module = module;
  262. asCFuncdefType *fdt = funcDef->funcdefType;
  263. fdt->module = module;
  264. module->AddFuncDef(fdt);
  265. engine->funcDefs.PushLast(fdt);
  266. // TODO: clean up: This is also done by the builder. It should probably be moved to a method in the module
  267. // Check if there is another identical funcdef from another module and if so reuse that instead
  268. if(funcDef->IsShared())
  269. {
  270. for( asUINT n = 0; n < engine->funcDefs.GetLength(); n++ )
  271. {
  272. asCFuncdefType *f2 = engine->funcDefs[n];
  273. if( f2 == 0 || fdt == f2 )
  274. continue;
  275. if( !f2->funcdef->IsShared() )
  276. continue;
  277. if( f2->name == fdt->name &&
  278. f2->nameSpace == fdt->nameSpace &&
  279. f2->parentClass == fdt->parentClass &&
  280. f2->funcdef->IsSignatureExceptNameEqual(funcDef) )
  281. {
  282. // Replace our funcdef for the existing one
  283. module->ReplaceFuncDef(fdt, f2);
  284. f2->AddRefInternal();
  285. if (isExternal)
  286. module->m_externalTypes.PushLast(f2);
  287. engine->funcDefs.RemoveValue(fdt);
  288. savedFunctions[savedFunctions.IndexOf(funcDef)] = f2->funcdef;
  289. if (fdt->parentClass)
  290. {
  291. // The real funcdef should already be in the object
  292. asASSERT(fdt->parentClass->childFuncDefs.IndexOf(f2) >= 0);
  293. fdt->parentClass = 0;
  294. }
  295. fdt->ReleaseInternal();
  296. funcDef = 0;
  297. break;
  298. }
  299. }
  300. }
  301. // Add the funcdef to the parentClass if this is a child funcdef
  302. if (funcDef && fdt->parentClass)
  303. fdt->parentClass->childFuncDefs.PushLast(fdt);
  304. // Check if an external shared funcdef was really found
  305. if (isExternal && funcDef)
  306. {
  307. asCString msg;
  308. msg.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, funcDef->name.AddressOf());
  309. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, msg.AddressOf());
  310. error = true;
  311. return asERROR;
  312. }
  313. }
  314. else
  315. Error(TXT_INVALID_BYTECODE_d);
  316. }
  317. // Read interface methods
  318. for( i = 0; i < module->m_classTypes.GetLength() && !error; i++ )
  319. {
  320. if( module->m_classTypes[i]->IsInterface() )
  321. ReadTypeDeclaration(module->m_classTypes[i], 2);
  322. }
  323. // Read class methods and behaviours
  324. for( i = 0; i < module->m_classTypes.GetLength() && !error; ++i )
  325. {
  326. if( !module->m_classTypes[i]->IsInterface() )
  327. ReadTypeDeclaration(module->m_classTypes[i], 2);
  328. }
  329. // Read class properties
  330. for( i = 0; i < module->m_classTypes.GetLength() && !error; ++i )
  331. {
  332. if( !module->m_classTypes[i]->IsInterface() )
  333. ReadTypeDeclaration(module->m_classTypes[i], 3);
  334. }
  335. if( error ) return asERROR;
  336. // Read typedefs
  337. count = ReadEncodedUInt();
  338. module->m_typeDefs.Allocate(count, false);
  339. for( i = 0; i < count && !error; i++ )
  340. {
  341. asCTypedefType *td = asNEW(asCTypedefType)(engine);
  342. if( td == 0 )
  343. {
  344. error = true;
  345. return asOUT_OF_MEMORY;
  346. }
  347. bool isExternal = false;
  348. ReadTypeDeclaration(td, 1, &isExternal);
  349. td->module = module;
  350. module->AddTypeDef(td);
  351. ReadTypeDeclaration(td, 2);
  352. }
  353. if( error ) return asERROR;
  354. // scriptGlobals[]
  355. count = ReadEncodedUInt();
  356. if( count && engine->ep.disallowGlobalVars )
  357. {
  358. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_GLOBAL_VARS_NOT_ALLOWED);
  359. Error(TXT_INVALID_BYTECODE_d);
  360. }
  361. module->m_scriptGlobals.Allocate(count, false);
  362. for( i = 0; i < count && !error; ++i )
  363. {
  364. ReadGlobalProperty();
  365. }
  366. // scriptFunctions[]
  367. count = ReadEncodedUInt();
  368. for( i = 0; i < count && !error; ++i )
  369. {
  370. size_t len = module->m_scriptFunctions.GetLength();
  371. bool isNew, isExternal;
  372. func = ReadFunction(isNew, true, true, true, &isExternal);
  373. if( func == 0 )
  374. {
  375. Error(TXT_INVALID_BYTECODE_d);
  376. break;
  377. }
  378. // Is the function shared and was it created now?
  379. if( func->IsShared() && len != module->m_scriptFunctions.GetLength() )
  380. {
  381. // If the function already existed in another module, then
  382. // we need to replace it with previously existing one
  383. for( asUINT n = 0; n < engine->scriptFunctions.GetLength() && !error; n++ )
  384. {
  385. asCScriptFunction *realFunc = engine->scriptFunctions[n];
  386. if( realFunc &&
  387. realFunc != func &&
  388. realFunc->IsShared() &&
  389. realFunc->nameSpace == func->nameSpace &&
  390. realFunc->IsSignatureEqual(func) )
  391. {
  392. // Replace the recently created function with the pre-existing function
  393. module->m_scriptFunctions[module->m_scriptFunctions.GetLength()-1] = realFunc;
  394. realFunc->AddRefInternal();
  395. savedFunctions[savedFunctions.GetLength()-1] = realFunc;
  396. engine->RemoveScriptFunction(func);
  397. // Insert the function in the dontTranslate array
  398. dontTranslate.Insert(realFunc, true);
  399. if (isExternal)
  400. module->m_externalFunctions.PushLast(realFunc);
  401. // Release the function, but make sure nothing else is released
  402. func->id = 0;
  403. if( func->scriptData )
  404. func->scriptData->byteCode.SetLength(0);
  405. func->ReleaseInternal();
  406. func = 0;
  407. break;
  408. }
  409. }
  410. }
  411. // Check if an external shared func was really found
  412. if (isExternal && func)
  413. {
  414. asCString msg;
  415. msg.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, func->name.AddressOf());
  416. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, msg.AddressOf());
  417. error = true;
  418. return asERROR;
  419. }
  420. }
  421. // globalFunctions[]
  422. count = ReadEncodedUInt();
  423. for( i = 0; i < count && !error; ++i )
  424. {
  425. bool isNew;
  426. func = ReadFunction(isNew, false, false);
  427. if( func )
  428. {
  429. // All the global functions were already loaded while loading the scriptFunctions, here
  430. // we're just re-reading the references to know which goes into the globalFunctions array
  431. asASSERT( !isNew );
  432. module->m_globalFunctions.Put(func);
  433. }
  434. else
  435. Error(TXT_INVALID_BYTECODE_d);
  436. }
  437. if( error ) return asERROR;
  438. // bindInformations[]
  439. count = ReadEncodedUInt();
  440. module->m_bindInformations.Allocate(count, false);
  441. for( i = 0; i < count && !error; ++i )
  442. {
  443. sBindInfo *info = asNEW(sBindInfo);
  444. if( info == 0 )
  445. {
  446. error = true;
  447. return asOUT_OF_MEMORY;
  448. }
  449. bool isNew;
  450. info->importedFunctionSignature = ReadFunction(isNew, false, false);
  451. if( info->importedFunctionSignature == 0 )
  452. {
  453. Error(TXT_INVALID_BYTECODE_d);
  454. break;
  455. }
  456. if( engine->freeImportedFunctionIdxs.GetLength() )
  457. {
  458. int id = engine->freeImportedFunctionIdxs.PopLast();
  459. info->importedFunctionSignature->id = int(FUNC_IMPORTED + id);
  460. engine->importedFunctions[id] = info;
  461. }
  462. else
  463. {
  464. info->importedFunctionSignature->id = int(FUNC_IMPORTED + engine->importedFunctions.GetLength());
  465. engine->importedFunctions.PushLast(info);
  466. }
  467. ReadString(&info->importFromModule);
  468. info->boundFunctionId = -1;
  469. module->m_bindInformations.PushLast(info);
  470. }
  471. if( error ) return asERROR;
  472. // usedTypes[]
  473. count = ReadEncodedUInt();
  474. usedTypes.Allocate(count, false);
  475. for( i = 0; i < count && !error; ++i )
  476. {
  477. asCTypeInfo *ti = ReadTypeInfo();
  478. usedTypes.PushLast(ti);
  479. }
  480. // usedTypeIds[]
  481. if( !error )
  482. ReadUsedTypeIds();
  483. // usedFunctions[]
  484. if( !error )
  485. ReadUsedFunctions();
  486. // usedGlobalProperties[]
  487. if( !error )
  488. ReadUsedGlobalProps();
  489. // usedStringConstants[]
  490. if( !error )
  491. ReadUsedStringConstants();
  492. // usedObjectProperties
  493. if( !error )
  494. ReadUsedObjectProps();
  495. // Validate the template types
  496. if( !error )
  497. {
  498. for( i = 0; i < usedTypes.GetLength() && !error; i++ )
  499. {
  500. asCObjectType *ot = CastToObjectType(usedTypes[i]);
  501. if( !ot ||
  502. !(ot->flags & asOBJ_TEMPLATE) ||
  503. !ot->beh.templateCallback )
  504. continue;
  505. bool dontGarbageCollect = false;
  506. asCScriptFunction *callback = engine->scriptFunctions[ot->beh.templateCallback];
  507. if( !engine->CallGlobalFunctionRetBool(ot, &dontGarbageCollect, callback->sysFuncIntf, callback) )
  508. {
  509. asCString sub = ot->templateSubTypes[0].Format(ot->nameSpace);
  510. for( asUINT n = 1; n < ot->templateSubTypes.GetLength(); n++ )
  511. {
  512. sub += ",";
  513. sub += ot->templateSubTypes[n].Format(ot->nameSpace);
  514. }
  515. asCString str;
  516. str.Format(TXT_INSTANCING_INVLD_TMPL_TYPE_s_s, ot->name.AddressOf(), sub.AddressOf());
  517. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  518. Error(TXT_INVALID_BYTECODE_d);
  519. }
  520. else
  521. {
  522. // If the callback said this template instance won't be garbage collected then remove the flag
  523. if( dontGarbageCollect )
  524. ot->flags &= ~asOBJ_GC;
  525. }
  526. }
  527. }
  528. engine->deferValidationOfTemplateTypes = false;
  529. if( error ) return asERROR;
  530. // Update the loaded bytecode to point to the correct types, property offsets,
  531. // function ids, etc. This is basically a linking stage.
  532. for( i = 0; i < module->m_scriptFunctions.GetLength() && !error; i++ )
  533. if( module->m_scriptFunctions[i]->funcType == asFUNC_SCRIPT )
  534. TranslateFunction(module->m_scriptFunctions[i]);
  535. asCSymbolTable<asCGlobalProperty>::iterator globIt = module->m_scriptGlobals.List();
  536. while( globIt && !error )
  537. {
  538. asCScriptFunction *initFunc = (*globIt)->GetInitFunc();
  539. if( initFunc )
  540. TranslateFunction(initFunc);
  541. globIt++;
  542. }
  543. if( error ) return asERROR;
  544. // Add references for all functions (except for the pre-existing shared code)
  545. for( i = 0; i < module->m_scriptFunctions.GetLength(); i++ )
  546. if( !dontTranslate.MoveTo(0, module->m_scriptFunctions[i]) )
  547. module->m_scriptFunctions[i]->AddReferences();
  548. globIt = module->m_scriptGlobals.List();
  549. while( globIt )
  550. {
  551. asCScriptFunction *initFunc = (*globIt)->GetInitFunc();
  552. if( initFunc )
  553. initFunc->AddReferences();
  554. globIt++;
  555. }
  556. return error ? asERROR : asSUCCESS;
  557. }
  558. void asCReader::ReadUsedStringConstants()
  559. {
  560. TimeIt("asCReader::ReadUsedStringConstants");
  561. asCString str;
  562. asUINT count;
  563. count = ReadEncodedUInt();
  564. if (count > 0 && engine->stringFactory == 0)
  565. {
  566. Error(TXT_STRINGS_NOT_RECOGNIZED);
  567. return;
  568. }
  569. usedStringConstants.Allocate(count, false);
  570. for( asUINT i = 0; i < count; ++i )
  571. {
  572. ReadString(&str);
  573. usedStringConstants.PushLast(const_cast<void*>(engine->stringFactory->GetStringConstant(str.AddressOf(), (asUINT)str.GetLength())));
  574. }
  575. }
  576. void asCReader::ReadUsedFunctions()
  577. {
  578. TimeIt("asCReader::ReadUsedFunctions");
  579. asUINT count;
  580. count = ReadEncodedUInt();
  581. usedFunctions.SetLength(count);
  582. if( usedFunctions.GetLength() != count )
  583. {
  584. // Out of memory
  585. error = true;
  586. return;
  587. }
  588. memset(usedFunctions.AddressOf(), 0, sizeof(asCScriptFunction *)*count);
  589. for( asUINT n = 0; n < usedFunctions.GetLength(); n++ )
  590. {
  591. char c;
  592. // Read the data to be able to uniquely identify the function
  593. // Is the function from the module or the application?
  594. ReadData(&c, 1);
  595. if( c == 'n' )
  596. {
  597. // Null function pointer
  598. usedFunctions[n] = 0;
  599. }
  600. else
  601. {
  602. asCScriptFunction func(engine, c == 'm' ? module : 0, asFUNC_DUMMY);
  603. asCObjectType *parentClass = 0;
  604. ReadFunctionSignature(&func, &parentClass);
  605. if( error )
  606. {
  607. func.funcType = asFUNC_DUMMY;
  608. return;
  609. }
  610. // Find the correct function
  611. if( c == 'm' )
  612. {
  613. if( func.funcType == asFUNC_IMPORTED )
  614. {
  615. for( asUINT i = 0; i < module->m_bindInformations.GetLength(); i++ )
  616. {
  617. asCScriptFunction *f = module->m_bindInformations[i]->importedFunctionSignature;
  618. if( func.objectType != f->objectType ||
  619. func.funcType != f->funcType ||
  620. func.nameSpace != f->nameSpace ||
  621. !func.IsSignatureEqual(f) )
  622. continue;
  623. usedFunctions[n] = f;
  624. break;
  625. }
  626. }
  627. else if( func.funcType == asFUNC_FUNCDEF )
  628. {
  629. const asCArray<asCFuncdefType *> &funcs = module->m_funcDefs;
  630. for( asUINT i = 0; i < funcs.GetLength(); i++ )
  631. {
  632. asCScriptFunction *f = funcs[i]->funcdef;
  633. if( f == 0 ||
  634. func.name != f->name ||
  635. !func.IsSignatureExceptNameAndObjectTypeEqual(f) ||
  636. funcs[i]->parentClass != parentClass )
  637. continue;
  638. asASSERT( f->objectType == 0 );
  639. usedFunctions[n] = f;
  640. break;
  641. }
  642. }
  643. else
  644. {
  645. // TODO: optimize: Global functions should be searched for in module->globalFunctions
  646. // TODO: optimize: funcdefs should be searched for in module->funcDefs
  647. // TODO: optimize: object methods should be searched for directly in the object type
  648. for( asUINT i = 0; i < module->m_scriptFunctions.GetLength(); i++ )
  649. {
  650. asCScriptFunction *f = module->m_scriptFunctions[i];
  651. if( func.objectType != f->objectType ||
  652. func.funcType != f->funcType ||
  653. func.nameSpace != f->nameSpace ||
  654. !func.IsSignatureEqual(f) )
  655. continue;
  656. usedFunctions[n] = f;
  657. break;
  658. }
  659. }
  660. }
  661. else if (c == 's')
  662. {
  663. // Look for shared entities in the engine, as they may not necessarily be part
  664. // of the scope of the module if they have been inhereted from other modules.
  665. if (func.funcType == asFUNC_FUNCDEF)
  666. {
  667. const asCArray<asCFuncdefType *> &funcs = engine->funcDefs;
  668. for (asUINT i = 0; i < funcs.GetLength(); i++)
  669. {
  670. asCScriptFunction *f = funcs[i]->funcdef;
  671. if (f == 0 ||
  672. func.name != f->name ||
  673. !func.IsSignatureExceptNameAndObjectTypeEqual(f) ||
  674. funcs[i]->parentClass != parentClass)
  675. continue;
  676. asASSERT(f->objectType == 0);
  677. usedFunctions[n] = f;
  678. break;
  679. }
  680. }
  681. else
  682. {
  683. for (asUINT i = 0; i < engine->scriptFunctions.GetLength(); i++)
  684. {
  685. asCScriptFunction *f = engine->scriptFunctions[i];
  686. if (f == 0 || !f->IsShared() ||
  687. func.objectType != f->objectType ||
  688. func.funcType != f->funcType ||
  689. func.nameSpace != f->nameSpace ||
  690. !func.IsSignatureEqual(f))
  691. continue;
  692. usedFunctions[n] = f;
  693. break;
  694. }
  695. }
  696. }
  697. else
  698. {
  699. asASSERT(c == 'a');
  700. if( func.funcType == asFUNC_FUNCDEF )
  701. {
  702. // This is a funcdef (registered or shared)
  703. const asCArray<asCFuncdefType *> &funcs = engine->funcDefs;
  704. for( asUINT i = 0; i < funcs.GetLength(); i++ )
  705. {
  706. asCScriptFunction *f = funcs[i]->funcdef;
  707. if( f == 0 || func.name != f->name || !func.IsSignatureExceptNameAndObjectTypeEqual(f) || funcs[i]->parentClass != parentClass )
  708. continue;
  709. asASSERT( f->objectType == 0 );
  710. usedFunctions[n] = f;
  711. break;
  712. }
  713. }
  714. else if( func.name[0] == '$' )
  715. {
  716. // This is a special function
  717. if( func.name == "$beh0" && func.objectType )
  718. {
  719. if (func.objectType->flags & asOBJ_TEMPLATE)
  720. {
  721. // Look for the matching constructor inside the factory stubs generated for the template instance
  722. // See asCCompiler::PerformFunctionCall
  723. for (asUINT i = 0; i < func.objectType->beh.constructors.GetLength(); i++)
  724. {
  725. asCScriptFunction *f = engine->scriptFunctions[func.objectType->beh.constructors[i]];
  726. // Find the id of the real constructor and not the generated stub
  727. asUINT id = 0;
  728. asDWORD *bc = f->scriptData->byteCode.AddressOf();
  729. while (bc)
  730. {
  731. if ((*(asBYTE*)bc) == asBC_CALLSYS)
  732. {
  733. id = asBC_INTARG(bc);
  734. break;
  735. }
  736. bc += asBCTypeSize[asBCInfo[*(asBYTE*)bc].type];
  737. }
  738. f = engine->scriptFunctions[id];
  739. if (f == 0 ||
  740. !func.IsSignatureExceptNameAndObjectTypeEqual(f))
  741. continue;
  742. usedFunctions[n] = f;
  743. break;
  744. }
  745. }
  746. if( usedFunctions[n] == 0 )
  747. {
  748. // This is a class constructor, so we can search directly in the object type's constructors
  749. for (asUINT i = 0; i < func.objectType->beh.constructors.GetLength(); i++)
  750. {
  751. asCScriptFunction *f = engine->scriptFunctions[func.objectType->beh.constructors[i]];
  752. if (f == 0 ||
  753. !func.IsSignatureExceptNameAndObjectTypeEqual(f))
  754. continue;
  755. usedFunctions[n] = f;
  756. break;
  757. }
  758. }
  759. }
  760. else if( func.name == "$fact" || func.name == "$beh3" )
  761. {
  762. // This is a factory (or stub), so look for the function in the return type's factories
  763. asCObjectType *objType = CastToObjectType(func.returnType.GetTypeInfo());
  764. if( objType )
  765. {
  766. for( asUINT i = 0; i < objType->beh.factories.GetLength(); i++ )
  767. {
  768. asCScriptFunction *f = engine->scriptFunctions[objType->beh.factories[i]];
  769. if( f == 0 ||
  770. !func.IsSignatureExceptNameAndObjectTypeEqual(f) )
  771. continue;
  772. usedFunctions[n] = f;
  773. break;
  774. }
  775. }
  776. }
  777. else if( func.name == "$list" )
  778. {
  779. // listFactory is used for both factory is global and returns a handle and constructor that is a method
  780. asCObjectType *objType = func.objectType ? func.objectType : CastToObjectType(func.returnType.GetTypeInfo());
  781. if( objType )
  782. {
  783. asCScriptFunction *f = engine->scriptFunctions[objType->beh.listFactory];
  784. if( f && func.IsSignatureExceptNameAndObjectTypeEqual(f) )
  785. usedFunctions[n] = f;
  786. }
  787. }
  788. else if( func.name == "$beh2" )
  789. {
  790. // This is a destructor, so check the object type's destructor
  791. asCObjectType *objType = func.objectType;
  792. if( objType )
  793. {
  794. asCScriptFunction *f = engine->scriptFunctions[objType->beh.destruct];
  795. if( f && func.IsSignatureExceptNameAndObjectTypeEqual(f) )
  796. usedFunctions[n] = f;
  797. }
  798. }
  799. else if( func.name == "$dlgte" )
  800. {
  801. // This is the delegate factory
  802. asCScriptFunction *f = engine->registeredGlobalFuncs.GetFirst(engine->nameSpaces[0], DELEGATE_FACTORY);
  803. asASSERT( f && func.IsSignatureEqual(f) );
  804. usedFunctions[n] = f;
  805. }
  806. else
  807. {
  808. // Must match one of the above cases
  809. asASSERT(false);
  810. }
  811. }
  812. else if( func.objectType == 0 )
  813. {
  814. // This is a global function
  815. const asCArray<asUINT> &funcs = engine->registeredGlobalFuncs.GetIndexes(func.nameSpace, func.name);
  816. for( asUINT i = 0; i < funcs.GetLength(); i++ )
  817. {
  818. asCScriptFunction *f = engine->registeredGlobalFuncs.Get(funcs[i]);
  819. if( f == 0 ||
  820. !func.IsSignatureExceptNameAndObjectTypeEqual(f) )
  821. continue;
  822. usedFunctions[n] = f;
  823. break;
  824. }
  825. }
  826. else if( func.objectType )
  827. {
  828. // It is a class member, so we can search directly in the object type's members
  829. // TODO: virtual function is different that implemented method
  830. for( asUINT i = 0; i < func.objectType->methods.GetLength(); i++ )
  831. {
  832. asCScriptFunction *f = engine->scriptFunctions[func.objectType->methods[i]];
  833. if( f == 0 ||
  834. !func.IsSignatureEqual(f) )
  835. continue;
  836. usedFunctions[n] = f;
  837. break;
  838. }
  839. }
  840. if( usedFunctions[n] == 0 )
  841. {
  842. // TODO: clean up: This part of the code should never happen. All functions should
  843. // be found in the above logic. The only valid reason to come here
  844. // is if the bytecode is wrong and the function doesn't exist anyway.
  845. // This loop is kept temporarily until we can be certain all scenarios
  846. // are covered.
  847. for( asUINT i = 0; i < engine->scriptFunctions.GetLength(); i++ )
  848. {
  849. asCScriptFunction *f = engine->scriptFunctions[i];
  850. if( f == 0 ||
  851. func.objectType != f->objectType ||
  852. func.nameSpace != f->nameSpace ||
  853. !func.IsSignatureEqual(f) )
  854. continue;
  855. usedFunctions[n] = f;
  856. break;
  857. }
  858. // No function is expected to be found
  859. asASSERT(usedFunctions[n] == 0);
  860. }
  861. }
  862. // Set the type to dummy so it won't try to release the id
  863. func.funcType = asFUNC_DUMMY;
  864. if( usedFunctions[n] == 0 )
  865. {
  866. Error(TXT_INVALID_BYTECODE_d);
  867. return;
  868. }
  869. }
  870. }
  871. }
  872. void asCReader::ReadFunctionSignature(asCScriptFunction *func, asCObjectType **parentClass)
  873. {
  874. asUINT i, count;
  875. asCDataType dt;
  876. int num;
  877. ReadString(&func->name);
  878. if( func->name == DELEGATE_FACTORY )
  879. {
  880. // It's not necessary to read anymore, everything is known
  881. asCScriptFunction *f = engine->registeredGlobalFuncs.GetFirst(engine->nameSpaces[0], DELEGATE_FACTORY);
  882. asASSERT( f );
  883. func->returnType = f->returnType;
  884. func->parameterTypes = f->parameterTypes;
  885. func->inOutFlags = f->inOutFlags;
  886. func->funcType = f->funcType;
  887. func->defaultArgs = f->defaultArgs;
  888. func->nameSpace = f->nameSpace;
  889. return;
  890. }
  891. ReadDataType(&func->returnType);
  892. count = ReadEncodedUInt();
  893. if( count > 256 )
  894. {
  895. // Too many arguments, must be something wrong in the file
  896. Error(TXT_INVALID_BYTECODE_d);
  897. return;
  898. }
  899. func->parameterTypes.Allocate(count, false);
  900. for( i = 0; i < count; ++i )
  901. {
  902. ReadDataType(&dt);
  903. func->parameterTypes.PushLast(dt);
  904. }
  905. func->inOutFlags.SetLength(func->parameterTypes.GetLength());
  906. if( func->inOutFlags.GetLength() != func->parameterTypes.GetLength() )
  907. {
  908. // Out of memory
  909. error = true;
  910. return;
  911. }
  912. memset(func->inOutFlags.AddressOf(), 0, sizeof(asETypeModifiers)*func->inOutFlags.GetLength());
  913. if (func->parameterTypes.GetLength() > 0)
  914. {
  915. count = ReadEncodedUInt();
  916. if (count > func->parameterTypes.GetLength())
  917. {
  918. // Cannot be more than the number of arguments
  919. Error(TXT_INVALID_BYTECODE_d);
  920. return;
  921. }
  922. for (i = 0; i < count; ++i)
  923. {
  924. num = ReadEncodedUInt();
  925. func->inOutFlags[i] = static_cast<asETypeModifiers>(num);
  926. }
  927. }
  928. func->funcType = (asEFuncType)ReadEncodedUInt();
  929. // Read the default args, from last to first
  930. if (func->parameterTypes.GetLength() > 0)
  931. {
  932. count = ReadEncodedUInt();
  933. if (count > func->parameterTypes.GetLength())
  934. {
  935. // Cannot be more than the number of arguments
  936. Error(TXT_INVALID_BYTECODE_d);
  937. return;
  938. }
  939. if (count)
  940. {
  941. func->defaultArgs.SetLength(func->parameterTypes.GetLength());
  942. if (func->defaultArgs.GetLength() != func->parameterTypes.GetLength())
  943. {
  944. // Out of memory
  945. error = true;
  946. return;
  947. }
  948. memset(func->defaultArgs.AddressOf(), 0, sizeof(asCString*)*func->defaultArgs.GetLength());
  949. for (i = 0; i < count; i++)
  950. {
  951. asCString *str = asNEW(asCString);
  952. if (str == 0)
  953. {
  954. // Out of memory
  955. error = true;
  956. return;
  957. }
  958. func->defaultArgs[func->defaultArgs.GetLength() - 1 - i] = str;
  959. ReadString(str);
  960. }
  961. }
  962. }
  963. func->objectType = CastToObjectType(ReadTypeInfo());
  964. if( func->objectType )
  965. {
  966. func->objectType->AddRefInternal();
  967. asBYTE b;
  968. ReadData(&b, 1);
  969. func->SetReadOnly((b & 1) ? true : false);
  970. func->SetPrivate((b & 2) ? true : false);
  971. func->SetProtected((b & 4) ? true : false);
  972. func->nameSpace = func->objectType->nameSpace;
  973. }
  974. else
  975. {
  976. if (func->funcType == asFUNC_FUNCDEF)
  977. {
  978. asBYTE b;
  979. ReadData(&b, 1);
  980. if (b == 'n')
  981. {
  982. asCString ns;
  983. ReadString(&ns);
  984. func->nameSpace = engine->AddNameSpace(ns.AddressOf());
  985. }
  986. else if (b == 'o')
  987. {
  988. func->nameSpace = 0;
  989. if (parentClass)
  990. *parentClass = CastToObjectType(ReadTypeInfo());
  991. else
  992. error = true;
  993. }
  994. else
  995. error = true;
  996. }
  997. else
  998. {
  999. asCString ns;
  1000. ReadString(&ns);
  1001. func->nameSpace = engine->AddNameSpace(ns.AddressOf());
  1002. }
  1003. }
  1004. }
  1005. asCScriptFunction *asCReader::ReadFunction(bool &isNew, bool addToModule, bool addToEngine, bool addToGC, bool *isExternal)
  1006. {
  1007. isNew = false;
  1008. if (isExternal) *isExternal = false;
  1009. if( error ) return 0;
  1010. char c;
  1011. ReadData(&c, 1);
  1012. if( c == '\0' )
  1013. {
  1014. // There is no function, so return a null pointer
  1015. return 0;
  1016. }
  1017. if( c == 'r' )
  1018. {
  1019. // This is a reference to a previously saved function
  1020. asUINT index = ReadEncodedUInt();
  1021. if( index < savedFunctions.GetLength() )
  1022. return savedFunctions[index];
  1023. else
  1024. {
  1025. Error(TXT_INVALID_BYTECODE_d);
  1026. return 0;
  1027. }
  1028. }
  1029. // Load the new function
  1030. isNew = true;
  1031. asCScriptFunction *func = asNEW(asCScriptFunction)(engine,0,asFUNC_DUMMY);
  1032. if( func == 0 )
  1033. {
  1034. // Out of memory
  1035. error = true;
  1036. return 0;
  1037. }
  1038. savedFunctions.PushLast(func);
  1039. int i, count;
  1040. asCDataType dt;
  1041. int num;
  1042. asCObjectType *parentClass = 0;
  1043. ReadFunctionSignature(func, &parentClass);
  1044. if( error )
  1045. {
  1046. func->DestroyHalfCreated();
  1047. return 0;
  1048. }
  1049. if( func->funcType == asFUNC_SCRIPT )
  1050. {
  1051. // Skip this for external shared entities
  1052. if (module->m_externalTypes.IndexOf(func->objectType) >= 0)
  1053. {
  1054. // Replace with the real function from the existing entity
  1055. isNew = false;
  1056. asCObjectType *ot = func->objectType;
  1057. for (asUINT n = 0; n < ot->methods.GetLength(); n++)
  1058. {
  1059. asCScriptFunction *func2 = engine->scriptFunctions[ot->methods[n]];
  1060. if (func2->funcType == asFUNC_VIRTUAL)
  1061. func2 = ot->virtualFunctionTable[func2->vfTableIdx];
  1062. if (func->IsSignatureEqual(func2))
  1063. {
  1064. func->DestroyHalfCreated();
  1065. // as this is an existing function it shouldn't be translated as if just loaded
  1066. dontTranslate.Insert(func2, true);
  1067. // update the saved functions for future references
  1068. savedFunctions[savedFunctions.GetLength() - 1] = func2;
  1069. // As it is an existing function it shouldn't be added to the module or the engine
  1070. return func2;
  1071. }
  1072. }
  1073. }
  1074. else
  1075. {
  1076. char bits;
  1077. ReadData(&bits, 1);
  1078. func->SetShared((bits & 1) ? true : false);
  1079. func->SetExplicit((bits & 32) ? true : false);
  1080. func->dontCleanUpOnException = (bits & 2) ? true : false;
  1081. if ((bits & 4) && isExternal)
  1082. *isExternal = true;
  1083. // for external shared functions the rest is not needed
  1084. if (!(bits & 4))
  1085. {
  1086. func->AllocateScriptFunctionData();
  1087. if (func->scriptData == 0)
  1088. {
  1089. // Out of memory
  1090. error = true;
  1091. func->DestroyHalfCreated();
  1092. return 0;
  1093. }
  1094. if (addToGC && !addToModule)
  1095. engine->gc.AddScriptObjectToGC(func, &engine->functionBehaviours);
  1096. ReadByteCode(func);
  1097. func->scriptData->variableSpace = ReadEncodedUInt();
  1098. func->scriptData->objVariablesOnHeap = 0;
  1099. if (bits & 8)
  1100. {
  1101. count = ReadEncodedUInt();
  1102. func->scriptData->objVariablePos.Allocate(count, false);
  1103. func->scriptData->objVariableTypes.Allocate(count, false);
  1104. for (i = 0; i < count; ++i)
  1105. {
  1106. func->scriptData->objVariableTypes.PushLast(ReadTypeInfo());
  1107. num = ReadEncodedUInt();
  1108. func->scriptData->objVariablePos.PushLast(num);
  1109. if (error)
  1110. {
  1111. // No need to continue (the error has already been reported before)
  1112. func->DestroyHalfCreated();
  1113. return 0;
  1114. }
  1115. }
  1116. if (count > 0)
  1117. func->scriptData->objVariablesOnHeap = ReadEncodedUInt();
  1118. int length = ReadEncodedUInt();
  1119. func->scriptData->objVariableInfo.SetLength(length);
  1120. for (i = 0; i < length; ++i)
  1121. {
  1122. func->scriptData->objVariableInfo[i].programPos = ReadEncodedUInt();
  1123. func->scriptData->objVariableInfo[i].variableOffset = ReadEncodedUInt();
  1124. asEObjVarInfoOption option = (asEObjVarInfoOption)ReadEncodedUInt();
  1125. func->scriptData->objVariableInfo[i].option = option;
  1126. if (option != asOBJ_INIT &&
  1127. option != asOBJ_UNINIT &&
  1128. option != asBLOCK_BEGIN &&
  1129. option != asBLOCK_END &&
  1130. option != asOBJ_VARDECL)
  1131. {
  1132. error = true;
  1133. func->DestroyHalfCreated();
  1134. return 0;
  1135. }
  1136. }
  1137. }
  1138. if (bits & 16)
  1139. {
  1140. // Read info on try/catch blocks
  1141. int length = ReadEncodedUInt();
  1142. func->scriptData->tryCatchInfo.SetLength(length);
  1143. for (i = 0; i < length; ++i)
  1144. {
  1145. // The program position must be adjusted to be in number of instructions
  1146. func->scriptData->tryCatchInfo[i].tryPos = ReadEncodedUInt();
  1147. func->scriptData->tryCatchInfo[i].catchPos = ReadEncodedUInt();
  1148. }
  1149. }
  1150. if (!noDebugInfo)
  1151. {
  1152. int length = ReadEncodedUInt();
  1153. func->scriptData->lineNumbers.SetLength(length);
  1154. if (int(func->scriptData->lineNumbers.GetLength()) != length)
  1155. {
  1156. // Out of memory
  1157. error = true;
  1158. func->DestroyHalfCreated();
  1159. return 0;
  1160. }
  1161. for (i = 0; i < length; ++i)
  1162. func->scriptData->lineNumbers[i] = ReadEncodedUInt();
  1163. // Read the array of script sections
  1164. length = ReadEncodedUInt();
  1165. func->scriptData->sectionIdxs.SetLength(length);
  1166. if (int(func->scriptData->sectionIdxs.GetLength()) != length)
  1167. {
  1168. // Out of memory
  1169. error = true;
  1170. func->DestroyHalfCreated();
  1171. return 0;
  1172. }
  1173. for (i = 0; i < length; ++i)
  1174. {
  1175. if ((i & 1) == 0)
  1176. func->scriptData->sectionIdxs[i] = ReadEncodedUInt();
  1177. else
  1178. {
  1179. asCString str;
  1180. ReadString(&str);
  1181. func->scriptData->sectionIdxs[i] = engine->GetScriptSectionNameIndex(str.AddressOf());
  1182. }
  1183. }
  1184. }
  1185. // Read the variable information
  1186. if (!noDebugInfo)
  1187. {
  1188. int length = ReadEncodedUInt();
  1189. func->scriptData->variables.Allocate(length, false);
  1190. for (i = 0; i < length; i++)
  1191. {
  1192. asSScriptVariable *var = asNEW(asSScriptVariable);
  1193. if (var == 0)
  1194. {
  1195. // Out of memory
  1196. error = true;
  1197. func->DestroyHalfCreated();
  1198. return 0;
  1199. }
  1200. func->scriptData->variables.PushLast(var);
  1201. var->declaredAtProgramPos = ReadEncodedUInt();
  1202. var->stackOffset = ReadEncodedUInt();
  1203. ReadString(&var->name);
  1204. ReadDataType(&var->type);
  1205. if (error)
  1206. {
  1207. // No need to continue (the error has already been reported before)
  1208. func->DestroyHalfCreated();
  1209. return 0;
  1210. }
  1211. }
  1212. }
  1213. // Read script section name
  1214. if (!noDebugInfo)
  1215. {
  1216. asCString name;
  1217. ReadString(&name);
  1218. func->scriptData->scriptSectionIdx = engine->GetScriptSectionNameIndex(name.AddressOf());
  1219. func->scriptData->declaredAt = ReadEncodedUInt();
  1220. }
  1221. // Read parameter names
  1222. if (!noDebugInfo)
  1223. {
  1224. asUINT countParam = asUINT(ReadEncodedUInt64());
  1225. if (countParam > func->parameterTypes.GetLength())
  1226. {
  1227. error = true;
  1228. func->DestroyHalfCreated();
  1229. return 0;
  1230. }
  1231. func->parameterNames.SetLength(countParam);
  1232. for (asUINT n = 0; n < countParam; n++)
  1233. ReadString(&func->parameterNames[n]);
  1234. }
  1235. }
  1236. }
  1237. }
  1238. else if( func->funcType == asFUNC_VIRTUAL || func->funcType == asFUNC_INTERFACE )
  1239. {
  1240. func->vfTableIdx = ReadEncodedUInt();
  1241. }
  1242. else if( func->funcType == asFUNC_FUNCDEF )
  1243. {
  1244. asBYTE bits;
  1245. ReadData(&bits, 1);
  1246. if( bits & 1 )
  1247. func->SetShared(true);
  1248. if ((bits & 2) && isExternal)
  1249. *isExternal = true;
  1250. // The asCFuncdefType constructor adds itself to the func->funcdefType member
  1251. asCFuncdefType *fdt = asNEW(asCFuncdefType)(engine, func);
  1252. fdt->parentClass = parentClass;
  1253. }
  1254. // Methods loaded for shared objects, owned by other modules should not be created as new functions
  1255. if( func->objectType && func->objectType->module != module )
  1256. {
  1257. // Return the real function from the object
  1258. asCScriptFunction *realFunc = 0;
  1259. bool found = false;
  1260. if( func->funcType == asFUNC_SCRIPT )
  1261. {
  1262. realFunc = engine->scriptFunctions[func->objectType->beh.destruct];
  1263. if( realFunc && realFunc->funcType != asFUNC_VIRTUAL && func->IsSignatureEqual(realFunc) )
  1264. {
  1265. found = true;
  1266. }
  1267. for( asUINT n = 0; !found && n < func->objectType->beh.constructors.GetLength(); n++ )
  1268. {
  1269. realFunc = engine->scriptFunctions[func->objectType->beh.constructors[n]];
  1270. if( realFunc && realFunc->funcType != asFUNC_VIRTUAL && func->IsSignatureEqual(realFunc) )
  1271. {
  1272. found = true;
  1273. break;
  1274. }
  1275. }
  1276. for( asUINT n = 0; !found && n < func->objectType->beh.factories.GetLength(); n++ )
  1277. {
  1278. realFunc = engine->scriptFunctions[func->objectType->beh.factories[n]];
  1279. if( realFunc && realFunc->funcType != asFUNC_VIRTUAL && func->IsSignatureEqual(realFunc) )
  1280. {
  1281. found = true;
  1282. break;
  1283. }
  1284. }
  1285. for( asUINT n = 0; !found && n < func->objectType->methods.GetLength(); n++ )
  1286. {
  1287. realFunc = engine->scriptFunctions[func->objectType->methods[n]];
  1288. if( realFunc && realFunc->funcType == func->funcType && func->IsSignatureEqual(realFunc) )
  1289. {
  1290. found = true;
  1291. break;
  1292. }
  1293. }
  1294. for( asUINT n = 0; !found && n < func->objectType->virtualFunctionTable.GetLength(); n++ )
  1295. {
  1296. realFunc = func->objectType->virtualFunctionTable[n];
  1297. if( realFunc && realFunc->funcType == func->funcType && func->IsSignatureEqual(realFunc) )
  1298. {
  1299. found = true;
  1300. break;
  1301. }
  1302. }
  1303. }
  1304. else if( func->funcType == asFUNC_VIRTUAL || func->funcType == asFUNC_INTERFACE )
  1305. {
  1306. // If the loaded function is a virtual function, then look for the identical virtual function in the methods array
  1307. for( asUINT n = 0; n < func->objectType->methods.GetLength(); n++ )
  1308. {
  1309. realFunc = engine->scriptFunctions[func->objectType->methods[n]];
  1310. if( realFunc && realFunc->funcType == func->funcType && func->IsSignatureEqual(realFunc) )
  1311. {
  1312. asASSERT( func->vfTableIdx == realFunc->vfTableIdx );
  1313. found = true;
  1314. break;
  1315. }
  1316. }
  1317. }
  1318. if( found )
  1319. {
  1320. // as this is an existing function it shouldn't be translated as if just loaded
  1321. dontTranslate.Insert(realFunc, true);
  1322. // update the saved functions for future references
  1323. savedFunctions[savedFunctions.GetLength() - 1] = realFunc;
  1324. if( realFunc->funcType == asFUNC_VIRTUAL && addToModule )
  1325. {
  1326. // Virtual methods must be added to the module's script functions array,
  1327. // even if they are not owned by the module
  1328. module->m_scriptFunctions.PushLast(realFunc);
  1329. realFunc->AddRefInternal();
  1330. }
  1331. }
  1332. else
  1333. {
  1334. asCString str;
  1335. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, func->objectType->GetName());
  1336. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1337. Error(TXT_INVALID_BYTECODE_d);
  1338. savedFunctions.PopLast();
  1339. realFunc = 0;
  1340. }
  1341. // Destroy the newly created function instance since it has been replaced by an existing function
  1342. isNew = false;
  1343. func->DestroyHalfCreated();
  1344. // As it is an existing function it shouldn't be added to the module or the engine
  1345. return realFunc;
  1346. }
  1347. if( addToModule )
  1348. {
  1349. // The refCount is already 1
  1350. module->m_scriptFunctions.PushLast(func);
  1351. func->module = module;
  1352. }
  1353. if( addToEngine )
  1354. {
  1355. func->id = engine->GetNextScriptFunctionId();
  1356. engine->AddScriptFunction(func);
  1357. }
  1358. if( func->objectType )
  1359. func->ComputeSignatureId();
  1360. return func;
  1361. }
  1362. void asCReader::ReadTypeDeclaration(asCTypeInfo *type, int phase, bool *isExternal)
  1363. {
  1364. if( phase == 1 )
  1365. {
  1366. asASSERT(isExternal);
  1367. if (isExternal)
  1368. *isExternal = false;
  1369. // Read the initial attributes
  1370. ReadString(&type->name);
  1371. ReadData(&type->flags, 4);
  1372. type->size = ReadEncodedUInt();
  1373. asCString ns;
  1374. ReadString(&ns);
  1375. type->nameSpace = engine->AddNameSpace(ns.AddressOf());
  1376. // Verify that the flags match the asCTypeInfo
  1377. if ((CastToEnumType(type) && !(type->flags & asOBJ_ENUM)) ||
  1378. (CastToFuncdefType(type) && !(type->flags & asOBJ_FUNCDEF)) ||
  1379. (CastToObjectType(type) && !(type->flags & (asOBJ_REF | asOBJ_VALUE))))
  1380. {
  1381. error = true;
  1382. return;
  1383. }
  1384. // Reset the size of script classes, since it will be recalculated as properties are added
  1385. if( (type->flags & asOBJ_SCRIPT_OBJECT) && type->size != 0 )
  1386. type->size = sizeof(asCScriptObject);
  1387. asCObjectType *ot = CastToObjectType(type);
  1388. if (ot)
  1389. {
  1390. // Use the default script class behaviours
  1391. ot->beh = engine->scriptTypeBehaviours.beh;
  1392. ot->beh.construct = 0;
  1393. ot->beh.factory = 0;
  1394. ot->beh.constructors.PopLast(); // These will be read from the file
  1395. ot->beh.factories.PopLast(); // These will be read from the file
  1396. engine->scriptFunctions[ot->beh.addref]->AddRefInternal();
  1397. engine->scriptFunctions[ot->beh.release]->AddRefInternal();
  1398. engine->scriptFunctions[ot->beh.gcEnumReferences]->AddRefInternal();
  1399. engine->scriptFunctions[ot->beh.gcGetFlag]->AddRefInternal();
  1400. engine->scriptFunctions[ot->beh.gcGetRefCount]->AddRefInternal();
  1401. engine->scriptFunctions[ot->beh.gcReleaseAllReferences]->AddRefInternal();
  1402. engine->scriptFunctions[ot->beh.gcSetFlag]->AddRefInternal();
  1403. engine->scriptFunctions[ot->beh.copy]->AddRefInternal();
  1404. // TODO: weak: Should not do this if the class has been declared with 'noweak'
  1405. engine->scriptFunctions[ot->beh.getWeakRefFlag]->AddRefInternal();
  1406. }
  1407. // external shared flag
  1408. if (type->flags & asOBJ_SHARED)
  1409. {
  1410. char c;
  1411. ReadData(&c, 1);
  1412. if (c == 'e')
  1413. *isExternal = true;
  1414. else if (c != ' ')
  1415. {
  1416. error = true;
  1417. return;
  1418. }
  1419. }
  1420. }
  1421. else if( phase == 2 )
  1422. {
  1423. // external shared types doesn't store this
  1424. if ((type->flags & asOBJ_SHARED) && module->m_externalTypes.IndexOf(type) >= 0)
  1425. return;
  1426. if( type->flags & asOBJ_ENUM )
  1427. {
  1428. asCEnumType *t = CastToEnumType(type);
  1429. int count = ReadEncodedUInt();
  1430. bool sharedExists = existingShared.MoveTo(0, type);
  1431. if( !sharedExists )
  1432. {
  1433. t->enumValues.Allocate(count, false);
  1434. for( int n = 0; n < count; n++ )
  1435. {
  1436. asSEnumValue *e = asNEW(asSEnumValue);
  1437. if( e == 0 )
  1438. {
  1439. // Out of memory
  1440. error = true;
  1441. return;
  1442. }
  1443. ReadString(&e->name);
  1444. ReadData(&e->value, 4); // TODO: Should be encoded
  1445. t->enumValues.PushLast(e);
  1446. }
  1447. }
  1448. else
  1449. {
  1450. // Verify that the enum values exists in the original
  1451. asCString name;
  1452. int value;
  1453. for( int n = 0; n < count; n++ )
  1454. {
  1455. ReadString(&name);
  1456. ReadData(&value, 4); // TODO: Should be encoded
  1457. bool found = false;
  1458. for( asUINT e = 0; e < t->enumValues.GetLength(); e++ )
  1459. {
  1460. if( t->enumValues[e]->name == name &&
  1461. t->enumValues[e]->value == value )
  1462. {
  1463. found = true;
  1464. break;
  1465. }
  1466. }
  1467. if( !found )
  1468. {
  1469. asCString str;
  1470. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1471. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1472. Error(TXT_INVALID_BYTECODE_d);
  1473. }
  1474. }
  1475. }
  1476. }
  1477. else if( type->flags & asOBJ_TYPEDEF )
  1478. {
  1479. asCTypedefType *td = CastToTypedefType(type);
  1480. asASSERT(td);
  1481. eTokenType t = (eTokenType)ReadEncodedUInt();
  1482. td->aliasForType = asCDataType::CreatePrimitive(t, false);
  1483. }
  1484. else
  1485. {
  1486. asCObjectType *ot = CastToObjectType(type);
  1487. asASSERT(ot);
  1488. // If the type is shared and pre-existing, we should just
  1489. // validate that the loaded methods match the original
  1490. bool sharedExists = existingShared.MoveTo(0, type);
  1491. if( sharedExists )
  1492. {
  1493. asCObjectType *dt = CastToObjectType(ReadTypeInfo());
  1494. if( ot->derivedFrom != dt )
  1495. {
  1496. asCString str;
  1497. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1498. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1499. Error(TXT_INVALID_BYTECODE_d);
  1500. }
  1501. }
  1502. else
  1503. {
  1504. ot->derivedFrom = CastToObjectType(ReadTypeInfo());
  1505. if( ot->derivedFrom )
  1506. ot->derivedFrom->AddRefInternal();
  1507. }
  1508. // interfaces[] / interfaceVFTOffsets[]
  1509. int size = ReadEncodedUInt();
  1510. if( sharedExists )
  1511. {
  1512. for( int n = 0; n < size; n++ )
  1513. {
  1514. asCObjectType *intf = CastToObjectType(ReadTypeInfo());
  1515. if (!ot->IsInterface())
  1516. ReadEncodedUInt();
  1517. if( !type->Implements(intf) )
  1518. {
  1519. asCString str;
  1520. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1521. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1522. Error(TXT_INVALID_BYTECODE_d);
  1523. }
  1524. }
  1525. }
  1526. else
  1527. {
  1528. ot->interfaces.Allocate(size, false);
  1529. if( !ot->IsInterface() )
  1530. ot->interfaceVFTOffsets.Allocate(size, false);
  1531. for( int n = 0; n < size; n++ )
  1532. {
  1533. asCObjectType *intf = CastToObjectType(ReadTypeInfo());
  1534. ot->interfaces.PushLast(intf);
  1535. if (!ot->IsInterface())
  1536. {
  1537. asUINT offset = ReadEncodedUInt();
  1538. ot->interfaceVFTOffsets.PushLast(offset);
  1539. }
  1540. }
  1541. }
  1542. // behaviours
  1543. if( !ot->IsInterface() && type->flags != asOBJ_TYPEDEF && type->flags != asOBJ_ENUM )
  1544. {
  1545. bool isNew;
  1546. asCScriptFunction *func = ReadFunction(isNew, !sharedExists, !sharedExists, !sharedExists);
  1547. if( sharedExists )
  1548. {
  1549. // Find the real function in the object, and update the savedFunctions array
  1550. asCScriptFunction *realFunc = engine->GetScriptFunction(ot->beh.destruct);
  1551. if( (realFunc == 0 && func == 0) || realFunc->IsSignatureEqual(func) )
  1552. {
  1553. // If the function is not the last, then the substitution has already occurred before
  1554. if( func && savedFunctions[savedFunctions.GetLength()-1] == func )
  1555. savedFunctions[savedFunctions.GetLength()-1] = realFunc;
  1556. }
  1557. else
  1558. {
  1559. asCString str;
  1560. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1561. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1562. Error(TXT_INVALID_BYTECODE_d);
  1563. }
  1564. if( func )
  1565. {
  1566. if( isNew )
  1567. {
  1568. // Destroy the function without releasing any references
  1569. func->id = 0;
  1570. func->scriptData->byteCode.SetLength(0);
  1571. func->ReleaseInternal();
  1572. }
  1573. dontTranslate.Insert(realFunc, true);
  1574. }
  1575. }
  1576. else
  1577. {
  1578. if( func )
  1579. {
  1580. ot->beh.destruct = func->id;
  1581. func->AddRefInternal();
  1582. }
  1583. else
  1584. ot->beh.destruct = 0;
  1585. }
  1586. size = ReadEncodedUInt();
  1587. for( int n = 0; n < size; n++ )
  1588. {
  1589. func = ReadFunction(isNew, !sharedExists, !sharedExists, !sharedExists);
  1590. if( func )
  1591. {
  1592. if( sharedExists )
  1593. {
  1594. // Find the real function in the object, and update the savedFunctions array
  1595. bool found = false;
  1596. for( asUINT f = 0; f < ot->beh.constructors.GetLength(); f++ )
  1597. {
  1598. asCScriptFunction *realFunc = engine->GetScriptFunction(ot->beh.constructors[f]);
  1599. if( realFunc->IsSignatureEqual(func) )
  1600. {
  1601. // If the function is not the last, then the substitution has already occurred before
  1602. if( savedFunctions[savedFunctions.GetLength()-1] == func )
  1603. savedFunctions[savedFunctions.GetLength()-1] = realFunc;
  1604. found = true;
  1605. dontTranslate.Insert(realFunc, true);
  1606. break;
  1607. }
  1608. }
  1609. if( !found )
  1610. {
  1611. asCString str;
  1612. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1613. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1614. Error(TXT_INVALID_BYTECODE_d);
  1615. }
  1616. if( isNew )
  1617. {
  1618. // Destroy the function without releasing any references
  1619. func->id = 0;
  1620. func->scriptData->byteCode.SetLength(0);
  1621. func->ReleaseInternal();
  1622. }
  1623. }
  1624. else
  1625. {
  1626. ot->beh.constructors.PushLast(func->id);
  1627. func->AddRefInternal();
  1628. if( func->parameterTypes.GetLength() == 0 )
  1629. ot->beh.construct = func->id;
  1630. }
  1631. }
  1632. else
  1633. {
  1634. Error(TXT_INVALID_BYTECODE_d);
  1635. }
  1636. func = ReadFunction(isNew, !sharedExists, !sharedExists, !sharedExists);
  1637. if( func )
  1638. {
  1639. if( sharedExists )
  1640. {
  1641. // Find the real function in the object, and update the savedFunctions array
  1642. bool found = false;
  1643. for( asUINT f = 0; f < ot->beh.factories.GetLength(); f++ )
  1644. {
  1645. asCScriptFunction *realFunc = engine->GetScriptFunction(ot->beh.factories[f]);
  1646. if( realFunc->IsSignatureEqual(func) )
  1647. {
  1648. // If the function is not the last, then the substitution has already occurred before
  1649. if( savedFunctions[savedFunctions.GetLength()-1] == func )
  1650. savedFunctions[savedFunctions.GetLength()-1] = realFunc;
  1651. found = true;
  1652. dontTranslate.Insert(realFunc, true);
  1653. break;
  1654. }
  1655. }
  1656. if( !found )
  1657. {
  1658. asCString str;
  1659. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1660. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1661. Error(TXT_INVALID_BYTECODE_d);
  1662. }
  1663. if( isNew )
  1664. {
  1665. // Destroy the function without releasing any references
  1666. func->id = 0;
  1667. func->scriptData->byteCode.SetLength(0);
  1668. func->ReleaseInternal();
  1669. }
  1670. }
  1671. else
  1672. {
  1673. ot->beh.factories.PushLast(func->id);
  1674. func->AddRefInternal();
  1675. if( func->parameterTypes.GetLength() == 0 )
  1676. ot->beh.factory = func->id;
  1677. }
  1678. }
  1679. else
  1680. {
  1681. Error(TXT_INVALID_BYTECODE_d);
  1682. }
  1683. }
  1684. }
  1685. // methods[]
  1686. size = ReadEncodedUInt();
  1687. int n;
  1688. for( n = 0; n < size; n++ )
  1689. {
  1690. bool isNew;
  1691. asCScriptFunction *func = ReadFunction(isNew, !sharedExists, !sharedExists, !sharedExists);
  1692. if( func )
  1693. {
  1694. if( sharedExists )
  1695. {
  1696. // Find the real function in the object, and update the savedFunctions array
  1697. bool found = false;
  1698. for( asUINT f = 0; f < ot->methods.GetLength(); f++ )
  1699. {
  1700. asCScriptFunction *realFunc = engine->GetScriptFunction(ot->methods[f]);
  1701. if( realFunc->IsSignatureEqual(func) )
  1702. {
  1703. // If the function is not the last, then the substitution has already occurred before
  1704. if( savedFunctions[savedFunctions.GetLength()-1] == func )
  1705. savedFunctions[savedFunctions.GetLength()-1] = realFunc;
  1706. found = true;
  1707. dontTranslate.Insert(realFunc, true);
  1708. break;
  1709. }
  1710. }
  1711. if( !found )
  1712. {
  1713. asCString str;
  1714. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1715. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1716. Error(TXT_INVALID_BYTECODE_d);
  1717. }
  1718. if( isNew )
  1719. {
  1720. // Destroy the function without releasing any references
  1721. if( func->id == func->signatureId )
  1722. engine->signatureIds.RemoveValue(func);
  1723. func->id = 0;
  1724. if( func->scriptData )
  1725. func->scriptData->byteCode.SetLength(0);
  1726. func->ReleaseInternal();
  1727. }
  1728. }
  1729. else
  1730. {
  1731. // If the method is the assignment operator we need to replace the default implementation
  1732. if( func->name == "opAssign" && func->parameterTypes.GetLength() == 1 &&
  1733. func->parameterTypes[0].GetTypeInfo() == func->objectType &&
  1734. (func->inOutFlags[0] & asTM_INREF) )
  1735. {
  1736. engine->scriptFunctions[ot->beh.copy]->ReleaseInternal();
  1737. ot->beh.copy = func->id;
  1738. func->AddRefInternal();
  1739. }
  1740. ot->methods.PushLast(func->id);
  1741. func->AddRefInternal();
  1742. }
  1743. }
  1744. else
  1745. {
  1746. Error(TXT_INVALID_BYTECODE_d);
  1747. }
  1748. }
  1749. // virtualFunctionTable[]
  1750. size = ReadEncodedUInt();
  1751. for( n = 0; n < size; n++ )
  1752. {
  1753. bool isNew;
  1754. asCScriptFunction *func = ReadFunction(isNew, !sharedExists, !sharedExists, !sharedExists);
  1755. if( func )
  1756. {
  1757. if( sharedExists )
  1758. {
  1759. // Find the real function in the object, and update the savedFunctions array
  1760. bool found = false;
  1761. for( asUINT f = 0; f < ot->virtualFunctionTable.GetLength(); f++ )
  1762. {
  1763. asCScriptFunction *realFunc = ot->virtualFunctionTable[f];
  1764. if( realFunc->IsSignatureEqual(func) )
  1765. {
  1766. // If the function is not the last, then the substitution has already occurred before
  1767. if( savedFunctions[savedFunctions.GetLength()-1] == func )
  1768. savedFunctions[savedFunctions.GetLength()-1] = realFunc;
  1769. found = true;
  1770. dontTranslate.Insert(realFunc, true);
  1771. break;
  1772. }
  1773. }
  1774. if( !found )
  1775. {
  1776. asCString str;
  1777. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1778. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1779. Error(TXT_INVALID_BYTECODE_d);
  1780. }
  1781. if( isNew )
  1782. {
  1783. // Destroy the function without releasing any references
  1784. func->id = 0;
  1785. if( func->scriptData )
  1786. func->scriptData->byteCode.SetLength(0);
  1787. func->ReleaseInternal();
  1788. }
  1789. }
  1790. else
  1791. {
  1792. ot->virtualFunctionTable.PushLast(func);
  1793. func->AddRefInternal();
  1794. }
  1795. }
  1796. else
  1797. {
  1798. Error(TXT_INVALID_BYTECODE_d);
  1799. }
  1800. }
  1801. }
  1802. }
  1803. else if( phase == 3 )
  1804. {
  1805. // external shared types doesn't store this
  1806. if ((type->flags & asOBJ_SHARED) && module->m_externalTypes.IndexOf(type) >= 0)
  1807. return;
  1808. asCObjectType *ot = CastToObjectType(type);
  1809. // This is only done for object types
  1810. asASSERT(ot);
  1811. // properties[]
  1812. asUINT size = ReadEncodedUInt();
  1813. for( asUINT n = 0; n < size; n++ )
  1814. ReadObjectProperty(ot);
  1815. }
  1816. }
  1817. asWORD asCReader::ReadEncodedUInt16()
  1818. {
  1819. asDWORD dw = ReadEncodedUInt();
  1820. if( (dw>>16) != 0 && (dw>>16) != 0xFFFF )
  1821. {
  1822. Error(TXT_INVALID_BYTECODE_d);
  1823. }
  1824. return asWORD(dw & 0xFFFF);
  1825. }
  1826. asUINT asCReader::ReadEncodedUInt()
  1827. {
  1828. asQWORD qw = ReadEncodedUInt64();
  1829. if( (qw>>32) != 0 && (qw>>32) != 0xFFFFFFFF )
  1830. {
  1831. Error(TXT_INVALID_BYTECODE_d);
  1832. }
  1833. return asUINT(qw & 0xFFFFFFFFu);
  1834. }
  1835. asQWORD asCReader::ReadEncodedUInt64()
  1836. {
  1837. asQWORD i = 0;
  1838. asBYTE b;
  1839. ReadData(&b, 1);
  1840. bool isNegative = ( b & 0x80 ) ? true : false;
  1841. b &= 0x7F;
  1842. if( (b & 0x7F) == 0x7F )
  1843. {
  1844. ReadData(&b, 1); i = asQWORD(b) << 56;
  1845. ReadData(&b, 1); i += asQWORD(b) << 48;
  1846. ReadData(&b, 1); i += asQWORD(b) << 40;
  1847. ReadData(&b, 1); i += asQWORD(b) << 32;
  1848. ReadData(&b, 1); i += asUINT(b) << 24;
  1849. ReadData(&b, 1); i += asUINT(b) << 16;
  1850. ReadData(&b, 1); i += asUINT(b) << 8;
  1851. ReadData(&b, 1); i += b;
  1852. }
  1853. else if( (b & 0x7E) == 0x7E )
  1854. {
  1855. i = asQWORD(b & 0x01) << 48;
  1856. ReadData(&b, 1); i += asQWORD(b) << 40;
  1857. ReadData(&b, 1); i += asQWORD(b) << 32;
  1858. ReadData(&b, 1); i += asUINT(b) << 24;
  1859. ReadData(&b, 1); i += asUINT(b) << 16;
  1860. ReadData(&b, 1); i += asUINT(b) << 8;
  1861. ReadData(&b, 1); i += b;
  1862. }
  1863. else if( (b & 0x7C) == 0x7C )
  1864. {
  1865. i = asQWORD(b & 0x03) << 40;
  1866. ReadData(&b, 1); i += asQWORD(b) << 32;
  1867. ReadData(&b, 1); i += asUINT(b) << 24;
  1868. ReadData(&b, 1); i += asUINT(b) << 16;
  1869. ReadData(&b, 1); i += asUINT(b) << 8;
  1870. ReadData(&b, 1); i += b;
  1871. }
  1872. else if( (b & 0x78) == 0x78 )
  1873. {
  1874. i = asQWORD(b & 0x07) << 32;
  1875. ReadData(&b, 1); i += asUINT(b) << 24;
  1876. ReadData(&b, 1); i += asUINT(b) << 16;
  1877. ReadData(&b, 1); i += asUINT(b) << 8;
  1878. ReadData(&b, 1); i += b;
  1879. }
  1880. else if( (b & 0x70) == 0x70 )
  1881. {
  1882. i = asUINT(b & 0x0F) << 24;
  1883. ReadData(&b, 1); i += asUINT(b) << 16;
  1884. ReadData(&b, 1); i += asUINT(b) << 8;
  1885. ReadData(&b, 1); i += b;
  1886. }
  1887. else if( (b & 0x60) == 0x60 )
  1888. {
  1889. i = asUINT(b & 0x1F) << 16;
  1890. ReadData(&b, 1); i += asUINT(b) << 8;
  1891. ReadData(&b, 1); i += b;
  1892. }
  1893. else if( (b & 0x40) == 0x40 )
  1894. {
  1895. i = asUINT(b & 0x3F) << 8;
  1896. ReadData(&b, 1); i += b;
  1897. }
  1898. else
  1899. {
  1900. i = b;
  1901. }
  1902. if( isNegative )
  1903. i = (asQWORD)(-asINT64(i));
  1904. return i;
  1905. }
  1906. void asCReader::ReadString(asCString* str)
  1907. {
  1908. asUINT len = ReadEncodedUInt();
  1909. if( len & 1 )
  1910. {
  1911. asUINT idx = len/2;
  1912. if( idx < savedStrings.GetLength() )
  1913. *str = savedStrings[idx];
  1914. else
  1915. Error(TXT_INVALID_BYTECODE_d);
  1916. }
  1917. else if( len > 0 )
  1918. {
  1919. len /= 2;
  1920. str->SetLength(len);
  1921. int r = stream->Read(str->AddressOf(), len);
  1922. if (r < 0)
  1923. Error(TXT_UNEXPECTED_END_OF_FILE);
  1924. savedStrings.PushLast(*str);
  1925. }
  1926. else
  1927. str->SetLength(0);
  1928. }
  1929. void asCReader::ReadGlobalProperty()
  1930. {
  1931. asCString name;
  1932. asCDataType type;
  1933. ReadString(&name);
  1934. asCString ns;
  1935. ReadString(&ns);
  1936. asSNameSpace *nameSpace = engine->AddNameSpace(ns.AddressOf());
  1937. ReadDataType(&type);
  1938. asCGlobalProperty *prop = module->AllocateGlobalProperty(name.AddressOf(), type, nameSpace);
  1939. // Read the initialization function
  1940. bool isNew;
  1941. // Do not add the function to the GC at this time. It will
  1942. // only be added to the GC when the module releases the property
  1943. asCScriptFunction *func = ReadFunction(isNew, false, true, false);
  1944. if( func )
  1945. {
  1946. // Make sure the function knows it is owned by the module
  1947. func->module = module;
  1948. prop->SetInitFunc(func);
  1949. func->ReleaseInternal();
  1950. }
  1951. }
  1952. void asCReader::ReadObjectProperty(asCObjectType *ot)
  1953. {
  1954. asCString name;
  1955. ReadString(&name);
  1956. asCDataType dt;
  1957. ReadDataType(&dt);
  1958. int flags = ReadEncodedUInt();
  1959. bool isPrivate = (flags & 1) ? true : false;
  1960. bool isProtected = (flags & 2) ? true : false;
  1961. bool isInherited = (flags & 4) ? true : false;
  1962. // TODO: shared: If the type is shared and pre-existing, we should just
  1963. // validate that the loaded methods match the original
  1964. if( !existingShared.MoveTo(0, ot) )
  1965. ot->AddPropertyToClass(name, dt, isPrivate, isProtected, isInherited);
  1966. }
  1967. void asCReader::ReadDataType(asCDataType *dt)
  1968. {
  1969. // Check if this is a previously used type
  1970. asUINT idx = ReadEncodedUInt();
  1971. if( idx != 0 )
  1972. {
  1973. // Get the datatype from the cache
  1974. *dt = savedDataTypes[idx-1];
  1975. return;
  1976. }
  1977. // Read the type definition
  1978. eTokenType tokenType = (eTokenType)ReadEncodedUInt();
  1979. // Reserve a spot in the savedDataTypes
  1980. asUINT saveSlot = savedDataTypes.GetLength();
  1981. savedDataTypes.PushLast(asCDataType());
  1982. // Read the datatype for the first time
  1983. asCTypeInfo *ti = 0;
  1984. if( tokenType == ttIdentifier )
  1985. ti = ReadTypeInfo();
  1986. // Read type flags as a bitmask
  1987. // Endian-safe code
  1988. bool isObjectHandle, isHandleToConst, isReference, isReadOnly;
  1989. char b = 0;
  1990. ReadData(&b, 1);
  1991. LOAD_FROM_BIT(isObjectHandle, b, 0);
  1992. LOAD_FROM_BIT(isHandleToConst, b, 1);
  1993. LOAD_FROM_BIT(isReference, b, 2);
  1994. LOAD_FROM_BIT(isReadOnly, b, 3);
  1995. if( tokenType == ttIdentifier )
  1996. *dt = asCDataType::CreateType(ti, false);
  1997. else
  1998. *dt = asCDataType::CreatePrimitive(tokenType, false);
  1999. if( isObjectHandle )
  2000. {
  2001. dt->MakeReadOnly(isHandleToConst ? true : false);
  2002. // Here we must allow a scoped type to be a handle
  2003. // e.g. if the datatype is for a system function
  2004. dt->MakeHandle(true, true);
  2005. }
  2006. dt->MakeReadOnly(isReadOnly ? true : false);
  2007. dt->MakeReference(isReference ? true : false);
  2008. // Update the previously saved slot
  2009. savedDataTypes[saveSlot] = *dt;
  2010. }
  2011. asCTypeInfo* asCReader::ReadTypeInfo()
  2012. {
  2013. asCTypeInfo *ot = 0;
  2014. char ch;
  2015. ReadData(&ch, 1);
  2016. if( ch == 'a' )
  2017. {
  2018. // Read the name of the template type
  2019. asCString typeName, ns;
  2020. ReadString(&typeName);
  2021. ReadString(&ns);
  2022. asSNameSpace *nameSpace = engine->AddNameSpace(ns.AddressOf());
  2023. asCTypeInfo *tmp = engine->GetRegisteredType(typeName.AddressOf(), nameSpace);
  2024. asCObjectType *tmpl = CastToObjectType(tmp);
  2025. if( tmpl == 0 )
  2026. {
  2027. asCString str;
  2028. str.Format(TXT_TEMPLATE_TYPE_s_DOESNT_EXIST, typeName.AddressOf());
  2029. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2030. Error(TXT_INVALID_BYTECODE_d);
  2031. return 0;
  2032. }
  2033. asUINT numSubTypes = ReadEncodedUInt();
  2034. asCArray<asCDataType> subTypes;
  2035. for( asUINT n = 0; n < numSubTypes; n++ )
  2036. {
  2037. ReadData(&ch, 1);
  2038. if( ch == 's' )
  2039. {
  2040. asCDataType dt;
  2041. ReadDataType(&dt);
  2042. subTypes.PushLast(dt);
  2043. }
  2044. else
  2045. {
  2046. eTokenType tokenType = (eTokenType)ReadEncodedUInt();
  2047. asCDataType dt = asCDataType::CreatePrimitive(tokenType, false);
  2048. subTypes.PushLast(dt);
  2049. }
  2050. }
  2051. // Return the actual template if the subtypes are the template's dummy types
  2052. if( tmpl->templateSubTypes == subTypes )
  2053. ot = tmpl;
  2054. else
  2055. {
  2056. // Get the template instance type based on the loaded subtypes
  2057. ot = engine->GetTemplateInstanceType(tmpl, subTypes, module);
  2058. }
  2059. if( ot == 0 )
  2060. {
  2061. // Show all subtypes in error message
  2062. asCString sub = subTypes[0].Format(nameSpace);
  2063. for( asUINT n = 1; n < subTypes.GetLength(); n++ )
  2064. {
  2065. sub += ",";
  2066. sub += subTypes[n].Format(nameSpace);
  2067. }
  2068. asCString str;
  2069. str.Format(TXT_INSTANCING_INVLD_TMPL_TYPE_s_s, typeName.AddressOf(), sub.AddressOf());
  2070. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2071. Error(TXT_INVALID_BYTECODE_d);
  2072. return 0;
  2073. }
  2074. }
  2075. else if( ch == 'l' )
  2076. {
  2077. asCObjectType *st = CastToObjectType(ReadTypeInfo());
  2078. if( st == 0 || st->beh.listFactory == 0 )
  2079. {
  2080. Error(TXT_INVALID_BYTECODE_d);
  2081. return 0;
  2082. }
  2083. ot = engine->GetListPatternType(st->beh.listFactory);
  2084. }
  2085. else if( ch == 's' )
  2086. {
  2087. // Read the name of the template subtype
  2088. asCString typeName;
  2089. ReadString(&typeName);
  2090. // Find the template subtype
  2091. ot = 0;
  2092. for( asUINT n = 0; n < engine->templateSubTypes.GetLength(); n++ )
  2093. {
  2094. if( engine->templateSubTypes[n] && engine->templateSubTypes[n]->name == typeName )
  2095. {
  2096. ot = engine->templateSubTypes[n];
  2097. break;
  2098. }
  2099. }
  2100. if( ot == 0 )
  2101. {
  2102. asCString str;
  2103. str.Format(TXT_TEMPLATE_SUBTYPE_s_DOESNT_EXIST, typeName.AddressOf());
  2104. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2105. Error(TXT_INVALID_BYTECODE_d);
  2106. return 0;
  2107. }
  2108. }
  2109. else if( ch == 'o' )
  2110. {
  2111. // Read the object type name
  2112. asCString typeName, ns;
  2113. ReadString(&typeName);
  2114. ReadString(&ns);
  2115. asSNameSpace *nameSpace = engine->AddNameSpace(ns.AddressOf());
  2116. if( typeName.GetLength() && typeName != "$obj" && typeName != "$func" )
  2117. {
  2118. // Find the object type
  2119. ot = module->GetType(typeName.AddressOf(), nameSpace);
  2120. if (!ot)
  2121. ot = engine->GetRegisteredType(typeName.AddressOf(), nameSpace);
  2122. if( ot == 0 )
  2123. {
  2124. asCString str;
  2125. str.Format(TXT_OBJECT_TYPE_s_DOESNT_EXIST, typeName.AddressOf());
  2126. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2127. Error(TXT_INVALID_BYTECODE_d);
  2128. return 0;
  2129. }
  2130. }
  2131. else if( typeName == "$obj" )
  2132. {
  2133. ot = &engine->scriptTypeBehaviours;
  2134. }
  2135. else if( typeName == "$func" )
  2136. {
  2137. ot = &engine->functionBehaviours;
  2138. }
  2139. else
  2140. asASSERT( false );
  2141. }
  2142. else if (ch == 'c')
  2143. {
  2144. // Read the object type name
  2145. asCString typeName, ns;
  2146. ReadString(&typeName);
  2147. // Read the parent class
  2148. asCObjectType *parentClass = CastToObjectType(ReadTypeInfo());
  2149. if (parentClass == 0)
  2150. {
  2151. Error(TXT_INVALID_BYTECODE_d);
  2152. return 0;
  2153. }
  2154. // Find the child type in the parentClass
  2155. for (asUINT n = 0; n < parentClass->childFuncDefs.GetLength(); n++)
  2156. {
  2157. if (parentClass->childFuncDefs[n]->name == typeName)
  2158. ot = parentClass->childFuncDefs[n];
  2159. }
  2160. if (ot == 0)
  2161. {
  2162. asCString str;
  2163. str.Format(TXT_OBJECT_TYPE_s_DOESNT_EXIST, typeName.AddressOf());
  2164. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2165. Error(TXT_INVALID_BYTECODE_d);
  2166. return 0;
  2167. }
  2168. }
  2169. else
  2170. {
  2171. // No object type
  2172. asASSERT( ch == '\0' || error );
  2173. ot = 0;
  2174. }
  2175. return ot;
  2176. }
  2177. void asCReader::ReadByteCode(asCScriptFunction *func)
  2178. {
  2179. asASSERT( func->scriptData );
  2180. // Read number of instructions
  2181. asUINT total, numInstructions;
  2182. total = numInstructions = ReadEncodedUInt();
  2183. // Reserve some space for the instructions
  2184. func->scriptData->byteCode.AllocateNoConstruct(numInstructions, false);
  2185. asUINT pos = 0;
  2186. while( numInstructions )
  2187. {
  2188. asBYTE b;
  2189. ReadData(&b, 1);
  2190. // Allocate the space for the instruction
  2191. asUINT len = asBCTypeSize[asBCInfo[b].type];
  2192. asUINT newSize = asUINT(func->scriptData->byteCode.GetLength()) + len;
  2193. if( func->scriptData->byteCode.GetCapacity() < newSize )
  2194. {
  2195. // Determine the average size of the loaded instructions and re-estimate the final size
  2196. asUINT size = asUINT(float(newSize) / (total - numInstructions) * total) + 1;
  2197. func->scriptData->byteCode.AllocateNoConstruct(size, true);
  2198. }
  2199. if( !func->scriptData->byteCode.SetLengthNoConstruct(newSize) )
  2200. {
  2201. // Out of memory
  2202. error = true;
  2203. return;
  2204. }
  2205. asDWORD *bc = func->scriptData->byteCode.AddressOf() + pos;
  2206. pos += len;
  2207. switch( asBCInfo[b].type )
  2208. {
  2209. case asBCTYPE_NO_ARG:
  2210. {
  2211. *(asBYTE*)(bc) = b;
  2212. bc++;
  2213. }
  2214. break;
  2215. case asBCTYPE_W_ARG:
  2216. case asBCTYPE_wW_ARG:
  2217. case asBCTYPE_rW_ARG:
  2218. {
  2219. *(asBYTE*)(bc) = b;
  2220. // Read the argument
  2221. asWORD w = ReadEncodedUInt16();
  2222. *(((asWORD*)bc)+1) = w;
  2223. bc++;
  2224. }
  2225. break;
  2226. case asBCTYPE_rW_DW_ARG:
  2227. case asBCTYPE_wW_DW_ARG:
  2228. case asBCTYPE_W_DW_ARG:
  2229. {
  2230. *(asBYTE*)(bc) = b;
  2231. // Read the word argument
  2232. asWORD w = ReadEncodedUInt16();
  2233. *(((asWORD*)bc)+1) = w;
  2234. bc++;
  2235. // Read the dword argument
  2236. *bc++ = ReadEncodedUInt();
  2237. }
  2238. break;
  2239. case asBCTYPE_DW_ARG:
  2240. {
  2241. *(asBYTE*)(bc) = b;
  2242. bc++;
  2243. // Read the argument
  2244. *bc++ = ReadEncodedUInt();
  2245. }
  2246. break;
  2247. case asBCTYPE_DW_DW_ARG:
  2248. {
  2249. *(asBYTE*)(bc) = b;
  2250. bc++;
  2251. // Read the first argument
  2252. *bc++ = ReadEncodedUInt();
  2253. // Read the second argument
  2254. *bc++ = ReadEncodedUInt();
  2255. }
  2256. break;
  2257. case asBCTYPE_wW_rW_rW_ARG:
  2258. {
  2259. *(asBYTE*)(bc) = b;
  2260. // Read the first argument
  2261. asWORD w = ReadEncodedUInt16();
  2262. *(((asWORD*)bc)+1) = w;
  2263. bc++;
  2264. // Read the second argument
  2265. w = ReadEncodedUInt16();
  2266. *(asWORD*)bc = w;
  2267. // Read the third argument
  2268. w = ReadEncodedUInt16();
  2269. *(((asWORD*)bc)+1) = w;
  2270. bc++;
  2271. }
  2272. break;
  2273. case asBCTYPE_wW_rW_ARG:
  2274. case asBCTYPE_rW_rW_ARG:
  2275. case asBCTYPE_wW_W_ARG:
  2276. {
  2277. *(asBYTE*)(bc) = b;
  2278. // Read the first argument
  2279. asWORD w = ReadEncodedUInt16();
  2280. *(((asWORD*)bc)+1) = w;
  2281. bc++;
  2282. // Read the second argument
  2283. w = ReadEncodedUInt16();
  2284. *(asWORD*)bc = w;
  2285. bc++;
  2286. }
  2287. break;
  2288. case asBCTYPE_wW_rW_DW_ARG:
  2289. case asBCTYPE_rW_W_DW_ARG:
  2290. {
  2291. *(asBYTE*)(bc) = b;
  2292. // Read the first argument
  2293. asWORD w = ReadEncodedUInt16();
  2294. *(((asWORD*)bc)+1) = w;
  2295. bc++;
  2296. // Read the second argument
  2297. w = ReadEncodedUInt16();
  2298. *(asWORD*)bc = w;
  2299. bc++;
  2300. // Read the third argument
  2301. asDWORD dw = ReadEncodedUInt();
  2302. *bc++ = dw;
  2303. }
  2304. break;
  2305. case asBCTYPE_QW_ARG:
  2306. {
  2307. *(asBYTE*)(bc) = b;
  2308. bc++;
  2309. // Read the argument
  2310. asQWORD qw = ReadEncodedUInt64();
  2311. *(asQWORD*)bc = qw;
  2312. bc += 2;
  2313. }
  2314. break;
  2315. case asBCTYPE_QW_DW_ARG:
  2316. {
  2317. *(asBYTE*)(bc) = b;
  2318. bc++;
  2319. // Read the first argument
  2320. asQWORD qw = ReadEncodedUInt64();
  2321. *(asQWORD*)bc = qw;
  2322. bc += 2;
  2323. // Read the second argument
  2324. asDWORD dw = ReadEncodedUInt();
  2325. *bc++ = dw;
  2326. }
  2327. break;
  2328. case asBCTYPE_rW_QW_ARG:
  2329. case asBCTYPE_wW_QW_ARG:
  2330. {
  2331. *(asBYTE*)(bc) = b;
  2332. // Read the first argument
  2333. asWORD w = ReadEncodedUInt16();
  2334. *(((asWORD*)bc)+1) = w;
  2335. bc++;
  2336. // Read the argument
  2337. asQWORD qw = ReadEncodedUInt64();
  2338. *(asQWORD*)bc = qw;
  2339. bc += 2;
  2340. }
  2341. break;
  2342. case asBCTYPE_rW_DW_DW_ARG:
  2343. {
  2344. *(asBYTE*)(bc) = b;
  2345. // Read the 1st argument
  2346. asWORD w = ReadEncodedUInt16();
  2347. *(((asWORD*)bc)+1) = w;
  2348. bc++;
  2349. // Read the 2nd argument
  2350. *bc++ = ReadEncodedUInt();
  2351. // Read the 3rd argument
  2352. *bc++ = ReadEncodedUInt();
  2353. }
  2354. break;
  2355. default:
  2356. {
  2357. // This should never happen
  2358. asASSERT(false);
  2359. // Read the next 3 bytes
  2360. asDWORD c; asBYTE t;
  2361. #if defined(AS_BIG_ENDIAN)
  2362. c = b << 24;
  2363. ReadData(&t, 1); c += t << 16;
  2364. ReadData(&t, 1); c += t << 8;
  2365. ReadData(&t, 1); c += t;
  2366. #else
  2367. c = b;
  2368. ReadData(&t, 1); c += t << 8;
  2369. ReadData(&t, 1); c += t << 16;
  2370. ReadData(&t, 1); c += t << 24;
  2371. #endif
  2372. *bc++ = c;
  2373. c = *(asBYTE*)&c;
  2374. // Read the bc as is
  2375. for( int n = 1; n < asBCTypeSize[asBCInfo[c].type]; n++ )
  2376. ReadData(&*bc++, 4);
  2377. }
  2378. }
  2379. numInstructions--;
  2380. }
  2381. // Correct the final size in case we over-estimated it
  2382. func->scriptData->byteCode.SetLengthNoConstruct(pos);
  2383. }
  2384. void asCReader::ReadUsedTypeIds()
  2385. {
  2386. TimeIt("asCReader::ReadUsedTypeIds");
  2387. asUINT count = ReadEncodedUInt();
  2388. usedTypeIds.Allocate(count, false);
  2389. for( asUINT n = 0; n < count; n++ )
  2390. {
  2391. asCDataType dt;
  2392. ReadDataType(&dt);
  2393. usedTypeIds.PushLast(engine->GetTypeIdFromDataType(dt));
  2394. }
  2395. }
  2396. void asCReader::ReadUsedGlobalProps()
  2397. {
  2398. TimeIt("asCReader::ReadUsedGlobalProps");
  2399. int c = ReadEncodedUInt();
  2400. usedGlobalProperties.Allocate(c, false);
  2401. for( int n = 0; n < c; n++ )
  2402. {
  2403. asCString name, ns;
  2404. asCDataType type;
  2405. char moduleProp;
  2406. ReadString(&name);
  2407. ReadString(&ns);
  2408. ReadDataType(&type);
  2409. ReadData(&moduleProp, 1);
  2410. asSNameSpace *nameSpace = engine->AddNameSpace(ns.AddressOf());
  2411. // Find the real property
  2412. asCGlobalProperty *globProp = 0;
  2413. if( moduleProp )
  2414. globProp = module->m_scriptGlobals.GetFirst(nameSpace, name);
  2415. else
  2416. globProp = engine->registeredGlobalProps.GetFirst(nameSpace, name);
  2417. void *prop = 0;
  2418. if( globProp && globProp->type == type )
  2419. prop = globProp->GetAddressOfValue();
  2420. usedGlobalProperties.PushLast(prop);
  2421. if( prop == 0 )
  2422. {
  2423. Error(TXT_INVALID_BYTECODE_d);
  2424. }
  2425. }
  2426. }
  2427. void asCReader::ReadUsedObjectProps()
  2428. {
  2429. TimeIt("asCReader::ReadUsedObjectProps");
  2430. asUINT c = ReadEncodedUInt();
  2431. usedObjectProperties.SetLength(c);
  2432. for( asUINT n = 0; n < c; n++ )
  2433. {
  2434. asCObjectType *objType = CastToObjectType(ReadTypeInfo());
  2435. if( objType == 0 )
  2436. {
  2437. Error(TXT_INVALID_BYTECODE_d);
  2438. break;
  2439. }
  2440. asCString name;
  2441. ReadString(&name);
  2442. // Find the property
  2443. bool found = false;
  2444. for( asUINT p = 0; p < objType->properties.GetLength(); p++ )
  2445. {
  2446. if( objType->properties[p]->name == name )
  2447. {
  2448. usedObjectProperties[n].objType = objType;
  2449. usedObjectProperties[n].prop = objType->properties[p];
  2450. found = true;
  2451. break;
  2452. }
  2453. }
  2454. if( !found )
  2455. {
  2456. Error(TXT_INVALID_BYTECODE_d);
  2457. return;
  2458. }
  2459. }
  2460. }
  2461. short asCReader::FindObjectPropOffset(asWORD index)
  2462. {
  2463. static asCObjectProperty *lastCompositeProp = 0;
  2464. if (lastCompositeProp)
  2465. {
  2466. if (index != 0)
  2467. {
  2468. Error(TXT_INVALID_BYTECODE_d);
  2469. return 0;
  2470. }
  2471. short offset = (short)lastCompositeProp->byteOffset;
  2472. lastCompositeProp = 0;
  2473. return offset;
  2474. }
  2475. if( index >= usedObjectProperties.GetLength() )
  2476. {
  2477. Error(TXT_INVALID_BYTECODE_d);
  2478. return 0;
  2479. }
  2480. if (usedObjectProperties[index].prop->compositeOffset || usedObjectProperties[index].prop->isCompositeIndirect)
  2481. {
  2482. lastCompositeProp = usedObjectProperties[index].prop;
  2483. return (short)lastCompositeProp->compositeOffset;
  2484. }
  2485. return (short)usedObjectProperties[index].prop->byteOffset;
  2486. }
  2487. asCScriptFunction *asCReader::FindFunction(int idx)
  2488. {
  2489. if( idx >= 0 && idx < (int)usedFunctions.GetLength() )
  2490. return usedFunctions[idx];
  2491. else
  2492. {
  2493. Error(TXT_INVALID_BYTECODE_d);
  2494. return 0;
  2495. }
  2496. }
  2497. void asCReader::TranslateFunction(asCScriptFunction *func)
  2498. {
  2499. // Skip this if the function is part of an pre-existing shared object
  2500. if( dontTranslate.MoveTo(0, func) ) return;
  2501. asASSERT( func->scriptData );
  2502. // Pre-compute the size of each instruction in order to translate jump offsets
  2503. asUINT n;
  2504. asDWORD *bc = func->scriptData->byteCode.AddressOf();
  2505. asUINT bcLength = (asUINT)func->scriptData->byteCode.GetLength();
  2506. asCArray<asUINT> bcSizes(bcLength);
  2507. asCArray<asUINT> instructionNbrToPos(bcLength);
  2508. for( n = 0; n < bcLength; )
  2509. {
  2510. int c = *(asBYTE*)&bc[n];
  2511. asUINT size = asBCTypeSize[asBCInfo[c].type];
  2512. if( size == 0 )
  2513. {
  2514. Error(TXT_INVALID_BYTECODE_d);
  2515. return;
  2516. }
  2517. bcSizes.PushLast(size);
  2518. instructionNbrToPos.PushLast(n);
  2519. n += size;
  2520. }
  2521. asUINT bcNum = 0;
  2522. for( n = 0; n < bcLength; bcNum++ )
  2523. {
  2524. int c = *(asBYTE*)&bc[n];
  2525. if( c == asBC_REFCPY ||
  2526. c == asBC_RefCpyV ||
  2527. c == asBC_OBJTYPE )
  2528. {
  2529. // Translate the index to the true object type
  2530. asPWORD *ot = (asPWORD*)&bc[n+1];
  2531. *(asCObjectType**)ot = CastToObjectType(FindType(int(*ot)));
  2532. }
  2533. else if( c == asBC_TYPEID ||
  2534. c == asBC_Cast )
  2535. {
  2536. // Translate the index to the type id
  2537. int *tid = (int*)&bc[n+1];
  2538. *tid = FindTypeId(*tid);
  2539. }
  2540. else if( c == asBC_ADDSi ||
  2541. c == asBC_LoadThisR )
  2542. {
  2543. // Translate the index to the type id
  2544. int *tid = (int*)&bc[n+1];
  2545. *tid = FindTypeId(*tid);
  2546. // Translate the prop index into the property offset
  2547. *(((short*)&bc[n])+1) = FindObjectPropOffset(*(((short*)&bc[n])+1));
  2548. }
  2549. else if( c == asBC_LoadRObjR ||
  2550. c == asBC_LoadVObjR )
  2551. {
  2552. // Translate the index to the type id
  2553. int *tid = (int*)&bc[n+2];
  2554. *tid = FindTypeId(*tid);
  2555. asCObjectType *ot = engine->GetObjectTypeFromTypeId(*tid);
  2556. if( ot && (ot->flags & asOBJ_LIST_PATTERN) )
  2557. {
  2558. // List patterns have a different way of adjusting the offsets
  2559. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  2560. *(((short*)&bc[n])+2) = (short)listAdj->AdjustOffset(*(((short*)&bc[n])+2));
  2561. }
  2562. else
  2563. {
  2564. // Translate the prop index into the property offset
  2565. *(((short*)&bc[n])+2) = FindObjectPropOffset(*(((short*)&bc[n])+2));
  2566. }
  2567. }
  2568. else if( c == asBC_COPY )
  2569. {
  2570. // Translate the index to the type id
  2571. int *tid = (int*)&bc[n+1];
  2572. *tid = FindTypeId(*tid);
  2573. // COPY is used to copy POD types that don't have the opAssign method. It is
  2574. // also used to copy references to scoped types during variable initializations.
  2575. // Update the number of dwords to copy as it may be different on the target platform
  2576. if( (*tid) & asTYPEID_OBJHANDLE )
  2577. {
  2578. // It is the actual reference that is being copied, not the object itself
  2579. asBC_SWORDARG0(&bc[n]) = AS_PTR_SIZE;
  2580. }
  2581. else
  2582. {
  2583. asCDataType dt = engine->GetDataTypeFromTypeId(*tid);
  2584. if( !dt.IsValid() )
  2585. {
  2586. Error(TXT_INVALID_BYTECODE_d);
  2587. }
  2588. else
  2589. asBC_SWORDARG0(&bc[n]) = (short)dt.GetSizeInMemoryDWords();
  2590. }
  2591. }
  2592. else if( c == asBC_RET )
  2593. {
  2594. // Determine the correct amount of DWORDs to pop
  2595. asWORD dw = (asWORD)func->GetSpaceNeededForArguments();
  2596. if( func->DoesReturnOnStack() ) dw += AS_PTR_SIZE;
  2597. if( func->objectType ) dw += AS_PTR_SIZE;
  2598. asBC_WORDARG0(&bc[n]) = dw;
  2599. }
  2600. else if( c == asBC_CALL ||
  2601. c == asBC_CALLINTF ||
  2602. c == asBC_CALLSYS ||
  2603. c == asBC_Thiscall1 )
  2604. {
  2605. // Translate the index to the func id
  2606. int *fid = (int*)&bc[n+1];
  2607. asCScriptFunction *f = FindFunction(*fid);
  2608. if( f )
  2609. *fid = f->id;
  2610. else
  2611. {
  2612. Error(TXT_INVALID_BYTECODE_d);
  2613. return;
  2614. }
  2615. }
  2616. else if( c == asBC_FuncPtr )
  2617. {
  2618. // Translate the index to the func pointer
  2619. asPWORD *fid = (asPWORD*)&bc[n+1];
  2620. *fid = (asPWORD)FindFunction(int(*fid));
  2621. }
  2622. else if( c == asBC_ALLOC )
  2623. {
  2624. // Translate the index to the true object type
  2625. asPWORD *arg = (asPWORD*)&bc[n+1];
  2626. *(asCObjectType**)arg = CastToObjectType(FindType(int(*arg)));
  2627. // The constructor function id must be translated, unless it is zero
  2628. int *fid = (int*)&bc[n+1+AS_PTR_SIZE];
  2629. if( *fid != 0 )
  2630. {
  2631. // Subtract 1 from the id, as it was incremented during the writing
  2632. asCScriptFunction *f = FindFunction(*fid-1);
  2633. if( f )
  2634. *fid = f->id;
  2635. else
  2636. {
  2637. Error(TXT_INVALID_BYTECODE_d);
  2638. return;
  2639. }
  2640. }
  2641. }
  2642. else if( c == asBC_STR )
  2643. {
  2644. Error(TXT_INVALID_BYTECODE_d);
  2645. return;
  2646. }
  2647. else if( c == asBC_CALLBND )
  2648. {
  2649. // Translate the function id
  2650. asUINT *fid = (asUINT*)&bc[n+1];
  2651. if( *fid < module->m_bindInformations.GetLength() )
  2652. {
  2653. sBindInfo *bi = module->m_bindInformations[*fid];
  2654. if( bi )
  2655. *fid = bi->importedFunctionSignature->id;
  2656. else
  2657. {
  2658. Error(TXT_INVALID_BYTECODE_d);
  2659. return;
  2660. }
  2661. }
  2662. else
  2663. {
  2664. Error(TXT_INVALID_BYTECODE_d);
  2665. return;
  2666. }
  2667. }
  2668. else if( c == asBC_PGA ||
  2669. c == asBC_PshGPtr ||
  2670. c == asBC_LDG ||
  2671. c == asBC_PshG4 ||
  2672. c == asBC_LdGRdR4 ||
  2673. c == asBC_CpyGtoV4 ||
  2674. c == asBC_CpyVtoG4 ||
  2675. c == asBC_SetG4 )
  2676. {
  2677. // Translate the index to pointer
  2678. asPWORD *index = (asPWORD*)&bc[n + 1];
  2679. if ((*index & 1))
  2680. {
  2681. if ((asUINT(*index)>>1) < usedGlobalProperties.GetLength())
  2682. *(void**)index = usedGlobalProperties[asUINT(*index)>>1];
  2683. else
  2684. {
  2685. Error(TXT_INVALID_BYTECODE_d);
  2686. return;
  2687. }
  2688. }
  2689. else
  2690. {
  2691. // Only PGA and PshGPtr can hold string constants
  2692. asASSERT(c == asBC_PGA || c == asBC_PshGPtr);
  2693. if ((asUINT(*index)>>1) < usedStringConstants.GetLength())
  2694. *(void**)index = usedStringConstants[asUINT(*index)>>1];
  2695. else
  2696. {
  2697. Error(TXT_INVALID_BYTECODE_d);
  2698. return;
  2699. }
  2700. }
  2701. }
  2702. else if( c == asBC_JMP ||
  2703. c == asBC_JZ ||
  2704. c == asBC_JNZ ||
  2705. c == asBC_JLowZ ||
  2706. c == asBC_JLowNZ ||
  2707. c == asBC_JS ||
  2708. c == asBC_JNS ||
  2709. c == asBC_JP ||
  2710. c == asBC_JNP ) // The JMPP instruction doesn't need modification
  2711. {
  2712. // Get the offset
  2713. int offset = int(bc[n+1]);
  2714. // Count the instruction sizes to the destination instruction
  2715. int size = 0;
  2716. if( offset >= 0 )
  2717. // If moving ahead, then start from next instruction
  2718. for( asUINT num = bcNum+1; offset-- > 0; num++ )
  2719. size += bcSizes[num];
  2720. else
  2721. // If moving backwards, then start at current instruction
  2722. for( asUINT num = bcNum; offset++ < 0; num-- )
  2723. size -= bcSizes[num];
  2724. // The size is dword offset
  2725. bc[n+1] = size;
  2726. }
  2727. else if( c == asBC_AllocMem )
  2728. {
  2729. // The size of the allocated memory is only known after all the elements has been seen.
  2730. // This helper class will collect this information and adjust the size when the
  2731. // corresponding asBC_FREE is encountered
  2732. // The adjuster also needs to know the list type so it can know the type of the elements
  2733. asCObjectType *ot = CastToObjectType(func->GetTypeInfoOfLocalVar(asBC_SWORDARG0(&bc[n])));
  2734. listAdjusters.PushLast(asNEW(SListAdjuster)(this, &bc[n], ot));
  2735. }
  2736. else if( c == asBC_FREE )
  2737. {
  2738. // Translate the index to the true object type
  2739. asPWORD *pot = (asPWORD*)&bc[n+1];
  2740. *(asCObjectType**)pot = CastToObjectType(FindType(int(*pot)));
  2741. asCObjectType *ot = *(asCObjectType**)pot;
  2742. if( ot && (ot->flags & asOBJ_LIST_PATTERN) )
  2743. {
  2744. if( listAdjusters.GetLength() == 0 )
  2745. {
  2746. Error(TXT_INVALID_BYTECODE_d);
  2747. return;
  2748. }
  2749. // Finalize the adjustment of the list buffer that was initiated with asBC_AllocMem
  2750. SListAdjuster *list = listAdjusters.PopLast();
  2751. list->AdjustAllocMem();
  2752. asDELETE(list, SListAdjuster);
  2753. }
  2754. }
  2755. else if( c == asBC_SetListSize )
  2756. {
  2757. // Adjust the offset in the list where the size is informed
  2758. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  2759. bc[n+1] = listAdj->AdjustOffset(bc[n+1]);
  2760. // Inform the list adjuster how many values will be repeated
  2761. listAdj->SetRepeatCount(bc[n+2]);
  2762. }
  2763. else if( c == asBC_PshListElmnt )
  2764. {
  2765. // Adjust the offset in the list where the size is informed
  2766. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  2767. bc[n+1] = listAdj->AdjustOffset(bc[n+1]);
  2768. }
  2769. else if( c == asBC_SetListType )
  2770. {
  2771. // Adjust the offset in the list where the typeid is informed
  2772. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  2773. bc[n+1] = listAdj->AdjustOffset(bc[n+1]);
  2774. // Translate the type id
  2775. bc[n+2] = FindTypeId(bc[n+2]);
  2776. // Inform the list adjuster the type id of the next element
  2777. listAdj->SetNextType(bc[n+2]);
  2778. }
  2779. n += asBCTypeSize[asBCInfo[c].type];
  2780. }
  2781. // Calculate the stack adjustments
  2782. CalculateAdjustmentByPos(func);
  2783. // Adjust all variable positions in the bytecode
  2784. bc = func->scriptData->byteCode.AddressOf();
  2785. for( n = 0; n < bcLength; )
  2786. {
  2787. int c = *(asBYTE*)&bc[n];
  2788. switch( asBCInfo[c].type )
  2789. {
  2790. case asBCTYPE_wW_ARG:
  2791. case asBCTYPE_rW_DW_ARG:
  2792. case asBCTYPE_wW_QW_ARG:
  2793. case asBCTYPE_rW_ARG:
  2794. case asBCTYPE_wW_DW_ARG:
  2795. case asBCTYPE_wW_W_ARG:
  2796. case asBCTYPE_rW_QW_ARG:
  2797. case asBCTYPE_rW_W_DW_ARG:
  2798. case asBCTYPE_rW_DW_DW_ARG:
  2799. {
  2800. asBC_SWORDARG0(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG0(&bc[n]));
  2801. }
  2802. break;
  2803. case asBCTYPE_wW_rW_ARG:
  2804. case asBCTYPE_wW_rW_DW_ARG:
  2805. case asBCTYPE_rW_rW_ARG:
  2806. {
  2807. asBC_SWORDARG0(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG0(&bc[n]));
  2808. asBC_SWORDARG1(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG1(&bc[n]));
  2809. }
  2810. break;
  2811. case asBCTYPE_wW_rW_rW_ARG:
  2812. {
  2813. asBC_SWORDARG0(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG0(&bc[n]));
  2814. asBC_SWORDARG1(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG1(&bc[n]));
  2815. asBC_SWORDARG2(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG2(&bc[n]));
  2816. }
  2817. break;
  2818. default:
  2819. // The other types don't treat variables so won't be modified
  2820. break;
  2821. }
  2822. n += asBCTypeSize[asBCInfo[c].type];
  2823. }
  2824. // Adjust the space needed for local variables
  2825. func->scriptData->variableSpace = AdjustStackPosition(func->scriptData->variableSpace);
  2826. // Adjust the variable information. This will be used during the adjustment below
  2827. for( n = 0; n < func->scriptData->variables.GetLength(); n++ )
  2828. {
  2829. func->scriptData->variables[n]->declaredAtProgramPos = instructionNbrToPos[func->scriptData->variables[n]->declaredAtProgramPos];
  2830. func->scriptData->variables[n]->stackOffset = AdjustStackPosition(func->scriptData->variables[n]->stackOffset);
  2831. }
  2832. // objVariablePos
  2833. for( n = 0; n < func->scriptData->objVariablePos.GetLength(); n++ )
  2834. func->scriptData->objVariablePos[n] = AdjustStackPosition(func->scriptData->objVariablePos[n]);
  2835. // Adjust the get offsets. This must be done in the second iteration because
  2836. // it relies on the function ids and variable position already being correct in the
  2837. // bytecodes that come after the GET instructions.
  2838. // TODO: optimize: Instead of doing a full extra loop. We can push the GET instructions
  2839. // on a stack, and then when a call instruction is found update all of them.
  2840. // This will also make the AdjustGetOffset() function quicker as it can
  2841. // receive the called function directly instead of having to search for it.
  2842. bc = func->scriptData->byteCode.AddressOf();
  2843. for( n = 0; n < bcLength; )
  2844. {
  2845. int c = *(asBYTE*)&bc[n];
  2846. if( c == asBC_GETREF ||
  2847. c == asBC_GETOBJ ||
  2848. c == asBC_GETOBJREF ||
  2849. c == asBC_ChkNullS )
  2850. {
  2851. asBC_WORDARG0(&bc[n]) = (asWORD)AdjustGetOffset(asBC_WORDARG0(&bc[n]), func, n);
  2852. }
  2853. n += asBCTypeSize[asBCInfo[c].type];
  2854. }
  2855. for( n = 0; n < func->scriptData->objVariableInfo.GetLength(); n++ )
  2856. {
  2857. // The program position must be adjusted as it is stored in number of instructions
  2858. func->scriptData->objVariableInfo[n].programPos = instructionNbrToPos[func->scriptData->objVariableInfo[n].programPos];
  2859. func->scriptData->objVariableInfo[n].variableOffset = AdjustStackPosition(func->scriptData->objVariableInfo[n].variableOffset);
  2860. }
  2861. for (n = 0; n < func->scriptData->tryCatchInfo.GetLength(); n++)
  2862. {
  2863. func->scriptData->tryCatchInfo[n].tryPos = instructionNbrToPos[func->scriptData->tryCatchInfo[n].tryPos];
  2864. func->scriptData->tryCatchInfo[n].catchPos = instructionNbrToPos[func->scriptData->tryCatchInfo[n].catchPos];
  2865. }
  2866. // The program position (every even number) needs to be adjusted
  2867. // for the line numbers to be in number of dwords instead of number of instructions
  2868. for( n = 0; n < func->scriptData->lineNumbers.GetLength(); n += 2 )
  2869. func->scriptData->lineNumbers[n] = instructionNbrToPos[func->scriptData->lineNumbers[n]];
  2870. for( n = 0; n < func->scriptData->sectionIdxs.GetLength(); n += 2 )
  2871. func->scriptData->sectionIdxs[n] = instructionNbrToPos[func->scriptData->sectionIdxs[n]];
  2872. CalculateStackNeeded(func);
  2873. }
  2874. asCReader::SListAdjuster::SListAdjuster(asCReader *rd, asDWORD *bc, asCObjectType *listType) :
  2875. reader(rd), allocMemBC(bc), maxOffset(0), patternType(listType), repeatCount(0), lastOffset(-1), nextOffset(0), nextTypeId(-1)
  2876. {
  2877. asASSERT( patternType && (patternType->flags & asOBJ_LIST_PATTERN) );
  2878. // Find the first expected value in the list
  2879. asSListPatternNode *node = patternType->engine->scriptFunctions[patternType->templateSubTypes[0].GetBehaviour()->listFactory]->listPattern;
  2880. asASSERT( node && node->type == asLPT_START );
  2881. patternNode = node->next;
  2882. }
  2883. int asCReader::SListAdjuster::AdjustOffset(int offset)
  2884. {
  2885. if( offset < lastOffset )
  2886. {
  2887. reader->Error(TXT_INVALID_BYTECODE_d);
  2888. return 0;
  2889. }
  2890. // If it is the same offset being accessed again, just return the same adjusted value
  2891. if( lastOffset == offset )
  2892. return lastAdjustedOffset;
  2893. lastOffset = offset;
  2894. lastAdjustedOffset = maxOffset;
  2895. // What is being expected at this position?
  2896. if( patternNode->type == asLPT_REPEAT || patternNode->type == asLPT_REPEAT_SAME )
  2897. {
  2898. // Align the offset to 4 bytes boundary
  2899. if( maxOffset & 0x3 )
  2900. {
  2901. maxOffset += 4 - (maxOffset & 0x3);
  2902. lastAdjustedOffset = maxOffset;
  2903. }
  2904. // Don't move the patternNode yet because the caller must make a call to SetRepeatCount too
  2905. maxOffset += 4;
  2906. nextOffset = offset+1;
  2907. return lastAdjustedOffset;
  2908. }
  2909. else if( patternNode->type == asLPT_TYPE )
  2910. {
  2911. const asCDataType &dt = reinterpret_cast<asSListPatternDataTypeNode*>(patternNode)->dataType;
  2912. if( dt.GetTokenType() == ttQuestion )
  2913. {
  2914. if( nextTypeId != -1 )
  2915. {
  2916. if( repeatCount > 0 )
  2917. repeatCount--;
  2918. asCDataType nextdt = patternType->engine->GetDataTypeFromTypeId(nextTypeId);
  2919. asUINT size;
  2920. if(nextdt.IsObjectHandle() || (nextdt.GetTypeInfo() && (nextdt.GetTypeInfo()->flags & asOBJ_REF)) )
  2921. size = AS_PTR_SIZE*4;
  2922. else
  2923. size = nextdt.GetSizeInMemoryBytes();
  2924. // Align the offset to 4 bytes boundary
  2925. if( size >= 4 && (maxOffset & 0x3) )
  2926. {
  2927. maxOffset += 4 - (maxOffset & 0x3);
  2928. lastAdjustedOffset = maxOffset;
  2929. }
  2930. // Only move the patternNode if we're not expecting any more repeated entries
  2931. if( repeatCount == 0 )
  2932. patternNode = patternNode->next;
  2933. nextTypeId = -1;
  2934. maxOffset += size;
  2935. nextOffset = offset+1;
  2936. return lastAdjustedOffset;
  2937. }
  2938. else
  2939. {
  2940. // Align the offset to 4 bytes boundary
  2941. if( maxOffset & 0x3 )
  2942. {
  2943. maxOffset += 4 - (maxOffset & 0x3);
  2944. lastAdjustedOffset = maxOffset;
  2945. }
  2946. // The first adjustment is for the typeId
  2947. maxOffset += 4;
  2948. nextOffset = offset+1;
  2949. return lastAdjustedOffset;
  2950. }
  2951. }
  2952. else
  2953. {
  2954. // Determine the size of the element
  2955. asUINT size;
  2956. if( dt.IsObjectHandle() || (dt.GetTypeInfo() && (dt.GetTypeInfo()->flags & asOBJ_REF)) )
  2957. size = AS_PTR_SIZE*4;
  2958. else
  2959. size = dt.GetSizeInMemoryBytes();
  2960. // If values are skipped, the offset needs to be incremented
  2961. while( nextOffset <= offset )
  2962. {
  2963. if( repeatCount > 0 )
  2964. repeatCount--;
  2965. // Align the offset to 4 bytes boundary
  2966. if( size >= 4 && (maxOffset & 0x3) )
  2967. maxOffset += 4 - (maxOffset & 0x3);
  2968. lastAdjustedOffset = maxOffset;
  2969. nextOffset += 1;
  2970. maxOffset += size;
  2971. }
  2972. // Only move the patternNode if we're not expecting any more repeated entries
  2973. if( repeatCount == 0 )
  2974. patternNode = patternNode->next;
  2975. nextOffset = offset+1;
  2976. return lastAdjustedOffset;
  2977. }
  2978. }
  2979. else if( patternNode->type == asLPT_START )
  2980. {
  2981. if( repeatCount > 0 )
  2982. repeatCount--;
  2983. SInfo info = {repeatCount, patternNode};
  2984. stack.PushLast(info);
  2985. repeatCount = 0;
  2986. patternNode = patternNode->next;
  2987. lastOffset--;
  2988. return AdjustOffset(offset);
  2989. }
  2990. else if( patternNode->type == asLPT_END )
  2991. {
  2992. if( stack.GetLength() == 0 )
  2993. {
  2994. reader->Error(TXT_INVALID_BYTECODE_d);
  2995. return 0;
  2996. }
  2997. SInfo info = stack.PopLast();
  2998. repeatCount = info.repeatCount;
  2999. if( repeatCount )
  3000. patternNode = info.startNode;
  3001. else
  3002. patternNode = patternNode->next;
  3003. lastOffset--;
  3004. return AdjustOffset(offset);
  3005. }
  3006. else
  3007. {
  3008. // Something is wrong with the pattern list declaration
  3009. reader->Error(TXT_INVALID_BYTECODE_d);
  3010. return 0;
  3011. }
  3012. UNREACHABLE_RETURN;
  3013. }
  3014. void asCReader::SListAdjuster::SetRepeatCount(asUINT rc)
  3015. {
  3016. // Make sure the list is expecting a repeat at this location
  3017. asASSERT( patternNode->type == asLPT_REPEAT || patternNode->type == asLPT_REPEAT_SAME );
  3018. // Now move to the next patternNode
  3019. patternNode = patternNode->next;
  3020. repeatCount = rc;
  3021. }
  3022. void asCReader::SListAdjuster::AdjustAllocMem()
  3023. {
  3024. allocMemBC[1] = maxOffset;
  3025. }
  3026. void asCReader::SListAdjuster::SetNextType(int typeId)
  3027. {
  3028. asASSERT( nextTypeId == -1 );
  3029. nextTypeId = typeId;
  3030. }
  3031. void asCReader::CalculateStackNeeded(asCScriptFunction *func)
  3032. {
  3033. asASSERT( func->scriptData );
  3034. int largestStackUsed = 0;
  3035. // Clear the known stack size for each bytecode
  3036. asCArray<int> stackSize;
  3037. stackSize.SetLength(func->scriptData->byteCode.GetLength());
  3038. memset(&stackSize[0], -1, stackSize.GetLength()*4);
  3039. // Add the first instruction to the list of unchecked code
  3040. // paths and set the stack size at that instruction to variableSpace
  3041. asCArray<asUINT> paths;
  3042. paths.PushLast(0);
  3043. stackSize[0] = func->scriptData->variableSpace;
  3044. // Go through each of the code paths
  3045. for( asUINT p = 0; p < paths.GetLength(); ++p )
  3046. {
  3047. asUINT pos = paths[p];
  3048. int currStackSize = stackSize[pos];
  3049. asBYTE bc = *(asBYTE*)&func->scriptData->byteCode[pos];
  3050. if( bc == asBC_RET )
  3051. continue;
  3052. // Determine the change in stack size for this instruction
  3053. int stackInc = asBCInfo[bc].stackInc;
  3054. if( stackInc == 0xFFFF )
  3055. {
  3056. // Determine the true delta from the instruction arguments
  3057. if( bc == asBC_CALL ||
  3058. bc == asBC_CALLSYS ||
  3059. bc == asBC_Thiscall1 ||
  3060. bc == asBC_CALLBND ||
  3061. bc == asBC_ALLOC ||
  3062. bc == asBC_CALLINTF ||
  3063. bc == asBC_CallPtr )
  3064. {
  3065. asCScriptFunction *called = GetCalledFunction(func, pos);
  3066. if( called )
  3067. {
  3068. stackInc = -called->GetSpaceNeededForArguments();
  3069. if( called->objectType )
  3070. stackInc -= AS_PTR_SIZE;
  3071. if( called->DoesReturnOnStack() )
  3072. stackInc -= AS_PTR_SIZE;
  3073. }
  3074. else
  3075. {
  3076. // It is an allocation for an object without a constructor
  3077. asASSERT( bc == asBC_ALLOC );
  3078. stackInc = -AS_PTR_SIZE;
  3079. }
  3080. }
  3081. }
  3082. currStackSize += stackInc;
  3083. asASSERT( currStackSize >= 0 );
  3084. if( currStackSize > largestStackUsed )
  3085. largestStackUsed = currStackSize;
  3086. if( bc == asBC_JMP )
  3087. {
  3088. // Find the label that we should jump to
  3089. int offset = asBC_INTARG(&func->scriptData->byteCode[pos]);
  3090. pos += 2 + offset;
  3091. // Add the destination as a new path
  3092. if( stackSize[pos] == -1 )
  3093. {
  3094. stackSize[pos] = currStackSize;
  3095. paths.PushLast(pos);
  3096. }
  3097. else
  3098. asASSERT(stackSize[pos] == currStackSize);
  3099. continue;
  3100. }
  3101. else if( bc == asBC_JZ || bc == asBC_JNZ ||
  3102. bc == asBC_JLowZ || bc == asBC_JLowNZ ||
  3103. bc == asBC_JS || bc == asBC_JNS ||
  3104. bc == asBC_JP || bc == asBC_JNP )
  3105. {
  3106. // Find the label that is being jumped to
  3107. int offset = asBC_INTARG(&func->scriptData->byteCode[pos]);
  3108. // Add both paths to the code paths
  3109. pos += 2;
  3110. if( stackSize[pos] == -1 )
  3111. {
  3112. stackSize[pos] = currStackSize;
  3113. paths.PushLast(pos);
  3114. }
  3115. else
  3116. asASSERT(stackSize[pos] == currStackSize);
  3117. pos += offset;
  3118. if( stackSize[pos] == -1 )
  3119. {
  3120. stackSize[pos] = currStackSize;
  3121. paths.PushLast(pos);
  3122. }
  3123. else
  3124. asASSERT(stackSize[pos] == currStackSize);
  3125. continue;
  3126. }
  3127. else if( bc == asBC_JMPP )
  3128. {
  3129. pos++;
  3130. // Add all subsequent JMP instructions to the path
  3131. while( *(asBYTE*)&func->scriptData->byteCode[pos] == asBC_JMP )
  3132. {
  3133. if( stackSize[pos] == -1 )
  3134. {
  3135. stackSize[pos] = currStackSize;
  3136. paths.PushLast(pos);
  3137. }
  3138. else
  3139. asASSERT(stackSize[pos] == currStackSize);
  3140. pos += 2;
  3141. }
  3142. continue;
  3143. }
  3144. else
  3145. {
  3146. // Add next instruction to the paths
  3147. pos += asBCTypeSize[asBCInfo[bc].type];
  3148. if( stackSize[pos] == -1 )
  3149. {
  3150. stackSize[pos] = currStackSize;
  3151. paths.PushLast(pos);
  3152. }
  3153. else
  3154. asASSERT(stackSize[pos] == currStackSize);
  3155. continue;
  3156. }
  3157. }
  3158. func->scriptData->stackNeeded = largestStackUsed;
  3159. }
  3160. void asCReader::CalculateAdjustmentByPos(asCScriptFunction *func)
  3161. {
  3162. // Adjust the offset of all negative variables (parameters) as
  3163. // all pointers have been stored as having a size of 1 dword
  3164. asUINT n;
  3165. asCArray<int> adjustments;
  3166. asUINT offset = 0;
  3167. if( func->objectType )
  3168. {
  3169. adjustments.PushLast(offset);
  3170. adjustments.PushLast(1-AS_PTR_SIZE);
  3171. offset += 1;
  3172. }
  3173. if( func->DoesReturnOnStack() )
  3174. {
  3175. adjustments.PushLast(offset);
  3176. adjustments.PushLast(1-AS_PTR_SIZE);
  3177. offset += 1;
  3178. }
  3179. for( n = 0; n < func->parameterTypes.GetLength(); n++ )
  3180. {
  3181. if( !func->parameterTypes[n].IsPrimitive() ||
  3182. func->parameterTypes[n].IsReference() )
  3183. {
  3184. adjustments.PushLast(offset);
  3185. adjustments.PushLast(1-AS_PTR_SIZE);
  3186. offset += 1;
  3187. }
  3188. else
  3189. {
  3190. asASSERT( func->parameterTypes[n].IsPrimitive() );
  3191. offset += func->parameterTypes[n].GetSizeOnStackDWords();
  3192. }
  3193. }
  3194. // Build look-up table with the adjustments for each stack position
  3195. adjustNegativeStackByPos.SetLength(offset);
  3196. memset(adjustNegativeStackByPos.AddressOf(), 0, adjustNegativeStackByPos.GetLength()*sizeof(int));
  3197. for( n = 0; n < adjustments.GetLength(); n+=2 )
  3198. {
  3199. int pos = adjustments[n];
  3200. int adjust = adjustments[n+1];
  3201. for( asUINT i = pos+1; i < adjustNegativeStackByPos.GetLength(); i++ )
  3202. adjustNegativeStackByPos[i] += adjust;
  3203. }
  3204. // The bytecode has been stored as if all object variables take up only 1 dword.
  3205. // It is necessary to adjust to the size according to the current platform.
  3206. adjustments.SetLength(0);
  3207. int highestPos = 0;
  3208. for( n = 0; n < func->scriptData->objVariableTypes.GetLength(); n++ )
  3209. {
  3210. // Determine the size the variable currently occupies on the stack
  3211. int size = AS_PTR_SIZE;
  3212. // objVariableTypes is null if the type is a null pointer
  3213. if( func->scriptData->objVariableTypes[n] &&
  3214. (func->scriptData->objVariableTypes[n]->GetFlags() & asOBJ_VALUE) &&
  3215. n >= func->scriptData->objVariablesOnHeap )
  3216. {
  3217. size = func->scriptData->objVariableTypes[n]->GetSize();
  3218. if( size < 4 )
  3219. size = 1;
  3220. else
  3221. size /= 4;
  3222. }
  3223. // Check if type has a different size than stored
  3224. if( size > 1 )
  3225. {
  3226. if( func->scriptData->objVariablePos[n] > highestPos )
  3227. highestPos = func->scriptData->objVariablePos[n];
  3228. adjustments.PushLast(func->scriptData->objVariablePos[n]);
  3229. adjustments.PushLast(size-1);
  3230. }
  3231. }
  3232. // Count position 0 too
  3233. adjustByPos.SetLength(highestPos+1);
  3234. memset(adjustByPos.AddressOf(), 0, adjustByPos.GetLength()*sizeof(int));
  3235. // Build look-up table with the adjustments for each stack position
  3236. for( n = 0; n < adjustments.GetLength(); n+=2 )
  3237. {
  3238. int pos = adjustments[n];
  3239. int adjust = adjustments[n+1];
  3240. for( asUINT i = pos; i < adjustByPos.GetLength(); i++ )
  3241. adjustByPos[i] += adjust;
  3242. }
  3243. }
  3244. int asCReader::AdjustStackPosition(int pos)
  3245. {
  3246. if( pos >= (int)adjustByPos.GetLength() )
  3247. {
  3248. // It can be higher for primitives allocated on top of highest object variable
  3249. if( adjustByPos.GetLength() )
  3250. pos += (short)adjustByPos[adjustByPos.GetLength()-1];
  3251. }
  3252. else if( pos >= 0 )
  3253. pos += (short)adjustByPos[pos];
  3254. else if( -pos >= (int)adjustNegativeStackByPos.GetLength() )
  3255. Error(TXT_INVALID_BYTECODE_d);
  3256. else
  3257. pos += (short)adjustNegativeStackByPos[-pos];
  3258. return pos;
  3259. }
  3260. asCScriptFunction *asCReader::GetCalledFunction(asCScriptFunction *func, asDWORD programPos)
  3261. {
  3262. asBYTE bc = *(asBYTE*)&func->scriptData->byteCode[programPos];
  3263. if( bc == asBC_CALL ||
  3264. bc == asBC_CALLSYS ||
  3265. bc == asBC_Thiscall1 ||
  3266. bc == asBC_CALLINTF )
  3267. {
  3268. // Find the function from the function id in bytecode
  3269. int funcId = asBC_INTARG(&func->scriptData->byteCode[programPos]);
  3270. return engine->scriptFunctions[funcId];
  3271. }
  3272. else if( bc == asBC_ALLOC )
  3273. {
  3274. // Find the function from the function id in the bytecode
  3275. int funcId = asBC_INTARG(&func->scriptData->byteCode[programPos+AS_PTR_SIZE]);
  3276. return engine->scriptFunctions[funcId];
  3277. }
  3278. else if( bc == asBC_CALLBND )
  3279. {
  3280. // Find the function from the engine's bind array
  3281. int funcId = asBC_INTARG(&func->scriptData->byteCode[programPos]);
  3282. return engine->importedFunctions[funcId & ~FUNC_IMPORTED]->importedFunctionSignature;
  3283. }
  3284. else if( bc == asBC_CallPtr )
  3285. {
  3286. asUINT v;
  3287. int var = asBC_SWORDARG0(&func->scriptData->byteCode[programPos]);
  3288. // Find the funcdef from the local variable
  3289. for( v = 0; v < func->scriptData->objVariablePos.GetLength(); v++ )
  3290. if( func->scriptData->objVariablePos[v] == var )
  3291. return CastToFuncdefType(func->scriptData->objVariableTypes[v])->funcdef;
  3292. // Look in parameters
  3293. int paramPos = 0;
  3294. if( func->objectType )
  3295. paramPos -= AS_PTR_SIZE;
  3296. if( func->DoesReturnOnStack() )
  3297. paramPos -= AS_PTR_SIZE;
  3298. for( v = 0; v < func->parameterTypes.GetLength(); v++ )
  3299. {
  3300. if (var == paramPos)
  3301. {
  3302. if (func->parameterTypes[v].IsFuncdef())
  3303. return CastToFuncdefType(func->parameterTypes[v].GetTypeInfo())->funcdef;
  3304. else
  3305. {
  3306. error = true;
  3307. return 0;
  3308. }
  3309. }
  3310. paramPos -= func->parameterTypes[v].GetSizeOnStackDWords();
  3311. }
  3312. }
  3313. return 0;
  3314. }
  3315. int asCReader::AdjustGetOffset(int offset, asCScriptFunction *func, asDWORD programPos)
  3316. {
  3317. // TODO: optimize: multiple instructions for the same function doesn't need to look for the function everytime
  3318. // the function can remember where it found the function and check if the programPos is still valid
  3319. // Get offset 0 doesn't need adjustment
  3320. if( offset == 0 ) return 0;
  3321. bool bcAlloc = false;
  3322. // Find out which function that will be called
  3323. asCScriptFunction *calledFunc = 0;
  3324. int stackDelta = 0;
  3325. for( asUINT n = programPos; func->scriptData->byteCode.GetLength(); )
  3326. {
  3327. asBYTE bc = *(asBYTE*)&func->scriptData->byteCode[n];
  3328. if( bc == asBC_CALL ||
  3329. bc == asBC_CALLSYS ||
  3330. bc == asBC_Thiscall1 ||
  3331. bc == asBC_CALLINTF ||
  3332. bc == asBC_ALLOC ||
  3333. bc == asBC_CALLBND ||
  3334. bc == asBC_CallPtr )
  3335. {
  3336. // The alloc instruction allocates the object memory
  3337. // so it doesn't take the this pointer as input
  3338. if (bc == asBC_ALLOC)
  3339. bcAlloc = true;
  3340. calledFunc = GetCalledFunction(func, n);
  3341. break;
  3342. }
  3343. else if( bc == asBC_REFCPY ||
  3344. bc == asBC_COPY )
  3345. {
  3346. // In this case we know there is only 1 pointer on the stack above
  3347. asASSERT( offset == 1 );
  3348. return offset - (1 - AS_PTR_SIZE);
  3349. }
  3350. // Keep track of the stack size between the
  3351. // instruction that needs to be adjusted and the call
  3352. stackDelta += asBCInfo[bc].stackInc;
  3353. n += asBCTypeSize[asBCInfo[bc].type];
  3354. }
  3355. if( calledFunc == 0 )
  3356. {
  3357. Error(TXT_INVALID_BYTECODE_d);
  3358. return offset;
  3359. }
  3360. // Count the number of pointers pushed on the stack above the
  3361. // current offset, and then adjust the offset accordingly
  3362. asUINT numPtrs = 0;
  3363. int currOffset = -stackDelta;
  3364. if( offset > currOffset && calledFunc->GetObjectType() && !bcAlloc )
  3365. {
  3366. currOffset++;
  3367. if( currOffset > 0 )
  3368. numPtrs++;
  3369. #if AS_PTR_SIZE == 2
  3370. // For 64bit platforms it is necessary to increment the currOffset by one more
  3371. // DWORD since the stackDelta was counting the full 64bit size of the pointer
  3372. else if( stackDelta )
  3373. currOffset++;
  3374. #endif
  3375. }
  3376. if( offset > currOffset && calledFunc->DoesReturnOnStack() )
  3377. {
  3378. currOffset++;
  3379. if( currOffset > 0 )
  3380. numPtrs++;
  3381. #if AS_PTR_SIZE == 2
  3382. // For 64bit platforms it is necessary to increment the currOffset by one more
  3383. // DWORD since the stackDelta was counting the full 64bit size of the pointer
  3384. else if( stackDelta )
  3385. currOffset++;
  3386. #endif
  3387. }
  3388. for( asUINT p = 0; p < calledFunc->parameterTypes.GetLength(); p++ )
  3389. {
  3390. if( offset <= currOffset ) break;
  3391. if( !calledFunc->parameterTypes[p].IsPrimitive() ||
  3392. calledFunc->parameterTypes[p].IsReference() )
  3393. {
  3394. currOffset++;
  3395. if( currOffset > 0 )
  3396. numPtrs++;
  3397. #if AS_PTR_SIZE == 2
  3398. // For 64bit platforms it is necessary to increment the currOffset by one more
  3399. // DWORD since the stackDelta was counting the full 64bit size of the pointer
  3400. else if( stackDelta )
  3401. currOffset++;
  3402. #endif
  3403. // The variable arg ? has an additiona 32bit integer with the typeid
  3404. if( calledFunc->parameterTypes[p].IsAnyType() )
  3405. currOffset += 1;
  3406. }
  3407. else
  3408. {
  3409. // Enums or built-in primitives are passed by value
  3410. asASSERT( calledFunc->parameterTypes[p].IsPrimitive() );
  3411. currOffset += calledFunc->parameterTypes[p].GetSizeOnStackDWords();
  3412. }
  3413. }
  3414. return offset - numPtrs * (1 - AS_PTR_SIZE);
  3415. }
  3416. int asCReader::FindTypeId(int idx)
  3417. {
  3418. if( idx >= 0 && idx < (int)usedTypeIds.GetLength() )
  3419. return usedTypeIds[idx];
  3420. else
  3421. {
  3422. Error(TXT_INVALID_BYTECODE_d);
  3423. return 0;
  3424. }
  3425. }
  3426. asCTypeInfo *asCReader::FindType(int idx)
  3427. {
  3428. if( idx < 0 || idx >= (int)usedTypes.GetLength() )
  3429. {
  3430. Error(TXT_INVALID_BYTECODE_d);
  3431. return 0;
  3432. }
  3433. return usedTypes[idx];
  3434. }
  3435. #ifndef AS_NO_COMPILER
  3436. asCWriter::asCWriter(asCModule* _module, asIBinaryStream* _stream, asCScriptEngine* _engine, bool _stripDebug)
  3437. : module(_module), stream(_stream), engine(_engine), stripDebugInfo(_stripDebug), error(false), bytesWritten(0)
  3438. {
  3439. }
  3440. int asCWriter::Error(const char *msg)
  3441. {
  3442. // Don't write if it has already been reported an error earlier
  3443. if (!error)
  3444. {
  3445. asCString str;
  3446. str.Format(msg, bytesWritten);
  3447. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  3448. error = true;
  3449. }
  3450. return asERROR;
  3451. }
  3452. int asCWriter::WriteData(const void *data, asUINT size)
  3453. {
  3454. asASSERT(size == 1 || size == 2 || size == 4 || size == 8);
  3455. int ret = 0;
  3456. #if defined(AS_BIG_ENDIAN)
  3457. for( asUINT n = 0; ret >= 0 && n < size; n++ )
  3458. ret = stream->Write(((asBYTE*)data)+n, 1);
  3459. #else
  3460. for( int n = size-1; ret >= 0 && n >= 0; n-- )
  3461. ret = stream->Write(((asBYTE*)data)+n, 1);
  3462. #endif
  3463. if (ret < 0)
  3464. Error(TXT_UNEXPECTED_END_OF_FILE);
  3465. bytesWritten += size;
  3466. return ret;
  3467. }
  3468. int asCWriter::Write()
  3469. {
  3470. TimeIt("asCWriter::Write");
  3471. unsigned long i, count;
  3472. // Store everything in the same order that the builder parses scripts
  3473. // TODO: Should be possible to skip saving the enum values. They are usually not needed after the script is compiled anyway
  3474. // TODO: Should be possible to skip saving the typedefs. They are usually not needed after the script is compiled anyway
  3475. // TODO: Should be possible to skip saving constants. They are usually not needed after the script is compiled anyway
  3476. // Write the flag as 1byte even on platforms with 4byte booleans
  3477. WriteEncodedInt64(stripDebugInfo ? 1 : 0);
  3478. // Store enums
  3479. {
  3480. TimeIt("store enums");
  3481. count = (asUINT)module->m_enumTypes.GetLength();
  3482. WriteEncodedInt64(count);
  3483. for( i = 0; i < count; i++ )
  3484. {
  3485. WriteTypeDeclaration(module->m_enumTypes[i], 1);
  3486. WriteTypeDeclaration(module->m_enumTypes[i], 2);
  3487. }
  3488. }
  3489. // Store type declarations first
  3490. {
  3491. TimeIt("type declarations");
  3492. count = (asUINT)module->m_classTypes.GetLength();
  3493. WriteEncodedInt64(count);
  3494. for( i = 0; i < count; i++ )
  3495. {
  3496. // Store only the name of the class/interface types
  3497. WriteTypeDeclaration(module->m_classTypes[i], 1);
  3498. }
  3499. }
  3500. // Store func defs
  3501. {
  3502. TimeIt("func defs");
  3503. count = (asUINT)module->m_funcDefs.GetLength();
  3504. WriteEncodedInt64(count);
  3505. for( i = 0; i < count; i++ )
  3506. WriteFunction(module->m_funcDefs[i]->funcdef);
  3507. }
  3508. // Now store all interface methods
  3509. {
  3510. TimeIt("interface methods");
  3511. count = (asUINT)module->m_classTypes.GetLength();
  3512. for( i = 0; i < count; i++ )
  3513. {
  3514. if( module->m_classTypes[i]->IsInterface() )
  3515. WriteTypeDeclaration(module->m_classTypes[i], 2);
  3516. }
  3517. }
  3518. // Then store the class methods and behaviours
  3519. {
  3520. TimeIt("class methods and behaviours");
  3521. for( i = 0; i < count; ++i )
  3522. {
  3523. if( !module->m_classTypes[i]->IsInterface() )
  3524. WriteTypeDeclaration(module->m_classTypes[i], 2);
  3525. }
  3526. }
  3527. // Then store the class properties
  3528. {
  3529. TimeIt("class properties");
  3530. for( i = 0; i < count; ++i )
  3531. {
  3532. if( !module->m_classTypes[i]->IsInterface() )
  3533. WriteTypeDeclaration(module->m_classTypes[i], 3);
  3534. }
  3535. }
  3536. // Store typedefs
  3537. {
  3538. TimeIt("type defs");
  3539. count = (asUINT)module->m_typeDefs.GetLength();
  3540. WriteEncodedInt64(count);
  3541. for( i = 0; i < count; i++ )
  3542. {
  3543. WriteTypeDeclaration(module->m_typeDefs[i], 1);
  3544. WriteTypeDeclaration(module->m_typeDefs[i], 2);
  3545. }
  3546. }
  3547. // scriptGlobals[]
  3548. {
  3549. TimeIt("script globals");
  3550. count = (asUINT)module->m_scriptGlobals.GetSize();
  3551. WriteEncodedInt64(count);
  3552. asCSymbolTable<asCGlobalProperty>::iterator it = module->m_scriptGlobals.List();
  3553. for( ; it; it++ )
  3554. WriteGlobalProperty(*it);
  3555. }
  3556. // scriptFunctions[]
  3557. {
  3558. TimeIt("scriptFunctions");
  3559. count = 0;
  3560. for( i = 0; i < module->m_scriptFunctions.GetLength(); i++ )
  3561. if( module->m_scriptFunctions[i]->objectType == 0 )
  3562. count++;
  3563. WriteEncodedInt64(count);
  3564. for( i = 0; i < module->m_scriptFunctions.GetLength(); ++i )
  3565. if( module->m_scriptFunctions[i]->objectType == 0 )
  3566. WriteFunction(module->m_scriptFunctions[i]);
  3567. }
  3568. // globalFunctions[]
  3569. {
  3570. TimeIt("globalFunctions");
  3571. count = (int)module->m_globalFunctions.GetSize();
  3572. asCSymbolTable<asCScriptFunction>::iterator funcIt = module->m_globalFunctions.List();
  3573. WriteEncodedInt64(count);
  3574. while( funcIt )
  3575. {
  3576. WriteFunction(*funcIt);
  3577. funcIt++;
  3578. }
  3579. }
  3580. // bindInformations[]
  3581. {
  3582. TimeIt("bindInformations");
  3583. count = (asUINT)module->m_bindInformations.GetLength();
  3584. WriteEncodedInt64(count);
  3585. for( i = 0; i < count; ++i )
  3586. {
  3587. WriteFunction(module->m_bindInformations[i]->importedFunctionSignature);
  3588. WriteString(&module->m_bindInformations[i]->importFromModule);
  3589. }
  3590. }
  3591. // usedTypes[]
  3592. {
  3593. TimeIt("usedTypes");
  3594. count = (asUINT)usedTypes.GetLength();
  3595. WriteEncodedInt64(count);
  3596. for( i = 0; i < count; ++i )
  3597. WriteTypeInfo(usedTypes[i]);
  3598. }
  3599. // usedTypeIds[]
  3600. WriteUsedTypeIds();
  3601. // usedFunctions[]
  3602. WriteUsedFunctions();
  3603. // usedGlobalProperties[]
  3604. WriteUsedGlobalProps();
  3605. // usedStringConstants[]
  3606. WriteUsedStringConstants();
  3607. // usedObjectProperties[]
  3608. WriteUsedObjectProps();
  3609. return error ? asERROR : asSUCCESS;
  3610. }
  3611. int asCWriter::FindStringConstantIndex(void *str)
  3612. {
  3613. asSMapNode<void*, int> *cursor = 0;
  3614. if (stringToIndexMap.MoveTo(&cursor, str))
  3615. return cursor->value;
  3616. usedStringConstants.PushLast(str);
  3617. int index = int(usedStringConstants.GetLength() - 1);
  3618. stringToIndexMap.Insert(str, index);
  3619. return index;
  3620. }
  3621. void asCWriter::WriteUsedStringConstants()
  3622. {
  3623. TimeIt("asCWriter::WriteUsedStringConstants");
  3624. asUINT count = (asUINT)usedStringConstants.GetLength();
  3625. WriteEncodedInt64(count);
  3626. asCString str;
  3627. for (asUINT i = 0; i < count; ++i)
  3628. {
  3629. asUINT length;
  3630. engine->stringFactory->GetRawStringData(usedStringConstants[i], 0, &length);
  3631. str.SetLength(length);
  3632. engine->stringFactory->GetRawStringData(usedStringConstants[i], str.AddressOf(), &length);
  3633. WriteString(&str);
  3634. }
  3635. }
  3636. void asCWriter::WriteUsedFunctions()
  3637. {
  3638. TimeIt("asCWriter::WriteUsedFunctions");
  3639. asUINT count = (asUINT)usedFunctions.GetLength();
  3640. WriteEncodedInt64(count);
  3641. for( asUINT n = 0; n < usedFunctions.GetLength(); n++ )
  3642. {
  3643. char c;
  3644. // Write enough data to be able to uniquely identify the function upon load
  3645. asCScriptFunction *func = usedFunctions[n];
  3646. if(func)
  3647. {
  3648. // Is the function from the module or the application?
  3649. c = func->module ? 'm' : 'a';
  3650. // Functions and methods that are shared should be stored as 's' as the bytecode
  3651. // may be imported from other modules (even if the current module have received ownership)
  3652. if (c == 'm' && func->IsShared() )
  3653. c = 's';
  3654. WriteData(&c, 1);
  3655. WriteFunctionSignature(func);
  3656. }
  3657. else
  3658. {
  3659. // null function pointer
  3660. c = 'n';
  3661. WriteData(&c, 1);
  3662. }
  3663. }
  3664. }
  3665. void asCWriter::WriteFunctionSignature(asCScriptFunction *func)
  3666. {
  3667. asUINT i, count;
  3668. WriteString(&func->name);
  3669. if( func->name == DELEGATE_FACTORY )
  3670. {
  3671. // It's not necessary to write anything else
  3672. return;
  3673. }
  3674. WriteDataType(&func->returnType);
  3675. count = (asUINT)func->parameterTypes.GetLength();
  3676. WriteEncodedInt64(count);
  3677. for( i = 0; i < count; ++i )
  3678. WriteDataType(&func->parameterTypes[i]);
  3679. // Only write the inout flags if any of them are set
  3680. // If the number of parameters is 0, then no need to save this
  3681. if (func->parameterTypes.GetLength() > 0)
  3682. {
  3683. count = 0;
  3684. for (i = asUINT(func->inOutFlags.GetLength()); i > 0; i--)
  3685. if (func->inOutFlags[i - 1] != asTM_NONE)
  3686. {
  3687. count = i;
  3688. break;
  3689. }
  3690. WriteEncodedInt64(count);
  3691. for (i = 0; i < count; ++i)
  3692. WriteEncodedInt64(func->inOutFlags[i]);
  3693. }
  3694. WriteEncodedInt64(func->funcType);
  3695. // Write the default args, from last to first
  3696. // If the number of parameters is 0, then no need to save this
  3697. if (func->parameterTypes.GetLength() > 0)
  3698. {
  3699. count = 0;
  3700. for (i = (asUINT)func->defaultArgs.GetLength(); i-- > 0; )
  3701. if (func->defaultArgs[i])
  3702. count++;
  3703. WriteEncodedInt64(count);
  3704. for (i = (asUINT)func->defaultArgs.GetLength(); i-- > 0; )
  3705. if (func->defaultArgs[i])
  3706. WriteString(func->defaultArgs[i]);
  3707. }
  3708. WriteTypeInfo(func->objectType);
  3709. if( func->objectType )
  3710. {
  3711. asBYTE b = 0;
  3712. b += func->IsReadOnly() ? 1 : 0;
  3713. b += func->IsPrivate() ? 2 : 0;
  3714. b += func->IsProtected() ? 4 : 0;
  3715. WriteData(&b, 1);
  3716. }
  3717. else
  3718. {
  3719. if (func->funcType == asFUNC_FUNCDEF)
  3720. {
  3721. if (func->nameSpace)
  3722. {
  3723. // This funcdef was declared as global entity
  3724. asBYTE b = 'n';
  3725. WriteData(&b, 1);
  3726. WriteString(&func->nameSpace->name);
  3727. }
  3728. else
  3729. {
  3730. // This funcdef was declared as class member
  3731. asBYTE b = 'o';
  3732. WriteData(&b, 1);
  3733. WriteTypeInfo(func->funcdefType->parentClass);
  3734. }
  3735. }
  3736. else
  3737. WriteString(&func->nameSpace->name);
  3738. }
  3739. }
  3740. void asCWriter::WriteFunction(asCScriptFunction* func)
  3741. {
  3742. char c;
  3743. // If there is no function, then store a null char
  3744. if( func == 0 )
  3745. {
  3746. c = '\0';
  3747. WriteData(&c, 1);
  3748. return;
  3749. }
  3750. // First check if the function has been saved already
  3751. for( asUINT f = 0; f < savedFunctions.GetLength(); f++ )
  3752. {
  3753. if( savedFunctions[f] == func )
  3754. {
  3755. c = 'r';
  3756. WriteData(&c, 1);
  3757. WriteEncodedInt64(f);
  3758. return;
  3759. }
  3760. }
  3761. // Keep a reference to the function in the list
  3762. savedFunctions.PushLast(func);
  3763. c = 'f';
  3764. WriteData(&c, 1);
  3765. asUINT i, count;
  3766. WriteFunctionSignature(func);
  3767. if( func->funcType == asFUNC_SCRIPT )
  3768. {
  3769. // Skip this for external shared entities
  3770. if (module->m_externalTypes.IndexOf(func->objectType) >= 0)
  3771. return;
  3772. char bits = 0;
  3773. bits += func->IsShared() ? 1 : 0;
  3774. bits += func->dontCleanUpOnException ? 2 : 0;
  3775. if (module->m_externalFunctions.IndexOf(func) >= 0)
  3776. bits += 4;
  3777. if (func->scriptData->objVariablePos.GetLength() || func->scriptData->objVariableInfo.GetLength())
  3778. bits += 8;
  3779. if (func->scriptData->tryCatchInfo.GetLength())
  3780. bits += 16;
  3781. bits += func->IsExplicit() ? 32 : 0;
  3782. WriteData(&bits, 1);
  3783. // For external shared functions the rest is not needed
  3784. if (bits & 4)
  3785. return;
  3786. // Calculate the adjustment by position lookup table
  3787. CalculateAdjustmentByPos(func);
  3788. WriteByteCode(func);
  3789. asDWORD varSpace = AdjustStackPosition(func->scriptData->variableSpace);
  3790. WriteEncodedInt64(varSpace);
  3791. if (bits & 8)
  3792. {
  3793. count = (asUINT)func->scriptData->objVariablePos.GetLength();
  3794. WriteEncodedInt64(count);
  3795. for (i = 0; i < count; ++i)
  3796. {
  3797. WriteTypeInfo(func->scriptData->objVariableTypes[i]);
  3798. WriteEncodedInt64(AdjustStackPosition(func->scriptData->objVariablePos[i]));
  3799. }
  3800. if (count > 0)
  3801. WriteEncodedInt64(func->scriptData->objVariablesOnHeap);
  3802. WriteEncodedInt64((asUINT)func->scriptData->objVariableInfo.GetLength());
  3803. for (i = 0; i < func->scriptData->objVariableInfo.GetLength(); ++i)
  3804. {
  3805. // The program position must be adjusted to be in number of instructions
  3806. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->objVariableInfo[i].programPos]);
  3807. WriteEncodedInt64(AdjustStackPosition(func->scriptData->objVariableInfo[i].variableOffset));
  3808. WriteEncodedInt64(func->scriptData->objVariableInfo[i].option);
  3809. }
  3810. }
  3811. if (bits & 16)
  3812. {
  3813. // Write info on try/catch blocks
  3814. WriteEncodedInt64((asUINT)func->scriptData->tryCatchInfo.GetLength());
  3815. for (i = 0; i < func->scriptData->tryCatchInfo.GetLength(); ++i)
  3816. {
  3817. // The program position must be adjusted to be in number of instructions
  3818. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->tryCatchInfo[i].tryPos]);
  3819. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->tryCatchInfo[i].catchPos]);
  3820. }
  3821. }
  3822. // The program position (every even number) needs to be adjusted
  3823. // to be in number of instructions instead of DWORD offset
  3824. if( !stripDebugInfo )
  3825. {
  3826. asUINT length = (asUINT)func->scriptData->lineNumbers.GetLength();
  3827. WriteEncodedInt64(length);
  3828. for( i = 0; i < length; ++i )
  3829. {
  3830. if( (i & 1) == 0 )
  3831. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->lineNumbers[i]]);
  3832. else
  3833. WriteEncodedInt64(func->scriptData->lineNumbers[i]);
  3834. }
  3835. // Write the array of script sections
  3836. length = (asUINT)func->scriptData->sectionIdxs.GetLength();
  3837. WriteEncodedInt64(length);
  3838. for( i = 0; i < length; ++i )
  3839. {
  3840. if( (i & 1) == 0 )
  3841. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->sectionIdxs[i]]);
  3842. else
  3843. {
  3844. if( func->scriptData->sectionIdxs[i] >= 0 )
  3845. WriteString(engine->scriptSectionNames[func->scriptData->sectionIdxs[i]]);
  3846. else
  3847. {
  3848. c = 0;
  3849. WriteData(&c, 1);
  3850. }
  3851. }
  3852. }
  3853. }
  3854. // Write the variable information
  3855. if( !stripDebugInfo )
  3856. {
  3857. WriteEncodedInt64((asUINT)func->scriptData->variables.GetLength());
  3858. for( i = 0; i < func->scriptData->variables.GetLength(); i++ )
  3859. {
  3860. // The program position must be adjusted to be in number of instructions
  3861. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->variables[i]->declaredAtProgramPos]);
  3862. // The stack position must be adjusted according to the pointer sizes
  3863. WriteEncodedInt64(AdjustStackPosition(func->scriptData->variables[i]->stackOffset));
  3864. WriteString(&func->scriptData->variables[i]->name);
  3865. WriteDataType(&func->scriptData->variables[i]->type);
  3866. }
  3867. }
  3868. // Store script section name
  3869. if( !stripDebugInfo )
  3870. {
  3871. if( func->scriptData->scriptSectionIdx >= 0 )
  3872. WriteString(engine->scriptSectionNames[func->scriptData->scriptSectionIdx]);
  3873. else
  3874. {
  3875. c = 0;
  3876. WriteData(&c, 1);
  3877. }
  3878. WriteEncodedInt64(func->scriptData->declaredAt);
  3879. }
  3880. // Store the parameter names
  3881. if( !stripDebugInfo )
  3882. {
  3883. count = asUINT(func->parameterNames.GetLength());
  3884. WriteEncodedInt64(count);
  3885. for( asUINT n = 0; n < count; n++ )
  3886. WriteString(&func->parameterNames[n]);
  3887. }
  3888. }
  3889. else if( func->funcType == asFUNC_VIRTUAL || func->funcType == asFUNC_INTERFACE )
  3890. {
  3891. // TODO: Do we really need to store this? It can probably be reconstructed by the reader
  3892. WriteEncodedInt64(func->vfTableIdx);
  3893. }
  3894. else if( func->funcType == asFUNC_FUNCDEF )
  3895. {
  3896. char bits = 0;
  3897. bits += func->IsShared() ? 1 : 0;
  3898. if (module->m_externalTypes.IndexOf(func->funcdefType) >= 0)
  3899. bits += 2;
  3900. WriteData(&bits,1);
  3901. }
  3902. }
  3903. void asCWriter::WriteTypeDeclaration(asCTypeInfo *type, int phase)
  3904. {
  3905. if( phase == 1 )
  3906. {
  3907. // name
  3908. WriteString(&type->name);
  3909. // flags
  3910. WriteData(&type->flags, 4);
  3911. // size
  3912. // TODO: Do we really need to store this? The reader should be able to
  3913. // determine the correct size from the object type's flags
  3914. if( (type->flags & asOBJ_SCRIPT_OBJECT) && type->size > 0 )
  3915. {
  3916. // The size for script objects may vary from platform to platform so
  3917. // only store 1 to diferentiate from interfaces that have size 0.
  3918. WriteEncodedInt64(1);
  3919. }
  3920. else
  3921. {
  3922. // Enums, typedefs, and interfaces have fixed sizes independently
  3923. // of platform so it is safe to serialize the size directly.
  3924. WriteEncodedInt64(type->size);
  3925. }
  3926. // namespace
  3927. WriteString(&type->nameSpace->name);
  3928. // external shared flag
  3929. if ((type->flags & asOBJ_SHARED))
  3930. {
  3931. char c = ' ';
  3932. if (module->m_externalTypes.IndexOf(type) >= 0)
  3933. c = 'e';
  3934. WriteData(&c, 1);
  3935. }
  3936. }
  3937. else if( phase == 2 )
  3938. {
  3939. // external shared types doesn't need to save this
  3940. if ((type->flags & asOBJ_SHARED) && module->m_externalTypes.IndexOf(type) >= 0)
  3941. return;
  3942. if(type->flags & asOBJ_ENUM )
  3943. {
  3944. // enumValues[]
  3945. asCEnumType *t = CastToEnumType(type);
  3946. int size = (int)t->enumValues.GetLength();
  3947. WriteEncodedInt64(size);
  3948. for( int n = 0; n < size; n++ )
  3949. {
  3950. WriteString(&t->enumValues[n]->name);
  3951. WriteData(&t->enumValues[n]->value, 4);
  3952. }
  3953. }
  3954. else if(type->flags & asOBJ_TYPEDEF )
  3955. {
  3956. asCTypedefType *td = CastToTypedefType(type);
  3957. eTokenType t = td->aliasForType.GetTokenType();
  3958. WriteEncodedInt64(t);
  3959. }
  3960. else
  3961. {
  3962. asCObjectType *t = CastToObjectType(type);
  3963. WriteTypeInfo(t->derivedFrom);
  3964. // interfaces[] / interfaceVFTOffsets[]
  3965. // TOOD: Is it really necessary to store the VFTOffsets? Can't the reader calculate those?
  3966. int size = (asUINT)t->interfaces.GetLength();
  3967. WriteEncodedInt64(size);
  3968. asUINT n;
  3969. asASSERT( t->IsInterface() || t->interfaces.GetLength() == t->interfaceVFTOffsets.GetLength() );
  3970. for( n = 0; n < t->interfaces.GetLength(); n++ )
  3971. {
  3972. WriteTypeInfo(t->interfaces[n]);
  3973. if( !t->IsInterface() )
  3974. WriteEncodedInt64(t->interfaceVFTOffsets[n]);
  3975. }
  3976. // behaviours
  3977. // TODO: Default behaviours should just be stored as a indicator
  3978. // to avoid storing the actual function object
  3979. if( !t->IsInterface() && type->flags != asOBJ_TYPEDEF && type->flags != asOBJ_ENUM )
  3980. {
  3981. WriteFunction(engine->scriptFunctions[t->beh.destruct]);
  3982. size = (int)t->beh.constructors.GetLength();
  3983. WriteEncodedInt64(size);
  3984. for( n = 0; n < t->beh.constructors.GetLength(); n++ )
  3985. {
  3986. WriteFunction(engine->scriptFunctions[t->beh.constructors[n]]);
  3987. WriteFunction(engine->scriptFunctions[t->beh.factories[n]]);
  3988. }
  3989. }
  3990. // methods[]
  3991. // TODO: Avoid storing inherited methods in interfaces, as the reader
  3992. // can add those directly from the base interface
  3993. size = (int)t->methods.GetLength();
  3994. WriteEncodedInt64(size);
  3995. for( n = 0; n < t->methods.GetLength(); n++ )
  3996. {
  3997. WriteFunction(engine->scriptFunctions[t->methods[n]]);
  3998. }
  3999. // virtualFunctionTable[]
  4000. // TODO: Is it really necessary to store this? Can't it be easily rebuilt by the reader
  4001. size = (int)t->virtualFunctionTable.GetLength();
  4002. WriteEncodedInt64(size);
  4003. for( n = 0; n < (asUINT)size; n++ )
  4004. {
  4005. WriteFunction(t->virtualFunctionTable[n]);
  4006. }
  4007. }
  4008. }
  4009. else if( phase == 3 )
  4010. {
  4011. // external shared types doesn't need to save this
  4012. if ((type->flags & asOBJ_SHARED) && module->m_externalTypes.IndexOf(type) >= 0)
  4013. return;
  4014. // properties[]
  4015. asCObjectType *t = CastToObjectType(type);
  4016. // This is only done for object types
  4017. asASSERT(t);
  4018. asUINT size = (asUINT)t->properties.GetLength();
  4019. WriteEncodedInt64(size);
  4020. for (asUINT n = 0; n < t->properties.GetLength(); n++)
  4021. {
  4022. WriteObjectProperty(t->properties[n]);
  4023. }
  4024. }
  4025. }
  4026. void asCWriter::WriteEncodedInt64(asINT64 i)
  4027. {
  4028. asBYTE signBit = ( i & asINT64(1)<<63 ) ? 0x80 : 0;
  4029. if( signBit ) i = -i;
  4030. asBYTE b;
  4031. if( i < (1<<6) )
  4032. {
  4033. b = (asBYTE)(signBit + i); WriteData(&b, 1);
  4034. }
  4035. else if( i < (1<<13) )
  4036. {
  4037. b = asBYTE(0x40 + signBit + (i >> 8)); WriteData(&b, 1);
  4038. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  4039. }
  4040. else if( i < (1<<20) )
  4041. {
  4042. b = asBYTE(0x60 + signBit + (i >> 16)); WriteData(&b, 1);
  4043. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  4044. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  4045. }
  4046. else if( i < (1<<27) )
  4047. {
  4048. b = asBYTE(0x70 + signBit + (i >> 24)); WriteData(&b, 1);
  4049. b = asBYTE((i >> 16) & 0xFF); WriteData(&b, 1);
  4050. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  4051. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  4052. }
  4053. else if( i < (asINT64(1)<<34) )
  4054. {
  4055. b = asBYTE(0x78 + signBit + (i >> 32)); WriteData(&b, 1);
  4056. b = asBYTE((i >> 24) & 0xFF); WriteData(&b, 1);
  4057. b = asBYTE((i >> 16) & 0xFF); WriteData(&b, 1);
  4058. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  4059. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  4060. }
  4061. else if( i < (asINT64(1)<<41) )
  4062. {
  4063. b = asBYTE(0x7C + signBit + (i >> 40)); WriteData(&b, 1);
  4064. b = asBYTE((i >> 32) & 0xFF); WriteData(&b, 1);
  4065. b = asBYTE((i >> 24) & 0xFF); WriteData(&b, 1);
  4066. b = asBYTE((i >> 16) & 0xFF); WriteData(&b, 1);
  4067. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  4068. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  4069. }
  4070. else if( i < (asINT64(1)<<48) )
  4071. {
  4072. b = asBYTE(0x7E + signBit + (i >> 48)); WriteData(&b, 1);
  4073. b = asBYTE((i >> 40) & 0xFF); WriteData(&b, 1);
  4074. b = asBYTE((i >> 32) & 0xFF); WriteData(&b, 1);
  4075. b = asBYTE((i >> 24) & 0xFF); WriteData(&b, 1);
  4076. b = asBYTE((i >> 16) & 0xFF); WriteData(&b, 1);
  4077. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  4078. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  4079. }
  4080. else
  4081. {
  4082. b = asBYTE(0x7F + signBit); WriteData(&b, 1);
  4083. b = asBYTE((i >> 56) & 0xFF); WriteData(&b, 1);
  4084. b = asBYTE((i >> 48) & 0xFF); WriteData(&b, 1);
  4085. b = asBYTE((i >> 40) & 0xFF); WriteData(&b, 1);
  4086. b = asBYTE((i >> 32) & 0xFF); WriteData(&b, 1);
  4087. b = asBYTE((i >> 24) & 0xFF); WriteData(&b, 1);
  4088. b = asBYTE((i >> 16) & 0xFF); WriteData(&b, 1);
  4089. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  4090. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  4091. }
  4092. }
  4093. void asCWriter::WriteString(asCString* str)
  4094. {
  4095. // First check if the string hasn't been saved already
  4096. asSMapNode<asCString, int> *cursor = 0;
  4097. if (stringToIdMap.MoveTo(&cursor, *str))
  4098. {
  4099. // Save a reference to the existing string
  4100. // The lowest bit is set to 1 to indicate a reference
  4101. WriteEncodedInt64(cursor->value*2+1);
  4102. return;
  4103. }
  4104. // Save a new string
  4105. // The lowest bit is set to 0 to indicate a new string
  4106. asUINT len = (asUINT)str->GetLength();
  4107. WriteEncodedInt64(len*2);
  4108. if( len > 0 )
  4109. {
  4110. stream->Write(str->AddressOf(), (asUINT)len);
  4111. bytesWritten += len;
  4112. savedStrings.PushLast(*str);
  4113. stringToIdMap.Insert(*str, int(savedStrings.GetLength()) - 1);
  4114. }
  4115. }
  4116. void asCWriter::WriteGlobalProperty(asCGlobalProperty* prop)
  4117. {
  4118. // TODO: We might be able to avoid storing the name and type of the global
  4119. // properties twice if we merge this with the WriteUsedGlobalProperties.
  4120. WriteString(&prop->name);
  4121. WriteString(&prop->nameSpace->name);
  4122. WriteDataType(&prop->type);
  4123. // Store the initialization function
  4124. WriteFunction(prop->GetInitFunc());
  4125. }
  4126. void asCWriter::WriteObjectProperty(asCObjectProperty* prop)
  4127. {
  4128. WriteString(&prop->name);
  4129. WriteDataType(&prop->type);
  4130. int flags = 0;
  4131. if( prop->isPrivate ) flags |= 1;
  4132. if( prop->isProtected ) flags |= 2;
  4133. if( prop->isInherited ) flags |= 4;
  4134. WriteEncodedInt64(flags);
  4135. }
  4136. void asCWriter::WriteDataType(const asCDataType *dt)
  4137. {
  4138. // First check if the datatype has already been saved
  4139. for( asUINT n = 0; n < savedDataTypes.GetLength(); n++ )
  4140. {
  4141. if( *dt == savedDataTypes[n] )
  4142. {
  4143. WriteEncodedInt64(n+1);
  4144. return;
  4145. }
  4146. }
  4147. // Indicate a new type with a null byte
  4148. asUINT c = 0;
  4149. WriteEncodedInt64(c);
  4150. // Save the new datatype
  4151. savedDataTypes.PushLast(*dt);
  4152. int t = dt->GetTokenType();
  4153. WriteEncodedInt64(t);
  4154. if( t == ttIdentifier )
  4155. WriteTypeInfo(dt->GetTypeInfo());
  4156. // Endianess safe bitmask
  4157. char bits = 0;
  4158. SAVE_TO_BIT(bits, dt->IsObjectHandle(), 0);
  4159. SAVE_TO_BIT(bits, dt->IsHandleToConst(), 1);
  4160. SAVE_TO_BIT(bits, dt->IsReference(), 2);
  4161. SAVE_TO_BIT(bits, dt->IsReadOnly(), 3);
  4162. WriteData(&bits, 1);
  4163. }
  4164. void asCWriter::WriteTypeInfo(asCTypeInfo* ti)
  4165. {
  4166. char ch;
  4167. if( ti )
  4168. {
  4169. // Check for template instances/specializations
  4170. asCObjectType *ot = CastToObjectType(ti);
  4171. if( ot && ot->templateSubTypes.GetLength() )
  4172. {
  4173. // Check for list pattern type or template type
  4174. if( ot->flags & asOBJ_LIST_PATTERN )
  4175. {
  4176. ch = 'l'; // list
  4177. WriteData(&ch, 1);
  4178. WriteTypeInfo(ot->templateSubTypes[0].GetTypeInfo());
  4179. }
  4180. else
  4181. {
  4182. ch = 'a'; // array
  4183. WriteData(&ch, 1);
  4184. WriteString(&ot->name);
  4185. WriteString(&ot->nameSpace->name);
  4186. WriteEncodedInt64(ot->templateSubTypes.GetLength());
  4187. for( asUINT n = 0; n < ot->templateSubTypes.GetLength(); n++ )
  4188. {
  4189. if( !ot->templateSubTypes[n].IsPrimitive() || ot->templateSubTypes[n].IsEnumType() )
  4190. {
  4191. ch = 's'; // sub type
  4192. WriteData(&ch, 1);
  4193. WriteDataType(&ot->templateSubTypes[n]);
  4194. }
  4195. else
  4196. {
  4197. ch = 't'; // token
  4198. WriteData(&ch, 1);
  4199. eTokenType t = ot->templateSubTypes[n].GetTokenType();
  4200. WriteEncodedInt64(t);
  4201. }
  4202. }
  4203. }
  4204. }
  4205. else if( ti->flags & asOBJ_TEMPLATE_SUBTYPE )
  4206. {
  4207. ch = 's'; // sub type
  4208. WriteData(&ch, 1);
  4209. WriteString(&ti->name);
  4210. }
  4211. else if( !ti->GetParentType() )
  4212. {
  4213. ch = 'o'; // object
  4214. WriteData(&ch, 1);
  4215. WriteString(&ti->name);
  4216. WriteString(&ti->nameSpace->name);
  4217. }
  4218. else
  4219. {
  4220. asASSERT(ti->flags & asOBJ_FUNCDEF);
  4221. ch = 'c'; // child type
  4222. WriteData(&ch, 1);
  4223. WriteString(&ti->name);
  4224. WriteTypeInfo(CastToFuncdefType(ti)->parentClass);
  4225. }
  4226. }
  4227. else
  4228. {
  4229. ch = '\0';
  4230. WriteData(&ch, 1);
  4231. }
  4232. }
  4233. void asCWriter::CalculateAdjustmentByPos(asCScriptFunction *func)
  4234. {
  4235. // Adjust the offset of all negative variables (parameters) so all pointers will have a size of 1 dword
  4236. asUINT n;
  4237. asCArray<int> adjustments;
  4238. asUINT offset = 0;
  4239. if( func->objectType )
  4240. {
  4241. adjustments.PushLast(offset);
  4242. adjustments.PushLast(1-AS_PTR_SIZE);
  4243. offset += AS_PTR_SIZE;
  4244. }
  4245. if( func->DoesReturnOnStack() )
  4246. {
  4247. adjustments.PushLast(offset);
  4248. adjustments.PushLast(1-AS_PTR_SIZE);
  4249. offset += AS_PTR_SIZE;
  4250. }
  4251. for( n = 0; n < func->parameterTypes.GetLength(); n++ )
  4252. {
  4253. if( !func->parameterTypes[n].IsPrimitive() ||
  4254. func->parameterTypes[n].IsReference() )
  4255. {
  4256. adjustments.PushLast(offset);
  4257. adjustments.PushLast(1-AS_PTR_SIZE);
  4258. offset += AS_PTR_SIZE;
  4259. }
  4260. else
  4261. {
  4262. asASSERT( func->parameterTypes[n].IsPrimitive() );
  4263. offset += func->parameterTypes[n].GetSizeOnStackDWords();
  4264. }
  4265. }
  4266. // Build look-up table with the adjustments for each stack position
  4267. adjustNegativeStackByPos.SetLength(offset);
  4268. memset(adjustNegativeStackByPos.AddressOf(), 0, adjustNegativeStackByPos.GetLength()*sizeof(int));
  4269. for( n = 0; n < adjustments.GetLength(); n+=2 )
  4270. {
  4271. int pos = adjustments[n];
  4272. int adjust = adjustments[n+1];
  4273. for( asUINT i = pos+1; i < adjustNegativeStackByPos.GetLength(); i++ )
  4274. adjustNegativeStackByPos[i] += adjust;
  4275. }
  4276. // Adjust the offset of all positive variables so that all object types and handles have a size of 1 dword
  4277. // This is similar to how the adjustment is done in the asCReader::TranslateFunction, only the reverse
  4278. adjustments.SetLength(0);
  4279. for( n = 0; n < func->scriptData->objVariableTypes.GetLength(); n++ )
  4280. {
  4281. // Determine the size the variable currently occupies on the stack
  4282. int size = AS_PTR_SIZE;
  4283. // objVariableTypes is null if the variable type is a null pointer
  4284. if( func->scriptData->objVariableTypes[n] &&
  4285. (func->scriptData->objVariableTypes[n]->GetFlags() & asOBJ_VALUE) &&
  4286. n >= func->scriptData->objVariablesOnHeap )
  4287. {
  4288. size = func->scriptData->objVariableTypes[n]->GetSize();
  4289. if( size < 4 )
  4290. size = 1;
  4291. else
  4292. size /= 4;
  4293. }
  4294. // If larger than 1 dword, adjust the offsets accordingly
  4295. if (size > 1)
  4296. {
  4297. // How much needs to be adjusted?
  4298. adjustments.PushLast(func->scriptData->objVariablePos[n]);
  4299. adjustments.PushLast(-(size - 1));
  4300. }
  4301. }
  4302. // Build look-up table with the adjustments for each stack position
  4303. adjustStackByPos.SetLength(func->scriptData->stackNeeded);
  4304. memset(adjustStackByPos.AddressOf(), 0, adjustStackByPos.GetLength()*sizeof(int));
  4305. for( n = 0; n < adjustments.GetLength(); n+=2 )
  4306. {
  4307. int pos = adjustments[n];
  4308. int adjust = adjustments[n+1];
  4309. for( asUINT i = pos; i < adjustStackByPos.GetLength(); i++ )
  4310. adjustStackByPos[i] += adjust;
  4311. }
  4312. // Compute the sequence number of each bytecode instruction in order to update the jump offsets
  4313. asUINT length = func->scriptData->byteCode.GetLength();
  4314. asDWORD *bc = func->scriptData->byteCode.AddressOf();
  4315. bytecodeNbrByPos.SetLength(length);
  4316. asUINT num;
  4317. for( offset = 0, num = 0; offset < length; )
  4318. {
  4319. bytecodeNbrByPos[offset] = num;
  4320. offset += asBCTypeSize[asBCInfo[*(asBYTE*)(bc+offset)].type];
  4321. num++;
  4322. }
  4323. // Store the number of instructions in the last position of bytecodeNbrByPos,
  4324. // so this can be easily queried in SaveBytecode. Normally this is already done
  4325. // as most functions end with BC_RET, but in some cases the last instruction in
  4326. // the function is not a BC_RET, e.g. when a function has a never ending loop.
  4327. bytecodeNbrByPos[length - 1] = num - 1;
  4328. }
  4329. int asCWriter::AdjustStackPosition(int pos)
  4330. {
  4331. if( pos >= (int)adjustStackByPos.GetLength() )
  4332. {
  4333. // This happens for example if the function only have temporary variables
  4334. // The adjustByPos can also be empty if the function doesn't have any variables at all, but receive a handle by parameter
  4335. if( adjustStackByPos.GetLength() > 0 )
  4336. pos += adjustStackByPos[adjustStackByPos.GetLength()-1];
  4337. }
  4338. else if( pos >= 0 )
  4339. pos += adjustStackByPos[pos];
  4340. else
  4341. {
  4342. asASSERT( -pos < (int)adjustNegativeStackByPos.GetLength() );
  4343. pos -= (short)adjustNegativeStackByPos[-pos];
  4344. }
  4345. return pos;
  4346. }
  4347. int asCWriter::AdjustGetOffset(int offset, asCScriptFunction *func, asDWORD programPos)
  4348. {
  4349. // TODO: optimize: multiple instructions for the same function doesn't need to look for the function everytime
  4350. // the function can remember where it found the function and check if the programPos is still valid
  4351. // Get offset 0 doesn't need adjustment
  4352. if( offset == 0 ) return 0;
  4353. bool bcAlloc = false;
  4354. // Find out which function that will be called
  4355. asCScriptFunction *calledFunc = 0;
  4356. int stackDelta = 0;
  4357. for( asUINT n = programPos; n < func->scriptData->byteCode.GetLength(); )
  4358. {
  4359. asBYTE bc = *(asBYTE*)&func->scriptData->byteCode[n];
  4360. if( bc == asBC_CALL ||
  4361. bc == asBC_CALLSYS ||
  4362. bc == asBC_Thiscall1 ||
  4363. bc == asBC_CALLINTF )
  4364. {
  4365. // Find the function from the function id in bytecode
  4366. int funcId = asBC_INTARG(&func->scriptData->byteCode[n]);
  4367. calledFunc = engine->scriptFunctions[funcId];
  4368. break;
  4369. }
  4370. else if( bc == asBC_ALLOC )
  4371. {
  4372. // The alloc instruction doesn't take the object pointer on the stack,
  4373. // as the memory will be allocated by the instruction itself
  4374. bcAlloc = true;
  4375. // Find the function from the function id in the bytecode
  4376. int funcId = asBC_INTARG(&func->scriptData->byteCode[n+AS_PTR_SIZE]);
  4377. calledFunc = engine->scriptFunctions[funcId];
  4378. break;
  4379. }
  4380. else if( bc == asBC_CALLBND )
  4381. {
  4382. // Find the function from the engine's bind array
  4383. int funcId = asBC_INTARG(&func->scriptData->byteCode[n]);
  4384. calledFunc = engine->importedFunctions[funcId & ~FUNC_IMPORTED]->importedFunctionSignature;
  4385. break;
  4386. }
  4387. else if( bc == asBC_CallPtr )
  4388. {
  4389. int var = asBC_SWORDARG0(&func->scriptData->byteCode[n]);
  4390. asUINT v;
  4391. // Find the funcdef from the local variable
  4392. for( v = 0; v < func->scriptData->objVariablePos.GetLength(); v++ )
  4393. {
  4394. if( func->scriptData->objVariablePos[v] == var )
  4395. {
  4396. calledFunc = CastToFuncdefType(func->scriptData->objVariableTypes[v])->funcdef;
  4397. break;
  4398. }
  4399. }
  4400. if( !calledFunc )
  4401. {
  4402. // Look in parameters
  4403. int paramPos = 0;
  4404. if( func->objectType )
  4405. paramPos -= AS_PTR_SIZE;
  4406. if( func->DoesReturnOnStack() )
  4407. paramPos -= AS_PTR_SIZE;
  4408. for( v = 0; v < func->parameterTypes.GetLength(); v++ )
  4409. {
  4410. if( var == paramPos )
  4411. {
  4412. calledFunc = CastToFuncdefType(func->parameterTypes[v].GetTypeInfo())->funcdef;
  4413. break;
  4414. }
  4415. paramPos -= func->parameterTypes[v].GetSizeOnStackDWords();
  4416. }
  4417. }
  4418. break;
  4419. }
  4420. else if( bc == asBC_REFCPY ||
  4421. bc == asBC_COPY )
  4422. {
  4423. // In this case we know there is only 1 pointer on the stack above
  4424. asASSERT( offset == AS_PTR_SIZE );
  4425. return offset + (1 - AS_PTR_SIZE);
  4426. }
  4427. // Keep track of the stack size between the
  4428. // instruction that needs to be adjusted and the call
  4429. stackDelta += asBCInfo[bc].stackInc;
  4430. n += asBCTypeSize[asBCInfo[bc].type];
  4431. }
  4432. asASSERT( calledFunc );
  4433. // Count the number of pointers pushed on the stack above the
  4434. // current offset, and then adjust the offset accordingly
  4435. asUINT numPtrs = 0;
  4436. int currOffset = -stackDelta;
  4437. if( offset > currOffset && calledFunc->GetObjectType() && !bcAlloc )
  4438. {
  4439. currOffset += AS_PTR_SIZE;
  4440. if( currOffset > 0 )
  4441. numPtrs++;
  4442. }
  4443. if( offset > currOffset && calledFunc->DoesReturnOnStack() )
  4444. {
  4445. currOffset += AS_PTR_SIZE;
  4446. if( currOffset > 0 )
  4447. numPtrs++;
  4448. }
  4449. for( asUINT p = 0; p < calledFunc->parameterTypes.GetLength(); p++ )
  4450. {
  4451. if( offset <= currOffset ) break;
  4452. if( !calledFunc->parameterTypes[p].IsPrimitive() ||
  4453. calledFunc->parameterTypes[p].IsReference() )
  4454. {
  4455. // objects and references are passed by pointer
  4456. currOffset += AS_PTR_SIZE;
  4457. if( currOffset > 0 )
  4458. numPtrs++;
  4459. // The variable arg ? has an additional 32bit int with the typeid
  4460. if( calledFunc->parameterTypes[p].IsAnyType() )
  4461. currOffset += 1;
  4462. }
  4463. else
  4464. {
  4465. // built-in primitives or enums are passed by value
  4466. asASSERT( calledFunc->parameterTypes[p].IsPrimitive() );
  4467. currOffset += calledFunc->parameterTypes[p].GetSizeOnStackDWords();
  4468. }
  4469. }
  4470. // The get offset must match one of the parameter offsets
  4471. asASSERT( offset == currOffset );
  4472. return offset + numPtrs * (1 - AS_PTR_SIZE);
  4473. }
  4474. void asCWriter::WriteByteCode(asCScriptFunction *func)
  4475. {
  4476. asDWORD *bc = func->scriptData->byteCode.AddressOf();
  4477. size_t length = func->scriptData->byteCode.GetLength();
  4478. // The length cannot be stored, because it is platform dependent,
  4479. // instead we store the number of instructions
  4480. asUINT count = bytecodeNbrByPos[bytecodeNbrByPos.GetLength()-1] + 1;
  4481. WriteEncodedInt64(count);
  4482. asDWORD *startBC = bc;
  4483. while( length )
  4484. {
  4485. asDWORD tmpBC[4]; // The biggest instructions take up 4 DWORDs
  4486. asDWORD c = *(asBYTE*)bc;
  4487. // Copy the instruction to a temp buffer so we can work on it before saving
  4488. memcpy(tmpBC, bc, asBCTypeSize[asBCInfo[c].type]*sizeof(asDWORD));
  4489. if( c == asBC_ALLOC ) // PTR_DW_ARG
  4490. {
  4491. // Translate the object type
  4492. asCObjectType *ot = *(asCObjectType**)(tmpBC+1);
  4493. *(asPWORD*)(tmpBC+1) = FindTypeInfoIdx(ot);
  4494. // Translate the constructor func id, unless it is 0
  4495. if( *(int*)&tmpBC[1+AS_PTR_SIZE] != 0 )
  4496. {
  4497. // Increment 1 to the translated function id, as 0 will be reserved for no function
  4498. *(int*)&tmpBC[1+AS_PTR_SIZE] = 1+FindFunctionIndex(engine->scriptFunctions[*(int*)&tmpBC[1+AS_PTR_SIZE]]);
  4499. }
  4500. }
  4501. else if( c == asBC_REFCPY || // PTR_ARG
  4502. c == asBC_RefCpyV || // wW_PTR_ARG
  4503. c == asBC_OBJTYPE ) // PTR_ARG
  4504. {
  4505. // Translate object type pointers into indices
  4506. *(asPWORD*)(tmpBC+1) = FindTypeInfoIdx(*(asCObjectType**)(tmpBC+1));
  4507. }
  4508. else if( c == asBC_JitEntry ) // PTR_ARG
  4509. {
  4510. // We don't store the JIT argument
  4511. *(asPWORD*)(tmpBC+1) = 0;
  4512. }
  4513. else if( c == asBC_TYPEID || // DW_ARG
  4514. c == asBC_Cast ) // DW_ARG
  4515. {
  4516. // Translate type ids into indices
  4517. *(int*)(tmpBC+1) = FindTypeIdIdx(*(int*)(tmpBC+1));
  4518. }
  4519. else if( c == asBC_ADDSi || // W_DW_ARG
  4520. c == asBC_LoadThisR ) // W_DW_ARG
  4521. {
  4522. // Translate property offsets into indices
  4523. *(((short*)tmpBC)+1) = (short)FindObjectPropIndex(*(((short*)tmpBC)+1), *(int*)(tmpBC+1), bc);
  4524. // Translate type ids into indices
  4525. *(int*)(tmpBC+1) = FindTypeIdIdx(*(int*)(tmpBC+1));
  4526. }
  4527. else if( c == asBC_LoadRObjR || // rW_W_DW_ARG
  4528. c == asBC_LoadVObjR ) // rW_W_DW_ARG
  4529. {
  4530. asCObjectType *ot = engine->GetObjectTypeFromTypeId(*(int*)(tmpBC+2));
  4531. if( ot->flags & asOBJ_LIST_PATTERN )
  4532. {
  4533. // List patterns have a different way of translating the offsets
  4534. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  4535. *(((short*)tmpBC)+2) = (short)listAdj->AdjustOffset(*(((short*)tmpBC)+2), ot);
  4536. }
  4537. else
  4538. {
  4539. // Translate property offsets into indices
  4540. *(((short*)tmpBC)+2) = (short)FindObjectPropIndex(*(((short*)tmpBC)+2), *(int*)(tmpBC+2), bc);
  4541. }
  4542. // Translate type ids into indices
  4543. *(int*)(tmpBC+2) = FindTypeIdIdx(*(int*)(tmpBC+2));
  4544. }
  4545. else if( c == asBC_COPY ) // W_DW_ARG
  4546. {
  4547. // Translate type ids into indices
  4548. *(int*)(tmpBC+1) = FindTypeIdIdx(*(int*)(tmpBC+1));
  4549. // Update the WORDARG0 to 0, as this will be recalculated on the target platform
  4550. asBC_WORDARG0(tmpBC) = 0;
  4551. }
  4552. else if( c == asBC_RET ) // W_ARG
  4553. {
  4554. // Save with arg 0, as this will be recalculated on the target platform
  4555. asBC_WORDARG0(tmpBC) = 0;
  4556. }
  4557. else if( c == asBC_CALL || // DW_ARG
  4558. c == asBC_CALLINTF || // DW_ARG
  4559. c == asBC_CALLSYS || // DW_ARG
  4560. c == asBC_Thiscall1 ) // DW_ARG
  4561. {
  4562. // Translate the function id
  4563. *(int*)(tmpBC+1) = FindFunctionIndex(engine->scriptFunctions[*(int*)(tmpBC+1)]);
  4564. }
  4565. else if( c == asBC_FuncPtr ) // PTR_ARG
  4566. {
  4567. // Translate the function pointer
  4568. *(asPWORD*)(tmpBC+1) = FindFunctionIndex(*(asCScriptFunction**)(tmpBC+1));
  4569. }
  4570. else if( c == asBC_CALLBND ) // DW_ARG
  4571. {
  4572. // Translate the function id
  4573. int funcId = tmpBC[1];
  4574. for( asUINT n = 0; n < module->m_bindInformations.GetLength(); n++ )
  4575. if( module->m_bindInformations[n]->importedFunctionSignature->id == funcId )
  4576. {
  4577. funcId = n;
  4578. break;
  4579. }
  4580. tmpBC[1] = funcId;
  4581. }
  4582. else if( c == asBC_PGA || // PTR_ARG
  4583. c == asBC_PshGPtr || // PTR_ARG
  4584. c == asBC_LDG || // PTR_ARG
  4585. c == asBC_PshG4 || // PTR_ARG
  4586. c == asBC_LdGRdR4 || // wW_PTR_ARG
  4587. c == asBC_CpyGtoV4 || // wW_PTR_ARG
  4588. c == asBC_CpyVtoG4 || // rW_PTR_ARG
  4589. c == asBC_SetG4 ) // PTR_DW_ARG
  4590. {
  4591. // Check if the address is a global property or a string constant
  4592. void *ptr = *(void**)(tmpBC + 1);
  4593. if (engine->varAddressMap.MoveTo(0, ptr))
  4594. {
  4595. // Translate global variable pointers into indices
  4596. // Flag the first bit to signal global property
  4597. *(asPWORD*)(tmpBC + 1) = (FindGlobalPropPtrIndex(*(void**)(tmpBC + 1)) << 1) + 1;
  4598. }
  4599. else
  4600. {
  4601. // Only PGA and PshGPtr can hold string constants
  4602. asASSERT(c == asBC_PGA || c == asBC_PshGPtr);
  4603. // Translate string constants into indices
  4604. // Leave the first bit clear to signal string constant
  4605. *(asPWORD*)(tmpBC + 1) = FindStringConstantIndex(*(void**)(tmpBC + 1)) << 1;
  4606. }
  4607. }
  4608. else if( c == asBC_JMP || // DW_ARG
  4609. c == asBC_JZ ||
  4610. c == asBC_JNZ ||
  4611. c == asBC_JLowZ ||
  4612. c == asBC_JLowNZ ||
  4613. c == asBC_JS ||
  4614. c == asBC_JNS ||
  4615. c == asBC_JP ||
  4616. c == asBC_JNP ) // The JMPP instruction doesn't need modification
  4617. {
  4618. // Get the DWORD offset from arg
  4619. int offset = *(int*)(tmpBC+1);
  4620. // Determine instruction number for next instruction and destination
  4621. int bcSeqNum = bytecodeNbrByPos[asUINT(bc - startBC)] + 1;
  4622. asDWORD *targetBC = bc + 2 + offset;
  4623. int targetBcSeqNum = bytecodeNbrByPos[asUINT(targetBC - startBC)];
  4624. // Set the offset in number of instructions
  4625. *(int*)(tmpBC+1) = targetBcSeqNum - bcSeqNum;
  4626. }
  4627. else if( c == asBC_GETOBJ || // W_ARG
  4628. c == asBC_GETOBJREF ||
  4629. c == asBC_GETREF ||
  4630. c == asBC_ChkNullS )
  4631. {
  4632. // Adjust the offset according to the function call that comes after
  4633. asBC_WORDARG0(tmpBC) = (asWORD)AdjustGetOffset(asBC_WORDARG0(tmpBC), func, asDWORD(bc - startBC));
  4634. }
  4635. else if( c == asBC_AllocMem )
  4636. {
  4637. // It's not necessary to store the size of the list buffer, as it will be recalculated in the reader
  4638. asBC_DWORDARG(tmpBC) = 0;
  4639. // Determine the type of the list pattern from the variable
  4640. short var = asBC_WORDARG0(tmpBC);
  4641. asCObjectType *ot = CastToObjectType(func->GetTypeInfoOfLocalVar(var));
  4642. // Create this helper object to adjust the offset of the elements accessed in the buffer
  4643. listAdjusters.PushLast(asNEW(SListAdjuster)(ot));
  4644. }
  4645. else if( c == asBC_FREE ) // wW_PTR_ARG
  4646. {
  4647. // Translate object type pointers into indices
  4648. asCObjectType *ot = *(asCObjectType**)(tmpBC+1);
  4649. *(asPWORD*)(tmpBC+1) = FindTypeInfoIdx(ot);
  4650. // Pop and destroy the list adjuster helper that was created with asBC_AllocMem
  4651. if( ot && (ot->flags & asOBJ_LIST_PATTERN) )
  4652. {
  4653. SListAdjuster *list = listAdjusters.PopLast();
  4654. asDELETE(list, SListAdjuster);
  4655. }
  4656. }
  4657. else if( c == asBC_SetListSize )
  4658. {
  4659. // Adjust the offset in the initialization list
  4660. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  4661. tmpBC[1] = listAdj->AdjustOffset(tmpBC[1], listAdj->patternType);
  4662. // Tell the adjuster how many repeated values there are
  4663. listAdj->SetRepeatCount(tmpBC[2]);
  4664. }
  4665. else if( c == asBC_PshListElmnt ) // W_DW_ARG
  4666. {
  4667. // Adjust the offset in the initialization list
  4668. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  4669. tmpBC[1] = listAdj->AdjustOffset(tmpBC[1], listAdj->patternType);
  4670. }
  4671. else if( c == asBC_SetListType )
  4672. {
  4673. // Adjust the offset in the initialization list
  4674. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  4675. tmpBC[1] = listAdj->AdjustOffset(tmpBC[1], listAdj->patternType);
  4676. // Inform the adjuster of the type id of the next element
  4677. listAdj->SetNextType(tmpBC[2]);
  4678. // Translate the type id
  4679. tmpBC[2] = FindTypeIdIdx(tmpBC[2]);
  4680. }
  4681. // Adjust the variable offsets
  4682. switch( asBCInfo[c].type )
  4683. {
  4684. case asBCTYPE_wW_ARG:
  4685. case asBCTYPE_rW_DW_ARG:
  4686. case asBCTYPE_wW_QW_ARG:
  4687. case asBCTYPE_rW_ARG:
  4688. case asBCTYPE_wW_DW_ARG:
  4689. case asBCTYPE_wW_W_ARG:
  4690. case asBCTYPE_rW_QW_ARG:
  4691. case asBCTYPE_rW_W_DW_ARG:
  4692. case asBCTYPE_rW_DW_DW_ARG:
  4693. {
  4694. asBC_SWORDARG0(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG0(tmpBC));
  4695. }
  4696. break;
  4697. case asBCTYPE_wW_rW_ARG:
  4698. case asBCTYPE_wW_rW_DW_ARG:
  4699. case asBCTYPE_rW_rW_ARG:
  4700. {
  4701. asBC_SWORDARG0(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG0(tmpBC));
  4702. asBC_SWORDARG1(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG1(tmpBC));
  4703. }
  4704. break;
  4705. case asBCTYPE_wW_rW_rW_ARG:
  4706. {
  4707. asBC_SWORDARG0(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG0(tmpBC));
  4708. asBC_SWORDARG1(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG1(tmpBC));
  4709. asBC_SWORDARG2(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG2(tmpBC));
  4710. }
  4711. break;
  4712. default:
  4713. // The other types don't treat variables so won't be modified
  4714. break;
  4715. }
  4716. // TODO: bytecode: Must make sure that floats and doubles are always stored the same way regardless of platform.
  4717. // Some platforms may not use the IEEE 754 standard, in which case it is necessary to encode the values
  4718. // Now store the instruction in the smallest possible way
  4719. switch( asBCInfo[c].type )
  4720. {
  4721. case asBCTYPE_NO_ARG:
  4722. {
  4723. // Just write 1 byte
  4724. asBYTE b = (asBYTE)c;
  4725. WriteData(&b, 1);
  4726. }
  4727. break;
  4728. case asBCTYPE_W_ARG:
  4729. case asBCTYPE_wW_ARG:
  4730. case asBCTYPE_rW_ARG:
  4731. {
  4732. // Write the instruction code
  4733. asBYTE b = (asBYTE)c;
  4734. WriteData(&b, 1);
  4735. // Write the argument
  4736. short w = *(((short*)tmpBC)+1);
  4737. WriteEncodedInt64(w);
  4738. }
  4739. break;
  4740. case asBCTYPE_rW_DW_ARG:
  4741. case asBCTYPE_wW_DW_ARG:
  4742. case asBCTYPE_W_DW_ARG:
  4743. {
  4744. // Write the instruction code
  4745. asBYTE b = (asBYTE)c;
  4746. WriteData(&b, 1);
  4747. // Write the word argument
  4748. short w = *(((short*)tmpBC)+1);
  4749. WriteEncodedInt64(w);
  4750. // Write the dword argument
  4751. WriteEncodedInt64((int)tmpBC[1]);
  4752. }
  4753. break;
  4754. case asBCTYPE_DW_ARG:
  4755. {
  4756. // Write the instruction code
  4757. asBYTE b = (asBYTE)c;
  4758. WriteData(&b, 1);
  4759. // Write the argument
  4760. WriteEncodedInt64((int)tmpBC[1]);
  4761. }
  4762. break;
  4763. case asBCTYPE_DW_DW_ARG:
  4764. {
  4765. // Write the instruction code
  4766. asBYTE b = (asBYTE)c;
  4767. WriteData(&b, 1);
  4768. // Write the dword argument
  4769. WriteEncodedInt64((int)tmpBC[1]);
  4770. // Write the dword argument
  4771. WriteEncodedInt64((int)tmpBC[2]);
  4772. }
  4773. break;
  4774. case asBCTYPE_wW_rW_rW_ARG:
  4775. {
  4776. // Write the instruction code
  4777. asBYTE b = (asBYTE)c;
  4778. WriteData(&b, 1);
  4779. // Write the first argument
  4780. short w = *(((short*)tmpBC)+1);
  4781. WriteEncodedInt64(w);
  4782. // Write the second argument
  4783. w = *(((short*)tmpBC)+2);
  4784. WriteEncodedInt64(w);
  4785. // Write the third argument
  4786. w = *(((short*)tmpBC)+3);
  4787. WriteEncodedInt64(w);
  4788. }
  4789. break;
  4790. case asBCTYPE_wW_rW_ARG:
  4791. case asBCTYPE_rW_rW_ARG:
  4792. case asBCTYPE_wW_W_ARG:
  4793. {
  4794. // Write the instruction code
  4795. asBYTE b = (asBYTE)c;
  4796. WriteData(&b, 1);
  4797. // Write the first argument
  4798. short w = *(((short*)tmpBC)+1);
  4799. WriteEncodedInt64(w);
  4800. // Write the second argument
  4801. w = *(((short*)tmpBC)+2);
  4802. WriteEncodedInt64(w);
  4803. }
  4804. break;
  4805. case asBCTYPE_wW_rW_DW_ARG:
  4806. case asBCTYPE_rW_W_DW_ARG:
  4807. {
  4808. // Write the instruction code
  4809. asBYTE b = (asBYTE)c;
  4810. WriteData(&b, 1);
  4811. // Write the first argument
  4812. short w = *(((short*)tmpBC)+1);
  4813. WriteEncodedInt64(w);
  4814. // Write the second argument
  4815. w = *(((short*)tmpBC)+2);
  4816. WriteEncodedInt64(w);
  4817. // Write the third argument
  4818. int dw = tmpBC[2];
  4819. WriteEncodedInt64(dw);
  4820. }
  4821. break;
  4822. case asBCTYPE_QW_ARG:
  4823. {
  4824. // Write the instruction code
  4825. asBYTE b = (asBYTE)c;
  4826. WriteData(&b, 1);
  4827. // Write the argument
  4828. asQWORD qw = *(asQWORD*)&tmpBC[1];
  4829. WriteEncodedInt64(qw);
  4830. }
  4831. break;
  4832. case asBCTYPE_QW_DW_ARG:
  4833. {
  4834. // Write the instruction code
  4835. asBYTE b = (asBYTE)c;
  4836. WriteData(&b, 1);
  4837. // Write the argument
  4838. asQWORD qw = *(asQWORD*)&tmpBC[1];
  4839. WriteEncodedInt64(qw);
  4840. // Write the second argument
  4841. int dw = tmpBC[3];
  4842. WriteEncodedInt64(dw);
  4843. }
  4844. break;
  4845. case asBCTYPE_rW_QW_ARG:
  4846. case asBCTYPE_wW_QW_ARG:
  4847. {
  4848. // Write the instruction code
  4849. asBYTE b = (asBYTE)c;
  4850. WriteData(&b, 1);
  4851. // Write the first argument
  4852. short w = *(((short*)tmpBC)+1);
  4853. WriteEncodedInt64(w);
  4854. // Write the argument
  4855. asQWORD qw = *(asQWORD*)&tmpBC[1];
  4856. WriteEncodedInt64(qw);
  4857. }
  4858. break;
  4859. case asBCTYPE_rW_DW_DW_ARG:
  4860. {
  4861. // Write the instruction code
  4862. asBYTE b = (asBYTE)c;
  4863. WriteData(&b, 1);
  4864. // Write the short argument
  4865. short w = *(((short*)tmpBC)+1);
  4866. WriteEncodedInt64(w);
  4867. // Write the dword argument
  4868. WriteEncodedInt64((int)tmpBC[1]);
  4869. // Write the dword argument
  4870. WriteEncodedInt64((int)tmpBC[2]);
  4871. }
  4872. break;
  4873. default:
  4874. {
  4875. // This should never happen
  4876. asASSERT(false);
  4877. // Store the bc as is
  4878. for( int n = 0; n < asBCTypeSize[asBCInfo[c].type]; n++ )
  4879. WriteData(&tmpBC[n], 4);
  4880. }
  4881. }
  4882. // Move to the next instruction
  4883. bc += asBCTypeSize[asBCInfo[c].type];
  4884. length -= asBCTypeSize[asBCInfo[c].type];
  4885. }
  4886. }
  4887. asCWriter::SListAdjuster::SListAdjuster(asCObjectType *ot) : patternType(ot), repeatCount(0), entries(0), lastOffset(-1), nextOffset(0), nextTypeId(-1)
  4888. {
  4889. asASSERT( ot && (ot->flags & asOBJ_LIST_PATTERN) );
  4890. // Find the first expected value in the list
  4891. asSListPatternNode *node = ot->engine->scriptFunctions[patternType->templateSubTypes[0].GetBehaviour()->listFactory]->listPattern;
  4892. asASSERT( node && node->type == asLPT_START );
  4893. patternNode = node->next;
  4894. }
  4895. int asCWriter::SListAdjuster::AdjustOffset(int offset, asCObjectType *listPatternType)
  4896. {
  4897. // TODO: cleanup: The listPatternType parameter is not needed
  4898. asASSERT( patternType == listPatternType );
  4899. UNUSED_VAR(listPatternType);
  4900. asASSERT( offset >= lastOffset );
  4901. // If it is the same offset being accessed again, just return the same adjusted value
  4902. if( offset == lastOffset )
  4903. return entries-1;
  4904. asASSERT( offset >= nextOffset );
  4905. // Update last offset for next call
  4906. lastOffset = offset;
  4907. // What is being expected at this position?
  4908. if( patternNode->type == asLPT_REPEAT || patternNode->type == asLPT_REPEAT_SAME )
  4909. {
  4910. // Don't move the patternNode yet because the caller must make a call to SetRepeatCount too
  4911. nextOffset = offset + 4;
  4912. return entries++;
  4913. }
  4914. else if( patternNode->type == asLPT_TYPE )
  4915. {
  4916. const asCDataType &dt = reinterpret_cast<asSListPatternDataTypeNode*>(patternNode)->dataType;
  4917. if( dt.GetTokenType() == ttQuestion )
  4918. {
  4919. // The bytecode need to inform the type that will
  4920. // come next and then adjust that position too before
  4921. // we can move to the next node
  4922. if( nextTypeId != -1 )
  4923. {
  4924. nextOffset = offset + 4;
  4925. if( repeatCount > 0 )
  4926. repeatCount--;
  4927. // Only move the patternNode if we're not expecting any more repeated entries
  4928. if( repeatCount == 0 )
  4929. patternNode = patternNode->next;
  4930. nextTypeId = -1;
  4931. }
  4932. }
  4933. else
  4934. {
  4935. if( repeatCount > 0 )
  4936. {
  4937. // Was any value skipped?
  4938. asUINT size;
  4939. if( dt.IsObjectHandle() || (dt.GetTypeInfo() && (dt.GetTypeInfo()->flags & asOBJ_REF)) )
  4940. size = AS_PTR_SIZE*4;
  4941. else
  4942. size = dt.GetSizeInMemoryBytes();
  4943. int count = 0;
  4944. while( nextOffset <= offset )
  4945. {
  4946. count++;
  4947. nextOffset += size;
  4948. // Align the offset on 4 byte boundaries
  4949. if( size >= 4 && (nextOffset & 0x3) )
  4950. nextOffset += 4 - (nextOffset & 0x3);
  4951. }
  4952. if( --count > 0 )
  4953. {
  4954. // Skip these values
  4955. repeatCount -= count;
  4956. entries += count;
  4957. }
  4958. nextOffset = offset + size;
  4959. repeatCount--;
  4960. }
  4961. // Only move the patternNode if we're not expecting any more repeated entries
  4962. if( repeatCount == 0 )
  4963. patternNode = patternNode->next;
  4964. }
  4965. return entries++;
  4966. }
  4967. else if( patternNode->type == asLPT_START )
  4968. {
  4969. if( repeatCount > 0 )
  4970. repeatCount--;
  4971. SInfo info = {repeatCount, patternNode};
  4972. stack.PushLast(info);
  4973. repeatCount = 0;
  4974. patternNode = patternNode->next;
  4975. lastOffset--;
  4976. return AdjustOffset(offset, listPatternType);
  4977. }
  4978. else if( patternNode->type == asLPT_END )
  4979. {
  4980. SInfo info = stack.PopLast();
  4981. repeatCount = info.repeatCount;
  4982. if( repeatCount )
  4983. patternNode = info.startNode;
  4984. else
  4985. patternNode = patternNode->next;
  4986. lastOffset--;
  4987. return AdjustOffset(offset, listPatternType);
  4988. }
  4989. else
  4990. {
  4991. // Something is wrong with the pattern list declaration
  4992. asASSERT( false );
  4993. }
  4994. return 0;
  4995. }
  4996. void asCWriter::SListAdjuster::SetRepeatCount(asUINT rc)
  4997. {
  4998. // Make sure the list is expecting a repeat at this location
  4999. asASSERT( patternNode->type == asLPT_REPEAT || patternNode->type == asLPT_REPEAT_SAME );
  5000. // Now move to the next patternNode
  5001. patternNode = patternNode->next;
  5002. repeatCount = rc;
  5003. }
  5004. void asCWriter::SListAdjuster::SetNextType(int typeId)
  5005. {
  5006. // Make sure the list is expecting a type at this location
  5007. asASSERT( patternNode->type == asLPT_TYPE &&
  5008. reinterpret_cast<asSListPatternDataTypeNode*>(patternNode)->dataType.GetTokenType() == ttQuestion );
  5009. // Inform the type id for the next adjustment
  5010. nextTypeId = typeId;
  5011. }
  5012. void asCWriter::WriteUsedTypeIds()
  5013. {
  5014. TimeIt("asCWriter::WriteUsedTypeIds");
  5015. asUINT count = (asUINT)usedTypeIds.GetLength();
  5016. WriteEncodedInt64(count);
  5017. for( asUINT n = 0; n < count; n++ )
  5018. {
  5019. asCDataType dt = engine->GetDataTypeFromTypeId(usedTypeIds[n]);
  5020. WriteDataType(&dt);
  5021. }
  5022. }
  5023. int asCWriter::FindGlobalPropPtrIndex(void *ptr)
  5024. {
  5025. int i = usedGlobalProperties.IndexOf(ptr);
  5026. if( i >= 0 ) return i;
  5027. usedGlobalProperties.PushLast(ptr);
  5028. return (int)usedGlobalProperties.GetLength()-1;
  5029. }
  5030. void asCWriter::WriteUsedGlobalProps()
  5031. {
  5032. TimeIt("asCWriter::WriteUsedGlobalProps");
  5033. int c = (int)usedGlobalProperties.GetLength();
  5034. WriteEncodedInt64(c);
  5035. for( int n = 0; n < c; n++ )
  5036. {
  5037. asPWORD *p = (asPWORD*)usedGlobalProperties[n];
  5038. // Find the property descriptor from the address
  5039. asCGlobalProperty *prop = 0;
  5040. asSMapNode<void*, asCGlobalProperty*> *cursor;
  5041. if( engine->varAddressMap.MoveTo(&cursor, p) )
  5042. {
  5043. prop = engine->varAddressMap.GetValue(cursor);
  5044. }
  5045. asASSERT(prop);
  5046. // Store the name and type of the property so we can find it again on loading
  5047. WriteString(&prop->name);
  5048. WriteString(&prop->nameSpace->name);
  5049. WriteDataType(&prop->type);
  5050. // Also store whether the property is a module property or a registered property
  5051. char moduleProp = 0;
  5052. if( prop->realAddress == 0 )
  5053. moduleProp = 1;
  5054. WriteData(&moduleProp, 1);
  5055. }
  5056. }
  5057. void asCWriter::WriteUsedObjectProps()
  5058. {
  5059. TimeIt("asCWriter::WriteUsedObjectProps");
  5060. int c = (int)usedObjectProperties.GetLength();
  5061. WriteEncodedInt64(c);
  5062. for( asUINT n = 0; n < usedObjectProperties.GetLength(); n++ )
  5063. {
  5064. WriteTypeInfo(usedObjectProperties[n].objType);
  5065. WriteString(&usedObjectProperties[n].prop->name);
  5066. }
  5067. }
  5068. int asCWriter::FindObjectPropIndex(short offset, int typeId, asDWORD *bc)
  5069. {
  5070. // If the last property was a composite property, then just return 0, because it won't be translated
  5071. static bool lastWasComposite = false;
  5072. if (lastWasComposite)
  5073. {
  5074. lastWasComposite = false;
  5075. return 0;
  5076. }
  5077. asCObjectType *objType = engine->GetObjectTypeFromTypeId(typeId);
  5078. asCObjectProperty *objProp = 0;
  5079. // Look for composite properties first
  5080. for (asUINT n = 0; objProp == 0 && n < objType->properties.GetLength(); n++)
  5081. {
  5082. // TODO: Composite: Perhaps it would be better to add metadata to the bytecode instruction to give the exact property.
  5083. // That would also allow me to remove the typeId from the bytecode instruction itself
  5084. // Or perhaps a new bytecode instruction all together for accessing composite properties
  5085. // One that would do both offsets and indirection in a single go.
  5086. // TODO: Composite: Need to be able to handle instructions replaced in bytecode optimizations too
  5087. if (objType->properties[n]->compositeOffset == offset)
  5088. {
  5089. // This is a potential composite property. Need to check the following instructions to be sure
  5090. objProp = objType->properties[n];
  5091. asDWORD *bcTemp = bc;
  5092. bcTemp += asBCTypeSize[asBCInfo[*(asBYTE*)bcTemp].type];
  5093. if (objProp->isCompositeIndirect)
  5094. {
  5095. // The next instruction would be a asBC_RDSPtr
  5096. if ((*(asBYTE*)bcTemp) != asBC_RDSPtr)
  5097. {
  5098. objProp = 0;
  5099. continue;
  5100. }
  5101. bcTemp += asBCTypeSize[asBCInfo[*(asBYTE*)bcTemp].type];
  5102. }
  5103. // The next instruction would be asBC_ADDSi
  5104. if ((*(asBYTE*)bcTemp) != asBC_ADDSi)
  5105. {
  5106. objProp = 0;
  5107. continue;
  5108. }
  5109. // Make sure the offset is the expected one
  5110. if (*(((short*)bcTemp) + 1) != objProp->byteOffset)
  5111. {
  5112. objProp = 0;
  5113. continue;
  5114. }
  5115. }
  5116. }
  5117. // If none of the composite properties matched, then look for ordinary property
  5118. for (asUINT n = 0; objProp == 0 && n < objType->properties.GetLength(); n++)
  5119. {
  5120. if (objType->properties[n]->byteOffset == offset && !(objType->properties[n]->compositeOffset || objType->properties[n]->isCompositeIndirect))
  5121. objProp = objType->properties[n];
  5122. }
  5123. asASSERT(objProp);
  5124. // Remember if this is a composite property as the next call will then be for the same property
  5125. if (objProp->compositeOffset || objProp->isCompositeIndirect)
  5126. lastWasComposite = true;
  5127. // Now check if the same property has already been accessed
  5128. for( asUINT n = 0; n < usedObjectProperties.GetLength(); n++ )
  5129. {
  5130. if( usedObjectProperties[n].objType == objType &&
  5131. usedObjectProperties[n].prop == objProp )
  5132. return n;
  5133. }
  5134. // Insert the new property
  5135. SObjProp prop = {objType, objProp};
  5136. usedObjectProperties.PushLast(prop);
  5137. return (int)usedObjectProperties.GetLength() - 1;
  5138. }
  5139. int asCWriter::FindFunctionIndex(asCScriptFunction *func)
  5140. {
  5141. for( asUINT n = 0; n < usedFunctions.GetLength(); n++ )
  5142. {
  5143. if( usedFunctions[n] == func )
  5144. return n;
  5145. }
  5146. usedFunctions.PushLast(func);
  5147. return (int)usedFunctions.GetLength() - 1;
  5148. }
  5149. int asCWriter::FindTypeIdIdx(int typeId)
  5150. {
  5151. asUINT n;
  5152. for( n = 0; n < usedTypeIds.GetLength(); n++ )
  5153. {
  5154. if( usedTypeIds[n] == typeId )
  5155. return n;
  5156. }
  5157. usedTypeIds.PushLast(typeId);
  5158. return (int)usedTypeIds.GetLength() - 1;
  5159. }
  5160. int asCWriter::FindTypeInfoIdx(asCTypeInfo *obj)
  5161. {
  5162. asUINT n;
  5163. for( n = 0; n < usedTypes.GetLength(); n++ )
  5164. {
  5165. if( usedTypes[n] == obj )
  5166. return n;
  5167. }
  5168. usedTypes.PushLast(obj);
  5169. return (int)usedTypes.GetLength() - 1;
  5170. }
  5171. #endif // AS_NO_COMPILER
  5172. END_AS_NAMESPACE