ogwasm.pas 190 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919
  1. {
  2. Copyright (c) 2021 by Nikolay Nikolov
  3. Contains the WebAssembly binary module format reader and writer
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit ogwasm;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. { common }
  22. cclasses,globtype,
  23. { target }
  24. systems,cpubase,
  25. { assembler }
  26. aasmbase,assemble,aasmcpu,
  27. { WebAssembly module format definitions }
  28. wasmbase,
  29. { output }
  30. ogbase,
  31. owbase;
  32. type
  33. TWasmObjSymbolExtraData = class;
  34. TGlobalInitializer = record
  35. case typ:TWasmBasicType of
  36. wbt_i32: (init_i32: Int32);
  37. wbt_i64: (init_i64: Int64);
  38. wbt_f32: (init_f32: Single);
  39. wbt_f64: (init_f64: Double);
  40. end;
  41. { TWasmObjSymbolLinkingData }
  42. TWasmObjSymbolLinkingData = class
  43. public
  44. ImportModule: string;
  45. ImportName: string;
  46. FuncType: TWasmFuncType;
  47. ExeFunctionIndex: Integer;
  48. ExeIndirectFunctionTableIndex: Integer;
  49. ExeTypeIndex: Integer;
  50. GlobalType: TWasmBasicType;
  51. GlobalIsMutable: Boolean;
  52. GlobalInitializer: TGlobalInitializer;
  53. IsExported: Boolean;
  54. ExportName: ansistring;
  55. constructor Create;
  56. destructor Destroy;override;
  57. end;
  58. { TWasmObjSymbol }
  59. TWasmObjSymbol = class(TObjSymbol)
  60. FuncIndex: Integer;
  61. SymbolIndex: Integer;
  62. GlobalIndex: Integer;
  63. TagIndex: Integer;
  64. AliasOf: string;
  65. ExtraData: TWasmObjSymbolExtraData;
  66. LinkingData: TWasmObjSymbolLinkingData;
  67. constructor create(AList:TFPHashObjectList;const AName:string);override;
  68. destructor Destroy;override;
  69. function IsAlias: Boolean;
  70. end;
  71. { TWasmObjRelocation }
  72. TWasmObjRelocation = class(TObjRelocation)
  73. public
  74. TypeIndex: Integer;
  75. Addend: LongInt;
  76. { used during linking }
  77. FuncType: TWasmFuncType;
  78. ExeTypeIndex: Integer;
  79. constructor CreateTypeIndex(ADataOffset:TObjSectionOfs; ATypeIndex: Integer);
  80. constructor CreateFuncType(ADataOffset:TObjSectionOfs; AFuncType: TWasmFuncType);
  81. destructor Destroy;override;
  82. end;
  83. { TWasmObjSymbolExtraData }
  84. TWasmObjSymbolExtraData = class(TFPHashObject)
  85. TypeIdx: Integer;
  86. ExceptionTagTypeIdx: Integer;
  87. ImportModule: string;
  88. ImportName: string;
  89. ExportName: string;
  90. GlobalType: TWasmBasicType;
  91. GlobalIsImmutable: Boolean;
  92. Locals: array of TWasmBasicType;
  93. constructor Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  94. procedure AddLocal(bastyp: TWasmBasicType);
  95. end;
  96. { TWasmObjSection }
  97. TWasmObjSection = class(TObjSection)
  98. public
  99. SegIdx: Integer;
  100. SegSymIdx: Integer;
  101. SegOfs: qword;
  102. FileSectionOfs: qword;
  103. MainFuncSymbol: TWasmObjSymbol;
  104. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);override;
  105. function IsCode: Boolean;
  106. function IsData: Boolean;
  107. function IsDebug: Boolean;
  108. end;
  109. { TWasmFuncTypeTable }
  110. TWasmFuncTypeTable = class
  111. private
  112. FFuncTypes: array of TWasmFuncType;
  113. function GetCount: Integer;
  114. function GetItem(Index: Integer): TWasmFuncType;
  115. public
  116. destructor Destroy; override;
  117. function AddOrGetFuncType(wft: TWasmFuncType): integer;
  118. procedure WriteTo(d: tdynamicarray);
  119. property Count: Integer read GetCount;
  120. property Items[Index: Integer]: TWasmFuncType read GetItem; default;
  121. end;
  122. { TWasmObjData }
  123. TWasmObjData = class(TObjData)
  124. private
  125. FFuncTypes: TWasmFuncTypeTable;
  126. FObjSymbolsExtraDataList: TFPHashObjectList;
  127. FLastFuncName: string;
  128. function is_smart_section(atype:TAsmSectiontype):boolean;
  129. function sectionname_gas(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  130. public
  131. constructor create(const n:string);override;
  132. destructor destroy; override;
  133. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  134. procedure writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  135. function AddOrCreateObjSymbolExtraData(const symname:TSymStr): TWasmObjSymbolExtraData;
  136. function globalref(asmsym:TAsmSymbol):TObjSymbol;
  137. function ExceptionTagRef(asmsym:TAsmSymbol):TObjSymbol;
  138. procedure DeclareGlobalType(gt: tai_globaltype);
  139. procedure DeclareFuncType(ft: tai_functype);
  140. procedure DeclareTagType(tt: tai_tagtype);
  141. procedure DeclareExportName(en: tai_export_name);
  142. procedure DeclareImportModule(aim: tai_import_module);
  143. procedure DeclareImportName(ain: tai_import_name);
  144. procedure DeclareLocal(al: tai_local);
  145. procedure symbolpairdefine(akind: TSymbolPairKind;const asym, avalue: string);override;
  146. property FuncTypes: TWasmFuncTypeTable read FFuncTypes;
  147. end;
  148. { TWasmObjOutput }
  149. TWasmObjOutput = class(tObjOutput)
  150. private
  151. FData: TWasmObjData;
  152. FWasmRelocationCodeTable: tdynamicarray;
  153. FWasmRelocationCodeTableEntriesCount: Integer;
  154. FWasmRelocationDataTable: tdynamicarray;
  155. FWasmRelocationDataTableEntriesCount: Integer;
  156. FWasmRelocationDebugFrameTable: tdynamicarray;
  157. FWasmRelocationDebugFrameTableEntriesCount: Integer;
  158. FWasmRelocationDebugInfoTable: tdynamicarray;
  159. FWasmRelocationDebugInfoTableEntriesCount: Integer;
  160. FWasmRelocationDebugLineTable: tdynamicarray;
  161. FWasmRelocationDebugLineTableEntriesCount: Integer;
  162. FWasmRelocationDebugAbbrevTable: tdynamicarray;
  163. FWasmRelocationDebugAbbrevTableEntriesCount: Integer;
  164. FWasmRelocationDebugArangesTable: tdynamicarray;
  165. FWasmRelocationDebugArangesTableEntriesCount: Integer;
  166. FWasmRelocationDebugRangesTable: tdynamicarray;
  167. FWasmRelocationDebugRangesTableEntriesCount: Integer;
  168. FWasmRelocationDebugStrTable: tdynamicarray;
  169. FWasmRelocationDebugStrTableEntriesCount: Integer;
  170. FWasmSymbolTable: tdynamicarray;
  171. FWasmSymbolTableEntriesCount: Integer;
  172. FWasmSections: array [TWasmSectionID] of tdynamicarray;
  173. FWasmCustomSections: array [TWasmCustomSectionType] of tdynamicarray;
  174. FWasmLinkingSubsections: array [low(TWasmLinkingSubsectionType)..high(TWasmLinkingSubsectionType)] of tdynamicarray;
  175. procedure WriteWasmSection(wsid: TWasmSectionID);
  176. procedure WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  177. function IsExternalFunction(sym: TObjSymbol): Boolean;
  178. function IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  179. procedure WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  180. procedure WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  181. procedure WriteSymbolTable;
  182. procedure WriteRelocationCodeTable(CodeSectionIndex: Integer);
  183. procedure WriteRelocationDataTable(DataSectionIndex: Integer);
  184. procedure MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
  185. procedure WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  186. procedure DoRelocations;
  187. procedure WriteRelocations;
  188. function FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
  189. protected
  190. function writeData(Data:TObjData):boolean;override;
  191. public
  192. constructor create(AWriter:TObjectWriter);override;
  193. destructor destroy;override;
  194. end;
  195. { TWasmObjInput }
  196. TWasmObjInput = class(TObjInput)
  197. private
  198. FFuncTypes: array of TWasmFuncType;
  199. public
  200. constructor create;override;
  201. destructor Destroy;override;
  202. class function CanReadObjData(AReader:TObjectreader):boolean;override;
  203. function ReadObjData(AReader:TObjectreader;out ObjData:TObjData):boolean;override;
  204. end;
  205. { TWasmExeOutput }
  206. TWasmExeOutput = class(TExeOutput)
  207. private
  208. FImports: TFPHashObjectList;
  209. FFuncTypes: TWasmFuncTypeTable;
  210. FFunctionImports: array of record
  211. ModName: ansistring;
  212. Name: ansistring;
  213. TypeIdx: uint32;
  214. end;
  215. FIndirectFunctionTable: array of record
  216. FuncIdx: Integer;
  217. end;
  218. FWasmSections: array [TWasmSectionID] of tdynamicarray;
  219. FStackPointerSym: TWasmObjSymbol;
  220. procedure WriteWasmSection(wsid: TWasmSectionID);
  221. procedure PrepareImports;
  222. procedure PrepareFunctions;
  223. function AddOrGetIndirectFunctionTableIndex(FuncIdx: Integer): integer;
  224. procedure SetStackPointer;
  225. protected
  226. function writeData:boolean;override;
  227. procedure DoRelocationFixup(objsec:TObjSection);override;
  228. public
  229. constructor create;override;
  230. destructor destroy;override;
  231. procedure GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);override;
  232. procedure AfterUnusedSectionRemoval;override;
  233. procedure MemPos_ExeSection(const aname:string);override;
  234. procedure Load_Symbol(const aname: string);override;
  235. end;
  236. { TWasmAssembler }
  237. TWasmAssembler = class(tinternalassembler)
  238. constructor create(info: pasminfo; smart:boolean);override;
  239. end;
  240. implementation
  241. uses
  242. cutils,verbose,version,globals,ogmap;
  243. const
  244. StackPointerSymStr='__stack_pointer';
  245. procedure WriteUleb5(d: tdynamicarray; v: uint64);
  246. var
  247. b: byte;
  248. i: Integer;
  249. begin
  250. for i:=1 to 5 do
  251. begin
  252. b:=byte(v) and 127;
  253. v:=v shr 7;
  254. if i<>5 then
  255. b:=b or 128;
  256. d.write(b,1);
  257. end;
  258. end;
  259. procedure WriteUleb5(d: tobjsection; v: uint64);
  260. var
  261. b: byte;
  262. i: Integer;
  263. begin
  264. for i:=1 to 5 do
  265. begin
  266. b:=byte(v) and 127;
  267. v:=v shr 7;
  268. if i<>5 then
  269. b:=b or 128;
  270. d.write(b,1);
  271. end;
  272. end;
  273. procedure WriteSleb5(d: tdynamicarray; v: int64);
  274. var
  275. b: byte;
  276. i: Integer;
  277. begin
  278. for i:=1 to 5 do
  279. begin
  280. b:=byte(v) and 127;
  281. v:=SarInt64(v,7);
  282. if i<>5 then
  283. b:=b or 128;
  284. d.write(b,1);
  285. end;
  286. end;
  287. procedure WriteSleb5(d: tobjsection; v: int64);
  288. var
  289. b: byte;
  290. i: Integer;
  291. begin
  292. for i:=1 to 5 do
  293. begin
  294. b:=byte(v) and 127;
  295. v:=SarInt64(v,7);
  296. if i<>5 then
  297. b:=b or 128;
  298. d.write(b,1);
  299. end;
  300. end;
  301. procedure WriteUleb(d: tdynamicarray; v: uint64);
  302. var
  303. b: byte;
  304. begin
  305. repeat
  306. b:=byte(v) and 127;
  307. v:=v shr 7;
  308. if v<>0 then
  309. b:=b or 128;
  310. d.write(b,1);
  311. until v=0;
  312. end;
  313. procedure WriteUleb(w: TObjectWriter; v: uint64);
  314. var
  315. b: byte;
  316. begin
  317. repeat
  318. b:=byte(v) and 127;
  319. v:=v shr 7;
  320. if v<>0 then
  321. b:=b or 128;
  322. w.write(b,1);
  323. until v=0;
  324. end;
  325. procedure WriteSleb(d: tdynamicarray; v: int64);
  326. var
  327. b: byte;
  328. Done: Boolean=false;
  329. begin
  330. repeat
  331. b:=byte(v) and 127;
  332. v:=SarInt64(v,7);
  333. if ((v=0) and ((b and 64)=0)) or ((v=-1) and ((b and 64)<>0)) then
  334. Done:=true
  335. else
  336. b:=b or 128;
  337. d.write(b,1);
  338. until Done;
  339. end;
  340. function UlebEncodingSize(v: uint64): Integer;
  341. var
  342. b: byte;
  343. begin
  344. Result:=0;
  345. repeat
  346. b:=byte(v) and 127;
  347. v:=v shr 7;
  348. if v<>0 then
  349. b:=b or 128;
  350. Inc(Result);
  351. until v=0;
  352. end;
  353. {$ifdef FPC_LITTLE_ENDIAN}
  354. procedure WriteF32LE(d: tdynamicarray; v: Single);
  355. begin
  356. d.write(v,4);
  357. end;
  358. procedure WriteF64LE(d: tdynamicarray; v: Double);
  359. begin
  360. d.write(v,8);
  361. end;
  362. {$else FPC_LITTLE_ENDIAN}
  363. procedure WriteF32LE(d: tdynamicarray; v: Single);
  364. var
  365. tmpI: UInt32;
  366. begin
  367. Move(v,tmpI,4);
  368. tmpI:=SwapEndian(tmpI);
  369. d.write(tmpI,4);
  370. end;
  371. procedure WriteF64LE(d: tdynamicarray; v: Double);
  372. var
  373. tmpI: UInt64;
  374. begin
  375. Move(v,tmpI,8);
  376. tmpI:=SwapEndian(tmpI);
  377. d.write(tmpI,8);
  378. end;
  379. {$endif FPC_LITTLE_ENDIAN}
  380. procedure WriteByte(d: tdynamicarray; b: byte);
  381. begin
  382. d.write(b,1);
  383. end;
  384. procedure WriteName(d: tdynamicarray; const s: string);
  385. begin
  386. WriteUleb(d,Length(s));
  387. d.writestr(s);
  388. end;
  389. procedure WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  390. begin
  391. WriteByte(dest,encode_wasm_basic_type(wbt));
  392. end;
  393. procedure WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  394. var
  395. i: Integer;
  396. begin
  397. WriteUleb(dest,Length(wrt));
  398. for i:=low(wrt) to high(wrt) do
  399. WriteWasmBasicType(dest,wrt[i]);
  400. end;
  401. function ReadUleb(d: tdynamicarray): uint64;
  402. var
  403. b: byte;
  404. shift:integer;
  405. begin
  406. b:=0;
  407. result:=0;
  408. shift:=0;
  409. repeat
  410. d.read(b,1);
  411. result:=result or (uint64(b and 127) shl shift);
  412. inc(shift,7);
  413. until (b and 128)=0;
  414. end;
  415. function ReadSleb(d: tdynamicarray): int64;
  416. var
  417. b: byte;
  418. shift:integer;
  419. begin
  420. b:=0;
  421. result:=0;
  422. shift:=0;
  423. repeat
  424. d.read(b,1);
  425. result:=result or (uint64(b and 127) shl shift);
  426. inc(shift,7);
  427. until (b and 128)=0;
  428. {$ifopt Q+}
  429. {$define overflowon}
  430. {$Q-}
  431. {$endif}
  432. {$ifopt R+}
  433. {$define rangeon}
  434. {$R-}
  435. {$endif}
  436. if (b and 64)<>0 then
  437. result:=result or (high(uint64) shl shift);
  438. end;
  439. {$ifdef overflowon}
  440. {$Q+}
  441. {$undef overflowon}
  442. {$endif}
  443. {$ifdef rangeon}
  444. {$R+}
  445. {$undef rangeon}
  446. {$endif}
  447. procedure AddSleb5(d: tdynamicarray; v: int64);
  448. var
  449. q: Int64;
  450. p: LongWord;
  451. begin
  452. p:=d.Pos;
  453. q:=ReadSleb(d);
  454. q:=q+v;
  455. d.seek(p);
  456. WriteSleb5(d,q);
  457. end;
  458. procedure AddUleb5(d: tdynamicarray; v: int64);
  459. var
  460. q: UInt64;
  461. p: LongWord;
  462. begin
  463. p:=d.Pos;
  464. q:=ReadUleb(d);
  465. q:=q+v;
  466. d.seek(p);
  467. WriteUleb5(d,q);
  468. end;
  469. procedure AddInt32(d: tdynamicarray; v: int32);
  470. var
  471. q: int32;
  472. p: LongWord;
  473. begin
  474. p:=d.Pos;
  475. d.read(q,4);
  476. {$ifdef FPC_BIG_ENDIAN}
  477. q:=SwapEndian(q);
  478. {$endif FPC_BIG_ENDIAN}
  479. q:=q+v;
  480. {$ifdef FPC_BIG_ENDIAN}
  481. q:=SwapEndian(q);
  482. {$endif FPC_BIG_ENDIAN}
  483. d.seek(p);
  484. d.write(q,4);
  485. end;
  486. procedure CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  487. var
  488. buf: array [0..4095] of byte;
  489. bs: Integer;
  490. begin
  491. while size>0 do
  492. begin
  493. if size<SizeOf(buf) then
  494. bs:=Integer(size)
  495. else
  496. bs:=SizeOf(buf);
  497. src.read(buf,bs);
  498. dest.write(buf,bs);
  499. dec(size,bs);
  500. end;
  501. end;
  502. procedure WriteZeros(dest: tdynamicarray; size: QWord);
  503. var
  504. buf : array[0..1023] of byte;
  505. bs: Integer;
  506. begin
  507. fillchar(buf,sizeof(buf),0);
  508. while size>0 do
  509. begin
  510. if size<SizeOf(buf) then
  511. bs:=Integer(size)
  512. else
  513. bs:=SizeOf(buf);
  514. dest.write(buf,bs);
  515. dec(size,bs);
  516. end;
  517. end;
  518. {****************************************************************************
  519. TWasmObjSymbolLinkingData
  520. ****************************************************************************}
  521. constructor TWasmObjSymbolLinkingData.Create;
  522. begin
  523. ExeFunctionIndex:=-1;
  524. ExeIndirectFunctionTableIndex:=-1;
  525. ExeTypeIndex:=-1;
  526. end;
  527. destructor TWasmObjSymbolLinkingData.Destroy;
  528. begin
  529. FuncType.Free;
  530. inherited Destroy;
  531. end;
  532. {****************************************************************************
  533. TWasmObjRelocation
  534. ****************************************************************************}
  535. constructor TWasmObjRelocation.CreateTypeIndex(ADataOffset: TObjSectionOfs; ATypeIndex: Integer);
  536. begin
  537. DataOffset:=ADataOffset;
  538. Symbol:=nil;
  539. OrgSize:=0;
  540. Group:=nil;
  541. ObjSection:=nil;
  542. ftype:=ord(RELOC_TYPE_INDEX_LEB);
  543. TypeIndex:=ATypeIndex;
  544. FuncType:=nil;
  545. ExeTypeIndex:=-1;
  546. end;
  547. constructor TWasmObjRelocation.CreateFuncType(ADataOffset: TObjSectionOfs; AFuncType: TWasmFuncType);
  548. begin
  549. DataOffset:=ADataOffset;
  550. Symbol:=nil;
  551. OrgSize:=0;
  552. Group:=nil;
  553. ObjSection:=nil;
  554. ftype:=ord(RELOC_TYPE_INDEX_LEB);
  555. TypeIndex:=-1;
  556. ExeTypeIndex:=-1;
  557. FuncType:=TWasmFuncType.Create(AFuncType);
  558. end;
  559. destructor TWasmObjRelocation.Destroy;
  560. begin
  561. FuncType.Free;
  562. inherited Destroy;
  563. end;
  564. {****************************************************************************
  565. TWasmObjSymbol
  566. ****************************************************************************}
  567. constructor TWasmObjSymbol.create(AList: TFPHashObjectList; const AName: string);
  568. begin
  569. inherited create(AList,AName);
  570. FuncIndex:=-1;
  571. SymbolIndex:=-1;
  572. GlobalIndex:=-1;
  573. TagIndex:=-1;
  574. AliasOf:='';
  575. ExtraData:=nil;
  576. LinkingData:=TWasmObjSymbolLinkingData.Create;
  577. end;
  578. destructor TWasmObjSymbol.Destroy;
  579. begin
  580. LinkingData.Free;
  581. inherited Destroy;
  582. end;
  583. function TWasmObjSymbol.IsAlias: Boolean;
  584. begin
  585. result:=AliasOf<>'';
  586. end;
  587. {****************************************************************************
  588. TWasmObjSymbolExtraData
  589. ****************************************************************************}
  590. constructor TWasmObjSymbolExtraData.Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  591. begin
  592. inherited Create(HashObjectList,s);
  593. TypeIdx:=-1;
  594. ExceptionTagTypeIdx:=-1;
  595. end;
  596. procedure TWasmObjSymbolExtraData.AddLocal(bastyp: TWasmBasicType);
  597. begin
  598. SetLength(Locals,Length(Locals)+1);
  599. Locals[High(Locals)]:=bastyp;
  600. end;
  601. {****************************************************************************
  602. TWasmObjSection
  603. ****************************************************************************}
  604. constructor TWasmObjSection.create(AList: TFPHashObjectList; const Aname: string; Aalign: longint; Aoptions: TObjSectionOptions);
  605. begin
  606. inherited create(AList, Aname, Aalign, Aoptions);
  607. SegIdx:=-1;
  608. SegSymIdx:=-1;
  609. MainFuncSymbol:=nil;
  610. end;
  611. function TWasmObjSection.IsCode: Boolean;
  612. const
  613. CodePrefix = '.text';
  614. begin
  615. result:=(Length(Name)>=Length(CodePrefix)) and
  616. (Copy(Name,1,Length(CodePrefix))=CodePrefix);
  617. end;
  618. function TWasmObjSection.IsData: Boolean;
  619. begin
  620. result:=not (IsCode or IsDebug);
  621. end;
  622. function TWasmObjSection.IsDebug: Boolean;
  623. const
  624. DebugPrefix = '.debug';
  625. begin
  626. result:=(Length(Name)>=Length(DebugPrefix)) and
  627. (Copy(Name,1,Length(DebugPrefix))=DebugPrefix);
  628. end;
  629. {****************************************************************************
  630. TWasmFuncTypeTable
  631. ****************************************************************************}
  632. function TWasmFuncTypeTable.GetCount: Integer;
  633. begin
  634. Result:=Length(FFuncTypes);
  635. end;
  636. function TWasmFuncTypeTable.GetItem(Index: Integer): TWasmFuncType;
  637. begin
  638. if (Index<Low(FFuncTypes)) or (Index>High(FFuncTypes)) then
  639. internalerror(2023123101);
  640. Result:=FFuncTypes[Index];
  641. end;
  642. destructor TWasmFuncTypeTable.Destroy;
  643. var
  644. i: Integer;
  645. begin
  646. for i:=low(FFuncTypes) to high(FFuncTypes) do
  647. begin
  648. FFuncTypes[i].free;
  649. FFuncTypes[i]:=nil;
  650. end;
  651. end;
  652. function TWasmFuncTypeTable.AddOrGetFuncType(wft: TWasmFuncType): integer;
  653. var
  654. i: Integer;
  655. begin
  656. for i:=low(FFuncTypes) to high(FFuncTypes) do
  657. if wft.Equals(FFuncTypes[i]) then
  658. exit(i);
  659. result:=Length(FFuncTypes);
  660. SetLength(FFuncTypes,result+1);
  661. FFuncTypes[result]:=TWasmFuncType.Create(wft);
  662. end;
  663. procedure TWasmFuncTypeTable.WriteTo(d: tdynamicarray);
  664. var
  665. types_count, i: Integer;
  666. begin
  667. types_count:=Count;
  668. WriteUleb(d,types_count);
  669. for i:=0 to types_count-1 do
  670. with Items[i] do
  671. begin
  672. WriteByte(d,$60);
  673. WriteWasmResultType(d,params);
  674. WriteWasmResultType(d,results);
  675. end;
  676. end;
  677. {****************************************************************************
  678. TWasmObjData
  679. ****************************************************************************}
  680. function TWasmObjData.is_smart_section(atype: TAsmSectiontype): boolean;
  681. begin
  682. { For bss we need to set some flags that are target dependent,
  683. it is easier to disable it for smartlinking. It doesn't take up
  684. filespace }
  685. result:=not(target_info.system in systems_darwin) and
  686. create_smartlink_sections and
  687. (atype<>sec_toc) and
  688. (atype<>sec_user) and
  689. { on embedded systems every byte counts, so smartlink bss too }
  690. ((atype<>sec_bss) or (target_info.system in (systems_embedded+systems_freertos)));
  691. end;
  692. function TWasmObjData.sectionname_gas(atype: TAsmSectiontype;
  693. const aname: string; aorder: TAsmSectionOrder): string;
  694. const
  695. secnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
  696. '.text',
  697. '.data',
  698. { why doesn't .rodata work? (FK) }
  699. { sometimes we have to create a data.rel.ro instead of .rodata, e.g. for }
  700. { vtables (and anything else containing relocations), otherwise those are }
  701. { not relocated properly on e.g. linux/ppc64. g++ generates there for a }
  702. { vtable for a class called Window: }
  703. { .section .data.rel.ro._ZTV6Window,"awG",@progbits,_ZTV6Window,comdat }
  704. { TODO: .data.ro not yet working}
  705. {$if defined(arm) or defined(riscv64) or defined(powerpc)}
  706. '.rodata',
  707. {$else defined(arm) or defined(riscv64) or defined(powerpc)}
  708. '.data',
  709. {$endif defined(arm) or defined(riscv64) or defined(powerpc)}
  710. '.rodata',
  711. '.bss',
  712. '.tbss',
  713. '.pdata',
  714. '', { stubs }
  715. '__DATA,__nl_symbol_ptr',
  716. '__DATA,__la_symbol_ptr',
  717. '__DATA,__mod_init_func',
  718. '__DATA,__mod_term_func',
  719. '.stab',
  720. '.stabstr',
  721. '.idata$2','.idata$4','.idata$5','.idata$6','.idata$7','.edata',
  722. '.eh_frame',
  723. '.debug_frame','.debug_info','.debug_line','.debug_abbrev','.debug_aranges','.debug_ranges',
  724. '.fpc',
  725. '.toc',
  726. '.init',
  727. '.fini',
  728. '.objc_class',
  729. '.objc_meta_class',
  730. '.objc_cat_cls_meth',
  731. '.objc_cat_inst_meth',
  732. '.objc_protocol',
  733. '.objc_string_object',
  734. '.objc_cls_meth',
  735. '.objc_inst_meth',
  736. '.objc_cls_refs',
  737. '.objc_message_refs',
  738. '.objc_symbols',
  739. '.objc_category',
  740. '.objc_class_vars',
  741. '.objc_instance_vars',
  742. '.objc_module_info',
  743. '.objc_class_names',
  744. '.objc_meth_var_types',
  745. '.objc_meth_var_names',
  746. '.objc_selector_strs',
  747. '.objc_protocol_ext',
  748. '.objc_class_ext',
  749. '.objc_property',
  750. '.objc_image_info',
  751. '.objc_cstring_object',
  752. '.objc_sel_fixup',
  753. '__DATA,__objc_data',
  754. '__DATA,__objc_const',
  755. '.objc_superrefs',
  756. '__DATA, __datacoal_nt,coalesced',
  757. '.objc_classlist',
  758. '.objc_nlclasslist',
  759. '.objc_catlist',
  760. '.obcj_nlcatlist',
  761. '.objc_protolist',
  762. '.stack',
  763. '.heap',
  764. '.gcc_except_table',
  765. '.ARM.attributes'
  766. );
  767. var
  768. sep : string[3];
  769. secname : string;
  770. begin
  771. secname:=secnames[atype];
  772. if (atype=sec_fpc) and (Copy(aname,1,3)='res') then
  773. begin
  774. result:=secname+'.'+aname;
  775. exit;
  776. end;
  777. { go32v2 stub only loads .text and .data sections, and allocates space for .bss.
  778. Thus, data which normally goes into .rodata and .rodata_norel sections must
  779. end up in .data section }
  780. if (atype in [sec_rodata,sec_rodata_norel]) and
  781. (target_info.system in [system_i386_go32v2,system_m68k_palmos]) then
  782. secname:='.data';
  783. { Windows correctly handles reallocations in readonly sections }
  784. if (atype=sec_rodata) and
  785. (target_info.system in systems_all_windows+systems_nativent-[system_i8086_win16]) then
  786. secname:='.rodata';
  787. { section type user gives the user full controll on the section name }
  788. if atype=sec_user then
  789. secname:=aname;
  790. if is_smart_section(atype) and (aname<>'') then
  791. begin
  792. case aorder of
  793. secorder_begin :
  794. sep:='.b_';
  795. secorder_end :
  796. sep:='.z_';
  797. else
  798. sep:='.n_';
  799. end;
  800. result:=secname+sep+aname
  801. end
  802. else
  803. result:=secname;
  804. end;
  805. constructor TWasmObjData.create(const n: string);
  806. begin
  807. inherited;
  808. CObjSection:=TWasmObjSection;
  809. CObjSymbol:=TWasmObjSymbol;
  810. FObjSymbolsExtraDataList:=TFPHashObjectList.Create;
  811. FFuncTypes:=TWasmFuncTypeTable.Create;
  812. end;
  813. destructor TWasmObjData.destroy;
  814. var
  815. i: Integer;
  816. begin
  817. FObjSymbolsExtraDataList.Free;
  818. FFuncTypes.Free;
  819. inherited destroy;
  820. end;
  821. function TWasmObjData.sectionname(atype: TAsmSectiontype;
  822. const aname: string; aorder: TAsmSectionOrder): string;
  823. begin
  824. if (atype=sec_fpc) or
  825. ((atype=sec_threadvar) and not (ts_wasm_threads in current_settings.targetswitches)) then
  826. atype:=sec_data;
  827. Result:=sectionname_gas(atype, aname, aorder);
  828. end;
  829. procedure TWasmObjData.writeReloc(Data: TRelocDataInt; len: aword;
  830. p: TObjSymbol; Reloctype: TObjRelocationType);
  831. const
  832. leb_zero: array[0..4] of byte=($80,$80,$80,$80,$00);
  833. var
  834. objreloc: TWasmObjRelocation;
  835. begin
  836. if CurrObjSec=nil then
  837. internalerror(200403072);
  838. { workaround crash, when generating debug info for threadvars, when multithreading is turned off.
  839. todo: ensure the debug info for threadvars is actually correct, once we've got WebAssembly debug info working in general }
  840. if (Reloctype=RELOC_DTPOFF) and not (ts_wasm_threads in current_settings.targetswitches) then
  841. Reloctype:=RELOC_ABSOLUTE;
  842. objreloc:=nil;
  843. case Reloctype of
  844. RELOC_FUNCTION_INDEX_LEB:
  845. begin
  846. if Data<>0 then
  847. internalerror(2021092502);
  848. if len<>5 then
  849. internalerror(2021092503);
  850. if not assigned(p) then
  851. internalerror(2021092504);
  852. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  853. CurrObjSec.ObjRelocations.Add(objreloc);
  854. writebytes(leb_zero,5);
  855. end;
  856. RELOC_MEMORY_ADDR_LEB,
  857. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  858. begin
  859. if (Reloctype=RELOC_MEMORY_ADDR_LEB) and (Data<0) then
  860. internalerror(2021092602);
  861. if len<>5 then
  862. internalerror(2021092503);
  863. if not assigned(p) then
  864. internalerror(2021092504);
  865. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  866. objreloc.Addend:=Data;
  867. CurrObjSec.ObjRelocations.Add(objreloc);
  868. if RelocType=RELOC_MEMORY_ADDR_LEB then
  869. WriteUleb5(CurrObjSec,Data)
  870. else
  871. WriteSleb5(CurrObjSec,Data);
  872. end;
  873. RELOC_ABSOLUTE:
  874. begin
  875. if len<>4 then
  876. internalerror(2021092607);
  877. if not assigned(p) then
  878. internalerror(2021092608);
  879. if (p.objsection<>nil) and TWasmObjSection(p.objsection).IsDebug and
  880. (p.bind<>AB_COMMON) and (p.bind<>AB_EXTERNAL) then
  881. begin
  882. objreloc:=TWasmObjRelocation.CreateSection(CurrObjSec.Size,p.objsection,RELOC_ABSOLUTE);
  883. objreloc.Addend:=Data+p.Address;
  884. CurrObjSec.ObjRelocations.Add(objreloc);
  885. {inc(data,p.address);}
  886. data:=0;
  887. Data:=NtoLE(Data);
  888. writebytes(Data,4);
  889. end
  890. else
  891. begin
  892. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  893. objreloc.Addend:=Data;
  894. CurrObjSec.ObjRelocations.Add(objreloc);
  895. Data:=NtoLE(Data);
  896. writebytes(Data,4);
  897. end;
  898. end;
  899. RELOC_TYPE_INDEX_LEB:
  900. begin
  901. if len<>5 then
  902. internalerror(2021092612);
  903. if assigned(p) then
  904. internalerror(2021092613);
  905. objreloc:=TWasmObjRelocation.CreateTypeIndex(CurrObjSec.Size,Data);
  906. CurrObjSec.ObjRelocations.Add(objreloc);
  907. WriteUleb5(CurrObjSec,Data);
  908. end;
  909. RELOC_GLOBAL_INDEX_LEB:
  910. begin
  911. if len<>5 then
  912. internalerror(2021092701);
  913. if Data<>0 then
  914. internalerror(2021092702);
  915. if not assigned(p) then
  916. internalerror(2021092703);
  917. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  918. CurrObjSec.ObjRelocations.Add(objreloc);
  919. WriteUleb5(CurrObjSec,0);
  920. end;
  921. RELOC_TAG_INDEX_LEB:
  922. begin
  923. if len<>5 then
  924. internalerror(2021092712);
  925. if Data<>0 then
  926. internalerror(2021092713);
  927. if not assigned(p) then
  928. internalerror(2021092714);
  929. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  930. CurrObjSec.ObjRelocations.Add(objreloc);
  931. WriteSleb5(CurrObjSec,0);
  932. end;
  933. else
  934. internalerror(2021092501);
  935. end;
  936. end;
  937. function TWasmObjData.AddOrCreateObjSymbolExtraData(const symname: TSymStr): TWasmObjSymbolExtraData;
  938. begin
  939. result:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(symname));
  940. if not assigned(result) then
  941. result:=TWasmObjSymbolExtraData.Create(FObjSymbolsExtraDataList,symname);
  942. end;
  943. function TWasmObjData.globalref(asmsym: TAsmSymbol): TObjSymbol;
  944. begin
  945. if assigned(asmsym) then
  946. begin
  947. if (asmsym.typ<>AT_WASM_GLOBAL) and (asmsym.typ<>AT_TLS) then
  948. internalerror(2021092706);
  949. result:=symbolref(asmsym);
  950. result.typ:=asmsym.typ;
  951. end
  952. else
  953. result:=nil;
  954. end;
  955. function TWasmObjData.ExceptionTagRef(asmsym: TAsmSymbol): TObjSymbol;
  956. begin
  957. if assigned(asmsym) then
  958. begin
  959. if asmsym.typ<>AT_WASM_EXCEPTION_TAG then
  960. internalerror(2021092707);
  961. result:=symbolref(asmsym);
  962. result.typ:=AT_WASM_EXCEPTION_TAG;
  963. end
  964. else
  965. result:=nil;
  966. end;
  967. procedure TWasmObjData.DeclareGlobalType(gt: tai_globaltype);
  968. var
  969. ObjSymExtraData: TWasmObjSymbolExtraData;
  970. ObjSym: TObjSymbol;
  971. begin
  972. if not gt.is_external then
  973. begin
  974. ObjSym:=symboldefine(gt.sym);
  975. ObjSym.typ:=AT_WASM_GLOBAL;
  976. end;
  977. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(gt.globalname);
  978. ObjSymExtraData.GlobalType:=gt.gtype;
  979. ObjSymExtraData.GlobalIsImmutable:=gt.immutable;
  980. end;
  981. procedure TWasmObjData.DeclareFuncType(ft: tai_functype);
  982. var
  983. i: Integer;
  984. ObjSymExtraData: TWasmObjSymbolExtraData;
  985. begin
  986. FLastFuncName:=ft.funcname;
  987. i:=FFuncTypes.AddOrGetFuncType(ft.functype);
  988. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ft.funcname);
  989. ObjSymExtraData.TypeIdx:=i;
  990. end;
  991. procedure TWasmObjData.DeclareTagType(tt: tai_tagtype);
  992. var
  993. ObjSymExtraData: TWasmObjSymbolExtraData;
  994. ft: TWasmFuncType;
  995. i: Integer;
  996. begin
  997. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(tt.tagname);
  998. ft:=TWasmFuncType.Create([],tt.params);
  999. i:=FFuncTypes.AddOrGetFuncType(ft);
  1000. ft.free;
  1001. ObjSymExtraData.ExceptionTagTypeIdx:=i;
  1002. end;
  1003. procedure TWasmObjData.DeclareExportName(en: tai_export_name);
  1004. var
  1005. ObjSymExtraData: TWasmObjSymbolExtraData;
  1006. begin
  1007. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(en.intname);
  1008. ObjSymExtraData.ExportName:=en.extname;
  1009. end;
  1010. procedure TWasmObjData.DeclareImportModule(aim: tai_import_module);
  1011. var
  1012. ObjSymExtraData: TWasmObjSymbolExtraData;
  1013. begin
  1014. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(aim.symname);
  1015. ObjSymExtraData.ImportModule:=aim.importmodule;
  1016. end;
  1017. procedure TWasmObjData.DeclareImportName(ain: tai_import_name);
  1018. var
  1019. ObjSymExtraData: TWasmObjSymbolExtraData;
  1020. begin
  1021. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ain.symname);
  1022. ObjSymExtraData.ImportName:=ain.importname;
  1023. end;
  1024. procedure TWasmObjData.DeclareLocal(al: tai_local);
  1025. var
  1026. ObjSymExtraData: TWasmObjSymbolExtraData;
  1027. begin
  1028. ObjSymExtraData:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(FLastFuncName));
  1029. ObjSymExtraData.AddLocal(al.bastyp);
  1030. end;
  1031. procedure TWasmObjData.symbolpairdefine(akind: TSymbolPairKind; const asym, avalue: string);
  1032. var
  1033. valsym: TObjSymbol;
  1034. aliassym: TWasmObjSymbol;
  1035. begin
  1036. valsym:=CreateSymbol(avalue);
  1037. aliassym:=TWasmObjSymbol(symboldefine(asym,valsym.bind,valsym.typ));
  1038. aliassym.AliasOf:=valsym.Name;
  1039. end;
  1040. {****************************************************************************
  1041. TWasmObjOutput
  1042. ****************************************************************************}
  1043. procedure TWasmObjOutput.WriteWasmSection(wsid: TWasmSectionID);
  1044. var
  1045. b: byte;
  1046. begin
  1047. b:=ord(wsid);
  1048. Writer.write(b,1);
  1049. WriteUleb(Writer,FWasmSections[wsid].size);
  1050. Writer.writearray(FWasmSections[wsid]);
  1051. end;
  1052. procedure TWasmObjOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  1053. var
  1054. b: byte;
  1055. begin
  1056. b:=0;
  1057. Writer.write(b,1);
  1058. WriteUleb(Writer,FWasmCustomSections[wcst].size);
  1059. Writer.writearray(FWasmCustomSections[wcst]);
  1060. end;
  1061. function TWasmObjOutput.IsExternalFunction(sym: TObjSymbol): Boolean;
  1062. var
  1063. ExtraData: TWasmObjSymbolExtraData;
  1064. begin
  1065. if sym.bind=AB_EXTERNAL then
  1066. begin
  1067. ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
  1068. result:=(ExtraData<>nil) and (ExtraData.TypeIdx<>-1);
  1069. end
  1070. else
  1071. result:=false;
  1072. end;
  1073. function TWasmObjOutput.IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  1074. var
  1075. ExtraData: TWasmObjSymbolExtraData;
  1076. begin
  1077. if (sym.typ=AT_FUNCTION) and not sym.IsAlias then
  1078. begin
  1079. ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
  1080. result:=(ExtraData<>nil) and (ExtraData.ExportName<>'');
  1081. end
  1082. else
  1083. result:=false;
  1084. end;
  1085. procedure TWasmObjOutput.WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  1086. var
  1087. i,
  1088. rle_entries,
  1089. cnt: Integer;
  1090. lasttype: TWasmBasicType;
  1091. begin
  1092. if Length(ed.Locals)=0 then
  1093. begin
  1094. WriteUleb(dest,0);
  1095. exit;
  1096. end;
  1097. rle_entries:=1;
  1098. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  1099. if ed.Locals[i]<>ed.Locals[i-1] then
  1100. inc(rle_entries);
  1101. WriteUleb(dest,rle_entries);
  1102. lasttype:=ed.Locals[Low(ed.Locals)];
  1103. cnt:=1;
  1104. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  1105. if ed.Locals[i]=ed.Locals[i-1] then
  1106. inc(cnt)
  1107. else
  1108. begin
  1109. WriteUleb(dest,cnt);
  1110. WriteWasmBasicType(dest,lasttype);
  1111. lasttype:=ed.Locals[i];
  1112. cnt:=1;
  1113. end;
  1114. WriteUleb(dest,cnt);
  1115. WriteWasmBasicType(dest,lasttype);
  1116. end;
  1117. procedure TWasmObjOutput.WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  1118. var
  1119. encoded_locals: tdynamicarray;
  1120. ObjSymExtraData: TWasmObjSymbolExtraData;
  1121. codelen: LongWord;
  1122. ObjSection: TWasmObjSection;
  1123. codeexprlen: QWord;
  1124. begin
  1125. ObjSymExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1126. ObjSection:=TWasmObjSection(objsym.objsection);
  1127. ObjSection.Data.seek(objsym.address);
  1128. codeexprlen:=objsym.size;
  1129. encoded_locals:=tdynamicarray.Create(64);
  1130. WriteFunctionLocals(encoded_locals,ObjSymExtraData);
  1131. codelen:=encoded_locals.size+codeexprlen+1;
  1132. WriteUleb(dest,codelen);
  1133. encoded_locals.seek(0);
  1134. CopyDynamicArray(encoded_locals,dest,encoded_locals.size);
  1135. ObjSection.FileSectionOfs:=dest.size-objsym.offset;
  1136. CopyDynamicArray(ObjSection.Data,dest,codeexprlen);
  1137. WriteByte(dest,$0B);
  1138. encoded_locals.Free;
  1139. end;
  1140. procedure TWasmObjOutput.WriteSymbolTable;
  1141. begin
  1142. WriteUleb(FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTableEntriesCount);
  1143. FWasmSymbolTable.seek(0);
  1144. CopyDynamicArray(FWasmSymbolTable,FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTable.size);
  1145. end;
  1146. procedure TWasmObjOutput.WriteRelocationCodeTable(CodeSectionIndex: Integer);
  1147. begin
  1148. WriteUleb(FWasmCustomSections[wcstRelocCode],CodeSectionIndex);
  1149. WriteUleb(FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTableEntriesCount);
  1150. FWasmRelocationCodeTable.seek(0);
  1151. CopyDynamicArray(FWasmRelocationCodeTable,FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTable.size);
  1152. end;
  1153. procedure TWasmObjOutput.WriteRelocationDataTable(DataSectionIndex: Integer);
  1154. begin
  1155. WriteUleb(FWasmCustomSections[wcstRelocData],DataSectionIndex);
  1156. WriteUleb(FWasmCustomSections[wcstRelocData],FWasmRelocationDataTableEntriesCount);
  1157. FWasmRelocationDataTable.seek(0);
  1158. CopyDynamicArray(FWasmRelocationDataTable,FWasmCustomSections[wcstRelocData],FWasmRelocationDataTable.size);
  1159. end;
  1160. procedure TWasmObjOutput.MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
  1161. begin
  1162. if EntriesCount>0 then
  1163. begin
  1164. WriteUleb(FWasmCustomSections[cst],SectionIndex);
  1165. WriteUleb(FWasmCustomSections[cst],EntriesCount);
  1166. Table.seek(0);
  1167. CopyDynamicArray(Table,FWasmCustomSections[cst],Table.size);
  1168. WriteWasmCustomSection(cst);
  1169. end;
  1170. end;
  1171. procedure TWasmObjOutput.WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  1172. begin
  1173. if FWasmLinkingSubsections[wlst].size>0 then
  1174. begin
  1175. WriteByte(FWasmCustomSections[wcstLinking],Ord(wlst));
  1176. WriteUleb(FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  1177. FWasmLinkingSubsections[wlst].seek(0);
  1178. CopyDynamicArray(FWasmLinkingSubsections[wlst],FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  1179. end;
  1180. end;
  1181. procedure TWasmObjOutput.DoRelocations;
  1182. var
  1183. si, ri: Integer;
  1184. objsec: TWasmObjSection;
  1185. objrel: TWasmObjRelocation;
  1186. begin
  1187. for si:=0 to FData.ObjSectionList.Count-1 do
  1188. begin
  1189. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  1190. for ri:=0 to objsec.ObjRelocations.Count-1 do
  1191. begin
  1192. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  1193. case objrel.typ of
  1194. RELOC_FUNCTION_INDEX_LEB:
  1195. begin
  1196. if not assigned(objrel.symbol) then
  1197. internalerror(2021092509);
  1198. objsec.Data.seek(objrel.DataOffset);
  1199. if TWasmObjSymbol(objrel.symbol).FuncIndex<0 then
  1200. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1201. else
  1202. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).FuncIndex);
  1203. end;
  1204. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  1205. begin
  1206. if not assigned(objrel.symbol) then
  1207. internalerror(2021092605);
  1208. if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  1209. begin
  1210. objsec.Data.seek(objrel.DataOffset);
  1211. AddSleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1212. end;
  1213. end;
  1214. RELOC_MEMORY_ADDR_LEB:
  1215. begin
  1216. if not assigned(objrel.symbol) then
  1217. internalerror(2021092606);
  1218. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1219. internalerror(2021092628);
  1220. if objrel.symbol.bind<>AB_EXTERNAL then
  1221. begin
  1222. objsec.Data.seek(objrel.DataOffset);
  1223. AddUleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1224. end;
  1225. end;
  1226. RELOC_ABSOLUTE:
  1227. begin
  1228. if assigned(objrel.ObjSection) then
  1229. begin
  1230. { todo: should we do something here? }
  1231. //Writeln('todo: section relocation');
  1232. end
  1233. else if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  1234. begin
  1235. objsec.Data.seek(objrel.DataOffset);
  1236. AddInt32(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1237. end;
  1238. end;
  1239. RELOC_TYPE_INDEX_LEB:
  1240. ;
  1241. RELOC_GLOBAL_INDEX_LEB:
  1242. begin
  1243. if not assigned(objrel.symbol) then
  1244. internalerror(2021092509);
  1245. objsec.Data.seek(objrel.DataOffset);
  1246. if TWasmObjSymbol(objrel.symbol).GlobalIndex<0 then
  1247. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1248. else
  1249. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).GlobalIndex);
  1250. end;
  1251. RELOC_TAG_INDEX_LEB:
  1252. begin
  1253. if not assigned(objrel.symbol) then
  1254. internalerror(2021092716);
  1255. objsec.Data.seek(objrel.DataOffset);
  1256. if TWasmObjSymbol(objrel.symbol).TagIndex<0 then
  1257. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1258. else
  1259. WriteSleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).TagIndex);
  1260. end;
  1261. else
  1262. internalerror(2021092510);
  1263. end;
  1264. end;
  1265. end;
  1266. end;
  1267. procedure TWasmObjOutput.WriteRelocations;
  1268. var
  1269. si, ri: Integer;
  1270. objsec: TWasmObjSection;
  1271. objrel: TWasmObjRelocation;
  1272. relout: tdynamicarray;
  1273. relcount: PInteger;
  1274. FuncSym: TWasmObjSymbol;
  1275. begin
  1276. for si:=0 to FData.ObjSectionList.Count-1 do
  1277. begin
  1278. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  1279. if objsec.IsCode then
  1280. begin
  1281. relout:=FWasmRelocationCodeTable;
  1282. relcount:=@FWasmRelocationCodeTableEntriesCount;
  1283. end
  1284. else if objsec.IsData then
  1285. begin
  1286. relout:=FWasmRelocationDataTable;
  1287. relcount:=@FWasmRelocationDataTableEntriesCount;
  1288. end
  1289. else if objsec.IsDebug then
  1290. begin
  1291. case objsec.Name of
  1292. '.debug_frame':
  1293. begin
  1294. relout:=FWasmRelocationDebugFrameTable;
  1295. relcount:=@FWasmRelocationDebugFrameTableEntriesCount;
  1296. end;
  1297. '.debug_info':
  1298. begin
  1299. relout:=FWasmRelocationDebugInfoTable;
  1300. relcount:=@FWasmRelocationDebugInfoTableEntriesCount;
  1301. end;
  1302. '.debug_line':
  1303. begin
  1304. relout:=FWasmRelocationDebugLineTable;
  1305. relcount:=@FWasmRelocationDebugLineTableEntriesCount;
  1306. end;
  1307. '.debug_abbrev':
  1308. begin
  1309. relout:=FWasmRelocationDebugAbbrevTable;
  1310. relcount:=@FWasmRelocationDebugAbbrevTableEntriesCount;
  1311. end;
  1312. '.debug_aranges':
  1313. begin
  1314. relout:=FWasmRelocationDebugArangesTable;
  1315. relcount:=@FWasmRelocationDebugArangesTableEntriesCount;
  1316. end;
  1317. '.debug_ranges':
  1318. begin
  1319. relout:=FWasmRelocationDebugRangesTable;
  1320. relcount:=@FWasmRelocationDebugRangesTableEntriesCount;
  1321. end;
  1322. '.debug_str':
  1323. begin
  1324. relout:=FWasmRelocationDebugStrTable;
  1325. relcount:=@FWasmRelocationDebugStrTableEntriesCount;
  1326. end;
  1327. else
  1328. internalerror(2022071601);
  1329. end;
  1330. end
  1331. else
  1332. continue;
  1333. for ri:=0 to objsec.ObjRelocations.Count-1 do
  1334. begin
  1335. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  1336. case objrel.typ of
  1337. RELOC_FUNCTION_INDEX_LEB:
  1338. begin
  1339. if not assigned(objrel.symbol) then
  1340. internalerror(2021092508);
  1341. Inc(relcount^);
  1342. WriteByte(relout,Ord(R_WASM_FUNCTION_INDEX_LEB));
  1343. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1344. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1345. end;
  1346. RELOC_MEMORY_ADDR_LEB:
  1347. begin
  1348. if not assigned(objrel.symbol) then
  1349. internalerror(2021092603);
  1350. Inc(relcount^);
  1351. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1352. internalerror(2021092628);
  1353. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_LEB));
  1354. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1355. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1356. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1357. end;
  1358. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  1359. begin
  1360. if not assigned(objrel.symbol) then
  1361. internalerror(2021092604);
  1362. Inc(relcount^);
  1363. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1364. begin
  1365. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_SLEB));
  1366. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1367. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1368. end
  1369. else
  1370. begin
  1371. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_SLEB));
  1372. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1373. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1374. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1375. end;
  1376. end;
  1377. RELOC_ABSOLUTE:
  1378. begin
  1379. // todo: figure this out, why do these exist?
  1380. //if assigned(objrel.symbol) and not assigned(objrel.symbol.objsection) then
  1381. // Writeln('!!! ', objrel.symbol.name);
  1382. if assigned(objrel.objsection) then
  1383. begin
  1384. Inc(relcount^);
  1385. WriteByte(relout,Ord(R_WASM_SECTION_OFFSET_I32));
  1386. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1387. if (TWasmObjSection(objrel.objsection).SegSymIdx<0) then
  1388. message1(asmw_e_illegal_unset_index,objrel.objsection.name)
  1389. else
  1390. WriteUleb(relout,TWasmObjSection(objrel.objsection).SegSymIdx);
  1391. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1392. end
  1393. else if (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION)) and not objsec.IsDebug then
  1394. begin
  1395. Inc(relcount^);
  1396. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_I32));
  1397. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1398. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1399. end
  1400. else if assigned(objrel.symbol) and assigned(objrel.symbol.objsection) and TWasmObjSection(objrel.symbol.objsection).IsCode then
  1401. begin
  1402. Inc(relcount^);
  1403. WriteByte(relout,Ord(R_WASM_FUNCTION_OFFSET_I32));
  1404. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1405. FuncSym:=FindFunctionSymbol(TWasmObjSymbol(objrel.Symbol));
  1406. if FuncSym.SymbolIndex<0 then
  1407. message1(asmw_e_illegal_unset_index,FuncSym.Name)
  1408. else
  1409. WriteUleb(relout,FuncSym.SymbolIndex);
  1410. WriteSleb(relout,objrel.Addend+objrel.symbol.address); { addend to add to the address }
  1411. end
  1412. else
  1413. begin
  1414. Inc(relcount^);
  1415. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_I32));
  1416. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1417. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1418. begin
  1419. Writeln(objrel.symbol.objsection.Name, ' ', objrel.symbol.name, ' ', objsec.Name);
  1420. message1(asmw_e_illegal_unset_index,objrel.symbol.name);
  1421. end
  1422. else
  1423. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1424. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1425. end;
  1426. end;
  1427. RELOC_TYPE_INDEX_LEB:
  1428. begin
  1429. Inc(relcount^);
  1430. WriteByte(relout,Ord(R_WASM_TYPE_INDEX_LEB));
  1431. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1432. WriteUleb(relout,objrel.TypeIndex);
  1433. end;
  1434. RELOC_GLOBAL_INDEX_LEB:
  1435. begin
  1436. if not assigned(objrel.symbol) then
  1437. internalerror(2021092704);
  1438. Inc(relcount^);
  1439. WriteByte(relout,Ord(R_WASM_GLOBAL_INDEX_LEB));
  1440. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1441. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1442. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1443. else
  1444. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1445. end;
  1446. RELOC_TAG_INDEX_LEB:
  1447. begin
  1448. if not assigned(objrel.symbol) then
  1449. internalerror(2021092717);
  1450. Inc(relcount^);
  1451. WriteByte(relout,Ord(R_WASM_TAG_INDEX_LEB));
  1452. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1453. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1454. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1455. else
  1456. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1457. end;
  1458. else
  1459. internalerror(2021092507);
  1460. end;
  1461. end;
  1462. end;
  1463. end;
  1464. function TWasmObjOutput.FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
  1465. begin
  1466. Result:=TWasmObjSection(Symbol.objsection).MainFuncSymbol;
  1467. end;
  1468. function TWasmObjOutput.writeData(Data:TObjData):boolean;
  1469. var
  1470. section_nr: Integer;
  1471. procedure MaybeAddDebugSectionToSymbolTable(st: TWasmCustomDebugSectionType; var debug_section_nr: Integer);
  1472. var
  1473. objsec: TWasmObjSection;
  1474. begin
  1475. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1476. if Assigned(objsec) then
  1477. begin
  1478. debug_section_nr:=section_nr;
  1479. Inc(section_nr);
  1480. objsec.SegSymIdx:=FWasmSymbolTableEntriesCount;
  1481. Inc(FWasmSymbolTableEntriesCount);
  1482. WriteByte(FWasmSymbolTable,Ord(SYMTAB_SECTION));
  1483. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL);
  1484. WriteUleb(FWasmSymbolTable,debug_section_nr);
  1485. end;
  1486. end;
  1487. procedure MaybeWriteDebugSection(st: TWasmCustomDebugSectionType);
  1488. var
  1489. objsec: TWasmObjSection;
  1490. begin
  1491. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1492. if Assigned(objsec) then
  1493. begin
  1494. if oso_Data in objsec.SecOptions then
  1495. begin
  1496. objsec.Data.seek(0);
  1497. CopyDynamicArray(objsec.Data,FWasmCustomSections[st],objsec.Size);
  1498. end
  1499. else
  1500. WriteZeros(FWasmCustomSections[st],objsec.Size);
  1501. WriteWasmCustomSection(st);
  1502. end;
  1503. end;
  1504. var
  1505. i: Integer;
  1506. objsec: TWasmObjSection;
  1507. segment_count: Integer = 0;
  1508. cur_seg_ofs: qword = 0;
  1509. imports_count, NextImportFunctionIndex, NextFunctionIndex,
  1510. code_section_nr, data_section_nr,
  1511. debug_abbrev_section_nr,debug_info_section_nr,debug_str_section_nr,
  1512. debug_line_section_nr,debug_frame_section_nr,debug_aranges_section_nr,
  1513. debug_ranges_section_nr,
  1514. NextGlobalIndex, NextTagIndex: Integer;
  1515. import_globals_count: Integer = 0;
  1516. globals_count: Integer = 0;
  1517. import_functions_count: Integer = 0;
  1518. export_functions_count: Integer = 0;
  1519. functions_count: Integer = 0;
  1520. import_exception_tags_count: Integer = 0;
  1521. exception_tags_count: Integer = 0;
  1522. objsym, ObjSymAlias: TWasmObjSymbol;
  1523. cust_sec: TWasmCustomSectionType;
  1524. SegmentFlags, SymbolFlags: UInt64;
  1525. begin
  1526. FData:=TWasmObjData(Data);
  1527. { each custom sections starts with its name }
  1528. for cust_sec in TWasmCustomSectionType do
  1529. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  1530. WriteUleb(FWasmCustomSections[wcstLinking],2); { linking metadata version }
  1531. for i:=0 to Data.ObjSymbolList.Count-1 do
  1532. begin
  1533. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1534. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1535. if objsym.bind=AB_EXTERNAL then
  1536. Inc(import_exception_tags_count)
  1537. else
  1538. Inc(exception_tags_count);
  1539. if objsym.typ=AT_WASM_GLOBAL then
  1540. if objsym.bind=AB_EXTERNAL then
  1541. Inc(import_globals_count)
  1542. else
  1543. Inc(globals_count);
  1544. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1545. Inc(import_globals_count);
  1546. if IsExternalFunction(objsym) then
  1547. Inc(import_functions_count);
  1548. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1549. begin
  1550. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  1551. Inc(functions_count);
  1552. end;
  1553. if IsExportedFunction(objsym) then
  1554. Inc(export_functions_count);
  1555. end;
  1556. FData.FFuncTypes.WriteTo(FWasmSections[wsiType]);
  1557. for i:=0 to Data.ObjSectionList.Count-1 do
  1558. begin
  1559. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1560. if objsec.IsCode then
  1561. objsec.SegIdx:=-1
  1562. else if objsec.IsData then
  1563. begin
  1564. objsec.SegIdx:=segment_count;
  1565. objsec.SegOfs:=cur_seg_ofs;
  1566. Inc(segment_count);
  1567. Inc(cur_seg_ofs,objsec.Size);
  1568. end;
  1569. end;
  1570. imports_count:=2+import_globals_count+import_functions_count+import_exception_tags_count;
  1571. WriteUleb(FWasmSections[wsiImport],imports_count);
  1572. { import memories }
  1573. WriteName(FWasmSections[wsiImport],'env');
  1574. WriteName(FWasmSections[wsiImport],'__linear_memory');
  1575. WriteByte(FWasmSections[wsiImport],$02); { mem }
  1576. WriteByte(FWasmSections[wsiImport],$00); { min }
  1577. WriteUleb(FWasmSections[wsiImport],1); { 1 page }
  1578. { import globals }
  1579. NextGlobalIndex:=0;
  1580. for i:=0 to Data.ObjSymbolList.Count-1 do
  1581. begin
  1582. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1583. if (objsym.bind=AB_EXTERNAL) and (objsym.typ=AT_WASM_GLOBAL) then
  1584. begin
  1585. objsym.GlobalIndex:=NextGlobalIndex;
  1586. Inc(NextGlobalIndex);
  1587. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1588. if objsym.ExtraData.ImportModule<>'' then
  1589. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1590. else
  1591. WriteName(FWasmSections[wsiImport],'env');
  1592. WriteName(FWasmSections[wsiImport],objsym.Name);
  1593. WriteByte(FWasmSections[wsiImport],$03); { global }
  1594. WriteWasmBasicType(FWasmSections[wsiImport],objsym.ExtraData.GlobalType);
  1595. if objsym.ExtraData.GlobalIsImmutable then
  1596. WriteByte(FWasmSections[wsiImport],$00) { const }
  1597. else
  1598. WriteByte(FWasmSections[wsiImport],$01); { var }
  1599. end
  1600. else if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1601. begin
  1602. objsym.GlobalIndex:=NextGlobalIndex;
  1603. Inc(NextGlobalIndex);
  1604. objsym.ExtraData:=nil;
  1605. WriteName(FWasmSections[wsiImport],'GOT.mem');
  1606. WriteName(FWasmSections[wsiImport],objsym.Name);
  1607. WriteByte(FWasmSections[wsiImport],$03); { global }
  1608. WriteWasmBasicType(FWasmSections[wsiImport],wbt_i32); { i32 }
  1609. WriteByte(FWasmSections[wsiImport],$01); { var }
  1610. end;
  1611. end;
  1612. { import functions }
  1613. NextImportFunctionIndex:=0;
  1614. for i:=0 to Data.ObjSymbolList.Count-1 do
  1615. begin
  1616. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1617. if IsExternalFunction(objsym) then
  1618. begin
  1619. objsym.FuncIndex:=NextImportFunctionIndex;
  1620. Inc(NextImportFunctionIndex);
  1621. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1622. if objsym.ExtraData.ImportModule<>'' then
  1623. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1624. else
  1625. WriteName(FWasmSections[wsiImport],'env');
  1626. WriteName(FWasmSections[wsiImport],objsym.Name);
  1627. WriteByte(FWasmSections[wsiImport],$00); { func }
  1628. WriteUleb(FWasmSections[wsiImport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1629. end;
  1630. end;
  1631. { import tables }
  1632. WriteName(FWasmSections[wsiImport],'env');
  1633. WriteName(FWasmSections[wsiImport],'__indirect_function_table');
  1634. WriteByte(FWasmSections[wsiImport],$01); { table }
  1635. WriteByte(FWasmSections[wsiImport],$70); { funcref }
  1636. WriteByte(FWasmSections[wsiImport],$00); { min }
  1637. WriteUleb(FWasmSections[wsiImport],1); { 1 }
  1638. { import tags }
  1639. NextTagIndex:=0;
  1640. for i:=0 to Data.ObjSymbolList.Count-1 do
  1641. begin
  1642. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1643. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind=AB_EXTERNAL) then
  1644. begin
  1645. objsym.TagIndex:=NextTagIndex;
  1646. Inc(NextTagIndex);
  1647. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1648. if objsym.ExtraData.ImportModule<>'' then
  1649. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1650. else
  1651. WriteName(FWasmSections[wsiImport],'env');
  1652. WriteName(FWasmSections[wsiImport],objsym.Name);
  1653. WriteByte(FWasmSections[wsiImport],$04); { tag }
  1654. WriteByte(FWasmSections[wsiImport],$00); { exception }
  1655. WriteUleb(FWasmSections[wsiImport],objsym.ExtraData.ExceptionTagTypeIdx);
  1656. end;
  1657. end;
  1658. WriteUleb(FWasmSections[wsiFunction],functions_count);
  1659. NextFunctionIndex:=NextImportFunctionIndex;
  1660. for i:=0 to Data.ObjSymbolList.Count-1 do
  1661. begin
  1662. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1663. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1664. begin
  1665. objsym.FuncIndex:=NextFunctionIndex;
  1666. Inc(NextFunctionIndex);
  1667. WriteUleb(FWasmSections[wsiFunction],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1668. end;
  1669. end;
  1670. if exception_tags_count>0 then
  1671. begin
  1672. WriteUleb(FWasmSections[wsiTag],exception_tags_count);
  1673. for i:=0 to Data.ObjSymbolList.Count-1 do
  1674. begin
  1675. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1676. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind<>AB_EXTERNAL) then
  1677. begin
  1678. objsym.TagIndex:=NextTagIndex;
  1679. Inc(NextTagIndex);
  1680. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1681. WriteByte(FWasmSections[wsiTag],$00); { exception }
  1682. WriteUleb(FWasmSections[wsiTag],objsym.ExtraData.ExceptionTagTypeIdx);
  1683. end;
  1684. end;
  1685. end;
  1686. if globals_count>0 then
  1687. begin
  1688. WriteUleb(FWasmSections[wsiGlobal],globals_count);
  1689. for i:=0 to Data.ObjSymbolList.Count-1 do
  1690. begin
  1691. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1692. if (objsym.typ=AT_WASM_GLOBAL) and (objsym.bind<>AB_EXTERNAL) then
  1693. begin
  1694. objsym.GlobalIndex:=NextGlobalIndex;
  1695. Inc(NextGlobalIndex);
  1696. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1697. WriteWasmBasicType(FWasmSections[wsiGlobal],objsym.ExtraData.GlobalType);
  1698. if objsym.ExtraData.GlobalIsImmutable then
  1699. WriteByte(FWasmSections[wsiGlobal],$00) { const }
  1700. else
  1701. WriteByte(FWasmSections[wsiGlobal],$01); { var }
  1702. { init expr }
  1703. case objsym.ExtraData.GlobalType of
  1704. wbt_i32:
  1705. begin
  1706. WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
  1707. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1708. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1709. end;
  1710. wbt_i64:
  1711. begin
  1712. WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
  1713. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1714. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1715. end;
  1716. wbt_f32:
  1717. begin
  1718. WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
  1719. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE single precision floating point format) }
  1720. WriteByte(FWasmSections[wsiGlobal],$00);
  1721. WriteByte(FWasmSections[wsiGlobal],$00);
  1722. WriteByte(FWasmSections[wsiGlobal],$00);
  1723. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1724. end;
  1725. wbt_f64:
  1726. begin
  1727. WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
  1728. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE double precision floating point format) }
  1729. WriteByte(FWasmSections[wsiGlobal],$00);
  1730. WriteByte(FWasmSections[wsiGlobal],$00);
  1731. WriteByte(FWasmSections[wsiGlobal],$00);
  1732. WriteByte(FWasmSections[wsiGlobal],$00);
  1733. WriteByte(FWasmSections[wsiGlobal],$00);
  1734. WriteByte(FWasmSections[wsiGlobal],$00);
  1735. WriteByte(FWasmSections[wsiGlobal],$00);
  1736. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1737. end;
  1738. wbt_externref:
  1739. begin
  1740. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null extern }
  1741. WriteByte(FWasmSections[wsiGlobal],$6F);
  1742. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1743. end;
  1744. wbt_funcref:
  1745. begin
  1746. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null func }
  1747. WriteByte(FWasmSections[wsiGlobal],$70);
  1748. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1749. end;
  1750. else
  1751. internalerror(2022052801);
  1752. end;
  1753. end;
  1754. end;
  1755. end;
  1756. if export_functions_count>0 then
  1757. begin
  1758. WriteUleb(FWasmSections[wsiExport],export_functions_count);
  1759. for i:=0 to Data.ObjSymbolList.Count-1 do
  1760. begin
  1761. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1762. if IsExportedFunction(objsym) then
  1763. begin
  1764. WriteName(FWasmSections[wsiExport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).ExportName);
  1765. WriteByte(FWasmSections[wsiExport],0); { func }
  1766. if (objsym.FuncIndex<0) then
  1767. message1(asmw_e_illegal_unset_index,objsym.name)
  1768. else
  1769. WriteUleb(FWasmSections[wsiExport],objsym.FuncIndex);
  1770. end;
  1771. end;
  1772. end;
  1773. for i:=0 to Data.ObjSymbolList.Count-1 do
  1774. begin
  1775. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1776. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1777. begin
  1778. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1779. Inc(FWasmSymbolTableEntriesCount);
  1780. WriteByte(FWasmSymbolTable,Ord(SYMTAB_EVENT));
  1781. if objsym.bind=AB_GLOBAL then
  1782. WriteUleb(FWasmSymbolTable,0)
  1783. else if objsym.bind=AB_LOCAL then
  1784. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL)
  1785. else if objsym.bind=AB_EXTERNAL then
  1786. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED)
  1787. else if objsym.bind=AB_WEAK then
  1788. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_WEAK)
  1789. else
  1790. internalerror(2021092715);
  1791. if (objsym.TagIndex<0) then
  1792. message1(asmw_e_illegal_unset_index,objsym.name)
  1793. else
  1794. WriteUleb(FWasmSymbolTable,objsym.TagIndex);
  1795. if objsym.bind<>AB_EXTERNAL then
  1796. WriteName(FWasmSymbolTable,objsym.Name);
  1797. end
  1798. else if objsym.typ=AT_WASM_GLOBAL then
  1799. begin
  1800. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1801. Inc(FWasmSymbolTableEntriesCount);
  1802. WriteByte(FWasmSymbolTable,Ord(SYMTAB_GLOBAL));
  1803. if objsym.bind=AB_EXTERNAL then
  1804. begin
  1805. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1806. if (objsym.GlobalIndex<0) then
  1807. message1(asmw_e_illegal_unset_index,objsym.name)
  1808. else
  1809. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  1810. end
  1811. else
  1812. begin
  1813. WriteUleb(FWasmSymbolTable,0);
  1814. if (objsym.GlobalIndex<0) then
  1815. message1(asmw_e_illegal_unset_index,objsym.name)
  1816. else
  1817. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  1818. WriteName(FWasmSymbolTable,objsym.Name);
  1819. end;
  1820. end
  1821. else if IsExternalFunction(objsym) then
  1822. begin
  1823. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1824. Inc(FWasmSymbolTableEntriesCount);
  1825. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1826. if objsym.ExtraData.ImportModule<>'' then
  1827. begin
  1828. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED or WASM_SYM_EXPLICIT_NAME);
  1829. if (objsym.FuncIndex<0) then
  1830. message1(asmw_e_illegal_unset_index,objsym.name)
  1831. else
  1832. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1833. WriteName(FWasmSymbolTable,objsym.Name);
  1834. end
  1835. else
  1836. begin
  1837. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1838. if (objsym.FuncIndex<0) then
  1839. message1(asmw_e_illegal_unset_index,objsym.name)
  1840. else
  1841. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1842. end;
  1843. end
  1844. else if objsym.typ=AT_FUNCTION then
  1845. begin
  1846. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1847. Inc(FWasmSymbolTableEntriesCount);
  1848. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1849. if objsym.IsAlias then
  1850. begin
  1851. ObjSymAlias:=TWasmObjSymbol(Data.ObjSymbolList.Find(objsym.AliasOf));
  1852. ObjSym.FuncIndex:=ObjSymAlias.FuncIndex;
  1853. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPLICIT_NAME or WASM_SYM_NO_STRIP);
  1854. WriteUleb(FWasmSymbolTable,ObjSymAlias.FuncIndex);
  1855. end
  1856. else
  1857. begin
  1858. if IsExportedFunction(objsym) then
  1859. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPORTED)
  1860. else
  1861. WriteUleb(FWasmSymbolTable,0);
  1862. if (objsym.FuncIndex<0) then
  1863. message1(asmw_e_illegal_unset_index,objsym.name)
  1864. else
  1865. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1866. end;
  1867. WriteName(FWasmSymbolTable,objsym.Name);
  1868. end
  1869. else if (objsym.typ in [AT_DATA,AT_TLS]) or ((objsym.typ=AT_NONE) and (objsym.bind=AB_EXTERNAL)) then
  1870. begin
  1871. if (objsym.bind<>AB_EXTERNAL) and TWasmObjSection(objsym.objsection).IsDebug then
  1872. begin
  1873. {todo: debug symbols}
  1874. end
  1875. else
  1876. begin
  1877. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1878. Inc(FWasmSymbolTableEntriesCount);
  1879. WriteByte(FWasmSymbolTable,Ord(SYMTAB_DATA));
  1880. if objsym.bind=AB_GLOBAL then
  1881. SymbolFlags:=0
  1882. else if objsym.bind=AB_LOCAL then
  1883. SymbolFlags:=WASM_SYM_BINDING_LOCAL
  1884. else if objsym.bind=AB_EXTERNAL then
  1885. SymbolFlags:=WASM_SYM_UNDEFINED
  1886. else
  1887. internalerror(2021092506);
  1888. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1889. SymbolFlags:=(SymbolFlags and not WASM_SYM_BINDING_LOCAL) or WASM_SYM_TLS;
  1890. WriteUleb(FWasmSymbolTable,SymbolFlags);
  1891. WriteName(FWasmSymbolTable,objsym.Name);
  1892. if objsym.bind<>AB_EXTERNAL then
  1893. begin
  1894. WriteUleb(FWasmSymbolTable,TWasmObjSection(objsym.objsection).SegIdx);
  1895. WriteUleb(FWasmSymbolTable,objsym.offset);
  1896. WriteUleb(FWasmSymbolTable,objsym.size);
  1897. end;
  1898. end;
  1899. end;
  1900. end;
  1901. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  1902. Writer.write(WasmVersion,SizeOf(WasmVersion));
  1903. if ts_wasm_threads in current_settings.targetswitches then
  1904. begin
  1905. WriteUleb(FWasmCustomSections[wcstTargetFeatures],4);
  1906. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1907. WriteName(FWasmCustomSections[wcstTargetFeatures],'atomics');
  1908. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1909. WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
  1910. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1911. WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
  1912. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1913. WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
  1914. end
  1915. else
  1916. begin
  1917. WriteUleb(FWasmCustomSections[wcstTargetFeatures],3);
  1918. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1919. WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
  1920. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1921. WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
  1922. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1923. WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
  1924. end;
  1925. { Write the producers section:
  1926. https://github.com/WebAssembly/tool-conventions/blob/main/ProducersSection.md }
  1927. WriteUleb(FWasmCustomSections[wcstProducers],2);
  1928. WriteName(FWasmCustomSections[wcstProducers],'language');
  1929. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1930. WriteName(FWasmCustomSections[wcstProducers],'Pascal');
  1931. WriteName(FWasmCustomSections[wcstProducers],'');
  1932. WriteName(FWasmCustomSections[wcstProducers],'processed-by');
  1933. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1934. WriteName(FWasmCustomSections[wcstProducers],'Free Pascal Compiler (FPC)');
  1935. WriteName(FWasmCustomSections[wcstProducers],full_version_string+' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname);
  1936. code_section_nr:=-1;
  1937. data_section_nr:=-1;
  1938. debug_abbrev_section_nr:=-1;
  1939. debug_info_section_nr:=-1;
  1940. debug_str_section_nr:=-1;
  1941. debug_line_section_nr:=-1;
  1942. debug_frame_section_nr:=-1;
  1943. debug_aranges_section_nr:=-1;
  1944. debug_ranges_section_nr:=-1;
  1945. section_nr:=0;
  1946. WriteWasmSection(wsiType);
  1947. Inc(section_nr);
  1948. WriteWasmSection(wsiImport);
  1949. Inc(section_nr);
  1950. WriteWasmSection(wsiFunction);
  1951. Inc(section_nr);
  1952. if exception_tags_count>0 then
  1953. begin
  1954. WriteWasmSection(wsiTag);
  1955. Inc(section_nr);
  1956. end;
  1957. if globals_count>0 then
  1958. begin
  1959. WriteWasmSection(wsiGlobal);
  1960. Inc(section_nr);
  1961. end;
  1962. if export_functions_count>0 then
  1963. begin
  1964. WriteWasmSection(wsiExport);
  1965. Inc(section_nr);
  1966. end;
  1967. { determine the section numbers for the datacount, code, data and debug sections ahead of time }
  1968. if segment_count>0 then
  1969. Inc(section_nr); { the DataCount section }
  1970. code_section_nr:=section_nr; { the Code section }
  1971. Inc(section_nr);
  1972. if segment_count>0 then
  1973. begin
  1974. data_section_nr:=section_nr; { the Data section }
  1975. Inc(section_nr);
  1976. end;
  1977. { the debug sections }
  1978. MaybeAddDebugSectionToSymbolTable(wcstDebugAbbrev,debug_abbrev_section_nr);
  1979. MaybeAddDebugSectionToSymbolTable(wcstDebugInfo,debug_info_section_nr);
  1980. MaybeAddDebugSectionToSymbolTable(wcstDebugStr,debug_str_section_nr);
  1981. MaybeAddDebugSectionToSymbolTable(wcstDebugLine,debug_line_section_nr);
  1982. MaybeAddDebugSectionToSymbolTable(wcstDebugFrame,debug_frame_section_nr);
  1983. MaybeAddDebugSectionToSymbolTable(wcstDebugAranges,debug_aranges_section_nr);
  1984. MaybeAddDebugSectionToSymbolTable(wcstDebugRanges,debug_ranges_section_nr);
  1985. DoRelocations;
  1986. if segment_count>0 then
  1987. begin
  1988. WriteUleb(FWasmSections[wsiData],segment_count);
  1989. WriteUleb(FWasmSections[wsiDataCount],segment_count);
  1990. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],segment_count);
  1991. for i:=0 to Data.ObjSectionList.Count-1 do
  1992. begin
  1993. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1994. if objsec.IsData then
  1995. begin
  1996. WriteName(FWasmLinkingSubsections[WASM_SEGMENT_INFO],objsec.Name);
  1997. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],BsrQWord(objsec.SecAlign));
  1998. SegmentFlags:=0;
  1999. if (ts_wasm_threads in current_settings.targetswitches) and
  2000. (oso_threadvar in objsec.SecOptions) then
  2001. SegmentFlags:=SegmentFlags or WASM_SEG_FLAG_TLS;
  2002. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],SegmentFlags); { flags }
  2003. WriteByte(FWasmSections[wsiData],0);
  2004. WriteByte(FWasmSections[wsiData],$41);
  2005. WriteSleb(FWasmSections[wsiData],objsec.SegOfs);
  2006. WriteByte(FWasmSections[wsiData],$0b);
  2007. WriteUleb(FWasmSections[wsiData],objsec.Size);
  2008. objsec.FileSectionOfs:=FWasmSections[wsiData].size;
  2009. if oso_Data in objsec.SecOptions then
  2010. begin
  2011. objsec.Data.seek(0);
  2012. CopyDynamicArray(objsec.Data,FWasmSections[wsiData],objsec.Size);
  2013. end
  2014. else
  2015. begin
  2016. WriteZeros(FWasmSections[wsiData],objsec.Size);
  2017. end;
  2018. end;
  2019. end;
  2020. end;
  2021. WriteUleb(FWasmSections[wsiCode],functions_count);
  2022. for i:=0 to Data.ObjSymbolList.Count-1 do
  2023. begin
  2024. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  2025. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  2026. WriteFunctionCode(FWasmSections[wsiCode],objsym);
  2027. end;
  2028. if segment_count>0 then
  2029. WriteWasmSection(wsiDataCount);
  2030. WriteWasmSection(wsiCode);
  2031. if segment_count>0 then
  2032. WriteWasmSection(wsiData);
  2033. MaybeWriteDebugSection(wcstDebugAbbrev);
  2034. MaybeWriteDebugSection(wcstDebugInfo);
  2035. MaybeWriteDebugSection(wcstDebugStr);
  2036. MaybeWriteDebugSection(wcstDebugLine);
  2037. MaybeWriteDebugSection(wcstDebugFrame);
  2038. MaybeWriteDebugSection(wcstDebugAranges);
  2039. MaybeWriteDebugSection(wcstDebugRanges);
  2040. WriteRelocations;
  2041. WriteSymbolTable;
  2042. WriteLinkingSubsection(WASM_SYMBOL_TABLE);
  2043. if segment_count>0 then
  2044. WriteLinkingSubsection(WASM_SEGMENT_INFO);
  2045. WriteRelocationCodeTable(code_section_nr);
  2046. if segment_count>0 then
  2047. WriteRelocationDataTable(data_section_nr);
  2048. WriteWasmCustomSection(wcstLinking);
  2049. Inc(section_nr);
  2050. WriteWasmCustomSection(wcstRelocCode);
  2051. Inc(section_nr);
  2052. if segment_count>0 then
  2053. begin
  2054. WriteWasmCustomSection(wcstRelocData);
  2055. Inc(section_nr);
  2056. end;
  2057. MaybeWriteRelocationDebugTable(wcstRelocDebugAbbrev,debug_abbrev_section_nr,FWasmRelocationDebugAbbrevTableEntriesCount,FWasmRelocationDebugAbbrevTable);
  2058. MaybeWriteRelocationDebugTable(wcstRelocDebugInfo,debug_info_section_nr,FWasmRelocationDebugInfoTableEntriesCount,FWasmRelocationDebugInfoTable);
  2059. MaybeWriteRelocationDebugTable(wcstRelocDebugStr,debug_str_section_nr,FWasmRelocationDebugStrTableEntriesCount,FWasmRelocationDebugStrTable);
  2060. MaybeWriteRelocationDebugTable(wcstRelocDebugLine,debug_line_section_nr,FWasmRelocationDebugLineTableEntriesCount,FWasmRelocationDebugLineTable);
  2061. MaybeWriteRelocationDebugTable(wcstRelocDebugFrame,debug_frame_section_nr,FWasmRelocationDebugFrameTableEntriesCount,FWasmRelocationDebugFrameTable);
  2062. MaybeWriteRelocationDebugTable(wcstRelocDebugAranges,debug_aranges_section_nr,FWasmRelocationDebugArangesTableEntriesCount,FWasmRelocationDebugArangesTable);
  2063. MaybeWriteRelocationDebugTable(wcstRelocDebugRanges,debug_ranges_section_nr,FWasmRelocationDebugRangesTableEntriesCount,FWasmRelocationDebugRangesTable);
  2064. WriteWasmCustomSection(wcstProducers);
  2065. Inc(section_nr);
  2066. WriteWasmCustomSection(wcstTargetFeatures);
  2067. Inc(section_nr);
  2068. result:=true;
  2069. end;
  2070. constructor TWasmObjOutput.create(AWriter: TObjectWriter);
  2071. var
  2072. i: TWasmSectionID;
  2073. j: TWasmCustomSectionType;
  2074. k: TWasmLinkingSubsectionType;
  2075. begin
  2076. inherited;
  2077. cobjdata:=TWasmObjData;
  2078. for i in TWasmSectionID do
  2079. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  2080. for j in TWasmCustomSectionType do
  2081. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  2082. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  2083. FWasmLinkingSubsections[k] := tdynamicarray.create(SectionDataMaxGrow);
  2084. FWasmSymbolTable:=tdynamicarray.create(SectionDataMaxGrow);
  2085. FWasmSymbolTableEntriesCount:=0;
  2086. FWasmRelocationCodeTable:=tdynamicarray.create(SectionDataMaxGrow);
  2087. FWasmRelocationCodeTableEntriesCount:=0;
  2088. FWasmRelocationDataTable:=tdynamicarray.create(SectionDataMaxGrow);
  2089. FWasmRelocationDataTableEntriesCount:=0;
  2090. FWasmRelocationDebugFrameTable:=tdynamicarray.create(SectionDataMaxGrow);
  2091. FWasmRelocationDebugFrameTableEntriesCount:=0;
  2092. FWasmRelocationDebugInfoTable:=tdynamicarray.create(SectionDataMaxGrow);
  2093. FWasmRelocationDebugInfoTableEntriesCount:=0;
  2094. FWasmRelocationDebugLineTable:=tdynamicarray.create(SectionDataMaxGrow);
  2095. FWasmRelocationDebugLineTableEntriesCount:=0;
  2096. FWasmRelocationDebugAbbrevTable:=tdynamicarray.create(SectionDataMaxGrow);
  2097. FWasmRelocationDebugAbbrevTableEntriesCount:=0;
  2098. FWasmRelocationDebugArangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  2099. FWasmRelocationDebugArangesTableEntriesCount:=0;
  2100. FWasmRelocationDebugRangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  2101. FWasmRelocationDebugRangesTableEntriesCount:=0;
  2102. FWasmRelocationDebugStrTable:=tdynamicarray.create(SectionDataMaxGrow);
  2103. FWasmRelocationDebugStrTableEntriesCount:=0;
  2104. end;
  2105. destructor TWasmObjOutput.destroy;
  2106. var
  2107. i: TWasmSectionID;
  2108. j: TWasmCustomSectionType;
  2109. k: TWasmLinkingSubsectionType;
  2110. begin
  2111. for i in TWasmSectionID do
  2112. FWasmSections[i].Free;
  2113. for j in TWasmCustomSectionType do
  2114. FWasmCustomSections[j].Free;
  2115. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  2116. FWasmLinkingSubsections[k].Free;
  2117. FWasmSymbolTable.Free;
  2118. FWasmRelocationCodeTable.Free;
  2119. FWasmRelocationDataTable.Free;
  2120. FWasmRelocationDebugFrameTable.Free;
  2121. FWasmRelocationDebugInfoTable.Free;
  2122. FWasmRelocationDebugLineTable.Free;
  2123. FWasmRelocationDebugAbbrevTable.Free;
  2124. FWasmRelocationDebugArangesTable.Free;
  2125. FWasmRelocationDebugRangesTable.Free;
  2126. FWasmRelocationDebugStrTable.Free;
  2127. inherited destroy;
  2128. end;
  2129. {****************************************************************************
  2130. TWasmObjInput
  2131. ****************************************************************************}
  2132. constructor TWasmObjInput.create;
  2133. begin
  2134. inherited create;
  2135. cobjdata:=TWasmObjData;
  2136. end;
  2137. destructor TWasmObjInput.Destroy;
  2138. var
  2139. i: Integer;
  2140. begin
  2141. for i:=low(FFuncTypes) to high(FFuncTypes) do
  2142. begin
  2143. FFuncTypes[i].free;
  2144. FFuncTypes[i]:=nil;
  2145. end;
  2146. inherited Destroy;
  2147. end;
  2148. class function TWasmObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  2149. var
  2150. ModuleMagic: array [0..3] of Byte;
  2151. ModuleVersion: array [0..3] of Byte;
  2152. i: Integer;
  2153. begin
  2154. result:=false;
  2155. if not AReader.read(ModuleMagic,4) then
  2156. exit;
  2157. for i:=0 to 3 do
  2158. if ModuleMagic[i]<>WasmModuleMagic[i] then
  2159. exit;
  2160. if not AReader.read(ModuleVersion,4) then
  2161. exit;
  2162. for i:=0 to 3 do
  2163. if ModuleVersion[i]<>WasmVersion[i] then
  2164. exit;
  2165. result:=true;
  2166. end;
  2167. function TWasmObjInput.ReadObjData(AReader: TObjectreader; out ObjData: TObjData): boolean;
  2168. type
  2169. TLimits = record
  2170. Min, Max: uint32;
  2171. HasMax: Boolean;
  2172. end;
  2173. var
  2174. SectionIndex: Integer = -1;
  2175. SectionId: Byte;
  2176. SectionSize: uint32;
  2177. SectionStart: LongInt;
  2178. CheckSectionBounds: Boolean;
  2179. TypeSectionRead: Boolean = false;
  2180. ImportSectionRead: Boolean = false;
  2181. FunctionSectionRead: Boolean = false;
  2182. GlobalSectionRead: Boolean = false;
  2183. ExportSectionRead: Boolean = false;
  2184. CodeSectionRead: Boolean = false;
  2185. DataSectionRead: Boolean = false;
  2186. DataCountSectionRead: Boolean = false;
  2187. SegmentInfoSectionRead: Boolean = false;
  2188. SymbolTableSectionRead: Boolean = false;
  2189. CodeSectionIndex: Integer = -1;
  2190. DataSectionIndex: Integer = -1;
  2191. FuncTypes: array of record
  2192. IsImport: Boolean;
  2193. ImportName: ansistring;
  2194. ImportModName: ansistring;
  2195. typidx: uint32;
  2196. IsExported: Boolean;
  2197. ExportName: ansistring;
  2198. end;
  2199. FuncTypeImportsCount: uint32;
  2200. TableTypes: array of record
  2201. IsImport: Boolean;
  2202. ImportName: ansistring;
  2203. ImportModName: ansistring;
  2204. reftype: TWasmBAsicType;
  2205. limits: TLimits;
  2206. IsExported: Boolean;
  2207. ExportName: ansistring;
  2208. end;
  2209. TableTypeImportsCount: uint32;
  2210. MemTypes: array of record
  2211. IsImport: Boolean;
  2212. ImportName: ansistring;
  2213. ImportModName: ansistring;
  2214. limits: TLimits;
  2215. IsExported: Boolean;
  2216. ExportName: ansistring;
  2217. end;
  2218. MemTypeImportsCount: uint32;
  2219. GlobalTypes: array of record
  2220. IsImport: Boolean;
  2221. ImportName: ansistring;
  2222. ImportModName: ansistring;
  2223. valtype: TWasmBasicType;
  2224. IsMutable: Boolean;
  2225. IsExported: Boolean;
  2226. ExportName: ansistring;
  2227. GlobalInit: TGlobalInitializer;
  2228. end;
  2229. GlobalTypeImportsCount: uint32;
  2230. CodeSegments: array of record
  2231. CodeSectionOffset: uint32;
  2232. CodeSize: uint32;
  2233. DataPos: LongInt;
  2234. SegName: ansistring;
  2235. SegIsExported: Boolean;
  2236. end;
  2237. DataSegments: array of record
  2238. DataSectionOffset: uint32;
  2239. Active: Boolean;
  2240. MemIdx: uint32;
  2241. Len: uint32;
  2242. Offset: int32;
  2243. DataPos: LongInt;
  2244. SegName: ansistring;
  2245. SegAlignment: uint32;
  2246. SegFlags: uint32;
  2247. end;
  2248. SymbolTable: array of record
  2249. SymFlags: uint32;
  2250. TargetSection: uint32;
  2251. SymIndex: uint32;
  2252. SymOffset: uint32;
  2253. SymSize: uint32;
  2254. SymKind: Byte;
  2255. SymName: ansistring;
  2256. ObjSym: TWasmObjSymbol;
  2257. end;
  2258. { meaning of first index: }
  2259. { table 0 is code relocs }
  2260. { table 1 is data relocs }
  2261. { tables 2.. are custom section relocs }
  2262. RelocationTable: array of array of record
  2263. RelocType: Byte;
  2264. RelocOffset: uint32;
  2265. RelocIndex: uint32;
  2266. RelocAddend: int32;
  2267. end;
  2268. function ReadSection: Boolean;
  2269. function read(out b;len:longint):boolean;
  2270. begin
  2271. result:=false;
  2272. if not CheckSectionBounds or ((AReader.Pos+len)<=(SectionStart+SectionSize)) then
  2273. result:=AReader.read(b,len)
  2274. else
  2275. begin
  2276. { trying to read beyond the end of the section }
  2277. AReader.read(b,SectionStart+SectionSize-AReader.Pos);
  2278. result:=false;
  2279. end;
  2280. end;
  2281. function ReadUleb(out v: uint64): boolean;
  2282. var
  2283. b: byte;
  2284. shift:integer;
  2285. begin
  2286. result:=false;
  2287. b:=0;
  2288. v:=0;
  2289. shift:=0;
  2290. repeat
  2291. if not read(b,1) then
  2292. exit;
  2293. v:=v or (uint64(b and 127) shl shift);
  2294. inc(shift,7);
  2295. until (b and 128)=0;
  2296. result:=true;
  2297. end;
  2298. function ReadUleb32(out v: uint32): boolean;
  2299. var
  2300. vv: uint64;
  2301. begin
  2302. result:=false;
  2303. v:=default(uint32);
  2304. if not ReadUleb(vv) then
  2305. exit;
  2306. if vv>high(uint32) then
  2307. exit;
  2308. v:=vv;
  2309. result:=true;
  2310. end;
  2311. function ReadSleb(out v: int64): boolean;
  2312. var
  2313. b: byte;
  2314. shift:integer;
  2315. begin
  2316. result:=false;
  2317. b:=0;
  2318. v:=0;
  2319. shift:=0;
  2320. repeat
  2321. if not read(b,1) then
  2322. exit;
  2323. v:=v or (uint64(b and 127) shl shift);
  2324. inc(shift,7);
  2325. until (b and 128)=0;
  2326. {$ifopt Q+}
  2327. {$define overflowon}
  2328. {$Q-}
  2329. {$endif}
  2330. {$ifopt R+}
  2331. {$define rangeon}
  2332. {$R-}
  2333. {$endif}
  2334. if (b and 64)<>0 then
  2335. v:=v or (high(uint64) shl shift);
  2336. result:=true;
  2337. end;
  2338. {$ifdef overflowon}
  2339. {$Q+}
  2340. {$undef overflowon}
  2341. {$endif}
  2342. {$ifdef rangeon}
  2343. {$R+}
  2344. {$undef rangeon}
  2345. {$endif}
  2346. function ReadSleb32(out v: int32): boolean;
  2347. var
  2348. vv: int64;
  2349. begin
  2350. result:=false;
  2351. v:=default(int32);
  2352. if not ReadSleb(vv) then
  2353. exit;
  2354. if (vv>high(int32)) or (vv<low(int32)) then
  2355. exit;
  2356. v:=vv;
  2357. result:=true;
  2358. end;
  2359. function ReadName(out v: ansistring): boolean;
  2360. var
  2361. len: uint32;
  2362. begin
  2363. result:=false;
  2364. if not ReadUleb32(len) then
  2365. exit;
  2366. SetLength(v,len);
  2367. if len>0 then
  2368. result:=read(v[1],len)
  2369. else
  2370. result:=true;
  2371. end;
  2372. function ReadCustomSection: Boolean;
  2373. function ReadRelocationSection: Boolean;
  2374. var
  2375. TargetSection, RelocCount: uint32;
  2376. i: Integer;
  2377. RelocTableIndex: Integer;
  2378. begin
  2379. Result:=False;
  2380. if not ReadUleb32(TargetSection) then
  2381. begin
  2382. InputError('Error reading the index of the target section of a relocation section');
  2383. exit;
  2384. end;
  2385. if TargetSection=CodeSectionIndex then
  2386. RelocTableIndex:=0
  2387. else if TargetSection=DataSectionIndex then
  2388. RelocTableIndex:=1
  2389. else
  2390. begin
  2391. InputError('Relocation for custom sections not supported, yet');
  2392. exit;
  2393. end;
  2394. if not ReadUleb32(RelocCount) then
  2395. begin
  2396. InputError('Error reading the relocation entries count from a relocation section');
  2397. exit;
  2398. end;
  2399. SetLength(RelocationTable[RelocTableIndex],RelocCount);
  2400. for i:=0 to RelocCount-1 do
  2401. with RelocationTable[RelocTableIndex,i] do
  2402. begin
  2403. if not Read(RelocType,1) then
  2404. begin
  2405. InputError('Error reading the relocation type of a relocation entry');
  2406. exit;
  2407. end;
  2408. if not (TWasmRelocationType(RelocType) in [R_WASM_FUNCTION_INDEX_LEB,
  2409. R_WASM_MEMORY_ADDR_LEB,
  2410. R_WASM_TABLE_INDEX_SLEB,
  2411. R_WASM_MEMORY_ADDR_SLEB,
  2412. R_WASM_SECTION_OFFSET_I32,
  2413. R_WASM_TABLE_INDEX_I32,
  2414. R_WASM_FUNCTION_OFFSET_I32,
  2415. R_WASM_MEMORY_ADDR_I32,
  2416. R_WASM_TYPE_INDEX_LEB,
  2417. R_WASM_GLOBAL_INDEX_LEB,
  2418. R_WASM_TAG_INDEX_LEB]) then
  2419. begin
  2420. InputError('Unsupported relocation type: ' + tostr(RelocType));
  2421. exit;
  2422. end;
  2423. if not ReadUleb32(RelocOffset) then
  2424. begin
  2425. InputError('Error reading the relocation offset of a relocation entry');
  2426. exit;
  2427. end;
  2428. if not ReadUleb32(RelocIndex) then
  2429. begin
  2430. InputError('Error reading the relocation index of a relocation entry');
  2431. exit;
  2432. end;
  2433. if TWasmRelocationType(RelocType) in [R_WASM_FUNCTION_OFFSET_I32,R_WASM_SECTION_OFFSET_I32,R_WASM_MEMORY_ADDR_LEB,R_WASM_MEMORY_ADDR_SLEB,R_WASM_MEMORY_ADDR_I32] then
  2434. begin
  2435. if not ReadSleb32(RelocAddend) then
  2436. begin
  2437. InputError('Error reading the relocation addend of a relocation entry');
  2438. exit;
  2439. end;
  2440. end;
  2441. end;
  2442. if AReader.Pos<>(SectionStart+SectionSize) then
  2443. begin
  2444. InputError('Unexpected relocation section size');
  2445. exit;
  2446. end;
  2447. Result:=True;
  2448. end;
  2449. function ReadLinkingSection: Boolean;
  2450. function ReadSegmentInfo: Boolean;
  2451. var
  2452. SegmentCount: uint32;
  2453. i: Integer;
  2454. begin
  2455. Result:=False;
  2456. if SegmentInfoSectionRead then
  2457. begin
  2458. InputError('The WASM_SEGMENT_INFO subsection is duplicated');
  2459. exit;
  2460. end;
  2461. SegmentInfoSectionRead:=True;
  2462. if not ReadUleb32(SegmentCount) then
  2463. begin
  2464. InputError('Error reading the segment count from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2465. exit;
  2466. end;
  2467. if SegmentCount<>Length(DataSegments) then
  2468. begin
  2469. InputError('Segment count in the WASM_SEGMENT_INFO subsection does not match the data count in the data section');
  2470. exit;
  2471. end;
  2472. for i:=0 to SegmentCount-1 do
  2473. with DataSegments[i] do
  2474. begin
  2475. if not ReadName(SegName) then
  2476. begin
  2477. InputError('Error reading segment name from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2478. exit;
  2479. end;
  2480. if not ReadUleb32(SegAlignment) then
  2481. begin
  2482. InputError('Error reading segment alignment from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2483. exit;
  2484. end;
  2485. if not ReadUleb32(SegFlags) then
  2486. begin
  2487. InputError('Error reading segment flags from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2488. exit;
  2489. end;
  2490. end;
  2491. if AReader.Pos<>(SectionStart+SectionSize) then
  2492. begin
  2493. InputError('Unexpected WASM_SEGMENT_INFO section size');
  2494. exit;
  2495. end;
  2496. Result:=True;
  2497. end;
  2498. function ReadSymbolTable: Boolean;
  2499. var
  2500. SymCount: uint32;
  2501. i: Integer;
  2502. SymKindName: string;
  2503. begin
  2504. Result:=False;
  2505. if SymbolTableSectionRead then
  2506. begin
  2507. InputError('The WASM_SYMBOL_TABLE subsection is duplicated');
  2508. exit;
  2509. end;
  2510. SymbolTableSectionRead:=True;
  2511. if not ReadUleb32(SymCount) then
  2512. begin
  2513. InputError('Error reading the symbol count from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2514. exit;
  2515. end;
  2516. SetLength(SymbolTable,SymCount);
  2517. for i:=0 to SymCount-1 do
  2518. with SymbolTable[i] do
  2519. begin
  2520. if not Read(SymKind,1) then
  2521. begin
  2522. InputError('Error reading symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2523. exit;
  2524. end;
  2525. if not ReadUleb32(SymFlags) then
  2526. begin
  2527. InputError('Error reading symbol flags from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2528. exit;
  2529. end;
  2530. case SymKind of
  2531. byte(SYMTAB_FUNCTION),
  2532. byte(SYMTAB_GLOBAL),
  2533. byte(SYMTAB_EVENT),
  2534. byte(SYMTAB_TABLE):
  2535. begin
  2536. WriteStr(SymKindName, TWasmSymbolType(SymKind));
  2537. if not ReadUleb32(SymIndex) then
  2538. begin
  2539. InputError('Error reading the index of a ' + SymKindName + ' symbol');
  2540. exit;
  2541. end;
  2542. if ((SymKind=byte(SYMTAB_FUNCTION)) and (SymIndex>high(FuncTypes))) then
  2543. begin
  2544. InputError('Symbol index too high');
  2545. exit;
  2546. end;
  2547. if ((SymFlags and WASM_SYM_EXPLICIT_NAME)<>0) or
  2548. ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  2549. begin
  2550. if not ReadName(SymName) then
  2551. begin
  2552. InputError('Error reading symbol name of a ' + SymKindName + ' symbol');
  2553. exit;
  2554. end;
  2555. end;
  2556. end;
  2557. byte(SYMTAB_DATA):
  2558. begin
  2559. if not ReadName(SymName) then
  2560. begin
  2561. InputError('Error reading symbol name of a SYMTAB_DATA symbol');
  2562. exit;
  2563. end;
  2564. if (SymFlags and WASM_SYM_UNDEFINED)=0 then
  2565. begin
  2566. if not ReadUleb32(SymIndex) then
  2567. begin
  2568. InputError('Error reading the data segment index of a SYMTAB_DATA symbol');
  2569. exit;
  2570. end;
  2571. if SymIndex>high(DataSegments) then
  2572. begin
  2573. InputError('Data segment index of SYMTAB_DATA symbol out of bounds');
  2574. exit;
  2575. end;
  2576. if not ReadUleb32(SymOffset) then
  2577. begin
  2578. InputError('Error reading the offset of a SYMTAB_DATA symbol');
  2579. exit;
  2580. end;
  2581. if not ReadUleb32(SymSize) then
  2582. begin
  2583. InputError('Error reading the size of a SYMTAB_DATA symbol');
  2584. exit;
  2585. end;
  2586. end;
  2587. end;
  2588. byte(SYMTAB_SECTION):
  2589. begin
  2590. if not ReadUleb32(TargetSection) then
  2591. begin
  2592. InputError('Error reading the target section of a SYMTAB_SECTION symbol');
  2593. exit;
  2594. end;
  2595. end;
  2596. else
  2597. begin
  2598. InputError('Unsupported symbol kind: ' + tostr(SymKind));
  2599. exit;
  2600. end;
  2601. end;
  2602. end;
  2603. if AReader.Pos<>(SectionStart+SectionSize) then
  2604. begin
  2605. InputError('Unexpected WASM_SYMBOL_TABLE section size');
  2606. exit;
  2607. end;
  2608. Result:=True;
  2609. end;
  2610. const
  2611. ExpectedVersion = 2;
  2612. var
  2613. Version, SubsectionSize, SaveSectionSize: uint32;
  2614. SubsectionType: Byte;
  2615. SaveSectionStart: LongInt;
  2616. begin
  2617. Result:=False;
  2618. if not ReadUleb32(Version) then
  2619. begin
  2620. InputError('Error reading the version of the ''linking'' section');
  2621. exit;
  2622. end;
  2623. if Version<>ExpectedVersion then
  2624. begin
  2625. InputError('The ''linking'' section has an unsupported version (expected version ' + tostr(ExpectedVersion) + ', got version ' + tostr(Version) + ')');
  2626. exit;
  2627. end;
  2628. while AReader.Pos<(SectionStart+SectionSize) do
  2629. begin
  2630. if not read(SubsectionType, 1) then
  2631. begin
  2632. InputError('Error reading subsection type in the ''linking'' section');
  2633. exit;
  2634. end;
  2635. if not ReadUleb32(SubsectionSize) then
  2636. begin
  2637. InputError('Error reading subsection size in the ''linking'' section');
  2638. exit;
  2639. end;
  2640. if (AReader.Pos+SubsectionSize)>(SectionStart+SectionSize) then
  2641. begin
  2642. InputError('Subsection size exceeds bounds of its parent ''linking'' section');
  2643. exit;
  2644. end;
  2645. SaveSectionStart:=SectionStart;
  2646. SaveSectionSize:=SectionSize;
  2647. SectionStart:=AReader.Pos;
  2648. SectionSize:=SubsectionSize;
  2649. case SubsectionType of
  2650. Byte(WASM_SEGMENT_INFO):
  2651. if not ReadSegmentInfo then
  2652. begin
  2653. InputError('Error reading the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2654. exit;
  2655. end;
  2656. Byte(WASM_SYMBOL_TABLE):
  2657. if not ReadSymbolTable then
  2658. begin
  2659. InputError('Error reading the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2660. exit;
  2661. end;
  2662. else
  2663. begin
  2664. InputError('Unsupported ''linking'' section subsection type ' + tostr(SubsectionType));
  2665. exit;
  2666. end;
  2667. end;
  2668. AReader.Seek(SectionStart+SectionSize);
  2669. SectionStart:=SaveSectionStart;
  2670. SectionSize:=SaveSectionSize;
  2671. end;
  2672. result:=True;
  2673. end;
  2674. function ReadProducersSection: Boolean;
  2675. begin
  2676. Result:=False;
  2677. end;
  2678. function ReadTargetFeaturesSection: Boolean;
  2679. begin
  2680. Result:=False;
  2681. end;
  2682. const
  2683. RelocationSectionPrefix = 'reloc.';
  2684. var
  2685. SectionName: ansistring;
  2686. begin
  2687. Result:=False;
  2688. ReadName(SectionName);
  2689. if Copy(SectionName,1,Length(RelocationSectionPrefix)) = RelocationSectionPrefix then
  2690. begin
  2691. if not ReadRelocationSection then
  2692. begin
  2693. InputError('Error reading the relocation section ''' + SectionName + '''');
  2694. exit;
  2695. end;
  2696. end
  2697. else
  2698. case SectionName of
  2699. 'linking':
  2700. if not ReadLinkingSection then
  2701. begin
  2702. InputError('Error reading the ''linking'' section');
  2703. exit;
  2704. end;
  2705. 'producers':
  2706. Result:=ReadProducersSection;
  2707. 'target_features':
  2708. Result:=ReadTargetFeaturesSection;
  2709. else
  2710. InputError('Unsupported custom section: ''' + SectionName + '''');
  2711. end;
  2712. Result:=True;
  2713. end;
  2714. function ReadTypeSection: Boolean;
  2715. var
  2716. FuncTypesCount, ParamsCount, ResultsCount: uint32;
  2717. FuncTypeId, WasmTypeId: Byte;
  2718. i, j: Integer;
  2719. wbt: TWasmBasicType;
  2720. begin
  2721. Result:=False;
  2722. if TypeSectionRead then
  2723. begin
  2724. InputError('Type section is duplicated');
  2725. exit;
  2726. end;
  2727. TypeSectionRead:=True;
  2728. if not ReadUleb32(FuncTypesCount) then
  2729. begin
  2730. InputError('Error reading the func types count');
  2731. exit;
  2732. end;
  2733. SetLength(FFuncTypes,FuncTypesCount);
  2734. for i:=0 to FuncTypesCount - 1 do
  2735. begin
  2736. FFuncTypes[i]:=TWasmFuncType.Create([],[]);
  2737. if not AReader.read(FuncTypeId,1) then
  2738. begin
  2739. InputError('Error reading the function type identifier');
  2740. exit;
  2741. end;
  2742. if FuncTypeId<>$60 then
  2743. begin
  2744. InputError('Incorrect function type identifier (expected $60, got $' + HexStr(FuncTypeId,2) + ')');
  2745. exit;
  2746. end;
  2747. if not ReadUleb32(ParamsCount) then
  2748. begin
  2749. InputError('Error reading the function parameters count');
  2750. exit;
  2751. end;
  2752. for j:=0 to ParamsCount-1 do
  2753. begin
  2754. if not AReader.read(WasmTypeId,1) then
  2755. begin
  2756. InputError('Error reading a function parameter basic type');
  2757. exit;
  2758. end;
  2759. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2760. begin
  2761. InputError('Unknown function parameter basic type: $' + HexStr(WasmTypeId,2));
  2762. exit;
  2763. end;
  2764. FFuncTypes[i].add_param(wbt);
  2765. end;
  2766. if not ReadUleb32(ResultsCount) then
  2767. begin
  2768. InputError('Error reading the function results count');
  2769. exit;
  2770. end;
  2771. for j:=0 to ResultsCount-1 do
  2772. begin
  2773. if not AReader.read(WasmTypeId,1) then
  2774. begin
  2775. InputError('Error reading a function result basic type');
  2776. exit;
  2777. end;
  2778. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2779. begin
  2780. InputError('Unknown function result basic type: $' + HexStr(WasmTypeId,2));
  2781. exit;
  2782. end;
  2783. FFuncTypes[i].add_result(wbt);
  2784. end;
  2785. end;
  2786. if AReader.Pos<>(SectionStart+SectionSize) then
  2787. begin
  2788. InputError('Unexpected type section size');
  2789. exit;
  2790. end;
  2791. Result:=true;
  2792. end;
  2793. function ReadImportSection: Boolean;
  2794. var
  2795. ImportsCount: uint32;
  2796. i: Integer;
  2797. ModName, Name: ansistring;
  2798. ImportType, TableElemTyp, TableLimitsKind, MemoryLimitsKind,
  2799. GlobalType, GlobalMutabilityType: Byte;
  2800. begin
  2801. Result:=False;
  2802. if ImportSectionRead then
  2803. begin
  2804. InputError('Import section is duplicated');
  2805. exit;
  2806. end;
  2807. ImportSectionRead:=True;
  2808. if not ReadUleb32(ImportsCount) then
  2809. begin
  2810. InputError('Error reading the imports count');
  2811. exit;
  2812. end;
  2813. for i:=0 to ImportsCount-1 do
  2814. begin
  2815. if not ReadName(ModName) then
  2816. begin
  2817. InputError('Error reading import module name');
  2818. exit;
  2819. end;
  2820. if not ReadName(Name) then
  2821. begin
  2822. InputError('Error import name');
  2823. exit;
  2824. end;
  2825. if not AReader.Read(ImportType,1) then
  2826. begin
  2827. InputError('Error reading import type');
  2828. exit;
  2829. end;
  2830. case ImportType of
  2831. $00: { func }
  2832. begin
  2833. Inc(FuncTypeImportsCount);
  2834. SetLength(FuncTypes,FuncTypeImportsCount);
  2835. with FuncTypes[FuncTypeImportsCount-1] do
  2836. begin
  2837. IsImport:=True;
  2838. ImportName:=Name;
  2839. ImportModName:=ModName;
  2840. if not ReadUleb32(typidx) then
  2841. begin
  2842. InputError('Error reading type index for func import');
  2843. exit;
  2844. end;
  2845. if typidx>high(FFuncTypes) then
  2846. begin
  2847. InputError('Type index in func import exceeds bounds of the types table');
  2848. exit;
  2849. end;
  2850. end;
  2851. end;
  2852. $01: { table }
  2853. begin
  2854. Inc(TableTypeImportsCount);
  2855. SetLength(TableTypes,TableTypeImportsCount);
  2856. with TableTypes[TableTypeImportsCount-1] do
  2857. begin
  2858. IsImport:=True;
  2859. ImportName:=Name;
  2860. ImportModName:=ModName;
  2861. if not AReader.read(TableElemTyp,1) then
  2862. begin
  2863. InputError('Error reading table element type for table import');
  2864. exit;
  2865. end;
  2866. if not decode_wasm_basic_type(TableElemTyp,reftype) then
  2867. begin
  2868. InputError('Invalid table element type for table import: $' + HexStr(TableElemTyp,2));
  2869. exit;
  2870. end;
  2871. if not (reftype in WasmReferenceTypes) then
  2872. begin
  2873. InputError('Table element type for table import must be a reference type');
  2874. exit;
  2875. end;
  2876. if not AReader.read(TableLimitsKind,1) then
  2877. begin
  2878. InputError('Error reading table limits kind for table import');
  2879. exit;
  2880. end;
  2881. case TableLimitsKind of
  2882. $00:
  2883. begin
  2884. limits.HasMax:=False;
  2885. limits.Max:=high(limits.Max);
  2886. if not ReadUleb32(limits.min) then
  2887. begin
  2888. InputError('Error reading table limits min for table import');
  2889. exit;
  2890. end;
  2891. end;
  2892. $01:
  2893. begin
  2894. limits.HasMax:=True;
  2895. if not ReadUleb32(limits.min) then
  2896. begin
  2897. InputError('Error reading table limits min for table import');
  2898. exit;
  2899. end;
  2900. if not ReadUleb32(limits.max) then
  2901. begin
  2902. InputError('Error reading table limits max for table import');
  2903. exit;
  2904. end;
  2905. if limits.min>limits.max then
  2906. begin
  2907. InputError('Table limits min exceed table limits max in table import');
  2908. exit;
  2909. end;
  2910. end;
  2911. else
  2912. begin
  2913. InputError('Unsupported table limits kind for table import: $' + HexStr(TableLimitsKind,2));
  2914. exit;
  2915. end;
  2916. end;
  2917. end;
  2918. end;
  2919. $02: { mem }
  2920. begin
  2921. Inc(MemTypeImportsCount);
  2922. SetLength(MemTypes,MemTypeImportsCount);
  2923. with MemTypes[MemTypeImportsCount-1] do
  2924. begin
  2925. IsImport:=True;
  2926. ImportName:=Name;
  2927. ImportModName:=ModName;
  2928. if not AReader.read(MemoryLimitsKind,1) then
  2929. begin
  2930. InputError('Error reading memory limits kind for memory import');
  2931. exit;
  2932. end;
  2933. case MemoryLimitsKind of
  2934. $00:
  2935. begin
  2936. limits.HasMax:=False;
  2937. limits.Max:=high(limits.Max);
  2938. if not ReadUleb32(limits.min) then
  2939. begin
  2940. InputError('Error reading memory limits min for memory import');
  2941. exit;
  2942. end;
  2943. end;
  2944. $01:
  2945. begin
  2946. limits.HasMax:=True;
  2947. if not ReadUleb32(limits.min) then
  2948. begin
  2949. InputError('Error reading memory limits min for memory import');
  2950. exit;
  2951. end;
  2952. if not ReadUleb32(limits.max) then
  2953. begin
  2954. InputError('Error reading memory limits max for memory import');
  2955. exit;
  2956. end;
  2957. if limits.Min>limits.Max then
  2958. begin
  2959. InputError('Memory limits min exceed memory limits max in memory import');
  2960. exit;
  2961. end;
  2962. end;
  2963. else
  2964. begin
  2965. InputError('Unsupported memory limits kind for memory import: $' + HexStr(MemoryLimitsKind,2));
  2966. exit;
  2967. end;
  2968. end;
  2969. end;
  2970. end;
  2971. $03: { global }
  2972. begin
  2973. Inc(GlobalTypeImportsCount);
  2974. SetLength(GlobalTypes,GlobalTypeImportsCount);
  2975. with GlobalTypes[GlobalTypeImportsCount-1] do
  2976. begin
  2977. IsImport:=True;
  2978. ImportName:=Name;
  2979. ImportModName:=ModName;
  2980. if not AReader.read(GlobalType,1) then
  2981. begin
  2982. InputError('Error reading global type for global import');
  2983. exit;
  2984. end;
  2985. if not decode_wasm_basic_type(GlobalType,valtype) then
  2986. begin
  2987. InputError('Unsupported global type for global import: ' + HexStr(GlobalType,2));
  2988. exit;
  2989. end;
  2990. if not AReader.read(GlobalMutabilityType,1) then
  2991. begin
  2992. InputError('Error reading global mutability flag for global import');
  2993. exit;
  2994. end;
  2995. case GlobalMutabilityType of
  2996. $00:
  2997. IsMutable:=False;
  2998. $01:
  2999. IsMutable:=True;
  3000. else
  3001. begin
  3002. InputError('Unknown global mutability flag for global import: $' + HexStr(GlobalMutabilityType,2));
  3003. exit;
  3004. end;
  3005. end;
  3006. end;
  3007. end;
  3008. else
  3009. begin
  3010. InputError('Unknown import type: $' + HexStr(ImportType,2));
  3011. exit;
  3012. end;
  3013. end;
  3014. end;
  3015. if AReader.Pos<>(SectionStart+SectionSize) then
  3016. begin
  3017. InputError('Unexpected import section size');
  3018. exit;
  3019. end;
  3020. Result:=true;
  3021. end;
  3022. function ReadFunctionSection: Boolean;
  3023. var
  3024. FunctionsCount: uint32;
  3025. i: Integer;
  3026. begin
  3027. Result:=False;
  3028. if FunctionSectionRead then
  3029. begin
  3030. InputError('Function section is duplicated');
  3031. exit;
  3032. end;
  3033. FunctionSectionRead:=True;
  3034. if not ReadUleb32(FunctionsCount) then
  3035. begin
  3036. InputError('Error reading the functions count');
  3037. exit;
  3038. end;
  3039. SetLength(FuncTypes, FuncTypeImportsCount + FunctionsCount);
  3040. for i:=0 to FunctionsCount-1 do
  3041. with FuncTypes[i + FuncTypeImportsCount] do
  3042. begin
  3043. IsImport:=False;
  3044. if not ReadUleb32(typidx) then
  3045. begin
  3046. InputError('Error reading type index for function');
  3047. exit;
  3048. end;
  3049. if typidx>high(FFuncTypes) then
  3050. begin
  3051. InputError('Type index in the function section exceeds bounds of the types table');
  3052. exit;
  3053. end;
  3054. end;
  3055. if AReader.Pos<>(SectionStart+SectionSize) then
  3056. begin
  3057. InputError('Unexpected function section size');
  3058. exit;
  3059. end;
  3060. Result:=true;
  3061. end;
  3062. function ReadGlobalSection: Boolean;
  3063. function ParseExpr(out Init: TGlobalInitializer): Boolean;
  3064. var
  3065. B, B2: Byte;
  3066. tmpU32: UInt32;
  3067. tmpU64: UInt64;
  3068. begin
  3069. Result:=False;
  3070. repeat
  3071. if not Read(B, 1) then
  3072. exit;
  3073. case B of
  3074. $0B: { end }
  3075. ;
  3076. $41: { i32.const }
  3077. begin
  3078. Init.typ:=wbt_i32;
  3079. if not ReadSleb32(Init.init_i32) then
  3080. exit;
  3081. end;
  3082. $42: { i64.const }
  3083. begin
  3084. Init.typ:=wbt_i64;
  3085. if not ReadSleb(Init.init_i64) then
  3086. exit;
  3087. end;
  3088. $43: { f32.const }
  3089. begin
  3090. Init.typ:=wbt_f32;
  3091. if not Read(tmpU32, 4) then
  3092. exit;
  3093. {$ifdef FPC_BIG_ENDIAN}
  3094. tmpU32:=SwapEndian(tmpU32);
  3095. {$endif FPC_BIG_ENDIAN}
  3096. Move(tmpU32,Init.init_f32,4);
  3097. end;
  3098. $44: { f64.const }
  3099. begin
  3100. Init.typ:=wbt_f64;
  3101. if not Read(tmpU64, 8) then
  3102. exit;
  3103. {$ifdef FPC_BIG_ENDIAN}
  3104. tmpU64:=SwapEndian(tmpU64);
  3105. {$endif FPC_BIG_ENDIAN}
  3106. Move(tmpU64,Init.init_f64,8);
  3107. end;
  3108. $D0: { ref.null }
  3109. begin
  3110. if not Read(B2, 1) then
  3111. exit;
  3112. if not decode_wasm_basic_type(B2, Init.typ) then
  3113. exit;
  3114. if not (Init.typ in WasmReferenceTypes) then
  3115. exit;
  3116. end;
  3117. else
  3118. begin
  3119. InputError('Unsupported opcode in global initializer');
  3120. exit;
  3121. end;
  3122. end;
  3123. until b = $0B;
  3124. Result:=True;
  3125. end;
  3126. var
  3127. GlobalsCount: uint32;
  3128. i: Integer;
  3129. vt: Byte;
  3130. mut: Byte;
  3131. begin
  3132. Result:=False;
  3133. if GlobalSectionRead then
  3134. begin
  3135. InputError('Global section is duplicated');
  3136. exit;
  3137. end;
  3138. GlobalSectionRead:=True;
  3139. if not ReadUleb32(GlobalsCount) then
  3140. begin
  3141. InputError('Error reading the globals count from the global section');
  3142. exit;
  3143. end;
  3144. SetLength(GlobalTypes,Length(GlobalTypes)+GlobalsCount);
  3145. for i:=0 to GlobalsCount-1 do
  3146. with GlobalTypes[i + GlobalTypeImportsCount] do
  3147. begin
  3148. if not read(vt,1) then
  3149. begin
  3150. InputError('Error reading the type of a global from the global section');
  3151. exit;
  3152. end;
  3153. if not decode_wasm_basic_type(vt,valtype) then
  3154. begin
  3155. InputError('Unsupported type of global in the global section');
  3156. exit;
  3157. end;
  3158. if not read(mut,1) then
  3159. begin
  3160. InputError('Error reading the mutability flag of a global in the global section');
  3161. exit;
  3162. end;
  3163. case mut of
  3164. $00:
  3165. IsMutable:=False;
  3166. $01:
  3167. IsMutable:=True;
  3168. else
  3169. begin
  3170. InputError('Unsupported value (' + tostr(mut) + ') for the mutability flag of a global in the global section');
  3171. exit;
  3172. end;
  3173. end;
  3174. if not ParseExpr(GlobalInit) then
  3175. begin
  3176. InputError('Error parsing the global initializer expression in the global section');
  3177. exit;
  3178. end;
  3179. if GlobalInit.typ<>valtype then
  3180. begin
  3181. InputError('Initializer expression for global produces a type, which does not match the type of the global');
  3182. exit;
  3183. end;
  3184. end;
  3185. if AReader.Pos<>(SectionStart+SectionSize) then
  3186. begin
  3187. InputError('Unexpected global section size');
  3188. exit;
  3189. end;
  3190. Result:=True;
  3191. end;
  3192. function ReadExportSection: Boolean;
  3193. var
  3194. ExportsCount, FuncIdx, TableIdx, MemIdx, GlobalIdx: uint32;
  3195. i: Integer;
  3196. Name: ansistring;
  3197. ExportType: Byte;
  3198. begin
  3199. Result:=False;
  3200. if ExportSectionRead then
  3201. begin
  3202. InputError('Export section is duplicated');
  3203. exit;
  3204. end;
  3205. ExportSectionRead:=True;
  3206. if not ReadUleb32(ExportsCount) then
  3207. begin
  3208. InputError('Error reading the exports count from the export section');
  3209. exit;
  3210. end;
  3211. for i:=0 to ExportsCount-1 do
  3212. begin
  3213. if not ReadName(Name) then
  3214. begin
  3215. InputError('Error reading an export name from the export section');
  3216. exit;
  3217. end;
  3218. if not Read(ExportType,1) then
  3219. begin
  3220. InputError('Error reading an export type from the export section');
  3221. exit;
  3222. end;
  3223. case ExportType of
  3224. $00: { func }
  3225. begin
  3226. if not ReadUleb32(FuncIdx) then
  3227. begin
  3228. InputError('Error reading a func index from the export section');
  3229. exit;
  3230. end;
  3231. if FuncIdx>high(FuncTypes) then
  3232. begin
  3233. InputError('Func index too high in the export section');
  3234. exit;
  3235. end;
  3236. with FuncTypes[FuncIdx] do
  3237. begin
  3238. IsExported:=True;
  3239. ExportName:=Name;
  3240. end;
  3241. end;
  3242. $01: { table }
  3243. begin
  3244. if not ReadUleb32(TableIdx) then
  3245. begin
  3246. InputError('Error reading a table index from the export section');
  3247. exit;
  3248. end;
  3249. if TableIdx>high(TableTypes) then
  3250. begin
  3251. InputError('Table index too high in the export section');
  3252. exit;
  3253. end;
  3254. with TableTypes[TableIdx] do
  3255. begin
  3256. IsExported:=True;
  3257. ExportName:=Name;
  3258. end;
  3259. end;
  3260. $02: { mem }
  3261. begin
  3262. if not ReadUleb32(MemIdx) then
  3263. begin
  3264. InputError('Error reading a mem index from the export section');
  3265. exit;
  3266. end;
  3267. if MemIdx>high(MemTypes) then
  3268. begin
  3269. InputError('Mem index too high in the export section');
  3270. exit;
  3271. end;
  3272. with MemTypes[MemIdx] do
  3273. begin
  3274. IsExported:=True;
  3275. ExportName:=Name;
  3276. end;
  3277. end;
  3278. $03: { global }
  3279. begin
  3280. if not ReadUleb32(GlobalIdx) then
  3281. begin
  3282. InputError('Error reading a global index from the export section');
  3283. exit;
  3284. end;
  3285. if GlobalIdx>high(GlobalTypes) then
  3286. begin
  3287. InputError('Global index too high in the export section');
  3288. exit;
  3289. end;
  3290. with GlobalTypes[GlobalIdx] do
  3291. begin
  3292. IsExported:=True;
  3293. ExportName:=Name;
  3294. end;
  3295. end;
  3296. else
  3297. begin
  3298. InputError('Unsupported export type in the export section: ' + tostr(ExportType));
  3299. exit;
  3300. end;
  3301. end;
  3302. end;
  3303. if AReader.Pos<>(SectionStart+SectionSize) then
  3304. begin
  3305. InputError('Unexpected export section size');
  3306. exit;
  3307. end;
  3308. Result:=True;
  3309. end;
  3310. function ReadCodeSection: Boolean;
  3311. var
  3312. CodeEntriesCount: uint32;
  3313. i: Integer;
  3314. begin
  3315. Result:=False;
  3316. if CodeSectionRead then
  3317. begin
  3318. InputError('Code section is duplicated');
  3319. exit;
  3320. end;
  3321. CodeSectionRead:=True;
  3322. CodeSectionIndex:=SectionIndex;
  3323. if not ReadUleb32(CodeEntriesCount) then
  3324. begin
  3325. InputError('Error reading the code entries cound from the code section');
  3326. exit;
  3327. end;
  3328. if CodeEntriesCount <> (Length(FuncTypes) - FuncTypeImportsCount) then
  3329. begin
  3330. InputError('Code segment count in the code section does not match the function definition count in the function section');
  3331. exit;
  3332. end;
  3333. SetLength(CodeSegments,CodeEntriesCount);
  3334. for i:=0 to CodeEntriesCount-1 do
  3335. with CodeSegments[i] do
  3336. begin
  3337. if not ReadUleb32(CodeSize) then
  3338. begin
  3339. InputError('Error reading the code size of an entry in the code section');
  3340. exit;
  3341. end;
  3342. if (AReader.Pos+CodeSize)>(SectionStart+SectionSize) then
  3343. begin
  3344. InputError('Code segment exceeds the bounds of the code section');
  3345. exit;
  3346. end;
  3347. DataPos:=AReader.Pos;
  3348. CodeSectionOffset:=AReader.Pos-SectionStart;
  3349. AReader.Seek(AReader.Pos+CodeSize);
  3350. end;
  3351. if AReader.Pos<>(SectionStart+SectionSize) then
  3352. begin
  3353. InputError('Unexpected code section size');
  3354. exit;
  3355. end;
  3356. Result:=true;
  3357. end;
  3358. function ReadDataSection: Boolean;
  3359. function ReadExpr(out ExprV: int32): Boolean;
  3360. var
  3361. b: Byte;
  3362. begin
  3363. Result:=False;
  3364. if not Read(b,1) then
  3365. exit;
  3366. if b<>$41 then
  3367. begin
  3368. InputError('Only i32.const expressions supported');
  3369. exit;
  3370. end;
  3371. if not ReadSleb32(ExprV) then
  3372. exit;
  3373. if not Read(b,1) then
  3374. exit;
  3375. if b<>$0B then
  3376. begin
  3377. InputError('Only single const expressions supported');
  3378. exit;
  3379. end;
  3380. Result:=True;
  3381. end;
  3382. var
  3383. DataCount: uint32;
  3384. DataType: Byte;
  3385. i: Integer;
  3386. begin
  3387. Result:=False;
  3388. if DataSectionRead then
  3389. begin
  3390. InputError('Data section is duplicated');
  3391. exit;
  3392. end;
  3393. DataSectionRead:=True;
  3394. DataSectionIndex:=SectionIndex;
  3395. if not ReadUleb32(DataCount) then
  3396. begin
  3397. InputError('Error reading the data entries count from the data section');
  3398. exit;
  3399. end;
  3400. if DataCountSectionRead then
  3401. begin
  3402. if Length(DataSegments)<>DataCount then
  3403. begin
  3404. InputError('Data entries count in the data section do not match the number, specified in the data count section');
  3405. exit;
  3406. end;
  3407. end
  3408. else
  3409. SetLength(DataSegments,DataCount);
  3410. for i:=0 to DataCount-1 do
  3411. with DataSegments[i] do
  3412. begin
  3413. if not read(DataType, 1) then
  3414. begin
  3415. InputError('Error reading data type of segment from the data section');
  3416. exit;
  3417. end;
  3418. case DataType of
  3419. 0:
  3420. begin
  3421. Active:=True;
  3422. MemIdx:=0;
  3423. if not ReadExpr(Offset) then
  3424. begin
  3425. InputError('Error reading memory offset of segment from the data section');
  3426. exit;
  3427. end;
  3428. end;
  3429. 1:
  3430. Active:=False;
  3431. 2:
  3432. begin
  3433. Active:=True;
  3434. if not ReadUleb32(MemIdx) then
  3435. begin
  3436. InputError('Error reading MemIdx of segment from the data section');
  3437. exit;
  3438. end;
  3439. if not ReadExpr(Offset) then
  3440. begin
  3441. InputError('Error reading memory offset of segment from the data section');
  3442. exit;
  3443. end;
  3444. end;
  3445. else
  3446. begin
  3447. InputError('Unsupported data type of segment in the data section: ' + tostr(DataType));
  3448. exit;
  3449. end;
  3450. end;
  3451. if MemIdx<>0 then
  3452. begin
  3453. InputError('Memory index other than 0 not supported (got ' + tostr(MemIdx) + ')');
  3454. exit;
  3455. end;
  3456. if not Active then
  3457. begin
  3458. InputError('Passive memory segments not supported');
  3459. exit;
  3460. end;
  3461. if not ReadUleb32(Len) then
  3462. begin
  3463. InputError('Error reading data segment length');
  3464. exit;
  3465. end;
  3466. if (AReader.Pos+Len)>(SectionStart+SectionSize) then
  3467. begin
  3468. InputError('Data segment exceeds the bounds of the data section');
  3469. exit;
  3470. end;
  3471. DataPos:=AReader.Pos;
  3472. DataSectionOffset:=AReader.Pos-SectionStart;
  3473. AReader.Seek(AReader.Pos+Len);
  3474. end;
  3475. if AReader.Pos<>(SectionStart+SectionSize) then
  3476. begin
  3477. InputError('Unexpected data section size');
  3478. exit;
  3479. end;
  3480. Result:=true;
  3481. end;
  3482. function ReadDataCountSection: Boolean;
  3483. var
  3484. DataCount: uint32;
  3485. begin
  3486. Result:=False;
  3487. if DataCountSectionRead then
  3488. begin
  3489. InputError('Data count section is duplicated');
  3490. exit;
  3491. end;
  3492. DataCountSectionRead:=True;
  3493. if DataSectionRead then
  3494. begin
  3495. InputError('The data count section must occur before the data section');
  3496. exit;
  3497. end;
  3498. if not ReadUleb32(DataCount) then
  3499. begin
  3500. InputError('Error reading the data count from the data count section');
  3501. exit;
  3502. end;
  3503. if AReader.Pos<>(SectionStart+SectionSize) then
  3504. begin
  3505. InputError('Unexpected data count section size');
  3506. exit;
  3507. end;
  3508. SetLength(DataSegments, DataCount);
  3509. Result:=true;
  3510. end;
  3511. begin
  3512. Result:=False;
  3513. Inc(SectionIndex);
  3514. if not AReader.read(SectionId,1) then
  3515. begin
  3516. InputError('Error reading section ID');
  3517. exit;
  3518. end;
  3519. CheckSectionBounds:=false;
  3520. if not ReadUleb32(SectionSize) then
  3521. begin
  3522. InputError('Error reading section size');
  3523. exit;
  3524. end;
  3525. if (AReader.Pos+SectionSize)>AReader.size then
  3526. begin
  3527. InputError('Section exceeds beyond the end of file');
  3528. exit;
  3529. end;
  3530. SectionStart:=AReader.Pos;
  3531. CheckSectionBounds:=true;
  3532. case SectionId of
  3533. Byte(wsiCustom):
  3534. if not ReadCustomSection then
  3535. begin
  3536. InputError('Error encountered, while reading a custom section');
  3537. exit;
  3538. end;
  3539. Byte(wsiType):
  3540. if not ReadTypeSection then
  3541. begin
  3542. InputError('Error reading the type section');
  3543. exit;
  3544. end;
  3545. Byte(wsiImport):
  3546. if not ReadImportSection then
  3547. begin
  3548. InputError('Error reading the import section');
  3549. exit;
  3550. end;
  3551. Byte(wsiFunction):
  3552. if not ReadFunctionSection then
  3553. begin
  3554. InputError('Error reading the function section');
  3555. exit;
  3556. end;
  3557. Byte(wsiGlobal):
  3558. if not ReadGlobalSection then
  3559. begin
  3560. InputError('Error reading the global section');
  3561. exit;
  3562. end;
  3563. Byte(wsiExport):
  3564. if not ReadExportSection then
  3565. begin
  3566. InputError('Error reading the export section');
  3567. exit;
  3568. end;
  3569. Byte(wsiCode):
  3570. if not ReadCodeSection then
  3571. begin
  3572. InputError('Error reading the code section');
  3573. exit;
  3574. end;
  3575. Byte(wsiData):
  3576. if not ReadDataSection then
  3577. begin
  3578. InputError('Error reading the data section');
  3579. exit;
  3580. end;
  3581. Byte(wsiDataCount):
  3582. begin
  3583. if not ReadDataCountSection then
  3584. begin
  3585. InputError('Error reading the data count section');
  3586. exit;
  3587. end;
  3588. end
  3589. else
  3590. begin
  3591. InputError('Unknown section: ' + ToStr(SectionId));
  3592. exit;
  3593. end;
  3594. end;
  3595. if SectionSize>0 then
  3596. AReader.seek(SectionStart+SectionSize);
  3597. Result:=True;
  3598. end;
  3599. function FindCodeSegment(Ofs: uint32): Integer;
  3600. var
  3601. L, R, M: Integer;
  3602. begin
  3603. L:=Low(CodeSegments);
  3604. R:=High(CodeSegments);
  3605. while L<=R do
  3606. begin
  3607. M:=(L+R) div 2;
  3608. if (CodeSegments[M].CodeSectionOffset+CodeSegments[M].CodeSize-1) < Ofs then
  3609. L:=M+1
  3610. else if CodeSegments[M].CodeSectionOffset > Ofs then
  3611. R:=M-1
  3612. else
  3613. begin
  3614. Result:=M;
  3615. exit;
  3616. end;
  3617. end;
  3618. Result:=-1;
  3619. end;
  3620. function FindDataSegment(Ofs: uint32): Integer;
  3621. var
  3622. L, R, M: Integer;
  3623. begin
  3624. L:=Low(DataSegments);
  3625. R:=High(DataSegments);
  3626. while L<=R do
  3627. begin
  3628. M:=(L+R) div 2;
  3629. if (DataSegments[M].DataSectionOffset+DataSegments[M].Len-1) < Ofs then
  3630. L:=M+1
  3631. else if DataSegments[M].DataSectionOffset > Ofs then
  3632. R:=M-1
  3633. else
  3634. begin
  3635. Result:=M;
  3636. exit;
  3637. end;
  3638. end;
  3639. Result:=-1;
  3640. end;
  3641. var
  3642. ModuleMagic: array [0..3] of Byte;
  3643. ModuleVersion: array [0..3] of Byte;
  3644. i, j, FirstDataSegmentIdx, SegI: Integer;
  3645. CurrSec, ObjSec: TObjSection;
  3646. BaseSectionOffset: UInt32;
  3647. ObjReloc: TWasmObjRelocation;
  3648. begin
  3649. FReader:=AReader;
  3650. InputFileName:=AReader.FileName;
  3651. objdata:=CObjData.Create(InputFileName);
  3652. result:=false;
  3653. CodeSegments:=nil;
  3654. DataSegments:=nil;
  3655. SymbolTable:=nil;
  3656. RelocationTable:=nil;
  3657. SetLength(RelocationTable,2);
  3658. FuncTypes:=nil;
  3659. FuncTypeImportsCount:=0;
  3660. TableTypes:=nil;
  3661. TableTypeImportsCount:=0;
  3662. MemTypes:=nil;
  3663. MemTypeImportsCount:=0;
  3664. GlobalTypes:=nil;
  3665. GlobalTypeImportsCount:=0;
  3666. if not AReader.read(ModuleMagic,4) then
  3667. exit;
  3668. for i:=0 to 3 do
  3669. if ModuleMagic[i]<>WasmModuleMagic[i] then
  3670. exit;
  3671. if not AReader.read(ModuleVersion,4) then
  3672. exit;
  3673. for i:=0 to 3 do
  3674. if ModuleVersion[i]<>WasmVersion[i] then
  3675. exit;
  3676. while AReader.Pos<AReader.size do
  3677. if not ReadSection then
  3678. exit;
  3679. { fill the code segment names }
  3680. for i:=low(SymbolTable) to high(SymbolTable) do
  3681. with SymbolTable[i] do
  3682. if (SymKind=byte(SYMTAB_FUNCTION)) and ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  3683. begin
  3684. if FuncTypes[SymIndex].IsImport then
  3685. begin
  3686. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_FUNCTION symbol, that is an import');
  3687. exit;
  3688. end;
  3689. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  3690. begin
  3691. with CodeSegments[SymIndex-FuncTypeImportsCount] do
  3692. begin
  3693. SegName:='.text.n_'+SymName;
  3694. SegIsExported:=FuncTypes[SymIndex].IsExported;
  3695. end;
  3696. end;
  3697. end;
  3698. { create segments }
  3699. for i:=low(CodeSegments) to high(CodeSegments) do
  3700. with CodeSegments[i] do
  3701. begin
  3702. if SegName='' then
  3703. begin
  3704. InputError('Code section ' + tostr(i) + ' does not have a main symbol defined in the symbol table');
  3705. exit;
  3706. end;
  3707. if SegIsExported then
  3708. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load,oso_keep],false)
  3709. else
  3710. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load],false);
  3711. CurrSec.DataPos:=DataPos;
  3712. CurrSec.Size:=CodeSize;
  3713. end;
  3714. FirstDataSegmentIdx:=ObjData.ObjSectionList.Count;
  3715. for i:=low(DataSegments) to high(DataSegments) do
  3716. with DataSegments[i] do
  3717. if Active then
  3718. begin
  3719. CurrSec:=ObjData.createsection(SegName,1 shl SegAlignment,[oso_Data,oso_load,oso_write],false);
  3720. CurrSec.DataPos:=DataPos;
  3721. CurrSec.MemPos:=Offset;
  3722. CurrSec.Size:=Len;
  3723. end;
  3724. ReadSectionContent(ObjData);
  3725. for i:=low(SymbolTable) to high(SymbolTable) do
  3726. with SymbolTable[i] do
  3727. case SymKind of
  3728. byte(SYMTAB_DATA):
  3729. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3730. begin
  3731. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3732. objsym.bind:=AB_EXTERNAL;
  3733. objsym.typ:=AT_DATA;
  3734. objsym.objsection:=nil;
  3735. objsym.offset:=0;
  3736. objsym.size:=0;
  3737. end
  3738. else
  3739. begin
  3740. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3741. if (SymFlags and WASM_SYM_BINDING_LOCAL)<> 0 then
  3742. objsym.bind:=AB_LOCAL
  3743. else
  3744. objsym.bind:=AB_GLOBAL;
  3745. objsym.typ:=AT_DATA;
  3746. objsym.objsection:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SymIndex]);
  3747. objsym.offset:=SymOffset;
  3748. objsym.size:=SymSize;
  3749. end;
  3750. byte(SYMTAB_FUNCTION):
  3751. begin
  3752. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3753. begin
  3754. if not FuncTypes[SymIndex].IsImport then
  3755. begin
  3756. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_FUNCTION symbol, that is not an import');
  3757. exit;
  3758. end;
  3759. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  3760. begin
  3761. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3762. objsym.bind:=AB_EXTERNAL;
  3763. objsym.typ:=AT_FUNCTION;
  3764. objsym.objsection:=nil;
  3765. objsym.offset:=0;
  3766. objsym.size:=0;
  3767. objsym.LinkingData.ImportModule:=FuncTypes[SymIndex].ImportModName;
  3768. objsym.LinkingData.ImportName:=FuncTypes[SymIndex].ImportName;
  3769. end
  3770. else
  3771. begin
  3772. if FuncTypes[SymIndex].ImportModName = 'env' then
  3773. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportName))
  3774. else
  3775. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportModName + '.' + FuncTypes[SymIndex].ImportName));
  3776. objsym.bind:=AB_EXTERNAL;
  3777. objsym.typ:=AT_FUNCTION;
  3778. objsym.objsection:=nil;
  3779. objsym.offset:=0;
  3780. objsym.size:=0;
  3781. end;
  3782. end
  3783. else
  3784. begin
  3785. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3786. objsym.bind:=AB_GLOBAL;
  3787. objsym.typ:=AT_FUNCTION;
  3788. objsym.objsection:=TObjSection(ObjData.ObjSectionList[SymIndex-FuncTypeImportsCount]);
  3789. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  3790. TWasmObjSection(ObjData.ObjSectionList[SymIndex-FuncTypeImportsCount]).MainFuncSymbol:=objsym;
  3791. objsym.offset:=0;
  3792. objsym.size:=objsym.objsection.Size;
  3793. end;
  3794. objsym.LinkingData.FuncType:=TWasmFuncType.Create(FFuncTypes[FuncTypes[SymIndex].typidx]);
  3795. objsym.LinkingData.IsExported:=FuncTypes[SymIndex].IsExported;
  3796. objsym.LinkingData.ExportName:=FuncTypes[SymIndex].ExportName;
  3797. end;
  3798. byte(SYMTAB_GLOBAL):
  3799. begin
  3800. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3801. begin
  3802. if not GlobalTypes[SymIndex].IsImport then
  3803. begin
  3804. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_GLOBAL symbol, that is not an import');
  3805. exit;
  3806. end;
  3807. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  3808. begin
  3809. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3810. objsym.bind:=AB_EXTERNAL;
  3811. objsym.typ:=AT_WASM_GLOBAL;
  3812. objsym.objsection:=nil;
  3813. objsym.offset:=0;
  3814. objsym.size:=1;
  3815. objsym.LinkingData.ImportModule:=GlobalTypes[SymIndex].ImportModName;
  3816. objsym.LinkingData.ImportName:=GlobalTypes[SymIndex].ImportName;
  3817. end
  3818. else
  3819. begin
  3820. if GlobalTypes[SymIndex].ImportModName = 'env' then
  3821. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportName))
  3822. else
  3823. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportModName + '.' + GlobalTypes[SymIndex].ImportName));
  3824. objsym.bind:=AB_EXTERNAL;
  3825. objsym.typ:=AT_WASM_GLOBAL;
  3826. objsym.objsection:=nil;
  3827. objsym.offset:=0;
  3828. objsym.size:=1;
  3829. end;
  3830. end
  3831. else
  3832. begin
  3833. if GlobalTypes[SymIndex].IsImport then
  3834. begin
  3835. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_GLOBAL symbol, that is an import');
  3836. exit;
  3837. end;
  3838. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3839. objsym.bind:=AB_GLOBAL;
  3840. objsym.typ:=AT_WASM_GLOBAL;
  3841. objsym.objsection:=ObjData.createsection('.wasm_globals.n_'+SymName,1,[oso_Data,oso_load],true);
  3842. if objsym.objsection.Size=0 then
  3843. objsym.objsection.WriteZeros(1);
  3844. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  3845. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  3846. objsym.offset:=0;
  3847. objsym.size:=1;
  3848. objsym.LinkingData.GlobalInitializer:=GlobalTypes[SymIndex].GlobalInit;
  3849. end;
  3850. objsym.LinkingData.GlobalType:=GlobalTypes[SymIndex].valtype;
  3851. objsym.LinkingData.GlobalIsMutable:=GlobalTypes[SymIndex].IsMutable;
  3852. objsym.LinkingData.IsExported:=GlobalTypes[SymIndex].IsExported;
  3853. objsym.LinkingData.ExportName:=GlobalTypes[SymIndex].ExportName;
  3854. end;
  3855. byte(SYMTAB_SECTION),
  3856. byte(SYMTAB_EVENT),
  3857. byte(SYMTAB_TABLE):
  3858. {TODO};
  3859. else
  3860. internalerror(2023122701);
  3861. end;
  3862. for j:=0 to high(RelocationTable) do
  3863. for i:=0 to high(RelocationTable[j]) do
  3864. with RelocationTable[j,i] do
  3865. begin
  3866. case j of
  3867. 0:
  3868. begin
  3869. SegI:=FindCodeSegment(RelocOffset);
  3870. if SegI=-1 then
  3871. begin
  3872. InputError('Relocation offset not found in code segment');
  3873. Exit;
  3874. end;
  3875. BaseSectionOffset:=CodeSegments[SegI].CodeSectionOffset;
  3876. ObjSec:=TObjSection(ObjData.ObjSectionList[SegI]);
  3877. end;
  3878. 1:
  3879. begin
  3880. SegI:=FindDataSegment(RelocOffset);
  3881. if SegI=-1 then
  3882. begin
  3883. InputError('Relocation offset not found in data segment');
  3884. Exit;
  3885. end;
  3886. BaseSectionOffset:=DataSegments[SegI].DataSectionOffset;
  3887. ObjSec:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SegI]);
  3888. end
  3889. else
  3890. internalerror(2023122801);
  3891. end;
  3892. case TWasmRelocationType(RelocType) of
  3893. R_WASM_FUNCTION_INDEX_LEB:
  3894. begin
  3895. if RelocIndex>high(SymbolTable) then
  3896. begin
  3897. InputError('Symbol index in relocation too high');
  3898. exit;
  3899. end;
  3900. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3901. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_FUNCTION_INDEX_LEB))
  3902. else
  3903. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3904. end;
  3905. R_WASM_TABLE_INDEX_SLEB:
  3906. begin
  3907. if RelocIndex>high(SymbolTable) then
  3908. begin
  3909. InputError('Symbol index in relocation too high');
  3910. exit;
  3911. end;
  3912. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3913. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB))
  3914. else
  3915. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3916. end;
  3917. R_WASM_TABLE_INDEX_I32:
  3918. begin
  3919. if RelocIndex>high(SymbolTable) then
  3920. begin
  3921. InputError('Symbol index in relocation too high');
  3922. exit;
  3923. end;
  3924. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3925. begin
  3926. if SymbolTable[RelocIndex].ObjSym.typ<>AT_FUNCTION then
  3927. begin
  3928. InputError('R_WASM_TABLE_INDEX_I32 relocation must point to a function symbol');
  3929. exit;
  3930. end;
  3931. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE))
  3932. end
  3933. else
  3934. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3935. end;
  3936. R_WASM_MEMORY_ADDR_LEB:
  3937. begin
  3938. if RelocIndex>high(SymbolTable) then
  3939. begin
  3940. InputError('Symbol index in relocation too high');
  3941. exit;
  3942. end;
  3943. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3944. begin
  3945. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_LEB);
  3946. ObjReloc.Addend:=RelocAddend;
  3947. ObjSec.ObjRelocations.Add(ObjReloc);
  3948. end
  3949. else
  3950. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3951. end;
  3952. R_WASM_MEMORY_ADDR_SLEB:
  3953. begin
  3954. if RelocIndex>high(SymbolTable) then
  3955. begin
  3956. InputError('Symbol index in relocation too high');
  3957. exit;
  3958. end;
  3959. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3960. begin
  3961. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB);
  3962. ObjReloc.Addend:=RelocAddend;
  3963. ObjSec.ObjRelocations.Add(ObjReloc);
  3964. end
  3965. else
  3966. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3967. end;
  3968. R_WASM_MEMORY_ADDR_I32:
  3969. begin
  3970. if RelocIndex>high(SymbolTable) then
  3971. begin
  3972. InputError('Symbol index in relocation too high');
  3973. exit;
  3974. end;
  3975. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3976. begin
  3977. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  3978. ObjReloc.Addend:=RelocAddend;
  3979. ObjSec.ObjRelocations.Add(ObjReloc);
  3980. end
  3981. else
  3982. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3983. end;
  3984. R_WASM_TYPE_INDEX_LEB:
  3985. begin
  3986. if RelocIndex>high(FFuncTypes) then
  3987. begin
  3988. InputError('Type index in relocation too high');
  3989. exit;
  3990. end;
  3991. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateFuncType(RelocOffset-BaseSectionOffset,FFuncTypes[RelocIndex]));
  3992. end;
  3993. R_WASM_FUNCTION_OFFSET_I32:
  3994. begin
  3995. if RelocIndex>high(SymbolTable) then
  3996. begin
  3997. InputError('Symbol index in relocation too high');
  3998. exit;
  3999. end;
  4000. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  4001. begin
  4002. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  4003. ObjReloc.Addend:=RelocAddend;
  4004. ObjSec.ObjRelocations.Add(ObjReloc);
  4005. end
  4006. else
  4007. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  4008. end;
  4009. R_WASM_SECTION_OFFSET_I32:
  4010. begin
  4011. InputError('R_WASM_SECTION_OFFSET_I32 relocations not yet implemented');
  4012. exit;
  4013. end;
  4014. R_WASM_GLOBAL_INDEX_LEB:
  4015. begin
  4016. if RelocIndex>high(SymbolTable) then
  4017. begin
  4018. InputError('Symbol index in relocation too high');
  4019. exit;
  4020. end;
  4021. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  4022. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_GLOBAL_INDEX_LEB))
  4023. else
  4024. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  4025. end;
  4026. R_WASM_TAG_INDEX_LEB:
  4027. begin
  4028. InputError('R_WASM_TAG_INDEX_LEB relocations not yet implemented');
  4029. exit;
  4030. end;
  4031. else
  4032. internalerror(2023122802);
  4033. end;
  4034. end;
  4035. Result:=True;
  4036. end;
  4037. {****************************************************************************
  4038. TWasmExeOutput
  4039. ****************************************************************************}
  4040. procedure TWasmExeOutput.WriteWasmSection(wsid: TWasmSectionID);
  4041. var
  4042. b: byte;
  4043. begin
  4044. b:=ord(wsid);
  4045. Writer.write(b,1);
  4046. WriteUleb(Writer,FWasmSections[wsid].size);
  4047. Writer.writearray(FWasmSections[wsid]);
  4048. end;
  4049. function TWasmExeOutput.writeData: boolean;
  4050. procedure WriteImportSection;
  4051. var
  4052. imports_count: SizeInt;
  4053. i: Integer;
  4054. begin
  4055. imports_count:=Length(FFunctionImports);
  4056. WriteUleb(FWasmSections[wsiImport],imports_count);
  4057. for i:=0 to Length(FFunctionImports)-1 do
  4058. with FFunctionImports[i] do
  4059. begin
  4060. WriteName(FWasmSections[wsiImport],ModName);
  4061. WriteName(FWasmSections[wsiImport],Name);
  4062. WriteByte(FWasmSections[wsiImport],$00);
  4063. WriteUleb(FWasmSections[wsiImport],TypeIdx);
  4064. end;
  4065. end;
  4066. procedure WriteCodeSegments;
  4067. var
  4068. i: Integer;
  4069. exesec: TExeSection;
  4070. objsec: TWasmObjSection;
  4071. begin
  4072. exesec:=FindExeSection('.text');
  4073. if not assigned(exesec) then
  4074. internalerror(2023123102);
  4075. if not (oso_Data in exesec.SecOptions) then
  4076. internalerror(2023123103);
  4077. WriteUleb(FWasmSections[wsiFunction],exesec.ObjSectionList.Count);
  4078. WriteUleb(FWasmSections[wsiCode],exesec.ObjSectionList.Count);
  4079. for i:=0 to exesec.ObjSectionList.Count-1 do
  4080. begin
  4081. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4082. if not (oso_data in objsec.secoptions) then
  4083. internalerror(2023123104);
  4084. if not assigned(objsec.data) then
  4085. internalerror(2023123105);
  4086. if objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex<>(i+Length(FFunctionImports)) then
  4087. internalerror(2024010101);
  4088. WriteUleb(FWasmSections[wsiFunction],objsec.MainFuncSymbol.LinkingData.ExeTypeIndex);
  4089. WriteUleb(FWasmSections[wsiCode],objsec.Data.size);
  4090. objsec.Data.seek(0);
  4091. CopyDynamicArray(objsec.Data,FWasmSections[wsiCode],objsec.Data.size);
  4092. end;
  4093. end;
  4094. procedure WriteDataSegments;
  4095. procedure WriteExeSection(exesec: TExeSection);
  4096. var
  4097. i: Integer;
  4098. objsec: TObjSection;
  4099. exesecdatapos: LongWord;
  4100. dpos, pad: QWord;
  4101. begin
  4102. WriteByte(FWasmSections[wsiData],0);
  4103. WriteByte(FWasmSections[wsiData],$41); { i32.const }
  4104. WriteSleb(FWasmSections[wsiData],longint(exesec.MemPos));
  4105. WriteByte(FWasmSections[wsiData],$0B); { end }
  4106. WriteUleb(FWasmSections[wsiData],exesec.Size);
  4107. exesecdatapos:=FWasmSections[wsiData].size;
  4108. for i:=0 to exesec.ObjSectionList.Count-1 do
  4109. begin
  4110. objsec:=TObjSection(exesec.ObjSectionList[i]);
  4111. if not (oso_data in objsec.secoptions) then
  4112. internalerror(2024010104);
  4113. if not assigned(objsec.data) then
  4114. internalerror(2024010105);
  4115. dpos:=objsec.MemPos-exesec.MemPos+exesecdatapos;
  4116. pad:=dpos-FWasmSections[wsiData].size;
  4117. { objsection must be within SecAlign bytes from the previous one }
  4118. if (dpos<FWasmSections[wsiData].Size) or
  4119. (pad>=max(objsec.SecAlign,1)) then
  4120. internalerror(2024010106);
  4121. writeZeros(FWasmSections[wsiData],pad);
  4122. objsec.data.seek(0);
  4123. CopyDynamicArray(objsec.data,FWasmSections[wsiData],objsec.data.size);
  4124. end;
  4125. if (FWasmSections[wsiData].size-exesecdatapos)<>exesec.Size then
  4126. internalerror(2024010107);
  4127. end;
  4128. var
  4129. DataCount: Integer;
  4130. begin
  4131. DataCount:=2;
  4132. WriteUleb(FWasmSections[wsiDataCount],DataCount);
  4133. WriteUleb(FWasmSections[wsiData],DataCount);
  4134. WriteExeSection(FindExeSection('.rodata'));
  4135. WriteExeSection(FindExeSection('.data'));
  4136. end;
  4137. procedure WriteTableAndElemSections;
  4138. const
  4139. TableCount=1;
  4140. var
  4141. i: Integer;
  4142. begin
  4143. { Table section }
  4144. WriteUleb(FWasmSections[wsiTable],TableCount);
  4145. { table 0 }
  4146. { table type }
  4147. WriteByte(FWasmSections[wsiTable],encode_wasm_basic_type(wbt_funcref));
  4148. { table limits }
  4149. WriteByte(FWasmSections[wsiTable],$01); { has min & max }
  4150. WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { min }
  4151. WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { max }
  4152. { Elem section }
  4153. WriteUleb(FWasmSections[wsiElement],1); { 1 element segment }
  4154. { element segment 0 }
  4155. WriteByte(FWasmSections[wsiElement],0); { type funcref, init((ref.func y) end)*, mode active <table 0, offset e> }
  4156. { e:expr }
  4157. WriteByte(FWasmSections[wsiElement],$41); { i32.const }
  4158. WriteSleb(FWasmSections[wsiElement],1); { starting from 1 (table entry 0 is ref.null) }
  4159. WriteByte(FWasmSections[wsiElement],$0B); { end }
  4160. { y*:vec(funcidx) }
  4161. WriteUleb(FWasmSections[wsiElement],Length(FIndirectFunctionTable)-1);
  4162. for i:=1 to Length(FIndirectFunctionTable)-1 do
  4163. WriteUleb(FWasmSections[wsiElement],FIndirectFunctionTable[i].FuncIdx);
  4164. end;
  4165. procedure WriteGlobalSection;
  4166. var
  4167. exesec: TExeSection;
  4168. globals_count, i: Integer;
  4169. objsec: TWasmObjSection;
  4170. begin
  4171. exesec:=FindExeSection('.wasm_globals');
  4172. if not assigned(exesec) then
  4173. internalerror(2024010112);
  4174. globals_count:=exesec.ObjSectionList.Count;
  4175. if globals_count<>exesec.Size then
  4176. internalerror(2024010113);
  4177. WriteUleb(FWasmSections[wsiGlobal],globals_count);
  4178. for i:=0 to exesec.ObjSectionList.Count-1 do
  4179. begin
  4180. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4181. WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(objsec.MainFuncSymbol.LinkingData.GlobalType));
  4182. if objsec.MainFuncSymbol.LinkingData.GlobalIsMutable then
  4183. WriteByte(FWasmSections[wsiGlobal],1)
  4184. else
  4185. WriteByte(FWasmSections[wsiGlobal],0);
  4186. { initializer expr }
  4187. with objsec.MainFuncSymbol.LinkingData.GlobalInitializer do
  4188. case typ of
  4189. wbt_i32:
  4190. begin
  4191. WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
  4192. WriteSleb(FWasmSections[wsiGlobal],init_i32);
  4193. end;
  4194. wbt_i64:
  4195. begin
  4196. WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
  4197. WriteSleb(FWasmSections[wsiGlobal],init_i64);
  4198. end;
  4199. wbt_f32:
  4200. begin
  4201. WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
  4202. WriteF32LE(FWasmSections[wsiGlobal],init_f32);
  4203. end;
  4204. wbt_f64:
  4205. begin
  4206. WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
  4207. WriteF64LE(FWasmSections[wsiGlobal],init_f64);
  4208. end;
  4209. wbt_funcref,
  4210. wbt_externref:
  4211. begin
  4212. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null }
  4213. WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(typ));
  4214. end;
  4215. else
  4216. internalerror(2024010114);
  4217. end;
  4218. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  4219. end;
  4220. end;
  4221. procedure WriteExportSection;
  4222. const
  4223. MemoryExportsCount=1;
  4224. var
  4225. FunctionExportsCount: Integer;
  4226. ExportsCount: Integer;
  4227. textsec: TExeSection;
  4228. i: Integer;
  4229. objsec: TWasmObjSection;
  4230. begin
  4231. FunctionExportsCount:=0;
  4232. textsec:=FindExeSection('.text');
  4233. if not assigned(textsec) then
  4234. internalerror(2024010115);
  4235. for i:=0 to textsec.ObjSectionList.Count-1 do
  4236. begin
  4237. objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
  4238. if objsec.MainFuncSymbol.LinkingData.IsExported then
  4239. Inc(FunctionExportsCount)
  4240. end;
  4241. ExportsCount:=MemoryExportsCount+FunctionExportsCount;
  4242. WriteUleb(FWasmSections[wsiExport],ExportsCount);
  4243. { export 0 }
  4244. WriteName(FWasmSections[wsiExport],'memory');
  4245. WriteByte(FWasmSections[wsiExport],$02); { mem }
  4246. WriteUleb(FWasmSections[wsiExport],0); { memidx = 0 }
  4247. for i:=0 to textsec.ObjSectionList.Count-1 do
  4248. begin
  4249. objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
  4250. if objsec.MainFuncSymbol.LinkingData.IsExported then
  4251. begin
  4252. WriteName(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExportName);
  4253. WriteByte(FWasmSections[wsiExport],$00); { func }
  4254. WriteUleb(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex); { funcidx }
  4255. end;
  4256. end;
  4257. end;
  4258. begin
  4259. result:=false;
  4260. SetStackPointer;
  4261. FFuncTypes.WriteTo(FWasmSections[wsiType]);
  4262. WriteImportSection;
  4263. WriteCodeSegments;
  4264. WriteDataSegments;
  4265. WriteTableAndElemSections;
  4266. WriteGlobalSection;
  4267. WriteExportSection;
  4268. WriteUleb(FWasmSections[wsiMemory],1);
  4269. WriteByte(FWasmSections[wsiMemory],0);
  4270. WriteUleb(FWasmSections[wsiMemory],2); { todo: fill min memory (pages) }
  4271. {...}
  4272. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  4273. Writer.write(WasmVersion,SizeOf(WasmVersion));
  4274. WriteWasmSection(wsiType);
  4275. WriteWasmSection(wsiImport);
  4276. WriteWasmSection(wsiFunction);
  4277. WriteWasmSection(wsiTable);
  4278. WriteWasmSection(wsiMemory);
  4279. WriteWasmSection(wsiGlobal);
  4280. WriteWasmSection(wsiExport);
  4281. WriteWasmSection(wsiElement);
  4282. WriteWasmSection(wsiDataCount);
  4283. WriteWasmSection(wsiCode);
  4284. WriteWasmSection(wsiData);
  4285. result := true;
  4286. end;
  4287. procedure TWasmExeOutput.DoRelocationFixup(objsec: TObjSection);
  4288. procedure writeUInt32LE(v: uint32);
  4289. begin
  4290. {$ifdef FPC_BIG_ENDIAN}
  4291. v:=SwapEndian(v);
  4292. {$endif FPC_BIG_ENDIAN}
  4293. objsec.data.write(v,4);
  4294. end;
  4295. var
  4296. i: Integer;
  4297. objreloc: TWasmObjRelocation;
  4298. objsym: TWasmObjSymbol;
  4299. begin
  4300. for i:=0 to objsec.ObjRelocations.Count-1 do
  4301. begin
  4302. objreloc:=TWasmObjRelocation(objsec.ObjRelocations[i]);
  4303. if assigned(objreloc.symbol) then
  4304. begin
  4305. objsym:=TWasmObjSymbol(objreloc.symbol);
  4306. case objreloc.typ of
  4307. RELOC_FUNCTION_INDEX_LEB:
  4308. begin
  4309. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4310. internalerror(2024010103);
  4311. objsec.Data.seek(objreloc.DataOffset);
  4312. WriteUleb5(objsec.Data,objsym.LinkingData.ExeFunctionIndex);
  4313. end;
  4314. RELOC_ABSOLUTE:
  4315. begin
  4316. case objsym.typ of
  4317. AT_FUNCTION:
  4318. begin
  4319. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4320. internalerror(2024010103);
  4321. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  4322. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  4323. objsec.Data.seek(objreloc.DataOffset);
  4324. writeUInt32LE(UInt32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  4325. end;
  4326. AT_DATA:
  4327. begin
  4328. objsec.Data.seek(objreloc.DataOffset);
  4329. writeUInt32LE(UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4330. end;
  4331. else
  4332. internalerror(2024010108);
  4333. end;
  4334. end;
  4335. RELOC_MEMORY_ADDR_LEB:
  4336. begin
  4337. if objsym.typ<>AT_DATA then
  4338. internalerror(2024010109);
  4339. objsec.Data.seek(objreloc.DataOffset);
  4340. WriteUleb5(objsec.Data,UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4341. end;
  4342. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  4343. begin
  4344. case objsym.typ of
  4345. AT_FUNCTION:
  4346. begin
  4347. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4348. internalerror(2024010103);
  4349. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  4350. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  4351. objsec.Data.seek(objreloc.DataOffset);
  4352. WriteSleb5(objsec.Data,Int32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  4353. end;
  4354. AT_DATA:
  4355. begin
  4356. objsec.Data.seek(objreloc.DataOffset);
  4357. WriteSleb5(objsec.Data,Int32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4358. end;
  4359. else
  4360. internalerror(2024010110);
  4361. end;
  4362. end;
  4363. RELOC_GLOBAL_INDEX_LEB:
  4364. begin
  4365. if objsym.typ<>AT_WASM_GLOBAL then
  4366. internalerror(2024010111);
  4367. objsec.Data.seek(objreloc.DataOffset);
  4368. WriteUleb5(objsec.Data,UInt32(objsym.offset+objsym.objsection.MemPos));
  4369. end;
  4370. else
  4371. Writeln('Symbol relocation not yet implemented! ', objreloc.typ);
  4372. end;
  4373. end
  4374. else if objreloc.typ=RELOC_TYPE_INDEX_LEB then
  4375. begin
  4376. objreloc.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(objreloc.FuncType);
  4377. objsec.Data.seek(objreloc.DataOffset);
  4378. WriteUleb5(objsec.Data,objreloc.ExeTypeIndex);
  4379. end
  4380. else
  4381. Writeln('Non-symbol relocation not yet implemented! ', objreloc.typ);
  4382. end;
  4383. end;
  4384. constructor TWasmExeOutput.create;
  4385. var
  4386. i: TWasmSectionID;
  4387. begin
  4388. inherited create;
  4389. CObjData:=TWasmObjData;
  4390. MaxMemPos:=$FFFFFFFF;
  4391. FFuncTypes:=TWasmFuncTypeTable.Create;
  4392. for i in TWasmSectionID do
  4393. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  4394. SetLength(FIndirectFunctionTable,1);
  4395. FIndirectFunctionTable[0].FuncIdx:=-1;
  4396. end;
  4397. destructor TWasmExeOutput.destroy;
  4398. var
  4399. i: TWasmSectionID;
  4400. begin
  4401. for i in TWasmSectionID do
  4402. FWasmSections[i].Free;
  4403. FFuncTypes.Free;
  4404. inherited destroy;
  4405. end;
  4406. procedure TWasmExeOutput.GenerateLibraryImports(ImportLibraryList: TFPHashObjectList);
  4407. var
  4408. i, j: Integer;
  4409. ImportLibrary: TImportLibrary;
  4410. ImportSymbol: TImportSymbol;
  4411. exesym: TExeSymbol;
  4412. begin
  4413. { Here map import symbols to exe symbols and create necessary sections.
  4414. Actual import generation is done after unused sections (and symbols) are removed. }
  4415. FImports:=ImportLibraryList;
  4416. for i:=0 to ImportLibraryList.Count-1 do
  4417. begin
  4418. ImportLibrary:=TImportLibrary(ImportLibraryList[i]);
  4419. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4420. begin
  4421. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4422. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  4423. if assigned(exesym) and
  4424. (exesym.State<>symstate_defined) then
  4425. begin
  4426. ImportSymbol.CachedExeSymbol:=exesym;
  4427. exesym.State:=symstate_defined;
  4428. end;
  4429. end;
  4430. end;
  4431. PackUnresolvedExeSymbols('after module imports');
  4432. end;
  4433. procedure TWasmExeOutput.AfterUnusedSectionRemoval;
  4434. begin
  4435. PrepareImports;
  4436. PrepareFunctions;
  4437. end;
  4438. procedure TWasmExeOutput.MemPos_ExeSection(const aname: string);
  4439. var
  4440. ExeSec: TExeSection;
  4441. i: Integer;
  4442. objsec: TObjSection;
  4443. begin
  4444. { WebAssembly is a Harvard architecture.
  4445. Data lives in a separate address space, so start addressing back from 0
  4446. (the LLVM leaves the first 1024 bytes in the data segment empty, so we
  4447. start at 1024). }
  4448. if aname='.rodata' then
  4449. begin
  4450. CurrMemPos:=1024;
  4451. inherited;
  4452. end
  4453. else if aname='.text' then
  4454. begin
  4455. CurrMemPos:=0;
  4456. ExeSec:=FindExeSection(aname);
  4457. if not assigned(ExeSec) then
  4458. exit;
  4459. exesec.MemPos:=CurrMemPos;
  4460. CurrMemPos:=CurrMemPos+UlebEncodingSize(exesec.ObjSectionList.Count);
  4461. { set position of object ObjSections }
  4462. for i:=0 to exesec.ObjSectionList.Count-1 do
  4463. begin
  4464. objsec:=TObjSection(exesec.ObjSectionList[i]);
  4465. CurrMemPos:=CurrMemPos+UlebEncodingSize(objsec.Size);
  4466. CurrMemPos:=objsec.setmempos(CurrMemPos);
  4467. end;
  4468. { calculate size of the section }
  4469. exesec.Size:=CurrMemPos-exesec.MemPos;
  4470. end
  4471. else
  4472. inherited;
  4473. end;
  4474. procedure TWasmExeOutput.Load_Symbol(const aname: string);
  4475. begin
  4476. if aname=StackPointerSymStr then
  4477. begin
  4478. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  4479. FStackPointerSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  4480. FStackPointerSym.size:=1;
  4481. FStackPointerSym.ObjSection.WriteZeros(1);
  4482. TWasmObjSection(FStackPointerSym.ObjSection).MainFuncSymbol:=FStackPointerSym;
  4483. FStackPointerSym.LinkingData.GlobalType:=wbt_i32;
  4484. FStackPointerSym.LinkingData.GlobalIsMutable:=True;
  4485. FStackPointerSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  4486. FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=0;
  4487. end
  4488. else
  4489. inherited;
  4490. end;
  4491. procedure TWasmExeOutput.PrepareImports;
  4492. function AddFunctionImport(const libname,symname:TCmdStr; functype: TWasmFuncType): Integer;
  4493. begin
  4494. SetLength(FFunctionImports,Length(FFunctionImports)+1);
  4495. Result:=High(FFunctionImports);
  4496. if assigned(exemap) then
  4497. exemap.Add(' Importing Function[' + tostr(Result) + '] ' + symname + functype.ToString);
  4498. with FFunctionImports[Result] do
  4499. begin
  4500. ModName:=libname;
  4501. Name:=symname;
  4502. TypeIdx:=FFuncTypes.AddOrGetFuncType(functype);
  4503. end;
  4504. end;
  4505. var
  4506. i, j: Integer;
  4507. ImportLibrary: TImportLibrary;
  4508. ImportSymbol: TImportSymbol;
  4509. exesym: TExeSymbol;
  4510. newdll: Boolean;
  4511. begin
  4512. for i:=0 to FImports.Count-1 do
  4513. begin
  4514. ImportLibrary:=TImportLibrary(FImports[i]);
  4515. newdll:=False;
  4516. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4517. begin
  4518. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4519. exesym:=ImportSymbol.CachedExeSymbol;
  4520. if assigned(exesym) and
  4521. exesym.Used then
  4522. begin
  4523. if (not newdll) and assigned(exemap) then
  4524. begin
  4525. exemap.Add('');
  4526. exemap.Add('Importing from module '+ImportLibrary.Name);
  4527. end;
  4528. newdll:=True;
  4529. TWasmObjSymbol(exesym.ObjSymbol).LinkingData.ExeFunctionIndex:=
  4530. AddFunctionImport(ImportLibrary.Name,ImportSymbol.Name,TWasmObjSymbol(exesym.ObjSymbol).LinkingData.FuncType);
  4531. end;
  4532. end;
  4533. end;
  4534. end;
  4535. procedure TWasmExeOutput.PrepareFunctions;
  4536. var
  4537. i, j: Integer;
  4538. exesec: TExeSection;
  4539. objsec: TWasmObjSection;
  4540. fsym: TWasmObjSymbol;
  4541. objdata: TObjData;
  4542. begin
  4543. if assigned(exemap) then
  4544. begin
  4545. exemap.Add('');
  4546. exemap.Add('Functions, defined in this module:');
  4547. end;
  4548. exesec:=FindExeSection('.text');
  4549. if not assigned(exesec) then
  4550. internalerror(2023123106);
  4551. for i:=0 to exesec.ObjSectionList.Count-1 do
  4552. begin
  4553. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4554. fsym:=objsec.MainFuncSymbol;
  4555. if not assigned(fsym) then
  4556. internalerror(2023123107);
  4557. if not assigned(fsym.LinkingData.FuncType) then
  4558. internalerror(2023123108);
  4559. if fsym.LinkingData.ExeFunctionIndex<>-1 then
  4560. internalerror(2023123109);
  4561. if fsym.LinkingData.ExeTypeIndex<>-1 then
  4562. internalerror(2023123109);
  4563. fsym.LinkingData.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(fsym.LinkingData.FuncType);
  4564. fsym.LinkingData.ExeFunctionIndex:=i+Length(FFunctionImports);
  4565. if assigned(exemap) then
  4566. begin
  4567. exemap.Add(' Function[' + tostr(fsym.LinkingData.ExeFunctionIndex) + '] ' + fsym.Name + fsym.LinkingData.FuncType.ToString);
  4568. end;
  4569. end;
  4570. { set ExeFunctionIndex to the alias symbols as well }
  4571. for i:=0 to ObjDataList.Count-1 do
  4572. begin
  4573. objdata:=TObjData(ObjDataList[i]);
  4574. for j:=0 to objdata.ObjSymbolList.Count-1 do
  4575. begin
  4576. fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
  4577. if assigned(fsym.objsection) and fsym.objsection.USed and (fsym.typ=AT_FUNCTION) and (fsym.LinkingData.ExeFunctionIndex=-1) then
  4578. begin
  4579. fsym.LinkingData.ExeFunctionIndex:=TWasmObjSection(fsym.objsection).MainFuncSymbol.LinkingData.ExeFunctionIndex;
  4580. if fsym.LinkingData.ExeFunctionIndex=-1 then
  4581. internalerror(2024010102);
  4582. end;
  4583. end;
  4584. end;
  4585. end;
  4586. function TWasmExeOutput.AddOrGetIndirectFunctionTableIndex(FuncIdx: Integer): integer;
  4587. var
  4588. i: Integer;
  4589. begin
  4590. for i:=1 to length(FIndirectFunctionTable)-1 do
  4591. if FIndirectFunctionTable[i].FuncIdx=FuncIdx then
  4592. begin
  4593. Result:=i;
  4594. exit;
  4595. end;
  4596. SetLength(FIndirectFunctionTable,Length(FIndirectFunctionTable)+1);
  4597. Result:=High(FIndirectFunctionTable);
  4598. FIndirectFunctionTable[Result].FuncIdx:=FuncIdx;
  4599. end;
  4600. procedure TWasmExeOutput.SetStackPointer;
  4601. var
  4602. BssSec: TExeSection;
  4603. StackStart: QWord;
  4604. begin
  4605. BssSec:=FindExeSection('.bss');
  4606. FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=Int32((BssSec.MemPos+BssSec.Size+stacksize+15) and (not 15));
  4607. end;
  4608. {****************************************************************************
  4609. TWasmAssembler
  4610. ****************************************************************************}
  4611. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  4612. begin
  4613. inherited;
  4614. CObjOutput:=TWasmObjOutput;
  4615. end;
  4616. {*****************************************************************************
  4617. Initialize
  4618. *****************************************************************************}
  4619. {$ifdef wasm32}
  4620. const
  4621. as_wasm32_wasm_info : tasminfo =
  4622. (
  4623. id : as_wasm32_wasm;
  4624. idtxt : 'WASM';
  4625. asmbin : '';
  4626. asmcmd : '';
  4627. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  4628. flags : [af_outputbinary,af_smartlink_sections];
  4629. labelprefix : '..@';
  4630. labelmaxlen : -1;
  4631. comment : '; ';
  4632. dollarsign: '$';
  4633. );
  4634. {$endif wasm32}
  4635. initialization
  4636. {$ifdef wasm32}
  4637. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  4638. {$endif wasm32}
  4639. end.