ogwasm.pas 230 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876
  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
  1472. begin
  1473. Inc(relcount^);
  1474. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_I32));
  1475. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1476. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1477. begin
  1478. Writeln(objrel.symbol.objsection.Name, ' ', objrel.symbol.name, ' ', objsec.Name);
  1479. message1(asmw_e_illegal_unset_index,objrel.symbol.name);
  1480. end
  1481. else
  1482. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1483. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1484. end;
  1485. end;
  1486. RELOC_TYPE_INDEX_LEB:
  1487. begin
  1488. Inc(relcount^);
  1489. WriteByte(relout,Ord(R_WASM_TYPE_INDEX_LEB));
  1490. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1491. WriteUleb(relout,objrel.TypeIndex);
  1492. end;
  1493. RELOC_GLOBAL_INDEX_LEB:
  1494. begin
  1495. if not assigned(objrel.symbol) then
  1496. internalerror(2021092704);
  1497. Inc(relcount^);
  1498. WriteByte(relout,Ord(R_WASM_GLOBAL_INDEX_LEB));
  1499. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1500. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1501. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1502. else
  1503. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1504. end;
  1505. RELOC_TAG_INDEX_LEB:
  1506. begin
  1507. if not assigned(objrel.symbol) then
  1508. internalerror(2021092717);
  1509. Inc(relcount^);
  1510. WriteByte(relout,Ord(R_WASM_TAG_INDEX_LEB));
  1511. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1512. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1513. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1514. else
  1515. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1516. end;
  1517. else
  1518. internalerror(2021092507);
  1519. end;
  1520. end;
  1521. end;
  1522. end;
  1523. function TWasmObjOutput.FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
  1524. begin
  1525. Result:=TWasmObjSection(Symbol.objsection).MainFuncSymbol;
  1526. end;
  1527. function TWasmObjOutput.writeData(Data:TObjData):boolean;
  1528. var
  1529. section_nr: Integer;
  1530. procedure MaybeAddDebugSectionToSymbolTable(st: TWasmCustomDebugSectionType; var debug_section_nr: Integer);
  1531. var
  1532. objsec: TWasmObjSection;
  1533. begin
  1534. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1535. if Assigned(objsec) then
  1536. begin
  1537. debug_section_nr:=section_nr;
  1538. Inc(section_nr);
  1539. objsec.SegSymIdx:=FWasmSymbolTableEntriesCount;
  1540. objsec.CustomSectionIdx:=debug_section_nr;
  1541. Inc(FWasmSymbolTableEntriesCount);
  1542. WriteByte(FWasmSymbolTable,Ord(SYMTAB_SECTION));
  1543. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL);
  1544. WriteUleb(FWasmSymbolTable,debug_section_nr);
  1545. end;
  1546. end;
  1547. procedure MaybeWriteDebugSection(st: TWasmCustomDebugSectionType);
  1548. var
  1549. objsec: TWasmObjSection;
  1550. begin
  1551. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1552. if Assigned(objsec) then
  1553. begin
  1554. if oso_Data in objsec.SecOptions then
  1555. begin
  1556. objsec.Data.seek(0);
  1557. CopyDynamicArray(objsec.Data,FWasmCustomSections[st],objsec.Size);
  1558. end
  1559. else
  1560. WriteZeros(FWasmCustomSections[st],objsec.Size);
  1561. WriteWasmCustomSection(st);
  1562. end;
  1563. end;
  1564. var
  1565. i: Integer;
  1566. objsec: TWasmObjSection;
  1567. segment_count: Integer = 0;
  1568. cur_seg_ofs: qword = 0;
  1569. imports_count, NextImportFunctionIndex, NextFunctionIndex,
  1570. code_section_nr, data_section_nr,
  1571. debug_abbrev_section_nr,debug_info_section_nr,debug_str_section_nr,
  1572. debug_line_section_nr,debug_frame_section_nr,debug_aranges_section_nr,
  1573. debug_ranges_section_nr,
  1574. NextGlobalIndex, NextTagIndex: Integer;
  1575. import_globals_count: Integer = 0;
  1576. globals_count: Integer = 0;
  1577. import_functions_count: Integer = 0;
  1578. export_functions_count: Integer = 0;
  1579. functions_count: Integer = 0;
  1580. import_exception_tags_count: Integer = 0;
  1581. exception_tags_count: Integer = 0;
  1582. objsym, ObjSymAlias: TWasmObjSymbol;
  1583. cust_sec: TWasmCustomSectionType;
  1584. SegmentFlags, SymbolFlags: UInt64;
  1585. begin
  1586. FData:=TWasmObjData(Data);
  1587. { each custom sections starts with its name }
  1588. for cust_sec in TWasmCustomSectionType do
  1589. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  1590. WriteUleb(FWasmCustomSections[wcstLinking],2); { linking metadata version }
  1591. for i:=0 to Data.ObjSymbolList.Count-1 do
  1592. begin
  1593. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1594. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1595. if objsym.bind=AB_EXTERNAL then
  1596. Inc(import_exception_tags_count)
  1597. else
  1598. Inc(exception_tags_count);
  1599. if objsym.typ=AT_WASM_GLOBAL then
  1600. if objsym.bind=AB_EXTERNAL then
  1601. Inc(import_globals_count)
  1602. else
  1603. Inc(globals_count);
  1604. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1605. Inc(import_globals_count);
  1606. if IsExternalFunction(objsym) then
  1607. Inc(import_functions_count);
  1608. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1609. begin
  1610. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  1611. Inc(functions_count);
  1612. end;
  1613. if IsExportedFunction(objsym) then
  1614. Inc(export_functions_count);
  1615. end;
  1616. FData.FFuncTypes.WriteTo(FWasmSections[wsiType]);
  1617. for i:=0 to Data.ObjSectionList.Count-1 do
  1618. begin
  1619. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1620. if objsec.IsCode then
  1621. objsec.SegIdx:=-1
  1622. else if objsec.IsData then
  1623. begin
  1624. objsec.SegIdx:=segment_count;
  1625. objsec.SegOfs:=cur_seg_ofs;
  1626. Inc(segment_count);
  1627. Inc(cur_seg_ofs,objsec.Size);
  1628. end;
  1629. end;
  1630. imports_count:=2+import_globals_count+import_functions_count+import_exception_tags_count;
  1631. WriteUleb(FWasmSections[wsiImport],imports_count);
  1632. { import memories }
  1633. WriteName(FWasmSections[wsiImport],'env');
  1634. WriteName(FWasmSections[wsiImport],'__linear_memory');
  1635. WriteByte(FWasmSections[wsiImport],$02); { mem }
  1636. WriteByte(FWasmSections[wsiImport],$00); { min }
  1637. WriteUleb(FWasmSections[wsiImport],1); { 1 page }
  1638. { import globals }
  1639. NextGlobalIndex:=0;
  1640. for i:=0 to Data.ObjSymbolList.Count-1 do
  1641. begin
  1642. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1643. if (objsym.bind=AB_EXTERNAL) and (objsym.typ=AT_WASM_GLOBAL) then
  1644. begin
  1645. objsym.GlobalIndex:=NextGlobalIndex;
  1646. Inc(NextGlobalIndex);
  1647. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1648. if objsym.ExtraData.ImportModule<>'' then
  1649. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1650. else
  1651. WriteName(FWasmSections[wsiImport],'env');
  1652. WriteName(FWasmSections[wsiImport],objsym.Name);
  1653. WriteByte(FWasmSections[wsiImport],$03); { global }
  1654. WriteWasmBasicType(FWasmSections[wsiImport],objsym.ExtraData.GlobalType);
  1655. if objsym.ExtraData.GlobalIsImmutable then
  1656. WriteByte(FWasmSections[wsiImport],$00) { const }
  1657. else
  1658. WriteByte(FWasmSections[wsiImport],$01); { var }
  1659. end
  1660. else if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1661. begin
  1662. objsym.GlobalIndex:=NextGlobalIndex;
  1663. Inc(NextGlobalIndex);
  1664. objsym.ExtraData:=nil;
  1665. WriteName(FWasmSections[wsiImport],'GOT.mem');
  1666. WriteName(FWasmSections[wsiImport],objsym.Name);
  1667. WriteByte(FWasmSections[wsiImport],$03); { global }
  1668. WriteWasmBasicType(FWasmSections[wsiImport],wbt_i32); { i32 }
  1669. WriteByte(FWasmSections[wsiImport],$01); { var }
  1670. end;
  1671. end;
  1672. { import functions }
  1673. NextImportFunctionIndex:=0;
  1674. for i:=0 to Data.ObjSymbolList.Count-1 do
  1675. begin
  1676. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1677. if IsExternalFunction(objsym) then
  1678. begin
  1679. objsym.FuncIndex:=NextImportFunctionIndex;
  1680. Inc(NextImportFunctionIndex);
  1681. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1682. if objsym.ExtraData.ImportModule<>'' then
  1683. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1684. else
  1685. WriteName(FWasmSections[wsiImport],'env');
  1686. WriteName(FWasmSections[wsiImport],objsym.Name);
  1687. WriteByte(FWasmSections[wsiImport],$00); { func }
  1688. WriteUleb(FWasmSections[wsiImport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1689. end;
  1690. end;
  1691. { import tables }
  1692. WriteName(FWasmSections[wsiImport],'env');
  1693. WriteName(FWasmSections[wsiImport],'__indirect_function_table');
  1694. WriteByte(FWasmSections[wsiImport],$01); { table }
  1695. WriteByte(FWasmSections[wsiImport],$70); { funcref }
  1696. WriteByte(FWasmSections[wsiImport],$00); { min }
  1697. WriteUleb(FWasmSections[wsiImport],1); { 1 }
  1698. { import tags }
  1699. NextTagIndex:=0;
  1700. for i:=0 to Data.ObjSymbolList.Count-1 do
  1701. begin
  1702. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1703. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind=AB_EXTERNAL) then
  1704. begin
  1705. objsym.TagIndex:=NextTagIndex;
  1706. Inc(NextTagIndex);
  1707. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1708. if objsym.ExtraData.ImportModule<>'' then
  1709. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1710. else
  1711. WriteName(FWasmSections[wsiImport],'env');
  1712. WriteName(FWasmSections[wsiImport],objsym.Name);
  1713. WriteByte(FWasmSections[wsiImport],$04); { tag }
  1714. WriteByte(FWasmSections[wsiImport],$00); { exception }
  1715. WriteUleb(FWasmSections[wsiImport],objsym.ExtraData.ExceptionTagTypeIdx);
  1716. end;
  1717. end;
  1718. WriteUleb(FWasmSections[wsiFunction],functions_count);
  1719. NextFunctionIndex:=NextImportFunctionIndex;
  1720. for i:=0 to Data.ObjSymbolList.Count-1 do
  1721. begin
  1722. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1723. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1724. begin
  1725. objsym.FuncIndex:=NextFunctionIndex;
  1726. Inc(NextFunctionIndex);
  1727. WriteUleb(FWasmSections[wsiFunction],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1728. end;
  1729. end;
  1730. if exception_tags_count>0 then
  1731. begin
  1732. WriteUleb(FWasmSections[wsiTag],exception_tags_count);
  1733. for i:=0 to Data.ObjSymbolList.Count-1 do
  1734. begin
  1735. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1736. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind<>AB_EXTERNAL) then
  1737. begin
  1738. objsym.TagIndex:=NextTagIndex;
  1739. Inc(NextTagIndex);
  1740. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1741. WriteByte(FWasmSections[wsiTag],$00); { exception }
  1742. WriteUleb(FWasmSections[wsiTag],objsym.ExtraData.ExceptionTagTypeIdx);
  1743. end;
  1744. end;
  1745. end;
  1746. if globals_count>0 then
  1747. begin
  1748. WriteUleb(FWasmSections[wsiGlobal],globals_count);
  1749. for i:=0 to Data.ObjSymbolList.Count-1 do
  1750. begin
  1751. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1752. if (objsym.typ=AT_WASM_GLOBAL) and (objsym.bind<>AB_EXTERNAL) then
  1753. begin
  1754. objsym.GlobalIndex:=NextGlobalIndex;
  1755. Inc(NextGlobalIndex);
  1756. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1757. WriteWasmBasicType(FWasmSections[wsiGlobal],objsym.ExtraData.GlobalType);
  1758. if objsym.ExtraData.GlobalIsImmutable then
  1759. WriteByte(FWasmSections[wsiGlobal],$00) { const }
  1760. else
  1761. WriteByte(FWasmSections[wsiGlobal],$01); { var }
  1762. { init expr }
  1763. case objsym.ExtraData.GlobalType of
  1764. wbt_i32:
  1765. begin
  1766. WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
  1767. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1768. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1769. end;
  1770. wbt_i64:
  1771. begin
  1772. WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
  1773. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1774. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1775. end;
  1776. wbt_f32:
  1777. begin
  1778. WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
  1779. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE single precision floating point format) }
  1780. WriteByte(FWasmSections[wsiGlobal],$00);
  1781. WriteByte(FWasmSections[wsiGlobal],$00);
  1782. WriteByte(FWasmSections[wsiGlobal],$00);
  1783. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1784. end;
  1785. wbt_f64:
  1786. begin
  1787. WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
  1788. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE double precision floating point format) }
  1789. WriteByte(FWasmSections[wsiGlobal],$00);
  1790. WriteByte(FWasmSections[wsiGlobal],$00);
  1791. WriteByte(FWasmSections[wsiGlobal],$00);
  1792. WriteByte(FWasmSections[wsiGlobal],$00);
  1793. WriteByte(FWasmSections[wsiGlobal],$00);
  1794. WriteByte(FWasmSections[wsiGlobal],$00);
  1795. WriteByte(FWasmSections[wsiGlobal],$00);
  1796. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1797. end;
  1798. wbt_externref:
  1799. begin
  1800. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null extern }
  1801. WriteByte(FWasmSections[wsiGlobal],$6F);
  1802. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1803. end;
  1804. wbt_funcref:
  1805. begin
  1806. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null func }
  1807. WriteByte(FWasmSections[wsiGlobal],$70);
  1808. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1809. end;
  1810. else
  1811. internalerror(2022052801);
  1812. end;
  1813. end;
  1814. end;
  1815. end;
  1816. if export_functions_count>0 then
  1817. begin
  1818. WriteUleb(FWasmSections[wsiExport],export_functions_count);
  1819. for i:=0 to Data.ObjSymbolList.Count-1 do
  1820. begin
  1821. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1822. if IsExportedFunction(objsym) then
  1823. begin
  1824. WriteName(FWasmSections[wsiExport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).ExportName);
  1825. WriteByte(FWasmSections[wsiExport],0); { func }
  1826. if (objsym.FuncIndex<0) then
  1827. message1(asmw_e_illegal_unset_index,objsym.name)
  1828. else
  1829. WriteUleb(FWasmSections[wsiExport],objsym.FuncIndex);
  1830. end;
  1831. end;
  1832. end;
  1833. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  1834. Writer.write(WasmVersion,SizeOf(WasmVersion));
  1835. if ts_wasm_threads in current_settings.targetswitches then
  1836. begin
  1837. WriteUleb(FWasmCustomSections[wcstTargetFeatures],4);
  1838. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1839. WriteName(FWasmCustomSections[wcstTargetFeatures],'atomics');
  1840. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1841. WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
  1842. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1843. WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
  1844. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1845. WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
  1846. end
  1847. else
  1848. begin
  1849. WriteUleb(FWasmCustomSections[wcstTargetFeatures],3);
  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. { Write the producers section:
  1858. https://github.com/WebAssembly/tool-conventions/blob/main/ProducersSection.md }
  1859. WriteUleb(FWasmCustomSections[wcstProducers],2);
  1860. WriteName(FWasmCustomSections[wcstProducers],'language');
  1861. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1862. WriteName(FWasmCustomSections[wcstProducers],'Pascal');
  1863. WriteName(FWasmCustomSections[wcstProducers],'');
  1864. WriteName(FWasmCustomSections[wcstProducers],'processed-by');
  1865. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1866. WriteName(FWasmCustomSections[wcstProducers],'Free Pascal Compiler (FPC)');
  1867. WriteName(FWasmCustomSections[wcstProducers],full_version_string+' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname);
  1868. code_section_nr:=-1;
  1869. data_section_nr:=-1;
  1870. debug_abbrev_section_nr:=-1;
  1871. debug_info_section_nr:=-1;
  1872. debug_str_section_nr:=-1;
  1873. debug_line_section_nr:=-1;
  1874. debug_frame_section_nr:=-1;
  1875. debug_aranges_section_nr:=-1;
  1876. debug_ranges_section_nr:=-1;
  1877. section_nr:=0;
  1878. WriteWasmSection(wsiType);
  1879. Inc(section_nr);
  1880. WriteWasmSection(wsiImport);
  1881. Inc(section_nr);
  1882. WriteWasmSection(wsiFunction);
  1883. Inc(section_nr);
  1884. if exception_tags_count>0 then
  1885. begin
  1886. WriteWasmSection(wsiTag);
  1887. Inc(section_nr);
  1888. end;
  1889. if globals_count>0 then
  1890. begin
  1891. WriteWasmSection(wsiGlobal);
  1892. Inc(section_nr);
  1893. end;
  1894. if export_functions_count>0 then
  1895. begin
  1896. WriteWasmSection(wsiExport);
  1897. Inc(section_nr);
  1898. end;
  1899. { determine the section numbers for the datacount, code, data and debug sections ahead of time }
  1900. if segment_count>0 then
  1901. Inc(section_nr); { the DataCount section }
  1902. code_section_nr:=section_nr; { the Code section }
  1903. Inc(section_nr);
  1904. if segment_count>0 then
  1905. begin
  1906. data_section_nr:=section_nr; { the Data section }
  1907. Inc(section_nr);
  1908. end;
  1909. { the debug sections }
  1910. MaybeAddDebugSectionToSymbolTable(wcstDebugAbbrev,debug_abbrev_section_nr);
  1911. MaybeAddDebugSectionToSymbolTable(wcstDebugInfo,debug_info_section_nr);
  1912. MaybeAddDebugSectionToSymbolTable(wcstDebugStr,debug_str_section_nr);
  1913. MaybeAddDebugSectionToSymbolTable(wcstDebugLine,debug_line_section_nr);
  1914. MaybeAddDebugSectionToSymbolTable(wcstDebugFrame,debug_frame_section_nr);
  1915. MaybeAddDebugSectionToSymbolTable(wcstDebugAranges,debug_aranges_section_nr);
  1916. MaybeAddDebugSectionToSymbolTable(wcstDebugRanges,debug_ranges_section_nr);
  1917. for i:=0 to Data.ObjSymbolList.Count-1 do
  1918. begin
  1919. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1920. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1921. begin
  1922. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1923. Inc(FWasmSymbolTableEntriesCount);
  1924. WriteByte(FWasmSymbolTable,Ord(SYMTAB_EVENT));
  1925. if objsym.bind=AB_GLOBAL then
  1926. WriteUleb(FWasmSymbolTable,0)
  1927. else if objsym.bind=AB_LOCAL then
  1928. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL)
  1929. else if objsym.bind=AB_EXTERNAL then
  1930. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED)
  1931. else if objsym.bind=AB_WEAK then
  1932. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_WEAK)
  1933. else
  1934. internalerror(2021092715);
  1935. if (objsym.TagIndex<0) then
  1936. message1(asmw_e_illegal_unset_index,objsym.name)
  1937. else
  1938. WriteUleb(FWasmSymbolTable,objsym.TagIndex);
  1939. if objsym.bind<>AB_EXTERNAL then
  1940. WriteName(FWasmSymbolTable,objsym.Name);
  1941. end
  1942. else if objsym.typ=AT_WASM_GLOBAL then
  1943. begin
  1944. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1945. Inc(FWasmSymbolTableEntriesCount);
  1946. WriteByte(FWasmSymbolTable,Ord(SYMTAB_GLOBAL));
  1947. if objsym.bind=AB_EXTERNAL then
  1948. begin
  1949. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1950. if (objsym.GlobalIndex<0) then
  1951. message1(asmw_e_illegal_unset_index,objsym.name)
  1952. else
  1953. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  1954. end
  1955. else
  1956. begin
  1957. WriteUleb(FWasmSymbolTable,0);
  1958. if (objsym.GlobalIndex<0) then
  1959. message1(asmw_e_illegal_unset_index,objsym.name)
  1960. else
  1961. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  1962. WriteName(FWasmSymbolTable,objsym.Name);
  1963. end;
  1964. end
  1965. else if IsExternalFunction(objsym) then
  1966. begin
  1967. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1968. Inc(FWasmSymbolTableEntriesCount);
  1969. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1970. if objsym.ExtraData.ImportModule<>'' then
  1971. begin
  1972. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED or WASM_SYM_EXPLICIT_NAME);
  1973. if (objsym.FuncIndex<0) then
  1974. message1(asmw_e_illegal_unset_index,objsym.name)
  1975. else
  1976. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1977. WriteName(FWasmSymbolTable,objsym.Name);
  1978. end
  1979. else
  1980. begin
  1981. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1982. if (objsym.FuncIndex<0) then
  1983. message1(asmw_e_illegal_unset_index,objsym.name)
  1984. else
  1985. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1986. end;
  1987. end
  1988. else if objsym.typ=AT_FUNCTION then
  1989. begin
  1990. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1991. Inc(FWasmSymbolTableEntriesCount);
  1992. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1993. if objsym.IsAlias then
  1994. begin
  1995. ObjSymAlias:=TWasmObjSymbol(Data.ObjSymbolList.Find(objsym.AliasOf));
  1996. ObjSym.FuncIndex:=ObjSymAlias.FuncIndex;
  1997. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPLICIT_NAME or WASM_SYM_NO_STRIP);
  1998. WriteUleb(FWasmSymbolTable,ObjSymAlias.FuncIndex);
  1999. end
  2000. else
  2001. begin
  2002. if IsExportedFunction(objsym) then
  2003. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPORTED)
  2004. else
  2005. WriteUleb(FWasmSymbolTable,0);
  2006. if (objsym.FuncIndex<0) then
  2007. message1(asmw_e_illegal_unset_index,objsym.name)
  2008. else
  2009. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  2010. end;
  2011. WriteName(FWasmSymbolTable,objsym.Name);
  2012. end
  2013. else if (objsym.typ in [AT_DATA,AT_TLS,AT_METADATA]) or ((objsym.typ=AT_NONE) and (objsym.bind=AB_EXTERNAL)) then
  2014. begin
  2015. if (objsym.bind<>AB_EXTERNAL) and TWasmObjSection(objsym.objsection).IsDebug then
  2016. begin
  2017. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  2018. Inc(FWasmSymbolTableEntriesCount);
  2019. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FPC_CUSTOM));
  2020. if objsym.bind=AB_GLOBAL then
  2021. SymbolFlags:=0
  2022. else if objsym.bind=AB_LOCAL then
  2023. SymbolFlags:=WASM_SYM_BINDING_LOCAL
  2024. else if objsym.bind=AB_EXTERNAL then
  2025. SymbolFlags:=WASM_SYM_UNDEFINED
  2026. else
  2027. internalerror(2024090701);
  2028. WriteUleb(FWasmSymbolTable,SymbolFlags);
  2029. WriteName(FWasmSymbolTable,objsym.Name);
  2030. WriteUleb(FWasmSymbolTable,TWasmObjSection(objsym.objsection).CustomSectionIdx);
  2031. WriteUleb(FWasmSymbolTable,objsym.offset);
  2032. WriteUleb(FWasmSymbolTable,objsym.size);
  2033. end
  2034. else
  2035. begin
  2036. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  2037. Inc(FWasmSymbolTableEntriesCount);
  2038. WriteByte(FWasmSymbolTable,Ord(SYMTAB_DATA));
  2039. if objsym.bind=AB_GLOBAL then
  2040. SymbolFlags:=0
  2041. else if objsym.bind=AB_LOCAL then
  2042. SymbolFlags:=WASM_SYM_BINDING_LOCAL
  2043. else if objsym.bind=AB_EXTERNAL then
  2044. SymbolFlags:=WASM_SYM_UNDEFINED
  2045. else
  2046. internalerror(2021092506);
  2047. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  2048. SymbolFlags:=(SymbolFlags and not WASM_SYM_BINDING_LOCAL) or WASM_SYM_TLS;
  2049. WriteUleb(FWasmSymbolTable,SymbolFlags);
  2050. WriteName(FWasmSymbolTable,objsym.Name);
  2051. if objsym.bind<>AB_EXTERNAL then
  2052. begin
  2053. WriteUleb(FWasmSymbolTable,TWasmObjSection(objsym.objsection).SegIdx);
  2054. WriteUleb(FWasmSymbolTable,objsym.offset);
  2055. WriteUleb(FWasmSymbolTable,objsym.size);
  2056. end;
  2057. end;
  2058. end;
  2059. end;
  2060. DoRelocations;
  2061. if segment_count>0 then
  2062. begin
  2063. WriteUleb(FWasmSections[wsiData],segment_count);
  2064. WriteUleb(FWasmSections[wsiDataCount],segment_count);
  2065. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],segment_count);
  2066. for i:=0 to Data.ObjSectionList.Count-1 do
  2067. begin
  2068. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  2069. if objsec.IsData then
  2070. begin
  2071. WriteName(FWasmLinkingSubsections[WASM_SEGMENT_INFO],objsec.Name);
  2072. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],BsrQWord(objsec.SecAlign));
  2073. SegmentFlags:=0;
  2074. if (ts_wasm_threads in current_settings.targetswitches) and
  2075. (oso_threadvar in objsec.SecOptions) then
  2076. SegmentFlags:=SegmentFlags or WASM_SEG_FLAG_TLS;
  2077. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],SegmentFlags); { flags }
  2078. WriteByte(FWasmSections[wsiData],0);
  2079. WriteByte(FWasmSections[wsiData],$41);
  2080. WriteSleb(FWasmSections[wsiData],objsec.SegOfs);
  2081. WriteByte(FWasmSections[wsiData],$0b);
  2082. WriteUleb(FWasmSections[wsiData],objsec.Size);
  2083. objsec.FileSectionOfs:=FWasmSections[wsiData].size;
  2084. if oso_Data in objsec.SecOptions then
  2085. begin
  2086. objsec.Data.seek(0);
  2087. CopyDynamicArray(objsec.Data,FWasmSections[wsiData],objsec.Size);
  2088. end
  2089. else
  2090. begin
  2091. WriteZeros(FWasmSections[wsiData],objsec.Size);
  2092. end;
  2093. end;
  2094. end;
  2095. end;
  2096. WriteUleb(FWasmSections[wsiCode],functions_count);
  2097. for i:=0 to Data.ObjSymbolList.Count-1 do
  2098. begin
  2099. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  2100. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  2101. WriteFunctionCode(FWasmSections[wsiCode],objsym);
  2102. end;
  2103. if segment_count>0 then
  2104. WriteWasmSection(wsiDataCount);
  2105. WriteWasmSection(wsiCode);
  2106. if segment_count>0 then
  2107. WriteWasmSection(wsiData);
  2108. MaybeWriteDebugSection(wcstDebugAbbrev);
  2109. MaybeWriteDebugSection(wcstDebugInfo);
  2110. MaybeWriteDebugSection(wcstDebugStr);
  2111. MaybeWriteDebugSection(wcstDebugLine);
  2112. MaybeWriteDebugSection(wcstDebugFrame);
  2113. MaybeWriteDebugSection(wcstDebugAranges);
  2114. MaybeWriteDebugSection(wcstDebugRanges);
  2115. WriteRelocations;
  2116. WriteSymbolTable;
  2117. WriteLinkingSubsection(WASM_SYMBOL_TABLE);
  2118. if segment_count>0 then
  2119. WriteLinkingSubsection(WASM_SEGMENT_INFO);
  2120. WriteRelocationCodeTable(code_section_nr);
  2121. if segment_count>0 then
  2122. WriteRelocationDataTable(data_section_nr);
  2123. WriteWasmCustomSection(wcstLinking);
  2124. Inc(section_nr);
  2125. WriteWasmCustomSection(wcstRelocCode);
  2126. Inc(section_nr);
  2127. if segment_count>0 then
  2128. begin
  2129. WriteWasmCustomSection(wcstRelocData);
  2130. Inc(section_nr);
  2131. end;
  2132. MaybeWriteRelocationDebugTable(wcstRelocDebugAbbrev,debug_abbrev_section_nr,FWasmRelocationDebugAbbrevTableEntriesCount,FWasmRelocationDebugAbbrevTable);
  2133. MaybeWriteRelocationDebugTable(wcstRelocDebugInfo,debug_info_section_nr,FWasmRelocationDebugInfoTableEntriesCount,FWasmRelocationDebugInfoTable);
  2134. MaybeWriteRelocationDebugTable(wcstRelocDebugStr,debug_str_section_nr,FWasmRelocationDebugStrTableEntriesCount,FWasmRelocationDebugStrTable);
  2135. MaybeWriteRelocationDebugTable(wcstRelocDebugLine,debug_line_section_nr,FWasmRelocationDebugLineTableEntriesCount,FWasmRelocationDebugLineTable);
  2136. MaybeWriteRelocationDebugTable(wcstRelocDebugFrame,debug_frame_section_nr,FWasmRelocationDebugFrameTableEntriesCount,FWasmRelocationDebugFrameTable);
  2137. MaybeWriteRelocationDebugTable(wcstRelocDebugAranges,debug_aranges_section_nr,FWasmRelocationDebugArangesTableEntriesCount,FWasmRelocationDebugArangesTable);
  2138. MaybeWriteRelocationDebugTable(wcstRelocDebugRanges,debug_ranges_section_nr,FWasmRelocationDebugRangesTableEntriesCount,FWasmRelocationDebugRangesTable);
  2139. WriteWasmCustomSection(wcstProducers);
  2140. Inc(section_nr);
  2141. WriteWasmCustomSection(wcstTargetFeatures);
  2142. Inc(section_nr);
  2143. result:=true;
  2144. end;
  2145. constructor TWasmObjOutput.create(AWriter: TObjectWriter);
  2146. var
  2147. i: TWasmSectionID;
  2148. j: TWasmCustomSectionType;
  2149. k: TWasmLinkingSubsectionType;
  2150. begin
  2151. inherited;
  2152. cobjdata:=TWasmObjData;
  2153. for i in TWasmSectionID do
  2154. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  2155. for j in TWasmCustomSectionType do
  2156. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  2157. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  2158. FWasmLinkingSubsections[k] := tdynamicarray.create(SectionDataMaxGrow);
  2159. FWasmSymbolTable:=tdynamicarray.create(SectionDataMaxGrow);
  2160. FWasmSymbolTableEntriesCount:=0;
  2161. FWasmRelocationCodeTable:=tdynamicarray.create(SectionDataMaxGrow);
  2162. FWasmRelocationCodeTableEntriesCount:=0;
  2163. FWasmRelocationDataTable:=tdynamicarray.create(SectionDataMaxGrow);
  2164. FWasmRelocationDataTableEntriesCount:=0;
  2165. FWasmRelocationDebugFrameTable:=tdynamicarray.create(SectionDataMaxGrow);
  2166. FWasmRelocationDebugFrameTableEntriesCount:=0;
  2167. FWasmRelocationDebugInfoTable:=tdynamicarray.create(SectionDataMaxGrow);
  2168. FWasmRelocationDebugInfoTableEntriesCount:=0;
  2169. FWasmRelocationDebugLineTable:=tdynamicarray.create(SectionDataMaxGrow);
  2170. FWasmRelocationDebugLineTableEntriesCount:=0;
  2171. FWasmRelocationDebugAbbrevTable:=tdynamicarray.create(SectionDataMaxGrow);
  2172. FWasmRelocationDebugAbbrevTableEntriesCount:=0;
  2173. FWasmRelocationDebugArangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  2174. FWasmRelocationDebugArangesTableEntriesCount:=0;
  2175. FWasmRelocationDebugRangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  2176. FWasmRelocationDebugRangesTableEntriesCount:=0;
  2177. FWasmRelocationDebugStrTable:=tdynamicarray.create(SectionDataMaxGrow);
  2178. FWasmRelocationDebugStrTableEntriesCount:=0;
  2179. end;
  2180. destructor TWasmObjOutput.destroy;
  2181. var
  2182. i: TWasmSectionID;
  2183. j: TWasmCustomSectionType;
  2184. k: TWasmLinkingSubsectionType;
  2185. begin
  2186. for i in TWasmSectionID do
  2187. FWasmSections[i].Free;
  2188. for j in TWasmCustomSectionType do
  2189. FWasmCustomSections[j].Free;
  2190. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  2191. FWasmLinkingSubsections[k].Free;
  2192. FWasmSymbolTable.Free;
  2193. FWasmRelocationCodeTable.Free;
  2194. FWasmRelocationDataTable.Free;
  2195. FWasmRelocationDebugFrameTable.Free;
  2196. FWasmRelocationDebugInfoTable.Free;
  2197. FWasmRelocationDebugLineTable.Free;
  2198. FWasmRelocationDebugAbbrevTable.Free;
  2199. FWasmRelocationDebugArangesTable.Free;
  2200. FWasmRelocationDebugRangesTable.Free;
  2201. FWasmRelocationDebugStrTable.Free;
  2202. inherited destroy;
  2203. end;
  2204. {****************************************************************************
  2205. TWasmObjInput
  2206. ****************************************************************************}
  2207. constructor TWasmObjInput.create;
  2208. begin
  2209. inherited create;
  2210. cobjdata:=TWasmObjData;
  2211. end;
  2212. destructor TWasmObjInput.Destroy;
  2213. var
  2214. i: Integer;
  2215. begin
  2216. for i:=low(FFuncTypes) to high(FFuncTypes) do
  2217. begin
  2218. FFuncTypes[i].free;
  2219. FFuncTypes[i]:=nil;
  2220. end;
  2221. inherited Destroy;
  2222. end;
  2223. class function TWasmObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  2224. var
  2225. ModuleMagic: array [0..3] of Byte;
  2226. ModuleVersion: array [0..3] of Byte;
  2227. i: Integer;
  2228. begin
  2229. result:=false;
  2230. if not AReader.read(ModuleMagic,4) then
  2231. exit;
  2232. for i:=0 to 3 do
  2233. if ModuleMagic[i]<>WasmModuleMagic[i] then
  2234. exit;
  2235. if not AReader.read(ModuleVersion,4) then
  2236. exit;
  2237. for i:=0 to 3 do
  2238. if ModuleVersion[i]<>WasmVersion[i] then
  2239. exit;
  2240. result:=true;
  2241. end;
  2242. function TWasmObjInput.ReadObjData(AReader: TObjectreader; out ObjData: TObjData): boolean;
  2243. type
  2244. TLimits = record
  2245. Min, Max: uint32;
  2246. HasMax: Boolean;
  2247. end;
  2248. var
  2249. SectionIndex: Integer = -1;
  2250. SectionId: Byte;
  2251. SectionSize: uint32;
  2252. SectionStart: LongInt;
  2253. CheckSectionBounds: Boolean;
  2254. TypeSectionRead: Boolean = false;
  2255. ImportSectionRead: Boolean = false;
  2256. FunctionSectionRead: Boolean = false;
  2257. GlobalSectionRead: Boolean = false;
  2258. ExportSectionRead: Boolean = false;
  2259. ElementSectionRead: Boolean = false;
  2260. TagSectionRead: Boolean = false;
  2261. CodeSectionRead: Boolean = false;
  2262. DataSectionRead: Boolean = false;
  2263. DataCountSectionRead: Boolean = false;
  2264. SegmentInfoSectionRead: Boolean = false;
  2265. SymbolTableSectionRead: Boolean = false;
  2266. CodeSectionIndex: Integer = -1;
  2267. DataSectionIndex: Integer = -1;
  2268. DebugSectionIndex: array [TWasmCustomDebugSectionType] of Integer = (-1,-1,-1,-1,-1,-1,-1);
  2269. FuncTypes: array of record
  2270. IsImport: Boolean;
  2271. ImportName: ansistring;
  2272. ImportModName: ansistring;
  2273. typidx: uint32;
  2274. IsExported: Boolean;
  2275. ExportName: ansistring;
  2276. end;
  2277. FuncTypeImportsCount: uint32;
  2278. TableTypes: array of record
  2279. IsImport: Boolean;
  2280. ImportName: ansistring;
  2281. ImportModName: ansistring;
  2282. reftype: TWasmBAsicType;
  2283. limits: TLimits;
  2284. IsExported: Boolean;
  2285. ExportName: ansistring;
  2286. end;
  2287. TableTypeImportsCount: uint32;
  2288. MemTypes: array of record
  2289. IsImport: Boolean;
  2290. ImportName: ansistring;
  2291. ImportModName: ansistring;
  2292. limits: TLimits;
  2293. IsExported: Boolean;
  2294. ExportName: ansistring;
  2295. end;
  2296. MemTypeImportsCount: uint32;
  2297. GlobalTypes: array of record
  2298. IsImport: Boolean;
  2299. ImportName: ansistring;
  2300. ImportModName: ansistring;
  2301. valtype: TWasmBasicType;
  2302. IsMutable: Boolean;
  2303. IsExported: Boolean;
  2304. ExportName: ansistring;
  2305. GlobalInit: TGlobalInitializer;
  2306. end;
  2307. GlobalTypeImportsCount: uint32;
  2308. TagTypes: array of record
  2309. IsImport: Boolean;
  2310. ImportName: ansistring;
  2311. ImportModName: ansistring;
  2312. TagAttr: Byte;
  2313. TagTypeIdx: uint32;
  2314. IsExported: Boolean;
  2315. ExportName: ansistring;
  2316. end;
  2317. TagTypeImportsCount: uint32;
  2318. CodeSegments: array of record
  2319. CodeSectionOffset: uint32;
  2320. CodeSize: uint32;
  2321. DataPos: LongInt;
  2322. SegName: ansistring;
  2323. SegIsExported: Boolean;
  2324. end;
  2325. DataSegments: array of record
  2326. DataSectionOffset: uint32;
  2327. Active: Boolean;
  2328. MemIdx: uint32;
  2329. Len: uint32;
  2330. Offset: int32;
  2331. DataPos: LongInt;
  2332. SegName: ansistring;
  2333. SegAlignment: uint32;
  2334. SegFlags: uint32;
  2335. end;
  2336. SymbolTable: array of record
  2337. SymFlags: uint32;
  2338. TargetSection: uint32;
  2339. SymIndex: uint32;
  2340. SymOffset: uint32;
  2341. SymSize: uint32;
  2342. SymCustomSectionIndex: uint32;
  2343. SymCustomSectionType: TWasmCustomDebugSectionType;
  2344. SymKind: TWasmSymbolType;
  2345. SymName: ansistring;
  2346. ObjSym: TWasmObjSymbol;
  2347. ObjSec: TWasmObjSection;
  2348. end;
  2349. { meaning of first index: }
  2350. { table 0 is code relocs }
  2351. { table 1 is data relocs }
  2352. { tables 2.. are custom section relocs for debug sections }
  2353. RelocationTable: array of array of record
  2354. RelocType: TWasmRelocationType;
  2355. RelocOffset: uint32;
  2356. RelocIndex: uint32;
  2357. RelocAddend: int32;
  2358. end;
  2359. function FindDebugSectionByIndex(SectionIndex: Integer; out res: TWasmCustomDebugSectionType): Boolean;
  2360. var
  2361. ds: TWasmCustomDebugSectionType;
  2362. begin
  2363. for ds in TWasmCustomDebugSectionType do
  2364. if DebugSectionIndex[ds]=SectionIndex then
  2365. begin
  2366. Res:=ds;
  2367. Result:=True;
  2368. exit;
  2369. end;
  2370. {$push} {$R-}{$Q-}
  2371. Res:=default(TWasmCustomDebugSectionType);
  2372. {$pop}
  2373. Result:=False;
  2374. end;
  2375. function ReadSection: Boolean;
  2376. function read(out b;len:longint):boolean;
  2377. begin
  2378. result:=false;
  2379. if not CheckSectionBounds or ((AReader.Pos+len)<=(SectionStart+SectionSize)) then
  2380. result:=AReader.read(b,len)
  2381. else
  2382. begin
  2383. { trying to read beyond the end of the section }
  2384. AReader.read(b,SectionStart+SectionSize-AReader.Pos);
  2385. result:=false;
  2386. end;
  2387. end;
  2388. function ReadUleb(out v: uint64): boolean;
  2389. var
  2390. b: byte;
  2391. shift:integer;
  2392. begin
  2393. result:=false;
  2394. b:=0;
  2395. v:=0;
  2396. shift:=0;
  2397. repeat
  2398. if not read(b,1) then
  2399. exit;
  2400. v:=v or (uint64(b and 127) shl shift);
  2401. inc(shift,7);
  2402. until (b and 128)=0;
  2403. result:=true;
  2404. end;
  2405. function ReadUleb32(out v: uint32): boolean;
  2406. var
  2407. vv: uint64;
  2408. begin
  2409. result:=false;
  2410. v:=default(uint32);
  2411. if not ReadUleb(vv) then
  2412. exit;
  2413. if vv>high(uint32) then
  2414. exit;
  2415. v:=vv;
  2416. result:=true;
  2417. end;
  2418. function ReadSleb(out v: int64): boolean;
  2419. var
  2420. b: byte;
  2421. shift:integer;
  2422. begin
  2423. result:=false;
  2424. b:=0;
  2425. v:=0;
  2426. shift:=0;
  2427. repeat
  2428. if not read(b,1) then
  2429. exit;
  2430. v:=v or (uint64(b and 127) shl shift);
  2431. inc(shift,7);
  2432. until (b and 128)=0;
  2433. {$ifopt Q+}
  2434. {$define overflowon}
  2435. {$Q-}
  2436. {$endif}
  2437. {$ifopt R+}
  2438. {$define rangeon}
  2439. {$R-}
  2440. {$endif}
  2441. if (b and 64)<>0 then
  2442. v:=v or (high(uint64) shl shift);
  2443. result:=true;
  2444. end;
  2445. {$ifdef overflowon}
  2446. {$Q+}
  2447. {$undef overflowon}
  2448. {$endif}
  2449. {$ifdef rangeon}
  2450. {$R+}
  2451. {$undef rangeon}
  2452. {$endif}
  2453. function ReadSleb32(out v: int32): boolean;
  2454. var
  2455. vv: int64;
  2456. begin
  2457. result:=false;
  2458. v:=default(int32);
  2459. if not ReadSleb(vv) then
  2460. exit;
  2461. if (vv>high(int32)) or (vv<low(int32)) then
  2462. exit;
  2463. v:=vv;
  2464. result:=true;
  2465. end;
  2466. function ReadName(out v: ansistring): boolean;
  2467. var
  2468. len: uint32;
  2469. begin
  2470. result:=false;
  2471. if not ReadUleb32(len) then
  2472. exit;
  2473. SetLength(v,len);
  2474. if len>0 then
  2475. result:=read(v[1],len)
  2476. else
  2477. result:=true;
  2478. end;
  2479. function ReadCustomSection: Boolean;
  2480. function ReadRelocationSection: Boolean;
  2481. var
  2482. TargetSection, RelocCount: uint32;
  2483. i: Integer;
  2484. RelocTableIndex: Integer;
  2485. ds: TWasmCustomDebugSectionType;
  2486. begin
  2487. Result:=False;
  2488. if not ReadUleb32(TargetSection) then
  2489. begin
  2490. InputError('Error reading the index of the target section of a relocation section');
  2491. exit;
  2492. end;
  2493. if TargetSection=CodeSectionIndex then
  2494. RelocTableIndex:=0
  2495. else if TargetSection=DataSectionIndex then
  2496. RelocTableIndex:=1
  2497. else
  2498. begin
  2499. RelocTableIndex:=-1;
  2500. for ds:=Low(DebugSectionIndex) to High(DebugSectionIndex) do
  2501. if DebugSectionIndex[ds]=TargetSection then
  2502. begin
  2503. RelocTableIndex:=2+(Ord(ds)-Ord(Low(TWasmCustomDebugSectionType)));
  2504. break;
  2505. end;
  2506. if RelocTableIndex=-1 then
  2507. begin
  2508. InputError('Relocation found for a custom section, that is not supported');
  2509. exit;
  2510. end;
  2511. end;
  2512. if not ReadUleb32(RelocCount) then
  2513. begin
  2514. InputError('Error reading the relocation entries count from a relocation section');
  2515. exit;
  2516. end;
  2517. SetLength(RelocationTable[RelocTableIndex],RelocCount);
  2518. for i:=0 to RelocCount-1 do
  2519. with RelocationTable[RelocTableIndex,i] do
  2520. begin
  2521. if not Read(RelocType,1) then
  2522. begin
  2523. InputError('Error reading the relocation type of a relocation entry');
  2524. exit;
  2525. end;
  2526. if not (RelocType in [R_WASM_FUNCTION_INDEX_LEB,
  2527. R_WASM_MEMORY_ADDR_LEB,
  2528. R_WASM_TABLE_INDEX_SLEB,
  2529. R_WASM_MEMORY_ADDR_SLEB,
  2530. R_WASM_SECTION_OFFSET_I32,
  2531. R_WASM_TABLE_INDEX_I32,
  2532. R_WASM_FUNCTION_OFFSET_I32,
  2533. R_WASM_MEMORY_ADDR_I32,
  2534. R_WASM_TYPE_INDEX_LEB,
  2535. R_WASM_GLOBAL_INDEX_LEB,
  2536. R_WASM_TAG_INDEX_LEB]) then
  2537. begin
  2538. InputError('Unsupported relocation type: ' + tostr(Ord(RelocType)));
  2539. exit;
  2540. end;
  2541. if not ReadUleb32(RelocOffset) then
  2542. begin
  2543. InputError('Error reading the relocation offset of a relocation entry');
  2544. exit;
  2545. end;
  2546. if not ReadUleb32(RelocIndex) then
  2547. begin
  2548. InputError('Error reading the relocation index of a relocation entry');
  2549. exit;
  2550. end;
  2551. 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
  2552. begin
  2553. if not ReadSleb32(RelocAddend) then
  2554. begin
  2555. InputError('Error reading the relocation addend of a relocation entry');
  2556. exit;
  2557. end;
  2558. end;
  2559. if (RelocType in [
  2560. R_WASM_SECTION_OFFSET_I32,
  2561. R_WASM_FUNCTION_INDEX_LEB,
  2562. R_WASM_TABLE_INDEX_SLEB,
  2563. R_WASM_TABLE_INDEX_I32,
  2564. R_WASM_MEMORY_ADDR_LEB,
  2565. R_WASM_MEMORY_ADDR_SLEB,
  2566. R_WASM_MEMORY_ADDR_I32,
  2567. R_WASM_FUNCTION_OFFSET_I32,
  2568. R_WASM_GLOBAL_INDEX_LEB]) and (RelocIndex>High(SymbolTable)) then
  2569. begin
  2570. InputError('Relocation index outside the bounds of the symbol table');
  2571. exit;
  2572. end;
  2573. if (RelocType=R_WASM_TYPE_INDEX_LEB) and (RelocIndex>High(FFuncTypes)) then
  2574. begin
  2575. InputError('Relocation index of R_WASM_TYPE_INDEX_LEB outside the bounds of the func types, defined in the func section of the module');
  2576. exit;
  2577. end;
  2578. if (RelocType=R_WASM_SECTION_OFFSET_I32) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_SECTION) then
  2579. begin
  2580. InputError('R_WASM_SECTION_OFFSET_I32 must point to a SYMTAB_SECTION symbol');
  2581. exit;
  2582. end;
  2583. if (RelocType=R_WASM_GLOBAL_INDEX_LEB) and
  2584. not ((SymbolTable[RelocIndex].SymKind=SYMTAB_GLOBAL) or
  2585. ((ts_wasm_threads in current_settings.targetswitches) and
  2586. (SymbolTable[RelocIndex].SymKind=SYMTAB_DATA) and
  2587. ((SymbolTable[RelocIndex].SymFlags and WASM_SYM_TLS)<>0))) then
  2588. begin
  2589. if ts_wasm_threads in current_settings.targetswitches then
  2590. InputError('Relocation must point to a SYMTAB_GLOBAL symbol or a SYMTAB_DATA symbol with the WASM_SYM_TLS flag set')
  2591. else
  2592. InputError('Relocation must point to a SYMTAB_GLOBAL symbol');
  2593. exit;
  2594. end;
  2595. if (RelocType=R_WASM_TAG_INDEX_LEB) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_EVENT) then
  2596. begin
  2597. InputError('Relocation must point to a SYMTAB_EVENT symbol');
  2598. exit;
  2599. end;
  2600. if (RelocType in [
  2601. R_WASM_FUNCTION_INDEX_LEB,
  2602. R_WASM_TABLE_INDEX_SLEB,
  2603. R_WASM_TABLE_INDEX_I32,
  2604. R_WASM_FUNCTION_OFFSET_I32]) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_FUNCTION) then
  2605. begin
  2606. InputError('Relocation must point to a SYMTAB_FUNCTION symbol');
  2607. exit;
  2608. end;
  2609. if (RelocType in [
  2610. R_WASM_MEMORY_ADDR_LEB,
  2611. R_WASM_MEMORY_ADDR_SLEB,
  2612. R_WASM_MEMORY_ADDR_I32]) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_DATA) then
  2613. begin
  2614. InputError('Relocation must point to a SYMTAB_DATA symbol');
  2615. exit;
  2616. end;
  2617. end;
  2618. if AReader.Pos<>(SectionStart+SectionSize) then
  2619. begin
  2620. InputError('Unexpected relocation section size');
  2621. exit;
  2622. end;
  2623. Result:=True;
  2624. end;
  2625. function ReadLinkingSection: Boolean;
  2626. function ReadSegmentInfo: Boolean;
  2627. var
  2628. SegmentCount: uint32;
  2629. i: Integer;
  2630. begin
  2631. Result:=False;
  2632. if SegmentInfoSectionRead then
  2633. begin
  2634. InputError('The WASM_SEGMENT_INFO subsection is duplicated');
  2635. exit;
  2636. end;
  2637. SegmentInfoSectionRead:=True;
  2638. if not ReadUleb32(SegmentCount) then
  2639. begin
  2640. InputError('Error reading the segment count from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2641. exit;
  2642. end;
  2643. if SegmentCount<>Length(DataSegments) then
  2644. begin
  2645. InputError('Segment count in the WASM_SEGMENT_INFO subsection does not match the data count in the data section');
  2646. exit;
  2647. end;
  2648. for i:=0 to SegmentCount-1 do
  2649. with DataSegments[i] do
  2650. begin
  2651. if not ReadName(SegName) then
  2652. begin
  2653. InputError('Error reading segment name from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2654. exit;
  2655. end;
  2656. if not ReadUleb32(SegAlignment) then
  2657. begin
  2658. InputError('Error reading segment alignment from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2659. exit;
  2660. end;
  2661. if not ReadUleb32(SegFlags) then
  2662. begin
  2663. InputError('Error reading segment flags from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2664. exit;
  2665. end;
  2666. end;
  2667. if AReader.Pos<>(SectionStart+SectionSize) then
  2668. begin
  2669. InputError('Unexpected WASM_SEGMENT_INFO section size');
  2670. exit;
  2671. end;
  2672. Result:=True;
  2673. end;
  2674. function ReadSymbolTable: Boolean;
  2675. var
  2676. SymCount: uint32;
  2677. i: Integer;
  2678. SymKindName: string;
  2679. SymKindB: Byte;
  2680. begin
  2681. Result:=False;
  2682. if SymbolTableSectionRead then
  2683. begin
  2684. InputError('The WASM_SYMBOL_TABLE subsection is duplicated');
  2685. exit;
  2686. end;
  2687. SymbolTableSectionRead:=True;
  2688. if not ReadUleb32(SymCount) then
  2689. begin
  2690. InputError('Error reading the symbol count from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2691. exit;
  2692. end;
  2693. SetLength(SymbolTable,SymCount);
  2694. for i:=0 to SymCount-1 do
  2695. with SymbolTable[i] do
  2696. begin
  2697. if not Read(SymKindB,1) then
  2698. begin
  2699. InputError('Error reading symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2700. exit;
  2701. end;
  2702. if SymKindB>Ord(High(TWasmSymbolType)) then
  2703. begin
  2704. InputError('Unsupported symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2705. exit;
  2706. end;
  2707. SymKind:=TWasmSymbolType(SymKindB);
  2708. if not ReadUleb32(SymFlags) then
  2709. begin
  2710. InputError('Error reading symbol flags from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2711. exit;
  2712. end;
  2713. case SymKind of
  2714. SYMTAB_FUNCTION,
  2715. SYMTAB_GLOBAL,
  2716. SYMTAB_EVENT,
  2717. SYMTAB_TABLE:
  2718. begin
  2719. WriteStr(SymKindName, SymKind);
  2720. if not ReadUleb32(SymIndex) then
  2721. begin
  2722. InputError('Error reading the index of a ' + SymKindName + ' symbol');
  2723. exit;
  2724. end;
  2725. if ((SymKind=SYMTAB_FUNCTION) and (SymIndex>high(FuncTypes))) or
  2726. ((SymKind=SYMTAB_EVENT) and (SymIndex>high(TagTypes))) then
  2727. begin
  2728. InputError('Symbol index too high');
  2729. exit;
  2730. end;
  2731. if ((SymFlags and WASM_SYM_EXPLICIT_NAME)<>0) or
  2732. ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  2733. begin
  2734. if not ReadName(SymName) then
  2735. begin
  2736. InputError('Error reading symbol name of a ' + SymKindName + ' symbol');
  2737. exit;
  2738. end;
  2739. end;
  2740. end;
  2741. SYMTAB_DATA:
  2742. begin
  2743. if not ReadName(SymName) then
  2744. begin
  2745. InputError('Error reading symbol name of a SYMTAB_DATA symbol');
  2746. exit;
  2747. end;
  2748. if (SymFlags and WASM_SYM_UNDEFINED)=0 then
  2749. begin
  2750. if not ReadUleb32(SymIndex) then
  2751. begin
  2752. InputError('Error reading the data segment index of a SYMTAB_DATA symbol');
  2753. exit;
  2754. end;
  2755. if SymIndex>high(DataSegments) then
  2756. begin
  2757. InputError('Data segment index of SYMTAB_DATA symbol out of bounds');
  2758. exit;
  2759. end;
  2760. if not ReadUleb32(SymOffset) then
  2761. begin
  2762. InputError('Error reading the offset of a SYMTAB_DATA symbol');
  2763. exit;
  2764. end;
  2765. if not ReadUleb32(SymSize) then
  2766. begin
  2767. InputError('Error reading the size of a SYMTAB_DATA symbol');
  2768. exit;
  2769. end;
  2770. end;
  2771. end;
  2772. SYMTAB_FPC_CUSTOM:
  2773. begin
  2774. if not ReadName(SymName) then
  2775. begin
  2776. InputError('Error reading symbol name of a SYMTAB_FPC_CUSTOM symbol');
  2777. exit;
  2778. end;
  2779. if (SymFlags and WASM_SYM_UNDEFINED)=0 then
  2780. begin
  2781. if not ReadUleb32(SymCustomSectionIndex) then
  2782. begin
  2783. InputError('Error reading the custom section index of a SYMTAB_FPC_CUSTOM symbol');
  2784. exit;
  2785. end;
  2786. if not FindDebugSectionByIndex(SymCustomSectionIndex,SymCustomSectionType) then
  2787. begin
  2788. InputError('Custom section index of SYMTAB_FPC_CUSTOM symbol not pointing to a debug section');
  2789. exit;
  2790. end;
  2791. if not ReadUleb32(SymOffset) then
  2792. begin
  2793. InputError('Error reading the offset of a SYMTAB_FPC_CUSTOM symbol');
  2794. exit;
  2795. end;
  2796. if not ReadUleb32(SymSize) then
  2797. begin
  2798. InputError('Error reading the size of a SYMTAB_FPC_CUSTOM symbol');
  2799. exit;
  2800. end;
  2801. end;
  2802. end;
  2803. SYMTAB_SECTION:
  2804. begin
  2805. if not ReadUleb32(TargetSection) then
  2806. begin
  2807. InputError('Error reading the target section of a SYMTAB_SECTION symbol');
  2808. exit;
  2809. end;
  2810. end;
  2811. end;
  2812. end;
  2813. if AReader.Pos<>(SectionStart+SectionSize) then
  2814. begin
  2815. InputError('Unexpected WASM_SYMBOL_TABLE section size');
  2816. exit;
  2817. end;
  2818. Result:=True;
  2819. end;
  2820. const
  2821. ExpectedVersion = 2;
  2822. var
  2823. Version, SubsectionSize, SaveSectionSize: uint32;
  2824. SubsectionType: Byte;
  2825. SaveSectionStart: LongInt;
  2826. begin
  2827. Result:=False;
  2828. if not ReadUleb32(Version) then
  2829. begin
  2830. InputError('Error reading the version of the ''linking'' section');
  2831. exit;
  2832. end;
  2833. if Version<>ExpectedVersion then
  2834. begin
  2835. InputError('The ''linking'' section has an unsupported version (expected version ' + tostr(ExpectedVersion) + ', got version ' + tostr(Version) + ')');
  2836. exit;
  2837. end;
  2838. while AReader.Pos<(SectionStart+SectionSize) do
  2839. begin
  2840. if not read(SubsectionType, 1) then
  2841. begin
  2842. InputError('Error reading subsection type in the ''linking'' section');
  2843. exit;
  2844. end;
  2845. if not ReadUleb32(SubsectionSize) then
  2846. begin
  2847. InputError('Error reading subsection size in the ''linking'' section');
  2848. exit;
  2849. end;
  2850. if (AReader.Pos+SubsectionSize)>(SectionStart+SectionSize) then
  2851. begin
  2852. InputError('Subsection size exceeds bounds of its parent ''linking'' section');
  2853. exit;
  2854. end;
  2855. SaveSectionStart:=SectionStart;
  2856. SaveSectionSize:=SectionSize;
  2857. SectionStart:=AReader.Pos;
  2858. SectionSize:=SubsectionSize;
  2859. case SubsectionType of
  2860. Byte(WASM_SEGMENT_INFO):
  2861. if not ReadSegmentInfo then
  2862. begin
  2863. InputError('Error reading the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2864. exit;
  2865. end;
  2866. Byte(WASM_SYMBOL_TABLE):
  2867. if not ReadSymbolTable then
  2868. begin
  2869. InputError('Error reading the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2870. exit;
  2871. end;
  2872. else
  2873. begin
  2874. InputError('Unsupported ''linking'' section subsection type ' + tostr(SubsectionType));
  2875. exit;
  2876. end;
  2877. end;
  2878. AReader.Seek(SectionStart+SectionSize);
  2879. SectionStart:=SaveSectionStart;
  2880. SectionSize:=SaveSectionSize;
  2881. end;
  2882. result:=True;
  2883. end;
  2884. function ReadProducersSection: Boolean;
  2885. begin
  2886. Result:=False;
  2887. end;
  2888. function ReadTargetFeaturesSection: Boolean;
  2889. begin
  2890. Result:=False;
  2891. end;
  2892. function ReadDebugSection(const SectionName: string; SectionType: TWasmCustomDebugSectionType): Boolean;
  2893. var
  2894. ObjSec: TObjSection;
  2895. begin
  2896. Result:=False;
  2897. if DebugSectionIndex[SectionType]<>-1 then
  2898. begin
  2899. InputError('Duplicated debug section: ' + SectionName);
  2900. exit;
  2901. end;
  2902. DebugSectionIndex[SectionType]:=SectionIndex;
  2903. ObjSec:=ObjData.createsection(SectionName,1,[oso_Data,oso_debug],false);
  2904. ObjSec.DataPos:=AReader.Pos;
  2905. ObjSec.Size:=SectionStart+SectionSize-AReader.Pos;
  2906. Result:=True;
  2907. end;
  2908. const
  2909. RelocationSectionPrefix = 'reloc.';
  2910. var
  2911. SectionName: ansistring;
  2912. begin
  2913. Result:=False;
  2914. ReadName(SectionName);
  2915. if Copy(SectionName,1,Length(RelocationSectionPrefix)) = RelocationSectionPrefix then
  2916. begin
  2917. if not ReadRelocationSection then
  2918. begin
  2919. InputError('Error reading the relocation section ''' + SectionName + '''');
  2920. exit;
  2921. end;
  2922. end
  2923. else
  2924. case SectionName of
  2925. 'linking':
  2926. if not ReadLinkingSection then
  2927. begin
  2928. InputError('Error reading the ''linking'' section');
  2929. exit;
  2930. end;
  2931. 'producers':
  2932. Result:=ReadProducersSection;
  2933. 'target_features':
  2934. Result:=ReadTargetFeaturesSection;
  2935. '.debug_frame':
  2936. if not ReadDebugSection(SectionName, wcstDebugFrame) then
  2937. begin
  2938. InputError('Error reading section ' + SectionName);
  2939. exit;
  2940. end;
  2941. '.debug_info':
  2942. if not ReadDebugSection(SectionName, wcstDebugInfo) then
  2943. begin
  2944. InputError('Error reading section ' + SectionName);
  2945. exit;
  2946. end;
  2947. '.debug_line':
  2948. if not ReadDebugSection(SectionName, wcstDebugLine) then
  2949. begin
  2950. InputError('Error reading section ' + SectionName);
  2951. exit;
  2952. end;
  2953. '.debug_abbrev':
  2954. if not ReadDebugSection(SectionName, wcstDebugAbbrev) then
  2955. begin
  2956. InputError('Error reading section ' + SectionName);
  2957. exit;
  2958. end;
  2959. '.debug_aranges':
  2960. if not ReadDebugSection(SectionName, wcstDebugAranges) then
  2961. begin
  2962. InputError('Error reading section ' + SectionName);
  2963. exit;
  2964. end;
  2965. '.debug_ranges':
  2966. if not ReadDebugSection(SectionName, wcstDebugRanges) then
  2967. begin
  2968. InputError('Error reading section ' + SectionName);
  2969. exit;
  2970. end;
  2971. '.debug_str':
  2972. if not ReadDebugSection(SectionName, wcstDebugStr) then
  2973. begin
  2974. InputError('Error reading section ' + SectionName);
  2975. exit;
  2976. end;
  2977. else
  2978. InputError('Unsupported custom section: ''' + SectionName + '''');
  2979. end;
  2980. Result:=True;
  2981. end;
  2982. function ReadTypeSection: Boolean;
  2983. var
  2984. FuncTypesCount, ParamsCount, ResultsCount: uint32;
  2985. FuncTypeId, WasmTypeId: Byte;
  2986. i, j: Integer;
  2987. wbt: TWasmBasicType;
  2988. begin
  2989. Result:=False;
  2990. if TypeSectionRead then
  2991. begin
  2992. InputError('Type section is duplicated');
  2993. exit;
  2994. end;
  2995. TypeSectionRead:=True;
  2996. if not ReadUleb32(FuncTypesCount) then
  2997. begin
  2998. InputError('Error reading the func types count');
  2999. exit;
  3000. end;
  3001. SetLength(FFuncTypes,FuncTypesCount);
  3002. for i:=0 to FuncTypesCount - 1 do
  3003. begin
  3004. FFuncTypes[i]:=TWasmFuncType.Create([],[]);
  3005. if not AReader.read(FuncTypeId,1) then
  3006. begin
  3007. InputError('Error reading the function type identifier');
  3008. exit;
  3009. end;
  3010. if FuncTypeId<>$60 then
  3011. begin
  3012. InputError('Incorrect function type identifier (expected $60, got $' + HexStr(FuncTypeId,2) + ')');
  3013. exit;
  3014. end;
  3015. if not ReadUleb32(ParamsCount) then
  3016. begin
  3017. InputError('Error reading the function parameters count');
  3018. exit;
  3019. end;
  3020. for j:=0 to ParamsCount-1 do
  3021. begin
  3022. if not AReader.read(WasmTypeId,1) then
  3023. begin
  3024. InputError('Error reading a function parameter basic type');
  3025. exit;
  3026. end;
  3027. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  3028. begin
  3029. InputError('Unknown function parameter basic type: $' + HexStr(WasmTypeId,2));
  3030. exit;
  3031. end;
  3032. FFuncTypes[i].add_param(wbt);
  3033. end;
  3034. if not ReadUleb32(ResultsCount) then
  3035. begin
  3036. InputError('Error reading the function results count');
  3037. exit;
  3038. end;
  3039. for j:=0 to ResultsCount-1 do
  3040. begin
  3041. if not AReader.read(WasmTypeId,1) then
  3042. begin
  3043. InputError('Error reading a function result basic type');
  3044. exit;
  3045. end;
  3046. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  3047. begin
  3048. InputError('Unknown function result basic type: $' + HexStr(WasmTypeId,2));
  3049. exit;
  3050. end;
  3051. FFuncTypes[i].add_result(wbt);
  3052. end;
  3053. end;
  3054. if AReader.Pos<>(SectionStart+SectionSize) then
  3055. begin
  3056. InputError('Unexpected type section size');
  3057. exit;
  3058. end;
  3059. Result:=true;
  3060. end;
  3061. function ReadImportSection: Boolean;
  3062. var
  3063. ImportsCount: uint32;
  3064. i: Integer;
  3065. ModName, Name: ansistring;
  3066. ImportType, TableElemTyp, TableLimitsKind, MemoryLimitsKind,
  3067. GlobalType, GlobalMutabilityType: Byte;
  3068. begin
  3069. Result:=False;
  3070. if ImportSectionRead then
  3071. begin
  3072. InputError('Import section is duplicated');
  3073. exit;
  3074. end;
  3075. ImportSectionRead:=True;
  3076. if not ReadUleb32(ImportsCount) then
  3077. begin
  3078. InputError('Error reading the imports count');
  3079. exit;
  3080. end;
  3081. for i:=0 to ImportsCount-1 do
  3082. begin
  3083. if not ReadName(ModName) then
  3084. begin
  3085. InputError('Error reading import module name');
  3086. exit;
  3087. end;
  3088. if not ReadName(Name) then
  3089. begin
  3090. InputError('Error import name');
  3091. exit;
  3092. end;
  3093. if not AReader.Read(ImportType,1) then
  3094. begin
  3095. InputError('Error reading import type');
  3096. exit;
  3097. end;
  3098. case ImportType of
  3099. $00: { func }
  3100. begin
  3101. Inc(FuncTypeImportsCount);
  3102. SetLength(FuncTypes,FuncTypeImportsCount);
  3103. with FuncTypes[FuncTypeImportsCount-1] do
  3104. begin
  3105. IsImport:=True;
  3106. ImportName:=Name;
  3107. ImportModName:=ModName;
  3108. if not ReadUleb32(typidx) then
  3109. begin
  3110. InputError('Error reading type index for func import');
  3111. exit;
  3112. end;
  3113. if typidx>high(FFuncTypes) then
  3114. begin
  3115. InputError('Type index in func import exceeds bounds of the types table');
  3116. exit;
  3117. end;
  3118. end;
  3119. end;
  3120. $01: { table }
  3121. begin
  3122. Inc(TableTypeImportsCount);
  3123. SetLength(TableTypes,TableTypeImportsCount);
  3124. with TableTypes[TableTypeImportsCount-1] do
  3125. begin
  3126. IsImport:=True;
  3127. ImportName:=Name;
  3128. ImportModName:=ModName;
  3129. if not AReader.read(TableElemTyp,1) then
  3130. begin
  3131. InputError('Error reading table element type for table import');
  3132. exit;
  3133. end;
  3134. if not decode_wasm_basic_type(TableElemTyp,reftype) then
  3135. begin
  3136. InputError('Invalid table element type for table import: $' + HexStr(TableElemTyp,2));
  3137. exit;
  3138. end;
  3139. if not (reftype in WasmReferenceTypes) then
  3140. begin
  3141. InputError('Table element type for table import must be a reference type');
  3142. exit;
  3143. end;
  3144. if not AReader.read(TableLimitsKind,1) then
  3145. begin
  3146. InputError('Error reading table limits kind for table import');
  3147. exit;
  3148. end;
  3149. case TableLimitsKind of
  3150. $00:
  3151. begin
  3152. limits.HasMax:=False;
  3153. limits.Max:=high(limits.Max);
  3154. if not ReadUleb32(limits.min) then
  3155. begin
  3156. InputError('Error reading table limits min for table import');
  3157. exit;
  3158. end;
  3159. end;
  3160. $01:
  3161. begin
  3162. limits.HasMax:=True;
  3163. if not ReadUleb32(limits.min) then
  3164. begin
  3165. InputError('Error reading table limits min for table import');
  3166. exit;
  3167. end;
  3168. if not ReadUleb32(limits.max) then
  3169. begin
  3170. InputError('Error reading table limits max for table import');
  3171. exit;
  3172. end;
  3173. if limits.min>limits.max then
  3174. begin
  3175. InputError('Table limits min exceed table limits max in table import');
  3176. exit;
  3177. end;
  3178. end;
  3179. else
  3180. begin
  3181. InputError('Unsupported table limits kind for table import: $' + HexStr(TableLimitsKind,2));
  3182. exit;
  3183. end;
  3184. end;
  3185. end;
  3186. end;
  3187. $02: { mem }
  3188. begin
  3189. Inc(MemTypeImportsCount);
  3190. SetLength(MemTypes,MemTypeImportsCount);
  3191. with MemTypes[MemTypeImportsCount-1] do
  3192. begin
  3193. IsImport:=True;
  3194. ImportName:=Name;
  3195. ImportModName:=ModName;
  3196. if not AReader.read(MemoryLimitsKind,1) then
  3197. begin
  3198. InputError('Error reading memory limits kind for memory import');
  3199. exit;
  3200. end;
  3201. case MemoryLimitsKind of
  3202. $00:
  3203. begin
  3204. limits.HasMax:=False;
  3205. limits.Max:=high(limits.Max);
  3206. if not ReadUleb32(limits.min) then
  3207. begin
  3208. InputError('Error reading memory limits min for memory import');
  3209. exit;
  3210. end;
  3211. end;
  3212. $01:
  3213. begin
  3214. limits.HasMax:=True;
  3215. if not ReadUleb32(limits.min) then
  3216. begin
  3217. InputError('Error reading memory limits min for memory import');
  3218. exit;
  3219. end;
  3220. if not ReadUleb32(limits.max) then
  3221. begin
  3222. InputError('Error reading memory limits max for memory import');
  3223. exit;
  3224. end;
  3225. if limits.Min>limits.Max then
  3226. begin
  3227. InputError('Memory limits min exceed memory limits max in memory import');
  3228. exit;
  3229. end;
  3230. end;
  3231. else
  3232. begin
  3233. InputError('Unsupported memory limits kind for memory import: $' + HexStr(MemoryLimitsKind,2));
  3234. exit;
  3235. end;
  3236. end;
  3237. end;
  3238. end;
  3239. $03: { global }
  3240. begin
  3241. Inc(GlobalTypeImportsCount);
  3242. SetLength(GlobalTypes,GlobalTypeImportsCount);
  3243. with GlobalTypes[GlobalTypeImportsCount-1] do
  3244. begin
  3245. IsImport:=True;
  3246. ImportName:=Name;
  3247. ImportModName:=ModName;
  3248. if not AReader.read(GlobalType,1) then
  3249. begin
  3250. InputError('Error reading global type for global import');
  3251. exit;
  3252. end;
  3253. if not decode_wasm_basic_type(GlobalType,valtype) then
  3254. begin
  3255. InputError('Unsupported global type for global import: ' + HexStr(GlobalType,2));
  3256. exit;
  3257. end;
  3258. if not AReader.read(GlobalMutabilityType,1) then
  3259. begin
  3260. InputError('Error reading global mutability flag for global import');
  3261. exit;
  3262. end;
  3263. case GlobalMutabilityType of
  3264. $00:
  3265. IsMutable:=False;
  3266. $01:
  3267. IsMutable:=True;
  3268. else
  3269. begin
  3270. InputError('Unknown global mutability flag for global import: $' + HexStr(GlobalMutabilityType,2));
  3271. exit;
  3272. end;
  3273. end;
  3274. end;
  3275. end;
  3276. $04: { tag }
  3277. begin
  3278. Inc(TagTypeImportsCount);
  3279. SetLength(TagTypes,TagTypeImportsCount);
  3280. with TagTypes[TagTypeImportsCount-1] do
  3281. begin
  3282. IsImport:=True;
  3283. ImportName:=Name;
  3284. ImportModName:=ModName;
  3285. if not Read(TagAttr,1) then
  3286. begin
  3287. InputError('Error reading import tag attribute');
  3288. exit;
  3289. end;
  3290. if not ReadUleb32(TagTypeIdx) then
  3291. begin
  3292. InputError('Error reading import tag type index');
  3293. exit;
  3294. end;
  3295. if TagTypeIdx>high(FFuncTypes) then
  3296. begin
  3297. InputError('Type index in tag import exceeds bounds of the types table');
  3298. exit;
  3299. end;
  3300. end;
  3301. end;
  3302. else
  3303. begin
  3304. InputError('Unknown import type: $' + HexStr(ImportType,2));
  3305. exit;
  3306. end;
  3307. end;
  3308. end;
  3309. if AReader.Pos<>(SectionStart+SectionSize) then
  3310. begin
  3311. InputError('Unexpected import section size');
  3312. exit;
  3313. end;
  3314. Result:=true;
  3315. end;
  3316. function ReadFunctionSection: Boolean;
  3317. var
  3318. FunctionsCount: uint32;
  3319. i: Integer;
  3320. begin
  3321. Result:=False;
  3322. if FunctionSectionRead then
  3323. begin
  3324. InputError('Function section is duplicated');
  3325. exit;
  3326. end;
  3327. FunctionSectionRead:=True;
  3328. if not ReadUleb32(FunctionsCount) then
  3329. begin
  3330. InputError('Error reading the functions count');
  3331. exit;
  3332. end;
  3333. SetLength(FuncTypes, FuncTypeImportsCount + FunctionsCount);
  3334. for i:=0 to FunctionsCount-1 do
  3335. with FuncTypes[i + FuncTypeImportsCount] do
  3336. begin
  3337. IsImport:=False;
  3338. if not ReadUleb32(typidx) then
  3339. begin
  3340. InputError('Error reading type index for function');
  3341. exit;
  3342. end;
  3343. if typidx>high(FFuncTypes) then
  3344. begin
  3345. InputError('Type index in the function section exceeds bounds of the types table');
  3346. exit;
  3347. end;
  3348. end;
  3349. if AReader.Pos<>(SectionStart+SectionSize) then
  3350. begin
  3351. InputError('Unexpected function section size');
  3352. exit;
  3353. end;
  3354. Result:=true;
  3355. end;
  3356. function ReadGlobalSection: Boolean;
  3357. function ParseExpr(out Init: TGlobalInitializer): Boolean;
  3358. var
  3359. B, B2: Byte;
  3360. tmpU32: UInt32;
  3361. tmpU64: UInt64;
  3362. begin
  3363. Result:=False;
  3364. repeat
  3365. if not Read(B, 1) then
  3366. exit;
  3367. case B of
  3368. $0B: { end }
  3369. ;
  3370. $41: { i32.const }
  3371. begin
  3372. Init.typ:=wbt_i32;
  3373. if not ReadSleb32(Init.init_i32) then
  3374. exit;
  3375. end;
  3376. $42: { i64.const }
  3377. begin
  3378. Init.typ:=wbt_i64;
  3379. if not ReadSleb(Init.init_i64) then
  3380. exit;
  3381. end;
  3382. $43: { f32.const }
  3383. begin
  3384. Init.typ:=wbt_f32;
  3385. if not Read(tmpU32, 4) then
  3386. exit;
  3387. {$ifdef FPC_BIG_ENDIAN}
  3388. tmpU32:=SwapEndian(tmpU32);
  3389. {$endif FPC_BIG_ENDIAN}
  3390. Move(tmpU32,Init.init_f32,4);
  3391. end;
  3392. $44: { f64.const }
  3393. begin
  3394. Init.typ:=wbt_f64;
  3395. if not Read(tmpU64, 8) then
  3396. exit;
  3397. {$ifdef FPC_BIG_ENDIAN}
  3398. tmpU64:=SwapEndian(tmpU64);
  3399. {$endif FPC_BIG_ENDIAN}
  3400. Move(tmpU64,Init.init_f64,8);
  3401. end;
  3402. $D0: { ref.null }
  3403. begin
  3404. if not Read(B2, 1) then
  3405. exit;
  3406. if not decode_wasm_basic_type(B2, Init.typ) then
  3407. exit;
  3408. if not (Init.typ in WasmReferenceTypes) then
  3409. exit;
  3410. end;
  3411. else
  3412. begin
  3413. InputError('Unsupported opcode in global initializer');
  3414. exit;
  3415. end;
  3416. end;
  3417. until b = $0B;
  3418. Result:=True;
  3419. end;
  3420. var
  3421. GlobalsCount: uint32;
  3422. i: Integer;
  3423. vt: Byte;
  3424. mut: Byte;
  3425. begin
  3426. Result:=False;
  3427. if GlobalSectionRead then
  3428. begin
  3429. InputError('Global section is duplicated');
  3430. exit;
  3431. end;
  3432. GlobalSectionRead:=True;
  3433. if not ReadUleb32(GlobalsCount) then
  3434. begin
  3435. InputError('Error reading the globals count from the global section');
  3436. exit;
  3437. end;
  3438. SetLength(GlobalTypes,Length(GlobalTypes)+GlobalsCount);
  3439. for i:=0 to GlobalsCount-1 do
  3440. with GlobalTypes[i + GlobalTypeImportsCount] do
  3441. begin
  3442. if not read(vt,1) then
  3443. begin
  3444. InputError('Error reading the type of a global from the global section');
  3445. exit;
  3446. end;
  3447. if not decode_wasm_basic_type(vt,valtype) then
  3448. begin
  3449. InputError('Unsupported type of global in the global section');
  3450. exit;
  3451. end;
  3452. if not read(mut,1) then
  3453. begin
  3454. InputError('Error reading the mutability flag of a global in the global section');
  3455. exit;
  3456. end;
  3457. case mut of
  3458. $00:
  3459. IsMutable:=False;
  3460. $01:
  3461. IsMutable:=True;
  3462. else
  3463. begin
  3464. InputError('Unsupported value (' + tostr(mut) + ') for the mutability flag of a global in the global section');
  3465. exit;
  3466. end;
  3467. end;
  3468. if not ParseExpr(GlobalInit) then
  3469. begin
  3470. InputError('Error parsing the global initializer expression in the global section');
  3471. exit;
  3472. end;
  3473. if GlobalInit.typ<>valtype then
  3474. begin
  3475. InputError('Initializer expression for global produces a type, which does not match the type of the global');
  3476. exit;
  3477. end;
  3478. end;
  3479. if AReader.Pos<>(SectionStart+SectionSize) then
  3480. begin
  3481. InputError('Unexpected global section size');
  3482. exit;
  3483. end;
  3484. Result:=True;
  3485. end;
  3486. function ReadExportSection: Boolean;
  3487. var
  3488. ExportsCount, FuncIdx, TableIdx, MemIdx, GlobalIdx, TagIdx: uint32;
  3489. i: Integer;
  3490. Name: ansistring;
  3491. ExportType: Byte;
  3492. begin
  3493. Result:=False;
  3494. if ExportSectionRead then
  3495. begin
  3496. InputError('Export section is duplicated');
  3497. exit;
  3498. end;
  3499. ExportSectionRead:=True;
  3500. if not ReadUleb32(ExportsCount) then
  3501. begin
  3502. InputError('Error reading the exports count from the export section');
  3503. exit;
  3504. end;
  3505. for i:=0 to ExportsCount-1 do
  3506. begin
  3507. if not ReadName(Name) then
  3508. begin
  3509. InputError('Error reading an export name from the export section');
  3510. exit;
  3511. end;
  3512. if not Read(ExportType,1) then
  3513. begin
  3514. InputError('Error reading an export type from the export section');
  3515. exit;
  3516. end;
  3517. case ExportType of
  3518. $00: { func }
  3519. begin
  3520. if not ReadUleb32(FuncIdx) then
  3521. begin
  3522. InputError('Error reading a func index from the export section');
  3523. exit;
  3524. end;
  3525. if FuncIdx>high(FuncTypes) then
  3526. begin
  3527. InputError('Func index too high in the export section');
  3528. exit;
  3529. end;
  3530. with FuncTypes[FuncIdx] do
  3531. begin
  3532. IsExported:=True;
  3533. ExportName:=Name;
  3534. end;
  3535. end;
  3536. $01: { table }
  3537. begin
  3538. if not ReadUleb32(TableIdx) then
  3539. begin
  3540. InputError('Error reading a table index from the export section');
  3541. exit;
  3542. end;
  3543. if TableIdx>high(TableTypes) then
  3544. begin
  3545. InputError('Table index too high in the export section');
  3546. exit;
  3547. end;
  3548. with TableTypes[TableIdx] do
  3549. begin
  3550. IsExported:=True;
  3551. ExportName:=Name;
  3552. end;
  3553. end;
  3554. $02: { mem }
  3555. begin
  3556. if not ReadUleb32(MemIdx) then
  3557. begin
  3558. InputError('Error reading a mem index from the export section');
  3559. exit;
  3560. end;
  3561. if MemIdx>high(MemTypes) then
  3562. begin
  3563. InputError('Mem index too high in the export section');
  3564. exit;
  3565. end;
  3566. with MemTypes[MemIdx] do
  3567. begin
  3568. IsExported:=True;
  3569. ExportName:=Name;
  3570. end;
  3571. end;
  3572. $03: { global }
  3573. begin
  3574. if not ReadUleb32(GlobalIdx) then
  3575. begin
  3576. InputError('Error reading a global index from the export section');
  3577. exit;
  3578. end;
  3579. if GlobalIdx>high(GlobalTypes) then
  3580. begin
  3581. InputError('Global index too high in the export section');
  3582. exit;
  3583. end;
  3584. with GlobalTypes[GlobalIdx] do
  3585. begin
  3586. IsExported:=True;
  3587. ExportName:=Name;
  3588. end;
  3589. end;
  3590. $04: { tag }
  3591. begin
  3592. if not ReadUleb32(TagIdx) then
  3593. begin
  3594. InputError('Error reading a tag index from the export section');
  3595. exit;
  3596. end;
  3597. if TagIdx>high(TagTypes) then
  3598. begin
  3599. InputError('Tag index too high in the export section');
  3600. exit;
  3601. end;
  3602. with TagTypes[TagIdx] do
  3603. begin
  3604. IsExported:=True;
  3605. ExportName:=Name;
  3606. end;
  3607. end;
  3608. else
  3609. begin
  3610. InputError('Unsupported export type in the export section: ' + tostr(ExportType));
  3611. exit;
  3612. end;
  3613. end;
  3614. end;
  3615. if AReader.Pos<>(SectionStart+SectionSize) then
  3616. begin
  3617. InputError('Unexpected export section size');
  3618. exit;
  3619. end;
  3620. Result:=True;
  3621. end;
  3622. function ReadElementSection: Boolean;
  3623. begin
  3624. Result:=False;
  3625. if ElementSectionRead then
  3626. begin
  3627. InputError('Element section is duplicated');
  3628. exit;
  3629. end;
  3630. ElementSectionRead:=True;
  3631. { We skip the element section for now }
  3632. { TODO: implement reading it (and linking of tables) }
  3633. Result:=True;
  3634. end;
  3635. function ReadTagSection: Boolean;
  3636. var
  3637. TagCount: uint32;
  3638. i: Integer;
  3639. begin
  3640. Result:=False;
  3641. if TagSectionRead then
  3642. begin
  3643. InputError('Tag section is duplicated');
  3644. exit;
  3645. end;
  3646. TagSectionRead:=True;
  3647. if not ReadUleb32(TagCount) then
  3648. begin
  3649. InputError('Error reading the tag count from the tag section');
  3650. exit;
  3651. end;
  3652. SetLength(TagTypes,Length(TagTypes)+TagCount);
  3653. for i:=0 to TagCount-1 do
  3654. with TagTypes[i + TagTypeImportsCount] do
  3655. begin
  3656. if not Read(TagAttr,1) then
  3657. begin
  3658. InputError('Error reading tag attribute');
  3659. exit;
  3660. end;
  3661. if not ReadUleb32(TagTypeIdx) then
  3662. begin
  3663. InputError('Error reading tag type index');
  3664. exit;
  3665. end;
  3666. if TagTypeIdx>high(FFuncTypes) then
  3667. begin
  3668. InputError('Type index in tag import exceeds bounds of the types table');
  3669. exit;
  3670. end;
  3671. end;
  3672. if AReader.Pos<>(SectionStart+SectionSize) then
  3673. begin
  3674. InputError('Unexpected tag section size');
  3675. exit;
  3676. end;
  3677. Result:=True;
  3678. end;
  3679. function ReadCodeSection: Boolean;
  3680. var
  3681. CodeEntriesCount: uint32;
  3682. i: Integer;
  3683. begin
  3684. Result:=False;
  3685. if CodeSectionRead then
  3686. begin
  3687. InputError('Code section is duplicated');
  3688. exit;
  3689. end;
  3690. CodeSectionRead:=True;
  3691. CodeSectionIndex:=SectionIndex;
  3692. if not ReadUleb32(CodeEntriesCount) then
  3693. begin
  3694. InputError('Error reading the code entries cound from the code section');
  3695. exit;
  3696. end;
  3697. if CodeEntriesCount <> (Length(FuncTypes) - FuncTypeImportsCount) then
  3698. begin
  3699. InputError('Code segment count in the code section does not match the function definition count in the function section');
  3700. exit;
  3701. end;
  3702. SetLength(CodeSegments,CodeEntriesCount);
  3703. for i:=0 to CodeEntriesCount-1 do
  3704. with CodeSegments[i] do
  3705. begin
  3706. if not ReadUleb32(CodeSize) then
  3707. begin
  3708. InputError('Error reading the code size of an entry in the code section');
  3709. exit;
  3710. end;
  3711. if (AReader.Pos+CodeSize)>(SectionStart+SectionSize) then
  3712. begin
  3713. InputError('Code segment exceeds the bounds of the code section');
  3714. exit;
  3715. end;
  3716. DataPos:=AReader.Pos;
  3717. CodeSectionOffset:=AReader.Pos-SectionStart;
  3718. AReader.Seek(AReader.Pos+CodeSize);
  3719. end;
  3720. if AReader.Pos<>(SectionStart+SectionSize) then
  3721. begin
  3722. InputError('Unexpected code section size');
  3723. exit;
  3724. end;
  3725. Result:=true;
  3726. end;
  3727. function ReadDataSection: Boolean;
  3728. function ReadExpr(out ExprV: int32): Boolean;
  3729. var
  3730. b: Byte;
  3731. begin
  3732. Result:=False;
  3733. if not Read(b,1) then
  3734. exit;
  3735. if b<>$41 then
  3736. begin
  3737. InputError('Only i32.const expressions supported');
  3738. exit;
  3739. end;
  3740. if not ReadSleb32(ExprV) then
  3741. exit;
  3742. if not Read(b,1) then
  3743. exit;
  3744. if b<>$0B then
  3745. begin
  3746. InputError('Only single const expressions supported');
  3747. exit;
  3748. end;
  3749. Result:=True;
  3750. end;
  3751. var
  3752. DataCount: uint32;
  3753. DataType: Byte;
  3754. i: Integer;
  3755. begin
  3756. Result:=False;
  3757. if DataSectionRead then
  3758. begin
  3759. InputError('Data section is duplicated');
  3760. exit;
  3761. end;
  3762. DataSectionRead:=True;
  3763. DataSectionIndex:=SectionIndex;
  3764. if not ReadUleb32(DataCount) then
  3765. begin
  3766. InputError('Error reading the data entries count from the data section');
  3767. exit;
  3768. end;
  3769. if DataCountSectionRead then
  3770. begin
  3771. if Length(DataSegments)<>DataCount then
  3772. begin
  3773. InputError('Data entries count in the data section do not match the number, specified in the data count section');
  3774. exit;
  3775. end;
  3776. end
  3777. else
  3778. SetLength(DataSegments,DataCount);
  3779. for i:=0 to DataCount-1 do
  3780. with DataSegments[i] do
  3781. begin
  3782. if not read(DataType, 1) then
  3783. begin
  3784. InputError('Error reading data type of segment from the data section');
  3785. exit;
  3786. end;
  3787. case DataType of
  3788. 0:
  3789. begin
  3790. Active:=True;
  3791. MemIdx:=0;
  3792. if not ReadExpr(Offset) then
  3793. begin
  3794. InputError('Error reading memory offset of segment from the data section');
  3795. exit;
  3796. end;
  3797. end;
  3798. 1:
  3799. Active:=False;
  3800. 2:
  3801. begin
  3802. Active:=True;
  3803. if not ReadUleb32(MemIdx) then
  3804. begin
  3805. InputError('Error reading MemIdx of segment from the data section');
  3806. exit;
  3807. end;
  3808. if not ReadExpr(Offset) then
  3809. begin
  3810. InputError('Error reading memory offset of segment from the data section');
  3811. exit;
  3812. end;
  3813. end;
  3814. else
  3815. begin
  3816. InputError('Unsupported data type of segment in the data section: ' + tostr(DataType));
  3817. exit;
  3818. end;
  3819. end;
  3820. if MemIdx<>0 then
  3821. begin
  3822. InputError('Memory index other than 0 not supported (got ' + tostr(MemIdx) + ')');
  3823. exit;
  3824. end;
  3825. if not Active then
  3826. begin
  3827. InputError('Passive memory segments not supported');
  3828. exit;
  3829. end;
  3830. if not ReadUleb32(Len) then
  3831. begin
  3832. InputError('Error reading data segment length');
  3833. exit;
  3834. end;
  3835. if (AReader.Pos+Len)>(SectionStart+SectionSize) then
  3836. begin
  3837. InputError('Data segment exceeds the bounds of the data section');
  3838. exit;
  3839. end;
  3840. DataPos:=AReader.Pos;
  3841. DataSectionOffset:=AReader.Pos-SectionStart;
  3842. AReader.Seek(AReader.Pos+Len);
  3843. end;
  3844. if AReader.Pos<>(SectionStart+SectionSize) then
  3845. begin
  3846. InputError('Unexpected data section size');
  3847. exit;
  3848. end;
  3849. Result:=true;
  3850. end;
  3851. function ReadDataCountSection: Boolean;
  3852. var
  3853. DataCount: uint32;
  3854. begin
  3855. Result:=False;
  3856. if DataCountSectionRead then
  3857. begin
  3858. InputError('Data count section is duplicated');
  3859. exit;
  3860. end;
  3861. DataCountSectionRead:=True;
  3862. if DataSectionRead then
  3863. begin
  3864. InputError('The data count section must occur before the data section');
  3865. exit;
  3866. end;
  3867. if not ReadUleb32(DataCount) then
  3868. begin
  3869. InputError('Error reading the data count from the data count section');
  3870. exit;
  3871. end;
  3872. if AReader.Pos<>(SectionStart+SectionSize) then
  3873. begin
  3874. InputError('Unexpected data count section size');
  3875. exit;
  3876. end;
  3877. SetLength(DataSegments, DataCount);
  3878. Result:=true;
  3879. end;
  3880. begin
  3881. Result:=False;
  3882. Inc(SectionIndex);
  3883. if not AReader.read(SectionId,1) then
  3884. begin
  3885. InputError('Error reading section ID');
  3886. exit;
  3887. end;
  3888. CheckSectionBounds:=false;
  3889. if not ReadUleb32(SectionSize) then
  3890. begin
  3891. InputError('Error reading section size');
  3892. exit;
  3893. end;
  3894. if (AReader.Pos+SectionSize)>AReader.size then
  3895. begin
  3896. InputError('Section exceeds beyond the end of file');
  3897. exit;
  3898. end;
  3899. SectionStart:=AReader.Pos;
  3900. CheckSectionBounds:=true;
  3901. case SectionId of
  3902. Byte(wsiCustom):
  3903. if not ReadCustomSection then
  3904. begin
  3905. InputError('Error encountered, while reading a custom section');
  3906. exit;
  3907. end;
  3908. Byte(wsiType):
  3909. if not ReadTypeSection then
  3910. begin
  3911. InputError('Error reading the type section');
  3912. exit;
  3913. end;
  3914. Byte(wsiImport):
  3915. if not ReadImportSection then
  3916. begin
  3917. InputError('Error reading the import section');
  3918. exit;
  3919. end;
  3920. Byte(wsiFunction):
  3921. if not ReadFunctionSection then
  3922. begin
  3923. InputError('Error reading the function section');
  3924. exit;
  3925. end;
  3926. Byte(wsiGlobal):
  3927. if not ReadGlobalSection then
  3928. begin
  3929. InputError('Error reading the global section');
  3930. exit;
  3931. end;
  3932. Byte(wsiExport):
  3933. if not ReadExportSection then
  3934. begin
  3935. InputError('Error reading the export section');
  3936. exit;
  3937. end;
  3938. Byte(wsiElement):
  3939. if not ReadElementSection then
  3940. begin
  3941. InputError('Error reading the element section');
  3942. exit;
  3943. end;
  3944. Byte(wsiTag):
  3945. if not ReadTagSection then
  3946. begin
  3947. InputError('Error reading the tag section');
  3948. exit;
  3949. end;
  3950. Byte(wsiCode):
  3951. if not ReadCodeSection then
  3952. begin
  3953. InputError('Error reading the code section');
  3954. exit;
  3955. end;
  3956. Byte(wsiData):
  3957. if not ReadDataSection then
  3958. begin
  3959. InputError('Error reading the data section');
  3960. exit;
  3961. end;
  3962. Byte(wsiDataCount):
  3963. begin
  3964. if not ReadDataCountSection then
  3965. begin
  3966. InputError('Error reading the data count section');
  3967. exit;
  3968. end;
  3969. end
  3970. else
  3971. begin
  3972. InputError('Unknown section: ' + ToStr(SectionId));
  3973. exit;
  3974. end;
  3975. end;
  3976. if SectionSize>0 then
  3977. AReader.seek(SectionStart+SectionSize);
  3978. Result:=True;
  3979. end;
  3980. function FindCodeSegment(Ofs: uint32): Integer;
  3981. var
  3982. L, R, M: Integer;
  3983. begin
  3984. L:=Low(CodeSegments);
  3985. R:=High(CodeSegments);
  3986. while L<=R do
  3987. begin
  3988. M:=(L+R) div 2;
  3989. if (CodeSegments[M].CodeSectionOffset+CodeSegments[M].CodeSize-1) < Ofs then
  3990. L:=M+1
  3991. else if CodeSegments[M].CodeSectionOffset > Ofs then
  3992. R:=M-1
  3993. else
  3994. begin
  3995. Result:=M;
  3996. exit;
  3997. end;
  3998. end;
  3999. Result:=-1;
  4000. end;
  4001. function FindDataSegment(Ofs: uint32): Integer;
  4002. var
  4003. L, R, M: Integer;
  4004. begin
  4005. L:=Low(DataSegments);
  4006. R:=High(DataSegments);
  4007. while L<=R do
  4008. begin
  4009. M:=(L+R) div 2;
  4010. if (DataSegments[M].DataSectionOffset+DataSegments[M].Len-1) < Ofs then
  4011. L:=M+1
  4012. else if DataSegments[M].DataSectionOffset > Ofs then
  4013. R:=M-1
  4014. else
  4015. begin
  4016. Result:=M;
  4017. exit;
  4018. end;
  4019. end;
  4020. Result:=-1;
  4021. end;
  4022. var
  4023. ModuleMagic: array [0..3] of Byte;
  4024. ModuleVersion: array [0..3] of Byte;
  4025. i, j, FirstCodeSegmentIdx, FirstDataSegmentIdx, SegI: Integer;
  4026. CurrSec, ObjSec: TObjSection;
  4027. BaseSectionOffset: UInt32;
  4028. ObjReloc: TWasmObjRelocation;
  4029. ds: TWasmCustomDebugSectionType;
  4030. begin
  4031. FReader:=AReader;
  4032. InputFileName:=AReader.FileName;
  4033. objdata:=CObjData.Create(InputFileName);
  4034. result:=false;
  4035. CodeSegments:=nil;
  4036. DataSegments:=nil;
  4037. SymbolTable:=nil;
  4038. RelocationTable:=nil;
  4039. SetLength(RelocationTable,2+(Ord(High(TWasmCustomDebugSectionType))-Ord(Low(TWasmCustomDebugSectionType))+1));
  4040. FuncTypes:=nil;
  4041. FuncTypeImportsCount:=0;
  4042. TableTypes:=nil;
  4043. TableTypeImportsCount:=0;
  4044. MemTypes:=nil;
  4045. MemTypeImportsCount:=0;
  4046. GlobalTypes:=nil;
  4047. GlobalTypeImportsCount:=0;
  4048. TagTypes:=nil;
  4049. TagTypeImportsCount:=0;
  4050. if not AReader.read(ModuleMagic,4) then
  4051. exit;
  4052. for i:=0 to 3 do
  4053. if ModuleMagic[i]<>WasmModuleMagic[i] then
  4054. exit;
  4055. if not AReader.read(ModuleVersion,4) then
  4056. exit;
  4057. for i:=0 to 3 do
  4058. if ModuleVersion[i]<>WasmVersion[i] then
  4059. exit;
  4060. while AReader.Pos<AReader.size do
  4061. if not ReadSection then
  4062. exit;
  4063. { fill the code segment names }
  4064. for i:=low(SymbolTable) to high(SymbolTable) do
  4065. with SymbolTable[i] do
  4066. if (SymKind=SYMTAB_FUNCTION) and ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  4067. begin
  4068. if FuncTypes[SymIndex].IsImport then
  4069. begin
  4070. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_FUNCTION symbol, that is an import');
  4071. exit;
  4072. end;
  4073. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  4074. begin
  4075. with CodeSegments[SymIndex-FuncTypeImportsCount] do
  4076. begin
  4077. SegName:='.text.n_'+SymName;
  4078. SegIsExported:=FuncTypes[SymIndex].IsExported;
  4079. end;
  4080. end;
  4081. end;
  4082. { create segments }
  4083. FirstCodeSegmentIdx:=ObjData.ObjSectionList.Count;
  4084. for i:=low(CodeSegments) to high(CodeSegments) do
  4085. with CodeSegments[i] do
  4086. begin
  4087. if SegName='' then
  4088. begin
  4089. InputError('Code section ' + tostr(i) + ' does not have a main symbol defined in the symbol table');
  4090. exit;
  4091. end;
  4092. if SegIsExported then
  4093. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load,oso_keep],false)
  4094. else
  4095. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load],false);
  4096. CurrSec.DataPos:=DataPos;
  4097. CurrSec.Size:=CodeSize;
  4098. end;
  4099. FirstDataSegmentIdx:=ObjData.ObjSectionList.Count;
  4100. for i:=low(DataSegments) to high(DataSegments) do
  4101. with DataSegments[i] do
  4102. if Active then
  4103. begin
  4104. CurrSec:=ObjData.createsection(SegName,1 shl SegAlignment,[oso_Data,oso_load,oso_write],false);
  4105. CurrSec.DataPos:=DataPos;
  4106. CurrSec.MemPos:=Offset;
  4107. CurrSec.Size:=Len;
  4108. end;
  4109. ReadSectionContent(ObjData);
  4110. for i:=low(SymbolTable) to high(SymbolTable) do
  4111. with SymbolTable[i] do
  4112. case SymKind of
  4113. SYMTAB_DATA:
  4114. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  4115. begin
  4116. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4117. objsym.bind:=AB_EXTERNAL;
  4118. if (SymFlags and WASM_SYM_TLS)<>0 then
  4119. begin
  4120. objsym.typ:=AT_TLS;
  4121. objsym.TlsGlobalSym:=TWasmObjSymbol(ObjData.CreateSymbol('GOT.mem.'+SymName));
  4122. objsym.TlsGlobalSym.TlsDataSym:=objsym;
  4123. objsym.TlsGlobalSym.bind:=AB_EXTERNAL;
  4124. objsym.TlsGlobalSym.typ:=AT_WASM_GLOBAL;
  4125. objsym.TlsGlobalSym.objsection:=nil;
  4126. objsym.TlsGlobalSym.offset:=0;
  4127. objsym.TlsGlobalSym.size:=1;
  4128. objsym.TlsGlobalSym.LinkingData.GlobalType:=wbt_i32;
  4129. objsym.TlsGlobalSym.LinkingData.GlobalIsMutable:=true;
  4130. end
  4131. else
  4132. objsym.typ:=AT_DATA;
  4133. objsym.objsection:=nil;
  4134. objsym.offset:=0;
  4135. objsym.size:=0;
  4136. end
  4137. else
  4138. begin
  4139. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4140. if (SymFlags and WASM_SYM_BINDING_LOCAL)<> 0 then
  4141. objsym.bind:=AB_LOCAL
  4142. else
  4143. objsym.bind:=AB_GLOBAL;
  4144. if (SymFlags and WASM_SYM_TLS)<>0 then
  4145. begin
  4146. objsym.typ:=AT_TLS;
  4147. objsym.TlsGlobalSym:=TWasmObjSymbol(ObjData.CreateSymbol('GOT.mem.'+SymName));
  4148. objsym.TlsGlobalSym.TlsDataSym:=objsym;
  4149. objsym.TlsGlobalSym.bind:=objsym.bind;
  4150. objsym.TlsGlobalSym.typ:=AT_WASM_GLOBAL;
  4151. objsym.TlsGlobalSym.objsection:=ObjData.createsection('.wasm_globals.n_'+objsym.TlsGlobalSym.Name,1,[oso_Data,oso_load],true);
  4152. if objsym.TlsGlobalSym.objsection.Size=0 then
  4153. objsym.TlsGlobalSym.objsection.WriteZeros(1);
  4154. TWasmObjSection(objsym.TlsGlobalSym.objsection).MainFuncSymbol:=objsym.TlsGlobalSym;
  4155. objsym.TlsGlobalSym.offset:=0;
  4156. objsym.TlsGlobalSym.size:=1;
  4157. objsym.TlsGlobalSym.LinkingData.GlobalType:=wbt_i32;
  4158. objsym.TlsGlobalSym.LinkingData.GlobalIsMutable:=true;
  4159. end
  4160. else
  4161. objsym.typ:=AT_DATA;
  4162. objsym.objsection:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SymIndex]);
  4163. objsym.offset:=SymOffset;
  4164. objsym.size:=SymSize;
  4165. end;
  4166. SYMTAB_FPC_CUSTOM:
  4167. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  4168. begin
  4169. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4170. objsym.bind:=AB_EXTERNAL;
  4171. if (SymFlags and WASM_SYM_TLS)<>0 then
  4172. internalerror(2024080702);
  4173. objsym.typ:=AT_DATA;
  4174. objsym.objsection:=nil;
  4175. objsym.offset:=0;
  4176. objsym.size:=0;
  4177. end
  4178. else
  4179. begin
  4180. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4181. if (SymFlags and WASM_SYM_BINDING_LOCAL)<> 0 then
  4182. objsym.bind:=AB_LOCAL
  4183. else
  4184. objsym.bind:=AB_GLOBAL;
  4185. if (SymFlags and WASM_SYM_TLS)<>0 then
  4186. internalerror(2024080703);
  4187. objsym.typ:=AT_DATA;
  4188. objsym.objsection:=TObjSection(ObjData.ObjSectionList.Find(WasmCustomSectionName[SymCustomSectionType]));
  4189. objsym.offset:=SymOffset;
  4190. objsym.size:=SymSize;
  4191. end;
  4192. SYMTAB_FUNCTION:
  4193. begin
  4194. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  4195. begin
  4196. if not FuncTypes[SymIndex].IsImport then
  4197. begin
  4198. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_FUNCTION symbol, that is not an import');
  4199. exit;
  4200. end;
  4201. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  4202. begin
  4203. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4204. objsym.bind:=AB_EXTERNAL;
  4205. objsym.typ:=AT_FUNCTION;
  4206. objsym.objsection:=nil;
  4207. objsym.offset:=0;
  4208. objsym.size:=0;
  4209. objsym.LinkingData.ImportModule:=FuncTypes[SymIndex].ImportModName;
  4210. objsym.LinkingData.ImportName:=FuncTypes[SymIndex].ImportName;
  4211. end
  4212. else
  4213. begin
  4214. if FuncTypes[SymIndex].ImportModName = 'env' then
  4215. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportName))
  4216. else
  4217. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportModName + '.' + FuncTypes[SymIndex].ImportName));
  4218. objsym.bind:=AB_EXTERNAL;
  4219. objsym.typ:=AT_FUNCTION;
  4220. objsym.objsection:=nil;
  4221. objsym.offset:=0;
  4222. objsym.size:=0;
  4223. end;
  4224. end
  4225. else
  4226. begin
  4227. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4228. objsym.bind:=AB_GLOBAL;
  4229. objsym.typ:=AT_FUNCTION;
  4230. objsym.objsection:=TObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SymIndex-FuncTypeImportsCount]);
  4231. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  4232. TWasmObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SymIndex-FuncTypeImportsCount]).MainFuncSymbol:=objsym;
  4233. objsym.offset:=0;
  4234. objsym.size:=objsym.objsection.Size;
  4235. end;
  4236. objsym.LinkingData.FuncType:=TWasmFuncType.Create(FFuncTypes[FuncTypes[SymIndex].typidx]);
  4237. objsym.LinkingData.IsExported:=FuncTypes[SymIndex].IsExported;
  4238. objsym.LinkingData.ExportName:=FuncTypes[SymIndex].ExportName;
  4239. end;
  4240. SYMTAB_GLOBAL:
  4241. begin
  4242. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  4243. begin
  4244. if not GlobalTypes[SymIndex].IsImport then
  4245. begin
  4246. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_GLOBAL symbol, that is not an import');
  4247. exit;
  4248. end;
  4249. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  4250. begin
  4251. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4252. objsym.bind:=AB_EXTERNAL;
  4253. objsym.typ:=AT_WASM_GLOBAL;
  4254. objsym.objsection:=nil;
  4255. objsym.offset:=0;
  4256. objsym.size:=1;
  4257. objsym.LinkingData.ImportModule:=GlobalTypes[SymIndex].ImportModName;
  4258. objsym.LinkingData.ImportName:=GlobalTypes[SymIndex].ImportName;
  4259. end
  4260. else
  4261. begin
  4262. if GlobalTypes[SymIndex].ImportModName = 'env' then
  4263. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportName))
  4264. else
  4265. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportModName + '.' + GlobalTypes[SymIndex].ImportName));
  4266. objsym.bind:=AB_EXTERNAL;
  4267. objsym.typ:=AT_WASM_GLOBAL;
  4268. objsym.objsection:=nil;
  4269. objsym.offset:=0;
  4270. objsym.size:=1;
  4271. end;
  4272. end
  4273. else
  4274. begin
  4275. if GlobalTypes[SymIndex].IsImport then
  4276. begin
  4277. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_GLOBAL symbol, that is an import');
  4278. exit;
  4279. end;
  4280. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4281. objsym.bind:=AB_GLOBAL;
  4282. objsym.typ:=AT_WASM_GLOBAL;
  4283. objsym.objsection:=ObjData.createsection('.wasm_globals.n_'+SymName,1,[oso_Data,oso_load],true);
  4284. if objsym.objsection.Size=0 then
  4285. objsym.objsection.WriteZeros(1);
  4286. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  4287. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  4288. objsym.offset:=0;
  4289. objsym.size:=1;
  4290. objsym.LinkingData.GlobalInitializer:=GlobalTypes[SymIndex].GlobalInit;
  4291. end;
  4292. objsym.LinkingData.GlobalType:=GlobalTypes[SymIndex].valtype;
  4293. objsym.LinkingData.GlobalIsMutable:=GlobalTypes[SymIndex].IsMutable;
  4294. objsym.LinkingData.IsExported:=GlobalTypes[SymIndex].IsExported;
  4295. objsym.LinkingData.ExportName:=GlobalTypes[SymIndex].ExportName;
  4296. end;
  4297. SYMTAB_SECTION:
  4298. begin
  4299. for ds:=Low(DebugSectionIndex) to High(DebugSectionIndex) do
  4300. if DebugSectionIndex[ds]=TargetSection then
  4301. begin
  4302. ObjSec:=TWasmObjSection(ObjData.findsection(WasmCustomSectionName[ds]));
  4303. break;
  4304. end;
  4305. if ObjSec=nil then
  4306. begin
  4307. InputError('SYMTAB_SECTION entry points to an unsupported section');
  4308. exit;
  4309. end;
  4310. end;
  4311. SYMTAB_EVENT:
  4312. begin
  4313. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  4314. begin
  4315. if not TagTypes[SymIndex].IsImport then
  4316. begin
  4317. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_EVENT symbol, that is not an import');
  4318. exit;
  4319. end;
  4320. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  4321. begin
  4322. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4323. objsym.bind:=AB_EXTERNAL;
  4324. objsym.typ:=AT_WASM_EXCEPTION_TAG;
  4325. objsym.objsection:=nil;
  4326. objsym.offset:=0;
  4327. objsym.size:=1;
  4328. objsym.LinkingData.ImportModule:=TagTypes[SymIndex].ImportModName;
  4329. objsym.LinkingData.ImportName:=TagTypes[SymIndex].ImportName;
  4330. end
  4331. else
  4332. begin
  4333. if GlobalTypes[SymIndex].ImportModName = 'env' then
  4334. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportName))
  4335. else
  4336. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportModName + '.' + GlobalTypes[SymIndex].ImportName));
  4337. objsym.bind:=AB_EXTERNAL;
  4338. objsym.typ:=AT_WASM_EXCEPTION_TAG;
  4339. objsym.objsection:=nil;
  4340. objsym.offset:=0;
  4341. objsym.size:=1;
  4342. end;
  4343. end
  4344. else
  4345. begin
  4346. if TagTypes[SymIndex].IsImport then
  4347. begin
  4348. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_EVENT symbol, that is an import');
  4349. exit;
  4350. end;
  4351. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4352. if (symflags and WASM_SYM_BINDING_WEAK) <> 0 then
  4353. objsym.bind:=AB_WEAK_EXTERNAL
  4354. else if (symflags and WASM_SYM_BINDING_LOCAL) <> 0 then
  4355. objsym.bind:=AB_LOCAL
  4356. else
  4357. objsym.bind:=AB_GLOBAL;
  4358. objsym.typ:=AT_WASM_EXCEPTION_TAG;
  4359. objsym.objsection:=ObjData.createsection('.wasm_tags.n_'+SymName,1,[oso_Data,oso_load],true);
  4360. if objsym.objsection.Size=0 then
  4361. objsym.objsection.WriteZeros(1);
  4362. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  4363. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  4364. objsym.offset:=0;
  4365. objsym.size:=1;
  4366. end;
  4367. objsym.LinkingData.FuncType:=TWasmFuncType.Create(FFuncTypes[TagTypes[SymIndex].TagTypeIdx]);
  4368. objsym.LinkingData.IsExported:=TagTypes[SymIndex].IsExported;
  4369. objsym.LinkingData.ExportName:=TagTypes[SymIndex].ExportName;
  4370. end;
  4371. SYMTAB_TABLE:
  4372. {TODO};
  4373. end;
  4374. for j:=0 to high(RelocationTable) do
  4375. for i:=0 to high(RelocationTable[j]) do
  4376. with RelocationTable[j,i] do
  4377. begin
  4378. case j of
  4379. 0:
  4380. begin
  4381. SegI:=FindCodeSegment(RelocOffset);
  4382. if SegI=-1 then
  4383. begin
  4384. InputError('Relocation offset not found in code segment');
  4385. Exit;
  4386. end;
  4387. BaseSectionOffset:=CodeSegments[SegI].CodeSectionOffset;
  4388. ObjSec:=TObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SegI]);
  4389. end;
  4390. 1:
  4391. begin
  4392. SegI:=FindDataSegment(RelocOffset);
  4393. if SegI=-1 then
  4394. begin
  4395. InputError('Relocation offset not found in data segment');
  4396. Exit;
  4397. end;
  4398. BaseSectionOffset:=DataSegments[SegI].DataSectionOffset;
  4399. ObjSec:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SegI]);
  4400. end;
  4401. 2..2+(Ord(High(TWasmCustomDebugSectionType))-Ord(Low(TWasmCustomDebugSectionType))):
  4402. begin
  4403. BaseSectionOffset:=0;
  4404. ObjSec:=ObjData.findsection(WasmCustomSectionName[TWasmCustomSectionType((j-2)+Ord(Low(TWasmCustomDebugSectionType)))]);
  4405. end;
  4406. else
  4407. internalerror(2023122801);
  4408. end;
  4409. case RelocType of
  4410. R_WASM_FUNCTION_INDEX_LEB:
  4411. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_FUNCTION_INDEX_LEB));
  4412. R_WASM_TABLE_INDEX_SLEB:
  4413. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB));
  4414. R_WASM_TABLE_INDEX_I32:
  4415. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE));
  4416. R_WASM_MEMORY_ADDR_LEB:
  4417. begin
  4418. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_LEB);
  4419. ObjReloc.Addend:=RelocAddend;
  4420. ObjSec.ObjRelocations.Add(ObjReloc);
  4421. end;
  4422. R_WASM_MEMORY_ADDR_SLEB:
  4423. begin
  4424. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB);
  4425. ObjReloc.Addend:=RelocAddend;
  4426. ObjSec.ObjRelocations.Add(ObjReloc);
  4427. end;
  4428. R_WASM_MEMORY_ADDR_I32:
  4429. begin
  4430. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  4431. ObjReloc.Addend:=RelocAddend;
  4432. ObjSec.ObjRelocations.Add(ObjReloc);
  4433. end;
  4434. R_WASM_TYPE_INDEX_LEB:
  4435. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateFuncType(RelocOffset-BaseSectionOffset,FFuncTypes[RelocIndex]));
  4436. R_WASM_FUNCTION_OFFSET_I32:
  4437. begin
  4438. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  4439. ObjReloc.Addend:=RelocAddend;
  4440. ObjReloc.IsFunctionOffsetI32:=True;
  4441. ObjSec.ObjRelocations.Add(ObjReloc);
  4442. end;
  4443. R_WASM_SECTION_OFFSET_I32:
  4444. begin
  4445. ObjReloc:=TWasmObjRelocation.CreateSection(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSec,RELOC_ABSOLUTE);
  4446. ObjReloc.Addend:=RelocAddend;
  4447. ObjSec.ObjRelocations.Add(ObjReloc);
  4448. end;
  4449. R_WASM_GLOBAL_INDEX_LEB:
  4450. begin
  4451. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_GLOBAL_INDEX_LEB));
  4452. if Assigned(SymbolTable[RelocIndex].ObjSym.TlsGlobalSym) then
  4453. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym.TlsGlobalSym,RELOC_GLOBAL_INDEX_LEB));
  4454. end;
  4455. R_WASM_TAG_INDEX_LEB:
  4456. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_TAG_INDEX_LEB));
  4457. else
  4458. internalerror(2023122802);
  4459. end;
  4460. end;
  4461. Result:=True;
  4462. end;
  4463. {****************************************************************************
  4464. TWasmExeOutput
  4465. ****************************************************************************}
  4466. procedure TWasmExeOutput.WriteWasmSection(wsid: TWasmSectionID);
  4467. var
  4468. b: byte;
  4469. begin
  4470. b:=ord(wsid);
  4471. Writer.write(b,1);
  4472. WriteUleb(Writer,FWasmSections[wsid].size);
  4473. Writer.writearray(FWasmSections[wsid]);
  4474. end;
  4475. procedure TWasmExeOutput.WriteWasmSectionIfNotEmpty(wsid: TWasmSectionID);
  4476. begin
  4477. if FWasmSections[wsid].size>0 then
  4478. WriteWasmSection(wsid);
  4479. end;
  4480. procedure TWasmExeOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  4481. var
  4482. b: byte;
  4483. begin
  4484. b:=0;
  4485. Writer.write(b,1);
  4486. WriteUleb(Writer,FWasmCustomSections[wcst].size);
  4487. Writer.writearray(FWasmCustomSections[wcst]);
  4488. end;
  4489. function TWasmExeOutput.writeData: boolean;
  4490. procedure WriteImportSection;
  4491. var
  4492. imports_count,
  4493. memory_imports: SizeInt;
  4494. i: Integer;
  4495. begin
  4496. if ts_wasm_threads in current_settings.targetswitches then
  4497. memory_imports:=1
  4498. else
  4499. memory_imports:=0;
  4500. imports_count:=Length(FFunctionImports)+memory_imports;
  4501. WriteUleb(FWasmSections[wsiImport],imports_count);
  4502. if ts_wasm_threads in current_settings.targetswitches then
  4503. begin
  4504. WriteName(FWasmSections[wsiImport],'env');
  4505. WriteName(FWasmSections[wsiImport],'memory');
  4506. WriteByte(FWasmSections[wsiImport],$02); { mem }
  4507. WriteByte(FWasmSections[wsiImport],$03); { shared }
  4508. WriteUleb(FWasmSections[wsiImport],FMinMemoryPages);
  4509. WriteUleb(FWasmSections[wsiImport],Max(FMinMemoryPages,FMaxMemoryPages)); { max pages }
  4510. end;
  4511. for i:=0 to Length(FFunctionImports)-1 do
  4512. with FFunctionImports[i] do
  4513. begin
  4514. WriteName(FWasmSections[wsiImport],ModName);
  4515. WriteName(FWasmSections[wsiImport],Name);
  4516. WriteByte(FWasmSections[wsiImport],$00); { func }
  4517. WriteUleb(FWasmSections[wsiImport],TypeIdx);
  4518. end;
  4519. end;
  4520. procedure WriteCodeSegments;
  4521. var
  4522. i: Integer;
  4523. exesec: TExeSection;
  4524. objsec: TWasmObjSection;
  4525. begin
  4526. exesec:=FindExeSection('.text');
  4527. if not assigned(exesec) then
  4528. internalerror(2023123102);
  4529. if not (oso_Data in exesec.SecOptions) then
  4530. internalerror(2023123103);
  4531. WriteUleb(FWasmSections[wsiFunction],exesec.ObjSectionList.Count);
  4532. WriteUleb(FWasmSections[wsiCode],exesec.ObjSectionList.Count);
  4533. for i:=0 to exesec.ObjSectionList.Count-1 do
  4534. begin
  4535. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4536. if not (oso_data in objsec.secoptions) then
  4537. internalerror(2023123104);
  4538. if not assigned(objsec.data) then
  4539. internalerror(2023123105);
  4540. if objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex<>(i+Length(FFunctionImports)) then
  4541. internalerror(2024010101);
  4542. WriteUleb(FWasmSections[wsiFunction],objsec.MainFuncSymbol.LinkingData.ExeTypeIndex);
  4543. WriteUleb(FWasmSections[wsiCode],objsec.Data.size);
  4544. objsec.Data.seek(0);
  4545. CopyDynamicArray(objsec.Data,FWasmSections[wsiCode],objsec.Data.size);
  4546. end;
  4547. end;
  4548. procedure WriteDataSegments;
  4549. procedure WriteExeSection(exesec: TExeSection);
  4550. var
  4551. i: Integer;
  4552. objsec: TObjSection;
  4553. exesecdatapos: LongWord;
  4554. dpos, pad: QWord;
  4555. begin
  4556. if ts_wasm_threads in current_settings.targetswitches then
  4557. WriteByte(FWasmSections[wsiData],1) { mode passive }
  4558. else
  4559. begin
  4560. WriteByte(FWasmSections[wsiData],0); { mode active, memory 0, offset e }
  4561. WriteByte(FWasmSections[wsiData],$41); { i32.const }
  4562. WriteSleb(FWasmSections[wsiData],longint(exesec.MemPos));
  4563. WriteByte(FWasmSections[wsiData],$0B); { end }
  4564. end;
  4565. WriteUleb(FWasmSections[wsiData],exesec.Size);
  4566. exesecdatapos:=FWasmSections[wsiData].size;
  4567. for i:=0 to exesec.ObjSectionList.Count-1 do
  4568. begin
  4569. objsec:=TObjSection(exesec.ObjSectionList[i]);
  4570. if not (oso_data in objsec.secoptions) then
  4571. internalerror(2024010104);
  4572. if not assigned(objsec.data) then
  4573. internalerror(2024010105);
  4574. dpos:=objsec.MemPos-exesec.MemPos+exesecdatapos;
  4575. pad:=dpos-FWasmSections[wsiData].size;
  4576. { objsection must be within SecAlign bytes from the previous one }
  4577. if (dpos<FWasmSections[wsiData].Size) or
  4578. (pad>=max(objsec.SecAlign,1)) then
  4579. internalerror(2024010106);
  4580. writeZeros(FWasmSections[wsiData],pad);
  4581. objsec.data.seek(0);
  4582. CopyDynamicArray(objsec.data,FWasmSections[wsiData],objsec.data.size);
  4583. end;
  4584. if (FWasmSections[wsiData].size-exesecdatapos)<>exesec.Size then
  4585. internalerror(2024010107);
  4586. end;
  4587. var
  4588. DataCount: Integer;
  4589. DataSecName: string;
  4590. ExeSec: TExeSection;
  4591. begin
  4592. DataCount:=0;
  4593. for DataSecName in DataSections do
  4594. begin
  4595. ExeSec:=FindExeSection(DataSecName);
  4596. if Assigned(ExeSec) and (ExeSec.Size>0) then
  4597. Inc(DataCount);
  4598. end;
  4599. WriteUleb(FWasmSections[wsiDataCount],DataCount);
  4600. WriteUleb(FWasmSections[wsiData],DataCount);
  4601. for DataSecName in DataSections do
  4602. begin
  4603. ExeSec:=FindExeSection(DataSecName);
  4604. if Assigned(ExeSec) and (ExeSec.Size>0) then
  4605. WriteExeSection(ExeSec);
  4606. end;
  4607. end;
  4608. procedure WriteTableAndElemSections;
  4609. const
  4610. TableCount=1;
  4611. var
  4612. i: Integer;
  4613. begin
  4614. { Table section }
  4615. WriteUleb(FWasmSections[wsiTable],TableCount);
  4616. { table 0 }
  4617. { table type }
  4618. WriteByte(FWasmSections[wsiTable],encode_wasm_basic_type(wbt_funcref));
  4619. { table limits }
  4620. WriteByte(FWasmSections[wsiTable],$01); { has min & max }
  4621. WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { min }
  4622. WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { max }
  4623. { Elem section }
  4624. WriteUleb(FWasmSections[wsiElement],1); { 1 element segment }
  4625. { element segment 0 }
  4626. WriteByte(FWasmSections[wsiElement],0); { type funcref, init((ref.func y) end)*, mode active <table 0, offset e> }
  4627. { e:expr }
  4628. WriteByte(FWasmSections[wsiElement],$41); { i32.const }
  4629. WriteSleb(FWasmSections[wsiElement],1); { starting from 1 (table entry 0 is ref.null) }
  4630. WriteByte(FWasmSections[wsiElement],$0B); { end }
  4631. { y*:vec(funcidx) }
  4632. WriteUleb(FWasmSections[wsiElement],Length(FIndirectFunctionTable)-1);
  4633. for i:=1 to Length(FIndirectFunctionTable)-1 do
  4634. WriteUleb(FWasmSections[wsiElement],FIndirectFunctionTable[i].FuncIdx);
  4635. end;
  4636. procedure WriteGlobalSection;
  4637. var
  4638. exesec: TExeSection;
  4639. globals_count, i: Integer;
  4640. objsec: TWasmObjSection;
  4641. begin
  4642. exesec:=FindExeSection('.wasm_globals');
  4643. if not assigned(exesec) then
  4644. internalerror(2024010112);
  4645. globals_count:=exesec.ObjSectionList.Count;
  4646. if globals_count<>exesec.Size then
  4647. internalerror(2024010113);
  4648. WriteUleb(FWasmSections[wsiGlobal],globals_count);
  4649. for i:=0 to exesec.ObjSectionList.Count-1 do
  4650. begin
  4651. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4652. WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(objsec.MainFuncSymbol.LinkingData.GlobalType));
  4653. if objsec.MainFuncSymbol.LinkingData.GlobalIsMutable then
  4654. WriteByte(FWasmSections[wsiGlobal],1)
  4655. else
  4656. WriteByte(FWasmSections[wsiGlobal],0);
  4657. { initializer expr }
  4658. with objsec.MainFuncSymbol.LinkingData.GlobalInitializer do
  4659. case typ of
  4660. wbt_i32:
  4661. begin
  4662. WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
  4663. WriteSleb(FWasmSections[wsiGlobal],init_i32);
  4664. end;
  4665. wbt_i64:
  4666. begin
  4667. WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
  4668. WriteSleb(FWasmSections[wsiGlobal],init_i64);
  4669. end;
  4670. wbt_f32:
  4671. begin
  4672. WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
  4673. WriteF32LE(FWasmSections[wsiGlobal],init_f32);
  4674. end;
  4675. wbt_f64:
  4676. begin
  4677. WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
  4678. WriteF64LE(FWasmSections[wsiGlobal],init_f64);
  4679. end;
  4680. wbt_funcref,
  4681. wbt_externref:
  4682. begin
  4683. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null }
  4684. WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(typ));
  4685. end;
  4686. else
  4687. internalerror(2024010114);
  4688. end;
  4689. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  4690. end;
  4691. end;
  4692. procedure WriteTagSection;
  4693. var
  4694. exesec: TExeSection;
  4695. tags_count, i: Integer;
  4696. objsec: TWasmObjSection;
  4697. begin
  4698. exesec:=FindExeSection('.wasm_tags');
  4699. if not assigned(exesec) then
  4700. exit;
  4701. tags_count:=exesec.ObjSectionList.Count;
  4702. if tags_count<>exesec.Size then
  4703. internalerror(2024010702);
  4704. if tags_count=0 then
  4705. exit;
  4706. WriteUleb(FWasmSections[wsiTag],tags_count);
  4707. for i:=0 to exesec.ObjSectionList.Count-1 do
  4708. begin
  4709. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4710. WriteByte(FWasmSections[wsiTag],0);
  4711. WriteUleb(FWasmSections[wsiTag],objsec.MainFuncSymbol.LinkingData.ExeTypeIndex);
  4712. end;
  4713. end;
  4714. procedure WriteExportSection;
  4715. const
  4716. MemoryExportsCount=1;
  4717. var
  4718. FunctionExportsCount: Integer;
  4719. ExportsCount: Integer;
  4720. textsec: TExeSection;
  4721. i: Integer;
  4722. objsec: TWasmObjSection;
  4723. begin
  4724. FunctionExportsCount:=0;
  4725. textsec:=FindExeSection('.text');
  4726. if not assigned(textsec) then
  4727. internalerror(2024010115);
  4728. for i:=0 to textsec.ObjSectionList.Count-1 do
  4729. begin
  4730. objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
  4731. if objsec.MainFuncSymbol.LinkingData.IsExported then
  4732. Inc(FunctionExportsCount)
  4733. end;
  4734. ExportsCount:=MemoryExportsCount+FunctionExportsCount;
  4735. WriteUleb(FWasmSections[wsiExport],ExportsCount);
  4736. { export 0 }
  4737. WriteName(FWasmSections[wsiExport],'memory');
  4738. WriteByte(FWasmSections[wsiExport],$02); { mem }
  4739. WriteUleb(FWasmSections[wsiExport],0); { memidx = 0 }
  4740. for i:=0 to textsec.ObjSectionList.Count-1 do
  4741. begin
  4742. objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
  4743. if objsec.MainFuncSymbol.LinkingData.IsExported then
  4744. begin
  4745. WriteName(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExportName);
  4746. WriteByte(FWasmSections[wsiExport],$00); { func }
  4747. WriteUleb(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex); { funcidx }
  4748. end;
  4749. end;
  4750. end;
  4751. procedure MaybeWriteDebugSection(st: TWasmCustomDebugSectionType);
  4752. var
  4753. exesec: TExeSection;
  4754. begin
  4755. exesec:=FindExeSection(WasmCustomSectionName[st]);
  4756. if assigned(exesec) then
  4757. begin
  4758. WriteExeSectionToDynArray(exesec,FWasmCustomSections[st]);
  4759. WriteWasmCustomSection(st);
  4760. end;
  4761. end;
  4762. var
  4763. cust_sec: TWasmCustomSectionType;
  4764. begin
  4765. result:=false;
  4766. FMaxMemoryPages:=align(maxheapsize,WasmPageSize) div WasmPageSize;
  4767. { each custom sections starts with its name }
  4768. for cust_sec in TWasmCustomSectionType do
  4769. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  4770. SetStackPointer;
  4771. SetTlsSizeAlignAndBase;
  4772. SetThreadVarGlobalsInitValues;
  4773. GenerateCode_InitTls;
  4774. GenerateCode_InitSharedMemory;
  4775. FFuncTypes.WriteTo(FWasmSections[wsiType]);
  4776. WriteImportSection;
  4777. WriteCodeSegments;
  4778. WriteDataSegments;
  4779. WriteTableAndElemSections;
  4780. WriteGlobalSection;
  4781. WriteTagSection;
  4782. WriteExportSection;
  4783. if not (ts_wasm_threads in current_settings.targetswitches) then
  4784. begin
  4785. WriteUleb(FWasmSections[wsiMemory],1);
  4786. if FMaxMemoryPages>=FMinMemoryPages then
  4787. begin
  4788. WriteByte(FWasmSections[wsiMemory],1);
  4789. WriteUleb(FWasmSections[wsiMemory],FMinMemoryPages);
  4790. WriteUleb(FWasmSections[wsiMemory],FMaxMemoryPages);
  4791. end
  4792. else
  4793. begin
  4794. WriteByte(FWasmSections[wsiMemory],0);
  4795. WriteUleb(FWasmSections[wsiMemory],FMinMemoryPages);
  4796. end;
  4797. end;
  4798. if ts_wasm_threads in current_settings.targetswitches then
  4799. WriteUleb(FWasmSections[wsiStart],FInitSharedMemoryFunctionSym.LinkingData.ExeFunctionIndex);
  4800. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  4801. Writer.write(WasmVersion,SizeOf(WasmVersion));
  4802. WriteWasmSection(wsiType);
  4803. WriteWasmSection(wsiImport);
  4804. WriteWasmSection(wsiFunction);
  4805. WriteWasmSection(wsiTable);
  4806. if not (ts_wasm_threads in current_settings.targetswitches) then
  4807. WriteWasmSection(wsiMemory);
  4808. WriteWasmSectionIfNotEmpty(wsiTag);
  4809. WriteWasmSection(wsiGlobal);
  4810. WriteWasmSection(wsiExport);
  4811. if ts_wasm_threads in current_settings.targetswitches then
  4812. WriteWasmSection(wsiStart);
  4813. WriteWasmSection(wsiElement);
  4814. WriteWasmSection(wsiDataCount);
  4815. WriteWasmSection(wsiCode);
  4816. WriteWasmSection(wsiData);
  4817. MaybeWriteDebugSection(wcstDebugAbbrev);
  4818. MaybeWriteDebugSection(wcstDebugInfo);
  4819. MaybeWriteDebugSection(wcstDebugStr);
  4820. MaybeWriteDebugSection(wcstDebugLine);
  4821. MaybeWriteDebugSection(wcstDebugFrame);
  4822. MaybeWriteDebugSection(wcstDebugAranges);
  4823. MaybeWriteDebugSection(wcstDebugRanges);
  4824. result := true;
  4825. end;
  4826. procedure TWasmExeOutput.DoRelocationFixup(objsec: TObjSection);
  4827. procedure writeUInt32LE(v: uint32);
  4828. begin
  4829. {$ifdef FPC_BIG_ENDIAN}
  4830. v:=SwapEndian(v);
  4831. {$endif FPC_BIG_ENDIAN}
  4832. objsec.data.write(v,4);
  4833. end;
  4834. var
  4835. i: Integer;
  4836. objreloc: TWasmObjRelocation;
  4837. objsym: TWasmObjSymbol;
  4838. begin
  4839. for i:=0 to objsec.ObjRelocations.Count-1 do
  4840. begin
  4841. objreloc:=TWasmObjRelocation(objsec.ObjRelocations[i]);
  4842. if assigned(objreloc.symbol) then
  4843. begin
  4844. objsym:=TWasmObjSymbol(objreloc.symbol);
  4845. case objreloc.typ of
  4846. RELOC_FUNCTION_INDEX_LEB:
  4847. begin
  4848. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4849. internalerror(2024010103);
  4850. objsec.Data.seek(objreloc.DataOffset);
  4851. WriteUleb5(objsec.Data,objsym.LinkingData.ExeFunctionIndex);
  4852. end;
  4853. RELOC_ABSOLUTE:
  4854. begin
  4855. case objsym.typ of
  4856. AT_FUNCTION:
  4857. begin
  4858. if objreloc.IsFunctionOffsetI32 then
  4859. begin
  4860. { R_WASM_FUNCTION_OFFSET_I32 }
  4861. objsec.Data.seek(objreloc.DataOffset);
  4862. writeUInt32LE(UInt32(objsym.objsection.MemPos+objreloc.Addend));
  4863. end
  4864. else
  4865. begin
  4866. { R_WASM_TABLE_INDEX_I32 }
  4867. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4868. internalerror(2024010103);
  4869. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  4870. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  4871. objsec.Data.seek(objreloc.DataOffset);
  4872. writeUInt32LE(UInt32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  4873. end;
  4874. end;
  4875. AT_DATA:
  4876. begin
  4877. if objreloc.IsFunctionOffsetI32 then
  4878. internalerror(2024010602);
  4879. objsec.Data.seek(objreloc.DataOffset);
  4880. writeUInt32LE(UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4881. end;
  4882. else
  4883. internalerror(2024010108);
  4884. end;
  4885. end;
  4886. RELOC_MEMORY_ADDR_LEB:
  4887. begin
  4888. if objsym.typ<>AT_DATA then
  4889. internalerror(2024010109);
  4890. objsec.Data.seek(objreloc.DataOffset);
  4891. WriteUleb5(objsec.Data,UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4892. end;
  4893. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  4894. begin
  4895. case objsym.typ of
  4896. AT_FUNCTION:
  4897. begin
  4898. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4899. internalerror(2024010103);
  4900. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  4901. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  4902. objsec.Data.seek(objreloc.DataOffset);
  4903. WriteSleb5(objsec.Data,Int32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  4904. end;
  4905. AT_DATA:
  4906. begin
  4907. objsec.Data.seek(objreloc.DataOffset);
  4908. WriteSleb5(objsec.Data,Int32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  4909. end;
  4910. else
  4911. internalerror(2024010110);
  4912. end;
  4913. end;
  4914. RELOC_GLOBAL_INDEX_LEB:
  4915. if objsym.typ=AT_WASM_GLOBAL then
  4916. begin
  4917. objsec.Data.seek(objreloc.DataOffset);
  4918. WriteUleb5(objsec.Data,UInt32(objsym.offset+objsym.objsection.MemPos));
  4919. end
  4920. else if (ts_wasm_threads in current_settings.targetswitches) and
  4921. (objsym.typ=AT_TLS) then
  4922. begin
  4923. { Nothing to do here. A second RELOC_GLOBAL_INDEX_LEB
  4924. relocation, overlaid on top of this one, pointing to
  4925. an AT_WASM_GLOBAL should have already done the job. }
  4926. end
  4927. else
  4928. internalerror(2024010111);
  4929. RELOC_TAG_INDEX_LEB:
  4930. begin
  4931. if objsym.typ<>AT_WASM_EXCEPTION_TAG then
  4932. internalerror(2024010708);
  4933. objsec.Data.seek(objreloc.DataOffset);
  4934. WriteUleb5(objsec.Data,UInt32(objsym.offset+objsym.objsection.MemPos));
  4935. end;
  4936. else
  4937. internalerror(2024010109);
  4938. end;
  4939. end
  4940. else if assigned(objreloc.objsection) then
  4941. begin
  4942. if objreloc.typ<>RELOC_ABSOLUTE then
  4943. internalerror(2024010601);
  4944. objsec.Data.seek(objreloc.DataOffset);
  4945. writeUInt32LE(UInt32((objreloc.objsection.MemPos)+objreloc.Addend));
  4946. end
  4947. else if objreloc.typ=RELOC_TYPE_INDEX_LEB then
  4948. begin
  4949. objreloc.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(objreloc.FuncType);
  4950. objsec.Data.seek(objreloc.DataOffset);
  4951. WriteUleb5(objsec.Data,objreloc.ExeTypeIndex);
  4952. end
  4953. else
  4954. internalerror(2024010110);
  4955. end;
  4956. end;
  4957. constructor TWasmExeOutput.create;
  4958. var
  4959. i: TWasmSectionID;
  4960. j: TWasmCustomSectionType;
  4961. begin
  4962. inherited create;
  4963. CObjData:=TWasmObjData;
  4964. SectionMemAlign:=16;
  4965. MaxMemPos:=$FFFFFFFF;
  4966. FFuncTypes:=TWasmFuncTypeTable.Create;
  4967. for i in TWasmSectionID do
  4968. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  4969. for j in TWasmCustomSectionType do
  4970. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  4971. SetLength(FIndirectFunctionTable,1);
  4972. FIndirectFunctionTable[0].FuncIdx:=-1;
  4973. end;
  4974. destructor TWasmExeOutput.destroy;
  4975. var
  4976. i: TWasmSectionID;
  4977. j: TWasmCustomSectionType;
  4978. begin
  4979. for i in TWasmSectionID do
  4980. FWasmSections[i].Free;
  4981. for j in TWasmCustomSectionType do
  4982. FWasmCustomSections[j].Free;
  4983. FFuncTypes.Free;
  4984. inherited destroy;
  4985. end;
  4986. procedure TWasmExeOutput.GenerateLibraryImports(ImportLibraryList: TFPHashObjectList);
  4987. var
  4988. i, j: Integer;
  4989. ImportLibrary: TImportLibrary;
  4990. ImportSymbol: TImportSymbol;
  4991. exesym: TExeSymbol;
  4992. begin
  4993. { Here map import symbols to exe symbols and create necessary sections.
  4994. Actual import generation is done after unused sections (and symbols) are removed. }
  4995. FImports:=ImportLibraryList;
  4996. for i:=0 to ImportLibraryList.Count-1 do
  4997. begin
  4998. ImportLibrary:=TImportLibrary(ImportLibraryList[i]);
  4999. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  5000. begin
  5001. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  5002. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  5003. if assigned(exesym) and
  5004. (exesym.State<>symstate_defined) then
  5005. begin
  5006. ImportSymbol.CachedExeSymbol:=exesym;
  5007. exesym.State:=symstate_defined;
  5008. end;
  5009. end;
  5010. end;
  5011. PackUnresolvedExeSymbols('after module imports');
  5012. end;
  5013. procedure TWasmExeOutput.AfterUnusedSectionRemoval;
  5014. begin
  5015. PrepareImports;
  5016. PrepareFunctions;
  5017. PrepareTags;
  5018. end;
  5019. procedure TWasmExeOutput.MemPos_ExeSection(const aname: string);
  5020. const
  5021. DebugPrefix = '.debug_';
  5022. var
  5023. ExeSec: TExeSection;
  5024. i: Integer;
  5025. objsec: TObjSection;
  5026. firstdatasec: string;
  5027. begin
  5028. { WebAssembly is a Harvard architecture.
  5029. Data lives in a separate address space, so start addressing back from 0
  5030. (the LLVM leaves the first 1024 bytes in the data segment empty, so we
  5031. start at 1024). }
  5032. if ts_wasm_threads in current_settings.targetswitches then
  5033. firstdatasec:='.tbss'
  5034. else
  5035. firstdatasec:='.rodata';
  5036. if aname=firstdatasec then
  5037. begin
  5038. CurrMemPos:=1024;
  5039. inherited;
  5040. end
  5041. else if aname='.text' then
  5042. begin
  5043. CurrMemPos:=0;
  5044. ExeSec:=FindExeSection(aname);
  5045. if not assigned(ExeSec) then
  5046. exit;
  5047. exesec.MemPos:=CurrMemPos;
  5048. CurrMemPos:=CurrMemPos+UlebEncodingSize(exesec.ObjSectionList.Count);
  5049. { set position of object ObjSections }
  5050. for i:=0 to exesec.ObjSectionList.Count-1 do
  5051. begin
  5052. objsec:=TObjSection(exesec.ObjSectionList[i]);
  5053. CurrMemPos:=CurrMemPos+UlebEncodingSize(objsec.Size);
  5054. CurrMemPos:=objsec.setmempos(CurrMemPos);
  5055. end;
  5056. { calculate size of the section }
  5057. exesec.Size:=CurrMemPos-exesec.MemPos;
  5058. end
  5059. else if (aname='.wasm_globals') or (aname='.wasm_tags') or
  5060. (Copy(aname,1,Length(DebugPrefix))=DebugPrefix) then
  5061. begin
  5062. CurrMemPos:=0;
  5063. inherited;
  5064. end
  5065. else
  5066. inherited;
  5067. end;
  5068. procedure TWasmExeOutput.Load_Symbol(const aname: string);
  5069. begin
  5070. if aname=StackPointerSymStr then
  5071. begin
  5072. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  5073. FStackPointerSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  5074. FStackPointerSym.size:=1;
  5075. FStackPointerSym.ObjSection.WriteZeros(1);
  5076. TWasmObjSection(FStackPointerSym.ObjSection).MainFuncSymbol:=FStackPointerSym;
  5077. FStackPointerSym.LinkingData.GlobalType:=wbt_i32;
  5078. FStackPointerSym.LinkingData.GlobalIsMutable:=True;
  5079. FStackPointerSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  5080. FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=0;
  5081. end
  5082. else if (ts_wasm_threads in current_settings.targetswitches) and (aname='__tls_base') then
  5083. begin
  5084. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  5085. FTlsBaseSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  5086. FTlsBaseSym.size:=1;
  5087. FTlsBaseSym.ObjSection.WriteZeros(1);
  5088. TWasmObjSection(FTlsBaseSym.ObjSection).MainFuncSymbol:=FTlsBaseSym;
  5089. FTlsBaseSym.LinkingData.GlobalType:=wbt_i32;
  5090. FTlsBaseSym.LinkingData.GlobalIsMutable:=True;
  5091. FTlsBaseSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  5092. FTlsBaseSym.LinkingData.GlobalInitializer.init_i32:=0;
  5093. end
  5094. else if (ts_wasm_threads in current_settings.targetswitches) and (aname='__tls_size') then
  5095. begin
  5096. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  5097. FTlsSizeSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  5098. FTlsSizeSym.size:=1;
  5099. FTlsSizeSym.ObjSection.WriteZeros(1);
  5100. TWasmObjSection(FTlsSizeSym.ObjSection).MainFuncSymbol:=FTlsSizeSym;
  5101. FTlsSizeSym.LinkingData.GlobalType:=wbt_i32;
  5102. FTlsSizeSym.LinkingData.GlobalIsMutable:=False;
  5103. FTlsSizeSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  5104. FTlsSizeSym.LinkingData.GlobalInitializer.init_i32:=0;
  5105. end
  5106. else if (ts_wasm_threads in current_settings.targetswitches) and (aname='__tls_align') then
  5107. begin
  5108. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  5109. FTlsAlignSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  5110. FTlsAlignSym.size:=1;
  5111. FTlsAlignSym.ObjSection.WriteZeros(1);
  5112. TWasmObjSection(FTlsAlignSym.ObjSection).MainFuncSymbol:=FTlsAlignSym;
  5113. FTlsAlignSym.LinkingData.GlobalType:=wbt_i32;
  5114. FTlsAlignSym.LinkingData.GlobalIsMutable:=False;
  5115. FTlsAlignSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  5116. FTlsAlignSym.LinkingData.GlobalInitializer.init_i32:=0;
  5117. end
  5118. else if (ts_wasm_threads in current_settings.targetswitches) and (aname='__wasm_init_tls') then
  5119. begin
  5120. internalObjData.createsection('*'+aname,0,[]);
  5121. FInitTlsFunctionSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_FUNCTION));
  5122. TWasmObjSection(FInitTlsFunctionSym.ObjSection).MainFuncSymbol:=FInitTlsFunctionSym;
  5123. FInitTlsFunctionSym.LinkingData.FuncType:=TWasmFuncType.Create([wbt_i32],[]);
  5124. end
  5125. else if (ts_wasm_threads in current_settings.targetswitches) and (aname='__fpc_wasm_init_shared_memory') then
  5126. begin
  5127. internalObjData.createsection('*'+aname,0,[]);
  5128. FInitSharedMemoryFunctionSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_FUNCTION));
  5129. TWasmObjSection(FInitSharedMemoryFunctionSym.ObjSection).MainFuncSymbol:=FInitSharedMemoryFunctionSym;
  5130. FInitSharedMemoryFunctionSym.ObjSection.SecOptions:=FInitSharedMemoryFunctionSym.ObjSection.SecOptions+[oso_keep];
  5131. FInitSharedMemoryFunctionSym.LinkingData.FuncType:=TWasmFuncType.Create([],[]);
  5132. end
  5133. else
  5134. inherited;
  5135. end;
  5136. procedure TWasmExeOutput.PrepareImports;
  5137. function AddFunctionImport(const libname,symname:TCmdStr; functype: TWasmFuncType): Integer;
  5138. begin
  5139. SetLength(FFunctionImports,Length(FFunctionImports)+1);
  5140. Result:=High(FFunctionImports);
  5141. if assigned(exemap) then
  5142. exemap.Add(' Importing Function[' + tostr(Result) + '] ' + symname + functype.ToString);
  5143. with FFunctionImports[Result] do
  5144. begin
  5145. ModName:=libname;
  5146. Name:=symname;
  5147. TypeIdx:=FFuncTypes.AddOrGetFuncType(functype);
  5148. end;
  5149. end;
  5150. var
  5151. i, j: Integer;
  5152. ImportLibrary: TImportLibrary;
  5153. ImportSymbol: TImportSymbol;
  5154. exesym: TExeSymbol;
  5155. newdll: Boolean;
  5156. fsym: TWasmObjSymbol;
  5157. objdata: TObjData;
  5158. begin
  5159. for i:=0 to FImports.Count-1 do
  5160. begin
  5161. ImportLibrary:=TImportLibrary(FImports[i]);
  5162. newdll:=False;
  5163. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  5164. begin
  5165. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  5166. exesym:=ImportSymbol.CachedExeSymbol;
  5167. if assigned(exesym) and
  5168. exesym.Used then
  5169. begin
  5170. if (not newdll) and assigned(exemap) then
  5171. begin
  5172. exemap.Add('');
  5173. exemap.Add('Importing from module '+ImportLibrary.Name);
  5174. end;
  5175. newdll:=True;
  5176. TWasmObjSymbol(exesym.ObjSymbol).LinkingData.ExeFunctionIndex:=
  5177. AddFunctionImport(ImportLibrary.Name,ImportSymbol.Name,TWasmObjSymbol(exesym.ObjSymbol).LinkingData.FuncType);
  5178. end;
  5179. end;
  5180. end;
  5181. { set ExeFunctionIndex to the alias symbols as well }
  5182. for i:=0 to ObjDataList.Count-1 do
  5183. begin
  5184. objdata:=TObjData(ObjDataList[i]);
  5185. for j:=0 to objdata.ObjSymbolList.Count-1 do
  5186. begin
  5187. fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
  5188. if (fsym.LinkingData.ExeFunctionIndex=-1) and assigned(fsym.exesymbol) and (TWasmObjSymbol(fsym.exesymbol.ObjSymbol).LinkingData.ExeFunctionIndex<>-1) then
  5189. fsym.LinkingData.ExeFunctionIndex:=TWasmObjSymbol(fsym.exesymbol.ObjSymbol).LinkingData.ExeFunctionIndex;
  5190. end;
  5191. end;
  5192. end;
  5193. procedure TWasmExeOutput.PrepareFunctions;
  5194. var
  5195. i, j: Integer;
  5196. exesec: TExeSection;
  5197. objsec: TWasmObjSection;
  5198. fsym: TWasmObjSymbol;
  5199. objdata: TObjData;
  5200. begin
  5201. if assigned(exemap) then
  5202. begin
  5203. exemap.Add('');
  5204. exemap.Add('Functions, defined in this module:');
  5205. end;
  5206. exesec:=FindExeSection('.text');
  5207. if not assigned(exesec) then
  5208. internalerror(2023123106);
  5209. for i:=0 to exesec.ObjSectionList.Count-1 do
  5210. begin
  5211. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  5212. fsym:=objsec.MainFuncSymbol;
  5213. if not assigned(fsym) then
  5214. internalerror(2023123107);
  5215. if not assigned(fsym.LinkingData.FuncType) then
  5216. internalerror(2023123108);
  5217. if fsym.LinkingData.ExeFunctionIndex<>-1 then
  5218. internalerror(2023123109);
  5219. if fsym.LinkingData.ExeTypeIndex<>-1 then
  5220. internalerror(2023123109);
  5221. fsym.LinkingData.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(fsym.LinkingData.FuncType);
  5222. fsym.LinkingData.ExeFunctionIndex:=i+Length(FFunctionImports);
  5223. if assigned(exemap) then
  5224. begin
  5225. exemap.Add(' Function[' + tostr(fsym.LinkingData.ExeFunctionIndex) + '] ' + fsym.Name + fsym.LinkingData.FuncType.ToString);
  5226. end;
  5227. end;
  5228. { set ExeFunctionIndex to the alias symbols as well }
  5229. for i:=0 to ObjDataList.Count-1 do
  5230. begin
  5231. objdata:=TObjData(ObjDataList[i]);
  5232. for j:=0 to objdata.ObjSymbolList.Count-1 do
  5233. begin
  5234. fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
  5235. if assigned(fsym.objsection) and fsym.objsection.USed and (fsym.typ=AT_FUNCTION) and (fsym.LinkingData.ExeFunctionIndex=-1) then
  5236. begin
  5237. fsym.LinkingData.ExeFunctionIndex:=TWasmObjSection(fsym.objsection).MainFuncSymbol.LinkingData.ExeFunctionIndex;
  5238. if fsym.LinkingData.ExeFunctionIndex=-1 then
  5239. internalerror(2024010102);
  5240. end;
  5241. end;
  5242. end;
  5243. end;
  5244. procedure TWasmExeOutput.PrepareTags;
  5245. var
  5246. exesec: TExeSection;
  5247. i, j: Integer;
  5248. objsec: TWasmObjSection;
  5249. fsym: TWasmObjSymbol;
  5250. objdata: TObjData;
  5251. begin
  5252. exesec:=FindExeSection('.wasm_tags');
  5253. if not assigned(exesec) then
  5254. exit;
  5255. if assigned(exemap) then
  5256. begin
  5257. exemap.Add('');
  5258. exemap.Add('Tags, defined in this module:');
  5259. end;
  5260. for i:=0 to exesec.ObjSectionList.Count-1 do
  5261. begin
  5262. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  5263. fsym:=objsec.MainFuncSymbol;
  5264. if not assigned(fsym) then
  5265. internalerror(2024010703);
  5266. if not assigned(fsym.LinkingData.FuncType) then
  5267. internalerror(2024010704);
  5268. if fsym.LinkingData.ExeTagIndex<>-1 then
  5269. internalerror(2024010705);
  5270. if fsym.LinkingData.ExeTypeIndex<>-1 then
  5271. internalerror(2024010706);
  5272. fsym.LinkingData.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(fsym.LinkingData.FuncType);
  5273. fsym.LinkingData.ExeTagIndex:=i+Length(FTagImports);
  5274. if assigned(exemap) then
  5275. begin
  5276. exemap.Add(' Tag[' + tostr(fsym.LinkingData.ExeTagIndex) + '] ' + fsym.Name + fsym.LinkingData.FuncType.ToString);
  5277. end;
  5278. end;
  5279. { set ExeTagIndex to the alias symbols as well }
  5280. for i:=0 to ObjDataList.Count-1 do
  5281. begin
  5282. objdata:=TObjData(ObjDataList[i]);
  5283. for j:=0 to objdata.ObjSymbolList.Count-1 do
  5284. begin
  5285. fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
  5286. if assigned(fsym.objsection) and fsym.objsection.USed and (fsym.typ=AT_WASM_EXCEPTION_TAG) and (fsym.LinkingData.ExeTagIndex=-1) then
  5287. begin
  5288. fsym.LinkingData.ExeTagIndex:=TWasmObjSection(fsym.objsection).MainFuncSymbol.LinkingData.ExeTagIndex;
  5289. if fsym.LinkingData.ExeTagIndex=-1 then
  5290. internalerror(2024010707);
  5291. end;
  5292. end;
  5293. end;
  5294. end;
  5295. function TWasmExeOutput.AddOrGetIndirectFunctionTableIndex(FuncIdx: Integer): integer;
  5296. var
  5297. i: Integer;
  5298. begin
  5299. for i:=1 to length(FIndirectFunctionTable)-1 do
  5300. if FIndirectFunctionTable[i].FuncIdx=FuncIdx then
  5301. begin
  5302. Result:=i;
  5303. exit;
  5304. end;
  5305. SetLength(FIndirectFunctionTable,Length(FIndirectFunctionTable)+1);
  5306. Result:=High(FIndirectFunctionTable);
  5307. FIndirectFunctionTable[Result].FuncIdx:=FuncIdx;
  5308. end;
  5309. procedure TWasmExeOutput.SetStackPointer;
  5310. var
  5311. BssSec: TExeSection;
  5312. StackStart, InitialStackPtrAddr: QWord;
  5313. begin
  5314. BssSec:=FindExeSection('.bss');
  5315. InitialStackPtrAddr := (BssSec.MemPos+BssSec.Size+stacksize+15) and (not 15);
  5316. FMinMemoryPages := Max(
  5317. QWord(Align(QWord(InitialStackPtrAddr),QWord(WasmPageSize)) div WasmPageSize),
  5318. QWord(Align(QWord(heapsize),QWord(WasmPageSize)) div WasmPageSize));
  5319. FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=Int32(InitialStackPtrAddr);
  5320. end;
  5321. procedure TWasmExeOutput.SetTlsSizeAlignAndBase;
  5322. var
  5323. TBssSec: TExeSection;
  5324. begin
  5325. if not (ts_wasm_threads in current_settings.targetswitches) then
  5326. exit;
  5327. TBssSec:=FindExeSection('.tbss');
  5328. FTlsSizeSym.LinkingData.GlobalInitializer.init_i32:=Int32(TBssSec.Size);
  5329. FTlsAlignSym.LinkingData.GlobalInitializer.init_i32:=Int32(TBssSec.SecAlign);
  5330. FTlsBaseSym.LinkingData.GlobalInitializer.init_i32:=Int32(TBssSec.MemPos);
  5331. end;
  5332. procedure TWasmExeOutput.SetThreadVarGlobalsInitValues;
  5333. var
  5334. exesec: TExeSection;
  5335. i: Integer;
  5336. objsec: TWasmObjSection;
  5337. objsym: TWasmObjSymbol;
  5338. begin
  5339. if not (ts_wasm_threads in current_settings.targetswitches) then
  5340. exit;
  5341. exesec:=FindExeSection('.wasm_globals');
  5342. if not assigned(exesec) then
  5343. internalerror(2024010112);
  5344. for i:=0 to exesec.ObjSectionList.Count-1 do
  5345. begin
  5346. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  5347. objsym:=objsec.MainFuncSymbol;
  5348. if Assigned(objsym.TlsDataSym) then
  5349. begin
  5350. objsym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  5351. objsym.LinkingData.GlobalInitializer.init_i32:=objsym.TlsDataSym.offset+objsym.TlsDataSym.objsection.MemPos;
  5352. end;
  5353. end;
  5354. end;
  5355. procedure TWasmExeOutput.GenerateCode_InitTls;
  5356. var
  5357. Sec: TObjSection;
  5358. globalexesec: TExeSection;
  5359. i: Integer;
  5360. globalobjsec: TWasmObjSection;
  5361. globalobjsym: TWasmObjSymbol;
  5362. OffsetInTls: QWord;
  5363. begin
  5364. if not (ts_wasm_threads in current_settings.targetswitches) then
  5365. exit;
  5366. globalexesec:=FindExeSection('.wasm_globals');
  5367. if not assigned(globalexesec) then
  5368. internalerror(2024010112);
  5369. Sec:=FInitTlsFunctionSym.objsection;
  5370. Sec.SecOptions:=Sec.SecOptions+[oso_Data];
  5371. { locals }
  5372. Sec.writeUInt8($00);
  5373. { local.get 0 }
  5374. Sec.writeUInt16BE($2000);
  5375. { global.set $__tls_base }
  5376. Sec.writeUInt8($24);
  5377. WriteUleb(sec,FTlsBaseSym.offset+FTlsBaseSym.objsection.MemPos);
  5378. for i:=0 to globalexesec.ObjSectionList.Count-1 do
  5379. begin
  5380. globalobjsec:=TWasmObjSection(globalexesec.ObjSectionList[i]);
  5381. globalobjsym:=globalobjsec.MainFuncSymbol;
  5382. if Assigned(globalobjsym.TlsDataSym) then
  5383. begin
  5384. OffsetInTls:=globalobjsym.TlsDataSym.offset+globalobjsym.TlsDataSym.objsection.MemPos-globalobjsym.TlsDataSym.objsection.ExeSection.MemPos;
  5385. { local.get 0 }
  5386. Sec.writeUInt16BE($2000);
  5387. if OffsetInTls<>0 then
  5388. begin
  5389. { i32.const $OffsetInTls }
  5390. Sec.writeUInt8($41);
  5391. WriteSleb(Sec,Int32(OffsetInTls));
  5392. { i32.add }
  5393. Sec.writeUInt8($6A);
  5394. end;
  5395. { global.set y }
  5396. Sec.writeUInt8($24);
  5397. WriteUleb(sec,globalobjsym.offset+globalobjsym.objsection.MemPos);
  5398. end;
  5399. end;
  5400. Sec.writeUInt8($0B); { end }
  5401. end;
  5402. procedure TWasmExeOutput.GenerateCode_InitSharedMemory;
  5403. const
  5404. InitFlagOfs=256;
  5405. var
  5406. Sec: TObjSection;
  5407. DataSecName: string;
  5408. DataSecIdx: Integer;
  5409. ExeSec: TExeSection;
  5410. begin
  5411. if not (ts_wasm_threads in current_settings.targetswitches) then
  5412. exit;
  5413. Sec:=FInitSharedMemoryFunctionSym.objsection;
  5414. Sec.SecOptions:=Sec.SecOptions+[oso_Data];
  5415. { locals }
  5416. Sec.writeUInt8($00);
  5417. { block }
  5418. Sec.writeUInt16BE($0240);
  5419. { block }
  5420. Sec.writeUInt16BE($0240);
  5421. { block }
  5422. Sec.writeUInt16BE($0240);
  5423. { i32.const $InitFlag }
  5424. Sec.writeUInt8($41);
  5425. WriteSleb(sec,InitFlagOfs);
  5426. { i32.const 0 }
  5427. Sec.writeUInt16BE($4100);
  5428. { i32.const 1 }
  5429. Sec.writeUInt16BE($4101);
  5430. { i32.atomic.rmw.cmpxchg 2 0 }
  5431. Sec.writeUInt32BE($fe480200);
  5432. { br_table 0 1 2 }
  5433. Sec.writebytes(#$0e#$02#$00#$01#$02);
  5434. { end }
  5435. Sec.writeUInt8($0B);
  5436. DataSecIdx:=-1;
  5437. for DataSecName in DataSections do
  5438. begin
  5439. ExeSec:=FindExeSection(DataSecName);
  5440. if Assigned(ExeSec) and (ExeSec.Size>0) then
  5441. begin
  5442. Inc(DataSecIdx);
  5443. { i32.const $memPos }
  5444. Sec.writeUInt8($41);
  5445. WriteSleb(sec,Int32(ExeSec.MemPos));
  5446. { i32.const 0 }
  5447. Sec.writeUInt16BE($4100);
  5448. { i32.const size }
  5449. Sec.writeUInt8($41);
  5450. WriteSleb(sec,Int32(ExeSec.Size));
  5451. { memory.init $DataSecIdx 0 }
  5452. Sec.writeUInt16BE($fc08);
  5453. WriteUleb(sec,DataSecIdx);
  5454. Sec.writeUInt8(0);
  5455. end;
  5456. end;
  5457. { i32.const $InitFlag }
  5458. Sec.writeUInt8($41);
  5459. WriteSleb(sec,InitFlagOfs);
  5460. { i32.const 2 }
  5461. Sec.writeUInt16BE($4102);
  5462. { i32.atomic.store 2 0 }
  5463. Sec.writeUInt32BE($fe170200);
  5464. { i32.const $InitFlag }
  5465. Sec.writeUInt8($41);
  5466. WriteSleb(sec,InitFlagOfs);
  5467. { i32.const 4294967295 }
  5468. Sec.writeUInt16BE($417f);
  5469. { memory.atomic.notify 2 0 }
  5470. Sec.writeUInt32BE($fe000200);
  5471. { drop }
  5472. Sec.writeUInt8($1A);
  5473. { end }
  5474. Sec.writeUInt8($0B);
  5475. { i32.const $InitFlag }
  5476. Sec.writeUInt8($41);
  5477. WriteSleb(sec,InitFlagOfs);
  5478. { i32.const 1 }
  5479. Sec.writeUInt16BE($4101);
  5480. { i64.const -1 }
  5481. Sec.writeUInt16BE($427f);
  5482. { memory.atomic.wait32 2 0 }
  5483. Sec.writeUInt32BE($fe010200);
  5484. { drop }
  5485. Sec.writeUInt8($1A);
  5486. { end }
  5487. Sec.writeUInt8($0B);
  5488. DataSecIdx:=-1;
  5489. for DataSecName in DataSections do
  5490. begin
  5491. ExeSec:=FindExeSection(DataSecName);
  5492. if Assigned(ExeSec) and (ExeSec.Size>0) then
  5493. begin
  5494. Inc(DataSecIdx);
  5495. { data.drop $DataSecIdx }
  5496. Sec.writeUInt16BE($fc09);
  5497. WriteUleb(sec,DataSecIdx);
  5498. end;
  5499. end;
  5500. { end }
  5501. Sec.writeUInt8($0B);
  5502. end;
  5503. procedure TWasmExeOutput.WriteExeSectionToDynArray(exesec: TExeSection; dynarr: tdynamicarray);
  5504. var
  5505. exesecdatapos: LongWord;
  5506. i: Integer;
  5507. objsec: TObjSection;
  5508. dpos, pad: QWord;
  5509. begin
  5510. exesecdatapos:=dynarr.size;
  5511. for i:=0 to exesec.ObjSectionList.Count-1 do
  5512. begin
  5513. objsec:=TObjSection(exesec.ObjSectionList[i]);
  5514. if not (oso_data in objsec.secoptions) then
  5515. internalerror(2024010104);
  5516. if not assigned(objsec.data) then
  5517. internalerror(2024010105);
  5518. dpos:=objsec.MemPos-exesec.MemPos+exesecdatapos;
  5519. pad:=dpos-dynarr.size;
  5520. { objsection must be within SecAlign bytes from the previous one }
  5521. if (dpos<dynarr.Size) or
  5522. (pad>=max(objsec.SecAlign,1)) then
  5523. internalerror(2024010106);
  5524. writeZeros(dynarr,pad);
  5525. objsec.data.seek(0);
  5526. CopyDynamicArray(objsec.data,dynarr,objsec.data.size);
  5527. end;
  5528. if (dynarr.size-exesecdatapos)<>exesec.Size then
  5529. internalerror(2024010107);
  5530. end;
  5531. {****************************************************************************
  5532. TWasmAssembler
  5533. ****************************************************************************}
  5534. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  5535. begin
  5536. inherited;
  5537. CObjOutput:=TWasmObjOutput;
  5538. end;
  5539. {*****************************************************************************
  5540. Initialize
  5541. *****************************************************************************}
  5542. {$ifdef wasm32}
  5543. const
  5544. as_wasm32_wasm_info : tasminfo =
  5545. (
  5546. id : as_wasm32_wasm;
  5547. idtxt : 'WASM';
  5548. asmbin : '';
  5549. asmcmd : '';
  5550. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  5551. flags : [af_outputbinary,af_smartlink_sections];
  5552. labelprefix : '..@';
  5553. labelmaxlen : -1;
  5554. comment : '; ';
  5555. dollarsign: '$';
  5556. );
  5557. {$endif wasm32}
  5558. initialization
  5559. {$ifdef wasm32}
  5560. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  5561. {$endif wasm32}
  5562. end.