ogwasm.pas 233 KB

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