ogwasm.pas 216 KB

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