ogwasm.pas 225 KB

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