ogwasm.pas 191 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940
  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. Writeln('Warning! Relocation section ignored!');
  2393. Result:=True;
  2394. //InputError('Relocation for custom sections not supported, yet');
  2395. exit;
  2396. end;
  2397. if not ReadUleb32(RelocCount) then
  2398. begin
  2399. InputError('Error reading the relocation entries count from a relocation section');
  2400. exit;
  2401. end;
  2402. SetLength(RelocationTable[RelocTableIndex],RelocCount);
  2403. for i:=0 to RelocCount-1 do
  2404. with RelocationTable[RelocTableIndex,i] do
  2405. begin
  2406. if not Read(RelocType,1) then
  2407. begin
  2408. InputError('Error reading the relocation type of a relocation entry');
  2409. exit;
  2410. end;
  2411. if not (TWasmRelocationType(RelocType) in [R_WASM_FUNCTION_INDEX_LEB,
  2412. R_WASM_MEMORY_ADDR_LEB,
  2413. R_WASM_TABLE_INDEX_SLEB,
  2414. R_WASM_MEMORY_ADDR_SLEB,
  2415. R_WASM_SECTION_OFFSET_I32,
  2416. R_WASM_TABLE_INDEX_I32,
  2417. R_WASM_FUNCTION_OFFSET_I32,
  2418. R_WASM_MEMORY_ADDR_I32,
  2419. R_WASM_TYPE_INDEX_LEB,
  2420. R_WASM_GLOBAL_INDEX_LEB,
  2421. R_WASM_TAG_INDEX_LEB]) then
  2422. begin
  2423. InputError('Unsupported relocation type: ' + tostr(RelocType));
  2424. exit;
  2425. end;
  2426. if not ReadUleb32(RelocOffset) then
  2427. begin
  2428. InputError('Error reading the relocation offset of a relocation entry');
  2429. exit;
  2430. end;
  2431. if not ReadUleb32(RelocIndex) then
  2432. begin
  2433. InputError('Error reading the relocation index of a relocation entry');
  2434. exit;
  2435. end;
  2436. 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
  2437. begin
  2438. if not ReadSleb32(RelocAddend) then
  2439. begin
  2440. InputError('Error reading the relocation addend of a relocation entry');
  2441. exit;
  2442. end;
  2443. end;
  2444. end;
  2445. if AReader.Pos<>(SectionStart+SectionSize) then
  2446. begin
  2447. InputError('Unexpected relocation section size');
  2448. exit;
  2449. end;
  2450. Result:=True;
  2451. end;
  2452. function ReadLinkingSection: Boolean;
  2453. function ReadSegmentInfo: Boolean;
  2454. var
  2455. SegmentCount: uint32;
  2456. i: Integer;
  2457. begin
  2458. Result:=False;
  2459. if SegmentInfoSectionRead then
  2460. begin
  2461. InputError('The WASM_SEGMENT_INFO subsection is duplicated');
  2462. exit;
  2463. end;
  2464. SegmentInfoSectionRead:=True;
  2465. if not ReadUleb32(SegmentCount) then
  2466. begin
  2467. InputError('Error reading the segment count from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2468. exit;
  2469. end;
  2470. if SegmentCount<>Length(DataSegments) then
  2471. begin
  2472. InputError('Segment count in the WASM_SEGMENT_INFO subsection does not match the data count in the data section');
  2473. exit;
  2474. end;
  2475. for i:=0 to SegmentCount-1 do
  2476. with DataSegments[i] do
  2477. begin
  2478. if not ReadName(SegName) then
  2479. begin
  2480. InputError('Error reading segment name from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2481. exit;
  2482. end;
  2483. if not ReadUleb32(SegAlignment) then
  2484. begin
  2485. InputError('Error reading segment alignment from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2486. exit;
  2487. end;
  2488. if not ReadUleb32(SegFlags) then
  2489. begin
  2490. InputError('Error reading segment flags from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2491. exit;
  2492. end;
  2493. end;
  2494. if AReader.Pos<>(SectionStart+SectionSize) then
  2495. begin
  2496. InputError('Unexpected WASM_SEGMENT_INFO section size');
  2497. exit;
  2498. end;
  2499. Result:=True;
  2500. end;
  2501. function ReadSymbolTable: Boolean;
  2502. var
  2503. SymCount: uint32;
  2504. i: Integer;
  2505. SymKindName: string;
  2506. begin
  2507. Result:=False;
  2508. if SymbolTableSectionRead then
  2509. begin
  2510. InputError('The WASM_SYMBOL_TABLE subsection is duplicated');
  2511. exit;
  2512. end;
  2513. SymbolTableSectionRead:=True;
  2514. if not ReadUleb32(SymCount) then
  2515. begin
  2516. InputError('Error reading the symbol count from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2517. exit;
  2518. end;
  2519. SetLength(SymbolTable,SymCount);
  2520. for i:=0 to SymCount-1 do
  2521. with SymbolTable[i] do
  2522. begin
  2523. if not Read(SymKind,1) then
  2524. begin
  2525. InputError('Error reading symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2526. exit;
  2527. end;
  2528. if not ReadUleb32(SymFlags) then
  2529. begin
  2530. InputError('Error reading symbol flags from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2531. exit;
  2532. end;
  2533. case SymKind of
  2534. byte(SYMTAB_FUNCTION),
  2535. byte(SYMTAB_GLOBAL),
  2536. byte(SYMTAB_EVENT),
  2537. byte(SYMTAB_TABLE):
  2538. begin
  2539. WriteStr(SymKindName, TWasmSymbolType(SymKind));
  2540. if not ReadUleb32(SymIndex) then
  2541. begin
  2542. InputError('Error reading the index of a ' + SymKindName + ' symbol');
  2543. exit;
  2544. end;
  2545. if ((SymKind=byte(SYMTAB_FUNCTION)) and (SymIndex>high(FuncTypes))) then
  2546. begin
  2547. InputError('Symbol index too high');
  2548. exit;
  2549. end;
  2550. if ((SymFlags and WASM_SYM_EXPLICIT_NAME)<>0) or
  2551. ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  2552. begin
  2553. if not ReadName(SymName) then
  2554. begin
  2555. InputError('Error reading symbol name of a ' + SymKindName + ' symbol');
  2556. exit;
  2557. end;
  2558. end;
  2559. end;
  2560. byte(SYMTAB_DATA):
  2561. begin
  2562. if not ReadName(SymName) then
  2563. begin
  2564. InputError('Error reading symbol name of a SYMTAB_DATA symbol');
  2565. exit;
  2566. end;
  2567. if (SymFlags and WASM_SYM_UNDEFINED)=0 then
  2568. begin
  2569. if not ReadUleb32(SymIndex) then
  2570. begin
  2571. InputError('Error reading the data segment index of a SYMTAB_DATA symbol');
  2572. exit;
  2573. end;
  2574. if SymIndex>high(DataSegments) then
  2575. begin
  2576. InputError('Data segment index of SYMTAB_DATA symbol out of bounds');
  2577. exit;
  2578. end;
  2579. if not ReadUleb32(SymOffset) then
  2580. begin
  2581. InputError('Error reading the offset of a SYMTAB_DATA symbol');
  2582. exit;
  2583. end;
  2584. if not ReadUleb32(SymSize) then
  2585. begin
  2586. InputError('Error reading the size of a SYMTAB_DATA symbol');
  2587. exit;
  2588. end;
  2589. end;
  2590. end;
  2591. byte(SYMTAB_SECTION):
  2592. begin
  2593. if not ReadUleb32(TargetSection) then
  2594. begin
  2595. InputError('Error reading the target section of a SYMTAB_SECTION symbol');
  2596. exit;
  2597. end;
  2598. end;
  2599. else
  2600. begin
  2601. InputError('Unsupported symbol kind: ' + tostr(SymKind));
  2602. exit;
  2603. end;
  2604. end;
  2605. end;
  2606. if AReader.Pos<>(SectionStart+SectionSize) then
  2607. begin
  2608. InputError('Unexpected WASM_SYMBOL_TABLE section size');
  2609. exit;
  2610. end;
  2611. Result:=True;
  2612. end;
  2613. const
  2614. ExpectedVersion = 2;
  2615. var
  2616. Version, SubsectionSize, SaveSectionSize: uint32;
  2617. SubsectionType: Byte;
  2618. SaveSectionStart: LongInt;
  2619. begin
  2620. Result:=False;
  2621. if not ReadUleb32(Version) then
  2622. begin
  2623. InputError('Error reading the version of the ''linking'' section');
  2624. exit;
  2625. end;
  2626. if Version<>ExpectedVersion then
  2627. begin
  2628. InputError('The ''linking'' section has an unsupported version (expected version ' + tostr(ExpectedVersion) + ', got version ' + tostr(Version) + ')');
  2629. exit;
  2630. end;
  2631. while AReader.Pos<(SectionStart+SectionSize) do
  2632. begin
  2633. if not read(SubsectionType, 1) then
  2634. begin
  2635. InputError('Error reading subsection type in the ''linking'' section');
  2636. exit;
  2637. end;
  2638. if not ReadUleb32(SubsectionSize) then
  2639. begin
  2640. InputError('Error reading subsection size in the ''linking'' section');
  2641. exit;
  2642. end;
  2643. if (AReader.Pos+SubsectionSize)>(SectionStart+SectionSize) then
  2644. begin
  2645. InputError('Subsection size exceeds bounds of its parent ''linking'' section');
  2646. exit;
  2647. end;
  2648. SaveSectionStart:=SectionStart;
  2649. SaveSectionSize:=SectionSize;
  2650. SectionStart:=AReader.Pos;
  2651. SectionSize:=SubsectionSize;
  2652. case SubsectionType of
  2653. Byte(WASM_SEGMENT_INFO):
  2654. if not ReadSegmentInfo then
  2655. begin
  2656. InputError('Error reading the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2657. exit;
  2658. end;
  2659. Byte(WASM_SYMBOL_TABLE):
  2660. if not ReadSymbolTable then
  2661. begin
  2662. InputError('Error reading the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2663. exit;
  2664. end;
  2665. else
  2666. begin
  2667. InputError('Unsupported ''linking'' section subsection type ' + tostr(SubsectionType));
  2668. exit;
  2669. end;
  2670. end;
  2671. AReader.Seek(SectionStart+SectionSize);
  2672. SectionStart:=SaveSectionStart;
  2673. SectionSize:=SaveSectionSize;
  2674. end;
  2675. result:=True;
  2676. end;
  2677. function ReadProducersSection: Boolean;
  2678. begin
  2679. Result:=False;
  2680. end;
  2681. function ReadTargetFeaturesSection: Boolean;
  2682. begin
  2683. Result:=False;
  2684. end;
  2685. function ReadDebugSection(const SectionName: string): Boolean;
  2686. var
  2687. ObjSec: TObjSection;
  2688. begin
  2689. ObjSec:=ObjData.createsection(SectionName,1,[oso_Data,oso_debug],false);
  2690. ObjSec.DataPos:=AReader.Pos;
  2691. ObjSec.Size:=SectionStart+SectionSize-AReader.Pos;
  2692. Result:=True;
  2693. end;
  2694. const
  2695. RelocationSectionPrefix = 'reloc.';
  2696. var
  2697. SectionName: ansistring;
  2698. begin
  2699. Result:=False;
  2700. ReadName(SectionName);
  2701. if Copy(SectionName,1,Length(RelocationSectionPrefix)) = RelocationSectionPrefix then
  2702. begin
  2703. if not ReadRelocationSection then
  2704. begin
  2705. InputError('Error reading the relocation section ''' + SectionName + '''');
  2706. exit;
  2707. end;
  2708. end
  2709. else
  2710. case SectionName of
  2711. 'linking':
  2712. if not ReadLinkingSection then
  2713. begin
  2714. InputError('Error reading the ''linking'' section');
  2715. exit;
  2716. end;
  2717. 'producers':
  2718. Result:=ReadProducersSection;
  2719. 'target_features':
  2720. Result:=ReadTargetFeaturesSection;
  2721. '.debug_abbrev',
  2722. '.debug_info',
  2723. '.debug_line',
  2724. '.debug_aranges',
  2725. '.debug_ranges':
  2726. Result:=ReadDebugSection(SectionName);
  2727. else
  2728. InputError('Unsupported custom section: ''' + SectionName + '''');
  2729. end;
  2730. Result:=True;
  2731. end;
  2732. function ReadTypeSection: Boolean;
  2733. var
  2734. FuncTypesCount, ParamsCount, ResultsCount: uint32;
  2735. FuncTypeId, WasmTypeId: Byte;
  2736. i, j: Integer;
  2737. wbt: TWasmBasicType;
  2738. begin
  2739. Result:=False;
  2740. if TypeSectionRead then
  2741. begin
  2742. InputError('Type section is duplicated');
  2743. exit;
  2744. end;
  2745. TypeSectionRead:=True;
  2746. if not ReadUleb32(FuncTypesCount) then
  2747. begin
  2748. InputError('Error reading the func types count');
  2749. exit;
  2750. end;
  2751. SetLength(FFuncTypes,FuncTypesCount);
  2752. for i:=0 to FuncTypesCount - 1 do
  2753. begin
  2754. FFuncTypes[i]:=TWasmFuncType.Create([],[]);
  2755. if not AReader.read(FuncTypeId,1) then
  2756. begin
  2757. InputError('Error reading the function type identifier');
  2758. exit;
  2759. end;
  2760. if FuncTypeId<>$60 then
  2761. begin
  2762. InputError('Incorrect function type identifier (expected $60, got $' + HexStr(FuncTypeId,2) + ')');
  2763. exit;
  2764. end;
  2765. if not ReadUleb32(ParamsCount) then
  2766. begin
  2767. InputError('Error reading the function parameters count');
  2768. exit;
  2769. end;
  2770. for j:=0 to ParamsCount-1 do
  2771. begin
  2772. if not AReader.read(WasmTypeId,1) then
  2773. begin
  2774. InputError('Error reading a function parameter basic type');
  2775. exit;
  2776. end;
  2777. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2778. begin
  2779. InputError('Unknown function parameter basic type: $' + HexStr(WasmTypeId,2));
  2780. exit;
  2781. end;
  2782. FFuncTypes[i].add_param(wbt);
  2783. end;
  2784. if not ReadUleb32(ResultsCount) then
  2785. begin
  2786. InputError('Error reading the function results count');
  2787. exit;
  2788. end;
  2789. for j:=0 to ResultsCount-1 do
  2790. begin
  2791. if not AReader.read(WasmTypeId,1) then
  2792. begin
  2793. InputError('Error reading a function result basic type');
  2794. exit;
  2795. end;
  2796. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2797. begin
  2798. InputError('Unknown function result basic type: $' + HexStr(WasmTypeId,2));
  2799. exit;
  2800. end;
  2801. FFuncTypes[i].add_result(wbt);
  2802. end;
  2803. end;
  2804. if AReader.Pos<>(SectionStart+SectionSize) then
  2805. begin
  2806. InputError('Unexpected type section size');
  2807. exit;
  2808. end;
  2809. Result:=true;
  2810. end;
  2811. function ReadImportSection: Boolean;
  2812. var
  2813. ImportsCount: uint32;
  2814. i: Integer;
  2815. ModName, Name: ansistring;
  2816. ImportType, TableElemTyp, TableLimitsKind, MemoryLimitsKind,
  2817. GlobalType, GlobalMutabilityType: Byte;
  2818. begin
  2819. Result:=False;
  2820. if ImportSectionRead then
  2821. begin
  2822. InputError('Import section is duplicated');
  2823. exit;
  2824. end;
  2825. ImportSectionRead:=True;
  2826. if not ReadUleb32(ImportsCount) then
  2827. begin
  2828. InputError('Error reading the imports count');
  2829. exit;
  2830. end;
  2831. for i:=0 to ImportsCount-1 do
  2832. begin
  2833. if not ReadName(ModName) then
  2834. begin
  2835. InputError('Error reading import module name');
  2836. exit;
  2837. end;
  2838. if not ReadName(Name) then
  2839. begin
  2840. InputError('Error import name');
  2841. exit;
  2842. end;
  2843. if not AReader.Read(ImportType,1) then
  2844. begin
  2845. InputError('Error reading import type');
  2846. exit;
  2847. end;
  2848. case ImportType of
  2849. $00: { func }
  2850. begin
  2851. Inc(FuncTypeImportsCount);
  2852. SetLength(FuncTypes,FuncTypeImportsCount);
  2853. with FuncTypes[FuncTypeImportsCount-1] do
  2854. begin
  2855. IsImport:=True;
  2856. ImportName:=Name;
  2857. ImportModName:=ModName;
  2858. if not ReadUleb32(typidx) then
  2859. begin
  2860. InputError('Error reading type index for func import');
  2861. exit;
  2862. end;
  2863. if typidx>high(FFuncTypes) then
  2864. begin
  2865. InputError('Type index in func import exceeds bounds of the types table');
  2866. exit;
  2867. end;
  2868. end;
  2869. end;
  2870. $01: { table }
  2871. begin
  2872. Inc(TableTypeImportsCount);
  2873. SetLength(TableTypes,TableTypeImportsCount);
  2874. with TableTypes[TableTypeImportsCount-1] do
  2875. begin
  2876. IsImport:=True;
  2877. ImportName:=Name;
  2878. ImportModName:=ModName;
  2879. if not AReader.read(TableElemTyp,1) then
  2880. begin
  2881. InputError('Error reading table element type for table import');
  2882. exit;
  2883. end;
  2884. if not decode_wasm_basic_type(TableElemTyp,reftype) then
  2885. begin
  2886. InputError('Invalid table element type for table import: $' + HexStr(TableElemTyp,2));
  2887. exit;
  2888. end;
  2889. if not (reftype in WasmReferenceTypes) then
  2890. begin
  2891. InputError('Table element type for table import must be a reference type');
  2892. exit;
  2893. end;
  2894. if not AReader.read(TableLimitsKind,1) then
  2895. begin
  2896. InputError('Error reading table limits kind for table import');
  2897. exit;
  2898. end;
  2899. case TableLimitsKind of
  2900. $00:
  2901. begin
  2902. limits.HasMax:=False;
  2903. limits.Max:=high(limits.Max);
  2904. if not ReadUleb32(limits.min) then
  2905. begin
  2906. InputError('Error reading table limits min for table import');
  2907. exit;
  2908. end;
  2909. end;
  2910. $01:
  2911. begin
  2912. limits.HasMax:=True;
  2913. if not ReadUleb32(limits.min) then
  2914. begin
  2915. InputError('Error reading table limits min for table import');
  2916. exit;
  2917. end;
  2918. if not ReadUleb32(limits.max) then
  2919. begin
  2920. InputError('Error reading table limits max for table import');
  2921. exit;
  2922. end;
  2923. if limits.min>limits.max then
  2924. begin
  2925. InputError('Table limits min exceed table limits max in table import');
  2926. exit;
  2927. end;
  2928. end;
  2929. else
  2930. begin
  2931. InputError('Unsupported table limits kind for table import: $' + HexStr(TableLimitsKind,2));
  2932. exit;
  2933. end;
  2934. end;
  2935. end;
  2936. end;
  2937. $02: { mem }
  2938. begin
  2939. Inc(MemTypeImportsCount);
  2940. SetLength(MemTypes,MemTypeImportsCount);
  2941. with MemTypes[MemTypeImportsCount-1] do
  2942. begin
  2943. IsImport:=True;
  2944. ImportName:=Name;
  2945. ImportModName:=ModName;
  2946. if not AReader.read(MemoryLimitsKind,1) then
  2947. begin
  2948. InputError('Error reading memory limits kind for memory import');
  2949. exit;
  2950. end;
  2951. case MemoryLimitsKind of
  2952. $00:
  2953. begin
  2954. limits.HasMax:=False;
  2955. limits.Max:=high(limits.Max);
  2956. if not ReadUleb32(limits.min) then
  2957. begin
  2958. InputError('Error reading memory limits min for memory import');
  2959. exit;
  2960. end;
  2961. end;
  2962. $01:
  2963. begin
  2964. limits.HasMax:=True;
  2965. if not ReadUleb32(limits.min) then
  2966. begin
  2967. InputError('Error reading memory limits min for memory import');
  2968. exit;
  2969. end;
  2970. if not ReadUleb32(limits.max) then
  2971. begin
  2972. InputError('Error reading memory limits max for memory import');
  2973. exit;
  2974. end;
  2975. if limits.Min>limits.Max then
  2976. begin
  2977. InputError('Memory limits min exceed memory limits max in memory import');
  2978. exit;
  2979. end;
  2980. end;
  2981. else
  2982. begin
  2983. InputError('Unsupported memory limits kind for memory import: $' + HexStr(MemoryLimitsKind,2));
  2984. exit;
  2985. end;
  2986. end;
  2987. end;
  2988. end;
  2989. $03: { global }
  2990. begin
  2991. Inc(GlobalTypeImportsCount);
  2992. SetLength(GlobalTypes,GlobalTypeImportsCount);
  2993. with GlobalTypes[GlobalTypeImportsCount-1] do
  2994. begin
  2995. IsImport:=True;
  2996. ImportName:=Name;
  2997. ImportModName:=ModName;
  2998. if not AReader.read(GlobalType,1) then
  2999. begin
  3000. InputError('Error reading global type for global import');
  3001. exit;
  3002. end;
  3003. if not decode_wasm_basic_type(GlobalType,valtype) then
  3004. begin
  3005. InputError('Unsupported global type for global import: ' + HexStr(GlobalType,2));
  3006. exit;
  3007. end;
  3008. if not AReader.read(GlobalMutabilityType,1) then
  3009. begin
  3010. InputError('Error reading global mutability flag for global import');
  3011. exit;
  3012. end;
  3013. case GlobalMutabilityType of
  3014. $00:
  3015. IsMutable:=False;
  3016. $01:
  3017. IsMutable:=True;
  3018. else
  3019. begin
  3020. InputError('Unknown global mutability flag for global import: $' + HexStr(GlobalMutabilityType,2));
  3021. exit;
  3022. end;
  3023. end;
  3024. end;
  3025. end;
  3026. else
  3027. begin
  3028. InputError('Unknown import type: $' + HexStr(ImportType,2));
  3029. exit;
  3030. end;
  3031. end;
  3032. end;
  3033. if AReader.Pos<>(SectionStart+SectionSize) then
  3034. begin
  3035. InputError('Unexpected import section size');
  3036. exit;
  3037. end;
  3038. Result:=true;
  3039. end;
  3040. function ReadFunctionSection: Boolean;
  3041. var
  3042. FunctionsCount: uint32;
  3043. i: Integer;
  3044. begin
  3045. Result:=False;
  3046. if FunctionSectionRead then
  3047. begin
  3048. InputError('Function section is duplicated');
  3049. exit;
  3050. end;
  3051. FunctionSectionRead:=True;
  3052. if not ReadUleb32(FunctionsCount) then
  3053. begin
  3054. InputError('Error reading the functions count');
  3055. exit;
  3056. end;
  3057. SetLength(FuncTypes, FuncTypeImportsCount + FunctionsCount);
  3058. for i:=0 to FunctionsCount-1 do
  3059. with FuncTypes[i + FuncTypeImportsCount] do
  3060. begin
  3061. IsImport:=False;
  3062. if not ReadUleb32(typidx) then
  3063. begin
  3064. InputError('Error reading type index for function');
  3065. exit;
  3066. end;
  3067. if typidx>high(FFuncTypes) then
  3068. begin
  3069. InputError('Type index in the function section exceeds bounds of the types table');
  3070. exit;
  3071. end;
  3072. end;
  3073. if AReader.Pos<>(SectionStart+SectionSize) then
  3074. begin
  3075. InputError('Unexpected function section size');
  3076. exit;
  3077. end;
  3078. Result:=true;
  3079. end;
  3080. function ReadGlobalSection: Boolean;
  3081. function ParseExpr(out Init: TGlobalInitializer): Boolean;
  3082. var
  3083. B, B2: Byte;
  3084. tmpU32: UInt32;
  3085. tmpU64: UInt64;
  3086. begin
  3087. Result:=False;
  3088. repeat
  3089. if not Read(B, 1) then
  3090. exit;
  3091. case B of
  3092. $0B: { end }
  3093. ;
  3094. $41: { i32.const }
  3095. begin
  3096. Init.typ:=wbt_i32;
  3097. if not ReadSleb32(Init.init_i32) then
  3098. exit;
  3099. end;
  3100. $42: { i64.const }
  3101. begin
  3102. Init.typ:=wbt_i64;
  3103. if not ReadSleb(Init.init_i64) then
  3104. exit;
  3105. end;
  3106. $43: { f32.const }
  3107. begin
  3108. Init.typ:=wbt_f32;
  3109. if not Read(tmpU32, 4) then
  3110. exit;
  3111. {$ifdef FPC_BIG_ENDIAN}
  3112. tmpU32:=SwapEndian(tmpU32);
  3113. {$endif FPC_BIG_ENDIAN}
  3114. Move(tmpU32,Init.init_f32,4);
  3115. end;
  3116. $44: { f64.const }
  3117. begin
  3118. Init.typ:=wbt_f64;
  3119. if not Read(tmpU64, 8) then
  3120. exit;
  3121. {$ifdef FPC_BIG_ENDIAN}
  3122. tmpU64:=SwapEndian(tmpU64);
  3123. {$endif FPC_BIG_ENDIAN}
  3124. Move(tmpU64,Init.init_f64,8);
  3125. end;
  3126. $D0: { ref.null }
  3127. begin
  3128. if not Read(B2, 1) then
  3129. exit;
  3130. if not decode_wasm_basic_type(B2, Init.typ) then
  3131. exit;
  3132. if not (Init.typ in WasmReferenceTypes) then
  3133. exit;
  3134. end;
  3135. else
  3136. begin
  3137. InputError('Unsupported opcode in global initializer');
  3138. exit;
  3139. end;
  3140. end;
  3141. until b = $0B;
  3142. Result:=True;
  3143. end;
  3144. var
  3145. GlobalsCount: uint32;
  3146. i: Integer;
  3147. vt: Byte;
  3148. mut: Byte;
  3149. begin
  3150. Result:=False;
  3151. if GlobalSectionRead then
  3152. begin
  3153. InputError('Global section is duplicated');
  3154. exit;
  3155. end;
  3156. GlobalSectionRead:=True;
  3157. if not ReadUleb32(GlobalsCount) then
  3158. begin
  3159. InputError('Error reading the globals count from the global section');
  3160. exit;
  3161. end;
  3162. SetLength(GlobalTypes,Length(GlobalTypes)+GlobalsCount);
  3163. for i:=0 to GlobalsCount-1 do
  3164. with GlobalTypes[i + GlobalTypeImportsCount] do
  3165. begin
  3166. if not read(vt,1) then
  3167. begin
  3168. InputError('Error reading the type of a global from the global section');
  3169. exit;
  3170. end;
  3171. if not decode_wasm_basic_type(vt,valtype) then
  3172. begin
  3173. InputError('Unsupported type of global in the global section');
  3174. exit;
  3175. end;
  3176. if not read(mut,1) then
  3177. begin
  3178. InputError('Error reading the mutability flag of a global in the global section');
  3179. exit;
  3180. end;
  3181. case mut of
  3182. $00:
  3183. IsMutable:=False;
  3184. $01:
  3185. IsMutable:=True;
  3186. else
  3187. begin
  3188. InputError('Unsupported value (' + tostr(mut) + ') for the mutability flag of a global in the global section');
  3189. exit;
  3190. end;
  3191. end;
  3192. if not ParseExpr(GlobalInit) then
  3193. begin
  3194. InputError('Error parsing the global initializer expression in the global section');
  3195. exit;
  3196. end;
  3197. if GlobalInit.typ<>valtype then
  3198. begin
  3199. InputError('Initializer expression for global produces a type, which does not match the type of the global');
  3200. exit;
  3201. end;
  3202. end;
  3203. if AReader.Pos<>(SectionStart+SectionSize) then
  3204. begin
  3205. InputError('Unexpected global section size');
  3206. exit;
  3207. end;
  3208. Result:=True;
  3209. end;
  3210. function ReadExportSection: Boolean;
  3211. var
  3212. ExportsCount, FuncIdx, TableIdx, MemIdx, GlobalIdx: uint32;
  3213. i: Integer;
  3214. Name: ansistring;
  3215. ExportType: Byte;
  3216. begin
  3217. Result:=False;
  3218. if ExportSectionRead then
  3219. begin
  3220. InputError('Export section is duplicated');
  3221. exit;
  3222. end;
  3223. ExportSectionRead:=True;
  3224. if not ReadUleb32(ExportsCount) then
  3225. begin
  3226. InputError('Error reading the exports count from the export section');
  3227. exit;
  3228. end;
  3229. for i:=0 to ExportsCount-1 do
  3230. begin
  3231. if not ReadName(Name) then
  3232. begin
  3233. InputError('Error reading an export name from the export section');
  3234. exit;
  3235. end;
  3236. if not Read(ExportType,1) then
  3237. begin
  3238. InputError('Error reading an export type from the export section');
  3239. exit;
  3240. end;
  3241. case ExportType of
  3242. $00: { func }
  3243. begin
  3244. if not ReadUleb32(FuncIdx) then
  3245. begin
  3246. InputError('Error reading a func index from the export section');
  3247. exit;
  3248. end;
  3249. if FuncIdx>high(FuncTypes) then
  3250. begin
  3251. InputError('Func index too high in the export section');
  3252. exit;
  3253. end;
  3254. with FuncTypes[FuncIdx] do
  3255. begin
  3256. IsExported:=True;
  3257. ExportName:=Name;
  3258. end;
  3259. end;
  3260. $01: { table }
  3261. begin
  3262. if not ReadUleb32(TableIdx) then
  3263. begin
  3264. InputError('Error reading a table index from the export section');
  3265. exit;
  3266. end;
  3267. if TableIdx>high(TableTypes) then
  3268. begin
  3269. InputError('Table index too high in the export section');
  3270. exit;
  3271. end;
  3272. with TableTypes[TableIdx] do
  3273. begin
  3274. IsExported:=True;
  3275. ExportName:=Name;
  3276. end;
  3277. end;
  3278. $02: { mem }
  3279. begin
  3280. if not ReadUleb32(MemIdx) then
  3281. begin
  3282. InputError('Error reading a mem index from the export section');
  3283. exit;
  3284. end;
  3285. if MemIdx>high(MemTypes) then
  3286. begin
  3287. InputError('Mem index too high in the export section');
  3288. exit;
  3289. end;
  3290. with MemTypes[MemIdx] do
  3291. begin
  3292. IsExported:=True;
  3293. ExportName:=Name;
  3294. end;
  3295. end;
  3296. $03: { global }
  3297. begin
  3298. if not ReadUleb32(GlobalIdx) then
  3299. begin
  3300. InputError('Error reading a global index from the export section');
  3301. exit;
  3302. end;
  3303. if GlobalIdx>high(GlobalTypes) then
  3304. begin
  3305. InputError('Global index too high in the export section');
  3306. exit;
  3307. end;
  3308. with GlobalTypes[GlobalIdx] do
  3309. begin
  3310. IsExported:=True;
  3311. ExportName:=Name;
  3312. end;
  3313. end;
  3314. else
  3315. begin
  3316. InputError('Unsupported export type in the export section: ' + tostr(ExportType));
  3317. exit;
  3318. end;
  3319. end;
  3320. end;
  3321. if AReader.Pos<>(SectionStart+SectionSize) then
  3322. begin
  3323. InputError('Unexpected export section size');
  3324. exit;
  3325. end;
  3326. Result:=True;
  3327. end;
  3328. function ReadCodeSection: Boolean;
  3329. var
  3330. CodeEntriesCount: uint32;
  3331. i: Integer;
  3332. begin
  3333. Result:=False;
  3334. if CodeSectionRead then
  3335. begin
  3336. InputError('Code section is duplicated');
  3337. exit;
  3338. end;
  3339. CodeSectionRead:=True;
  3340. CodeSectionIndex:=SectionIndex;
  3341. if not ReadUleb32(CodeEntriesCount) then
  3342. begin
  3343. InputError('Error reading the code entries cound from the code section');
  3344. exit;
  3345. end;
  3346. if CodeEntriesCount <> (Length(FuncTypes) - FuncTypeImportsCount) then
  3347. begin
  3348. InputError('Code segment count in the code section does not match the function definition count in the function section');
  3349. exit;
  3350. end;
  3351. SetLength(CodeSegments,CodeEntriesCount);
  3352. for i:=0 to CodeEntriesCount-1 do
  3353. with CodeSegments[i] do
  3354. begin
  3355. if not ReadUleb32(CodeSize) then
  3356. begin
  3357. InputError('Error reading the code size of an entry in the code section');
  3358. exit;
  3359. end;
  3360. if (AReader.Pos+CodeSize)>(SectionStart+SectionSize) then
  3361. begin
  3362. InputError('Code segment exceeds the bounds of the code section');
  3363. exit;
  3364. end;
  3365. DataPos:=AReader.Pos;
  3366. CodeSectionOffset:=AReader.Pos-SectionStart;
  3367. AReader.Seek(AReader.Pos+CodeSize);
  3368. end;
  3369. if AReader.Pos<>(SectionStart+SectionSize) then
  3370. begin
  3371. InputError('Unexpected code section size');
  3372. exit;
  3373. end;
  3374. Result:=true;
  3375. end;
  3376. function ReadDataSection: Boolean;
  3377. function ReadExpr(out ExprV: int32): Boolean;
  3378. var
  3379. b: Byte;
  3380. begin
  3381. Result:=False;
  3382. if not Read(b,1) then
  3383. exit;
  3384. if b<>$41 then
  3385. begin
  3386. InputError('Only i32.const expressions supported');
  3387. exit;
  3388. end;
  3389. if not ReadSleb32(ExprV) then
  3390. exit;
  3391. if not Read(b,1) then
  3392. exit;
  3393. if b<>$0B then
  3394. begin
  3395. InputError('Only single const expressions supported');
  3396. exit;
  3397. end;
  3398. Result:=True;
  3399. end;
  3400. var
  3401. DataCount: uint32;
  3402. DataType: Byte;
  3403. i: Integer;
  3404. begin
  3405. Result:=False;
  3406. if DataSectionRead then
  3407. begin
  3408. InputError('Data section is duplicated');
  3409. exit;
  3410. end;
  3411. DataSectionRead:=True;
  3412. DataSectionIndex:=SectionIndex;
  3413. if not ReadUleb32(DataCount) then
  3414. begin
  3415. InputError('Error reading the data entries count from the data section');
  3416. exit;
  3417. end;
  3418. if DataCountSectionRead then
  3419. begin
  3420. if Length(DataSegments)<>DataCount then
  3421. begin
  3422. InputError('Data entries count in the data section do not match the number, specified in the data count section');
  3423. exit;
  3424. end;
  3425. end
  3426. else
  3427. SetLength(DataSegments,DataCount);
  3428. for i:=0 to DataCount-1 do
  3429. with DataSegments[i] do
  3430. begin
  3431. if not read(DataType, 1) then
  3432. begin
  3433. InputError('Error reading data type of segment from the data section');
  3434. exit;
  3435. end;
  3436. case DataType of
  3437. 0:
  3438. begin
  3439. Active:=True;
  3440. MemIdx:=0;
  3441. if not ReadExpr(Offset) then
  3442. begin
  3443. InputError('Error reading memory offset of segment from the data section');
  3444. exit;
  3445. end;
  3446. end;
  3447. 1:
  3448. Active:=False;
  3449. 2:
  3450. begin
  3451. Active:=True;
  3452. if not ReadUleb32(MemIdx) then
  3453. begin
  3454. InputError('Error reading MemIdx of segment from the data section');
  3455. exit;
  3456. end;
  3457. if not ReadExpr(Offset) then
  3458. begin
  3459. InputError('Error reading memory offset of segment from the data section');
  3460. exit;
  3461. end;
  3462. end;
  3463. else
  3464. begin
  3465. InputError('Unsupported data type of segment in the data section: ' + tostr(DataType));
  3466. exit;
  3467. end;
  3468. end;
  3469. if MemIdx<>0 then
  3470. begin
  3471. InputError('Memory index other than 0 not supported (got ' + tostr(MemIdx) + ')');
  3472. exit;
  3473. end;
  3474. if not Active then
  3475. begin
  3476. InputError('Passive memory segments not supported');
  3477. exit;
  3478. end;
  3479. if not ReadUleb32(Len) then
  3480. begin
  3481. InputError('Error reading data segment length');
  3482. exit;
  3483. end;
  3484. if (AReader.Pos+Len)>(SectionStart+SectionSize) then
  3485. begin
  3486. InputError('Data segment exceeds the bounds of the data section');
  3487. exit;
  3488. end;
  3489. DataPos:=AReader.Pos;
  3490. DataSectionOffset:=AReader.Pos-SectionStart;
  3491. AReader.Seek(AReader.Pos+Len);
  3492. end;
  3493. if AReader.Pos<>(SectionStart+SectionSize) then
  3494. begin
  3495. InputError('Unexpected data section size');
  3496. exit;
  3497. end;
  3498. Result:=true;
  3499. end;
  3500. function ReadDataCountSection: Boolean;
  3501. var
  3502. DataCount: uint32;
  3503. begin
  3504. Result:=False;
  3505. if DataCountSectionRead then
  3506. begin
  3507. InputError('Data count section is duplicated');
  3508. exit;
  3509. end;
  3510. DataCountSectionRead:=True;
  3511. if DataSectionRead then
  3512. begin
  3513. InputError('The data count section must occur before the data section');
  3514. exit;
  3515. end;
  3516. if not ReadUleb32(DataCount) then
  3517. begin
  3518. InputError('Error reading the data count from the data count section');
  3519. exit;
  3520. end;
  3521. if AReader.Pos<>(SectionStart+SectionSize) then
  3522. begin
  3523. InputError('Unexpected data count section size');
  3524. exit;
  3525. end;
  3526. SetLength(DataSegments, DataCount);
  3527. Result:=true;
  3528. end;
  3529. begin
  3530. Result:=False;
  3531. Inc(SectionIndex);
  3532. if not AReader.read(SectionId,1) then
  3533. begin
  3534. InputError('Error reading section ID');
  3535. exit;
  3536. end;
  3537. CheckSectionBounds:=false;
  3538. if not ReadUleb32(SectionSize) then
  3539. begin
  3540. InputError('Error reading section size');
  3541. exit;
  3542. end;
  3543. if (AReader.Pos+SectionSize)>AReader.size then
  3544. begin
  3545. InputError('Section exceeds beyond the end of file');
  3546. exit;
  3547. end;
  3548. SectionStart:=AReader.Pos;
  3549. CheckSectionBounds:=true;
  3550. case SectionId of
  3551. Byte(wsiCustom):
  3552. if not ReadCustomSection then
  3553. begin
  3554. InputError('Error encountered, while reading a custom section');
  3555. exit;
  3556. end;
  3557. Byte(wsiType):
  3558. if not ReadTypeSection then
  3559. begin
  3560. InputError('Error reading the type section');
  3561. exit;
  3562. end;
  3563. Byte(wsiImport):
  3564. if not ReadImportSection then
  3565. begin
  3566. InputError('Error reading the import section');
  3567. exit;
  3568. end;
  3569. Byte(wsiFunction):
  3570. if not ReadFunctionSection then
  3571. begin
  3572. InputError('Error reading the function section');
  3573. exit;
  3574. end;
  3575. Byte(wsiGlobal):
  3576. if not ReadGlobalSection then
  3577. begin
  3578. InputError('Error reading the global section');
  3579. exit;
  3580. end;
  3581. Byte(wsiExport):
  3582. if not ReadExportSection then
  3583. begin
  3584. InputError('Error reading the export section');
  3585. exit;
  3586. end;
  3587. Byte(wsiCode):
  3588. if not ReadCodeSection then
  3589. begin
  3590. InputError('Error reading the code section');
  3591. exit;
  3592. end;
  3593. Byte(wsiData):
  3594. if not ReadDataSection then
  3595. begin
  3596. InputError('Error reading the data section');
  3597. exit;
  3598. end;
  3599. Byte(wsiDataCount):
  3600. begin
  3601. if not ReadDataCountSection then
  3602. begin
  3603. InputError('Error reading the data count section');
  3604. exit;
  3605. end;
  3606. end
  3607. else
  3608. begin
  3609. InputError('Unknown section: ' + ToStr(SectionId));
  3610. exit;
  3611. end;
  3612. end;
  3613. if SectionSize>0 then
  3614. AReader.seek(SectionStart+SectionSize);
  3615. Result:=True;
  3616. end;
  3617. function FindCodeSegment(Ofs: uint32): Integer;
  3618. var
  3619. L, R, M: Integer;
  3620. begin
  3621. L:=Low(CodeSegments);
  3622. R:=High(CodeSegments);
  3623. while L<=R do
  3624. begin
  3625. M:=(L+R) div 2;
  3626. if (CodeSegments[M].CodeSectionOffset+CodeSegments[M].CodeSize-1) < Ofs then
  3627. L:=M+1
  3628. else if CodeSegments[M].CodeSectionOffset > Ofs then
  3629. R:=M-1
  3630. else
  3631. begin
  3632. Result:=M;
  3633. exit;
  3634. end;
  3635. end;
  3636. Result:=-1;
  3637. end;
  3638. function FindDataSegment(Ofs: uint32): Integer;
  3639. var
  3640. L, R, M: Integer;
  3641. begin
  3642. L:=Low(DataSegments);
  3643. R:=High(DataSegments);
  3644. while L<=R do
  3645. begin
  3646. M:=(L+R) div 2;
  3647. if (DataSegments[M].DataSectionOffset+DataSegments[M].Len-1) < Ofs then
  3648. L:=M+1
  3649. else if DataSegments[M].DataSectionOffset > Ofs then
  3650. R:=M-1
  3651. else
  3652. begin
  3653. Result:=M;
  3654. exit;
  3655. end;
  3656. end;
  3657. Result:=-1;
  3658. end;
  3659. var
  3660. ModuleMagic: array [0..3] of Byte;
  3661. ModuleVersion: array [0..3] of Byte;
  3662. i, j, FirstDataSegmentIdx, SegI: Integer;
  3663. CurrSec, ObjSec: TObjSection;
  3664. BaseSectionOffset: UInt32;
  3665. ObjReloc: TWasmObjRelocation;
  3666. begin
  3667. FReader:=AReader;
  3668. InputFileName:=AReader.FileName;
  3669. objdata:=CObjData.Create(InputFileName);
  3670. result:=false;
  3671. CodeSegments:=nil;
  3672. DataSegments:=nil;
  3673. SymbolTable:=nil;
  3674. RelocationTable:=nil;
  3675. SetLength(RelocationTable,2);
  3676. FuncTypes:=nil;
  3677. FuncTypeImportsCount:=0;
  3678. TableTypes:=nil;
  3679. TableTypeImportsCount:=0;
  3680. MemTypes:=nil;
  3681. MemTypeImportsCount:=0;
  3682. GlobalTypes:=nil;
  3683. GlobalTypeImportsCount:=0;
  3684. if not AReader.read(ModuleMagic,4) then
  3685. exit;
  3686. for i:=0 to 3 do
  3687. if ModuleMagic[i]<>WasmModuleMagic[i] then
  3688. exit;
  3689. if not AReader.read(ModuleVersion,4) then
  3690. exit;
  3691. for i:=0 to 3 do
  3692. if ModuleVersion[i]<>WasmVersion[i] then
  3693. exit;
  3694. while AReader.Pos<AReader.size do
  3695. if not ReadSection then
  3696. exit;
  3697. { fill the code segment names }
  3698. for i:=low(SymbolTable) to high(SymbolTable) do
  3699. with SymbolTable[i] do
  3700. if (SymKind=byte(SYMTAB_FUNCTION)) and ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  3701. begin
  3702. if FuncTypes[SymIndex].IsImport then
  3703. begin
  3704. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_FUNCTION symbol, that is an import');
  3705. exit;
  3706. end;
  3707. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  3708. begin
  3709. with CodeSegments[SymIndex-FuncTypeImportsCount] do
  3710. begin
  3711. SegName:='.text.n_'+SymName;
  3712. SegIsExported:=FuncTypes[SymIndex].IsExported;
  3713. end;
  3714. end;
  3715. end;
  3716. { create segments }
  3717. for i:=low(CodeSegments) to high(CodeSegments) do
  3718. with CodeSegments[i] do
  3719. begin
  3720. if SegName='' then
  3721. begin
  3722. InputError('Code section ' + tostr(i) + ' does not have a main symbol defined in the symbol table');
  3723. exit;
  3724. end;
  3725. if SegIsExported then
  3726. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load,oso_keep],false)
  3727. else
  3728. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load],false);
  3729. CurrSec.DataPos:=DataPos;
  3730. CurrSec.Size:=CodeSize;
  3731. end;
  3732. FirstDataSegmentIdx:=ObjData.ObjSectionList.Count;
  3733. for i:=low(DataSegments) to high(DataSegments) do
  3734. with DataSegments[i] do
  3735. if Active then
  3736. begin
  3737. CurrSec:=ObjData.createsection(SegName,1 shl SegAlignment,[oso_Data,oso_load,oso_write],false);
  3738. CurrSec.DataPos:=DataPos;
  3739. CurrSec.MemPos:=Offset;
  3740. CurrSec.Size:=Len;
  3741. end;
  3742. ReadSectionContent(ObjData);
  3743. for i:=low(SymbolTable) to high(SymbolTable) do
  3744. with SymbolTable[i] do
  3745. case SymKind of
  3746. byte(SYMTAB_DATA):
  3747. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3748. begin
  3749. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3750. objsym.bind:=AB_EXTERNAL;
  3751. objsym.typ:=AT_DATA;
  3752. objsym.objsection:=nil;
  3753. objsym.offset:=0;
  3754. objsym.size:=0;
  3755. end
  3756. else
  3757. begin
  3758. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3759. if (SymFlags and WASM_SYM_BINDING_LOCAL)<> 0 then
  3760. objsym.bind:=AB_LOCAL
  3761. else
  3762. objsym.bind:=AB_GLOBAL;
  3763. objsym.typ:=AT_DATA;
  3764. objsym.objsection:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SymIndex]);
  3765. objsym.offset:=SymOffset;
  3766. objsym.size:=SymSize;
  3767. end;
  3768. byte(SYMTAB_FUNCTION):
  3769. begin
  3770. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3771. begin
  3772. if not FuncTypes[SymIndex].IsImport then
  3773. begin
  3774. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_FUNCTION symbol, that is not an import');
  3775. exit;
  3776. end;
  3777. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  3778. begin
  3779. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3780. objsym.bind:=AB_EXTERNAL;
  3781. objsym.typ:=AT_FUNCTION;
  3782. objsym.objsection:=nil;
  3783. objsym.offset:=0;
  3784. objsym.size:=0;
  3785. objsym.LinkingData.ImportModule:=FuncTypes[SymIndex].ImportModName;
  3786. objsym.LinkingData.ImportName:=FuncTypes[SymIndex].ImportName;
  3787. end
  3788. else
  3789. begin
  3790. if FuncTypes[SymIndex].ImportModName = 'env' then
  3791. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportName))
  3792. else
  3793. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportModName + '.' + FuncTypes[SymIndex].ImportName));
  3794. objsym.bind:=AB_EXTERNAL;
  3795. objsym.typ:=AT_FUNCTION;
  3796. objsym.objsection:=nil;
  3797. objsym.offset:=0;
  3798. objsym.size:=0;
  3799. end;
  3800. end
  3801. else
  3802. begin
  3803. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3804. objsym.bind:=AB_GLOBAL;
  3805. objsym.typ:=AT_FUNCTION;
  3806. objsym.objsection:=TObjSection(ObjData.ObjSectionList[SymIndex-FuncTypeImportsCount]);
  3807. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  3808. TWasmObjSection(ObjData.ObjSectionList[SymIndex-FuncTypeImportsCount]).MainFuncSymbol:=objsym;
  3809. objsym.offset:=0;
  3810. objsym.size:=objsym.objsection.Size;
  3811. end;
  3812. objsym.LinkingData.FuncType:=TWasmFuncType.Create(FFuncTypes[FuncTypes[SymIndex].typidx]);
  3813. objsym.LinkingData.IsExported:=FuncTypes[SymIndex].IsExported;
  3814. objsym.LinkingData.ExportName:=FuncTypes[SymIndex].ExportName;
  3815. end;
  3816. byte(SYMTAB_GLOBAL):
  3817. begin
  3818. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3819. begin
  3820. if not GlobalTypes[SymIndex].IsImport then
  3821. begin
  3822. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_GLOBAL symbol, that is not an import');
  3823. exit;
  3824. end;
  3825. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  3826. begin
  3827. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3828. objsym.bind:=AB_EXTERNAL;
  3829. objsym.typ:=AT_WASM_GLOBAL;
  3830. objsym.objsection:=nil;
  3831. objsym.offset:=0;
  3832. objsym.size:=1;
  3833. objsym.LinkingData.ImportModule:=GlobalTypes[SymIndex].ImportModName;
  3834. objsym.LinkingData.ImportName:=GlobalTypes[SymIndex].ImportName;
  3835. end
  3836. else
  3837. begin
  3838. if GlobalTypes[SymIndex].ImportModName = 'env' then
  3839. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportName))
  3840. else
  3841. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportModName + '.' + GlobalTypes[SymIndex].ImportName));
  3842. objsym.bind:=AB_EXTERNAL;
  3843. objsym.typ:=AT_WASM_GLOBAL;
  3844. objsym.objsection:=nil;
  3845. objsym.offset:=0;
  3846. objsym.size:=1;
  3847. end;
  3848. end
  3849. else
  3850. begin
  3851. if GlobalTypes[SymIndex].IsImport then
  3852. begin
  3853. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_GLOBAL symbol, that is an import');
  3854. exit;
  3855. end;
  3856. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  3857. objsym.bind:=AB_GLOBAL;
  3858. objsym.typ:=AT_WASM_GLOBAL;
  3859. objsym.objsection:=ObjData.createsection('.wasm_globals.n_'+SymName,1,[oso_Data,oso_load],true);
  3860. if objsym.objsection.Size=0 then
  3861. objsym.objsection.WriteZeros(1);
  3862. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  3863. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  3864. objsym.offset:=0;
  3865. objsym.size:=1;
  3866. objsym.LinkingData.GlobalInitializer:=GlobalTypes[SymIndex].GlobalInit;
  3867. end;
  3868. objsym.LinkingData.GlobalType:=GlobalTypes[SymIndex].valtype;
  3869. objsym.LinkingData.GlobalIsMutable:=GlobalTypes[SymIndex].IsMutable;
  3870. objsym.LinkingData.IsExported:=GlobalTypes[SymIndex].IsExported;
  3871. objsym.LinkingData.ExportName:=GlobalTypes[SymIndex].ExportName;
  3872. end;
  3873. byte(SYMTAB_SECTION),
  3874. byte(SYMTAB_EVENT),
  3875. byte(SYMTAB_TABLE):
  3876. {TODO};
  3877. else
  3878. internalerror(2023122701);
  3879. end;
  3880. for j:=0 to high(RelocationTable) do
  3881. for i:=0 to high(RelocationTable[j]) do
  3882. with RelocationTable[j,i] do
  3883. begin
  3884. case j of
  3885. 0:
  3886. begin
  3887. SegI:=FindCodeSegment(RelocOffset);
  3888. if SegI=-1 then
  3889. begin
  3890. InputError('Relocation offset not found in code segment');
  3891. Exit;
  3892. end;
  3893. BaseSectionOffset:=CodeSegments[SegI].CodeSectionOffset;
  3894. ObjSec:=TObjSection(ObjData.ObjSectionList[SegI]);
  3895. end;
  3896. 1:
  3897. begin
  3898. SegI:=FindDataSegment(RelocOffset);
  3899. if SegI=-1 then
  3900. begin
  3901. InputError('Relocation offset not found in data segment');
  3902. Exit;
  3903. end;
  3904. BaseSectionOffset:=DataSegments[SegI].DataSectionOffset;
  3905. ObjSec:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SegI]);
  3906. end
  3907. else
  3908. internalerror(2023122801);
  3909. end;
  3910. case TWasmRelocationType(RelocType) of
  3911. R_WASM_FUNCTION_INDEX_LEB:
  3912. begin
  3913. if RelocIndex>high(SymbolTable) then
  3914. begin
  3915. InputError('Symbol index in relocation too high');
  3916. exit;
  3917. end;
  3918. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3919. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_FUNCTION_INDEX_LEB))
  3920. else
  3921. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3922. end;
  3923. R_WASM_TABLE_INDEX_SLEB:
  3924. begin
  3925. if RelocIndex>high(SymbolTable) then
  3926. begin
  3927. InputError('Symbol index in relocation too high');
  3928. exit;
  3929. end;
  3930. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3931. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB))
  3932. else
  3933. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3934. end;
  3935. R_WASM_TABLE_INDEX_I32:
  3936. begin
  3937. if RelocIndex>high(SymbolTable) then
  3938. begin
  3939. InputError('Symbol index in relocation too high');
  3940. exit;
  3941. end;
  3942. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3943. begin
  3944. if SymbolTable[RelocIndex].ObjSym.typ<>AT_FUNCTION then
  3945. begin
  3946. InputError('R_WASM_TABLE_INDEX_I32 relocation must point to a function symbol');
  3947. exit;
  3948. end;
  3949. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE))
  3950. end
  3951. else
  3952. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3953. end;
  3954. R_WASM_MEMORY_ADDR_LEB:
  3955. begin
  3956. if RelocIndex>high(SymbolTable) then
  3957. begin
  3958. InputError('Symbol index in relocation too high');
  3959. exit;
  3960. end;
  3961. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3962. begin
  3963. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_LEB);
  3964. ObjReloc.Addend:=RelocAddend;
  3965. ObjSec.ObjRelocations.Add(ObjReloc);
  3966. end
  3967. else
  3968. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3969. end;
  3970. R_WASM_MEMORY_ADDR_SLEB:
  3971. begin
  3972. if RelocIndex>high(SymbolTable) then
  3973. begin
  3974. InputError('Symbol index in relocation too high');
  3975. exit;
  3976. end;
  3977. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3978. begin
  3979. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB);
  3980. ObjReloc.Addend:=RelocAddend;
  3981. ObjSec.ObjRelocations.Add(ObjReloc);
  3982. end
  3983. else
  3984. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  3985. end;
  3986. R_WASM_MEMORY_ADDR_I32:
  3987. begin
  3988. if RelocIndex>high(SymbolTable) then
  3989. begin
  3990. InputError('Symbol index in relocation too high');
  3991. exit;
  3992. end;
  3993. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  3994. begin
  3995. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  3996. ObjReloc.Addend:=RelocAddend;
  3997. ObjSec.ObjRelocations.Add(ObjReloc);
  3998. end
  3999. else
  4000. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  4001. end;
  4002. R_WASM_TYPE_INDEX_LEB:
  4003. begin
  4004. if RelocIndex>high(FFuncTypes) then
  4005. begin
  4006. InputError('Type index in relocation too high');
  4007. exit;
  4008. end;
  4009. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateFuncType(RelocOffset-BaseSectionOffset,FFuncTypes[RelocIndex]));
  4010. end;
  4011. R_WASM_FUNCTION_OFFSET_I32:
  4012. begin
  4013. if RelocIndex>high(SymbolTable) then
  4014. begin
  4015. InputError('Symbol index in relocation too high');
  4016. exit;
  4017. end;
  4018. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  4019. begin
  4020. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  4021. ObjReloc.Addend:=RelocAddend;
  4022. ObjSec.ObjRelocations.Add(ObjReloc);
  4023. end
  4024. else
  4025. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  4026. end;
  4027. R_WASM_SECTION_OFFSET_I32:
  4028. begin
  4029. InputError('R_WASM_SECTION_OFFSET_I32 relocations not yet implemented');
  4030. exit;
  4031. end;
  4032. R_WASM_GLOBAL_INDEX_LEB:
  4033. begin
  4034. if RelocIndex>high(SymbolTable) then
  4035. begin
  4036. InputError('Symbol index in relocation too high');
  4037. exit;
  4038. end;
  4039. if Assigned(SymbolTable[RelocIndex].ObjSym) then
  4040. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_GLOBAL_INDEX_LEB))
  4041. else
  4042. Writeln('Warning! No object symbol created for ', SymbolTable[RelocIndex].SymName);
  4043. end;
  4044. R_WASM_TAG_INDEX_LEB:
  4045. begin
  4046. InputError('R_WASM_TAG_INDEX_LEB relocations not yet implemented');
  4047. exit;
  4048. end;
  4049. else
  4050. internalerror(2023122802);
  4051. end;
  4052. end;
  4053. Result:=True;
  4054. end;
  4055. {****************************************************************************
  4056. TWasmExeOutput
  4057. ****************************************************************************}
  4058. procedure TWasmExeOutput.WriteWasmSection(wsid: TWasmSectionID);
  4059. var
  4060. b: byte;
  4061. begin
  4062. b:=ord(wsid);
  4063. Writer.write(b,1);
  4064. WriteUleb(Writer,FWasmSections[wsid].size);
  4065. Writer.writearray(FWasmSections[wsid]);
  4066. end;
  4067. function TWasmExeOutput.writeData: boolean;
  4068. procedure WriteImportSection;
  4069. var
  4070. imports_count: SizeInt;
  4071. i: Integer;
  4072. begin
  4073. imports_count:=Length(FFunctionImports);
  4074. WriteUleb(FWasmSections[wsiImport],imports_count);
  4075. for i:=0 to Length(FFunctionImports)-1 do
  4076. with FFunctionImports[i] do
  4077. begin
  4078. WriteName(FWasmSections[wsiImport],ModName);
  4079. WriteName(FWasmSections[wsiImport],Name);
  4080. WriteByte(FWasmSections[wsiImport],$00);
  4081. WriteUleb(FWasmSections[wsiImport],TypeIdx);
  4082. end;
  4083. end;
  4084. procedure WriteCodeSegments;
  4085. var
  4086. i: Integer;
  4087. exesec: TExeSection;
  4088. objsec: TWasmObjSection;
  4089. begin
  4090. exesec:=FindExeSection('.text');
  4091. if not assigned(exesec) then
  4092. internalerror(2023123102);
  4093. if not (oso_Data in exesec.SecOptions) then
  4094. internalerror(2023123103);
  4095. WriteUleb(FWasmSections[wsiFunction],exesec.ObjSectionList.Count);
  4096. WriteUleb(FWasmSections[wsiCode],exesec.ObjSectionList.Count);
  4097. for i:=0 to exesec.ObjSectionList.Count-1 do
  4098. begin
  4099. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4100. if not (oso_data in objsec.secoptions) then
  4101. internalerror(2023123104);
  4102. if not assigned(objsec.data) then
  4103. internalerror(2023123105);
  4104. if objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex<>(i+Length(FFunctionImports)) then
  4105. internalerror(2024010101);
  4106. WriteUleb(FWasmSections[wsiFunction],objsec.MainFuncSymbol.LinkingData.ExeTypeIndex);
  4107. WriteUleb(FWasmSections[wsiCode],objsec.Data.size);
  4108. objsec.Data.seek(0);
  4109. CopyDynamicArray(objsec.Data,FWasmSections[wsiCode],objsec.Data.size);
  4110. end;
  4111. end;
  4112. procedure WriteDataSegments;
  4113. procedure WriteExeSection(exesec: TExeSection);
  4114. var
  4115. i: Integer;
  4116. objsec: TObjSection;
  4117. exesecdatapos: LongWord;
  4118. dpos, pad: QWord;
  4119. begin
  4120. WriteByte(FWasmSections[wsiData],0);
  4121. WriteByte(FWasmSections[wsiData],$41); { i32.const }
  4122. WriteSleb(FWasmSections[wsiData],longint(exesec.MemPos));
  4123. WriteByte(FWasmSections[wsiData],$0B); { end }
  4124. WriteUleb(FWasmSections[wsiData],exesec.Size);
  4125. exesecdatapos:=FWasmSections[wsiData].size;
  4126. for i:=0 to exesec.ObjSectionList.Count-1 do
  4127. begin
  4128. objsec:=TObjSection(exesec.ObjSectionList[i]);
  4129. if not (oso_data in objsec.secoptions) then
  4130. internalerror(2024010104);
  4131. if not assigned(objsec.data) then
  4132. internalerror(2024010105);
  4133. dpos:=objsec.MemPos-exesec.MemPos+exesecdatapos;
  4134. pad:=dpos-FWasmSections[wsiData].size;
  4135. { objsection must be within SecAlign bytes from the previous one }
  4136. if (dpos<FWasmSections[wsiData].Size) or
  4137. (pad>=max(objsec.SecAlign,1)) then
  4138. internalerror(2024010106);
  4139. writeZeros(FWasmSections[wsiData],pad);
  4140. objsec.data.seek(0);
  4141. CopyDynamicArray(objsec.data,FWasmSections[wsiData],objsec.data.size);
  4142. end;
  4143. if (FWasmSections[wsiData].size-exesecdatapos)<>exesec.Size then
  4144. internalerror(2024010107);
  4145. end;
  4146. var
  4147. DataCount: Integer;
  4148. begin
  4149. DataCount:=2;
  4150. WriteUleb(FWasmSections[wsiDataCount],DataCount);
  4151. WriteUleb(FWasmSections[wsiData],DataCount);
  4152. WriteExeSection(FindExeSection('.rodata'));
  4153. WriteExeSection(FindExeSection('.data'));
  4154. end;
  4155. procedure WriteTableAndElemSections;
  4156. const
  4157. TableCount=1;
  4158. var
  4159. i: Integer;
  4160. begin
  4161. { Table section }
  4162. WriteUleb(FWasmSections[wsiTable],TableCount);
  4163. { table 0 }
  4164. { table type }
  4165. WriteByte(FWasmSections[wsiTable],encode_wasm_basic_type(wbt_funcref));
  4166. { table limits }
  4167. WriteByte(FWasmSections[wsiTable],$01); { has min & max }
  4168. WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { min }
  4169. WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { max }
  4170. { Elem section }
  4171. WriteUleb(FWasmSections[wsiElement],1); { 1 element segment }
  4172. { element segment 0 }
  4173. WriteByte(FWasmSections[wsiElement],0); { type funcref, init((ref.func y) end)*, mode active <table 0, offset e> }
  4174. { e:expr }
  4175. WriteByte(FWasmSections[wsiElement],$41); { i32.const }
  4176. WriteSleb(FWasmSections[wsiElement],1); { starting from 1 (table entry 0 is ref.null) }
  4177. WriteByte(FWasmSections[wsiElement],$0B); { end }
  4178. { y*:vec(funcidx) }
  4179. WriteUleb(FWasmSections[wsiElement],Length(FIndirectFunctionTable)-1);
  4180. for i:=1 to Length(FIndirectFunctionTable)-1 do
  4181. WriteUleb(FWasmSections[wsiElement],FIndirectFunctionTable[i].FuncIdx);
  4182. end;
  4183. procedure WriteGlobalSection;
  4184. var
  4185. exesec: TExeSection;
  4186. globals_count, i: Integer;
  4187. objsec: TWasmObjSection;
  4188. begin
  4189. exesec:=FindExeSection('.wasm_globals');
  4190. if not assigned(exesec) then
  4191. internalerror(2024010112);
  4192. globals_count:=exesec.ObjSectionList.Count;
  4193. if globals_count<>exesec.Size then
  4194. internalerror(2024010113);
  4195. WriteUleb(FWasmSections[wsiGlobal],globals_count);
  4196. for i:=0 to exesec.ObjSectionList.Count-1 do
  4197. begin
  4198. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4199. WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(objsec.MainFuncSymbol.LinkingData.GlobalType));
  4200. if objsec.MainFuncSymbol.LinkingData.GlobalIsMutable then
  4201. WriteByte(FWasmSections[wsiGlobal],1)
  4202. else
  4203. WriteByte(FWasmSections[wsiGlobal],0);
  4204. { initializer expr }
  4205. with objsec.MainFuncSymbol.LinkingData.GlobalInitializer do
  4206. case typ of
  4207. wbt_i32:
  4208. begin
  4209. WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
  4210. WriteSleb(FWasmSections[wsiGlobal],init_i32);
  4211. end;
  4212. wbt_i64:
  4213. begin
  4214. WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
  4215. WriteSleb(FWasmSections[wsiGlobal],init_i64);
  4216. end;
  4217. wbt_f32:
  4218. begin
  4219. WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
  4220. WriteF32LE(FWasmSections[wsiGlobal],init_f32);
  4221. end;
  4222. wbt_f64:
  4223. begin
  4224. WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
  4225. WriteF64LE(FWasmSections[wsiGlobal],init_f64);
  4226. end;
  4227. wbt_funcref,
  4228. wbt_externref:
  4229. begin
  4230. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null }
  4231. WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(typ));
  4232. end;
  4233. else
  4234. internalerror(2024010114);
  4235. end;
  4236. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  4237. end;
  4238. end;
  4239. procedure WriteExportSection;
  4240. const
  4241. MemoryExportsCount=1;
  4242. var
  4243. FunctionExportsCount: Integer;
  4244. ExportsCount: Integer;
  4245. textsec: TExeSection;
  4246. i: Integer;
  4247. objsec: TWasmObjSection;
  4248. begin
  4249. FunctionExportsCount:=0;
  4250. textsec:=FindExeSection('.text');
  4251. if not assigned(textsec) then
  4252. internalerror(2024010115);
  4253. for i:=0 to textsec.ObjSectionList.Count-1 do
  4254. begin
  4255. objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
  4256. if objsec.MainFuncSymbol.LinkingData.IsExported then
  4257. Inc(FunctionExportsCount)
  4258. end;
  4259. ExportsCount:=MemoryExportsCount+FunctionExportsCount;
  4260. WriteUleb(FWasmSections[wsiExport],ExportsCount);
  4261. { export 0 }
  4262. WriteName(FWasmSections[wsiExport],'memory');
  4263. WriteByte(FWasmSections[wsiExport],$02); { mem }
  4264. WriteUleb(FWasmSections[wsiExport],0); { memidx = 0 }
  4265. for i:=0 to textsec.ObjSectionList.Count-1 do
  4266. begin
  4267. objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
  4268. if objsec.MainFuncSymbol.LinkingData.IsExported then
  4269. begin
  4270. WriteName(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExportName);
  4271. WriteByte(FWasmSections[wsiExport],$00); { func }
  4272. WriteUleb(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex); { funcidx }
  4273. end;
  4274. end;
  4275. end;
  4276. begin
  4277. result:=false;
  4278. SetStackPointer;
  4279. FFuncTypes.WriteTo(FWasmSections[wsiType]);
  4280. WriteImportSection;
  4281. WriteCodeSegments;
  4282. WriteDataSegments;
  4283. WriteTableAndElemSections;
  4284. WriteGlobalSection;
  4285. WriteExportSection;
  4286. WriteUleb(FWasmSections[wsiMemory],1);
  4287. WriteByte(FWasmSections[wsiMemory],0);
  4288. WriteUleb(FWasmSections[wsiMemory],FMinMemoryPages);
  4289. {...}
  4290. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  4291. Writer.write(WasmVersion,SizeOf(WasmVersion));
  4292. WriteWasmSection(wsiType);
  4293. WriteWasmSection(wsiImport);
  4294. WriteWasmSection(wsiFunction);
  4295. WriteWasmSection(wsiTable);
  4296. WriteWasmSection(wsiMemory);
  4297. WriteWasmSection(wsiGlobal);
  4298. WriteWasmSection(wsiExport);
  4299. WriteWasmSection(wsiElement);
  4300. WriteWasmSection(wsiDataCount);
  4301. WriteWasmSection(wsiCode);
  4302. WriteWasmSection(wsiData);
  4303. result := true;
  4304. end;
  4305. procedure TWasmExeOutput.DoRelocationFixup(objsec: TObjSection);
  4306. procedure writeUInt32LE(v: uint32);
  4307. begin
  4308. {$ifdef FPC_BIG_ENDIAN}
  4309. v:=SwapEndian(v);
  4310. {$endif FPC_BIG_ENDIAN}
  4311. objsec.data.write(v,4);
  4312. end;
  4313. var
  4314. i: Integer;
  4315. objreloc: TWasmObjRelocation;
  4316. objsym: TWasmObjSymbol;
  4317. begin
  4318. for i:=0 to objsec.ObjRelocations.Count-1 do
  4319. begin
  4320. objreloc:=TWasmObjRelocation(objsec.ObjRelocations[i]);
  4321. if assigned(objreloc.symbol) then
  4322. begin
  4323. objsym:=TWasmObjSymbol(objreloc.symbol);
  4324. case objreloc.typ of
  4325. RELOC_FUNCTION_INDEX_LEB:
  4326. begin
  4327. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4328. internalerror(2024010103);
  4329. objsec.Data.seek(objreloc.DataOffset);
  4330. WriteUleb5(objsec.Data,objsym.LinkingData.ExeFunctionIndex);
  4331. end;
  4332. RELOC_ABSOLUTE:
  4333. begin
  4334. case objsym.typ of
  4335. AT_FUNCTION:
  4336. begin
  4337. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4338. internalerror(2024010103);
  4339. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  4340. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  4341. objsec.Data.seek(objreloc.DataOffset);
  4342. writeUInt32LE(UInt32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  4343. end;
  4344. AT_DATA:
  4345. begin
  4346. objsec.Data.seek(objreloc.DataOffset);
  4347. writeUInt32LE(UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4348. end;
  4349. else
  4350. internalerror(2024010108);
  4351. end;
  4352. end;
  4353. RELOC_MEMORY_ADDR_LEB:
  4354. begin
  4355. if objsym.typ<>AT_DATA then
  4356. internalerror(2024010109);
  4357. objsec.Data.seek(objreloc.DataOffset);
  4358. WriteUleb5(objsec.Data,UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4359. end;
  4360. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  4361. begin
  4362. case objsym.typ of
  4363. AT_FUNCTION:
  4364. begin
  4365. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4366. internalerror(2024010103);
  4367. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  4368. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  4369. objsec.Data.seek(objreloc.DataOffset);
  4370. WriteSleb5(objsec.Data,Int32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  4371. end;
  4372. AT_DATA:
  4373. begin
  4374. objsec.Data.seek(objreloc.DataOffset);
  4375. WriteSleb5(objsec.Data,Int32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4376. end;
  4377. else
  4378. internalerror(2024010110);
  4379. end;
  4380. end;
  4381. RELOC_GLOBAL_INDEX_LEB:
  4382. begin
  4383. if objsym.typ<>AT_WASM_GLOBAL then
  4384. internalerror(2024010111);
  4385. objsec.Data.seek(objreloc.DataOffset);
  4386. WriteUleb5(objsec.Data,UInt32(objsym.offset+objsym.objsection.MemPos));
  4387. end;
  4388. else
  4389. Writeln('Symbol relocation not yet implemented! ', objreloc.typ);
  4390. end;
  4391. end
  4392. else if objreloc.typ=RELOC_TYPE_INDEX_LEB then
  4393. begin
  4394. objreloc.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(objreloc.FuncType);
  4395. objsec.Data.seek(objreloc.DataOffset);
  4396. WriteUleb5(objsec.Data,objreloc.ExeTypeIndex);
  4397. end
  4398. else
  4399. Writeln('Non-symbol relocation not yet implemented! ', objreloc.typ);
  4400. end;
  4401. end;
  4402. constructor TWasmExeOutput.create;
  4403. var
  4404. i: TWasmSectionID;
  4405. begin
  4406. inherited create;
  4407. CObjData:=TWasmObjData;
  4408. MaxMemPos:=$FFFFFFFF;
  4409. FFuncTypes:=TWasmFuncTypeTable.Create;
  4410. for i in TWasmSectionID do
  4411. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  4412. SetLength(FIndirectFunctionTable,1);
  4413. FIndirectFunctionTable[0].FuncIdx:=-1;
  4414. end;
  4415. destructor TWasmExeOutput.destroy;
  4416. var
  4417. i: TWasmSectionID;
  4418. begin
  4419. for i in TWasmSectionID do
  4420. FWasmSections[i].Free;
  4421. FFuncTypes.Free;
  4422. inherited destroy;
  4423. end;
  4424. procedure TWasmExeOutput.GenerateLibraryImports(ImportLibraryList: TFPHashObjectList);
  4425. var
  4426. i, j: Integer;
  4427. ImportLibrary: TImportLibrary;
  4428. ImportSymbol: TImportSymbol;
  4429. exesym: TExeSymbol;
  4430. begin
  4431. { Here map import symbols to exe symbols and create necessary sections.
  4432. Actual import generation is done after unused sections (and symbols) are removed. }
  4433. FImports:=ImportLibraryList;
  4434. for i:=0 to ImportLibraryList.Count-1 do
  4435. begin
  4436. ImportLibrary:=TImportLibrary(ImportLibraryList[i]);
  4437. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4438. begin
  4439. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4440. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  4441. if assigned(exesym) and
  4442. (exesym.State<>symstate_defined) then
  4443. begin
  4444. ImportSymbol.CachedExeSymbol:=exesym;
  4445. exesym.State:=symstate_defined;
  4446. end;
  4447. end;
  4448. end;
  4449. PackUnresolvedExeSymbols('after module imports');
  4450. end;
  4451. procedure TWasmExeOutput.AfterUnusedSectionRemoval;
  4452. begin
  4453. PrepareImports;
  4454. PrepareFunctions;
  4455. end;
  4456. procedure TWasmExeOutput.MemPos_ExeSection(const aname: string);
  4457. var
  4458. ExeSec: TExeSection;
  4459. i: Integer;
  4460. objsec: TObjSection;
  4461. begin
  4462. { WebAssembly is a Harvard architecture.
  4463. Data lives in a separate address space, so start addressing back from 0
  4464. (the LLVM leaves the first 1024 bytes in the data segment empty, so we
  4465. start at 1024). }
  4466. if aname='.rodata' then
  4467. begin
  4468. CurrMemPos:=1024;
  4469. inherited;
  4470. end
  4471. else if aname='.text' then
  4472. begin
  4473. CurrMemPos:=0;
  4474. ExeSec:=FindExeSection(aname);
  4475. if not assigned(ExeSec) then
  4476. exit;
  4477. exesec.MemPos:=CurrMemPos;
  4478. CurrMemPos:=CurrMemPos+UlebEncodingSize(exesec.ObjSectionList.Count);
  4479. { set position of object ObjSections }
  4480. for i:=0 to exesec.ObjSectionList.Count-1 do
  4481. begin
  4482. objsec:=TObjSection(exesec.ObjSectionList[i]);
  4483. CurrMemPos:=CurrMemPos+UlebEncodingSize(objsec.Size);
  4484. CurrMemPos:=objsec.setmempos(CurrMemPos);
  4485. end;
  4486. { calculate size of the section }
  4487. exesec.Size:=CurrMemPos-exesec.MemPos;
  4488. end
  4489. else
  4490. inherited;
  4491. end;
  4492. procedure TWasmExeOutput.Load_Symbol(const aname: string);
  4493. begin
  4494. if aname=StackPointerSymStr then
  4495. begin
  4496. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  4497. FStackPointerSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  4498. FStackPointerSym.size:=1;
  4499. FStackPointerSym.ObjSection.WriteZeros(1);
  4500. TWasmObjSection(FStackPointerSym.ObjSection).MainFuncSymbol:=FStackPointerSym;
  4501. FStackPointerSym.LinkingData.GlobalType:=wbt_i32;
  4502. FStackPointerSym.LinkingData.GlobalIsMutable:=True;
  4503. FStackPointerSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  4504. FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=0;
  4505. end
  4506. else
  4507. inherited;
  4508. end;
  4509. procedure TWasmExeOutput.PrepareImports;
  4510. function AddFunctionImport(const libname,symname:TCmdStr; functype: TWasmFuncType): Integer;
  4511. begin
  4512. SetLength(FFunctionImports,Length(FFunctionImports)+1);
  4513. Result:=High(FFunctionImports);
  4514. if assigned(exemap) then
  4515. exemap.Add(' Importing Function[' + tostr(Result) + '] ' + symname + functype.ToString);
  4516. with FFunctionImports[Result] do
  4517. begin
  4518. ModName:=libname;
  4519. Name:=symname;
  4520. TypeIdx:=FFuncTypes.AddOrGetFuncType(functype);
  4521. end;
  4522. end;
  4523. var
  4524. i, j: Integer;
  4525. ImportLibrary: TImportLibrary;
  4526. ImportSymbol: TImportSymbol;
  4527. exesym: TExeSymbol;
  4528. newdll: Boolean;
  4529. begin
  4530. for i:=0 to FImports.Count-1 do
  4531. begin
  4532. ImportLibrary:=TImportLibrary(FImports[i]);
  4533. newdll:=False;
  4534. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4535. begin
  4536. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4537. exesym:=ImportSymbol.CachedExeSymbol;
  4538. if assigned(exesym) and
  4539. exesym.Used then
  4540. begin
  4541. if (not newdll) and assigned(exemap) then
  4542. begin
  4543. exemap.Add('');
  4544. exemap.Add('Importing from module '+ImportLibrary.Name);
  4545. end;
  4546. newdll:=True;
  4547. TWasmObjSymbol(exesym.ObjSymbol).LinkingData.ExeFunctionIndex:=
  4548. AddFunctionImport(ImportLibrary.Name,ImportSymbol.Name,TWasmObjSymbol(exesym.ObjSymbol).LinkingData.FuncType);
  4549. end;
  4550. end;
  4551. end;
  4552. end;
  4553. procedure TWasmExeOutput.PrepareFunctions;
  4554. var
  4555. i, j: Integer;
  4556. exesec: TExeSection;
  4557. objsec: TWasmObjSection;
  4558. fsym: TWasmObjSymbol;
  4559. objdata: TObjData;
  4560. begin
  4561. if assigned(exemap) then
  4562. begin
  4563. exemap.Add('');
  4564. exemap.Add('Functions, defined in this module:');
  4565. end;
  4566. exesec:=FindExeSection('.text');
  4567. if not assigned(exesec) then
  4568. internalerror(2023123106);
  4569. for i:=0 to exesec.ObjSectionList.Count-1 do
  4570. begin
  4571. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4572. fsym:=objsec.MainFuncSymbol;
  4573. if not assigned(fsym) then
  4574. internalerror(2023123107);
  4575. if not assigned(fsym.LinkingData.FuncType) then
  4576. internalerror(2023123108);
  4577. if fsym.LinkingData.ExeFunctionIndex<>-1 then
  4578. internalerror(2023123109);
  4579. if fsym.LinkingData.ExeTypeIndex<>-1 then
  4580. internalerror(2023123109);
  4581. fsym.LinkingData.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(fsym.LinkingData.FuncType);
  4582. fsym.LinkingData.ExeFunctionIndex:=i+Length(FFunctionImports);
  4583. if assigned(exemap) then
  4584. begin
  4585. exemap.Add(' Function[' + tostr(fsym.LinkingData.ExeFunctionIndex) + '] ' + fsym.Name + fsym.LinkingData.FuncType.ToString);
  4586. end;
  4587. end;
  4588. { set ExeFunctionIndex to the alias symbols as well }
  4589. for i:=0 to ObjDataList.Count-1 do
  4590. begin
  4591. objdata:=TObjData(ObjDataList[i]);
  4592. for j:=0 to objdata.ObjSymbolList.Count-1 do
  4593. begin
  4594. fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
  4595. if assigned(fsym.objsection) and fsym.objsection.USed and (fsym.typ=AT_FUNCTION) and (fsym.LinkingData.ExeFunctionIndex=-1) then
  4596. begin
  4597. fsym.LinkingData.ExeFunctionIndex:=TWasmObjSection(fsym.objsection).MainFuncSymbol.LinkingData.ExeFunctionIndex;
  4598. if fsym.LinkingData.ExeFunctionIndex=-1 then
  4599. internalerror(2024010102);
  4600. end;
  4601. end;
  4602. end;
  4603. end;
  4604. function TWasmExeOutput.AddOrGetIndirectFunctionTableIndex(FuncIdx: Integer): integer;
  4605. var
  4606. i: Integer;
  4607. begin
  4608. for i:=1 to length(FIndirectFunctionTable)-1 do
  4609. if FIndirectFunctionTable[i].FuncIdx=FuncIdx then
  4610. begin
  4611. Result:=i;
  4612. exit;
  4613. end;
  4614. SetLength(FIndirectFunctionTable,Length(FIndirectFunctionTable)+1);
  4615. Result:=High(FIndirectFunctionTable);
  4616. FIndirectFunctionTable[Result].FuncIdx:=FuncIdx;
  4617. end;
  4618. procedure TWasmExeOutput.SetStackPointer;
  4619. var
  4620. BssSec: TExeSection;
  4621. StackStart, InitialStackPtrAddr: QWord;
  4622. begin
  4623. BssSec:=FindExeSection('.bss');
  4624. InitialStackPtrAddr := (BssSec.MemPos+BssSec.Size+stacksize+15) and (not 15);
  4625. FMinMemoryPages := (InitialStackPtrAddr+65535) shr 16;
  4626. FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=Int32(InitialStackPtrAddr);
  4627. end;
  4628. {****************************************************************************
  4629. TWasmAssembler
  4630. ****************************************************************************}
  4631. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  4632. begin
  4633. inherited;
  4634. CObjOutput:=TWasmObjOutput;
  4635. end;
  4636. {*****************************************************************************
  4637. Initialize
  4638. *****************************************************************************}
  4639. {$ifdef wasm32}
  4640. const
  4641. as_wasm32_wasm_info : tasminfo =
  4642. (
  4643. id : as_wasm32_wasm;
  4644. idtxt : 'WASM';
  4645. asmbin : '';
  4646. asmcmd : '';
  4647. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  4648. flags : [af_outputbinary,af_smartlink_sections];
  4649. labelprefix : '..@';
  4650. labelmaxlen : -1;
  4651. comment : '; ';
  4652. dollarsign: '$';
  4653. );
  4654. {$endif wasm32}
  4655. initialization
  4656. {$ifdef wasm32}
  4657. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  4658. {$endif wasm32}
  4659. end.