ogwasm.pas 232 KB

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