as_restore.cpp 153 KB

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