as_restore.cpp 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741
  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->SetExplicit((bits & 32) ? true : false);
  1086. func->dontCleanUpOnException = (bits & 2) ? true : false;
  1087. if ((bits & 4) && isExternal)
  1088. *isExternal = true;
  1089. // for external shared functions the rest is not needed
  1090. if (!(bits & 4))
  1091. {
  1092. func->AllocateScriptFunctionData();
  1093. if (func->scriptData == 0)
  1094. {
  1095. // Out of memory
  1096. error = true;
  1097. func->DestroyHalfCreated();
  1098. return 0;
  1099. }
  1100. if (addToGC && !addToModule)
  1101. engine->gc.AddScriptObjectToGC(func, &engine->functionBehaviours);
  1102. ReadByteCode(func);
  1103. func->scriptData->variableSpace = ReadEncodedUInt();
  1104. func->scriptData->objVariablesOnHeap = 0;
  1105. if (bits & 8)
  1106. {
  1107. count = ReadEncodedUInt();
  1108. func->scriptData->objVariablePos.Allocate(count, false);
  1109. func->scriptData->objVariableTypes.Allocate(count, false);
  1110. for (i = 0; i < count; ++i)
  1111. {
  1112. func->scriptData->objVariableTypes.PushLast(ReadTypeInfo());
  1113. num = ReadEncodedUInt();
  1114. func->scriptData->objVariablePos.PushLast(num);
  1115. if (error)
  1116. {
  1117. // No need to continue (the error has already been reported before)
  1118. func->DestroyHalfCreated();
  1119. return 0;
  1120. }
  1121. }
  1122. if (count > 0)
  1123. func->scriptData->objVariablesOnHeap = ReadEncodedUInt();
  1124. int length = ReadEncodedUInt();
  1125. func->scriptData->objVariableInfo.SetLength(length);
  1126. for (i = 0; i < length; ++i)
  1127. {
  1128. func->scriptData->objVariableInfo[i].programPos = ReadEncodedUInt();
  1129. func->scriptData->objVariableInfo[i].variableOffset = ReadEncodedUInt();
  1130. asEObjVarInfoOption option = (asEObjVarInfoOption)ReadEncodedUInt();
  1131. func->scriptData->objVariableInfo[i].option = option;
  1132. if (option != asOBJ_INIT &&
  1133. option != asOBJ_UNINIT &&
  1134. option != asBLOCK_BEGIN &&
  1135. option != asBLOCK_END &&
  1136. option != asOBJ_VARDECL)
  1137. {
  1138. error = true;
  1139. func->DestroyHalfCreated();
  1140. return 0;
  1141. }
  1142. }
  1143. }
  1144. if (bits & 16)
  1145. {
  1146. // Read info on try/catch blocks
  1147. int length = ReadEncodedUInt();
  1148. func->scriptData->tryCatchInfo.SetLength(length);
  1149. for (i = 0; i < length; ++i)
  1150. {
  1151. // The program position must be adjusted to be in number of instructions
  1152. func->scriptData->tryCatchInfo[i].tryPos = ReadEncodedUInt();
  1153. func->scriptData->tryCatchInfo[i].catchPos = ReadEncodedUInt();
  1154. }
  1155. }
  1156. if (!noDebugInfo)
  1157. {
  1158. int length = ReadEncodedUInt();
  1159. func->scriptData->lineNumbers.SetLength(length);
  1160. if (int(func->scriptData->lineNumbers.GetLength()) != length)
  1161. {
  1162. // Out of memory
  1163. error = true;
  1164. func->DestroyHalfCreated();
  1165. return 0;
  1166. }
  1167. for (i = 0; i < length; ++i)
  1168. func->scriptData->lineNumbers[i] = ReadEncodedUInt();
  1169. // Read the array of script sections
  1170. length = ReadEncodedUInt();
  1171. func->scriptData->sectionIdxs.SetLength(length);
  1172. if (int(func->scriptData->sectionIdxs.GetLength()) != length)
  1173. {
  1174. // Out of memory
  1175. error = true;
  1176. func->DestroyHalfCreated();
  1177. return 0;
  1178. }
  1179. for (i = 0; i < length; ++i)
  1180. {
  1181. if ((i & 1) == 0)
  1182. func->scriptData->sectionIdxs[i] = ReadEncodedUInt();
  1183. else
  1184. {
  1185. asCString str;
  1186. ReadString(&str);
  1187. func->scriptData->sectionIdxs[i] = engine->GetScriptSectionNameIndex(str.AddressOf());
  1188. }
  1189. }
  1190. }
  1191. // Read the variable information
  1192. if (!noDebugInfo)
  1193. {
  1194. int length = ReadEncodedUInt();
  1195. func->scriptData->variables.Allocate(length, false);
  1196. for (i = 0; i < length; i++)
  1197. {
  1198. asSScriptVariable *var = asNEW(asSScriptVariable);
  1199. if (var == 0)
  1200. {
  1201. // Out of memory
  1202. error = true;
  1203. func->DestroyHalfCreated();
  1204. return 0;
  1205. }
  1206. func->scriptData->variables.PushLast(var);
  1207. var->declaredAtProgramPos = ReadEncodedUInt();
  1208. var->stackOffset = ReadEncodedUInt();
  1209. ReadString(&var->name);
  1210. ReadDataType(&var->type);
  1211. if (error)
  1212. {
  1213. // No need to continue (the error has already been reported before)
  1214. func->DestroyHalfCreated();
  1215. return 0;
  1216. }
  1217. }
  1218. }
  1219. // Read script section name
  1220. if (!noDebugInfo)
  1221. {
  1222. asCString name;
  1223. ReadString(&name);
  1224. func->scriptData->scriptSectionIdx = engine->GetScriptSectionNameIndex(name.AddressOf());
  1225. func->scriptData->declaredAt = ReadEncodedUInt();
  1226. }
  1227. // Read parameter names
  1228. if (!noDebugInfo)
  1229. {
  1230. asUINT countParam = asUINT(ReadEncodedUInt64());
  1231. if (countParam > func->parameterTypes.GetLength())
  1232. {
  1233. error = true;
  1234. func->DestroyHalfCreated();
  1235. return 0;
  1236. }
  1237. func->parameterNames.SetLength(countParam);
  1238. for (asUINT n = 0; n < countParam; n++)
  1239. ReadString(&func->parameterNames[n]);
  1240. }
  1241. }
  1242. }
  1243. }
  1244. else if( func->funcType == asFUNC_VIRTUAL || func->funcType == asFUNC_INTERFACE )
  1245. {
  1246. func->vfTableIdx = ReadEncodedUInt();
  1247. }
  1248. else if( func->funcType == asFUNC_FUNCDEF )
  1249. {
  1250. asBYTE bits;
  1251. ReadData(&bits, 1);
  1252. if( bits & 1 )
  1253. func->SetShared(true);
  1254. if ((bits & 2) && isExternal)
  1255. *isExternal = true;
  1256. // The asCFuncdefType constructor adds itself to the func->funcdefType member
  1257. asCFuncdefType *fdt = asNEW(asCFuncdefType)(engine, func);
  1258. fdt->parentClass = parentClass;
  1259. }
  1260. if( addToModule )
  1261. {
  1262. // The refCount is already 1
  1263. module->scriptFunctions.PushLast(func);
  1264. func->module = module;
  1265. }
  1266. if( addToEngine )
  1267. {
  1268. func->id = engine->GetNextScriptFunctionId();
  1269. engine->AddScriptFunction(func);
  1270. }
  1271. if( func->objectType )
  1272. func->ComputeSignatureId();
  1273. return func;
  1274. }
  1275. void asCReader::ReadTypeDeclaration(asCTypeInfo *type, int phase, bool *isExternal)
  1276. {
  1277. if( phase == 1 )
  1278. {
  1279. asASSERT(isExternal);
  1280. if (isExternal)
  1281. *isExternal = false;
  1282. // Read the initial attributes
  1283. ReadString(&type->name);
  1284. ReadData(&type->flags, 4);
  1285. type->size = ReadEncodedUInt();
  1286. asCString ns;
  1287. ReadString(&ns);
  1288. type->nameSpace = engine->AddNameSpace(ns.AddressOf());
  1289. // Verify that the flags match the asCTypeInfo
  1290. if ((CastToEnumType(type) && !(type->flags & asOBJ_ENUM)) ||
  1291. (CastToFuncdefType(type) && !(type->flags & asOBJ_FUNCDEF)) ||
  1292. (CastToObjectType(type) && !(type->flags & (asOBJ_REF | asOBJ_VALUE))))
  1293. {
  1294. error = true;
  1295. return;
  1296. }
  1297. // Reset the size of script classes, since it will be recalculated as properties are added
  1298. if( (type->flags & asOBJ_SCRIPT_OBJECT) && type->size != 0 )
  1299. type->size = sizeof(asCScriptObject);
  1300. asCObjectType *ot = CastToObjectType(type);
  1301. if (ot)
  1302. {
  1303. // Use the default script class behaviours
  1304. ot->beh = engine->scriptTypeBehaviours.beh;
  1305. ot->beh.construct = 0;
  1306. ot->beh.factory = 0;
  1307. ot->beh.constructors.PopLast(); // These will be read from the file
  1308. ot->beh.factories.PopLast(); // These will be read from the file
  1309. engine->scriptFunctions[ot->beh.addref]->AddRefInternal();
  1310. engine->scriptFunctions[ot->beh.release]->AddRefInternal();
  1311. engine->scriptFunctions[ot->beh.gcEnumReferences]->AddRefInternal();
  1312. engine->scriptFunctions[ot->beh.gcGetFlag]->AddRefInternal();
  1313. engine->scriptFunctions[ot->beh.gcGetRefCount]->AddRefInternal();
  1314. engine->scriptFunctions[ot->beh.gcReleaseAllReferences]->AddRefInternal();
  1315. engine->scriptFunctions[ot->beh.gcSetFlag]->AddRefInternal();
  1316. engine->scriptFunctions[ot->beh.copy]->AddRefInternal();
  1317. // TODO: weak: Should not do this if the class has been declared with 'noweak'
  1318. engine->scriptFunctions[ot->beh.getWeakRefFlag]->AddRefInternal();
  1319. }
  1320. // external shared flag
  1321. if (type->flags & asOBJ_SHARED)
  1322. {
  1323. char c;
  1324. ReadData(&c, 1);
  1325. if (c == 'e')
  1326. *isExternal = true;
  1327. else if (c != ' ')
  1328. {
  1329. error = true;
  1330. return;
  1331. }
  1332. }
  1333. }
  1334. else if( phase == 2 )
  1335. {
  1336. // external shared types doesn't store this
  1337. if ((type->flags & asOBJ_SHARED) && module->externalTypes.IndexOf(type) >= 0)
  1338. return;
  1339. if( type->flags & asOBJ_ENUM )
  1340. {
  1341. asCEnumType *t = CastToEnumType(type);
  1342. int count = ReadEncodedUInt();
  1343. bool sharedExists = existingShared.MoveTo(0, type);
  1344. if( !sharedExists )
  1345. {
  1346. t->enumValues.Allocate(count, false);
  1347. for( int n = 0; n < count; n++ )
  1348. {
  1349. asSEnumValue *e = asNEW(asSEnumValue);
  1350. if( e == 0 )
  1351. {
  1352. // Out of memory
  1353. error = true;
  1354. return;
  1355. }
  1356. ReadString(&e->name);
  1357. ReadData(&e->value, 4); // TODO: Should be encoded
  1358. t->enumValues.PushLast(e);
  1359. }
  1360. }
  1361. else
  1362. {
  1363. // Verify that the enum values exists in the original
  1364. asCString name;
  1365. int value;
  1366. for( int n = 0; n < count; n++ )
  1367. {
  1368. ReadString(&name);
  1369. ReadData(&value, 4); // TODO: Should be encoded
  1370. bool found = false;
  1371. for( asUINT e = 0; e < t->enumValues.GetLength(); e++ )
  1372. {
  1373. if( t->enumValues[e]->name == name &&
  1374. t->enumValues[e]->value == value )
  1375. {
  1376. found = true;
  1377. break;
  1378. }
  1379. }
  1380. if( !found )
  1381. {
  1382. asCString str;
  1383. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1384. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1385. Error(TXT_INVALID_BYTECODE_d);
  1386. }
  1387. }
  1388. }
  1389. }
  1390. else if( type->flags & asOBJ_TYPEDEF )
  1391. {
  1392. asCTypedefType *td = CastToTypedefType(type);
  1393. asASSERT(td);
  1394. eTokenType t = (eTokenType)ReadEncodedUInt();
  1395. td->aliasForType = asCDataType::CreatePrimitive(t, false);
  1396. }
  1397. else
  1398. {
  1399. asCObjectType *ot = CastToObjectType(type);
  1400. asASSERT(ot);
  1401. // If the type is shared and pre-existing, we should just
  1402. // validate that the loaded methods match the original
  1403. bool sharedExists = existingShared.MoveTo(0, type);
  1404. if( sharedExists )
  1405. {
  1406. asCObjectType *dt = CastToObjectType(ReadTypeInfo());
  1407. if( ot->derivedFrom != dt )
  1408. {
  1409. asCString str;
  1410. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1411. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1412. Error(TXT_INVALID_BYTECODE_d);
  1413. }
  1414. }
  1415. else
  1416. {
  1417. ot->derivedFrom = CastToObjectType(ReadTypeInfo());
  1418. if( ot->derivedFrom )
  1419. ot->derivedFrom->AddRefInternal();
  1420. }
  1421. // interfaces[] / interfaceVFTOffsets[]
  1422. int size = ReadEncodedUInt();
  1423. if( sharedExists )
  1424. {
  1425. for( int n = 0; n < size; n++ )
  1426. {
  1427. asCObjectType *intf = CastToObjectType(ReadTypeInfo());
  1428. if (!ot->IsInterface())
  1429. ReadEncodedUInt();
  1430. if( !type->Implements(intf) )
  1431. {
  1432. asCString str;
  1433. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1434. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1435. Error(TXT_INVALID_BYTECODE_d);
  1436. }
  1437. }
  1438. }
  1439. else
  1440. {
  1441. ot->interfaces.Allocate(size, false);
  1442. if( !ot->IsInterface() )
  1443. ot->interfaceVFTOffsets.Allocate(size, false);
  1444. for( int n = 0; n < size; n++ )
  1445. {
  1446. asCObjectType *intf = CastToObjectType(ReadTypeInfo());
  1447. ot->interfaces.PushLast(intf);
  1448. if (!ot->IsInterface())
  1449. {
  1450. asUINT offset = ReadEncodedUInt();
  1451. ot->interfaceVFTOffsets.PushLast(offset);
  1452. }
  1453. }
  1454. }
  1455. // behaviours
  1456. if( !ot->IsInterface() && type->flags != asOBJ_TYPEDEF && type->flags != asOBJ_ENUM )
  1457. {
  1458. bool isNew;
  1459. asCScriptFunction *func = ReadFunction(isNew, !sharedExists, !sharedExists, !sharedExists);
  1460. if( sharedExists )
  1461. {
  1462. // Find the real function in the object, and update the savedFunctions array
  1463. asCScriptFunction *realFunc = engine->GetScriptFunction(ot->beh.destruct);
  1464. if( (realFunc == 0 && func == 0) || realFunc->IsSignatureEqual(func) )
  1465. {
  1466. // If the function is not the last, then the substitution has already occurred before
  1467. if( func && savedFunctions[savedFunctions.GetLength()-1] == func )
  1468. savedFunctions[savedFunctions.GetLength()-1] = realFunc;
  1469. }
  1470. else
  1471. {
  1472. asCString str;
  1473. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1474. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1475. Error(TXT_INVALID_BYTECODE_d);
  1476. }
  1477. if( func )
  1478. {
  1479. if( isNew )
  1480. {
  1481. // Destroy the function without releasing any references
  1482. func->id = 0;
  1483. func->scriptData->byteCode.SetLength(0);
  1484. func->ReleaseInternal();
  1485. }
  1486. module->scriptFunctions.PushLast(realFunc);
  1487. realFunc->AddRefInternal();
  1488. dontTranslate.Insert(realFunc, true);
  1489. }
  1490. }
  1491. else
  1492. {
  1493. if( func )
  1494. {
  1495. ot->beh.destruct = func->id;
  1496. func->AddRefInternal();
  1497. }
  1498. else
  1499. ot->beh.destruct = 0;
  1500. }
  1501. size = ReadEncodedUInt();
  1502. for( int n = 0; n < size; n++ )
  1503. {
  1504. func = ReadFunction(isNew, !sharedExists, !sharedExists, !sharedExists);
  1505. if( func )
  1506. {
  1507. if( sharedExists )
  1508. {
  1509. // Find the real function in the object, and update the savedFunctions array
  1510. bool found = false;
  1511. for( asUINT f = 0; f < ot->beh.constructors.GetLength(); f++ )
  1512. {
  1513. asCScriptFunction *realFunc = engine->GetScriptFunction(ot->beh.constructors[f]);
  1514. if( realFunc->IsSignatureEqual(func) )
  1515. {
  1516. // If the function is not the last, then the substitution has already occurred before
  1517. if( savedFunctions[savedFunctions.GetLength()-1] == func )
  1518. savedFunctions[savedFunctions.GetLength()-1] = realFunc;
  1519. found = true;
  1520. module->scriptFunctions.PushLast(realFunc);
  1521. realFunc->AddRefInternal();
  1522. dontTranslate.Insert(realFunc, true);
  1523. break;
  1524. }
  1525. }
  1526. if( !found )
  1527. {
  1528. asCString str;
  1529. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1530. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1531. Error(TXT_INVALID_BYTECODE_d);
  1532. }
  1533. if( isNew )
  1534. {
  1535. // Destroy the function without releasing any references
  1536. func->id = 0;
  1537. func->scriptData->byteCode.SetLength(0);
  1538. func->ReleaseInternal();
  1539. }
  1540. }
  1541. else
  1542. {
  1543. ot->beh.constructors.PushLast(func->id);
  1544. func->AddRefInternal();
  1545. if( func->parameterTypes.GetLength() == 0 )
  1546. ot->beh.construct = func->id;
  1547. }
  1548. }
  1549. else
  1550. {
  1551. Error(TXT_INVALID_BYTECODE_d);
  1552. }
  1553. func = ReadFunction(isNew, !sharedExists, !sharedExists, !sharedExists);
  1554. if( func )
  1555. {
  1556. if( sharedExists )
  1557. {
  1558. // Find the real function in the object, and update the savedFunctions array
  1559. bool found = false;
  1560. for( asUINT f = 0; f < ot->beh.factories.GetLength(); f++ )
  1561. {
  1562. asCScriptFunction *realFunc = engine->GetScriptFunction(ot->beh.factories[f]);
  1563. if( realFunc->IsSignatureEqual(func) )
  1564. {
  1565. // If the function is not the last, then the substitution has already occurred before
  1566. if( savedFunctions[savedFunctions.GetLength()-1] == func )
  1567. savedFunctions[savedFunctions.GetLength()-1] = realFunc;
  1568. found = true;
  1569. module->scriptFunctions.PushLast(realFunc);
  1570. realFunc->AddRefInternal();
  1571. dontTranslate.Insert(realFunc, true);
  1572. break;
  1573. }
  1574. }
  1575. if( !found )
  1576. {
  1577. asCString str;
  1578. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1579. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1580. Error(TXT_INVALID_BYTECODE_d);
  1581. }
  1582. if( isNew )
  1583. {
  1584. // Destroy the function without releasing any references
  1585. func->id = 0;
  1586. func->scriptData->byteCode.SetLength(0);
  1587. func->ReleaseInternal();
  1588. }
  1589. }
  1590. else
  1591. {
  1592. ot->beh.factories.PushLast(func->id);
  1593. func->AddRefInternal();
  1594. if( func->parameterTypes.GetLength() == 0 )
  1595. ot->beh.factory = func->id;
  1596. }
  1597. }
  1598. else
  1599. {
  1600. Error(TXT_INVALID_BYTECODE_d);
  1601. }
  1602. }
  1603. }
  1604. // methods[]
  1605. size = ReadEncodedUInt();
  1606. int n;
  1607. for( n = 0; n < size; n++ )
  1608. {
  1609. bool isNew;
  1610. asCScriptFunction *func = ReadFunction(isNew, !sharedExists, !sharedExists, !sharedExists);
  1611. if( func )
  1612. {
  1613. if( sharedExists )
  1614. {
  1615. // Find the real function in the object, and update the savedFunctions array
  1616. bool found = false;
  1617. for( asUINT f = 0; f < ot->methods.GetLength(); f++ )
  1618. {
  1619. asCScriptFunction *realFunc = engine->GetScriptFunction(ot->methods[f]);
  1620. if( realFunc->IsSignatureEqual(func) )
  1621. {
  1622. // If the function is not the last, then the substitution has already occurred before
  1623. if( savedFunctions[savedFunctions.GetLength()-1] == func )
  1624. savedFunctions[savedFunctions.GetLength()-1] = realFunc;
  1625. found = true;
  1626. module->scriptFunctions.PushLast(realFunc);
  1627. realFunc->AddRefInternal();
  1628. dontTranslate.Insert(realFunc, true);
  1629. break;
  1630. }
  1631. }
  1632. if( !found )
  1633. {
  1634. asCString str;
  1635. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1636. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1637. Error(TXT_INVALID_BYTECODE_d);
  1638. }
  1639. if( isNew )
  1640. {
  1641. // Destroy the function without releasing any references
  1642. func->id = 0;
  1643. if( func->scriptData )
  1644. func->scriptData->byteCode.SetLength(0);
  1645. func->ReleaseInternal();
  1646. }
  1647. }
  1648. else
  1649. {
  1650. // If the method is the assignment operator we need to replace the default implementation
  1651. if( func->name == "opAssign" && func->parameterTypes.GetLength() == 1 &&
  1652. func->parameterTypes[0].GetTypeInfo() == func->objectType &&
  1653. (func->inOutFlags[0] & asTM_INREF) )
  1654. {
  1655. engine->scriptFunctions[ot->beh.copy]->ReleaseInternal();
  1656. ot->beh.copy = func->id;
  1657. func->AddRefInternal();
  1658. }
  1659. ot->methods.PushLast(func->id);
  1660. func->AddRefInternal();
  1661. }
  1662. }
  1663. else
  1664. {
  1665. Error(TXT_INVALID_BYTECODE_d);
  1666. }
  1667. }
  1668. // virtualFunctionTable[]
  1669. size = ReadEncodedUInt();
  1670. for( n = 0; n < size; n++ )
  1671. {
  1672. bool isNew;
  1673. asCScriptFunction *func = ReadFunction(isNew, !sharedExists, !sharedExists, !sharedExists);
  1674. if( func )
  1675. {
  1676. if( sharedExists )
  1677. {
  1678. // Find the real function in the object, and update the savedFunctions array
  1679. bool found = false;
  1680. for( asUINT f = 0; f < ot->virtualFunctionTable.GetLength(); f++ )
  1681. {
  1682. asCScriptFunction *realFunc = ot->virtualFunctionTable[f];
  1683. if( realFunc->IsSignatureEqual(func) )
  1684. {
  1685. // If the function is not the last, then the substitution has already occurred before
  1686. if( savedFunctions[savedFunctions.GetLength()-1] == func )
  1687. savedFunctions[savedFunctions.GetLength()-1] = realFunc;
  1688. found = true;
  1689. module->scriptFunctions.PushLast(realFunc);
  1690. realFunc->AddRefInternal();
  1691. dontTranslate.Insert(realFunc, true);
  1692. break;
  1693. }
  1694. }
  1695. if( !found )
  1696. {
  1697. asCString str;
  1698. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, type->GetName());
  1699. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1700. Error(TXT_INVALID_BYTECODE_d);
  1701. }
  1702. if( isNew )
  1703. {
  1704. // Destroy the function without releasing any references
  1705. func->id = 0;
  1706. if( func->scriptData )
  1707. func->scriptData->byteCode.SetLength(0);
  1708. func->ReleaseInternal();
  1709. }
  1710. }
  1711. else
  1712. {
  1713. ot->virtualFunctionTable.PushLast(func);
  1714. func->AddRefInternal();
  1715. }
  1716. }
  1717. else
  1718. {
  1719. Error(TXT_INVALID_BYTECODE_d);
  1720. }
  1721. }
  1722. }
  1723. }
  1724. else if( phase == 3 )
  1725. {
  1726. // external shared types doesn't store this
  1727. if ((type->flags & asOBJ_SHARED) && module->externalTypes.IndexOf(type) >= 0)
  1728. return;
  1729. asCObjectType *ot = CastToObjectType(type);
  1730. // This is only done for object types
  1731. asASSERT(ot);
  1732. // properties[]
  1733. asUINT size = ReadEncodedUInt();
  1734. for( asUINT n = 0; n < size; n++ )
  1735. ReadObjectProperty(ot);
  1736. }
  1737. }
  1738. asWORD asCReader::ReadEncodedUInt16()
  1739. {
  1740. asDWORD dw = ReadEncodedUInt();
  1741. if( (dw>>16) != 0 && (dw>>16) != 0xFFFF )
  1742. {
  1743. Error(TXT_INVALID_BYTECODE_d);
  1744. }
  1745. return asWORD(dw & 0xFFFF);
  1746. }
  1747. asUINT asCReader::ReadEncodedUInt()
  1748. {
  1749. asQWORD qw = ReadEncodedUInt64();
  1750. if( (qw>>32) != 0 && (qw>>32) != 0xFFFFFFFF )
  1751. {
  1752. Error(TXT_INVALID_BYTECODE_d);
  1753. }
  1754. return asUINT(qw & 0xFFFFFFFFu);
  1755. }
  1756. asQWORD asCReader::ReadEncodedUInt64()
  1757. {
  1758. asQWORD i = 0;
  1759. asBYTE b;
  1760. ReadData(&b, 1);
  1761. bool isNegative = ( b & 0x80 ) ? true : false;
  1762. b &= 0x7F;
  1763. if( (b & 0x7F) == 0x7F )
  1764. {
  1765. ReadData(&b, 1); i = asQWORD(b) << 56;
  1766. ReadData(&b, 1); i += asQWORD(b) << 48;
  1767. ReadData(&b, 1); i += asQWORD(b) << 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 & 0x7E) == 0x7E )
  1775. {
  1776. i = asQWORD(b & 0x01) << 48;
  1777. ReadData(&b, 1); i += asQWORD(b) << 40;
  1778. ReadData(&b, 1); i += asQWORD(b) << 32;
  1779. ReadData(&b, 1); i += asUINT(b) << 24;
  1780. ReadData(&b, 1); i += asUINT(b) << 16;
  1781. ReadData(&b, 1); i += asUINT(b) << 8;
  1782. ReadData(&b, 1); i += b;
  1783. }
  1784. else if( (b & 0x7C) == 0x7C )
  1785. {
  1786. i = asQWORD(b & 0x03) << 40;
  1787. ReadData(&b, 1); i += asQWORD(b) << 32;
  1788. ReadData(&b, 1); i += asUINT(b) << 24;
  1789. ReadData(&b, 1); i += asUINT(b) << 16;
  1790. ReadData(&b, 1); i += asUINT(b) << 8;
  1791. ReadData(&b, 1); i += b;
  1792. }
  1793. else if( (b & 0x78) == 0x78 )
  1794. {
  1795. i = asQWORD(b & 0x07) << 32;
  1796. ReadData(&b, 1); i += asUINT(b) << 24;
  1797. ReadData(&b, 1); i += asUINT(b) << 16;
  1798. ReadData(&b, 1); i += asUINT(b) << 8;
  1799. ReadData(&b, 1); i += b;
  1800. }
  1801. else if( (b & 0x70) == 0x70 )
  1802. {
  1803. i = asUINT(b & 0x0F) << 24;
  1804. ReadData(&b, 1); i += asUINT(b) << 16;
  1805. ReadData(&b, 1); i += asUINT(b) << 8;
  1806. ReadData(&b, 1); i += b;
  1807. }
  1808. else if( (b & 0x60) == 0x60 )
  1809. {
  1810. i = asUINT(b & 0x1F) << 16;
  1811. ReadData(&b, 1); i += asUINT(b) << 8;
  1812. ReadData(&b, 1); i += b;
  1813. }
  1814. else if( (b & 0x40) == 0x40 )
  1815. {
  1816. i = asUINT(b & 0x3F) << 8;
  1817. ReadData(&b, 1); i += b;
  1818. }
  1819. else
  1820. {
  1821. i = b;
  1822. }
  1823. if( isNegative )
  1824. i = (asQWORD)(-asINT64(i));
  1825. return i;
  1826. }
  1827. void asCReader::ReadString(asCString* str)
  1828. {
  1829. asUINT len = ReadEncodedUInt();
  1830. if( len & 1 )
  1831. {
  1832. asUINT idx = len/2;
  1833. if( idx < savedStrings.GetLength() )
  1834. *str = savedStrings[idx];
  1835. else
  1836. Error(TXT_INVALID_BYTECODE_d);
  1837. }
  1838. else if( len > 0 )
  1839. {
  1840. len /= 2;
  1841. str->SetLength(len);
  1842. int r = stream->Read(str->AddressOf(), len);
  1843. if (r < 0)
  1844. Error(TXT_UNEXPECTED_END_OF_FILE);
  1845. savedStrings.PushLast(*str);
  1846. }
  1847. else
  1848. str->SetLength(0);
  1849. }
  1850. void asCReader::ReadGlobalProperty()
  1851. {
  1852. asCString name;
  1853. asCDataType type;
  1854. ReadString(&name);
  1855. asCString ns;
  1856. ReadString(&ns);
  1857. asSNameSpace *nameSpace = engine->AddNameSpace(ns.AddressOf());
  1858. ReadDataType(&type);
  1859. asCGlobalProperty *prop = module->AllocateGlobalProperty(name.AddressOf(), type, nameSpace);
  1860. // Read the initialization function
  1861. bool isNew;
  1862. // Do not add the function to the GC at this time. It will
  1863. // only be added to the GC when the module releases the property
  1864. asCScriptFunction *func = ReadFunction(isNew, false, true, false);
  1865. if( func )
  1866. {
  1867. // Make sure the function knows it is owned by the module
  1868. func->module = module;
  1869. prop->SetInitFunc(func);
  1870. func->ReleaseInternal();
  1871. }
  1872. }
  1873. void asCReader::ReadObjectProperty(asCObjectType *ot)
  1874. {
  1875. asCString name;
  1876. ReadString(&name);
  1877. asCDataType dt;
  1878. ReadDataType(&dt);
  1879. int flags = ReadEncodedUInt();
  1880. bool isPrivate = (flags & 1) ? true : false;
  1881. bool isProtected = (flags & 2) ? true : false;
  1882. bool isInherited = (flags & 4) ? true : false;
  1883. // TODO: shared: If the type is shared and pre-existing, we should just
  1884. // validate that the loaded methods match the original
  1885. if( !existingShared.MoveTo(0, ot) )
  1886. ot->AddPropertyToClass(name, dt, isPrivate, isProtected, isInherited);
  1887. }
  1888. void asCReader::ReadDataType(asCDataType *dt)
  1889. {
  1890. // Check if this is a previously used type
  1891. asUINT idx = ReadEncodedUInt();
  1892. if( idx != 0 )
  1893. {
  1894. // Get the datatype from the cache
  1895. *dt = savedDataTypes[idx-1];
  1896. return;
  1897. }
  1898. // Read the type definition
  1899. eTokenType tokenType = (eTokenType)ReadEncodedUInt();
  1900. // Reserve a spot in the savedDataTypes
  1901. asUINT saveSlot = savedDataTypes.GetLength();
  1902. savedDataTypes.PushLast(asCDataType());
  1903. // Read the datatype for the first time
  1904. asCTypeInfo *ti = 0;
  1905. if( tokenType == ttIdentifier )
  1906. ti = ReadTypeInfo();
  1907. // Read type flags as a bitmask
  1908. // Endian-safe code
  1909. bool isObjectHandle, isHandleToConst, isReference, isReadOnly;
  1910. char b = 0;
  1911. ReadData(&b, 1);
  1912. LOAD_FROM_BIT(isObjectHandle, b, 0);
  1913. LOAD_FROM_BIT(isHandleToConst, b, 1);
  1914. LOAD_FROM_BIT(isReference, b, 2);
  1915. LOAD_FROM_BIT(isReadOnly, b, 3);
  1916. if( tokenType == ttIdentifier )
  1917. *dt = asCDataType::CreateType(ti, false);
  1918. else
  1919. *dt = asCDataType::CreatePrimitive(tokenType, false);
  1920. if( isObjectHandle )
  1921. {
  1922. dt->MakeReadOnly(isHandleToConst ? true : false);
  1923. // Here we must allow a scoped type to be a handle
  1924. // e.g. if the datatype is for a system function
  1925. dt->MakeHandle(true, true);
  1926. }
  1927. dt->MakeReadOnly(isReadOnly ? true : false);
  1928. dt->MakeReference(isReference ? true : false);
  1929. // Update the previously saved slot
  1930. savedDataTypes[saveSlot] = *dt;
  1931. }
  1932. asCTypeInfo* asCReader::ReadTypeInfo()
  1933. {
  1934. asCTypeInfo *ot = 0;
  1935. char ch;
  1936. ReadData(&ch, 1);
  1937. if( ch == 'a' )
  1938. {
  1939. // Read the name of the template type
  1940. asCString typeName, ns;
  1941. ReadString(&typeName);
  1942. ReadString(&ns);
  1943. asSNameSpace *nameSpace = engine->AddNameSpace(ns.AddressOf());
  1944. asCTypeInfo *tmp = engine->GetRegisteredType(typeName.AddressOf(), nameSpace);
  1945. asCObjectType *tmpl = CastToObjectType(tmp);
  1946. if( tmpl == 0 )
  1947. {
  1948. asCString str;
  1949. str.Format(TXT_TEMPLATE_TYPE_s_DOESNT_EXIST, typeName.AddressOf());
  1950. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1951. Error(TXT_INVALID_BYTECODE_d);
  1952. return 0;
  1953. }
  1954. asUINT numSubTypes = ReadEncodedUInt();
  1955. asCArray<asCDataType> subTypes;
  1956. for( asUINT n = 0; n < numSubTypes; n++ )
  1957. {
  1958. ReadData(&ch, 1);
  1959. if( ch == 's' )
  1960. {
  1961. asCDataType dt;
  1962. ReadDataType(&dt);
  1963. subTypes.PushLast(dt);
  1964. }
  1965. else
  1966. {
  1967. eTokenType tokenType = (eTokenType)ReadEncodedUInt();
  1968. asCDataType dt = asCDataType::CreatePrimitive(tokenType, false);
  1969. subTypes.PushLast(dt);
  1970. }
  1971. }
  1972. // Return the actual template if the subtypes are the template's dummy types
  1973. if( tmpl->templateSubTypes == subTypes )
  1974. ot = tmpl;
  1975. else
  1976. {
  1977. // Get the template instance type based on the loaded subtypes
  1978. ot = engine->GetTemplateInstanceType(tmpl, subTypes, module);
  1979. }
  1980. if( ot == 0 )
  1981. {
  1982. // Show all subtypes in error message
  1983. asCString sub = subTypes[0].Format(nameSpace);
  1984. for( asUINT n = 1; n < subTypes.GetLength(); n++ )
  1985. {
  1986. sub += ",";
  1987. sub += subTypes[n].Format(nameSpace);
  1988. }
  1989. asCString str;
  1990. str.Format(TXT_INSTANCING_INVLD_TMPL_TYPE_s_s, typeName.AddressOf(), sub.AddressOf());
  1991. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1992. Error(TXT_INVALID_BYTECODE_d);
  1993. return 0;
  1994. }
  1995. }
  1996. else if( ch == 'l' )
  1997. {
  1998. asCObjectType *st = CastToObjectType(ReadTypeInfo());
  1999. if( st == 0 || st->beh.listFactory == 0 )
  2000. {
  2001. Error(TXT_INVALID_BYTECODE_d);
  2002. return 0;
  2003. }
  2004. ot = engine->GetListPatternType(st->beh.listFactory);
  2005. }
  2006. else if( ch == 's' )
  2007. {
  2008. // Read the name of the template subtype
  2009. asCString typeName;
  2010. ReadString(&typeName);
  2011. // Find the template subtype
  2012. ot = 0;
  2013. for( asUINT n = 0; n < engine->templateSubTypes.GetLength(); n++ )
  2014. {
  2015. if( engine->templateSubTypes[n] && engine->templateSubTypes[n]->name == typeName )
  2016. {
  2017. ot = engine->templateSubTypes[n];
  2018. break;
  2019. }
  2020. }
  2021. if( ot == 0 )
  2022. {
  2023. asCString str;
  2024. str.Format(TXT_TEMPLATE_SUBTYPE_s_DOESNT_EXIST, typeName.AddressOf());
  2025. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2026. Error(TXT_INVALID_BYTECODE_d);
  2027. return 0;
  2028. }
  2029. }
  2030. else if( ch == 'o' )
  2031. {
  2032. // Read the object type name
  2033. asCString typeName, ns;
  2034. ReadString(&typeName);
  2035. ReadString(&ns);
  2036. asSNameSpace *nameSpace = engine->AddNameSpace(ns.AddressOf());
  2037. if( typeName.GetLength() && typeName != "$obj" && typeName != "$func" )
  2038. {
  2039. // Find the object type
  2040. ot = module->GetType(typeName.AddressOf(), nameSpace);
  2041. if (!ot)
  2042. ot = engine->GetRegisteredType(typeName.AddressOf(), nameSpace);
  2043. if( ot == 0 )
  2044. {
  2045. asCString str;
  2046. str.Format(TXT_OBJECT_TYPE_s_DOESNT_EXIST, typeName.AddressOf());
  2047. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2048. Error(TXT_INVALID_BYTECODE_d);
  2049. return 0;
  2050. }
  2051. }
  2052. else if( typeName == "$obj" )
  2053. {
  2054. ot = &engine->scriptTypeBehaviours;
  2055. }
  2056. else if( typeName == "$func" )
  2057. {
  2058. ot = &engine->functionBehaviours;
  2059. }
  2060. else
  2061. asASSERT( false );
  2062. }
  2063. else if (ch == 'c')
  2064. {
  2065. // Read the object type name
  2066. asCString typeName, ns;
  2067. ReadString(&typeName);
  2068. // Read the parent class
  2069. asCObjectType *parentClass = CastToObjectType(ReadTypeInfo());
  2070. if (parentClass == 0)
  2071. {
  2072. Error(TXT_INVALID_BYTECODE_d);
  2073. return 0;
  2074. }
  2075. // Find the child type in the parentClass
  2076. for (asUINT n = 0; n < parentClass->childFuncDefs.GetLength(); n++)
  2077. {
  2078. if (parentClass->childFuncDefs[n]->name == typeName)
  2079. ot = parentClass->childFuncDefs[n];
  2080. }
  2081. if (ot == 0)
  2082. {
  2083. asCString str;
  2084. str.Format(TXT_OBJECT_TYPE_s_DOESNT_EXIST, typeName.AddressOf());
  2085. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2086. Error(TXT_INVALID_BYTECODE_d);
  2087. return 0;
  2088. }
  2089. }
  2090. else
  2091. {
  2092. // No object type
  2093. asASSERT( ch == '\0' || error );
  2094. ot = 0;
  2095. }
  2096. return ot;
  2097. }
  2098. void asCReader::ReadByteCode(asCScriptFunction *func)
  2099. {
  2100. asASSERT( func->scriptData );
  2101. // Read number of instructions
  2102. asUINT total, numInstructions;
  2103. total = numInstructions = ReadEncodedUInt();
  2104. // Reserve some space for the instructions
  2105. func->scriptData->byteCode.AllocateNoConstruct(numInstructions, false);
  2106. asUINT pos = 0;
  2107. while( numInstructions )
  2108. {
  2109. asBYTE b;
  2110. ReadData(&b, 1);
  2111. // Allocate the space for the instruction
  2112. asUINT len = asBCTypeSize[asBCInfo[b].type];
  2113. asUINT newSize = asUINT(func->scriptData->byteCode.GetLength()) + len;
  2114. if( func->scriptData->byteCode.GetCapacity() < newSize )
  2115. {
  2116. // Determine the average size of the loaded instructions and re-estimate the final size
  2117. asUINT size = asUINT(float(newSize) / (total - numInstructions) * total) + 1;
  2118. func->scriptData->byteCode.AllocateNoConstruct(size, true);
  2119. }
  2120. if( !func->scriptData->byteCode.SetLengthNoConstruct(newSize) )
  2121. {
  2122. // Out of memory
  2123. error = true;
  2124. return;
  2125. }
  2126. asDWORD *bc = func->scriptData->byteCode.AddressOf() + pos;
  2127. pos += len;
  2128. switch( asBCInfo[b].type )
  2129. {
  2130. case asBCTYPE_NO_ARG:
  2131. {
  2132. *(asBYTE*)(bc) = b;
  2133. bc++;
  2134. }
  2135. break;
  2136. case asBCTYPE_W_ARG:
  2137. case asBCTYPE_wW_ARG:
  2138. case asBCTYPE_rW_ARG:
  2139. {
  2140. *(asBYTE*)(bc) = b;
  2141. // Read the argument
  2142. asWORD w = ReadEncodedUInt16();
  2143. *(((asWORD*)bc)+1) = w;
  2144. bc++;
  2145. }
  2146. break;
  2147. case asBCTYPE_rW_DW_ARG:
  2148. case asBCTYPE_wW_DW_ARG:
  2149. case asBCTYPE_W_DW_ARG:
  2150. {
  2151. *(asBYTE*)(bc) = b;
  2152. // Read the word argument
  2153. asWORD w = ReadEncodedUInt16();
  2154. *(((asWORD*)bc)+1) = w;
  2155. bc++;
  2156. // Read the dword argument
  2157. *bc++ = ReadEncodedUInt();
  2158. }
  2159. break;
  2160. case asBCTYPE_DW_ARG:
  2161. {
  2162. *(asBYTE*)(bc) = b;
  2163. bc++;
  2164. // Read the argument
  2165. *bc++ = ReadEncodedUInt();
  2166. }
  2167. break;
  2168. case asBCTYPE_DW_DW_ARG:
  2169. {
  2170. *(asBYTE*)(bc) = b;
  2171. bc++;
  2172. // Read the first argument
  2173. *bc++ = ReadEncodedUInt();
  2174. // Read the second argument
  2175. *bc++ = ReadEncodedUInt();
  2176. }
  2177. break;
  2178. case asBCTYPE_wW_rW_rW_ARG:
  2179. {
  2180. *(asBYTE*)(bc) = b;
  2181. // Read the first argument
  2182. asWORD w = ReadEncodedUInt16();
  2183. *(((asWORD*)bc)+1) = w;
  2184. bc++;
  2185. // Read the second argument
  2186. w = ReadEncodedUInt16();
  2187. *(asWORD*)bc = w;
  2188. // Read the third argument
  2189. w = ReadEncodedUInt16();
  2190. *(((asWORD*)bc)+1) = w;
  2191. bc++;
  2192. }
  2193. break;
  2194. case asBCTYPE_wW_rW_ARG:
  2195. case asBCTYPE_rW_rW_ARG:
  2196. case asBCTYPE_wW_W_ARG:
  2197. {
  2198. *(asBYTE*)(bc) = b;
  2199. // Read the first argument
  2200. asWORD w = ReadEncodedUInt16();
  2201. *(((asWORD*)bc)+1) = w;
  2202. bc++;
  2203. // Read the second argument
  2204. w = ReadEncodedUInt16();
  2205. *(asWORD*)bc = w;
  2206. bc++;
  2207. }
  2208. break;
  2209. case asBCTYPE_wW_rW_DW_ARG:
  2210. case asBCTYPE_rW_W_DW_ARG:
  2211. {
  2212. *(asBYTE*)(bc) = b;
  2213. // Read the first argument
  2214. asWORD w = ReadEncodedUInt16();
  2215. *(((asWORD*)bc)+1) = w;
  2216. bc++;
  2217. // Read the second argument
  2218. w = ReadEncodedUInt16();
  2219. *(asWORD*)bc = w;
  2220. bc++;
  2221. // Read the third argument
  2222. asDWORD dw = ReadEncodedUInt();
  2223. *bc++ = dw;
  2224. }
  2225. break;
  2226. case asBCTYPE_QW_ARG:
  2227. {
  2228. *(asBYTE*)(bc) = b;
  2229. bc++;
  2230. // Read the argument
  2231. asQWORD qw = ReadEncodedUInt64();
  2232. *(asQWORD*)bc = qw;
  2233. bc += 2;
  2234. }
  2235. break;
  2236. case asBCTYPE_QW_DW_ARG:
  2237. {
  2238. *(asBYTE*)(bc) = b;
  2239. bc++;
  2240. // Read the first argument
  2241. asQWORD qw = ReadEncodedUInt64();
  2242. *(asQWORD*)bc = qw;
  2243. bc += 2;
  2244. // Read the second argument
  2245. asDWORD dw = ReadEncodedUInt();
  2246. *bc++ = dw;
  2247. }
  2248. break;
  2249. case asBCTYPE_rW_QW_ARG:
  2250. case asBCTYPE_wW_QW_ARG:
  2251. {
  2252. *(asBYTE*)(bc) = b;
  2253. // Read the first argument
  2254. asWORD w = ReadEncodedUInt16();
  2255. *(((asWORD*)bc)+1) = w;
  2256. bc++;
  2257. // Read the argument
  2258. asQWORD qw = ReadEncodedUInt64();
  2259. *(asQWORD*)bc = qw;
  2260. bc += 2;
  2261. }
  2262. break;
  2263. case asBCTYPE_rW_DW_DW_ARG:
  2264. {
  2265. *(asBYTE*)(bc) = b;
  2266. // Read the 1st argument
  2267. asWORD w = ReadEncodedUInt16();
  2268. *(((asWORD*)bc)+1) = w;
  2269. bc++;
  2270. // Read the 2nd argument
  2271. *bc++ = ReadEncodedUInt();
  2272. // Read the 3rd argument
  2273. *bc++ = ReadEncodedUInt();
  2274. }
  2275. break;
  2276. default:
  2277. {
  2278. // This should never happen
  2279. asASSERT(false);
  2280. // Read the next 3 bytes
  2281. asDWORD c; asBYTE t;
  2282. #if defined(AS_BIG_ENDIAN)
  2283. c = b << 24;
  2284. ReadData(&t, 1); c += t << 16;
  2285. ReadData(&t, 1); c += t << 8;
  2286. ReadData(&t, 1); c += t;
  2287. #else
  2288. c = b;
  2289. ReadData(&t, 1); c += t << 8;
  2290. ReadData(&t, 1); c += t << 16;
  2291. ReadData(&t, 1); c += t << 24;
  2292. #endif
  2293. *bc++ = c;
  2294. c = *(asBYTE*)&c;
  2295. // Read the bc as is
  2296. for( int n = 1; n < asBCTypeSize[asBCInfo[c].type]; n++ )
  2297. ReadData(&*bc++, 4);
  2298. }
  2299. }
  2300. numInstructions--;
  2301. }
  2302. // Correct the final size in case we over-estimated it
  2303. func->scriptData->byteCode.SetLengthNoConstruct(pos);
  2304. }
  2305. void asCReader::ReadUsedTypeIds()
  2306. {
  2307. TimeIt("asCReader::ReadUsedTypeIds");
  2308. asUINT count = ReadEncodedUInt();
  2309. usedTypeIds.Allocate(count, false);
  2310. for( asUINT n = 0; n < count; n++ )
  2311. {
  2312. asCDataType dt;
  2313. ReadDataType(&dt);
  2314. usedTypeIds.PushLast(engine->GetTypeIdFromDataType(dt));
  2315. }
  2316. }
  2317. void asCReader::ReadUsedGlobalProps()
  2318. {
  2319. TimeIt("asCReader::ReadUsedGlobalProps");
  2320. int c = ReadEncodedUInt();
  2321. usedGlobalProperties.Allocate(c, false);
  2322. for( int n = 0; n < c; n++ )
  2323. {
  2324. asCString name, ns;
  2325. asCDataType type;
  2326. char moduleProp;
  2327. ReadString(&name);
  2328. ReadString(&ns);
  2329. ReadDataType(&type);
  2330. ReadData(&moduleProp, 1);
  2331. asSNameSpace *nameSpace = engine->AddNameSpace(ns.AddressOf());
  2332. // Find the real property
  2333. asCGlobalProperty *globProp = 0;
  2334. if( moduleProp )
  2335. globProp = module->scriptGlobals.GetFirst(nameSpace, name);
  2336. else
  2337. globProp = engine->registeredGlobalProps.GetFirst(nameSpace, name);
  2338. void *prop = 0;
  2339. if( globProp && globProp->type == type )
  2340. prop = globProp->GetAddressOfValue();
  2341. usedGlobalProperties.PushLast(prop);
  2342. if( prop == 0 )
  2343. {
  2344. Error(TXT_INVALID_BYTECODE_d);
  2345. }
  2346. }
  2347. }
  2348. void asCReader::ReadUsedObjectProps()
  2349. {
  2350. TimeIt("asCReader::ReadUsedObjectProps");
  2351. asUINT c = ReadEncodedUInt();
  2352. usedObjectProperties.SetLength(c);
  2353. for( asUINT n = 0; n < c; n++ )
  2354. {
  2355. asCObjectType *objType = CastToObjectType(ReadTypeInfo());
  2356. if( objType == 0 )
  2357. {
  2358. Error(TXT_INVALID_BYTECODE_d);
  2359. break;
  2360. }
  2361. asCString name;
  2362. ReadString(&name);
  2363. // Find the property
  2364. bool found = false;
  2365. for( asUINT p = 0; p < objType->properties.GetLength(); p++ )
  2366. {
  2367. if( objType->properties[p]->name == name )
  2368. {
  2369. usedObjectProperties[n].objType = objType;
  2370. usedObjectProperties[n].prop = objType->properties[p];
  2371. found = true;
  2372. break;
  2373. }
  2374. }
  2375. if( !found )
  2376. {
  2377. Error(TXT_INVALID_BYTECODE_d);
  2378. return;
  2379. }
  2380. }
  2381. }
  2382. short asCReader::FindObjectPropOffset(asWORD index)
  2383. {
  2384. static asCObjectProperty *lastCompositeProp = 0;
  2385. if (lastCompositeProp)
  2386. {
  2387. if (index != 0)
  2388. {
  2389. Error(TXT_INVALID_BYTECODE_d);
  2390. return 0;
  2391. }
  2392. short offset = (short)lastCompositeProp->byteOffset;
  2393. lastCompositeProp = 0;
  2394. return offset;
  2395. }
  2396. if( index >= usedObjectProperties.GetLength() )
  2397. {
  2398. Error(TXT_INVALID_BYTECODE_d);
  2399. return 0;
  2400. }
  2401. if (usedObjectProperties[index].prop->compositeOffset || usedObjectProperties[index].prop->isCompositeIndirect)
  2402. {
  2403. lastCompositeProp = usedObjectProperties[index].prop;
  2404. return (short)lastCompositeProp->compositeOffset;
  2405. }
  2406. return (short)usedObjectProperties[index].prop->byteOffset;
  2407. }
  2408. asCScriptFunction *asCReader::FindFunction(int idx)
  2409. {
  2410. if( idx >= 0 && idx < (int)usedFunctions.GetLength() )
  2411. return usedFunctions[idx];
  2412. else
  2413. {
  2414. Error(TXT_INVALID_BYTECODE_d);
  2415. return 0;
  2416. }
  2417. }
  2418. void asCReader::TranslateFunction(asCScriptFunction *func)
  2419. {
  2420. // Skip this if the function is part of an pre-existing shared object
  2421. if( dontTranslate.MoveTo(0, func) ) return;
  2422. asASSERT( func->scriptData );
  2423. // Pre-compute the size of each instruction in order to translate jump offsets
  2424. asUINT n;
  2425. asDWORD *bc = func->scriptData->byteCode.AddressOf();
  2426. asUINT bcLength = (asUINT)func->scriptData->byteCode.GetLength();
  2427. asCArray<asUINT> bcSizes(bcLength);
  2428. asCArray<asUINT> instructionNbrToPos(bcLength);
  2429. for( n = 0; n < bcLength; )
  2430. {
  2431. int c = *(asBYTE*)&bc[n];
  2432. asUINT size = asBCTypeSize[asBCInfo[c].type];
  2433. if( size == 0 )
  2434. {
  2435. Error(TXT_INVALID_BYTECODE_d);
  2436. return;
  2437. }
  2438. bcSizes.PushLast(size);
  2439. instructionNbrToPos.PushLast(n);
  2440. n += size;
  2441. }
  2442. asUINT bcNum = 0;
  2443. for( n = 0; n < bcLength; bcNum++ )
  2444. {
  2445. int c = *(asBYTE*)&bc[n];
  2446. if( c == asBC_REFCPY ||
  2447. c == asBC_RefCpyV ||
  2448. c == asBC_OBJTYPE )
  2449. {
  2450. // Translate the index to the true object type
  2451. asPWORD *ot = (asPWORD*)&bc[n+1];
  2452. *(asCObjectType**)ot = CastToObjectType(FindType(int(*ot)));
  2453. }
  2454. else if( c == asBC_TYPEID ||
  2455. c == asBC_Cast )
  2456. {
  2457. // Translate the index to the type id
  2458. int *tid = (int*)&bc[n+1];
  2459. *tid = FindTypeId(*tid);
  2460. }
  2461. else if( c == asBC_ADDSi ||
  2462. c == asBC_LoadThisR )
  2463. {
  2464. // Translate the index to the type id
  2465. int *tid = (int*)&bc[n+1];
  2466. *tid = FindTypeId(*tid);
  2467. // Translate the prop index into the property offset
  2468. *(((short*)&bc[n])+1) = FindObjectPropOffset(*(((short*)&bc[n])+1));
  2469. }
  2470. else if( c == asBC_LoadRObjR ||
  2471. c == asBC_LoadVObjR )
  2472. {
  2473. // Translate the index to the type id
  2474. int *tid = (int*)&bc[n+2];
  2475. *tid = FindTypeId(*tid);
  2476. asCObjectType *ot = engine->GetObjectTypeFromTypeId(*tid);
  2477. if( ot && (ot->flags & asOBJ_LIST_PATTERN) )
  2478. {
  2479. // List patterns have a different way of adjusting the offsets
  2480. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  2481. *(((short*)&bc[n])+2) = (short)listAdj->AdjustOffset(*(((short*)&bc[n])+2));
  2482. }
  2483. else
  2484. {
  2485. // Translate the prop index into the property offset
  2486. *(((short*)&bc[n])+2) = FindObjectPropOffset(*(((short*)&bc[n])+2));
  2487. }
  2488. }
  2489. else if( c == asBC_COPY )
  2490. {
  2491. // Translate the index to the type id
  2492. int *tid = (int*)&bc[n+1];
  2493. *tid = FindTypeId(*tid);
  2494. // COPY is used to copy POD types that don't have the opAssign method. It is
  2495. // also used to copy references to scoped types during variable initializations.
  2496. // Update the number of dwords to copy as it may be different on the target platform
  2497. if( (*tid) & asTYPEID_OBJHANDLE )
  2498. {
  2499. // It is the actual reference that is being copied, not the object itself
  2500. asBC_SWORDARG0(&bc[n]) = AS_PTR_SIZE;
  2501. }
  2502. else
  2503. {
  2504. asCDataType dt = engine->GetDataTypeFromTypeId(*tid);
  2505. if( !dt.IsValid() )
  2506. {
  2507. Error(TXT_INVALID_BYTECODE_d);
  2508. }
  2509. else
  2510. asBC_SWORDARG0(&bc[n]) = (short)dt.GetSizeInMemoryDWords();
  2511. }
  2512. }
  2513. else if( c == asBC_RET )
  2514. {
  2515. // Determine the correct amount of DWORDs to pop
  2516. asWORD dw = (asWORD)func->GetSpaceNeededForArguments();
  2517. if( func->DoesReturnOnStack() ) dw += AS_PTR_SIZE;
  2518. if( func->objectType ) dw += AS_PTR_SIZE;
  2519. asBC_WORDARG0(&bc[n]) = dw;
  2520. }
  2521. else if( c == asBC_CALL ||
  2522. c == asBC_CALLINTF ||
  2523. c == asBC_CALLSYS ||
  2524. c == asBC_Thiscall1 )
  2525. {
  2526. // Translate the index to the func id
  2527. int *fid = (int*)&bc[n+1];
  2528. asCScriptFunction *f = FindFunction(*fid);
  2529. if( f )
  2530. *fid = f->id;
  2531. else
  2532. {
  2533. Error(TXT_INVALID_BYTECODE_d);
  2534. return;
  2535. }
  2536. }
  2537. else if( c == asBC_FuncPtr )
  2538. {
  2539. // Translate the index to the func pointer
  2540. asPWORD *fid = (asPWORD*)&bc[n+1];
  2541. *fid = (asPWORD)FindFunction(int(*fid));
  2542. }
  2543. else if( c == asBC_ALLOC )
  2544. {
  2545. // Translate the index to the true object type
  2546. asPWORD *arg = (asPWORD*)&bc[n+1];
  2547. *(asCObjectType**)arg = CastToObjectType(FindType(int(*arg)));
  2548. // The constructor function id must be translated, unless it is zero
  2549. int *fid = (int*)&bc[n+1+AS_PTR_SIZE];
  2550. if( *fid != 0 )
  2551. {
  2552. // Subtract 1 from the id, as it was incremented during the writing
  2553. asCScriptFunction *f = FindFunction(*fid-1);
  2554. if( f )
  2555. *fid = f->id;
  2556. else
  2557. {
  2558. Error(TXT_INVALID_BYTECODE_d);
  2559. return;
  2560. }
  2561. }
  2562. }
  2563. else if( c == asBC_STR )
  2564. {
  2565. Error(TXT_INVALID_BYTECODE_d);
  2566. return;
  2567. }
  2568. else if( c == asBC_CALLBND )
  2569. {
  2570. // Translate the function id
  2571. asUINT *fid = (asUINT*)&bc[n+1];
  2572. if( *fid < module->bindInformations.GetLength() )
  2573. {
  2574. sBindInfo *bi = module->bindInformations[*fid];
  2575. if( bi )
  2576. *fid = bi->importedFunctionSignature->id;
  2577. else
  2578. {
  2579. Error(TXT_INVALID_BYTECODE_d);
  2580. return;
  2581. }
  2582. }
  2583. else
  2584. {
  2585. Error(TXT_INVALID_BYTECODE_d);
  2586. return;
  2587. }
  2588. }
  2589. else if( c == asBC_PGA ||
  2590. c == asBC_PshGPtr ||
  2591. c == asBC_LDG ||
  2592. c == asBC_PshG4 ||
  2593. c == asBC_LdGRdR4 ||
  2594. c == asBC_CpyGtoV4 ||
  2595. c == asBC_CpyVtoG4 ||
  2596. c == asBC_SetG4 )
  2597. {
  2598. // Translate the index to pointer
  2599. asPWORD *index = (asPWORD*)&bc[n + 1];
  2600. if ((*index & 1))
  2601. {
  2602. if ((asUINT(*index)>>1) < usedGlobalProperties.GetLength())
  2603. *(void**)index = usedGlobalProperties[asUINT(*index)>>1];
  2604. else
  2605. {
  2606. Error(TXT_INVALID_BYTECODE_d);
  2607. return;
  2608. }
  2609. }
  2610. else
  2611. {
  2612. // Only PGA and PshGPtr can hold string constants
  2613. asASSERT(c == asBC_PGA || c == asBC_PshGPtr);
  2614. if ((asUINT(*index)>>1) < usedStringConstants.GetLength())
  2615. *(void**)index = usedStringConstants[asUINT(*index)>>1];
  2616. else
  2617. {
  2618. Error(TXT_INVALID_BYTECODE_d);
  2619. return;
  2620. }
  2621. }
  2622. }
  2623. else if( c == asBC_JMP ||
  2624. c == asBC_JZ ||
  2625. c == asBC_JNZ ||
  2626. c == asBC_JLowZ ||
  2627. c == asBC_JLowNZ ||
  2628. c == asBC_JS ||
  2629. c == asBC_JNS ||
  2630. c == asBC_JP ||
  2631. c == asBC_JNP ) // The JMPP instruction doesn't need modification
  2632. {
  2633. // Get the offset
  2634. int offset = int(bc[n+1]);
  2635. // Count the instruction sizes to the destination instruction
  2636. int size = 0;
  2637. if( offset >= 0 )
  2638. // If moving ahead, then start from next instruction
  2639. for( asUINT num = bcNum+1; offset-- > 0; num++ )
  2640. size += bcSizes[num];
  2641. else
  2642. // If moving backwards, then start at current instruction
  2643. for( asUINT num = bcNum; offset++ < 0; num-- )
  2644. size -= bcSizes[num];
  2645. // The size is dword offset
  2646. bc[n+1] = size;
  2647. }
  2648. else if( c == asBC_AllocMem )
  2649. {
  2650. // The size of the allocated memory is only known after all the elements has been seen.
  2651. // This helper class will collect this information and adjust the size when the
  2652. // corresponding asBC_FREE is encountered
  2653. // The adjuster also needs to know the list type so it can know the type of the elements
  2654. asCObjectType *ot = CastToObjectType(func->GetTypeInfoOfLocalVar(asBC_SWORDARG0(&bc[n])));
  2655. listAdjusters.PushLast(asNEW(SListAdjuster)(this, &bc[n], ot));
  2656. }
  2657. else if( c == asBC_FREE )
  2658. {
  2659. // Translate the index to the true object type
  2660. asPWORD *pot = (asPWORD*)&bc[n+1];
  2661. *(asCObjectType**)pot = CastToObjectType(FindType(int(*pot)));
  2662. asCObjectType *ot = *(asCObjectType**)pot;
  2663. if( ot && (ot->flags & asOBJ_LIST_PATTERN) )
  2664. {
  2665. if( listAdjusters.GetLength() == 0 )
  2666. {
  2667. Error(TXT_INVALID_BYTECODE_d);
  2668. return;
  2669. }
  2670. // Finalize the adjustment of the list buffer that was initiated with asBC_AllocMem
  2671. SListAdjuster *list = listAdjusters.PopLast();
  2672. list->AdjustAllocMem();
  2673. asDELETE(list, SListAdjuster);
  2674. }
  2675. }
  2676. else if( c == asBC_SetListSize )
  2677. {
  2678. // Adjust the offset in the list where the size is informed
  2679. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  2680. bc[n+1] = listAdj->AdjustOffset(bc[n+1]);
  2681. // Inform the list adjuster how many values will be repeated
  2682. listAdj->SetRepeatCount(bc[n+2]);
  2683. }
  2684. else if( c == asBC_PshListElmnt )
  2685. {
  2686. // Adjust the offset in the list where the size is informed
  2687. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  2688. bc[n+1] = listAdj->AdjustOffset(bc[n+1]);
  2689. }
  2690. else if( c == asBC_SetListType )
  2691. {
  2692. // Adjust the offset in the list where the typeid is informed
  2693. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  2694. bc[n+1] = listAdj->AdjustOffset(bc[n+1]);
  2695. // Translate the type id
  2696. bc[n+2] = FindTypeId(bc[n+2]);
  2697. // Inform the list adjuster the type id of the next element
  2698. listAdj->SetNextType(bc[n+2]);
  2699. }
  2700. n += asBCTypeSize[asBCInfo[c].type];
  2701. }
  2702. // Calculate the stack adjustments
  2703. CalculateAdjustmentByPos(func);
  2704. // Adjust all variable positions in the bytecode
  2705. bc = func->scriptData->byteCode.AddressOf();
  2706. for( n = 0; n < bcLength; )
  2707. {
  2708. int c = *(asBYTE*)&bc[n];
  2709. switch( asBCInfo[c].type )
  2710. {
  2711. case asBCTYPE_wW_ARG:
  2712. case asBCTYPE_rW_DW_ARG:
  2713. case asBCTYPE_wW_QW_ARG:
  2714. case asBCTYPE_rW_ARG:
  2715. case asBCTYPE_wW_DW_ARG:
  2716. case asBCTYPE_wW_W_ARG:
  2717. case asBCTYPE_rW_QW_ARG:
  2718. case asBCTYPE_rW_W_DW_ARG:
  2719. case asBCTYPE_rW_DW_DW_ARG:
  2720. {
  2721. asBC_SWORDARG0(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG0(&bc[n]));
  2722. }
  2723. break;
  2724. case asBCTYPE_wW_rW_ARG:
  2725. case asBCTYPE_wW_rW_DW_ARG:
  2726. case asBCTYPE_rW_rW_ARG:
  2727. {
  2728. asBC_SWORDARG0(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG0(&bc[n]));
  2729. asBC_SWORDARG1(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG1(&bc[n]));
  2730. }
  2731. break;
  2732. case asBCTYPE_wW_rW_rW_ARG:
  2733. {
  2734. asBC_SWORDARG0(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG0(&bc[n]));
  2735. asBC_SWORDARG1(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG1(&bc[n]));
  2736. asBC_SWORDARG2(&bc[n]) = (short)AdjustStackPosition(asBC_SWORDARG2(&bc[n]));
  2737. }
  2738. break;
  2739. default:
  2740. // The other types don't treat variables so won't be modified
  2741. break;
  2742. }
  2743. n += asBCTypeSize[asBCInfo[c].type];
  2744. }
  2745. // Adjust the space needed for local variables
  2746. func->scriptData->variableSpace = AdjustStackPosition(func->scriptData->variableSpace);
  2747. // Adjust the variable information. This will be used during the adjustment below
  2748. for( n = 0; n < func->scriptData->variables.GetLength(); n++ )
  2749. {
  2750. func->scriptData->variables[n]->declaredAtProgramPos = instructionNbrToPos[func->scriptData->variables[n]->declaredAtProgramPos];
  2751. func->scriptData->variables[n]->stackOffset = AdjustStackPosition(func->scriptData->variables[n]->stackOffset);
  2752. }
  2753. // objVariablePos
  2754. for( n = 0; n < func->scriptData->objVariablePos.GetLength(); n++ )
  2755. func->scriptData->objVariablePos[n] = AdjustStackPosition(func->scriptData->objVariablePos[n]);
  2756. // Adjust the get offsets. This must be done in the second iteration because
  2757. // it relies on the function ids and variable position already being correct in the
  2758. // bytecodes that come after the GET instructions.
  2759. // TODO: optimize: Instead of doing a full extra loop. We can push the GET instructions
  2760. // on a stack, and then when a call instruction is found update all of them.
  2761. // This will also make the AdjustGetOffset() function quicker as it can
  2762. // receive the called function directly instead of having to search for it.
  2763. bc = func->scriptData->byteCode.AddressOf();
  2764. for( n = 0; n < bcLength; )
  2765. {
  2766. int c = *(asBYTE*)&bc[n];
  2767. if( c == asBC_GETREF ||
  2768. c == asBC_GETOBJ ||
  2769. c == asBC_GETOBJREF ||
  2770. c == asBC_ChkNullS )
  2771. {
  2772. asBC_WORDARG0(&bc[n]) = (asWORD)AdjustGetOffset(asBC_WORDARG0(&bc[n]), func, n);
  2773. }
  2774. n += asBCTypeSize[asBCInfo[c].type];
  2775. }
  2776. for( n = 0; n < func->scriptData->objVariableInfo.GetLength(); n++ )
  2777. {
  2778. // The program position must be adjusted as it is stored in number of instructions
  2779. func->scriptData->objVariableInfo[n].programPos = instructionNbrToPos[func->scriptData->objVariableInfo[n].programPos];
  2780. func->scriptData->objVariableInfo[n].variableOffset = AdjustStackPosition(func->scriptData->objVariableInfo[n].variableOffset);
  2781. }
  2782. for (n = 0; n < func->scriptData->tryCatchInfo.GetLength(); n++)
  2783. {
  2784. func->scriptData->tryCatchInfo[n].tryPos = instructionNbrToPos[func->scriptData->tryCatchInfo[n].tryPos];
  2785. func->scriptData->tryCatchInfo[n].catchPos = instructionNbrToPos[func->scriptData->tryCatchInfo[n].catchPos];
  2786. }
  2787. // The program position (every even number) needs to be adjusted
  2788. // for the line numbers to be in number of dwords instead of number of instructions
  2789. for( n = 0; n < func->scriptData->lineNumbers.GetLength(); n += 2 )
  2790. func->scriptData->lineNumbers[n] = instructionNbrToPos[func->scriptData->lineNumbers[n]];
  2791. for( n = 0; n < func->scriptData->sectionIdxs.GetLength(); n += 2 )
  2792. func->scriptData->sectionIdxs[n] = instructionNbrToPos[func->scriptData->sectionIdxs[n]];
  2793. CalculateStackNeeded(func);
  2794. }
  2795. asCReader::SListAdjuster::SListAdjuster(asCReader *rd, asDWORD *bc, asCObjectType *listType) :
  2796. reader(rd), allocMemBC(bc), maxOffset(0), patternType(listType), repeatCount(0), lastOffset(-1), nextOffset(0), nextTypeId(-1)
  2797. {
  2798. asASSERT( patternType && (patternType->flags & asOBJ_LIST_PATTERN) );
  2799. // Find the first expected value in the list
  2800. asSListPatternNode *node = patternType->engine->scriptFunctions[patternType->templateSubTypes[0].GetBehaviour()->listFactory]->listPattern;
  2801. asASSERT( node && node->type == asLPT_START );
  2802. patternNode = node->next;
  2803. }
  2804. int asCReader::SListAdjuster::AdjustOffset(int offset)
  2805. {
  2806. if( offset < lastOffset )
  2807. {
  2808. reader->Error(TXT_INVALID_BYTECODE_d);
  2809. return 0;
  2810. }
  2811. // If it is the same offset being accessed again, just return the same adjusted value
  2812. if( lastOffset == offset )
  2813. return lastAdjustedOffset;
  2814. lastOffset = offset;
  2815. lastAdjustedOffset = maxOffset;
  2816. // What is being expected at this position?
  2817. if( patternNode->type == asLPT_REPEAT || patternNode->type == asLPT_REPEAT_SAME )
  2818. {
  2819. // Align the offset to 4 bytes boundary
  2820. if( maxOffset & 0x3 )
  2821. {
  2822. maxOffset += 4 - (maxOffset & 0x3);
  2823. lastAdjustedOffset = maxOffset;
  2824. }
  2825. // Don't move the patternNode yet because the caller must make a call to SetRepeatCount too
  2826. maxOffset += 4;
  2827. nextOffset = offset+1;
  2828. return lastAdjustedOffset;
  2829. }
  2830. else if( patternNode->type == asLPT_TYPE )
  2831. {
  2832. const asCDataType &dt = reinterpret_cast<asSListPatternDataTypeNode*>(patternNode)->dataType;
  2833. if( dt.GetTokenType() == ttQuestion )
  2834. {
  2835. if( nextTypeId != -1 )
  2836. {
  2837. if( repeatCount > 0 )
  2838. repeatCount--;
  2839. asCDataType nextdt = patternType->engine->GetDataTypeFromTypeId(nextTypeId);
  2840. asUINT size;
  2841. if(nextdt.IsObjectHandle() || (nextdt.GetTypeInfo() && (nextdt.GetTypeInfo()->flags & asOBJ_REF)) )
  2842. size = AS_PTR_SIZE*4;
  2843. else
  2844. size = nextdt.GetSizeInMemoryBytes();
  2845. // Align the offset to 4 bytes boundary
  2846. if( size >= 4 && (maxOffset & 0x3) )
  2847. {
  2848. maxOffset += 4 - (maxOffset & 0x3);
  2849. lastAdjustedOffset = maxOffset;
  2850. }
  2851. // Only move the patternNode if we're not expecting any more repeated entries
  2852. if( repeatCount == 0 )
  2853. patternNode = patternNode->next;
  2854. nextTypeId = -1;
  2855. maxOffset += size;
  2856. nextOffset = offset+1;
  2857. return lastAdjustedOffset;
  2858. }
  2859. else
  2860. {
  2861. // Align the offset to 4 bytes boundary
  2862. if( maxOffset & 0x3 )
  2863. {
  2864. maxOffset += 4 - (maxOffset & 0x3);
  2865. lastAdjustedOffset = maxOffset;
  2866. }
  2867. // The first adjustment is for the typeId
  2868. maxOffset += 4;
  2869. nextOffset = offset+1;
  2870. return lastAdjustedOffset;
  2871. }
  2872. }
  2873. else
  2874. {
  2875. // Determine the size of the element
  2876. asUINT size;
  2877. if( dt.IsObjectHandle() || (dt.GetTypeInfo() && (dt.GetTypeInfo()->flags & asOBJ_REF)) )
  2878. size = AS_PTR_SIZE*4;
  2879. else
  2880. size = dt.GetSizeInMemoryBytes();
  2881. // If values are skipped, the offset needs to be incremented
  2882. while( nextOffset <= offset )
  2883. {
  2884. if( repeatCount > 0 )
  2885. repeatCount--;
  2886. // Align the offset to 4 bytes boundary
  2887. if( size >= 4 && (maxOffset & 0x3) )
  2888. maxOffset += 4 - (maxOffset & 0x3);
  2889. lastAdjustedOffset = maxOffset;
  2890. nextOffset += 1;
  2891. maxOffset += size;
  2892. }
  2893. // Only move the patternNode if we're not expecting any more repeated entries
  2894. if( repeatCount == 0 )
  2895. patternNode = patternNode->next;
  2896. nextOffset = offset+1;
  2897. return lastAdjustedOffset;
  2898. }
  2899. }
  2900. else if( patternNode->type == asLPT_START )
  2901. {
  2902. if( repeatCount > 0 )
  2903. repeatCount--;
  2904. SInfo info = {repeatCount, patternNode};
  2905. stack.PushLast(info);
  2906. repeatCount = 0;
  2907. patternNode = patternNode->next;
  2908. lastOffset--;
  2909. return AdjustOffset(offset);
  2910. }
  2911. else if( patternNode->type == asLPT_END )
  2912. {
  2913. if( stack.GetLength() == 0 )
  2914. {
  2915. reader->Error(TXT_INVALID_BYTECODE_d);
  2916. return 0;
  2917. }
  2918. SInfo info = stack.PopLast();
  2919. repeatCount = info.repeatCount;
  2920. if( repeatCount )
  2921. patternNode = info.startNode;
  2922. else
  2923. patternNode = patternNode->next;
  2924. lastOffset--;
  2925. return AdjustOffset(offset);
  2926. }
  2927. else
  2928. {
  2929. // Something is wrong with the pattern list declaration
  2930. reader->Error(TXT_INVALID_BYTECODE_d);
  2931. return 0;
  2932. }
  2933. UNREACHABLE_RETURN;
  2934. }
  2935. void asCReader::SListAdjuster::SetRepeatCount(asUINT rc)
  2936. {
  2937. // Make sure the list is expecting a repeat at this location
  2938. asASSERT( patternNode->type == asLPT_REPEAT || patternNode->type == asLPT_REPEAT_SAME );
  2939. // Now move to the next patternNode
  2940. patternNode = patternNode->next;
  2941. repeatCount = rc;
  2942. }
  2943. void asCReader::SListAdjuster::AdjustAllocMem()
  2944. {
  2945. allocMemBC[1] = maxOffset;
  2946. }
  2947. void asCReader::SListAdjuster::SetNextType(int typeId)
  2948. {
  2949. asASSERT( nextTypeId == -1 );
  2950. nextTypeId = typeId;
  2951. }
  2952. void asCReader::CalculateStackNeeded(asCScriptFunction *func)
  2953. {
  2954. asASSERT( func->scriptData );
  2955. int largestStackUsed = 0;
  2956. // Clear the known stack size for each bytecode
  2957. asCArray<int> stackSize;
  2958. stackSize.SetLength(func->scriptData->byteCode.GetLength());
  2959. memset(&stackSize[0], -1, stackSize.GetLength()*4);
  2960. // Add the first instruction to the list of unchecked code
  2961. // paths and set the stack size at that instruction to variableSpace
  2962. asCArray<asUINT> paths;
  2963. paths.PushLast(0);
  2964. stackSize[0] = func->scriptData->variableSpace;
  2965. // Go through each of the code paths
  2966. for( asUINT p = 0; p < paths.GetLength(); ++p )
  2967. {
  2968. asUINT pos = paths[p];
  2969. int currStackSize = stackSize[pos];
  2970. asBYTE bc = *(asBYTE*)&func->scriptData->byteCode[pos];
  2971. if( bc == asBC_RET )
  2972. continue;
  2973. // Determine the change in stack size for this instruction
  2974. int stackInc = asBCInfo[bc].stackInc;
  2975. if( stackInc == 0xFFFF )
  2976. {
  2977. // Determine the true delta from the instruction arguments
  2978. if( bc == asBC_CALL ||
  2979. bc == asBC_CALLSYS ||
  2980. bc == asBC_Thiscall1 ||
  2981. bc == asBC_CALLBND ||
  2982. bc == asBC_ALLOC ||
  2983. bc == asBC_CALLINTF ||
  2984. bc == asBC_CallPtr )
  2985. {
  2986. asCScriptFunction *called = GetCalledFunction(func, pos);
  2987. if( called )
  2988. {
  2989. stackInc = -called->GetSpaceNeededForArguments();
  2990. if( called->objectType )
  2991. stackInc -= AS_PTR_SIZE;
  2992. if( called->DoesReturnOnStack() )
  2993. stackInc -= AS_PTR_SIZE;
  2994. }
  2995. else
  2996. {
  2997. // It is an allocation for an object without a constructor
  2998. asASSERT( bc == asBC_ALLOC );
  2999. stackInc = -AS_PTR_SIZE;
  3000. }
  3001. }
  3002. }
  3003. currStackSize += stackInc;
  3004. asASSERT( currStackSize >= 0 );
  3005. if( currStackSize > largestStackUsed )
  3006. largestStackUsed = currStackSize;
  3007. if( bc == asBC_JMP )
  3008. {
  3009. // Find the label that we should jump to
  3010. int offset = asBC_INTARG(&func->scriptData->byteCode[pos]);
  3011. pos += 2 + offset;
  3012. // Add the destination as a new path
  3013. if( stackSize[pos] == -1 )
  3014. {
  3015. stackSize[pos] = currStackSize;
  3016. paths.PushLast(pos);
  3017. }
  3018. else
  3019. asASSERT(stackSize[pos] == currStackSize);
  3020. continue;
  3021. }
  3022. else if( bc == asBC_JZ || bc == asBC_JNZ ||
  3023. bc == asBC_JLowZ || bc == asBC_JLowNZ ||
  3024. bc == asBC_JS || bc == asBC_JNS ||
  3025. bc == asBC_JP || bc == asBC_JNP )
  3026. {
  3027. // Find the label that is being jumped to
  3028. int offset = asBC_INTARG(&func->scriptData->byteCode[pos]);
  3029. // Add both paths to the code paths
  3030. pos += 2;
  3031. if( stackSize[pos] == -1 )
  3032. {
  3033. stackSize[pos] = currStackSize;
  3034. paths.PushLast(pos);
  3035. }
  3036. else
  3037. asASSERT(stackSize[pos] == currStackSize);
  3038. pos += offset;
  3039. if( stackSize[pos] == -1 )
  3040. {
  3041. stackSize[pos] = currStackSize;
  3042. paths.PushLast(pos);
  3043. }
  3044. else
  3045. asASSERT(stackSize[pos] == currStackSize);
  3046. continue;
  3047. }
  3048. else if( bc == asBC_JMPP )
  3049. {
  3050. pos++;
  3051. // Add all subsequent JMP instructions to the path
  3052. while( *(asBYTE*)&func->scriptData->byteCode[pos] == asBC_JMP )
  3053. {
  3054. if( stackSize[pos] == -1 )
  3055. {
  3056. stackSize[pos] = currStackSize;
  3057. paths.PushLast(pos);
  3058. }
  3059. else
  3060. asASSERT(stackSize[pos] == currStackSize);
  3061. pos += 2;
  3062. }
  3063. continue;
  3064. }
  3065. else
  3066. {
  3067. // Add next instruction to the paths
  3068. pos += asBCTypeSize[asBCInfo[bc].type];
  3069. if( stackSize[pos] == -1 )
  3070. {
  3071. stackSize[pos] = currStackSize;
  3072. paths.PushLast(pos);
  3073. }
  3074. else
  3075. asASSERT(stackSize[pos] == currStackSize);
  3076. continue;
  3077. }
  3078. }
  3079. func->scriptData->stackNeeded = largestStackUsed;
  3080. }
  3081. void asCReader::CalculateAdjustmentByPos(asCScriptFunction *func)
  3082. {
  3083. // Adjust the offset of all negative variables (parameters) as
  3084. // all pointers have been stored as having a size of 1 dword
  3085. asUINT n;
  3086. asCArray<int> adjustments;
  3087. asUINT offset = 0;
  3088. if( func->objectType )
  3089. {
  3090. adjustments.PushLast(offset);
  3091. adjustments.PushLast(1-AS_PTR_SIZE);
  3092. offset += 1;
  3093. }
  3094. if( func->DoesReturnOnStack() )
  3095. {
  3096. adjustments.PushLast(offset);
  3097. adjustments.PushLast(1-AS_PTR_SIZE);
  3098. offset += 1;
  3099. }
  3100. for( n = 0; n < func->parameterTypes.GetLength(); n++ )
  3101. {
  3102. if( !func->parameterTypes[n].IsPrimitive() ||
  3103. func->parameterTypes[n].IsReference() )
  3104. {
  3105. adjustments.PushLast(offset);
  3106. adjustments.PushLast(1-AS_PTR_SIZE);
  3107. offset += 1;
  3108. }
  3109. else
  3110. {
  3111. asASSERT( func->parameterTypes[n].IsPrimitive() );
  3112. offset += func->parameterTypes[n].GetSizeOnStackDWords();
  3113. }
  3114. }
  3115. // Build look-up table with the adjustments for each stack position
  3116. adjustNegativeStackByPos.SetLength(offset);
  3117. memset(adjustNegativeStackByPos.AddressOf(), 0, adjustNegativeStackByPos.GetLength()*sizeof(int));
  3118. for( n = 0; n < adjustments.GetLength(); n+=2 )
  3119. {
  3120. int pos = adjustments[n];
  3121. int adjust = adjustments[n+1];
  3122. for( asUINT i = pos+1; i < adjustNegativeStackByPos.GetLength(); i++ )
  3123. adjustNegativeStackByPos[i] += adjust;
  3124. }
  3125. // The bytecode has been stored as if all object variables take up only 1 dword.
  3126. // It is necessary to adjust to the size according to the current platform.
  3127. adjustments.SetLength(0);
  3128. int highestPos = 0;
  3129. for( n = 0; n < func->scriptData->objVariableTypes.GetLength(); n++ )
  3130. {
  3131. // Determine the size the variable currently occupies on the stack
  3132. int size = AS_PTR_SIZE;
  3133. // objVariableTypes is null if the type is a null pointer
  3134. if( func->scriptData->objVariableTypes[n] &&
  3135. (func->scriptData->objVariableTypes[n]->GetFlags() & asOBJ_VALUE) &&
  3136. n >= func->scriptData->objVariablesOnHeap )
  3137. {
  3138. size = func->scriptData->objVariableTypes[n]->GetSize();
  3139. if( size < 4 )
  3140. size = 1;
  3141. else
  3142. size /= 4;
  3143. }
  3144. // Check if type has a different size than stored
  3145. if( size > 1 )
  3146. {
  3147. if( func->scriptData->objVariablePos[n] > highestPos )
  3148. highestPos = func->scriptData->objVariablePos[n];
  3149. adjustments.PushLast(func->scriptData->objVariablePos[n]);
  3150. adjustments.PushLast(size-1);
  3151. }
  3152. }
  3153. // Count position 0 too
  3154. adjustByPos.SetLength(highestPos+1);
  3155. memset(adjustByPos.AddressOf(), 0, adjustByPos.GetLength()*sizeof(int));
  3156. // Build look-up table with the adjustments for each stack position
  3157. for( n = 0; n < adjustments.GetLength(); n+=2 )
  3158. {
  3159. int pos = adjustments[n];
  3160. int adjust = adjustments[n+1];
  3161. for( asUINT i = pos; i < adjustByPos.GetLength(); i++ )
  3162. adjustByPos[i] += adjust;
  3163. }
  3164. }
  3165. int asCReader::AdjustStackPosition(int pos)
  3166. {
  3167. if( pos >= (int)adjustByPos.GetLength() )
  3168. {
  3169. // It can be higher for primitives allocated on top of highest object variable
  3170. if( adjustByPos.GetLength() )
  3171. pos += (short)adjustByPos[adjustByPos.GetLength()-1];
  3172. }
  3173. else if( pos >= 0 )
  3174. pos += (short)adjustByPos[pos];
  3175. else if( -pos >= (int)adjustNegativeStackByPos.GetLength() )
  3176. Error(TXT_INVALID_BYTECODE_d);
  3177. else
  3178. pos += (short)adjustNegativeStackByPos[-pos];
  3179. return pos;
  3180. }
  3181. asCScriptFunction *asCReader::GetCalledFunction(asCScriptFunction *func, asDWORD programPos)
  3182. {
  3183. asBYTE bc = *(asBYTE*)&func->scriptData->byteCode[programPos];
  3184. if( bc == asBC_CALL ||
  3185. bc == asBC_CALLSYS ||
  3186. bc == asBC_Thiscall1 ||
  3187. bc == asBC_CALLINTF )
  3188. {
  3189. // Find the function from the function id in bytecode
  3190. int funcId = asBC_INTARG(&func->scriptData->byteCode[programPos]);
  3191. return engine->scriptFunctions[funcId];
  3192. }
  3193. else if( bc == asBC_ALLOC )
  3194. {
  3195. // Find the function from the function id in the bytecode
  3196. int funcId = asBC_INTARG(&func->scriptData->byteCode[programPos+AS_PTR_SIZE]);
  3197. return engine->scriptFunctions[funcId];
  3198. }
  3199. else if( bc == asBC_CALLBND )
  3200. {
  3201. // Find the function from the engine's bind array
  3202. int funcId = asBC_INTARG(&func->scriptData->byteCode[programPos]);
  3203. return engine->importedFunctions[funcId & ~FUNC_IMPORTED]->importedFunctionSignature;
  3204. }
  3205. else if( bc == asBC_CallPtr )
  3206. {
  3207. asUINT v;
  3208. int var = asBC_SWORDARG0(&func->scriptData->byteCode[programPos]);
  3209. // Find the funcdef from the local variable
  3210. for( v = 0; v < func->scriptData->objVariablePos.GetLength(); v++ )
  3211. if( func->scriptData->objVariablePos[v] == var )
  3212. return CastToFuncdefType(func->scriptData->objVariableTypes[v])->funcdef;
  3213. // Look in parameters
  3214. int paramPos = 0;
  3215. if( func->objectType )
  3216. paramPos -= AS_PTR_SIZE;
  3217. if( func->DoesReturnOnStack() )
  3218. paramPos -= AS_PTR_SIZE;
  3219. for( v = 0; v < func->parameterTypes.GetLength(); v++ )
  3220. {
  3221. if (var == paramPos)
  3222. {
  3223. if (func->parameterTypes[v].IsFuncdef())
  3224. return CastToFuncdefType(func->parameterTypes[v].GetTypeInfo())->funcdef;
  3225. else
  3226. {
  3227. error = true;
  3228. return 0;
  3229. }
  3230. }
  3231. paramPos -= func->parameterTypes[v].GetSizeOnStackDWords();
  3232. }
  3233. }
  3234. return 0;
  3235. }
  3236. int asCReader::AdjustGetOffset(int offset, asCScriptFunction *func, asDWORD programPos)
  3237. {
  3238. // TODO: optimize: multiple instructions for the same function doesn't need to look for the function everytime
  3239. // the function can remember where it found the function and check if the programPos is still valid
  3240. // Get offset 0 doesn't need adjustment
  3241. if( offset == 0 ) return 0;
  3242. bool bcAlloc = false;
  3243. // Find out which function that will be called
  3244. asCScriptFunction *calledFunc = 0;
  3245. int stackDelta = 0;
  3246. for( asUINT n = programPos; func->scriptData->byteCode.GetLength(); )
  3247. {
  3248. asBYTE bc = *(asBYTE*)&func->scriptData->byteCode[n];
  3249. if( bc == asBC_CALL ||
  3250. bc == asBC_CALLSYS ||
  3251. bc == asBC_Thiscall1 ||
  3252. bc == asBC_CALLINTF ||
  3253. bc == asBC_ALLOC ||
  3254. bc == asBC_CALLBND ||
  3255. bc == asBC_CallPtr )
  3256. {
  3257. // The alloc instruction allocates the object memory
  3258. // so it doesn't take the this pointer as input
  3259. if (bc == asBC_ALLOC)
  3260. bcAlloc = true;
  3261. calledFunc = GetCalledFunction(func, n);
  3262. break;
  3263. }
  3264. else if( bc == asBC_REFCPY ||
  3265. bc == asBC_COPY )
  3266. {
  3267. // In this case we know there is only 1 pointer on the stack above
  3268. asASSERT( offset == 1 );
  3269. return offset - (1 - AS_PTR_SIZE);
  3270. }
  3271. // Keep track of the stack size between the
  3272. // instruction that needs to be adjusted and the call
  3273. stackDelta += asBCInfo[bc].stackInc;
  3274. n += asBCTypeSize[asBCInfo[bc].type];
  3275. }
  3276. if( calledFunc == 0 )
  3277. {
  3278. Error(TXT_INVALID_BYTECODE_d);
  3279. return offset;
  3280. }
  3281. // Count the number of pointers pushed on the stack above the
  3282. // current offset, and then adjust the offset accordingly
  3283. asUINT numPtrs = 0;
  3284. int currOffset = -stackDelta;
  3285. if( offset > currOffset && calledFunc->GetObjectType() && !bcAlloc )
  3286. {
  3287. currOffset++;
  3288. if( currOffset > 0 )
  3289. numPtrs++;
  3290. #if AS_PTR_SIZE == 2
  3291. // For 64bit platforms it is necessary to increment the currOffset by one more
  3292. // DWORD since the stackDelta was counting the full 64bit size of the pointer
  3293. else if( stackDelta )
  3294. currOffset++;
  3295. #endif
  3296. }
  3297. if( offset > currOffset && calledFunc->DoesReturnOnStack() )
  3298. {
  3299. currOffset++;
  3300. if( currOffset > 0 )
  3301. numPtrs++;
  3302. #if AS_PTR_SIZE == 2
  3303. // For 64bit platforms it is necessary to increment the currOffset by one more
  3304. // DWORD since the stackDelta was counting the full 64bit size of the pointer
  3305. else if( stackDelta )
  3306. currOffset++;
  3307. #endif
  3308. }
  3309. for( asUINT p = 0; p < calledFunc->parameterTypes.GetLength(); p++ )
  3310. {
  3311. if( offset <= currOffset ) break;
  3312. if( !calledFunc->parameterTypes[p].IsPrimitive() ||
  3313. calledFunc->parameterTypes[p].IsReference() )
  3314. {
  3315. currOffset++;
  3316. if( currOffset > 0 )
  3317. numPtrs++;
  3318. #if AS_PTR_SIZE == 2
  3319. // For 64bit platforms it is necessary to increment the currOffset by one more
  3320. // DWORD since the stackDelta was counting the full 64bit size of the pointer
  3321. else if( stackDelta )
  3322. currOffset++;
  3323. #endif
  3324. // The variable arg ? has an additiona 32bit integer with the typeid
  3325. if( calledFunc->parameterTypes[p].IsAnyType() )
  3326. currOffset += 1;
  3327. }
  3328. else
  3329. {
  3330. // Enums or built-in primitives are passed by value
  3331. asASSERT( calledFunc->parameterTypes[p].IsPrimitive() );
  3332. currOffset += calledFunc->parameterTypes[p].GetSizeOnStackDWords();
  3333. }
  3334. }
  3335. return offset - numPtrs * (1 - AS_PTR_SIZE);
  3336. }
  3337. int asCReader::FindTypeId(int idx)
  3338. {
  3339. if( idx >= 0 && idx < (int)usedTypeIds.GetLength() )
  3340. return usedTypeIds[idx];
  3341. else
  3342. {
  3343. Error(TXT_INVALID_BYTECODE_d);
  3344. return 0;
  3345. }
  3346. }
  3347. asCTypeInfo *asCReader::FindType(int idx)
  3348. {
  3349. if( idx < 0 || idx >= (int)usedTypes.GetLength() )
  3350. {
  3351. Error(TXT_INVALID_BYTECODE_d);
  3352. return 0;
  3353. }
  3354. return usedTypes[idx];
  3355. }
  3356. #ifndef AS_NO_COMPILER
  3357. asCWriter::asCWriter(asCModule* _module, asIBinaryStream* _stream, asCScriptEngine* _engine, bool _stripDebug)
  3358. : module(_module), stream(_stream), engine(_engine), stripDebugInfo(_stripDebug), error(false), bytesWritten(0)
  3359. {
  3360. }
  3361. int asCWriter::Error(const char *msg)
  3362. {
  3363. // Don't write if it has already been reported an error earlier
  3364. if (!error)
  3365. {
  3366. asCString str;
  3367. str.Format(msg, bytesWritten);
  3368. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  3369. error = true;
  3370. }
  3371. return asERROR;
  3372. }
  3373. int asCWriter::WriteData(const void *data, asUINT size)
  3374. {
  3375. asASSERT(size == 1 || size == 2 || size == 4 || size == 8);
  3376. int ret = 0;
  3377. #if defined(AS_BIG_ENDIAN)
  3378. for( asUINT n = 0; ret >= 0 && n < size; n++ )
  3379. ret = stream->Write(((asBYTE*)data)+n, 1);
  3380. #else
  3381. for( int n = size-1; ret >= 0 && n >= 0; n-- )
  3382. ret = stream->Write(((asBYTE*)data)+n, 1);
  3383. #endif
  3384. if (ret < 0)
  3385. Error(TXT_UNEXPECTED_END_OF_FILE);
  3386. bytesWritten += size;
  3387. return ret;
  3388. }
  3389. int asCWriter::Write()
  3390. {
  3391. TimeIt("asCWriter::Write");
  3392. unsigned long i, count;
  3393. // Store everything in the same order that the builder parses scripts
  3394. // TODO: Should be possible to skip saving the enum values. They are usually not needed after the script is compiled anyway
  3395. // TODO: Should be possible to skip saving the typedefs. They are usually not needed after the script is compiled anyway
  3396. // TODO: Should be possible to skip saving constants. They are usually not needed after the script is compiled anyway
  3397. // Write the flag as 1byte even on platforms with 4byte booleans
  3398. WriteEncodedInt64(stripDebugInfo ? 1 : 0);
  3399. // Store enums
  3400. {
  3401. TimeIt("store enums");
  3402. count = (asUINT)module->enumTypes.GetLength();
  3403. WriteEncodedInt64(count);
  3404. for( i = 0; i < count; i++ )
  3405. {
  3406. WriteTypeDeclaration(module->enumTypes[i], 1);
  3407. WriteTypeDeclaration(module->enumTypes[i], 2);
  3408. }
  3409. }
  3410. // Store type declarations first
  3411. {
  3412. TimeIt("type declarations");
  3413. count = (asUINT)module->classTypes.GetLength();
  3414. WriteEncodedInt64(count);
  3415. for( i = 0; i < count; i++ )
  3416. {
  3417. // Store only the name of the class/interface types
  3418. WriteTypeDeclaration(module->classTypes[i], 1);
  3419. }
  3420. }
  3421. // Store func defs
  3422. {
  3423. TimeIt("func defs");
  3424. count = (asUINT)module->funcDefs.GetLength();
  3425. WriteEncodedInt64(count);
  3426. for( i = 0; i < count; i++ )
  3427. WriteFunction(module->funcDefs[i]->funcdef);
  3428. }
  3429. // Now store all interface methods
  3430. {
  3431. TimeIt("interface methods");
  3432. count = (asUINT)module->classTypes.GetLength();
  3433. for( i = 0; i < count; i++ )
  3434. {
  3435. if( module->classTypes[i]->IsInterface() )
  3436. WriteTypeDeclaration(module->classTypes[i], 2);
  3437. }
  3438. }
  3439. // Then store the class methods and behaviours
  3440. {
  3441. TimeIt("class methods and behaviours");
  3442. for( i = 0; i < count; ++i )
  3443. {
  3444. if( !module->classTypes[i]->IsInterface() )
  3445. WriteTypeDeclaration(module->classTypes[i], 2);
  3446. }
  3447. }
  3448. // Then store the class properties
  3449. {
  3450. TimeIt("class properties");
  3451. for( i = 0; i < count; ++i )
  3452. {
  3453. if( !module->classTypes[i]->IsInterface() )
  3454. WriteTypeDeclaration(module->classTypes[i], 3);
  3455. }
  3456. }
  3457. // Store typedefs
  3458. {
  3459. TimeIt("type defs");
  3460. count = (asUINT)module->typeDefs.GetLength();
  3461. WriteEncodedInt64(count);
  3462. for( i = 0; i < count; i++ )
  3463. {
  3464. WriteTypeDeclaration(module->typeDefs[i], 1);
  3465. WriteTypeDeclaration(module->typeDefs[i], 2);
  3466. }
  3467. }
  3468. // scriptGlobals[]
  3469. {
  3470. TimeIt("script globals");
  3471. count = (asUINT)module->scriptGlobals.GetSize();
  3472. WriteEncodedInt64(count);
  3473. asCSymbolTable<asCGlobalProperty>::iterator it = module->scriptGlobals.List();
  3474. for( ; it; it++ )
  3475. WriteGlobalProperty(*it);
  3476. }
  3477. // scriptFunctions[]
  3478. {
  3479. TimeIt("scriptFunctions");
  3480. count = 0;
  3481. for( i = 0; i < module->scriptFunctions.GetLength(); i++ )
  3482. if( module->scriptFunctions[i]->objectType == 0 )
  3483. count++;
  3484. WriteEncodedInt64(count);
  3485. for( i = 0; i < module->scriptFunctions.GetLength(); ++i )
  3486. if( module->scriptFunctions[i]->objectType == 0 )
  3487. WriteFunction(module->scriptFunctions[i]);
  3488. }
  3489. // globalFunctions[]
  3490. {
  3491. TimeIt("globalFunctions");
  3492. count = (int)module->globalFunctions.GetSize();
  3493. asCSymbolTable<asCScriptFunction>::iterator funcIt = module->globalFunctions.List();
  3494. WriteEncodedInt64(count);
  3495. while( funcIt )
  3496. {
  3497. WriteFunction(*funcIt);
  3498. funcIt++;
  3499. }
  3500. }
  3501. // bindInformations[]
  3502. {
  3503. TimeIt("bindInformations");
  3504. count = (asUINT)module->bindInformations.GetLength();
  3505. WriteEncodedInt64(count);
  3506. for( i = 0; i < count; ++i )
  3507. {
  3508. WriteFunction(module->bindInformations[i]->importedFunctionSignature);
  3509. WriteString(&module->bindInformations[i]->importFromModule);
  3510. }
  3511. }
  3512. // usedTypes[]
  3513. {
  3514. TimeIt("usedTypes");
  3515. count = (asUINT)usedTypes.GetLength();
  3516. WriteEncodedInt64(count);
  3517. for( i = 0; i < count; ++i )
  3518. WriteTypeInfo(usedTypes[i]);
  3519. }
  3520. // usedTypeIds[]
  3521. WriteUsedTypeIds();
  3522. // usedFunctions[]
  3523. WriteUsedFunctions();
  3524. // usedGlobalProperties[]
  3525. WriteUsedGlobalProps();
  3526. // usedStringConstants[]
  3527. WriteUsedStringConstants();
  3528. // usedObjectProperties[]
  3529. WriteUsedObjectProps();
  3530. return error ? asERROR : asSUCCESS;
  3531. }
  3532. int asCWriter::FindStringConstantIndex(void *str)
  3533. {
  3534. asSMapNode<void*, int> *cursor = 0;
  3535. if (stringToIndexMap.MoveTo(&cursor, str))
  3536. return cursor->value;
  3537. usedStringConstants.PushLast(str);
  3538. int index = int(usedStringConstants.GetLength() - 1);
  3539. stringToIndexMap.Insert(str, index);
  3540. return index;
  3541. }
  3542. void asCWriter::WriteUsedStringConstants()
  3543. {
  3544. TimeIt("asCWriter::WriteUsedStringConstants");
  3545. asUINT count = (asUINT)usedStringConstants.GetLength();
  3546. WriteEncodedInt64(count);
  3547. asCString str;
  3548. for (asUINT i = 0; i < count; ++i)
  3549. {
  3550. asUINT length;
  3551. engine->stringFactory->GetRawStringData(usedStringConstants[i], 0, &length);
  3552. str.SetLength(length);
  3553. engine->stringFactory->GetRawStringData(usedStringConstants[i], str.AddressOf(), &length);
  3554. WriteString(&str);
  3555. }
  3556. }
  3557. void asCWriter::WriteUsedFunctions()
  3558. {
  3559. TimeIt("asCWriter::WriteUsedFunctions");
  3560. asUINT count = (asUINT)usedFunctions.GetLength();
  3561. WriteEncodedInt64(count);
  3562. for( asUINT n = 0; n < usedFunctions.GetLength(); n++ )
  3563. {
  3564. char c;
  3565. // Write enough data to be able to uniquely identify the function upon load
  3566. asCScriptFunction *func = usedFunctions[n];
  3567. if(func)
  3568. {
  3569. // Is the function from the module or the application?
  3570. c = func->module ? 'm' : 'a';
  3571. // Functions and methods that are shared and not owned by the module can be
  3572. // stored as 's' to tell the reader that these are received from other modules.
  3573. if (c == 'm' && func->IsShared() && module->scriptFunctions.IndexOf(func) < 0 )
  3574. c = 's';
  3575. WriteData(&c, 1);
  3576. WriteFunctionSignature(func);
  3577. }
  3578. else
  3579. {
  3580. // null function pointer
  3581. c = 'n';
  3582. WriteData(&c, 1);
  3583. }
  3584. }
  3585. }
  3586. void asCWriter::WriteFunctionSignature(asCScriptFunction *func)
  3587. {
  3588. asUINT i, count;
  3589. WriteString(&func->name);
  3590. if( func->name == DELEGATE_FACTORY )
  3591. {
  3592. // It's not necessary to write anything else
  3593. return;
  3594. }
  3595. WriteDataType(&func->returnType);
  3596. count = (asUINT)func->parameterTypes.GetLength();
  3597. WriteEncodedInt64(count);
  3598. for( i = 0; i < count; ++i )
  3599. WriteDataType(&func->parameterTypes[i]);
  3600. // Only write the inout flags if any of them are set
  3601. // If the number of parameters is 0, then no need to save this
  3602. if (func->parameterTypes.GetLength() > 0)
  3603. {
  3604. count = 0;
  3605. for (i = asUINT(func->inOutFlags.GetLength()); i > 0; i--)
  3606. if (func->inOutFlags[i - 1] != asTM_NONE)
  3607. {
  3608. count = i;
  3609. break;
  3610. }
  3611. WriteEncodedInt64(count);
  3612. for (i = 0; i < count; ++i)
  3613. WriteEncodedInt64(func->inOutFlags[i]);
  3614. }
  3615. WriteEncodedInt64(func->funcType);
  3616. // Write the default args, from last to first
  3617. // If the number of parameters is 0, then no need to save this
  3618. if (func->parameterTypes.GetLength() > 0)
  3619. {
  3620. count = 0;
  3621. for (i = (asUINT)func->defaultArgs.GetLength(); i-- > 0; )
  3622. if (func->defaultArgs[i])
  3623. count++;
  3624. WriteEncodedInt64(count);
  3625. for (i = (asUINT)func->defaultArgs.GetLength(); i-- > 0; )
  3626. if (func->defaultArgs[i])
  3627. WriteString(func->defaultArgs[i]);
  3628. }
  3629. WriteTypeInfo(func->objectType);
  3630. if( func->objectType )
  3631. {
  3632. asBYTE b = 0;
  3633. b += func->IsReadOnly() ? 1 : 0;
  3634. b += func->IsPrivate() ? 2 : 0;
  3635. b += func->IsProtected() ? 4 : 0;
  3636. WriteData(&b, 1);
  3637. }
  3638. else
  3639. {
  3640. if (func->funcType == asFUNC_FUNCDEF)
  3641. {
  3642. if (func->nameSpace)
  3643. {
  3644. // This funcdef was declared as global entity
  3645. asBYTE b = 'n';
  3646. WriteData(&b, 1);
  3647. WriteString(&func->nameSpace->name);
  3648. }
  3649. else
  3650. {
  3651. // This funcdef was declared as class member
  3652. asBYTE b = 'o';
  3653. WriteData(&b, 1);
  3654. WriteTypeInfo(func->funcdefType->parentClass);
  3655. }
  3656. }
  3657. else
  3658. WriteString(&func->nameSpace->name);
  3659. }
  3660. }
  3661. void asCWriter::WriteFunction(asCScriptFunction* func)
  3662. {
  3663. char c;
  3664. // If there is no function, then store a null char
  3665. if( func == 0 )
  3666. {
  3667. c = '\0';
  3668. WriteData(&c, 1);
  3669. return;
  3670. }
  3671. // First check if the function has been saved already
  3672. for( asUINT f = 0; f < savedFunctions.GetLength(); f++ )
  3673. {
  3674. if( savedFunctions[f] == func )
  3675. {
  3676. c = 'r';
  3677. WriteData(&c, 1);
  3678. WriteEncodedInt64(f);
  3679. return;
  3680. }
  3681. }
  3682. // Keep a reference to the function in the list
  3683. savedFunctions.PushLast(func);
  3684. c = 'f';
  3685. WriteData(&c, 1);
  3686. asUINT i, count;
  3687. WriteFunctionSignature(func);
  3688. if( func->funcType == asFUNC_SCRIPT )
  3689. {
  3690. // Skip this for external shared entities
  3691. if (module->externalTypes.IndexOf(func->objectType) >= 0)
  3692. return;
  3693. char bits = 0;
  3694. bits += func->IsShared() ? 1 : 0;
  3695. bits += func->dontCleanUpOnException ? 2 : 0;
  3696. if (module->externalFunctions.IndexOf(func) >= 0)
  3697. bits += 4;
  3698. if (func->scriptData->objVariablePos.GetLength() || func->scriptData->objVariableInfo.GetLength())
  3699. bits += 8;
  3700. if (func->scriptData->tryCatchInfo.GetLength())
  3701. bits += 16;
  3702. bits += func->IsExplicit() ? 32 : 0;
  3703. WriteData(&bits, 1);
  3704. // For external shared functions the rest is not needed
  3705. if (bits & 4)
  3706. return;
  3707. // Calculate the adjustment by position lookup table
  3708. CalculateAdjustmentByPos(func);
  3709. WriteByteCode(func);
  3710. asDWORD varSpace = AdjustStackPosition(func->scriptData->variableSpace);
  3711. WriteEncodedInt64(varSpace);
  3712. if (bits & 8)
  3713. {
  3714. count = (asUINT)func->scriptData->objVariablePos.GetLength();
  3715. WriteEncodedInt64(count);
  3716. for (i = 0; i < count; ++i)
  3717. {
  3718. WriteTypeInfo(func->scriptData->objVariableTypes[i]);
  3719. WriteEncodedInt64(AdjustStackPosition(func->scriptData->objVariablePos[i]));
  3720. }
  3721. if (count > 0)
  3722. WriteEncodedInt64(func->scriptData->objVariablesOnHeap);
  3723. WriteEncodedInt64((asUINT)func->scriptData->objVariableInfo.GetLength());
  3724. for (i = 0; i < func->scriptData->objVariableInfo.GetLength(); ++i)
  3725. {
  3726. // The program position must be adjusted to be in number of instructions
  3727. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->objVariableInfo[i].programPos]);
  3728. WriteEncodedInt64(AdjustStackPosition(func->scriptData->objVariableInfo[i].variableOffset));
  3729. WriteEncodedInt64(func->scriptData->objVariableInfo[i].option);
  3730. }
  3731. }
  3732. if (bits & 16)
  3733. {
  3734. // Write info on try/catch blocks
  3735. WriteEncodedInt64((asUINT)func->scriptData->tryCatchInfo.GetLength());
  3736. for (i = 0; i < func->scriptData->tryCatchInfo.GetLength(); ++i)
  3737. {
  3738. // The program position must be adjusted to be in number of instructions
  3739. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->tryCatchInfo[i].tryPos]);
  3740. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->tryCatchInfo[i].catchPos]);
  3741. }
  3742. }
  3743. // The program position (every even number) needs to be adjusted
  3744. // to be in number of instructions instead of DWORD offset
  3745. if( !stripDebugInfo )
  3746. {
  3747. asUINT length = (asUINT)func->scriptData->lineNumbers.GetLength();
  3748. WriteEncodedInt64(length);
  3749. for( i = 0; i < length; ++i )
  3750. {
  3751. if( (i & 1) == 0 )
  3752. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->lineNumbers[i]]);
  3753. else
  3754. WriteEncodedInt64(func->scriptData->lineNumbers[i]);
  3755. }
  3756. // Write the array of script sections
  3757. length = (asUINT)func->scriptData->sectionIdxs.GetLength();
  3758. WriteEncodedInt64(length);
  3759. for( i = 0; i < length; ++i )
  3760. {
  3761. if( (i & 1) == 0 )
  3762. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->sectionIdxs[i]]);
  3763. else
  3764. {
  3765. if( func->scriptData->sectionIdxs[i] >= 0 )
  3766. WriteString(engine->scriptSectionNames[func->scriptData->sectionIdxs[i]]);
  3767. else
  3768. {
  3769. c = 0;
  3770. WriteData(&c, 1);
  3771. }
  3772. }
  3773. }
  3774. }
  3775. // Write the variable information
  3776. if( !stripDebugInfo )
  3777. {
  3778. WriteEncodedInt64((asUINT)func->scriptData->variables.GetLength());
  3779. for( i = 0; i < func->scriptData->variables.GetLength(); i++ )
  3780. {
  3781. // The program position must be adjusted to be in number of instructions
  3782. WriteEncodedInt64(bytecodeNbrByPos[func->scriptData->variables[i]->declaredAtProgramPos]);
  3783. // The stack position must be adjusted according to the pointer sizes
  3784. WriteEncodedInt64(AdjustStackPosition(func->scriptData->variables[i]->stackOffset));
  3785. WriteString(&func->scriptData->variables[i]->name);
  3786. WriteDataType(&func->scriptData->variables[i]->type);
  3787. }
  3788. }
  3789. // Store script section name
  3790. if( !stripDebugInfo )
  3791. {
  3792. if( func->scriptData->scriptSectionIdx >= 0 )
  3793. WriteString(engine->scriptSectionNames[func->scriptData->scriptSectionIdx]);
  3794. else
  3795. {
  3796. c = 0;
  3797. WriteData(&c, 1);
  3798. }
  3799. WriteEncodedInt64(func->scriptData->declaredAt);
  3800. }
  3801. // Store the parameter names
  3802. if( !stripDebugInfo )
  3803. {
  3804. count = asUINT(func->parameterNames.GetLength());
  3805. WriteEncodedInt64(count);
  3806. for( asUINT n = 0; n < count; n++ )
  3807. WriteString(&func->parameterNames[n]);
  3808. }
  3809. }
  3810. else if( func->funcType == asFUNC_VIRTUAL || func->funcType == asFUNC_INTERFACE )
  3811. {
  3812. // TODO: Do we really need to store this? It can probably be reconstructed by the reader
  3813. WriteEncodedInt64(func->vfTableIdx);
  3814. }
  3815. else if( func->funcType == asFUNC_FUNCDEF )
  3816. {
  3817. char bits = 0;
  3818. bits += func->IsShared() ? 1 : 0;
  3819. if (module->externalTypes.IndexOf(func->funcdefType) >= 0)
  3820. bits += 2;
  3821. WriteData(&bits,1);
  3822. }
  3823. }
  3824. void asCWriter::WriteTypeDeclaration(asCTypeInfo *type, int phase)
  3825. {
  3826. if( phase == 1 )
  3827. {
  3828. // name
  3829. WriteString(&type->name);
  3830. // flags
  3831. WriteData(&type->flags, 4);
  3832. // size
  3833. // TODO: Do we really need to store this? The reader should be able to
  3834. // determine the correct size from the object type's flags
  3835. if( (type->flags & asOBJ_SCRIPT_OBJECT) && type->size > 0 )
  3836. {
  3837. // The size for script objects may vary from platform to platform so
  3838. // only store 1 to diferentiate from interfaces that have size 0.
  3839. WriteEncodedInt64(1);
  3840. }
  3841. else
  3842. {
  3843. // Enums, typedefs, and interfaces have fixed sizes independently
  3844. // of platform so it is safe to serialize the size directly.
  3845. WriteEncodedInt64(type->size);
  3846. }
  3847. // namespace
  3848. WriteString(&type->nameSpace->name);
  3849. // external shared flag
  3850. if ((type->flags & asOBJ_SHARED))
  3851. {
  3852. char c = ' ';
  3853. if (module->externalTypes.IndexOf(type) >= 0)
  3854. c = 'e';
  3855. WriteData(&c, 1);
  3856. }
  3857. }
  3858. else if( phase == 2 )
  3859. {
  3860. // external shared types doesn't need to save this
  3861. if ((type->flags & asOBJ_SHARED) && module->externalTypes.IndexOf(type) >= 0)
  3862. return;
  3863. if(type->flags & asOBJ_ENUM )
  3864. {
  3865. // enumValues[]
  3866. asCEnumType *t = CastToEnumType(type);
  3867. int size = (int)t->enumValues.GetLength();
  3868. WriteEncodedInt64(size);
  3869. for( int n = 0; n < size; n++ )
  3870. {
  3871. WriteString(&t->enumValues[n]->name);
  3872. WriteData(&t->enumValues[n]->value, 4);
  3873. }
  3874. }
  3875. else if(type->flags & asOBJ_TYPEDEF )
  3876. {
  3877. asCTypedefType *td = CastToTypedefType(type);
  3878. eTokenType t = td->aliasForType.GetTokenType();
  3879. WriteEncodedInt64(t);
  3880. }
  3881. else
  3882. {
  3883. asCObjectType *t = CastToObjectType(type);
  3884. WriteTypeInfo(t->derivedFrom);
  3885. // interfaces[] / interfaceVFTOffsets[]
  3886. // TOOD: Is it really necessary to store the VFTOffsets? Can't the reader calculate those?
  3887. int size = (asUINT)t->interfaces.GetLength();
  3888. WriteEncodedInt64(size);
  3889. asUINT n;
  3890. asASSERT( t->IsInterface() || t->interfaces.GetLength() == t->interfaceVFTOffsets.GetLength() );
  3891. for( n = 0; n < t->interfaces.GetLength(); n++ )
  3892. {
  3893. WriteTypeInfo(t->interfaces[n]);
  3894. if( !t->IsInterface() )
  3895. WriteEncodedInt64(t->interfaceVFTOffsets[n]);
  3896. }
  3897. // behaviours
  3898. // TODO: Default behaviours should just be stored as a indicator
  3899. // to avoid storing the actual function object
  3900. if( !t->IsInterface() && type->flags != asOBJ_TYPEDEF && type->flags != asOBJ_ENUM )
  3901. {
  3902. WriteFunction(engine->scriptFunctions[t->beh.destruct]);
  3903. size = (int)t->beh.constructors.GetLength();
  3904. WriteEncodedInt64(size);
  3905. for( n = 0; n < t->beh.constructors.GetLength(); n++ )
  3906. {
  3907. WriteFunction(engine->scriptFunctions[t->beh.constructors[n]]);
  3908. WriteFunction(engine->scriptFunctions[t->beh.factories[n]]);
  3909. }
  3910. }
  3911. // methods[]
  3912. // TODO: Avoid storing inherited methods in interfaces, as the reader
  3913. // can add those directly from the base interface
  3914. size = (int)t->methods.GetLength();
  3915. WriteEncodedInt64(size);
  3916. for( n = 0; n < t->methods.GetLength(); n++ )
  3917. {
  3918. WriteFunction(engine->scriptFunctions[t->methods[n]]);
  3919. }
  3920. // virtualFunctionTable[]
  3921. // TODO: Is it really necessary to store this? Can't it be easily rebuilt by the reader
  3922. size = (int)t->virtualFunctionTable.GetLength();
  3923. WriteEncodedInt64(size);
  3924. for( n = 0; n < (asUINT)size; n++ )
  3925. {
  3926. WriteFunction(t->virtualFunctionTable[n]);
  3927. }
  3928. }
  3929. }
  3930. else if( phase == 3 )
  3931. {
  3932. // external shared types doesn't need to save this
  3933. if ((type->flags & asOBJ_SHARED) && module->externalTypes.IndexOf(type) >= 0)
  3934. return;
  3935. // properties[]
  3936. asCObjectType *t = CastToObjectType(type);
  3937. // This is only done for object types
  3938. asASSERT(t);
  3939. asUINT size = (asUINT)t->properties.GetLength();
  3940. WriteEncodedInt64(size);
  3941. for (asUINT n = 0; n < t->properties.GetLength(); n++)
  3942. {
  3943. WriteObjectProperty(t->properties[n]);
  3944. }
  3945. }
  3946. }
  3947. void asCWriter::WriteEncodedInt64(asINT64 i)
  3948. {
  3949. asBYTE signBit = ( i & asINT64(1)<<63 ) ? 0x80 : 0;
  3950. if( signBit ) i = -i;
  3951. asBYTE b;
  3952. if( i < (1<<6) )
  3953. {
  3954. b = (asBYTE)(signBit + i); WriteData(&b, 1);
  3955. }
  3956. else if( i < (1<<13) )
  3957. {
  3958. b = asBYTE(0x40 + signBit + (i >> 8)); WriteData(&b, 1);
  3959. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  3960. }
  3961. else if( i < (1<<20) )
  3962. {
  3963. b = asBYTE(0x60 + signBit + (i >> 16)); WriteData(&b, 1);
  3964. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  3965. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  3966. }
  3967. else if( i < (1<<27) )
  3968. {
  3969. b = asBYTE(0x70 + signBit + (i >> 24)); WriteData(&b, 1);
  3970. b = asBYTE((i >> 16) & 0xFF); WriteData(&b, 1);
  3971. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  3972. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  3973. }
  3974. else if( i < (asINT64(1)<<34) )
  3975. {
  3976. b = asBYTE(0x78 + signBit + (i >> 32)); WriteData(&b, 1);
  3977. b = asBYTE((i >> 24) & 0xFF); WriteData(&b, 1);
  3978. b = asBYTE((i >> 16) & 0xFF); WriteData(&b, 1);
  3979. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  3980. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  3981. }
  3982. else if( i < (asINT64(1)<<41) )
  3983. {
  3984. b = asBYTE(0x7C + signBit + (i >> 40)); WriteData(&b, 1);
  3985. b = asBYTE((i >> 32) & 0xFF); WriteData(&b, 1);
  3986. b = asBYTE((i >> 24) & 0xFF); WriteData(&b, 1);
  3987. b = asBYTE((i >> 16) & 0xFF); WriteData(&b, 1);
  3988. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  3989. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  3990. }
  3991. else if( i < (asINT64(1)<<48) )
  3992. {
  3993. b = asBYTE(0x7E + signBit + (i >> 48)); WriteData(&b, 1);
  3994. b = asBYTE((i >> 40) & 0xFF); WriteData(&b, 1);
  3995. b = asBYTE((i >> 32) & 0xFF); WriteData(&b, 1);
  3996. b = asBYTE((i >> 24) & 0xFF); WriteData(&b, 1);
  3997. b = asBYTE((i >> 16) & 0xFF); WriteData(&b, 1);
  3998. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  3999. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  4000. }
  4001. else
  4002. {
  4003. b = asBYTE(0x7F + signBit); WriteData(&b, 1);
  4004. b = asBYTE((i >> 56) & 0xFF); WriteData(&b, 1);
  4005. b = asBYTE((i >> 48) & 0xFF); WriteData(&b, 1);
  4006. b = asBYTE((i >> 40) & 0xFF); WriteData(&b, 1);
  4007. b = asBYTE((i >> 32) & 0xFF); WriteData(&b, 1);
  4008. b = asBYTE((i >> 24) & 0xFF); WriteData(&b, 1);
  4009. b = asBYTE((i >> 16) & 0xFF); WriteData(&b, 1);
  4010. b = asBYTE((i >> 8) & 0xFF); WriteData(&b, 1);
  4011. b = asBYTE(i & 0xFF); WriteData(&b, 1);
  4012. }
  4013. }
  4014. void asCWriter::WriteString(asCString* str)
  4015. {
  4016. // First check if the string hasn't been saved already
  4017. asSMapNode<asCString, int> *cursor = 0;
  4018. if (stringToIdMap.MoveTo(&cursor, *str))
  4019. {
  4020. // Save a reference to the existing string
  4021. // The lowest bit is set to 1 to indicate a reference
  4022. WriteEncodedInt64(cursor->value*2+1);
  4023. return;
  4024. }
  4025. // Save a new string
  4026. // The lowest bit is set to 0 to indicate a new string
  4027. asUINT len = (asUINT)str->GetLength();
  4028. WriteEncodedInt64(len*2);
  4029. if( len > 0 )
  4030. {
  4031. stream->Write(str->AddressOf(), (asUINT)len);
  4032. bytesWritten += len;
  4033. savedStrings.PushLast(*str);
  4034. stringToIdMap.Insert(*str, int(savedStrings.GetLength()) - 1);
  4035. }
  4036. }
  4037. void asCWriter::WriteGlobalProperty(asCGlobalProperty* prop)
  4038. {
  4039. // TODO: We might be able to avoid storing the name and type of the global
  4040. // properties twice if we merge this with the WriteUsedGlobalProperties.
  4041. WriteString(&prop->name);
  4042. WriteString(&prop->nameSpace->name);
  4043. WriteDataType(&prop->type);
  4044. // Store the initialization function
  4045. WriteFunction(prop->GetInitFunc());
  4046. }
  4047. void asCWriter::WriteObjectProperty(asCObjectProperty* prop)
  4048. {
  4049. WriteString(&prop->name);
  4050. WriteDataType(&prop->type);
  4051. int flags = 0;
  4052. if( prop->isPrivate ) flags |= 1;
  4053. if( prop->isProtected ) flags |= 2;
  4054. if( prop->isInherited ) flags |= 4;
  4055. WriteEncodedInt64(flags);
  4056. }
  4057. void asCWriter::WriteDataType(const asCDataType *dt)
  4058. {
  4059. // First check if the datatype has already been saved
  4060. for( asUINT n = 0; n < savedDataTypes.GetLength(); n++ )
  4061. {
  4062. if( *dt == savedDataTypes[n] )
  4063. {
  4064. WriteEncodedInt64(n+1);
  4065. return;
  4066. }
  4067. }
  4068. // Indicate a new type with a null byte
  4069. asUINT c = 0;
  4070. WriteEncodedInt64(c);
  4071. // Save the new datatype
  4072. savedDataTypes.PushLast(*dt);
  4073. int t = dt->GetTokenType();
  4074. WriteEncodedInt64(t);
  4075. if( t == ttIdentifier )
  4076. WriteTypeInfo(dt->GetTypeInfo());
  4077. // Endianess safe bitmask
  4078. char bits = 0;
  4079. SAVE_TO_BIT(bits, dt->IsObjectHandle(), 0);
  4080. SAVE_TO_BIT(bits, dt->IsHandleToConst(), 1);
  4081. SAVE_TO_BIT(bits, dt->IsReference(), 2);
  4082. SAVE_TO_BIT(bits, dt->IsReadOnly(), 3);
  4083. WriteData(&bits, 1);
  4084. }
  4085. void asCWriter::WriteTypeInfo(asCTypeInfo* ti)
  4086. {
  4087. char ch;
  4088. if( ti )
  4089. {
  4090. // Check for template instances/specializations
  4091. asCObjectType *ot = CastToObjectType(ti);
  4092. if( ot && ot->templateSubTypes.GetLength() )
  4093. {
  4094. // Check for list pattern type or template type
  4095. if( ot->flags & asOBJ_LIST_PATTERN )
  4096. {
  4097. ch = 'l'; // list
  4098. WriteData(&ch, 1);
  4099. WriteTypeInfo(ot->templateSubTypes[0].GetTypeInfo());
  4100. }
  4101. else
  4102. {
  4103. ch = 'a'; // array
  4104. WriteData(&ch, 1);
  4105. WriteString(&ot->name);
  4106. WriteString(&ot->nameSpace->name);
  4107. WriteEncodedInt64(ot->templateSubTypes.GetLength());
  4108. for( asUINT n = 0; n < ot->templateSubTypes.GetLength(); n++ )
  4109. {
  4110. if( !ot->templateSubTypes[n].IsPrimitive() || ot->templateSubTypes[n].IsEnumType() )
  4111. {
  4112. ch = 's'; // sub type
  4113. WriteData(&ch, 1);
  4114. WriteDataType(&ot->templateSubTypes[n]);
  4115. }
  4116. else
  4117. {
  4118. ch = 't'; // token
  4119. WriteData(&ch, 1);
  4120. eTokenType t = ot->templateSubTypes[n].GetTokenType();
  4121. WriteEncodedInt64(t);
  4122. }
  4123. }
  4124. }
  4125. }
  4126. else if( ti->flags & asOBJ_TEMPLATE_SUBTYPE )
  4127. {
  4128. ch = 's'; // sub type
  4129. WriteData(&ch, 1);
  4130. WriteString(&ti->name);
  4131. }
  4132. else if( !ti->GetParentType() )
  4133. {
  4134. ch = 'o'; // object
  4135. WriteData(&ch, 1);
  4136. WriteString(&ti->name);
  4137. WriteString(&ti->nameSpace->name);
  4138. }
  4139. else
  4140. {
  4141. asASSERT(ti->flags & asOBJ_FUNCDEF);
  4142. ch = 'c'; // child type
  4143. WriteData(&ch, 1);
  4144. WriteString(&ti->name);
  4145. WriteTypeInfo(CastToFuncdefType(ti)->parentClass);
  4146. }
  4147. }
  4148. else
  4149. {
  4150. ch = '\0';
  4151. WriteData(&ch, 1);
  4152. }
  4153. }
  4154. void asCWriter::CalculateAdjustmentByPos(asCScriptFunction *func)
  4155. {
  4156. // Adjust the offset of all negative variables (parameters) so all pointers will have a size of 1 dword
  4157. asUINT n;
  4158. asCArray<int> adjustments;
  4159. asUINT offset = 0;
  4160. if( func->objectType )
  4161. {
  4162. adjustments.PushLast(offset);
  4163. adjustments.PushLast(1-AS_PTR_SIZE);
  4164. offset += AS_PTR_SIZE;
  4165. }
  4166. if( func->DoesReturnOnStack() )
  4167. {
  4168. adjustments.PushLast(offset);
  4169. adjustments.PushLast(1-AS_PTR_SIZE);
  4170. offset += AS_PTR_SIZE;
  4171. }
  4172. for( n = 0; n < func->parameterTypes.GetLength(); n++ )
  4173. {
  4174. if( !func->parameterTypes[n].IsPrimitive() ||
  4175. func->parameterTypes[n].IsReference() )
  4176. {
  4177. adjustments.PushLast(offset);
  4178. adjustments.PushLast(1-AS_PTR_SIZE);
  4179. offset += AS_PTR_SIZE;
  4180. }
  4181. else
  4182. {
  4183. asASSERT( func->parameterTypes[n].IsPrimitive() );
  4184. offset += func->parameterTypes[n].GetSizeOnStackDWords();
  4185. }
  4186. }
  4187. // Build look-up table with the adjustments for each stack position
  4188. adjustNegativeStackByPos.SetLength(offset);
  4189. memset(adjustNegativeStackByPos.AddressOf(), 0, adjustNegativeStackByPos.GetLength()*sizeof(int));
  4190. for( n = 0; n < adjustments.GetLength(); n+=2 )
  4191. {
  4192. int pos = adjustments[n];
  4193. int adjust = adjustments[n+1];
  4194. for( asUINT i = pos+1; i < adjustNegativeStackByPos.GetLength(); i++ )
  4195. adjustNegativeStackByPos[i] += adjust;
  4196. }
  4197. // Adjust the offset of all positive variables so that all object types and handles have a size of 1 dword
  4198. // This is similar to how the adjustment is done in the asCReader::TranslateFunction, only the reverse
  4199. adjustments.SetLength(0);
  4200. for( n = 0; n < func->scriptData->objVariableTypes.GetLength(); n++ )
  4201. {
  4202. // Determine the size the variable currently occupies on the stack
  4203. int size = AS_PTR_SIZE;
  4204. // objVariableTypes is null if the variable type is a null pointer
  4205. if( func->scriptData->objVariableTypes[n] &&
  4206. (func->scriptData->objVariableTypes[n]->GetFlags() & asOBJ_VALUE) &&
  4207. n >= func->scriptData->objVariablesOnHeap )
  4208. {
  4209. size = func->scriptData->objVariableTypes[n]->GetSize();
  4210. if( size < 4 )
  4211. size = 1;
  4212. else
  4213. size /= 4;
  4214. }
  4215. // If larger than 1 dword, adjust the offsets accordingly
  4216. if (size > 1)
  4217. {
  4218. // How much needs to be adjusted?
  4219. adjustments.PushLast(func->scriptData->objVariablePos[n]);
  4220. adjustments.PushLast(-(size - 1));
  4221. }
  4222. }
  4223. // Build look-up table with the adjustments for each stack position
  4224. adjustStackByPos.SetLength(func->scriptData->stackNeeded);
  4225. memset(adjustStackByPos.AddressOf(), 0, adjustStackByPos.GetLength()*sizeof(int));
  4226. for( n = 0; n < adjustments.GetLength(); n+=2 )
  4227. {
  4228. int pos = adjustments[n];
  4229. int adjust = adjustments[n+1];
  4230. for( asUINT i = pos; i < adjustStackByPos.GetLength(); i++ )
  4231. adjustStackByPos[i] += adjust;
  4232. }
  4233. // Compute the sequence number of each bytecode instruction in order to update the jump offsets
  4234. asUINT length = func->scriptData->byteCode.GetLength();
  4235. asDWORD *bc = func->scriptData->byteCode.AddressOf();
  4236. bytecodeNbrByPos.SetLength(length);
  4237. asUINT num;
  4238. for( offset = 0, num = 0; offset < length; )
  4239. {
  4240. bytecodeNbrByPos[offset] = num;
  4241. offset += asBCTypeSize[asBCInfo[*(asBYTE*)(bc+offset)].type];
  4242. num++;
  4243. }
  4244. // Store the number of instructions in the last position of bytecodeNbrByPos,
  4245. // so this can be easily queried in SaveBytecode. Normally this is already done
  4246. // as most functions end with BC_RET, but in some cases the last instruction in
  4247. // the function is not a BC_RET, e.g. when a function has a never ending loop.
  4248. bytecodeNbrByPos[length - 1] = num - 1;
  4249. }
  4250. int asCWriter::AdjustStackPosition(int pos)
  4251. {
  4252. if( pos >= (int)adjustStackByPos.GetLength() )
  4253. {
  4254. // This happens for example if the function only have temporary variables
  4255. // The adjustByPos can also be empty if the function doesn't have any variables at all, but receive a handle by parameter
  4256. if( adjustStackByPos.GetLength() > 0 )
  4257. pos += adjustStackByPos[adjustStackByPos.GetLength()-1];
  4258. }
  4259. else if( pos >= 0 )
  4260. pos += adjustStackByPos[pos];
  4261. else
  4262. {
  4263. asASSERT( -pos < (int)adjustNegativeStackByPos.GetLength() );
  4264. pos -= (short)adjustNegativeStackByPos[-pos];
  4265. }
  4266. return pos;
  4267. }
  4268. int asCWriter::AdjustGetOffset(int offset, asCScriptFunction *func, asDWORD programPos)
  4269. {
  4270. // TODO: optimize: multiple instructions for the same function doesn't need to look for the function everytime
  4271. // the function can remember where it found the function and check if the programPos is still valid
  4272. // Get offset 0 doesn't need adjustment
  4273. if( offset == 0 ) return 0;
  4274. bool bcAlloc = false;
  4275. // Find out which function that will be called
  4276. asCScriptFunction *calledFunc = 0;
  4277. int stackDelta = 0;
  4278. for( asUINT n = programPos; n < func->scriptData->byteCode.GetLength(); )
  4279. {
  4280. asBYTE bc = *(asBYTE*)&func->scriptData->byteCode[n];
  4281. if( bc == asBC_CALL ||
  4282. bc == asBC_CALLSYS ||
  4283. bc == asBC_Thiscall1 ||
  4284. bc == asBC_CALLINTF )
  4285. {
  4286. // Find the function from the function id in bytecode
  4287. int funcId = asBC_INTARG(&func->scriptData->byteCode[n]);
  4288. calledFunc = engine->scriptFunctions[funcId];
  4289. break;
  4290. }
  4291. else if( bc == asBC_ALLOC )
  4292. {
  4293. // The alloc instruction doesn't take the object pointer on the stack,
  4294. // as the memory will be allocated by the instruction itself
  4295. bcAlloc = true;
  4296. // Find the function from the function id in the bytecode
  4297. int funcId = asBC_INTARG(&func->scriptData->byteCode[n+AS_PTR_SIZE]);
  4298. calledFunc = engine->scriptFunctions[funcId];
  4299. break;
  4300. }
  4301. else if( bc == asBC_CALLBND )
  4302. {
  4303. // Find the function from the engine's bind array
  4304. int funcId = asBC_INTARG(&func->scriptData->byteCode[n]);
  4305. calledFunc = engine->importedFunctions[funcId & ~FUNC_IMPORTED]->importedFunctionSignature;
  4306. break;
  4307. }
  4308. else if( bc == asBC_CallPtr )
  4309. {
  4310. int var = asBC_SWORDARG0(&func->scriptData->byteCode[n]);
  4311. asUINT v;
  4312. // Find the funcdef from the local variable
  4313. for( v = 0; v < func->scriptData->objVariablePos.GetLength(); v++ )
  4314. {
  4315. if( func->scriptData->objVariablePos[v] == var )
  4316. {
  4317. calledFunc = CastToFuncdefType(func->scriptData->objVariableTypes[v])->funcdef;
  4318. break;
  4319. }
  4320. }
  4321. if( !calledFunc )
  4322. {
  4323. // Look in parameters
  4324. int paramPos = 0;
  4325. if( func->objectType )
  4326. paramPos -= AS_PTR_SIZE;
  4327. if( func->DoesReturnOnStack() )
  4328. paramPos -= AS_PTR_SIZE;
  4329. for( v = 0; v < func->parameterTypes.GetLength(); v++ )
  4330. {
  4331. if( var == paramPos )
  4332. {
  4333. calledFunc = CastToFuncdefType(func->parameterTypes[v].GetTypeInfo())->funcdef;
  4334. break;
  4335. }
  4336. paramPos -= func->parameterTypes[v].GetSizeOnStackDWords();
  4337. }
  4338. }
  4339. break;
  4340. }
  4341. else if( bc == asBC_REFCPY ||
  4342. bc == asBC_COPY )
  4343. {
  4344. // In this case we know there is only 1 pointer on the stack above
  4345. asASSERT( offset == AS_PTR_SIZE );
  4346. return offset + (1 - AS_PTR_SIZE);
  4347. }
  4348. // Keep track of the stack size between the
  4349. // instruction that needs to be adjusted and the call
  4350. stackDelta += asBCInfo[bc].stackInc;
  4351. n += asBCTypeSize[asBCInfo[bc].type];
  4352. }
  4353. asASSERT( calledFunc );
  4354. // Count the number of pointers pushed on the stack above the
  4355. // current offset, and then adjust the offset accordingly
  4356. asUINT numPtrs = 0;
  4357. int currOffset = -stackDelta;
  4358. if( offset > currOffset && calledFunc->GetObjectType() && !bcAlloc )
  4359. {
  4360. currOffset += AS_PTR_SIZE;
  4361. if( currOffset > 0 )
  4362. numPtrs++;
  4363. }
  4364. if( offset > currOffset && calledFunc->DoesReturnOnStack() )
  4365. {
  4366. currOffset += AS_PTR_SIZE;
  4367. if( currOffset > 0 )
  4368. numPtrs++;
  4369. }
  4370. for( asUINT p = 0; p < calledFunc->parameterTypes.GetLength(); p++ )
  4371. {
  4372. if( offset <= currOffset ) break;
  4373. if( !calledFunc->parameterTypes[p].IsPrimitive() ||
  4374. calledFunc->parameterTypes[p].IsReference() )
  4375. {
  4376. // objects and references are passed by pointer
  4377. currOffset += AS_PTR_SIZE;
  4378. if( currOffset > 0 )
  4379. numPtrs++;
  4380. // The variable arg ? has an additional 32bit int with the typeid
  4381. if( calledFunc->parameterTypes[p].IsAnyType() )
  4382. currOffset += 1;
  4383. }
  4384. else
  4385. {
  4386. // built-in primitives or enums are passed by value
  4387. asASSERT( calledFunc->parameterTypes[p].IsPrimitive() );
  4388. currOffset += calledFunc->parameterTypes[p].GetSizeOnStackDWords();
  4389. }
  4390. }
  4391. // The get offset must match one of the parameter offsets
  4392. asASSERT( offset == currOffset );
  4393. return offset + numPtrs * (1 - AS_PTR_SIZE);
  4394. }
  4395. void asCWriter::WriteByteCode(asCScriptFunction *func)
  4396. {
  4397. asDWORD *bc = func->scriptData->byteCode.AddressOf();
  4398. size_t length = func->scriptData->byteCode.GetLength();
  4399. // The length cannot be stored, because it is platform dependent,
  4400. // instead we store the number of instructions
  4401. asUINT count = bytecodeNbrByPos[bytecodeNbrByPos.GetLength()-1] + 1;
  4402. WriteEncodedInt64(count);
  4403. asDWORD *startBC = bc;
  4404. while( length )
  4405. {
  4406. asDWORD tmpBC[4]; // The biggest instructions take up 4 DWORDs
  4407. asDWORD c = *(asBYTE*)bc;
  4408. // Copy the instruction to a temp buffer so we can work on it before saving
  4409. memcpy(tmpBC, bc, asBCTypeSize[asBCInfo[c].type]*sizeof(asDWORD));
  4410. if( c == asBC_ALLOC ) // PTR_DW_ARG
  4411. {
  4412. // Translate the object type
  4413. asCObjectType *ot = *(asCObjectType**)(tmpBC+1);
  4414. *(asPWORD*)(tmpBC+1) = FindTypeInfoIdx(ot);
  4415. // Translate the constructor func id, unless it is 0
  4416. if( *(int*)&tmpBC[1+AS_PTR_SIZE] != 0 )
  4417. {
  4418. // Increment 1 to the translated function id, as 0 will be reserved for no function
  4419. *(int*)&tmpBC[1+AS_PTR_SIZE] = 1+FindFunctionIndex(engine->scriptFunctions[*(int*)&tmpBC[1+AS_PTR_SIZE]]);
  4420. }
  4421. }
  4422. else if( c == asBC_REFCPY || // PTR_ARG
  4423. c == asBC_RefCpyV || // wW_PTR_ARG
  4424. c == asBC_OBJTYPE ) // PTR_ARG
  4425. {
  4426. // Translate object type pointers into indices
  4427. *(asPWORD*)(tmpBC+1) = FindTypeInfoIdx(*(asCObjectType**)(tmpBC+1));
  4428. }
  4429. else if( c == asBC_JitEntry ) // PTR_ARG
  4430. {
  4431. // We don't store the JIT argument
  4432. *(asPWORD*)(tmpBC+1) = 0;
  4433. }
  4434. else if( c == asBC_TYPEID || // DW_ARG
  4435. c == asBC_Cast ) // DW_ARG
  4436. {
  4437. // Translate type ids into indices
  4438. *(int*)(tmpBC+1) = FindTypeIdIdx(*(int*)(tmpBC+1));
  4439. }
  4440. else if( c == asBC_ADDSi || // W_DW_ARG
  4441. c == asBC_LoadThisR ) // W_DW_ARG
  4442. {
  4443. // Translate property offsets into indices
  4444. *(((short*)tmpBC)+1) = (short)FindObjectPropIndex(*(((short*)tmpBC)+1), *(int*)(tmpBC+1), bc);
  4445. // Translate type ids into indices
  4446. *(int*)(tmpBC+1) = FindTypeIdIdx(*(int*)(tmpBC+1));
  4447. }
  4448. else if( c == asBC_LoadRObjR || // rW_W_DW_ARG
  4449. c == asBC_LoadVObjR ) // rW_W_DW_ARG
  4450. {
  4451. asCObjectType *ot = engine->GetObjectTypeFromTypeId(*(int*)(tmpBC+2));
  4452. if( ot->flags & asOBJ_LIST_PATTERN )
  4453. {
  4454. // List patterns have a different way of translating the offsets
  4455. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  4456. *(((short*)tmpBC)+2) = (short)listAdj->AdjustOffset(*(((short*)tmpBC)+2), ot);
  4457. }
  4458. else
  4459. {
  4460. // Translate property offsets into indices
  4461. *(((short*)tmpBC)+2) = (short)FindObjectPropIndex(*(((short*)tmpBC)+2), *(int*)(tmpBC+2), bc);
  4462. }
  4463. // Translate type ids into indices
  4464. *(int*)(tmpBC+2) = FindTypeIdIdx(*(int*)(tmpBC+2));
  4465. }
  4466. else if( c == asBC_COPY ) // W_DW_ARG
  4467. {
  4468. // Translate type ids into indices
  4469. *(int*)(tmpBC+1) = FindTypeIdIdx(*(int*)(tmpBC+1));
  4470. // Update the WORDARG0 to 0, as this will be recalculated on the target platform
  4471. asBC_WORDARG0(tmpBC) = 0;
  4472. }
  4473. else if( c == asBC_RET ) // W_ARG
  4474. {
  4475. // Save with arg 0, as this will be recalculated on the target platform
  4476. asBC_WORDARG0(tmpBC) = 0;
  4477. }
  4478. else if( c == asBC_CALL || // DW_ARG
  4479. c == asBC_CALLINTF || // DW_ARG
  4480. c == asBC_CALLSYS || // DW_ARG
  4481. c == asBC_Thiscall1 ) // DW_ARG
  4482. {
  4483. // Translate the function id
  4484. *(int*)(tmpBC+1) = FindFunctionIndex(engine->scriptFunctions[*(int*)(tmpBC+1)]);
  4485. }
  4486. else if( c == asBC_FuncPtr ) // PTR_ARG
  4487. {
  4488. // Translate the function pointer
  4489. *(asPWORD*)(tmpBC+1) = FindFunctionIndex(*(asCScriptFunction**)(tmpBC+1));
  4490. }
  4491. else if( c == asBC_CALLBND ) // DW_ARG
  4492. {
  4493. // Translate the function id
  4494. int funcId = tmpBC[1];
  4495. for( asUINT n = 0; n < module->bindInformations.GetLength(); n++ )
  4496. if( module->bindInformations[n]->importedFunctionSignature->id == funcId )
  4497. {
  4498. funcId = n;
  4499. break;
  4500. }
  4501. tmpBC[1] = funcId;
  4502. }
  4503. else if( c == asBC_PGA || // PTR_ARG
  4504. c == asBC_PshGPtr || // PTR_ARG
  4505. c == asBC_LDG || // PTR_ARG
  4506. c == asBC_PshG4 || // PTR_ARG
  4507. c == asBC_LdGRdR4 || // wW_PTR_ARG
  4508. c == asBC_CpyGtoV4 || // wW_PTR_ARG
  4509. c == asBC_CpyVtoG4 || // rW_PTR_ARG
  4510. c == asBC_SetG4 ) // PTR_DW_ARG
  4511. {
  4512. // Check if the address is a global property or a string constant
  4513. void *ptr = *(void**)(tmpBC + 1);
  4514. if (engine->varAddressMap.MoveTo(0, ptr))
  4515. {
  4516. // Translate global variable pointers into indices
  4517. // Flag the first bit to signal global property
  4518. *(asPWORD*)(tmpBC + 1) = (FindGlobalPropPtrIndex(*(void**)(tmpBC + 1)) << 1) + 1;
  4519. }
  4520. else
  4521. {
  4522. // Only PGA and PshGPtr can hold string constants
  4523. asASSERT(c == asBC_PGA || c == asBC_PshGPtr);
  4524. // Translate string constants into indices
  4525. // Leave the first bit clear to signal string constant
  4526. *(asPWORD*)(tmpBC + 1) = FindStringConstantIndex(*(void**)(tmpBC + 1)) << 1;
  4527. }
  4528. }
  4529. else if( c == asBC_JMP || // DW_ARG
  4530. c == asBC_JZ ||
  4531. c == asBC_JNZ ||
  4532. c == asBC_JLowZ ||
  4533. c == asBC_JLowNZ ||
  4534. c == asBC_JS ||
  4535. c == asBC_JNS ||
  4536. c == asBC_JP ||
  4537. c == asBC_JNP ) // The JMPP instruction doesn't need modification
  4538. {
  4539. // Get the DWORD offset from arg
  4540. int offset = *(int*)(tmpBC+1);
  4541. // Determine instruction number for next instruction and destination
  4542. int bcSeqNum = bytecodeNbrByPos[asUINT(bc - startBC)] + 1;
  4543. asDWORD *targetBC = bc + 2 + offset;
  4544. int targetBcSeqNum = bytecodeNbrByPos[asUINT(targetBC - startBC)];
  4545. // Set the offset in number of instructions
  4546. *(int*)(tmpBC+1) = targetBcSeqNum - bcSeqNum;
  4547. }
  4548. else if( c == asBC_GETOBJ || // W_ARG
  4549. c == asBC_GETOBJREF ||
  4550. c == asBC_GETREF ||
  4551. c == asBC_ChkNullS )
  4552. {
  4553. // Adjust the offset according to the function call that comes after
  4554. asBC_WORDARG0(tmpBC) = (asWORD)AdjustGetOffset(asBC_WORDARG0(tmpBC), func, asDWORD(bc - startBC));
  4555. }
  4556. else if( c == asBC_AllocMem )
  4557. {
  4558. // It's not necessary to store the size of the list buffer, as it will be recalculated in the reader
  4559. asBC_DWORDARG(tmpBC) = 0;
  4560. // Determine the type of the list pattern from the variable
  4561. short var = asBC_WORDARG0(tmpBC);
  4562. asCObjectType *ot = CastToObjectType(func->GetTypeInfoOfLocalVar(var));
  4563. // Create this helper object to adjust the offset of the elements accessed in the buffer
  4564. listAdjusters.PushLast(asNEW(SListAdjuster)(ot));
  4565. }
  4566. else if( c == asBC_FREE ) // wW_PTR_ARG
  4567. {
  4568. // Translate object type pointers into indices
  4569. asCObjectType *ot = *(asCObjectType**)(tmpBC+1);
  4570. *(asPWORD*)(tmpBC+1) = FindTypeInfoIdx(ot);
  4571. // Pop and destroy the list adjuster helper that was created with asBC_AllocMem
  4572. if( ot && (ot->flags & asOBJ_LIST_PATTERN) )
  4573. {
  4574. SListAdjuster *list = listAdjusters.PopLast();
  4575. asDELETE(list, SListAdjuster);
  4576. }
  4577. }
  4578. else if( c == asBC_SetListSize )
  4579. {
  4580. // Adjust the offset in the initialization list
  4581. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  4582. tmpBC[1] = listAdj->AdjustOffset(tmpBC[1], listAdj->patternType);
  4583. // Tell the adjuster how many repeated values there are
  4584. listAdj->SetRepeatCount(tmpBC[2]);
  4585. }
  4586. else if( c == asBC_PshListElmnt ) // W_DW_ARG
  4587. {
  4588. // Adjust the offset in the initialization list
  4589. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  4590. tmpBC[1] = listAdj->AdjustOffset(tmpBC[1], listAdj->patternType);
  4591. }
  4592. else if( c == asBC_SetListType )
  4593. {
  4594. // Adjust the offset in the initialization list
  4595. SListAdjuster *listAdj = listAdjusters[listAdjusters.GetLength()-1];
  4596. tmpBC[1] = listAdj->AdjustOffset(tmpBC[1], listAdj->patternType);
  4597. // Inform the adjuster of the type id of the next element
  4598. listAdj->SetNextType(tmpBC[2]);
  4599. // Translate the type id
  4600. tmpBC[2] = FindTypeIdIdx(tmpBC[2]);
  4601. }
  4602. // Adjust the variable offsets
  4603. switch( asBCInfo[c].type )
  4604. {
  4605. case asBCTYPE_wW_ARG:
  4606. case asBCTYPE_rW_DW_ARG:
  4607. case asBCTYPE_wW_QW_ARG:
  4608. case asBCTYPE_rW_ARG:
  4609. case asBCTYPE_wW_DW_ARG:
  4610. case asBCTYPE_wW_W_ARG:
  4611. case asBCTYPE_rW_QW_ARG:
  4612. case asBCTYPE_rW_W_DW_ARG:
  4613. case asBCTYPE_rW_DW_DW_ARG:
  4614. {
  4615. asBC_SWORDARG0(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG0(tmpBC));
  4616. }
  4617. break;
  4618. case asBCTYPE_wW_rW_ARG:
  4619. case asBCTYPE_wW_rW_DW_ARG:
  4620. case asBCTYPE_rW_rW_ARG:
  4621. {
  4622. asBC_SWORDARG0(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG0(tmpBC));
  4623. asBC_SWORDARG1(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG1(tmpBC));
  4624. }
  4625. break;
  4626. case asBCTYPE_wW_rW_rW_ARG:
  4627. {
  4628. asBC_SWORDARG0(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG0(tmpBC));
  4629. asBC_SWORDARG1(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG1(tmpBC));
  4630. asBC_SWORDARG2(tmpBC) = (short)AdjustStackPosition(asBC_SWORDARG2(tmpBC));
  4631. }
  4632. break;
  4633. default:
  4634. // The other types don't treat variables so won't be modified
  4635. break;
  4636. }
  4637. // TODO: bytecode: Must make sure that floats and doubles are always stored the same way regardless of platform.
  4638. // Some platforms may not use the IEEE 754 standard, in which case it is necessary to encode the values
  4639. // Now store the instruction in the smallest possible way
  4640. switch( asBCInfo[c].type )
  4641. {
  4642. case asBCTYPE_NO_ARG:
  4643. {
  4644. // Just write 1 byte
  4645. asBYTE b = (asBYTE)c;
  4646. WriteData(&b, 1);
  4647. }
  4648. break;
  4649. case asBCTYPE_W_ARG:
  4650. case asBCTYPE_wW_ARG:
  4651. case asBCTYPE_rW_ARG:
  4652. {
  4653. // Write the instruction code
  4654. asBYTE b = (asBYTE)c;
  4655. WriteData(&b, 1);
  4656. // Write the argument
  4657. short w = *(((short*)tmpBC)+1);
  4658. WriteEncodedInt64(w);
  4659. }
  4660. break;
  4661. case asBCTYPE_rW_DW_ARG:
  4662. case asBCTYPE_wW_DW_ARG:
  4663. case asBCTYPE_W_DW_ARG:
  4664. {
  4665. // Write the instruction code
  4666. asBYTE b = (asBYTE)c;
  4667. WriteData(&b, 1);
  4668. // Write the word argument
  4669. short w = *(((short*)tmpBC)+1);
  4670. WriteEncodedInt64(w);
  4671. // Write the dword argument
  4672. WriteEncodedInt64((int)tmpBC[1]);
  4673. }
  4674. break;
  4675. case asBCTYPE_DW_ARG:
  4676. {
  4677. // Write the instruction code
  4678. asBYTE b = (asBYTE)c;
  4679. WriteData(&b, 1);
  4680. // Write the argument
  4681. WriteEncodedInt64((int)tmpBC[1]);
  4682. }
  4683. break;
  4684. case asBCTYPE_DW_DW_ARG:
  4685. {
  4686. // Write the instruction code
  4687. asBYTE b = (asBYTE)c;
  4688. WriteData(&b, 1);
  4689. // Write the dword argument
  4690. WriteEncodedInt64((int)tmpBC[1]);
  4691. // Write the dword argument
  4692. WriteEncodedInt64((int)tmpBC[2]);
  4693. }
  4694. break;
  4695. case asBCTYPE_wW_rW_rW_ARG:
  4696. {
  4697. // Write the instruction code
  4698. asBYTE b = (asBYTE)c;
  4699. WriteData(&b, 1);
  4700. // Write the first argument
  4701. short w = *(((short*)tmpBC)+1);
  4702. WriteEncodedInt64(w);
  4703. // Write the second argument
  4704. w = *(((short*)tmpBC)+2);
  4705. WriteEncodedInt64(w);
  4706. // Write the third argument
  4707. w = *(((short*)tmpBC)+3);
  4708. WriteEncodedInt64(w);
  4709. }
  4710. break;
  4711. case asBCTYPE_wW_rW_ARG:
  4712. case asBCTYPE_rW_rW_ARG:
  4713. case asBCTYPE_wW_W_ARG:
  4714. {
  4715. // Write the instruction code
  4716. asBYTE b = (asBYTE)c;
  4717. WriteData(&b, 1);
  4718. // Write the first argument
  4719. short w = *(((short*)tmpBC)+1);
  4720. WriteEncodedInt64(w);
  4721. // Write the second argument
  4722. w = *(((short*)tmpBC)+2);
  4723. WriteEncodedInt64(w);
  4724. }
  4725. break;
  4726. case asBCTYPE_wW_rW_DW_ARG:
  4727. case asBCTYPE_rW_W_DW_ARG:
  4728. {
  4729. // Write the instruction code
  4730. asBYTE b = (asBYTE)c;
  4731. WriteData(&b, 1);
  4732. // Write the first argument
  4733. short w = *(((short*)tmpBC)+1);
  4734. WriteEncodedInt64(w);
  4735. // Write the second argument
  4736. w = *(((short*)tmpBC)+2);
  4737. WriteEncodedInt64(w);
  4738. // Write the third argument
  4739. int dw = tmpBC[2];
  4740. WriteEncodedInt64(dw);
  4741. }
  4742. break;
  4743. case asBCTYPE_QW_ARG:
  4744. {
  4745. // Write the instruction code
  4746. asBYTE b = (asBYTE)c;
  4747. WriteData(&b, 1);
  4748. // Write the argument
  4749. asQWORD qw = *(asQWORD*)&tmpBC[1];
  4750. WriteEncodedInt64(qw);
  4751. }
  4752. break;
  4753. case asBCTYPE_QW_DW_ARG:
  4754. {
  4755. // Write the instruction code
  4756. asBYTE b = (asBYTE)c;
  4757. WriteData(&b, 1);
  4758. // Write the argument
  4759. asQWORD qw = *(asQWORD*)&tmpBC[1];
  4760. WriteEncodedInt64(qw);
  4761. // Write the second argument
  4762. int dw = tmpBC[3];
  4763. WriteEncodedInt64(dw);
  4764. }
  4765. break;
  4766. case asBCTYPE_rW_QW_ARG:
  4767. case asBCTYPE_wW_QW_ARG:
  4768. {
  4769. // Write the instruction code
  4770. asBYTE b = (asBYTE)c;
  4771. WriteData(&b, 1);
  4772. // Write the first argument
  4773. short w = *(((short*)tmpBC)+1);
  4774. WriteEncodedInt64(w);
  4775. // Write the argument
  4776. asQWORD qw = *(asQWORD*)&tmpBC[1];
  4777. WriteEncodedInt64(qw);
  4778. }
  4779. break;
  4780. case asBCTYPE_rW_DW_DW_ARG:
  4781. {
  4782. // Write the instruction code
  4783. asBYTE b = (asBYTE)c;
  4784. WriteData(&b, 1);
  4785. // Write the short argument
  4786. short w = *(((short*)tmpBC)+1);
  4787. WriteEncodedInt64(w);
  4788. // Write the dword argument
  4789. WriteEncodedInt64((int)tmpBC[1]);
  4790. // Write the dword argument
  4791. WriteEncodedInt64((int)tmpBC[2]);
  4792. }
  4793. break;
  4794. default:
  4795. {
  4796. // This should never happen
  4797. asASSERT(false);
  4798. // Store the bc as is
  4799. for( int n = 0; n < asBCTypeSize[asBCInfo[c].type]; n++ )
  4800. WriteData(&tmpBC[n], 4);
  4801. }
  4802. }
  4803. // Move to the next instruction
  4804. bc += asBCTypeSize[asBCInfo[c].type];
  4805. length -= asBCTypeSize[asBCInfo[c].type];
  4806. }
  4807. }
  4808. asCWriter::SListAdjuster::SListAdjuster(asCObjectType *ot) : patternType(ot), repeatCount(0), entries(0), lastOffset(-1), nextOffset(0), nextTypeId(-1)
  4809. {
  4810. asASSERT( ot && (ot->flags & asOBJ_LIST_PATTERN) );
  4811. // Find the first expected value in the list
  4812. asSListPatternNode *node = ot->engine->scriptFunctions[patternType->templateSubTypes[0].GetBehaviour()->listFactory]->listPattern;
  4813. asASSERT( node && node->type == asLPT_START );
  4814. patternNode = node->next;
  4815. }
  4816. int asCWriter::SListAdjuster::AdjustOffset(int offset, asCObjectType *listPatternType)
  4817. {
  4818. // TODO: cleanup: The listPatternType parameter is not needed
  4819. asASSERT( patternType == listPatternType );
  4820. UNUSED_VAR(listPatternType);
  4821. asASSERT( offset >= lastOffset );
  4822. // If it is the same offset being accessed again, just return the same adjusted value
  4823. if( offset == lastOffset )
  4824. return entries-1;
  4825. asASSERT( offset >= nextOffset );
  4826. // Update last offset for next call
  4827. lastOffset = offset;
  4828. // What is being expected at this position?
  4829. if( patternNode->type == asLPT_REPEAT || patternNode->type == asLPT_REPEAT_SAME )
  4830. {
  4831. // Don't move the patternNode yet because the caller must make a call to SetRepeatCount too
  4832. nextOffset = offset + 4;
  4833. return entries++;
  4834. }
  4835. else if( patternNode->type == asLPT_TYPE )
  4836. {
  4837. const asCDataType &dt = reinterpret_cast<asSListPatternDataTypeNode*>(patternNode)->dataType;
  4838. if( dt.GetTokenType() == ttQuestion )
  4839. {
  4840. // The bytecode need to inform the type that will
  4841. // come next and then adjust that position too before
  4842. // we can move to the next node
  4843. if( nextTypeId != -1 )
  4844. {
  4845. nextOffset = offset + 4;
  4846. if( repeatCount > 0 )
  4847. repeatCount--;
  4848. // Only move the patternNode if we're not expecting any more repeated entries
  4849. if( repeatCount == 0 )
  4850. patternNode = patternNode->next;
  4851. nextTypeId = -1;
  4852. }
  4853. }
  4854. else
  4855. {
  4856. if( repeatCount > 0 )
  4857. {
  4858. // Was any value skipped?
  4859. asUINT size;
  4860. if( dt.IsObjectHandle() || (dt.GetTypeInfo() && (dt.GetTypeInfo()->flags & asOBJ_REF)) )
  4861. size = AS_PTR_SIZE*4;
  4862. else
  4863. size = dt.GetSizeInMemoryBytes();
  4864. int count = 0;
  4865. while( nextOffset <= offset )
  4866. {
  4867. count++;
  4868. nextOffset += size;
  4869. // Align the offset on 4 byte boundaries
  4870. if( size >= 4 && (nextOffset & 0x3) )
  4871. nextOffset += 4 - (nextOffset & 0x3);
  4872. }
  4873. if( --count > 0 )
  4874. {
  4875. // Skip these values
  4876. repeatCount -= count;
  4877. entries += count;
  4878. }
  4879. nextOffset = offset + size;
  4880. repeatCount--;
  4881. }
  4882. // Only move the patternNode if we're not expecting any more repeated entries
  4883. if( repeatCount == 0 )
  4884. patternNode = patternNode->next;
  4885. }
  4886. return entries++;
  4887. }
  4888. else if( patternNode->type == asLPT_START )
  4889. {
  4890. if( repeatCount > 0 )
  4891. repeatCount--;
  4892. SInfo info = {repeatCount, patternNode};
  4893. stack.PushLast(info);
  4894. repeatCount = 0;
  4895. patternNode = patternNode->next;
  4896. lastOffset--;
  4897. return AdjustOffset(offset, listPatternType);
  4898. }
  4899. else if( patternNode->type == asLPT_END )
  4900. {
  4901. SInfo info = stack.PopLast();
  4902. repeatCount = info.repeatCount;
  4903. if( repeatCount )
  4904. patternNode = info.startNode;
  4905. else
  4906. patternNode = patternNode->next;
  4907. lastOffset--;
  4908. return AdjustOffset(offset, listPatternType);
  4909. }
  4910. else
  4911. {
  4912. // Something is wrong with the pattern list declaration
  4913. asASSERT( false );
  4914. }
  4915. return 0;
  4916. }
  4917. void asCWriter::SListAdjuster::SetRepeatCount(asUINT rc)
  4918. {
  4919. // Make sure the list is expecting a repeat at this location
  4920. asASSERT( patternNode->type == asLPT_REPEAT || patternNode->type == asLPT_REPEAT_SAME );
  4921. // Now move to the next patternNode
  4922. patternNode = patternNode->next;
  4923. repeatCount = rc;
  4924. }
  4925. void asCWriter::SListAdjuster::SetNextType(int typeId)
  4926. {
  4927. // Make sure the list is expecting a type at this location
  4928. asASSERT( patternNode->type == asLPT_TYPE &&
  4929. reinterpret_cast<asSListPatternDataTypeNode*>(patternNode)->dataType.GetTokenType() == ttQuestion );
  4930. // Inform the type id for the next adjustment
  4931. nextTypeId = typeId;
  4932. }
  4933. void asCWriter::WriteUsedTypeIds()
  4934. {
  4935. TimeIt("asCWriter::WriteUsedTypeIds");
  4936. asUINT count = (asUINT)usedTypeIds.GetLength();
  4937. WriteEncodedInt64(count);
  4938. for( asUINT n = 0; n < count; n++ )
  4939. {
  4940. asCDataType dt = engine->GetDataTypeFromTypeId(usedTypeIds[n]);
  4941. WriteDataType(&dt);
  4942. }
  4943. }
  4944. int asCWriter::FindGlobalPropPtrIndex(void *ptr)
  4945. {
  4946. int i = usedGlobalProperties.IndexOf(ptr);
  4947. if( i >= 0 ) return i;
  4948. usedGlobalProperties.PushLast(ptr);
  4949. return (int)usedGlobalProperties.GetLength()-1;
  4950. }
  4951. void asCWriter::WriteUsedGlobalProps()
  4952. {
  4953. TimeIt("asCWriter::WriteUsedGlobalProps");
  4954. int c = (int)usedGlobalProperties.GetLength();
  4955. WriteEncodedInt64(c);
  4956. for( int n = 0; n < c; n++ )
  4957. {
  4958. asPWORD *p = (asPWORD*)usedGlobalProperties[n];
  4959. // Find the property descriptor from the address
  4960. asCGlobalProperty *prop = 0;
  4961. asSMapNode<void*, asCGlobalProperty*> *cursor;
  4962. if( engine->varAddressMap.MoveTo(&cursor, p) )
  4963. {
  4964. prop = engine->varAddressMap.GetValue(cursor);
  4965. }
  4966. asASSERT(prop);
  4967. // Store the name and type of the property so we can find it again on loading
  4968. WriteString(&prop->name);
  4969. WriteString(&prop->nameSpace->name);
  4970. WriteDataType(&prop->type);
  4971. // Also store whether the property is a module property or a registered property
  4972. char moduleProp = 0;
  4973. if( prop->realAddress == 0 )
  4974. moduleProp = 1;
  4975. WriteData(&moduleProp, 1);
  4976. }
  4977. }
  4978. void asCWriter::WriteUsedObjectProps()
  4979. {
  4980. TimeIt("asCWriter::WriteUsedObjectProps");
  4981. int c = (int)usedObjectProperties.GetLength();
  4982. WriteEncodedInt64(c);
  4983. for( asUINT n = 0; n < usedObjectProperties.GetLength(); n++ )
  4984. {
  4985. WriteTypeInfo(usedObjectProperties[n].objType);
  4986. WriteString(&usedObjectProperties[n].prop->name);
  4987. }
  4988. }
  4989. int asCWriter::FindObjectPropIndex(short offset, int typeId, asDWORD *bc)
  4990. {
  4991. // If the last property was a composite property, then just return 0, because it won't be translated
  4992. static bool lastWasComposite = false;
  4993. if (lastWasComposite)
  4994. {
  4995. lastWasComposite = false;
  4996. return 0;
  4997. }
  4998. asCObjectType *objType = engine->GetObjectTypeFromTypeId(typeId);
  4999. asCObjectProperty *objProp = 0;
  5000. // Look for composite properties first
  5001. for (asUINT n = 0; objProp == 0 && n < objType->properties.GetLength(); n++)
  5002. {
  5003. // TODO: Composite: Perhaps it would be better to add metadata to the bytecode instruction to give the exact property.
  5004. // That would also allow me to remove the typeId from the bytecode instruction itself
  5005. // Or perhaps a new bytecode instruction all together for accessing composite properties
  5006. // One that would do both offsets and indirection in a single go.
  5007. // TODO: Composite: Need to be able to handle instructions replaced in bytecode optimizations too
  5008. if (objType->properties[n]->compositeOffset == offset)
  5009. {
  5010. // This is a potential composite property. Need to check the following instructions to be sure
  5011. objProp = objType->properties[n];
  5012. asDWORD *bcTemp = bc;
  5013. bcTemp += asBCTypeSize[asBCInfo[*(asBYTE*)bcTemp].type];
  5014. if (objProp->isCompositeIndirect)
  5015. {
  5016. // The next instruction would be a asBC_RDSPtr
  5017. if ((*(asBYTE*)bcTemp) != asBC_RDSPtr)
  5018. {
  5019. objProp = 0;
  5020. continue;
  5021. }
  5022. bcTemp += asBCTypeSize[asBCInfo[*(asBYTE*)bcTemp].type];
  5023. }
  5024. // The next instruction would be asBC_ADDSi
  5025. if ((*(asBYTE*)bcTemp) != asBC_ADDSi)
  5026. {
  5027. objProp = 0;
  5028. continue;
  5029. }
  5030. // Make sure the offset is the expected one
  5031. if (*(((short*)bcTemp) + 1) != objProp->byteOffset)
  5032. {
  5033. objProp = 0;
  5034. continue;
  5035. }
  5036. }
  5037. }
  5038. // If none of the composite properties matched, then look for ordinary property
  5039. for (asUINT n = 0; objProp == 0 && n < objType->properties.GetLength(); n++)
  5040. {
  5041. if (objType->properties[n]->byteOffset == offset && !(objType->properties[n]->compositeOffset || objType->properties[n]->isCompositeIndirect))
  5042. objProp = objType->properties[n];
  5043. }
  5044. asASSERT(objProp);
  5045. // Remember if this is a composite property as the next call will then be for the same property
  5046. if (objProp->compositeOffset || objProp->isCompositeIndirect)
  5047. lastWasComposite = true;
  5048. // Now check if the same property has already been accessed
  5049. for( asUINT n = 0; n < usedObjectProperties.GetLength(); n++ )
  5050. {
  5051. if( usedObjectProperties[n].objType == objType &&
  5052. usedObjectProperties[n].prop == objProp )
  5053. return n;
  5054. }
  5055. // Insert the new property
  5056. SObjProp prop = {objType, objProp};
  5057. usedObjectProperties.PushLast(prop);
  5058. return (int)usedObjectProperties.GetLength() - 1;
  5059. }
  5060. int asCWriter::FindFunctionIndex(asCScriptFunction *func)
  5061. {
  5062. for( asUINT n = 0; n < usedFunctions.GetLength(); n++ )
  5063. {
  5064. if( usedFunctions[n] == func )
  5065. return n;
  5066. }
  5067. usedFunctions.PushLast(func);
  5068. return (int)usedFunctions.GetLength() - 1;
  5069. }
  5070. int asCWriter::FindTypeIdIdx(int typeId)
  5071. {
  5072. asUINT n;
  5073. for( n = 0; n < usedTypeIds.GetLength(); n++ )
  5074. {
  5075. if( usedTypeIds[n] == typeId )
  5076. return n;
  5077. }
  5078. usedTypeIds.PushLast(typeId);
  5079. return (int)usedTypeIds.GetLength() - 1;
  5080. }
  5081. int asCWriter::FindTypeInfoIdx(asCTypeInfo *obj)
  5082. {
  5083. asUINT n;
  5084. for( n = 0; n < usedTypes.GetLength(); n++ )
  5085. {
  5086. if( usedTypes[n] == obj )
  5087. return n;
  5088. }
  5089. usedTypes.PushLast(obj);
  5090. return (int)usedTypes.GetLength() - 1;
  5091. }
  5092. #endif // AS_NO_COMPILER
  5093. END_AS_NAMESPACE