ogwasm.pas 219 KB

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