as_restore.cpp 131 KB

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