ogwasm.pas 196 KB

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