ogwasm.pas 190 KB

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