as_restore.cpp 150 KB

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