ogomf.pas 185 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872
  1. {
  2. Copyright (c) 2015 by Nikolay Nikolov
  3. Contains the binary Relocatable Object Module Format (OMF) reader and writer
  4. This is the object format used on the i8086-msdos platform.
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16. ****************************************************************************
  17. }
  18. unit ogomf;
  19. {$i fpcdefs.inc}
  20. {$PackSet 1}
  21. interface
  22. uses
  23. { common }
  24. cclasses,globtype,
  25. { target }
  26. systems,
  27. { assembler }
  28. cpuinfo,cpubase,aasmbase,assemble,link,
  29. { OMF definitions }
  30. omfbase,
  31. { output }
  32. ogbase,
  33. owbase;
  34. type
  35. { TOmfObjSymbol }
  36. TOmfObjSymbol = class(TObjSymbol)
  37. public
  38. { string representation for the linker map file }
  39. function AddressStr(AImageBase: qword): string;override;
  40. end;
  41. { TOmfRelocation }
  42. TOmfRelocation = class(TObjRelocation)
  43. private
  44. FFrameGroup: string;
  45. FOmfFixup: TOmfSubRecord_FIXUP;
  46. public
  47. destructor Destroy; override;
  48. procedure BuildOmfFixup;
  49. property FrameGroup: string read FFrameGroup write FFrameGroup;
  50. property OmfFixup: TOmfSubRecord_FIXUP read FOmfFixup;
  51. end;
  52. TMZExeUnifiedLogicalSegment=class;
  53. { TOmfObjSection }
  54. TOmfObjSection = class(TObjSection)
  55. private
  56. FClassName: string;
  57. FOverlayName: string;
  58. FFirstSym: TObjSymbol;
  59. FCombination: TOmfSegmentCombination;
  60. FUse: TOmfSegmentUse;
  61. FPrimaryGroup: TObjSectionGroup;
  62. FSortOrder: Integer;
  63. FMZExeUnifiedLogicalSegment: TMZExeUnifiedLogicalSegment;
  64. FLinNumEntries: TOmfSubRecord_LINNUM_MsLink_LineNumberList;
  65. function GetOmfAlignment: TOmfSegmentAlignment;
  66. protected
  67. function GetAltName: string; override;
  68. public
  69. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);override;
  70. destructor destroy;override;
  71. function MemPosStr(AImageBase: qword): string;override;
  72. property ClassName: string read FClassName;
  73. property OverlayName: string read FOverlayName;
  74. property OmfAlignment: TOmfSegmentAlignment read GetOmfAlignment;
  75. property Combination: TOmfSegmentCombination read FCombination;
  76. property Use: TOmfSegmentUse read FUse;
  77. property PrimaryGroup: TObjSectionGroup read FPrimaryGroup;
  78. property SortOrder: Integer read FSortOrder write FSortOrder;
  79. property MZExeUnifiedLogicalSegment: TMZExeUnifiedLogicalSegment read FMZExeUnifiedLogicalSegment write FMZExeUnifiedLogicalSegment;
  80. property LinNumEntries: TOmfSubRecord_LINNUM_MsLink_LineNumberList read FLinNumEntries;
  81. end;
  82. { TOmfObjExportedSymbol }
  83. TOmfObjExportedSymbol = class(TFPHashObject)
  84. private
  85. FExportByOrdinal: Boolean;
  86. FResidentName: Boolean;
  87. FNoData: Boolean;
  88. FParmCount: Integer;
  89. FExportedName: string;
  90. FInternalName: string;
  91. FExportOrdinal: Word;
  92. public
  93. property ExportByOrdinal: Boolean read FExportByOrdinal write FExportByOrdinal;
  94. property ResidentName: Boolean read FResidentName write FResidentName;
  95. property NoData: Boolean read FNoData write FNoData;
  96. property ParmCount: Integer read FParmCount write FParmCount;
  97. property ExportedName: string read FExportedName write FExportedName;
  98. property InternalName: string read FInternalName write FInternalName;
  99. property ExportOrdinal: Word read FExportOrdinal write FExportOrdinal;
  100. end;
  101. { TOmfObjData }
  102. TOmfObjData = class(TObjData)
  103. private
  104. FMainSource: TPathStr;
  105. FImportLibraryList:TFPHashObjectList;
  106. FExportedSymbolList:TFPHashObjectList;
  107. class function CodeSectionName(const aname:string): string;
  108. public
  109. constructor create(const n:string);override;
  110. destructor destroy;override;
  111. function sectiontype2align(atype:TAsmSectiontype):longint;override;
  112. class function sectiontype2class(atype:TAsmSectiontype):string;
  113. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  114. function createsection(atype:TAsmSectionType;const aname:string='';aorder:TAsmSectionOrder=secorder_default):TObjSection;override;
  115. function reffardatasection:TObjSection;
  116. procedure writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  117. procedure AddImportSymbol(const libname,symname,symmangledname:TCmdStr;OrdNr: longint;isvar:boolean);
  118. procedure AddExportSymbol(aExportByOrdinal,aResidentName,aNoData:Boolean;aParmCount:Integer;aExportedName,aInternalName:string;aExportOrdinal:Word);
  119. property MainSource: TPathStr read FMainSource;
  120. property ImportLibraryList:TFPHashObjectList read FImportLibraryList;
  121. property ExportedSymbolList:TFPHashObjectList read FExportedSymbolList;
  122. end;
  123. { TOmfObjOutput }
  124. TOmfObjOutput = class(tObjOutput)
  125. private
  126. FLNames: TOmfOrderedNameCollection;
  127. FSegments: TFPHashObjectList;
  128. FGroups: TFPHashObjectList;
  129. procedure AddSegment(const name,segclass,ovlname: string;
  130. Alignment: TOmfSegmentAlignment; Combination: TOmfSegmentCombination;
  131. Use: TOmfSegmentUse; Size: TObjSectionOfs);
  132. procedure AddGroup(group: TObjSectionGroup);
  133. procedure WriteSections(Data:TObjData);
  134. procedure WriteSectionContentAndFixups(sec: TObjSection);
  135. procedure WriteLinNumRecords(sec: TOmfObjSection);
  136. procedure section_count_sections(p:TObject;arg:pointer);
  137. procedure group_count_groups(p:TObject;arg:pointer);
  138. procedure WritePUBDEFs(Data: TObjData);
  139. procedure WriteEXTDEFs(Data: TObjData);
  140. property LNames: TOmfOrderedNameCollection read FLNames;
  141. property Segments: TFPHashObjectList read FSegments;
  142. property Groups: TFPHashObjectList read FGroups;
  143. protected
  144. function writeData(Data:TObjData):boolean;override;
  145. public
  146. constructor create(AWriter:TObjectWriter);override;
  147. destructor Destroy;override;
  148. procedure WriteDllImport(const dllname,afuncname,mangledname:string;ordnr:longint;isvar:boolean);
  149. end;
  150. { TOmfObjInput }
  151. TOmfObjInput = class(TObjInput)
  152. private
  153. FLNames: TOmfOrderedNameCollection;
  154. FExtDefs: TFPHashObjectList;
  155. FPubDefs: TFPHashObjectList;
  156. FFixupThreads: TOmfThreads;
  157. FRawRecord: TOmfRawRecord;
  158. FCOMENTRecord: TOmfRecord_COMENT;
  159. FCaseSensitiveSegments: Boolean;
  160. FCaseSensitiveSymbols: Boolean;
  161. function PeekNextRecordType: Byte;
  162. function ReadLNames(RawRec: TOmfRawRecord): Boolean;
  163. function ReadSegDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  164. function ReadGrpDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  165. function ReadExtDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  166. function ReadPubDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  167. function ReadModEnd(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  168. function ReadLeOrLiDataAndFixups(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  169. function ReadImpDef(Rec: TOmfRecord_COMENT; objdata:TObjData): Boolean;
  170. function ReadExpDef(Rec: TOmfRecord_COMENT; objdata:TObjData): Boolean;
  171. function ImportOmfFixup(objdata: TObjData; objsec: TOmfObjSection; Fixup: TOmfSubRecord_FIXUP): Boolean;
  172. property LNames: TOmfOrderedNameCollection read FLNames;
  173. property ExtDefs: TFPHashObjectList read FExtDefs;
  174. property PubDefs: TFPHashObjectList read FPubDefs;
  175. { Specifies whether we're case sensitive in regards to segment, class, overlay and group names. }
  176. property CaseSensitiveSegments: Boolean read FCaseSensitiveSegments write FCaseSensitiveSegments;
  177. { Specifies whether symbol names (in EXTDEF and PUBDEF records) are case sensitive. }
  178. property CaseSensitiveSymbols: Boolean read FCaseSensitiveSymbols write FCaseSensitiveSymbols;
  179. public
  180. constructor create;override;
  181. destructor destroy;override;
  182. class function CanReadObjData(AReader:TObjectreader):boolean;override;
  183. function ReadObjData(AReader:TObjectreader;out objdata:TObjData):boolean;override;
  184. end;
  185. { TMZExeRelocation }
  186. TMZExeRelocation = record
  187. offset: Word;
  188. segment: Word;
  189. end;
  190. TMZExeRelocations = array of TMZExeRelocation;
  191. TMZExeExtraHeaderData = array of Byte;
  192. { TMZExeHeader }
  193. TMZExeHeader = class
  194. private
  195. FChecksum: Word;
  196. FExtraHeaderData: TMZExeExtraHeaderData;
  197. FHeaderSizeAlignment: Integer;
  198. FInitialCS: Word;
  199. FInitialIP: Word;
  200. FInitialSP: Word;
  201. FInitialSS: Word;
  202. FLoadableImageSize: DWord;
  203. FMaxExtraParagraphs: Word;
  204. FMinExtraParagraphs: Word;
  205. FOverlayNumber: Word;
  206. FRelocations: TMZExeRelocations;
  207. procedure SetHeaderSizeAlignment(AValue: Integer);
  208. public
  209. constructor Create;
  210. procedure WriteTo(aWriter: TObjectWriter);
  211. procedure AddRelocation(aSegment,aOffset: Word);
  212. property HeaderSizeAlignment: Integer read FHeaderSizeAlignment write SetHeaderSizeAlignment; {default=16, must be multiple of 16}
  213. property Relocations: TMZExeRelocations read FRelocations write FRelocations;
  214. property ExtraHeaderData: TMZExeExtraHeaderData read FExtraHeaderData write FExtraHeaderData;
  215. property LoadableImageSize: DWord read FLoadableImageSize write FLoadableImageSize;
  216. property MinExtraParagraphs: Word read FMinExtraParagraphs write FMinExtraParagraphs;
  217. property MaxExtraParagraphs: Word read FMaxExtraParagraphs write FMaxExtraParagraphs;
  218. property InitialSS: Word read FInitialSS write FInitialSS;
  219. property InitialSP: Word read FInitialSP write FInitialSP;
  220. property Checksum: Word read FChecksum write FChecksum;
  221. property InitialIP: Word read FInitialIP write FInitialIP;
  222. property InitialCS: Word read FInitialCS write FInitialCS;
  223. property OverlayNumber: Word read FOverlayNumber write FOverlayNumber;
  224. end;
  225. { TMZExeSection }
  226. TMZExeSection=class(TExeSection)
  227. public
  228. procedure AddObjSection(objsec:TObjSection;ignoreprops:boolean=false);override;
  229. end;
  230. { TMZExeUnifiedLogicalSegment }
  231. TMZExeUnifiedLogicalSegment=class(TFPHashObject)
  232. private
  233. FObjSectionList: TFPObjectList;
  234. FSegName: TSymStr;
  235. FSegClass: TSymStr;
  236. FPrimaryGroup: string;
  237. public
  238. Size,
  239. MemPos,
  240. MemBasePos: qword;
  241. IsStack: Boolean;
  242. constructor create(HashObjectList:TFPHashObjectList;const s:TSymStr);
  243. destructor destroy;override;
  244. procedure AddObjSection(ObjSec: TOmfObjSection);
  245. procedure CalcMemPos;
  246. function MemPosStr:string;
  247. property ObjSectionList: TFPObjectList read FObjSectionList;
  248. property SegName: TSymStr read FSegName;
  249. property SegClass: TSymStr read FSegClass;
  250. property PrimaryGroup: string read FPrimaryGroup write FPrimaryGroup;
  251. end;
  252. { TMZExeUnifiedLogicalGroup }
  253. TMZExeUnifiedLogicalGroup=class(TFPHashObject)
  254. private
  255. FSegmentList: TFPHashObjectList;
  256. public
  257. Size,
  258. MemPos: qword;
  259. constructor create(HashObjectList:TFPHashObjectList;const s:TSymStr);
  260. destructor destroy;override;
  261. procedure CalcMemPos;
  262. function MemPosStr:string;
  263. procedure AddSegment(UniSeg: TMZExeUnifiedLogicalSegment);
  264. property SegmentList: TFPHashObjectList read FSegmentList;
  265. end;
  266. { TMZExeOutput }
  267. TMZExeOutput = class(TExeOutput)
  268. private
  269. FMZFlatContentSection: TMZExeSection;
  270. FExeUnifiedLogicalSegments: TFPHashObjectList;
  271. FExeUnifiedLogicalGroups: TFPHashObjectList;
  272. FDwarfUnifiedLogicalSegments: TFPHashObjectList;
  273. FHeader: TMZExeHeader;
  274. function GetMZFlatContentSection: TMZExeSection;
  275. procedure CalcDwarfUnifiedLogicalSegmentsForSection(const SecName: TSymStr);
  276. procedure CalcExeUnifiedLogicalSegments;
  277. procedure CalcExeGroups;
  278. procedure CalcSegments_MemBasePos;
  279. procedure WriteMap_SegmentsAndGroups;
  280. procedure WriteMap_HeaderData;
  281. function FindStackSegment: TMZExeUnifiedLogicalSegment;
  282. procedure FillLoadableImageSize;
  283. procedure FillMinExtraParagraphs;
  284. procedure FillMaxExtraParagraphs;
  285. procedure FillStartAddress;
  286. procedure FillStackAddress;
  287. procedure FillHeaderData;
  288. function writeExe:boolean;
  289. function writeCom:boolean;
  290. function writeDebugElf:boolean;
  291. property ExeUnifiedLogicalSegments: TFPHashObjectList read FExeUnifiedLogicalSegments;
  292. property ExeUnifiedLogicalGroups: TFPHashObjectList read FExeUnifiedLogicalGroups;
  293. property DwarfUnifiedLogicalSegments: TFPHashObjectList read FExeUnifiedLogicalSegments;
  294. property Header: TMZExeHeader read FHeader;
  295. protected
  296. procedure DoRelocationFixup(objsec:TObjSection);override;
  297. procedure Order_ObjSectionList(ObjSectionList : TFPObjectList;const aPattern:string);override;
  298. function writeData:boolean;override;
  299. public
  300. constructor create;override;
  301. destructor destroy;override;
  302. procedure Load_Symbol(const aname:string);override;
  303. procedure MemPos_EndExeSection;override;
  304. procedure MemPos_ExeSection(const aname:string);override;
  305. property MZFlatContentSection: TMZExeSection read GetMZFlatContentSection;
  306. end;
  307. const
  308. NewExeHeaderSize = $40;
  309. NewExeSegmentHeaderSize = 8;
  310. NewExeRelocationRecordSize = 8;
  311. type
  312. TNewExeHeaderFlag = (
  313. nehfSingleData, { bit 0 }
  314. nehfMultipleData, { bit 1 }
  315. { 'Global initialization' according to BP7's TDUMP.EXE }
  316. nehfRealMode, { bit 2 }
  317. nehfProtectedModeOnly, { bit 3 }
  318. { 'EMSDIRECT' according to OpenWatcom's wdump }
  319. { '8086 instructions' according to Ralf Brown's Interrupt List }
  320. nehfReserved4, { bit 4 }
  321. { 'EMSBANK' according to OpenWatcom's wdump }
  322. { '80286 instructions' according to Ralf Brown's Interrupt List }
  323. nehfReserved5, { bit 5 }
  324. { 'EMSGLOBAL' according to OpenWatcom's wdump }
  325. { '80386 instructions' according to Ralf Brown's Interrupt List }
  326. nehfReserved6, { bit 6 }
  327. nehfNeedsFPU, { bit 7 }
  328. { Not compatible with windowing API }
  329. nehfNotWindowAPICompatible, { bit 8 }
  330. { Compatible with windowing API }
  331. { (NotWindowAPICompatible + WindowAPICompatible) = Uses windowing API }
  332. nehfWindowAPICompatible, { bit 9 }
  333. { Family Application (OS/2) according to Ralf Brown's Interrupt List }
  334. nehfReserved10, { bit 10 }
  335. nehfSelfLoading, { bit 11 }
  336. nehfReserved12, { bit 12 }
  337. nehfLinkErrors, { bit 13 }
  338. nehfReserved14, { bit 14 }
  339. nehfIsDLL); { bit 15 }
  340. TNewExeHeaderFlags = set of TNewExeHeaderFlag;
  341. TNewExeAdditionalHeaderFlag = (
  342. neahfLFNSupport, { bit 0 }
  343. neahfWindows2ProtectedMode, { bit 1 }
  344. neahfWindows2ProportionalFonts, { bit 2 }
  345. neahfHasGangloadArea); { bit 3 }
  346. TNewExeAdditionalHeaderFlags = set of TNewExeAdditionalHeaderFlag;
  347. TNewExeTargetOS = (
  348. netoUnknown = $00,
  349. netoOS2 = $01,
  350. netoWindows = $02,
  351. netoMultitaskingMsDos4 = $03,
  352. netoWindows386 = $04,
  353. netoBorlandOperatingSystemServices = $05,
  354. netoPharLap286DosExtenderOS2 = $81,
  355. netoPharLap286DosExtenderWindows = $82);
  356. TNewExeSegmentFlag = (
  357. nesfData, { bit 0 }
  358. nesfLoaderAllocatedMemory, { bit 1 }
  359. nesfLoaded, { bit 2 }
  360. nesfReserved3, { bit 3 }
  361. nesfMovable, { bit 4 }
  362. nesfShareable, { bit 5 }
  363. nesfPreload, { bit 6 }
  364. nesfExecuteOnlyCodeOrReadOnlyData, { bit 7 }
  365. nesfHasRelocationData, { bit 8 }
  366. nesfReserved9, { bit 9 }
  367. nesfReserved10, { bit 10 }
  368. nesfReserved11, { bit 11 }
  369. nesfDiscardable, { bit 12 }
  370. nesfReserved13, { bit 13 }
  371. nesfReserved14, { bit 14 }
  372. nesfReserved15); { bit 15 }
  373. TNewExeSegmentFlags = set of TNewExeSegmentFlag;
  374. TNewExeMsDosStub = array of byte;
  375. { TNewExeHeader }
  376. TNewExeHeader = class
  377. private
  378. FMsDosStub: TNewExeMsDosStub;
  379. FLinkerVersion: Byte;
  380. FLinkerRevision: Byte;
  381. FEntryTableOffset: Word;
  382. FEntryTableLength: Word;
  383. FReserved: LongWord;
  384. FFlags: TNewExeHeaderFlags;
  385. FAutoDataSegmentNumber: Word;
  386. FInitialLocalHeapSize: Word;
  387. FInitialStackSize: Word;
  388. FInitialIP: Word;
  389. FInitialCS: Word;
  390. FInitialSP: Word;
  391. FInitialSS: Word;
  392. FSegmentTableEntriesCount: Word;
  393. FModuleReferenceTableEntriesCount: Word;
  394. FNonresidentNameTableLength: Word;
  395. FSegmentTableStart: Word;
  396. FResourceTableStart: Word;
  397. FResidentNameTableStart: Word;
  398. FModuleReferenceTableStart: Word;
  399. FImportedNameTableStart: Word;
  400. FNonresidentNameTableStart: LongWord;
  401. FMovableEntryPointsCount: Word;
  402. FLogicalSectorAlignmentShiftCount: Word;
  403. FResourceSegmentsCount: Word;
  404. FTargetOS: TNewExeTargetOS;
  405. FAdditionalFlags: TNewExeAdditionalHeaderFlags;
  406. FGangLoadAreaStart: Word;
  407. FGangLoadAreaLength: Word;
  408. FReserved2: Word;
  409. FExpectedWindowsVersion: Word;
  410. public
  411. constructor Create;
  412. procedure WriteTo(aWriter: TObjectWriter);
  413. property MsDosStub: TNewExeMsDosStub read FMsDosStub write FMsDosStub;
  414. property LinkerVersion: Byte read FLinkerVersion write FLinkerVersion;
  415. property LinkerRevision: Byte read FLinkerRevision write FLinkerRevision;
  416. property EntryTableOffset: Word read FEntryTableOffset write FEntryTableOffset;
  417. property EntryTableLength: Word read FEntryTableLength write FEntryTableLength;
  418. property Reserved: LongWord read FReserved write FReserved;
  419. property Flags: TNewExeHeaderFlags read FFlags write FFlags;
  420. property AutoDataSegmentNumber: Word read FAutoDataSegmentNumber write FAutoDataSegmentNumber;
  421. property InitialLocalHeapSize: Word read FInitialLocalHeapSize write FInitialLocalHeapSize;
  422. property InitialStackSize: Word read FInitialStackSize write FInitialStackSize;
  423. property InitialIP: Word read FInitialIP write FInitialIP;
  424. property InitialCS: Word read FInitialCS write FInitialCS;
  425. property InitialSP: Word read FInitialSP write FInitialSP;
  426. property InitialSS: Word read FInitialSS write FInitialSS;
  427. property SegmentTableEntriesCount: Word read FSegmentTableEntriesCount write FSegmentTableEntriesCount;
  428. property ModuleReferenceTableEntriesCount: Word read FModuleReferenceTableEntriesCount write FModuleReferenceTableEntriesCount;
  429. property NonresidentNameTableLength: Word read FNonresidentNameTableLength write FNonresidentNameTableLength;
  430. property SegmentTableStart: Word read FSegmentTableStart write FSegmentTableStart;
  431. property ResourceTableStart: Word read FResourceTableStart write FResourceTableStart;
  432. property ResidentNameTableStart: Word read FResidentNameTableStart write FResidentNameTableStart;
  433. property ModuleReferenceTableStart: Word read FModuleReferenceTableStart write FModuleReferenceTableStart;
  434. property ImportedNameTableStart: Word read FImportedNameTableStart write FImportedNameTableStart;
  435. property NonresidentNameTableStart: LongWord read FNonresidentNameTableStart write FNonresidentNameTableStart;
  436. property MovableEntryPointsCount: Word read FMovableEntryPointsCount write FMovableEntryPointsCount;
  437. property LogicalSectorAlignmentShiftCount: Word read FLogicalSectorAlignmentShiftCount write FLogicalSectorAlignmentShiftCount;
  438. property ResourceSegmentsCount: Word read FResourceSegmentsCount write FResourceSegmentsCount;
  439. property TargetOS: TNewExeTargetOS read FTargetOS write FTargetOS;
  440. property AdditionalFlags: TNewExeAdditionalHeaderFlags read FAdditionalFlags write FAdditionalFlags;
  441. property GangLoadAreaStart: Word read FGangLoadAreaStart write FGangLoadAreaStart;
  442. property GangLoadAreaLength: Word read FGangLoadAreaLength write FGangLoadAreaLength;
  443. property Reserved2: Word read FReserved2 write FReserved2;
  444. property ExpectedWindowsVersion: Word read FExpectedWindowsVersion write FExpectedWindowsVersion;
  445. end;
  446. { TNewExeResourceTable }
  447. TNewExeResourceTable = class
  448. private
  449. FResourceDataAlignmentShiftCount: Word;
  450. function GetSize: QWord;
  451. public
  452. constructor Create;
  453. procedure WriteTo(aWriter: TObjectWriter);
  454. property ResourceDataAlignmentShiftCount: Word read FResourceDataAlignmentShiftCount write FResourceDataAlignmentShiftCount;
  455. property Size: QWord read GetSize;
  456. end;
  457. { TNewExeExportNameTableEntry }
  458. TNewExeExportNameTableEntry = class(TFPHashObject)
  459. private
  460. FOrdinalNr: Word;
  461. public
  462. constructor Create(HashObjectList:TFPHashObjectList;const s:TSymStr;OrdNr:Word);
  463. property OrdinalNr: Word read FOrdinalNr write FOrdinalNr;
  464. end;
  465. { TNewExeExportNameTable }
  466. TNewExeExportNameTable = class(TFPHashObjectList)
  467. private
  468. function GetSize: QWord;
  469. public
  470. procedure WriteTo(aWriter: TObjectWriter);
  471. property Size: QWord read GetSize;
  472. end;
  473. TNewExeImportedNameTable = class;
  474. { TNewExeModuleReferenceTableEntry }
  475. TNewExeModuleReferenceTableEntry = class(TFPHashObject)
  476. end;
  477. { TNewExeModuleReferenceTable }
  478. TNewExeModuleReferenceTable = class(TFPHashObjectList)
  479. private
  480. function GetSize: QWord;
  481. public
  482. procedure AddModuleReference(const dllname:TSymStr);
  483. procedure WriteTo(aWriter: TObjectWriter;imptbl:TNewExeImportedNameTable);
  484. property Size: QWord read GetSize;
  485. end;
  486. { TNewExeImportedNameTableEntry }
  487. TNewExeImportedNameTableEntry = class(TFPHashObject)
  488. private
  489. FTableOffset: Word;
  490. public
  491. property TableOffset: Word read FTableOffset write FTableOffset;
  492. end;
  493. { TNewExeImportedNameTable }
  494. TNewExeImportedNameTable = class(TFPHashObjectList)
  495. private
  496. function GetSize: QWord;
  497. public
  498. procedure AddImportedName(const name:TSymStr);
  499. procedure CalcTableOffsets;
  500. procedure WriteTo(aWriter: TObjectWriter);
  501. property Size: QWord read GetSize;
  502. end;
  503. TNewExeEntryPointFlag = (
  504. neepfMovableSegment,
  505. neepfExported,
  506. neepfSingleData
  507. );
  508. TNewExeEntryPointFlags = set of TNewExeEntryPointFlag;
  509. { TNewExeEntryPoint }
  510. TNewExeEntryPoint = class
  511. private
  512. FFlags: TNewExeEntryPointFlags;
  513. FSegment: Byte;
  514. FOffset: Word;
  515. FParmCount: Integer;
  516. function GetFlagsByte: Byte;
  517. public
  518. property Flags: TNewExeEntryPointFlags read FFlags write FFlags;
  519. property Segment: Byte read FSegment write FSegment;
  520. property Offset: Word read FOffset write FOffset;
  521. property ParmCount: Integer read FParmCount write FParmCount;
  522. property FlagsByte: Byte read GetFlagsByte;
  523. end;
  524. { TNewExeEntryTable }
  525. TNewExeEntryTable = class
  526. strict private
  527. FItems: array of TNewExeEntryPoint;
  528. function GetCount: Word;
  529. function GetItems(i: Integer): TNewExeEntryPoint;
  530. function GetSize: QWord;
  531. procedure SetItems(i: Integer; AValue: TNewExeEntryPoint);
  532. function CanBeInSameBundle(i,j:Integer):Boolean;
  533. function BundleSize(StartingElement:Integer): Byte;
  534. public
  535. destructor Destroy;override;
  536. procedure WriteTo(aWriter: TObjectWriter);
  537. procedure GrowTo(aNewCount: Word);
  538. property Size: QWord read GetSize;
  539. property Count: Word read GetCount;
  540. property Items[i: Integer]: TNewExeEntryPoint read GetItems write SetItems;default;
  541. end;
  542. { These are fake "meta sections" used by the linker script. The actual
  543. NewExe sections are segments, limited to 64kb, which means there can be
  544. multiple code segments, etc. These are created manually as object
  545. sections are added. If they fit the current segment, without exceeding
  546. 64kb, they are added to the current segment, otherwise a new segment is
  547. created. The current "meta sections" tells what kind of new segment to
  548. create (e.g. nemsCode means that a new code segment will be created). }
  549. TNewExeMetaSection = (
  550. nemsNone,
  551. nemsCode,
  552. nemsData);
  553. const
  554. NewExeMetaSection2String: array [TNewExeMetaSection] of string[9] = (
  555. '',
  556. 'Code',
  557. 'Data');
  558. type
  559. TNewExeRelocationAddressType = (
  560. neratLoByte = 0, { low 8 bits of 16-bit offset }
  561. neratSelector = 2, { 16-bit selector }
  562. neratFarPointer = 3, { 16-bit selector:16-bit offset }
  563. neratOffset = 5, { 16-bit offset }
  564. neratFarPointer48 = 11, { 16-bit selector:32-bit offset }
  565. neratOffset32 = 13); { 32-bit offset }
  566. TNewExeRelocationType = (
  567. nertInternalRef,
  568. nertImportName,
  569. nertImportOrdinal,
  570. nertOsFixup);
  571. TNewExeOsFixupType = (
  572. neoftFIARQQ_FJARQQ = 1,
  573. neoftFISRQQ_FJSRQQ = 2,
  574. neoftFICRQQ_FJCRQQ = 3,
  575. neoftFIERQQ = 4,
  576. neoftFIDRQQ = 5,
  577. neoftFIWRQQ = 6);
  578. TNewExeInternalRefSegmentType = (
  579. neirstFixed,
  580. neirstMovable);
  581. { TNewExeRelocation }
  582. TNewExeRelocation=class
  583. private
  584. FAddressType: TNewExeRelocationAddressType;
  585. FRelocationType: TNewExeRelocationType;
  586. FIsAdditive: Boolean;
  587. FInternalRefSegmentType: TNewExeInternalRefSegmentType;
  588. FOsFixupType: TNewExeOsFixupType;
  589. FOffset: Word;
  590. FImportModuleIndex: Word;
  591. FImportNameIndex: Word;
  592. FImportOrdinal: Word;
  593. FInternalRefFixedSegmentNumber: Byte;
  594. FInternalRefFixedSegmentOffset: Word;
  595. FInternalRefMovableSegmentEntryTableIndex: Word;
  596. public
  597. procedure EncodeTo(dest: PByte);
  598. property AddressType: TNewExeRelocationAddressType read FAddressType write FAddressType;
  599. property RelocationType: TNewExeRelocationType read FRelocationType write FRelocationType;
  600. property IsAdditive: Boolean read FIsAdditive write FIsAdditive;
  601. property InternalRefSegmentType: TNewExeInternalRefSegmentType read FInternalRefSegmentType write FInternalRefSegmentType;
  602. property OsFixupType: TNewExeOsFixupType read FOsFixupType write FOsFixupType;
  603. property Offset: Word read FOffset write FOffset;
  604. property ImportModuleIndex: Word read FImportModuleIndex write FImportModuleIndex;
  605. property ImportNameIndex: Word read FImportNameIndex write FImportNameIndex;
  606. property ImportOrdinal: Word read FImportOrdinal write FImportOrdinal;
  607. property InternalRefFixedSegmentNumber: Byte read FInternalRefFixedSegmentNumber write FInternalRefFixedSegmentNumber;
  608. property InternalRefFixedSegmentOffset: Word read FInternalRefFixedSegmentOffset write FInternalRefFixedSegmentOffset;
  609. property InternalRefMovableSegmentEntryTableIndex: Word read FInternalRefMovableSegmentEntryTableIndex write FInternalRefMovableSegmentEntryTableIndex;
  610. end;
  611. { TNewExeRelocationList }
  612. TNewExeRelocationList=class
  613. private
  614. FInternalList: TFPObjectList;
  615. function GetCount: Integer;
  616. function GetItem(Index: Integer): TNewExeRelocation;
  617. function GetSize: QWord;
  618. procedure SetCount(AValue: Integer);
  619. procedure SetItem(Index: Integer; AValue: TNewExeRelocation);
  620. public
  621. constructor Create;
  622. destructor Destroy; override;
  623. procedure WriteTo(aWriter: TObjectWriter);
  624. function Add(AObject: TNewExeRelocation): Integer;
  625. property Size: QWord read GetSize;
  626. property Count: Integer read GetCount write SetCount;
  627. property Items[Index: Integer]: TNewExeRelocation read GetItem write SetItem; default;
  628. end;
  629. { TNewExeSection }
  630. TNewExeSection=class(TExeSection)
  631. private
  632. FEarlySize: QWord;
  633. FStackSize: QWord;
  634. FExeMetaSec: TNewExeMetaSection;
  635. FMemBasePos: Word;
  636. FDataPosSectors: Word;
  637. FNewExeSegmentFlags: TNewExeSegmentFlags;
  638. FSizeInFile: QWord;
  639. FRelocations: TNewExeRelocationList;
  640. function GetMinAllocSize: QWord;
  641. function GetNewExeSegmentFlags: TNewExeSegmentFlags;
  642. public
  643. constructor create(AList:TFPHashObjectList;const AName:string);override;
  644. destructor destroy;override;
  645. procedure WriteHeaderTo(aWriter: TObjectWriter);
  646. function MemPosStr(AImageBase: qword): string;override;
  647. procedure AddObjSection(objsec:TObjSection;ignoreprops:boolean=false);override;
  648. function CanAddObjSection(objsec:TObjSection;ExeSectionLimit:QWord):boolean;
  649. property EarlySize: QWord read FEarlySize write FEarlySize;
  650. property StackSize: QWord read FStackSize write FStackSize;
  651. property ExeMetaSec: TNewExeMetaSection read FExeMetaSec write FExeMetaSec;
  652. property MemBasePos: Word read FMemBasePos write FMemBasePos;
  653. property DataPosSectors: Word read FDataPosSectors write FDataPosSectors;
  654. property MinAllocSize: QWord read GetMinAllocSize;
  655. property SizeInFile: QWord read FSizeInFile write FSizeInFile;
  656. property NewExeSegmentFlags: TNewExeSegmentFlags read GetNewExeSegmentFlags write FNewExeSegmentFlags;
  657. property Relocations: TNewExeRelocationList read FRelocations;
  658. end;
  659. { TNewExeOutput }
  660. TNewExeOutput = class(TExeOutput)
  661. private
  662. FHeader: TNewExeHeader;
  663. FImports: TFPHashObjectList;
  664. FCurrExeMetaSec: TNewExeMetaSection;
  665. FResourceTable: TNewExeResourceTable;
  666. FResidentNameTable: TNewExeExportNameTable;
  667. FNonresidentNameTable: TNewExeExportNameTable;
  668. FModuleReferenceTable: TNewExeModuleReferenceTable;
  669. FImportedNameTable: TNewExeImportedNameTable;
  670. FEntryTable: TNewExeEntryTable;
  671. procedure AddImportSymbol(const libname,symname,symmangledname:TCmdStr;OrdNr: longint;isvar:boolean);
  672. procedure AddImportLibrariesExtractedFromObjectModules;
  673. procedure AddNewExeSection;
  674. function WriteNewExe:boolean;
  675. procedure FillImportedNameAndModuleReferenceTable;
  676. function GetHighestExportSymbolOrdinal: Word;
  677. procedure AssignOrdinalsToAllExportSymbols;
  678. procedure AddEntryPointsForAllExportSymbols;
  679. procedure AddExportedNames;
  680. property Header: TNewExeHeader read FHeader;
  681. property CurrExeMetaSec: TNewExeMetaSection read FCurrExeMetaSec write FCurrExeMetaSec;
  682. property ResourceTable: TNewExeResourceTable read FResourceTable;
  683. property ResidentNameTable: TNewExeExportNameTable read FResidentNameTable;
  684. property NonresidentNameTable: TNewExeExportNameTable read FNonresidentNameTable;
  685. property ModuleReferenceTable: TNewExeModuleReferenceTable read FModuleReferenceTable;
  686. property ImportedNameTable: TNewExeImportedNameTable read FImportedNameTable;
  687. property EntryTable: TNewExeEntryTable read FEntryTable;
  688. protected
  689. procedure DoRelocationFixup(objsec:TObjSection);override;
  690. procedure Order_ObjSectionList(ObjSectionList : TFPObjectList;const aPattern:string);override;
  691. public
  692. constructor create;override;
  693. destructor destroy;override;
  694. procedure Order_ExeSection(const aname:string);override;
  695. procedure Order_EndExeSection;override;
  696. procedure Order_ObjSection(const aname:string);override;
  697. procedure MemPos_Start;override;
  698. procedure GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);override;
  699. function writeData:boolean;override;
  700. end;
  701. TOmfAssembler = class(tinternalassembler)
  702. constructor create(info: pasminfo; smart:boolean);override;
  703. end;
  704. function StripDllExt(const DllName:TSymStr):TSymStr;
  705. function MaybeAddDllExt(const DllName:TSymStr):TSymStr;
  706. implementation
  707. uses
  708. SysUtils,
  709. cutils,verbose,globals,fpchash,
  710. fmodule,aasmtai,aasmdata,
  711. ogmap,owomflib,elfbase,
  712. version
  713. ;
  714. const win16stub : array[0..255] of byte=(
  715. $4d,$5a,$00,$01,$01,$00,$00,$00,$08,$00,$10,$00,$ff,$ff,$08,$00,
  716. $00,$01,$00,$00,$00,$00,$00,$00,$40,$00,$00,$00,$00,$00,$00,$00,
  717. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  718. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$00,$00,
  719. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  720. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  721. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  722. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  723. $ba,$10,$00,$0e,$1f,$b4,$09,$cd,$21,$b8,$01,$4c,$cd,$21,$90,$90,
  724. $54,$68,$69,$73,$20,$70,$72,$6f,$67,$72,$61,$6d,$20,$72,$65,$71,
  725. $75,$69,$72,$65,$73,$20,$4d,$69,$63,$72,$6f,$73,$6f,$66,$74,$20,
  726. $57,$69,$6e,$64,$6f,$77,$73,$2e,$0d,$0a,$24,$20,$20,$20,$20,$20,
  727. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,
  728. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,
  729. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,
  730. $20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20);
  731. {****************************************************************************
  732. TTISTrailer
  733. ****************************************************************************}
  734. const
  735. TIS_TRAILER_SIGNATURE: array[1..4] of char='TIS'#0;
  736. TIS_TRAILER_VENDOR_TIS=0;
  737. TIS_TRAILER_TYPE_TIS_DWARF=0;
  738. type
  739. TTISTrailer=record
  740. tis_signature: array[1..4] of char;
  741. tis_vendor,
  742. tis_type,
  743. tis_size: LongWord;
  744. end;
  745. procedure MayBeSwapTISTrailer(var h: TTISTrailer);
  746. begin
  747. if source_info.endian<>target_info.endian then
  748. with h do
  749. begin
  750. tis_vendor:=swapendian(tis_vendor);
  751. tis_type:=swapendian(tis_type);
  752. tis_size:=swapendian(tis_size);
  753. end;
  754. end;
  755. {****************************************************************************
  756. TOmfObjSymbol
  757. ****************************************************************************}
  758. function TOmfObjSymbol.AddressStr(AImageBase: qword): string;
  759. var
  760. base: qword;
  761. begin
  762. if assigned(objsection.ExeSection) and (objsection.ExeSection is TNewExeSection) then
  763. Result:=HexStr(TNewExeSection(objsection.ExeSection).MemBasePos,4)+':'+HexStr(address,4)
  764. else
  765. begin
  766. if assigned(TOmfObjSection(objsection).MZExeUnifiedLogicalSegment) then
  767. base:=TOmfObjSection(objsection).MZExeUnifiedLogicalSegment.MemBasePos
  768. else
  769. base:=(address shr 4) shl 4;
  770. Result:=HexStr(base shr 4,4)+':'+HexStr(address-base,4);
  771. end;
  772. end;
  773. {****************************************************************************
  774. TOmfRelocation
  775. ****************************************************************************}
  776. destructor TOmfRelocation.Destroy;
  777. begin
  778. FOmfFixup.Free;
  779. inherited Destroy;
  780. end;
  781. procedure TOmfRelocation.BuildOmfFixup;
  782. begin
  783. FreeAndNil(FOmfFixup);
  784. FOmfFixup:=TOmfSubRecord_FIXUP.Create;
  785. if ObjSection<>nil then
  786. begin
  787. FOmfFixup.LocationOffset:=DataOffset;
  788. if typ in [RELOC_ABSOLUTE16,RELOC_RELATIVE16] then
  789. FOmfFixup.LocationType:=fltOffset
  790. else if typ in [RELOC_ABSOLUTE32,RELOC_RELATIVE32] then
  791. FOmfFixup.LocationType:=fltOffset32
  792. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  793. FOmfFixup.LocationType:=fltBase
  794. else
  795. internalerror(2015041501);
  796. FOmfFixup.FrameDeterminedByThread:=False;
  797. FOmfFixup.TargetDeterminedByThread:=False;
  798. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG] then
  799. FOmfFixup.Mode:=fmSegmentRelative
  800. else if typ in [RELOC_RELATIVE16,RELOC_RELATIVE32,RELOC_SEGREL] then
  801. FOmfFixup.Mode:=fmSelfRelative
  802. else
  803. internalerror(2015041408);
  804. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_RELATIVE16,RELOC_RELATIVE32] then
  805. begin
  806. FOmfFixup.TargetMethod:=ftmSegmentIndexNoDisp;
  807. FOmfFixup.TargetDatum:=ObjSection.Index;
  808. if TOmfObjSection(ObjSection).PrimaryGroup<>nil then
  809. begin
  810. FOmfFixup.FrameMethod:=ffmGroupIndex;
  811. FOmfFixup.FrameDatum:=TOmfObjSection(ObjSection).PrimaryGroup.index;
  812. end
  813. else
  814. FOmfFixup.FrameMethod:=ffmTarget;
  815. end
  816. else
  817. begin
  818. FOmfFixup.FrameMethod:=ffmTarget;
  819. if TOmfObjSection(ObjSection).PrimaryGroup<>nil then
  820. begin
  821. FOmfFixup.TargetMethod:=ftmGroupIndexNoDisp;
  822. FOmfFixup.TargetDatum:=TOmfObjSection(ObjSection).PrimaryGroup.index;
  823. end
  824. else
  825. begin
  826. FOmfFixup.TargetMethod:=ftmSegmentIndexNoDisp;
  827. FOmfFixup.TargetDatum:=ObjSection.Index;
  828. end;
  829. end;
  830. end
  831. else if symbol<>nil then
  832. begin
  833. FOmfFixup.LocationOffset:=DataOffset;
  834. if typ in [RELOC_ABSOLUTE16,RELOC_RELATIVE16] then
  835. FOmfFixup.LocationType:=fltOffset
  836. else if typ in [RELOC_ABSOLUTE32,RELOC_RELATIVE32] then
  837. FOmfFixup.LocationType:=fltOffset32
  838. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  839. FOmfFixup.LocationType:=fltBase
  840. else
  841. internalerror(2015041505);
  842. FOmfFixup.FrameDeterminedByThread:=False;
  843. FOmfFixup.TargetDeterminedByThread:=False;
  844. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG] then
  845. FOmfFixup.Mode:=fmSegmentRelative
  846. else if typ in [RELOC_RELATIVE16,RELOC_RELATIVE32,RELOC_SEGREL] then
  847. FOmfFixup.Mode:=fmSelfRelative
  848. else
  849. internalerror(2015041409);
  850. FOmfFixup.TargetMethod:=ftmExternalIndexNoDisp;
  851. FOmfFixup.TargetDatum:=symbol.symidx;
  852. FOmfFixup.FrameMethod:=ffmTarget;
  853. end
  854. else if group<>nil then
  855. begin
  856. FOmfFixup.LocationOffset:=DataOffset;
  857. if typ in [RELOC_ABSOLUTE16,RELOC_RELATIVE16] then
  858. FOmfFixup.LocationType:=fltOffset
  859. else if typ in [RELOC_ABSOLUTE32,RELOC_RELATIVE32] then
  860. FOmfFixup.LocationType:=fltOffset32
  861. else if typ in [RELOC_SEG,RELOC_SEGREL] then
  862. FOmfFixup.LocationType:=fltBase
  863. else
  864. internalerror(2015041506);
  865. FOmfFixup.FrameDeterminedByThread:=False;
  866. FOmfFixup.TargetDeterminedByThread:=False;
  867. if typ in [RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG] then
  868. FOmfFixup.Mode:=fmSegmentRelative
  869. else if typ in [RELOC_RELATIVE16,RELOC_RELATIVE32,RELOC_SEGREL] then
  870. FOmfFixup.Mode:=fmSelfRelative
  871. else
  872. internalerror(2015041410);
  873. FOmfFixup.FrameMethod:=ffmTarget;
  874. FOmfFixup.TargetMethod:=ftmGroupIndexNoDisp;
  875. FOmfFixup.TargetDatum:=group.index;
  876. end
  877. else
  878. internalerror(2015040702);
  879. end;
  880. {****************************************************************************
  881. TOmfObjSection
  882. ****************************************************************************}
  883. function TOmfObjSection.GetOmfAlignment: TOmfSegmentAlignment;
  884. begin
  885. case SecAlign of
  886. 1:
  887. result:=saRelocatableByteAligned;
  888. 2:
  889. result:=saRelocatableWordAligned;
  890. 4:
  891. result:=saRelocatableDWordAligned;
  892. 16:
  893. result:=saRelocatableParaAligned;
  894. 256:
  895. result:=saRelocatablePageAligned;
  896. 4096:
  897. result:=saNotSupported;
  898. else
  899. internalerror(2015041504);
  900. end;
  901. end;
  902. function TOmfObjSection.GetAltName: string;
  903. begin
  904. if FFirstSym<>nil then
  905. result:='/'+FFirstSym.Name
  906. else
  907. result:='';
  908. end;
  909. constructor TOmfObjSection.create(AList: TFPHashObjectList;
  910. const Aname: string; Aalign: longint; Aoptions: TObjSectionOptions);
  911. begin
  912. inherited create(AList, Aname, Aalign, Aoptions);
  913. FCombination:=scPublic;
  914. FUse:=suUse16;
  915. FLinNumEntries:=TOmfSubRecord_LINNUM_MsLink_LineNumberList.Create;
  916. end;
  917. destructor TOmfObjSection.destroy;
  918. begin
  919. FLinNumEntries.Free;
  920. inherited destroy;
  921. end;
  922. function TOmfObjSection.MemPosStr(AImageBase: qword): string;
  923. begin
  924. if Assigned(MZExeUnifiedLogicalSegment) then
  925. Result:=HexStr(MZExeUnifiedLogicalSegment.MemBasePos shr 4,4)+':'+
  926. HexStr(MemPos-MZExeUnifiedLogicalSegment.MemBasePos,4)
  927. else if Assigned(ExeSection) and (ExeSection is TNewExeSection) then
  928. Result:=HexStr(TNewExeSection(ExeSection).MemBasePos,4)+':'+HexStr(mempos,4)
  929. else
  930. Result:=inherited;
  931. end;
  932. {****************************************************************************
  933. TOmfObjData
  934. ****************************************************************************}
  935. class function TOmfObjData.CodeSectionName(const aname: string): string;
  936. begin
  937. {$ifdef i8086}
  938. if current_settings.x86memorymodel in x86_far_code_models then
  939. begin
  940. if cs_huge_code in current_settings.moduleswitches then
  941. result:=TrimStrCRC32(aname,30) + '_TEXT'
  942. else
  943. result:=current_module.modulename^ + '_TEXT';
  944. end
  945. else
  946. {$endif}
  947. result:='_TEXT';
  948. end;
  949. constructor TOmfObjData.create(const n: string);
  950. begin
  951. inherited create(n);
  952. CObjSymbol:=TOmfObjSymbol;
  953. CObjSection:=TOmfObjSection;
  954. createsectiongroup('DGROUP');
  955. FMainSource:=current_module.mainsource;
  956. FImportLibraryList:=TFPHashObjectList.Create(true);
  957. FExportedSymbolList:=TFPHashObjectList.Create(true);
  958. end;
  959. destructor TOmfObjData.destroy;
  960. begin
  961. FExportedSymbolList.Free;
  962. FImportLibraryList.Free;
  963. inherited destroy;
  964. end;
  965. function TOmfObjData.sectiontype2align(atype: TAsmSectiontype): longint;
  966. begin
  967. Result:=omf_sectiontype2align(atype);
  968. end;
  969. class function TOmfObjData.sectiontype2class(atype: TAsmSectiontype): string;
  970. begin
  971. Result:=omf_segclass(atype);
  972. end;
  973. function TOmfObjData.sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  974. var
  975. sep : string[3];
  976. secname : string;
  977. begin
  978. if (atype=sec_user) then
  979. Result:=aname
  980. else
  981. begin
  982. if omf_secnames[atype]=omf_secnames[sec_code] then
  983. secname:=CodeSectionName(aname)
  984. else if omf_segclass(atype)='FAR_DATA' then
  985. secname:=current_module.modulename^ + '_DATA'
  986. else
  987. secname:=omf_secnames[atype];
  988. if create_smartlink_sections and (aname<>'') then
  989. begin
  990. case aorder of
  991. secorder_begin :
  992. sep:='.b_';
  993. secorder_end :
  994. sep:='.z_';
  995. else
  996. sep:='.n_';
  997. end;
  998. result:=UpCase(secname+sep+aname);
  999. end
  1000. else
  1001. result:=secname;
  1002. end;
  1003. end;
  1004. function TOmfObjData.createsection(atype: TAsmSectionType; const aname: string; aorder: TAsmSectionOrder): TObjSection;
  1005. var
  1006. is_new: Boolean;
  1007. primary_group: String;
  1008. grp: TObjSectionGroup;
  1009. begin
  1010. is_new:=TObjSection(ObjSectionList.Find(sectionname(atype,aname,aorder)))=nil;
  1011. Result:=inherited createsection(atype, aname, aorder);
  1012. if is_new then
  1013. begin
  1014. TOmfObjSection(Result).FClassName:=sectiontype2class(atype);
  1015. if atype=sec_stack then
  1016. TOmfObjSection(Result).FCombination:=scStack
  1017. else if atype in [sec_debug_frame,sec_debug_info,sec_debug_line,sec_debug_abbrev,sec_debug_aranges,sec_debug_ranges] then
  1018. begin
  1019. TOmfObjSection(Result).FUse:=suUse32;
  1020. TOmfObjSection(Result).SizeLimit:=high(longword);
  1021. end;
  1022. primary_group:=omf_section_primary_group(atype,aname);
  1023. if primary_group<>'' then
  1024. begin
  1025. { find the primary group, if it already exists, else create it }
  1026. grp:=nil;
  1027. if GroupsList<>nil then
  1028. grp:=TObjSectionGroup(GroupsList.Find(primary_group));
  1029. if grp=nil then
  1030. grp:=createsectiongroup(primary_group);
  1031. { add the current section to the group }
  1032. SetLength(grp.members,Length(grp.members)+1);
  1033. grp.members[High(grp.members)]:=Result;
  1034. TOmfObjSection(Result).FPrimaryGroup:=grp;
  1035. end;
  1036. end;
  1037. end;
  1038. function TOmfObjData.reffardatasection: TObjSection;
  1039. var
  1040. secname: string;
  1041. begin
  1042. secname:=current_module.modulename^ + '_DATA';
  1043. result:=TObjSection(ObjSectionList.Find(secname));
  1044. if not assigned(result) then
  1045. begin
  1046. result:=CObjSection.create(ObjSectionList,secname,2,[oso_Data,oso_load,oso_write]);
  1047. result.ObjData:=self;
  1048. TOmfObjSection(Result).FClassName:='FAR_DATA';
  1049. end;
  1050. end;
  1051. procedure TOmfObjData.writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);
  1052. var
  1053. objreloc: TOmfRelocation;
  1054. symaddr: AWord;
  1055. begin
  1056. { RELOC_FARPTR = RELOC_ABSOLUTE16+RELOC_SEG }
  1057. if Reloctype=RELOC_FARPTR then
  1058. begin
  1059. if len<>4 then
  1060. internalerror(2015041502);
  1061. writeReloc(Data,2,p,RELOC_ABSOLUTE16);
  1062. writeReloc(0,2,p,RELOC_SEG);
  1063. exit;
  1064. end
  1065. { RELOC_FARPTR48 = RELOC_ABSOLUTE16+RELOC_SEG }
  1066. else if Reloctype=RELOC_FARPTR48 then
  1067. begin
  1068. if len<>6 then
  1069. internalerror(2015041507);
  1070. writeReloc(Data,4,p,RELOC_ABSOLUTE32);
  1071. writeReloc(0,2,p,RELOC_SEG);
  1072. exit;
  1073. end;
  1074. if CurrObjSec=nil then
  1075. internalerror(2004030704);
  1076. objreloc:=nil;
  1077. if Reloctype in [RELOC_FARDATASEG,RELOC_FARDATASEGREL] then
  1078. begin
  1079. if Reloctype=RELOC_FARDATASEG then
  1080. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,reffardatasection,RELOC_SEG)
  1081. else
  1082. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,reffardatasection,RELOC_SEGREL);
  1083. CurrObjSec.ObjRelocations.Add(objreloc);
  1084. end
  1085. else if assigned(p) then
  1086. begin
  1087. { real address of the symbol }
  1088. symaddr:=p.address;
  1089. if p.bind=AB_EXTERNAL then
  1090. begin
  1091. objreloc:=TOmfRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  1092. CurrObjSec.ObjRelocations.Add(objreloc);
  1093. end
  1094. { relative relocations within the same section can be calculated directly,
  1095. without the need to emit a relocation entry }
  1096. else if (p.objsection=CurrObjSec) and
  1097. (p.bind<>AB_COMMON) and
  1098. (Reloctype=RELOC_RELATIVE) then
  1099. begin
  1100. data:=data+symaddr-len-CurrObjSec.Size;
  1101. end
  1102. else
  1103. begin
  1104. objreloc:=TOmfRelocation.CreateSection(CurrObjSec.Size,p.objsection,Reloctype);
  1105. CurrObjSec.ObjRelocations.Add(objreloc);
  1106. if not (Reloctype in [RELOC_SEG,RELOC_SEGREL]) then
  1107. inc(data,symaddr);
  1108. end;
  1109. end
  1110. else if Reloctype in [RELOC_DGROUP,RELOC_DGROUPREL] then
  1111. begin
  1112. if Reloctype=RELOC_DGROUP then
  1113. objreloc:=TOmfRelocation.CreateGroup(CurrObjSec.Size,TObjSectionGroup(GroupsList.Find('DGROUP')),RELOC_SEG)
  1114. else
  1115. objreloc:=TOmfRelocation.CreateGroup(CurrObjSec.Size,TObjSectionGroup(GroupsList.Find('DGROUP')),RELOC_SEGREL);
  1116. CurrObjSec.ObjRelocations.Add(objreloc);
  1117. end;
  1118. CurrObjSec.write(data,len);
  1119. end;
  1120. procedure TOmfObjData.AddImportSymbol(const libname, symname,
  1121. symmangledname: TCmdStr; OrdNr: longint; isvar: boolean);
  1122. var
  1123. ImportLibrary : TImportLibrary;
  1124. ImportSymbol : TFPHashObject;
  1125. begin
  1126. ImportLibrary:=TImportLibrary(ImportLibraryList.Find(libname));
  1127. if not assigned(ImportLibrary) then
  1128. ImportLibrary:=TImportLibrary.Create(ImportLibraryList,libname);
  1129. ImportSymbol:=TFPHashObject(ImportLibrary.ImportSymbolList.Find(symname));
  1130. if not assigned(ImportSymbol) then
  1131. ImportSymbol:=TImportSymbol.Create(ImportLibrary.ImportSymbolList,symname,symmangledname,OrdNr,isvar);
  1132. end;
  1133. procedure TOmfObjData.AddExportSymbol(aExportByOrdinal, aResidentName,
  1134. aNoData: Boolean; aParmCount: Integer; aExportedName,
  1135. aInternalName: string; aExportOrdinal: Word);
  1136. var
  1137. s: TOmfObjExportedSymbol;
  1138. begin
  1139. s:=TOmfObjExportedSymbol.Create(ExportedSymbolList,aInternalName);
  1140. with s do
  1141. begin
  1142. ExportByOrdinal:=aExportByOrdinal;
  1143. ResidentName:=aResidentName;
  1144. NoData:=aNoData;
  1145. ParmCount:=aParmCount;
  1146. ExportedName:=aExportedName;
  1147. InternalName:=aInternalName;
  1148. ExportOrdinal:=aExportOrdinal;
  1149. end;
  1150. end;
  1151. {****************************************************************************
  1152. TOmfObjOutput
  1153. ****************************************************************************}
  1154. procedure TOmfObjOutput.AddSegment(const name, segclass, ovlname: string;
  1155. Alignment: TOmfSegmentAlignment; Combination: TOmfSegmentCombination;
  1156. Use: TOmfSegmentUse; Size: TObjSectionOfs);
  1157. var
  1158. s: TOmfRecord_SEGDEF;
  1159. begin
  1160. s:=TOmfRecord_SEGDEF.Create;
  1161. Segments.Add(name,s);
  1162. s.SegmentNameIndex:=LNames.Add(name);
  1163. s.ClassNameIndex:=LNames.Add(segclass);
  1164. s.OverlayNameIndex:=LNames.Add(ovlname);
  1165. s.Alignment:=Alignment;
  1166. s.Combination:=Combination;
  1167. s.Use:=Use;
  1168. s.SegmentLength:=Size;
  1169. end;
  1170. procedure TOmfObjOutput.AddGroup(group: TObjSectionGroup);
  1171. var
  1172. g: TOmfRecord_GRPDEF;
  1173. seglist: TSegmentList;
  1174. I: Integer;
  1175. begin
  1176. seglist:=nil;
  1177. g:=TOmfRecord_GRPDEF.Create;
  1178. Groups.Add(group.Name,g);
  1179. g.GroupNameIndex:=LNames.Add(group.Name);
  1180. SetLength(seglist,Length(group.members));
  1181. for I:=Low(group.members) to High(group.members) do
  1182. seglist[I]:=group.members[I].index;
  1183. g.SegmentList:=seglist;
  1184. end;
  1185. procedure TOmfObjOutput.WriteSections(Data: TObjData);
  1186. var
  1187. i:longint;
  1188. sec:TObjSection;
  1189. begin
  1190. for i:=0 to Data.ObjSectionList.Count-1 do
  1191. begin
  1192. sec:=TObjSection(Data.ObjSectionList[i]);
  1193. WriteSectionContentAndFixups(sec);
  1194. WriteLinNumRecords(TOmfObjSection(sec));
  1195. end;
  1196. end;
  1197. procedure TOmfObjOutput.WriteSectionContentAndFixups(sec: TObjSection);
  1198. const
  1199. MaxChunkSize=$3fa;
  1200. var
  1201. RawRecord: TOmfRawRecord;
  1202. ChunkStart,ChunkLen: DWord;
  1203. ChunkFixupStart,ChunkFixupEnd: Integer;
  1204. SegIndex: Integer;
  1205. NextOfs: Integer;
  1206. Is32BitLEDATA: Boolean;
  1207. I: Integer;
  1208. begin
  1209. if (oso_data in sec.SecOptions) then
  1210. begin
  1211. if sec.Data=nil then
  1212. internalerror(2004030705);
  1213. for I:=0 to sec.ObjRelocations.Count-1 do
  1214. TOmfRelocation(sec.ObjRelocations[I]).BuildOmfFixup;
  1215. SegIndex:=Segments.FindIndexOf(sec.Name);
  1216. RawRecord:=TOmfRawRecord.Create;
  1217. sec.data.seek(0);
  1218. ChunkFixupStart:=0;
  1219. ChunkFixupEnd:=-1;
  1220. ChunkStart:=0;
  1221. ChunkLen:=Min(MaxChunkSize, sec.Data.size-ChunkStart);
  1222. while ChunkLen>0 do
  1223. begin
  1224. { find last fixup in the chunk }
  1225. while (ChunkFixupEnd<(sec.ObjRelocations.Count-1)) and
  1226. (TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd+1]).DataOffset<(ChunkStart+ChunkLen)) do
  1227. inc(ChunkFixupEnd);
  1228. { check if last chunk is crossing the chunk boundary, and trim ChunkLen if necessary }
  1229. if (ChunkFixupEnd>=ChunkFixupStart) and
  1230. ((TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).DataOffset+
  1231. TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).OmfFixup.LocationSize)>(ChunkStart+ChunkLen)) then
  1232. begin
  1233. ChunkLen:=TOmfRelocation(sec.ObjRelocations[ChunkFixupEnd]).DataOffset-ChunkStart;
  1234. Dec(ChunkFixupEnd);
  1235. end;
  1236. { write LEDATA record }
  1237. Is32BitLEDATA:=TOmfObjSection(sec).Use=suUse32;
  1238. if Is32BitLEDATA then
  1239. RawRecord.RecordType:=RT_LEDATA32
  1240. else
  1241. RawRecord.RecordType:=RT_LEDATA;
  1242. NextOfs:=RawRecord.WriteIndexedRef(0,SegIndex);
  1243. if Is32BitLEDATA then
  1244. begin
  1245. unaligned(PUint32(@RawRecord.RawData[NextOfs{..NextOfs+3}])^):=NtoLE(uint32(ChunkStart));
  1246. Inc(NextOfs,4);
  1247. end
  1248. else
  1249. begin
  1250. if ChunkStart>$ffff then
  1251. internalerror(2018052201);
  1252. unaligned(PUint16(@RawRecord.RawData[NextOfs{..NextOfs+1}])^):=NtoLE(uint16(ChunkStart));
  1253. Inc(NextOfs,2);
  1254. end;
  1255. sec.data.read(RawRecord.RawData[NextOfs], ChunkLen);
  1256. Inc(NextOfs, ChunkLen);
  1257. RawRecord.RecordLength:=NextOfs+1;
  1258. RawRecord.CalculateChecksumByte;
  1259. RawRecord.WriteTo(FWriter);
  1260. { write FIXUPP record }
  1261. if ChunkFixupEnd>=ChunkFixupStart then
  1262. begin
  1263. RawRecord.RecordType:=RT_FIXUPP;
  1264. NextOfs:=0;
  1265. for I:=ChunkFixupStart to ChunkFixupEnd do
  1266. begin
  1267. TOmfRelocation(sec.ObjRelocations[I]).OmfFixup.DataRecordStartOffset:=ChunkStart;
  1268. NextOfs:=TOmfRelocation(sec.ObjRelocations[I]).OmfFixup.WriteAt(RawRecord,NextOfs);
  1269. end;
  1270. RawRecord.RecordLength:=NextOfs+1;
  1271. RawRecord.CalculateChecksumByte;
  1272. RawRecord.WriteTo(FWriter);
  1273. end;
  1274. { prepare next chunk }
  1275. Inc(ChunkStart, ChunkLen);
  1276. ChunkLen:=Min(MaxChunkSize, sec.Data.size-ChunkStart);
  1277. ChunkFixupStart:=ChunkFixupEnd+1;
  1278. end;
  1279. RawRecord.Free;
  1280. end;
  1281. end;
  1282. procedure TOmfObjOutput.WriteLinNumRecords(sec: TOmfObjSection);
  1283. var
  1284. SegIndex: Integer;
  1285. RawRecord: TOmfRawRecord;
  1286. LinNumRec: TOmfRecord_LINNUM_MsLink;
  1287. begin
  1288. if (oso_data in sec.SecOptions) then
  1289. begin
  1290. if sec.Data=nil then
  1291. internalerror(2004030706);
  1292. if sec.LinNumEntries.Count=0 then
  1293. exit;
  1294. SegIndex:=Segments.FindIndexOf(sec.Name);
  1295. RawRecord:=TOmfRawRecord.Create;
  1296. LinNumRec:=TOmfRecord_LINNUM_MsLink.Create;
  1297. LinNumRec.BaseGroup:=0;
  1298. LinNumRec.BaseSegment:=SegIndex;
  1299. LinNumRec.LineNumberList:=sec.LinNumEntries;
  1300. while LinNumRec.NextIndex<sec.LinNumEntries.Count do
  1301. begin
  1302. LinNumRec.EncodeTo(RawRecord);
  1303. RawRecord.WriteTo(FWriter);
  1304. end;
  1305. LinNumRec.Free;
  1306. RawRecord.Free;
  1307. end;
  1308. end;
  1309. procedure TOmfObjOutput.section_count_sections(p: TObject; arg: pointer);
  1310. begin
  1311. TOmfObjSection(p).index:=pinteger(arg)^;
  1312. inc(pinteger(arg)^);
  1313. end;
  1314. procedure TOmfObjOutput.group_count_groups(p: TObject; arg: pointer);
  1315. begin
  1316. TObjSectionGroup(p).index:=pinteger(arg)^;
  1317. inc(pinteger(arg)^);
  1318. end;
  1319. procedure TOmfObjOutput.WritePUBDEFs(Data: TObjData);
  1320. var
  1321. PubNamesForSection: array of TFPHashObjectList;
  1322. i: Integer;
  1323. objsym: TObjSymbol;
  1324. PublicNameElem: TOmfPublicNameElement;
  1325. RawRecord: TOmfRawRecord;
  1326. PubDefRec: TOmfRecord_PUBDEF;
  1327. begin
  1328. PubNamesForSection:=nil;
  1329. RawRecord:=TOmfRawRecord.Create;
  1330. SetLength(PubNamesForSection,Data.ObjSectionList.Count);
  1331. for i:=0 to Data.ObjSectionList.Count-1 do
  1332. PubNamesForSection[i]:=TFPHashObjectList.Create;
  1333. for i:=0 to Data.ObjSymbolList.Count-1 do
  1334. begin
  1335. objsym:=TObjSymbol(Data.ObjSymbolList[i]);
  1336. if objsym.bind=AB_GLOBAL then
  1337. begin
  1338. PublicNameElem:=TOmfPublicNameElement.Create(PubNamesForSection[objsym.objsection.index-1],objsym.Name);
  1339. PublicNameElem.PublicOffset:=objsym.offset;
  1340. PublicNameElem.IsLocal:=False;
  1341. end
  1342. else if objsym.bind=AB_LOCAL then
  1343. begin
  1344. PublicNameElem:=TOmfPublicNameElement.Create(PubNamesForSection[objsym.objsection.index-1],objsym.Name);
  1345. PublicNameElem.PublicOffset:=objsym.offset;
  1346. PublicNameElem.IsLocal:=True;
  1347. end
  1348. end;
  1349. for i:=0 to Data.ObjSectionList.Count-1 do
  1350. if PubNamesForSection[i].Count>0 then
  1351. begin
  1352. PubDefRec:=TOmfRecord_PUBDEF.Create;
  1353. PubDefRec.BaseSegmentIndex:=i+1;
  1354. if TOmfObjSection(Data.ObjSectionList[i]).PrimaryGroup<>nil then
  1355. PubDefRec.BaseGroupIndex:=Groups.FindIndexOf(TOmfObjSection(Data.ObjSectionList[i]).PrimaryGroup.Name)
  1356. else
  1357. PubDefRec.BaseGroupIndex:=0;
  1358. PubDefRec.PublicNames:=PubNamesForSection[i];
  1359. while PubDefRec.NextIndex<PubDefRec.PublicNames.Count do
  1360. begin
  1361. PubDefRec.EncodeTo(RawRecord);
  1362. RawRecord.WriteTo(FWriter);
  1363. end;
  1364. PubDefRec.Free;
  1365. end;
  1366. for i:=0 to Data.ObjSectionList.Count-1 do
  1367. FreeAndNil(PubNamesForSection[i]);
  1368. RawRecord.Free;
  1369. end;
  1370. procedure TOmfObjOutput.WriteEXTDEFs(Data: TObjData);
  1371. var
  1372. ExtNames: TFPHashObjectList;
  1373. RawRecord: TOmfRawRecord;
  1374. i,idx: Integer;
  1375. objsym: TObjSymbol;
  1376. ExtDefRec: TOmfRecord_EXTDEF;
  1377. begin
  1378. ExtNames:=TFPHashObjectList.Create;
  1379. RawRecord:=TOmfRawRecord.Create;
  1380. idx:=1;
  1381. for i:=0 to Data.ObjSymbolList.Count-1 do
  1382. begin
  1383. objsym:=TObjSymbol(Data.ObjSymbolList[i]);
  1384. if objsym.bind=AB_EXTERNAL then
  1385. begin
  1386. TOmfExternalNameElement.Create(ExtNames,objsym.Name);
  1387. objsym.symidx:=idx;
  1388. Inc(idx);
  1389. end;
  1390. end;
  1391. if ExtNames.Count>0 then
  1392. begin
  1393. ExtDefRec:=TOmfRecord_EXTDEF.Create;
  1394. ExtDefRec.ExternalNames:=ExtNames;
  1395. while ExtDefRec.NextIndex<ExtDefRec.ExternalNames.Count do
  1396. begin
  1397. ExtDefRec.EncodeTo(RawRecord);
  1398. RawRecord.WriteTo(FWriter);
  1399. end;
  1400. ExtDefRec.Free;
  1401. end;
  1402. ExtNames.Free;
  1403. RawRecord.Free;
  1404. end;
  1405. function TOmfObjOutput.writeData(Data:TObjData):boolean;
  1406. var
  1407. RawRecord: TOmfRawRecord;
  1408. Header: TOmfRecord_THEADR;
  1409. Translator_COMENT: TOmfRecord_COMENT;
  1410. DebugFormat_COMENT: TOmfRecord_COMENT;
  1411. LinkPassSeparator_COMENT: TOmfRecord_COMENT;
  1412. LNamesRec: TOmfRecord_LNAMES;
  1413. ModEnd: TOmfRecord_MODEND;
  1414. I: Integer;
  1415. SegDef: TOmfRecord_SEGDEF;
  1416. GrpDef: TOmfRecord_GRPDEF;
  1417. nsections,ngroups: Integer;
  1418. begin
  1419. { calc amount of sections we have and set their index, starting with 1 }
  1420. nsections:=1;
  1421. data.ObjSectionList.ForEachCall(@section_count_sections,@nsections);
  1422. { calc amount of groups we have and set their index, starting with 1 }
  1423. ngroups:=1;
  1424. data.GroupsList.ForEachCall(@group_count_groups,@ngroups);
  1425. { maximum amount of sections supported in the omf format is $7fff }
  1426. if (nsections-1)>$7fff then
  1427. internalerror(2015040701);
  1428. { maximum amount of groups supported in the omf format is $7fff }
  1429. if (ngroups-1)>$7fff then
  1430. internalerror(2018062101);
  1431. { write header record }
  1432. RawRecord:=TOmfRawRecord.Create;
  1433. Header:=TOmfRecord_THEADR.Create;
  1434. if cs_debuginfo in current_settings.moduleswitches then
  1435. Header.ModuleName:=TOmfObjData(Data).MainSource
  1436. else
  1437. Header.ModuleName:=Data.Name;
  1438. Header.EncodeTo(RawRecord);
  1439. RawRecord.WriteTo(FWriter);
  1440. Header.Free;
  1441. { write translator COMENT header }
  1442. Translator_COMENT:=TOmfRecord_COMENT.Create;
  1443. Translator_COMENT.CommentClass:=CC_Translator;
  1444. Translator_COMENT.CommentString:='FPC '+full_version_string+
  1445. ' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname;
  1446. Translator_COMENT.EncodeTo(RawRecord);
  1447. RawRecord.WriteTo(FWriter);
  1448. Translator_COMENT.Free;
  1449. if (target_dbg.id=dbg_codeview) or
  1450. ((ds_dwarf_omf_linnum in current_settings.debugswitches) and
  1451. (target_dbg.id in [dbg_dwarf2,dbg_dwarf3,dbg_dwarf4])) then
  1452. begin
  1453. DebugFormat_COMENT:=TOmfRecord_COMENT.Create;
  1454. DebugFormat_COMENT.CommentClass:=CC_NewOmfExtension;
  1455. DebugFormat_COMENT.CommentString:='';
  1456. DebugFormat_COMENT.EncodeTo(RawRecord);
  1457. RawRecord.WriteTo(FWriter);
  1458. DebugFormat_COMENT.Free;
  1459. end;
  1460. LNames.Clear;
  1461. LNames.Add(''); { insert an empty string, which has index 1 }
  1462. FSegments.Clear;
  1463. FSegments.Add('',nil);
  1464. FGroups.Clear;
  1465. FGroups.Add('',nil);
  1466. for i:=0 to Data.GroupsList.Count-1 do
  1467. AddGroup(TObjSectionGroup(Data.GroupsList[I]));
  1468. for i:=0 to Data.ObjSectionList.Count-1 do
  1469. with TOmfObjSection(Data.ObjSectionList[I]) do
  1470. AddSegment(Name,ClassName,OverlayName,OmfAlignment,Combination,Use,Size);
  1471. { write LNAMES record(s) }
  1472. LNamesRec:=TOmfRecord_LNAMES.Create;
  1473. LNamesRec.Names:=LNames;
  1474. while LNamesRec.NextIndex<=LNames.Count do
  1475. begin
  1476. LNamesRec.EncodeTo(RawRecord);
  1477. RawRecord.WriteTo(FWriter);
  1478. end;
  1479. LNamesRec.Free;
  1480. { write SEGDEF record(s) }
  1481. for I:=1 to Segments.Count-1 do
  1482. begin
  1483. SegDef:=TOmfRecord_SEGDEF(Segments[I]);
  1484. SegDef.EncodeTo(RawRecord);
  1485. RawRecord.WriteTo(FWriter);
  1486. end;
  1487. { write GRPDEF record(s) }
  1488. for I:=1 to Groups.Count-1 do
  1489. begin
  1490. GrpDef:=TOmfRecord_GRPDEF(Groups[I]);
  1491. GrpDef.EncodeTo(RawRecord);
  1492. RawRecord.WriteTo(FWriter);
  1493. end;
  1494. { write PUBDEF record(s) }
  1495. WritePUBDEFs(Data);
  1496. { write EXTDEF record(s) }
  1497. WriteEXTDEFs(Data);
  1498. { write link pass separator }
  1499. LinkPassSeparator_COMENT:=TOmfRecord_COMENT.Create;
  1500. LinkPassSeparator_COMENT.CommentClass:=CC_LinkPassSeparator;
  1501. LinkPassSeparator_COMENT.CommentString:=#1;
  1502. LinkPassSeparator_COMENT.NoList:=True;
  1503. LinkPassSeparator_COMENT.EncodeTo(RawRecord);
  1504. RawRecord.WriteTo(FWriter);
  1505. LinkPassSeparator_COMENT.Free;
  1506. { write section content, interleaved with fixups }
  1507. WriteSections(Data);
  1508. { write MODEND record }
  1509. ModEnd:=TOmfRecord_MODEND.Create;
  1510. ModEnd.EncodeTo(RawRecord);
  1511. RawRecord.WriteTo(FWriter);
  1512. ModEnd.Free;
  1513. RawRecord.Free;
  1514. result:=true;
  1515. end;
  1516. constructor TOmfObjOutput.create(AWriter:TObjectWriter);
  1517. begin
  1518. inherited create(AWriter);
  1519. cobjdata:=TOmfObjData;
  1520. FLNames:=TOmfOrderedNameCollection.Create(False);
  1521. FSegments:=TFPHashObjectList.Create;
  1522. FSegments.Add('',nil);
  1523. FGroups:=TFPHashObjectList.Create;
  1524. FGroups.Add('',nil);
  1525. end;
  1526. destructor TOmfObjOutput.Destroy;
  1527. begin
  1528. FGroups.Free;
  1529. FSegments.Free;
  1530. FLNames.Free;
  1531. inherited Destroy;
  1532. end;
  1533. procedure TOmfObjOutput.WriteDllImport(const dllname,afuncname,mangledname: string; ordnr: longint; isvar: boolean);
  1534. var
  1535. RawRecord: TOmfRawRecord;
  1536. Header: TOmfRecord_THEADR;
  1537. DllImport_COMENT: TOmfRecord_COMENT=nil;
  1538. DllImport_COMENT_IMPDEF: TOmfRecord_COMENT_IMPDEF=nil;
  1539. ModEnd: TOmfRecord_MODEND;
  1540. begin
  1541. { write header record }
  1542. RawRecord:=TOmfRawRecord.Create;
  1543. Header:=TOmfRecord_THEADR.Create;
  1544. Header.ModuleName:=mangledname;
  1545. Header.EncodeTo(RawRecord);
  1546. RawRecord.WriteTo(FWriter);
  1547. Header.Free;
  1548. { write IMPDEF record }
  1549. DllImport_COMENT_IMPDEF:=TOmfRecord_COMENT_IMPDEF.Create;
  1550. DllImport_COMENT_IMPDEF.InternalName:=mangledname;
  1551. DllImport_COMENT_IMPDEF.ModuleName:=dllname;
  1552. if ordnr <= 0 then
  1553. begin
  1554. DllImport_COMENT_IMPDEF.ImportByOrdinal:=False;
  1555. DllImport_COMENT_IMPDEF.Name:=afuncname;
  1556. end
  1557. else
  1558. begin
  1559. DllImport_COMENT_IMPDEF.ImportByOrdinal:=True;
  1560. DllImport_COMENT_IMPDEF.Ordinal:=ordnr;
  1561. end;
  1562. DllImport_COMENT:=TOmfRecord_COMENT.Create;
  1563. DllImport_COMENT_IMPDEF.EncodeTo(DllImport_COMENT);
  1564. FreeAndNil(DllImport_COMENT_IMPDEF);
  1565. DllImport_COMENT.EncodeTo(RawRecord);
  1566. FreeAndNil(DllImport_COMENT);
  1567. RawRecord.WriteTo(FWriter);
  1568. { write MODEND record }
  1569. ModEnd:=TOmfRecord_MODEND.Create;
  1570. ModEnd.EncodeTo(RawRecord);
  1571. RawRecord.WriteTo(FWriter);
  1572. ModEnd.Free;
  1573. RawRecord.Free;
  1574. end;
  1575. {****************************************************************************
  1576. TOmfObjInput
  1577. ****************************************************************************}
  1578. function TOmfObjInput.PeekNextRecordType: Byte;
  1579. var
  1580. OldPos: LongInt;
  1581. begin
  1582. OldPos:=FReader.Pos;
  1583. if not FReader.read(Result, 1) then
  1584. begin
  1585. InputError('Unexpected end of file');
  1586. Result:=0;
  1587. exit;
  1588. end;
  1589. FReader.seek(OldPos);
  1590. end;
  1591. function TOmfObjInput.ReadLNames(RawRec: TOmfRawRecord): Boolean;
  1592. var
  1593. LNamesRec: TOmfRecord_LNAMES;
  1594. begin
  1595. Result:=False;
  1596. LNamesRec:=TOmfRecord_LNAMES.Create;
  1597. LNamesRec.Names:=LNames;
  1598. LNamesRec.DecodeFrom(RawRec);
  1599. LNamesRec.Free;
  1600. Result:=True;
  1601. end;
  1602. function TOmfObjInput.ReadSegDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1603. var
  1604. SegDefRec: TOmfRecord_SEGDEF;
  1605. SegmentName,SegClassName,OverlayName: string;
  1606. SecAlign: LongInt;
  1607. secoptions: TObjSectionOptions;
  1608. objsec: TOmfObjSection;
  1609. begin
  1610. Result:=False;
  1611. SegDefRec:=TOmfRecord_SEGDEF.Create;
  1612. SegDefRec.DecodeFrom(RawRec);
  1613. if (SegDefRec.SegmentNameIndex<1) or (SegDefRec.SegmentNameIndex>LNames.Count) then
  1614. begin
  1615. InputError('Segment name index out of range');
  1616. SegDefRec.Free;
  1617. exit;
  1618. end;
  1619. SegmentName:=LNames[SegDefRec.SegmentNameIndex];
  1620. if (SegDefRec.ClassNameIndex<1) or (SegDefRec.ClassNameIndex>LNames.Count) then
  1621. begin
  1622. InputError('Segment class name index out of range');
  1623. SegDefRec.Free;
  1624. exit;
  1625. end;
  1626. SegClassName:=LNames[SegDefRec.ClassNameIndex];
  1627. if (SegDefRec.OverlayNameIndex<1) or (SegDefRec.OverlayNameIndex>LNames.Count) then
  1628. begin
  1629. InputError('Segment overlay name index out of range');
  1630. SegDefRec.Free;
  1631. exit;
  1632. end;
  1633. OverlayName:=LNames[SegDefRec.OverlayNameIndex];
  1634. SecAlign:=1; // otherwise warning prohibits compilation
  1635. case SegDefRec.Alignment of
  1636. saRelocatableByteAligned:
  1637. SecAlign:=1;
  1638. saRelocatableWordAligned:
  1639. SecAlign:=2;
  1640. saRelocatableParaAligned:
  1641. SecAlign:=16;
  1642. saRelocatableDWordAligned:
  1643. SecAlign:=4;
  1644. saRelocatablePageAligned:
  1645. SecAlign:=256;
  1646. saNotSupported:
  1647. SecAlign:=4096;
  1648. saAbsolute:
  1649. begin
  1650. InputError('Absolute segment alignment not supported');
  1651. SegDefRec.Free;
  1652. exit;
  1653. end;
  1654. saNotDefined:
  1655. begin
  1656. InputError('Invalid (unsupported/undefined) OMF segment alignment');
  1657. SegDefRec.Free;
  1658. exit;
  1659. end;
  1660. end;
  1661. if not CaseSensitiveSegments then
  1662. begin
  1663. SegmentName:=UpCase(SegmentName);
  1664. SegClassName:=UpCase(SegClassName);
  1665. OverlayName:=UpCase(OverlayName);
  1666. end;
  1667. { hack for supporting object modules, generated by Borland's BINOBJ tool }
  1668. if (SegClassName='') and (SegmentName='CODE') then
  1669. begin
  1670. SegmentName:=InputFileName;
  1671. SegClassName:='CODE';
  1672. end;
  1673. secoptions:=[];
  1674. objsec:=TOmfObjSection(objdata.createsection(SegmentName+'||'+SegClassName,SecAlign,secoptions,false));
  1675. objsec.FClassName:=SegClassName;
  1676. objsec.FOverlayName:=OverlayName;
  1677. objsec.FCombination:=SegDefRec.Combination;
  1678. objsec.FUse:=SegDefRec.Use;
  1679. if SegDefRec.SegmentLength>High(objsec.Size) then
  1680. begin
  1681. InputError('Segment too large');
  1682. SegDefRec.Free;
  1683. exit;
  1684. end;
  1685. objsec.Size:=SegDefRec.SegmentLength;
  1686. if SegClassName='DWARF' then
  1687. objsec.SecOptions:=objsec.SecOptions+[oso_debug];
  1688. if (SegClassName='HEAP') or
  1689. (SegClassName='STACK') or (SegDefRec.Combination=scStack) or
  1690. (SegClassName='BEGDATA') or
  1691. (SegmentName='FPC') then
  1692. objsec.SecOptions:=objsec.SecOptions+[oso_keep];
  1693. SegDefRec.Free;
  1694. Result:=True;
  1695. end;
  1696. function TOmfObjInput.ReadGrpDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1697. var
  1698. GrpDefRec: TOmfRecord_GRPDEF;
  1699. GroupName: string;
  1700. SecGroup: TObjSectionGroup;
  1701. i,SegIndex: Integer;
  1702. begin
  1703. Result:=False;
  1704. GrpDefRec:=TOmfRecord_GRPDEF.Create;
  1705. GrpDefRec.DecodeFrom(RawRec);
  1706. if (GrpDefRec.GroupNameIndex<1) or (GrpDefRec.GroupNameIndex>LNames.Count) then
  1707. begin
  1708. InputError('Group name index out of range');
  1709. GrpDefRec.Free;
  1710. exit;
  1711. end;
  1712. GroupName:=LNames[GrpDefRec.GroupNameIndex];
  1713. if not CaseSensitiveSegments then
  1714. GroupName:=UpCase(GroupName);
  1715. SecGroup:=objdata.createsectiongroup(GroupName);
  1716. SetLength(SecGroup.members,Length(GrpDefRec.SegmentList));
  1717. for i:=0 to Length(GrpDefRec.SegmentList)-1 do
  1718. begin
  1719. SegIndex:=GrpDefRec.SegmentList[i];
  1720. if (SegIndex<1) or (SegIndex>objdata.ObjSectionList.Count) then
  1721. begin
  1722. InputError('Segment name index out of range in group definition');
  1723. GrpDefRec.Free;
  1724. exit;
  1725. end;
  1726. SecGroup.members[i]:=TOmfObjSection(objdata.ObjSectionList[SegIndex-1]);
  1727. end;
  1728. GrpDefRec.Free;
  1729. Result:=True;
  1730. end;
  1731. function TOmfObjInput.ReadExtDef(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1732. var
  1733. ExtDefRec: TOmfRecord_EXTDEF;
  1734. ExtDefElem: TOmfExternalNameElement;
  1735. OldCount,NewCount,i: Integer;
  1736. objsym: TObjSymbol;
  1737. symname: TSymStr;
  1738. begin
  1739. Result:=False;
  1740. ExtDefRec:=TOmfRecord_EXTDEF.Create;
  1741. ExtDefRec.ExternalNames:=ExtDefs;
  1742. OldCount:=ExtDefs.Count;
  1743. ExtDefRec.DecodeFrom(RawRec);
  1744. NewCount:=ExtDefs.Count;
  1745. for i:=OldCount to NewCount-1 do
  1746. begin
  1747. ExtDefElem:=TOmfExternalNameElement(ExtDefs[i]);
  1748. symname:=ExtDefElem.Name;
  1749. if not CaseSensitiveSymbols then
  1750. symname:=UpCase(symname);
  1751. objsym:=objdata.CreateSymbol(symname);
  1752. objsym.bind:=AB_EXTERNAL;
  1753. objsym.typ:=AT_FUNCTION;
  1754. objsym.objsection:=nil;
  1755. objsym.offset:=0;
  1756. objsym.size:=0;
  1757. end;
  1758. ExtDefRec.Free;
  1759. Result:=True;
  1760. end;
  1761. function TOmfObjInput.ReadPubDef(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  1762. var
  1763. PubDefRec: TOmfRecord_PUBDEF;
  1764. PubDefElem: TOmfPublicNameElement;
  1765. OldCount,NewCount,i: Integer;
  1766. basegroup: TObjSectionGroup;
  1767. objsym: TObjSymbol;
  1768. objsec: TOmfObjSection;
  1769. symname: TSymStr;
  1770. begin
  1771. Result:=False;
  1772. PubDefRec:=TOmfRecord_PUBDEF.Create;
  1773. PubDefRec.PublicNames:=PubDefs;
  1774. OldCount:=PubDefs.Count;
  1775. PubDefRec.DecodeFrom(RawRec);
  1776. NewCount:=PubDefs.Count;
  1777. if (PubDefRec.BaseGroupIndex<0) or (PubDefRec.BaseGroupIndex>objdata.GroupsList.Count) then
  1778. begin
  1779. InputError('Public symbol''s group name index out of range');
  1780. PubDefRec.Free;
  1781. exit;
  1782. end;
  1783. if PubDefRec.BaseGroupIndex<>0 then
  1784. basegroup:=TObjSectionGroup(objdata.GroupsList[PubDefRec.BaseGroupIndex-1])
  1785. else
  1786. basegroup:=nil;
  1787. if (PubDefRec.BaseSegmentIndex<0) or (PubDefRec.BaseSegmentIndex>objdata.ObjSectionList.Count) then
  1788. begin
  1789. InputError('Public symbol''s segment name index out of range');
  1790. PubDefRec.Free;
  1791. exit;
  1792. end;
  1793. if PubDefRec.BaseSegmentIndex=0 then
  1794. begin
  1795. InputError('Public symbol uses absolute addressing, which is not supported by this linker');
  1796. PubDefRec.Free;
  1797. exit;
  1798. end;
  1799. objsec:=TOmfObjSection(objdata.ObjSectionList[PubDefRec.BaseSegmentIndex-1]);
  1800. for i:=OldCount to NewCount-1 do
  1801. begin
  1802. PubDefElem:=TOmfPublicNameElement(PubDefs[i]);
  1803. symname:=PubDefElem.Name;
  1804. if not CaseSensitiveSymbols then
  1805. symname:=UpCase(symname);
  1806. objsym:=objdata.CreateSymbol(symname);
  1807. if PubDefElem.IsLocal then
  1808. objsym.bind:=AB_LOCAL
  1809. else
  1810. objsym.bind:=AB_GLOBAL;
  1811. objsym.typ:=AT_FUNCTION;
  1812. objsym.group:=basegroup;
  1813. objsym.objsection:=objsec;
  1814. objsym.offset:=PubDefElem.PublicOffset;
  1815. objsym.size:=0;
  1816. if (objsym.bind=AB_GLOBAL) and (objsec.FFirstSym=nil) then
  1817. objsec.FFirstSym:=objsym;
  1818. end;
  1819. PubDefRec.Free;
  1820. Result:=True;
  1821. end;
  1822. function TOmfObjInput.ReadModEnd(RawRec: TOmfRawRecord; objdata:TObjData): Boolean;
  1823. var
  1824. ModEndRec: TOmfRecord_MODEND;
  1825. objsym: TObjSymbol;
  1826. objsec: TOmfObjSection;
  1827. basegroup: TObjSectionGroup;
  1828. begin
  1829. Result:=False;
  1830. ModEndRec:=TOmfRecord_MODEND.Create;
  1831. ModEndRec.DecodeFrom(RawRec);
  1832. if ModEndRec.HasStartAddress then
  1833. begin
  1834. if not ModEndRec.LogicalStartAddress then
  1835. begin
  1836. InputError('Physical start address not supported');
  1837. ModEndRec.Free;
  1838. exit;
  1839. end;
  1840. if not (ModEndRec.TargetMethod in [ftmSegmentIndex,ftmSegmentIndexNoDisp]) then
  1841. begin
  1842. InputError('Target method for start address other than "Segment Index" is not supported');
  1843. ModEndRec.Free;
  1844. exit;
  1845. end;
  1846. if (ModEndRec.TargetDatum<1) or (ModEndRec.TargetDatum>objdata.ObjSectionList.Count) then
  1847. begin
  1848. InputError('Segment name index for start address out of range');
  1849. ModEndRec.Free;
  1850. exit;
  1851. end;
  1852. case ModEndRec.FrameMethod of
  1853. ffmSegmentIndex:
  1854. begin
  1855. if (ModEndRec.FrameDatum<1) or (ModEndRec.FrameDatum>objdata.ObjSectionList.Count) then
  1856. begin
  1857. InputError('Frame segment name index for start address out of range');
  1858. ModEndRec.Free;
  1859. exit;
  1860. end;
  1861. if ModEndRec.FrameDatum<>ModEndRec.TargetDatum then
  1862. begin
  1863. InputError('Frame segment different than target segment is not supported supported for start address');
  1864. ModEndRec.Free;
  1865. exit;
  1866. end;
  1867. basegroup:=nil;
  1868. end;
  1869. ffmGroupIndex:
  1870. begin
  1871. if (ModEndRec.FrameDatum<1) or (ModEndRec.FrameDatum>objdata.GroupsList.Count) then
  1872. begin
  1873. InputError('Frame group name index for start address out of range');
  1874. ModEndRec.Free;
  1875. exit;
  1876. end;
  1877. basegroup:=TObjSectionGroup(objdata.GroupsList[ModEndRec.FrameDatum-1]);
  1878. end;
  1879. else
  1880. begin
  1881. InputError('Frame method for start address other than "Segment Index" or "Group Index" is not supported');
  1882. ModEndRec.Free;
  1883. exit;
  1884. end;
  1885. end;
  1886. objsec:=TOmfObjSection(objdata.ObjSectionList[ModEndRec.TargetDatum-1]);
  1887. objsym:=objdata.CreateSymbol('..start');
  1888. objsym.bind:=AB_GLOBAL;
  1889. objsym.typ:=AT_FUNCTION;
  1890. objsym.group:=basegroup;
  1891. objsym.objsection:=objsec;
  1892. objsym.offset:=ModEndRec.TargetDisplacement;
  1893. objsym.size:=0;
  1894. end;
  1895. ModEndRec.Free;
  1896. Result:=True;
  1897. end;
  1898. function TOmfObjInput.ReadLeOrLiDataAndFixups(RawRec: TOmfRawRecord; objdata: TObjData): Boolean;
  1899. var
  1900. Is32Bit: Boolean;
  1901. NextOfs: Integer;
  1902. SegmentIndex: Integer;
  1903. EnumeratedDataOffset: DWord;
  1904. BlockLength: Integer;
  1905. objsec: TOmfObjSection;
  1906. FixupRawRec: TOmfRawRecord=nil;
  1907. Fixup: TOmfSubRecord_FIXUP;
  1908. Thread: TOmfSubRecord_THREAD;
  1909. FixuppWithoutLeOrLiData: Boolean=False;
  1910. begin
  1911. objsec:=nil;
  1912. EnumeratedDataOffset:=0;
  1913. Result:=False;
  1914. case RawRec.RecordType of
  1915. RT_LEDATA,RT_LEDATA32:
  1916. begin
  1917. Is32Bit:=RawRec.RecordType=RT_LEDATA32;
  1918. NextOfs:=RawRec.ReadIndexedRef(0,SegmentIndex);
  1919. if Is32Bit then
  1920. begin
  1921. if (NextOfs+3)>=RawRec.RecordLength then
  1922. internalerror(2015040512);
  1923. EnumeratedDataOffset := LEtoN(unaligned(PUint32(@RawRec.RawData[NextOfs{..NextOfs+3}])^));
  1924. Inc(NextOfs,4);
  1925. end
  1926. else
  1927. begin
  1928. if (NextOfs+1)>=RawRec.RecordLength then
  1929. internalerror(2015040513);
  1930. EnumeratedDataOffset := LEtoN(unaligned(PUint16(@RawRec.RawData[NextOfs{..NextOfs+1}])^));
  1931. Inc(NextOfs,2);
  1932. end;
  1933. BlockLength:=RawRec.RecordLength-NextOfs-1;
  1934. if BlockLength<0 then
  1935. internalerror(2015060501);
  1936. if BlockLength>1024 then
  1937. begin
  1938. InputError('LEDATA contains more than 1024 bytes of data');
  1939. exit;
  1940. end;
  1941. if (SegmentIndex<1) or (SegmentIndex>objdata.ObjSectionList.Count) then
  1942. begin
  1943. InputError('Segment index in LEDATA field is out of range');
  1944. exit;
  1945. end;
  1946. objsec:=TOmfObjSection(objdata.ObjSectionList[SegmentIndex-1]);
  1947. objsec.SecOptions:=objsec.SecOptions+[oso_Data];
  1948. if (objsec.Data.Size>EnumeratedDataOffset) then
  1949. begin
  1950. InputError('LEDATA enumerated data offset field out of sequence');
  1951. exit;
  1952. end;
  1953. if (EnumeratedDataOffset+BlockLength)>objsec.Size then
  1954. begin
  1955. InputError('LEDATA goes beyond the segment size declared in the SEGDEF record');
  1956. exit;
  1957. end;
  1958. objsec.Data.seek(EnumeratedDataOffset);
  1959. objsec.Data.write(RawRec.RawData[NextOfs],BlockLength);
  1960. end;
  1961. RT_LIDATA,RT_LIDATA32:
  1962. begin
  1963. InputError('LIDATA records are not supported');
  1964. exit;
  1965. end;
  1966. RT_FIXUPP,RT_FIXUPP32:
  1967. begin
  1968. FixuppWithoutLeOrLiData:=True;
  1969. { a hack, used to indicate, that we must process this record }
  1970. { (RawRec) first in the FIXUPP record processing loop that follows }
  1971. FixupRawRec:=RawRec;
  1972. end;
  1973. else
  1974. internalerror(2015040316);
  1975. end;
  1976. { also read all the FIXUPP records that may follow; }
  1977. { (FixupRawRec=RawRec) indicates that we must process RawRec first, but }
  1978. { without freeing it }
  1979. while (FixupRawRec=RawRec) or (PeekNextRecordType in [RT_FIXUPP,RT_FIXUPP32]) do
  1980. begin
  1981. if FixupRawRec<>RawRec then
  1982. begin
  1983. FixupRawRec:=TOmfRawRecord.Create;
  1984. FixupRawRec.ReadFrom(FReader);
  1985. if not FRawRecord.VerifyChecksumByte then
  1986. begin
  1987. InputError('Invalid checksum in OMF record');
  1988. FixupRawRec.Free;
  1989. exit;
  1990. end;
  1991. end;
  1992. NextOfs:=0;
  1993. Thread:=TOmfSubRecord_THREAD.Create;
  1994. Fixup:=TOmfSubRecord_FIXUP.Create;
  1995. Fixup.Is32Bit:=FixupRawRec.RecordType=RT_FIXUPP32;
  1996. Fixup.DataRecordStartOffset:=EnumeratedDataOffset;
  1997. while NextOfs<(FixupRawRec.RecordLength-1) do
  1998. begin
  1999. if (FixupRawRec.RawData[NextOfs] and $80)<>0 then
  2000. begin
  2001. { FIXUP subrecord }
  2002. if FixuppWithoutLeOrLiData then
  2003. begin
  2004. InputError('FIXUP subrecord without previous LEDATA or LIDATA record');
  2005. Fixup.Free;
  2006. Thread.Free;
  2007. if FixupRawRec<>RawRec then
  2008. FixupRawRec.Free;
  2009. exit;
  2010. end;
  2011. NextOfs:=Fixup.ReadAt(FixupRawRec,NextOfs);
  2012. Fixup.ResolveByThread(FFixupThreads);
  2013. ImportOmfFixup(objdata,objsec,Fixup);
  2014. end
  2015. else
  2016. begin
  2017. { THREAD subrecord }
  2018. NextOfs:=Thread.ReadAt(FixupRawRec,NextOfs);
  2019. Thread.ApplyTo(FFixupThreads);
  2020. end;
  2021. end;
  2022. Fixup.Free;
  2023. Thread.Free;
  2024. if FixupRawRec<>RawRec then
  2025. FixupRawRec.Free;
  2026. { always set it to null, so that we read the next record on the next }
  2027. { loop iteration (this ensures that FixupRawRec<>RawRec, without }
  2028. { freeing RawRec) }
  2029. FixupRawRec:=nil;
  2030. end;
  2031. Result:=True;
  2032. end;
  2033. function TOmfObjInput.ReadImpDef(Rec: TOmfRecord_COMENT; objdata: TObjData): Boolean;
  2034. var
  2035. ImpDefRec: TOmfRecord_COMENT_IMPDEF;
  2036. SymName: string;
  2037. begin
  2038. ImpDefRec:=TOmfRecord_COMENT_IMPDEF.Create;
  2039. ImpDefRec.DecodeFrom(Rec);
  2040. SymName:=ImpDefRec.InternalName;
  2041. if not CaseSensitiveSymbols then
  2042. SymName:=UpCase(SymName);
  2043. if ImpDefRec.ImportByOrdinal then
  2044. TOmfObjData(objdata).AddImportSymbol(MaybeAddDllExt(ImpDefRec.ModuleName),'',SymName,ImpDefRec.Ordinal,false)
  2045. else
  2046. TOmfObjData(objdata).AddImportSymbol(MaybeAddDllExt(ImpDefRec.ModuleName),ImpDefRec.Name,SymName,0,false);
  2047. Result:=True;
  2048. ImpDefRec.Free;
  2049. end;
  2050. function TOmfObjInput.ReadExpDef(Rec: TOmfRecord_COMENT; objdata: TObjData): Boolean;
  2051. var
  2052. ExpDefRec: TOmfRecord_COMENT_EXPDEF;
  2053. SymName: string;
  2054. begin
  2055. ExpDefRec:=TOmfRecord_COMENT_EXPDEF.Create;
  2056. ExpDefRec.DecodeFrom(Rec);
  2057. SymName:=ExpDefRec.InternalName;
  2058. if not CaseSensitiveSymbols then
  2059. SymName:=UpCase(SymName);
  2060. TOmfObjData(objdata).AddExportSymbol(
  2061. ExpDefRec.ExportByOrdinal,
  2062. ExpDefRec.ResidentName,
  2063. ExpDefRec.NoData,
  2064. ExpDefRec.ParmCount,
  2065. ExpDefRec.ExportedName,
  2066. SymName,
  2067. ExpDefRec.ExportOrdinal);
  2068. Result:=True;
  2069. ExpDefRec.Free;
  2070. end;
  2071. function TOmfObjInput.ImportOmfFixup(objdata: TObjData; objsec: TOmfObjSection; Fixup: TOmfSubRecord_FIXUP): Boolean;
  2072. var
  2073. reloc: TOmfRelocation;
  2074. sym: TObjSymbol;
  2075. RelocType: TObjRelocationType;
  2076. target_section: TOmfObjSection;
  2077. target_group: TObjSectionGroup;
  2078. begin
  2079. Result:=False;
  2080. { range check location }
  2081. if (Fixup.LocationOffset+Fixup.LocationSize)>objsec.Size then
  2082. begin
  2083. InputError('Fixup location exceeds the current segment boundary');
  2084. exit;
  2085. end;
  2086. { range check target datum }
  2087. case Fixup.TargetMethod of
  2088. ftmSegmentIndex:
  2089. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.ObjSectionList.Count) then
  2090. begin
  2091. InputError('Segment name index in SI(<segment name>),<displacement> fixup target is out of range');
  2092. exit;
  2093. end;
  2094. ftmSegmentIndexNoDisp:
  2095. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.ObjSectionList.Count) then
  2096. begin
  2097. InputError('Segment name index in SI(<segment name>) fixup target is out of range');
  2098. exit;
  2099. end;
  2100. ftmGroupIndex:
  2101. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.GroupsList.Count) then
  2102. begin
  2103. InputError('Group name index in GI(<group name>),<displacement> fixup target is out of range');
  2104. exit;
  2105. end;
  2106. ftmGroupIndexNoDisp:
  2107. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>objdata.GroupsList.Count) then
  2108. begin
  2109. InputError('Group name index in GI(<group name>) fixup target is out of range');
  2110. exit;
  2111. end;
  2112. ftmExternalIndex:
  2113. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  2114. begin
  2115. InputError('External symbol name index in EI(<symbol name>),<displacement> fixup target is out of range');
  2116. exit;
  2117. end;
  2118. ftmExternalIndexNoDisp:
  2119. begin
  2120. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  2121. begin
  2122. InputError('External symbol name index in EI(<symbol name>) fixup target is out of range');
  2123. exit;
  2124. end;
  2125. end;
  2126. else
  2127. ;
  2128. end;
  2129. { range check frame datum }
  2130. case Fixup.FrameMethod of
  2131. ffmSegmentIndex:
  2132. if (Fixup.FrameDatum<1) or (Fixup.FrameDatum>objdata.ObjSectionList.Count) then
  2133. begin
  2134. InputError('Segment name index in SI(<segment name>) fixup frame is out of range');
  2135. exit;
  2136. end;
  2137. ffmGroupIndex:
  2138. if (Fixup.FrameDatum<1) or (Fixup.FrameDatum>objdata.GroupsList.Count) then
  2139. begin
  2140. InputError('Group name index in GI(<group name>) fixup frame is out of range');
  2141. exit;
  2142. end;
  2143. ffmExternalIndex:
  2144. if (Fixup.TargetDatum<1) or (Fixup.TargetDatum>ExtDefs.Count) then
  2145. begin
  2146. InputError('External symbol name index in EI(<symbol name>) fixup frame is out of range');
  2147. exit;
  2148. end;
  2149. else
  2150. ;
  2151. end;
  2152. if Fixup.TargetMethod in [ftmExternalIndex,ftmExternalIndexNoDisp] then
  2153. begin
  2154. sym:=objdata.symbolref(TOmfExternalNameElement(ExtDefs[Fixup.TargetDatum-1]).Name);
  2155. RelocType:=RELOC_NONE;
  2156. case Fixup.LocationType of
  2157. fltOffset:
  2158. case Fixup.Mode of
  2159. fmSegmentRelative:
  2160. RelocType:=RELOC_ABSOLUTE16;
  2161. fmSelfRelative:
  2162. RelocType:=RELOC_RELATIVE16;
  2163. end;
  2164. fltOffset32:
  2165. case Fixup.Mode of
  2166. fmSegmentRelative:
  2167. RelocType:=RELOC_ABSOLUTE32;
  2168. fmSelfRelative:
  2169. RelocType:=RELOC_RELATIVE32;
  2170. end;
  2171. fltBase:
  2172. case Fixup.Mode of
  2173. fmSegmentRelative:
  2174. RelocType:=RELOC_SEG;
  2175. fmSelfRelative:
  2176. RelocType:=RELOC_SEGREL;
  2177. end;
  2178. fltFarPointer:
  2179. case Fixup.Mode of
  2180. fmSegmentRelative:
  2181. RelocType:=RELOC_FARPTR;
  2182. fmSelfRelative:
  2183. RelocType:=RELOC_FARPTR_RELATIVEOFFSET;
  2184. end;
  2185. fltFarPointer48:
  2186. case Fixup.Mode of
  2187. fmSegmentRelative:
  2188. RelocType:=RELOC_FARPTR48;
  2189. fmSelfRelative:
  2190. RelocType:=RELOC_FARPTR48_RELATIVEOFFSET;
  2191. end;
  2192. else
  2193. ;
  2194. end;
  2195. if RelocType=RELOC_NONE then
  2196. begin
  2197. InputError('Unsupported fixup location type '+tostr(Ord(Fixup.LocationType))+' with mode '+tostr(ord(Fixup.Mode))+' in external reference to '+sym.Name);
  2198. exit;
  2199. end;
  2200. reloc:=TOmfRelocation.CreateSymbol(Fixup.LocationOffset,sym,RelocType);
  2201. objsec.ObjRelocations.Add(reloc);
  2202. case Fixup.FrameMethod of
  2203. ffmTarget:
  2204. {nothing};
  2205. ffmGroupIndex:
  2206. reloc.FrameGroup:=TObjSectionGroup(objdata.GroupsList[Fixup.FrameDatum-1]).Name;
  2207. else
  2208. begin
  2209. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in external reference to '+sym.Name);
  2210. exit;
  2211. end;
  2212. end;
  2213. if Fixup.TargetDisplacement<>0 then
  2214. begin
  2215. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in external reference to '+sym.Name);
  2216. exit;
  2217. end;
  2218. end
  2219. else if Fixup.TargetMethod in [ftmSegmentIndex,ftmSegmentIndexNoDisp] then
  2220. begin
  2221. target_section:=TOmfObjSection(objdata.ObjSectionList[Fixup.TargetDatum-1]);
  2222. RelocType:=RELOC_NONE;
  2223. case Fixup.LocationType of
  2224. fltOffset:
  2225. case Fixup.Mode of
  2226. fmSegmentRelative:
  2227. RelocType:=RELOC_ABSOLUTE16;
  2228. fmSelfRelative:
  2229. RelocType:=RELOC_RELATIVE16;
  2230. end;
  2231. fltOffset32:
  2232. case Fixup.Mode of
  2233. fmSegmentRelative:
  2234. RelocType:=RELOC_ABSOLUTE32;
  2235. fmSelfRelative:
  2236. RelocType:=RELOC_RELATIVE32;
  2237. end;
  2238. fltBase:
  2239. case Fixup.Mode of
  2240. fmSegmentRelative:
  2241. RelocType:=RELOC_SEG;
  2242. fmSelfRelative:
  2243. RelocType:=RELOC_SEGREL;
  2244. end;
  2245. fltFarPointer:
  2246. case Fixup.Mode of
  2247. fmSegmentRelative:
  2248. RelocType:=RELOC_FARPTR;
  2249. fmSelfRelative:
  2250. RelocType:=RELOC_FARPTR_RELATIVEOFFSET;
  2251. end;
  2252. fltFarPointer48:
  2253. case Fixup.Mode of
  2254. fmSegmentRelative:
  2255. RelocType:=RELOC_FARPTR48;
  2256. fmSelfRelative:
  2257. RelocType:=RELOC_FARPTR48_RELATIVEOFFSET;
  2258. end;
  2259. else
  2260. ;
  2261. end;
  2262. if RelocType=RELOC_NONE then
  2263. begin
  2264. InputError('Unsupported fixup location type '+tostr(Ord(Fixup.LocationType))+' with mode '+tostr(ord(Fixup.Mode)));
  2265. exit;
  2266. end;
  2267. reloc:=TOmfRelocation.CreateSection(Fixup.LocationOffset,target_section,RelocType);
  2268. objsec.ObjRelocations.Add(reloc);
  2269. case Fixup.FrameMethod of
  2270. ffmTarget:
  2271. {nothing};
  2272. ffmGroupIndex:
  2273. reloc.FrameGroup:=TObjSectionGroup(objdata.GroupsList[Fixup.FrameDatum-1]).Name;
  2274. else
  2275. begin
  2276. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in reference to segment '+target_section.Name);
  2277. exit;
  2278. end;
  2279. end;
  2280. if Fixup.TargetDisplacement<>0 then
  2281. begin
  2282. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in reference to segment '+target_section.Name);
  2283. exit;
  2284. end;
  2285. end
  2286. else if Fixup.TargetMethod in [ftmGroupIndex,ftmGroupIndexNoDisp] then
  2287. begin
  2288. target_group:=TObjSectionGroup(objdata.GroupsList[Fixup.TargetDatum-1]);
  2289. RelocType:=RELOC_NONE;
  2290. case Fixup.LocationType of
  2291. fltOffset:
  2292. case Fixup.Mode of
  2293. fmSegmentRelative:
  2294. RelocType:=RELOC_ABSOLUTE16;
  2295. fmSelfRelative:
  2296. RelocType:=RELOC_RELATIVE16;
  2297. end;
  2298. fltOffset32:
  2299. case Fixup.Mode of
  2300. fmSegmentRelative:
  2301. RelocType:=RELOC_ABSOLUTE32;
  2302. fmSelfRelative:
  2303. RelocType:=RELOC_RELATIVE32;
  2304. end;
  2305. fltBase:
  2306. case Fixup.Mode of
  2307. fmSegmentRelative:
  2308. RelocType:=RELOC_SEG;
  2309. fmSelfRelative:
  2310. RelocType:=RELOC_SEGREL;
  2311. end;
  2312. fltFarPointer:
  2313. case Fixup.Mode of
  2314. fmSegmentRelative:
  2315. RelocType:=RELOC_FARPTR;
  2316. fmSelfRelative:
  2317. RelocType:=RELOC_FARPTR_RELATIVEOFFSET;
  2318. end;
  2319. fltFarPointer48:
  2320. case Fixup.Mode of
  2321. fmSegmentRelative:
  2322. RelocType:=RELOC_FARPTR48;
  2323. fmSelfRelative:
  2324. RelocType:=RELOC_FARPTR48_RELATIVEOFFSET;
  2325. end;
  2326. else
  2327. ;
  2328. end;
  2329. if RelocType=RELOC_NONE then
  2330. begin
  2331. InputError('Unsupported fixup location type '+tostr(Ord(Fixup.LocationType))+' with mode '+tostr(ord(Fixup.Mode)));
  2332. exit;
  2333. end;
  2334. reloc:=TOmfRelocation.CreateGroup(Fixup.LocationOffset,target_group,RelocType);
  2335. objsec.ObjRelocations.Add(reloc);
  2336. case Fixup.FrameMethod of
  2337. ffmTarget:
  2338. {nothing};
  2339. else
  2340. begin
  2341. InputError('Unsupported frame method '+IntToStr(Ord(Fixup.FrameMethod))+' in reference to group '+target_group.Name);
  2342. exit;
  2343. end;
  2344. end;
  2345. if Fixup.TargetDisplacement<>0 then
  2346. begin
  2347. InputError('Unsupported nonzero target displacement '+IntToStr(Fixup.TargetDisplacement)+' in reference to group '+target_group.Name);
  2348. exit;
  2349. end;
  2350. end
  2351. else
  2352. begin
  2353. {todo: convert other fixup types as well }
  2354. InputError('Unsupported fixup target method '+IntToStr(Ord(Fixup.TargetMethod)));
  2355. exit;
  2356. end;
  2357. Result:=True;
  2358. end;
  2359. constructor TOmfObjInput.create;
  2360. begin
  2361. inherited create;
  2362. cobjdata:=TOmfObjData;
  2363. FLNames:=TOmfOrderedNameCollection.Create(True);
  2364. FExtDefs:=TFPHashObjectList.Create;
  2365. FPubDefs:=TFPHashObjectList.Create;
  2366. FFixupThreads:=TOmfThreads.Create;
  2367. FRawRecord:=TOmfRawRecord.Create;
  2368. CaseSensitiveSegments:=False;
  2369. CaseSensitiveSymbols:=True;
  2370. end;
  2371. destructor TOmfObjInput.destroy;
  2372. begin
  2373. FCOMENTRecord.Free;
  2374. FRawRecord.Free;
  2375. FFixupThreads.Free;
  2376. FPubDefs.Free;
  2377. FExtDefs.Free;
  2378. FLNames.Free;
  2379. inherited destroy;
  2380. end;
  2381. class function TOmfObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  2382. var
  2383. b: Byte;
  2384. begin
  2385. result:=false;
  2386. if AReader.Read(b,sizeof(b)) then
  2387. begin
  2388. if b=RT_THEADR then
  2389. { TODO: check additional fields }
  2390. result:=true;
  2391. end;
  2392. AReader.Seek(0);
  2393. end;
  2394. function TOmfObjInput.ReadObjData(AReader: TObjectreader; out objdata: TObjData): boolean;
  2395. begin
  2396. FReader:=AReader;
  2397. InputFileName:=AReader.FileName;
  2398. objdata:=CObjData.Create(InputFileName);
  2399. result:=false;
  2400. { the TOmfObjData constructor creates a group 'DGROUP', which is to be
  2401. used by the code generator, when writing files. When reading object
  2402. files, however, we need to start with an empty list of groups, so
  2403. let's clear the group list now. }
  2404. objdata.GroupsList.Clear;
  2405. LNames.Clear;
  2406. ExtDefs.Clear;
  2407. FRawRecord.ReadFrom(FReader);
  2408. if not FRawRecord.VerifyChecksumByte then
  2409. begin
  2410. InputError('Invalid checksum in OMF record');
  2411. exit;
  2412. end;
  2413. if FRawRecord.RecordType<>RT_THEADR then
  2414. begin
  2415. InputError('Can''t read OMF header');
  2416. exit;
  2417. end;
  2418. repeat
  2419. FRawRecord.ReadFrom(FReader);
  2420. if not FRawRecord.VerifyChecksumByte then
  2421. begin
  2422. InputError('Invalid checksum in OMF record');
  2423. exit;
  2424. end;
  2425. FreeAndNil(FCOMENTRecord);
  2426. case FRawRecord.RecordType of
  2427. RT_LNAMES:
  2428. if not ReadLNames(FRawRecord) then
  2429. exit;
  2430. RT_SEGDEF,RT_SEGDEF32:
  2431. if not ReadSegDef(FRawRecord,objdata) then
  2432. exit;
  2433. RT_GRPDEF:
  2434. if not ReadGrpDef(FRawRecord,objdata) then
  2435. exit;
  2436. RT_COMENT:
  2437. begin
  2438. FCOMENTRecord:=TOmfRecord_COMENT.Create;
  2439. FCOMENTRecord.DecodeFrom(FRawRecord);
  2440. case FCOMENTRecord.CommentClass of
  2441. CC_OmfExtension:
  2442. begin
  2443. if Length(FCOMENTRecord.CommentString)>=1 then
  2444. begin
  2445. case Ord(FCOMENTRecord.CommentString[1]) of
  2446. CC_OmfExtension_IMPDEF:
  2447. if not ReadImpDef(FCOMENTRecord,objdata) then
  2448. exit;
  2449. CC_OmfExtension_EXPDEF:
  2450. if not ReadExpDef(FCOMENTRecord,objdata) then
  2451. exit;
  2452. end;
  2453. end;
  2454. end;
  2455. CC_LIBMOD:
  2456. begin
  2457. {todo: do we need to read the module name here?}
  2458. end;
  2459. CC_EXESTR:
  2460. begin
  2461. InputError('EXESTR record (Executable String Record) is not supported');
  2462. exit;
  2463. end;
  2464. CC_INCERR:
  2465. begin
  2466. InputError('Invalid object file (contains indication of error encountered during incremental compilation)');
  2467. exit;
  2468. end;
  2469. CC_NOPAD:
  2470. begin
  2471. InputError('NOPAD (No Segment Padding) record is not supported');
  2472. exit;
  2473. end;
  2474. CC_WKEXT:
  2475. begin
  2476. InputError('Weak externals are not supported');
  2477. exit;
  2478. end;
  2479. CC_LZEXT:
  2480. begin
  2481. InputError('Lazy externals are not supported');
  2482. exit;
  2483. end;
  2484. else
  2485. begin
  2486. {the rest are ignored for now...}
  2487. end;
  2488. end;
  2489. end;
  2490. RT_EXTDEF:
  2491. if not ReadExtDef(FRawRecord,objdata) then
  2492. exit;
  2493. RT_LPUBDEF,RT_LPUBDEF32,
  2494. RT_PUBDEF,RT_PUBDEF32:
  2495. if not ReadPubDef(FRawRecord,objdata) then
  2496. exit;
  2497. RT_LEDATA,RT_LEDATA32,
  2498. RT_LIDATA,RT_LIDATA32,
  2499. RT_FIXUPP,RT_FIXUPP32:
  2500. if not ReadLeOrLiDataAndFixups(FRawRecord,objdata) then
  2501. exit;
  2502. RT_MODEND,RT_MODEND32:
  2503. if not ReadModEnd(FRawRecord,objdata) then
  2504. exit;
  2505. RT_LINNUM,RT_LINNUM32:
  2506. ;
  2507. else
  2508. begin
  2509. InputError('Unsupported OMF record type $'+HexStr(FRawRecord.RecordType,2));
  2510. exit;
  2511. end;
  2512. end;
  2513. until FRawRecord.RecordType in [RT_MODEND,RT_MODEND32];
  2514. result:=true;
  2515. end;
  2516. {****************************************************************************
  2517. TMZExeHeader
  2518. ****************************************************************************}
  2519. procedure TMZExeHeader.SetHeaderSizeAlignment(AValue: Integer);
  2520. begin
  2521. if (AValue<16) or ((AValue mod 16) <> 0) then
  2522. Internalerror(2015060601);
  2523. FHeaderSizeAlignment:=AValue;
  2524. end;
  2525. constructor TMZExeHeader.Create;
  2526. begin
  2527. FHeaderSizeAlignment:=16;
  2528. end;
  2529. procedure TMZExeHeader.WriteTo(aWriter: TObjectWriter);
  2530. var
  2531. NumRelocs: Word;
  2532. HeaderSizeInBytes: DWord;
  2533. HeaderParagraphs: Word;
  2534. RelocTableOffset: Word;
  2535. BytesInLastBlock: Word;
  2536. BlocksInFile: Word;
  2537. HeaderBytes: array [0..$1B] of Byte;
  2538. RelocBytes: array [0..3] of Byte;
  2539. TotalExeSize: DWord;
  2540. i: Integer;
  2541. begin
  2542. NumRelocs:=Length(Relocations);
  2543. RelocTableOffset:=$1C+Length(ExtraHeaderData);
  2544. HeaderSizeInBytes:=Align(RelocTableOffset+4*NumRelocs,16);
  2545. HeaderParagraphs:=HeaderSizeInBytes div 16;
  2546. TotalExeSize:=HeaderSizeInBytes+LoadableImageSize;
  2547. BlocksInFile:=(TotalExeSize+511) div 512;
  2548. BytesInLastBlock:=TotalExeSize mod 512;
  2549. HeaderBytes[$00]:=$4D; { 'M' }
  2550. HeaderBytes[$01]:=$5A; { 'Z' }
  2551. unaligned(PUint16(@HeaderBytes[$02{..$03}])^):=NtoLE(uint16(BytesInLastBlock));
  2552. unaligned(PUint16(@HeaderBytes[$04{..$05}])^):=NtoLE(uint16(BlocksInFile));
  2553. unaligned(PUint16(@HeaderBytes[$06{..$07}])^):=NtoLE(uint16(NumRelocs));
  2554. unaligned(PUint16(@HeaderBytes[$08{..$09}])^):=NtoLE(uint16(HeaderParagraphs));
  2555. unaligned(PUint16(@HeaderBytes[$0A{..$0B}])^):=NtoLE(uint16(MinExtraParagraphs));
  2556. unaligned(PUint16(@HeaderBytes[$0C{..$0D}])^):=NtoLE(uint16(MaxExtraParagraphs));
  2557. unaligned(PUint16(@HeaderBytes[$0E{..$0F}])^):=NtoLE(uint16(InitialSS));
  2558. unaligned(PUint16(@HeaderBytes[$10{..$11}])^):=NtoLE(uint16(InitialSP));
  2559. unaligned(PUint16(@HeaderBytes[$12{..$13}])^):=NtoLE(uint16(Checksum));
  2560. unaligned(PUint16(@HeaderBytes[$14{..$15}])^):=NtoLE(uint16(InitialIP));
  2561. unaligned(PUint16(@HeaderBytes[$16{..$17}])^):=NtoLE(uint16(InitialCS));
  2562. unaligned(PUint16(@HeaderBytes[$18{..$19}])^):=NtoLE(uint16(RelocTableOffset));
  2563. unaligned(PUint16(@HeaderBytes[$1A{..$1B}])^):=NtoLE(uint16(OverlayNumber));
  2564. aWriter.write(HeaderBytes[0],$1C);
  2565. aWriter.write(ExtraHeaderData[0],Length(ExtraHeaderData));
  2566. for i:=0 to NumRelocs-1 do
  2567. with Relocations[i] do
  2568. begin
  2569. unaligned(PUint16(@RelocBytes[0{..1}])^):=NtoLE(uint16(offset));
  2570. unaligned(PUint16(@RelocBytes[2{..3}])^):=NtoLE(uint16(segment));
  2571. aWriter.write(RelocBytes[0],4);
  2572. end;
  2573. { pad with zeros until the end of header (paragraph aligned) }
  2574. aWriter.WriteZeros(HeaderSizeInBytes-aWriter.Size);
  2575. end;
  2576. procedure TMZExeHeader.AddRelocation(aSegment, aOffset: Word);
  2577. begin
  2578. SetLength(FRelocations,Length(FRelocations)+1);
  2579. with FRelocations[High(FRelocations)] do
  2580. begin
  2581. segment:=aSegment;
  2582. offset:=aOffset;
  2583. end;
  2584. end;
  2585. {****************************************************************************
  2586. TMZExeSection
  2587. ****************************************************************************}
  2588. procedure TMZExeSection.AddObjSection(objsec: TObjSection; ignoreprops: boolean);
  2589. begin
  2590. { allow mixing initialized and uninitialized data in the same section
  2591. => set ignoreprops=true }
  2592. inherited AddObjSection(objsec,true);
  2593. end;
  2594. {****************************************************************************
  2595. TMZExeUnifiedLogicalSegment
  2596. ****************************************************************************}
  2597. constructor TMZExeUnifiedLogicalSegment.create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  2598. var
  2599. Separator: SizeInt;
  2600. begin
  2601. inherited create(HashObjectList,s);
  2602. FObjSectionList:=TFPObjectList.Create(false);
  2603. { name format is 'SegName||ClassName' }
  2604. Separator:=Pos('||',s);
  2605. if Separator>0 then
  2606. begin
  2607. FSegName:=Copy(s,1,Separator-1);
  2608. FSegClass:=Copy(s,Separator+2,Length(s)-Separator-1);
  2609. end
  2610. else
  2611. begin
  2612. FSegName:=Name;
  2613. FSegClass:='';
  2614. end;
  2615. { wlink recognizes the stack segment by the class name 'STACK' }
  2616. { let's be compatible with wlink }
  2617. IsStack:=FSegClass='STACK';
  2618. end;
  2619. destructor TMZExeUnifiedLogicalSegment.destroy;
  2620. begin
  2621. FObjSectionList.Free;
  2622. inherited destroy;
  2623. end;
  2624. procedure TMZExeUnifiedLogicalSegment.AddObjSection(ObjSec: TOmfObjSection);
  2625. begin
  2626. ObjSectionList.Add(ObjSec);
  2627. ObjSec.MZExeUnifiedLogicalSegment:=self;
  2628. { tlink (and ms link?) use the scStack segment combination to recognize
  2629. the stack segment.
  2630. let's be compatible with tlink as well }
  2631. if ObjSec.Combination=scStack then
  2632. IsStack:=True;
  2633. end;
  2634. procedure TMZExeUnifiedLogicalSegment.CalcMemPos;
  2635. var
  2636. MinMemPos: qword=high(qword);
  2637. MaxMemPos: qword=0;
  2638. objsec: TOmfObjSection;
  2639. i: Integer;
  2640. begin
  2641. if ObjSectionList.Count=0 then
  2642. internalerror(2015082201);
  2643. for i:=0 to ObjSectionList.Count-1 do
  2644. begin
  2645. objsec:=TOmfObjSection(ObjSectionList[i]);
  2646. if objsec.MemPos<MinMemPos then
  2647. MinMemPos:=objsec.MemPos;
  2648. if (objsec.MemPos+objsec.Size)>MaxMemPos then
  2649. MaxMemPos:=objsec.MemPos+objsec.Size;
  2650. end;
  2651. MemPos:=MinMemPos;
  2652. Size:=MaxMemPos-MemPos;
  2653. end;
  2654. function TMZExeUnifiedLogicalSegment.MemPosStr: string;
  2655. begin
  2656. Result:=HexStr(MemBasePos shr 4,4)+':'+HexStr((MemPos-MemBasePos),4);
  2657. end;
  2658. {****************************************************************************
  2659. TMZExeUnifiedLogicalGroup
  2660. ****************************************************************************}
  2661. constructor TMZExeUnifiedLogicalGroup.create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  2662. begin
  2663. inherited create(HashObjectList,s);
  2664. FSegmentList:=TFPHashObjectList.Create(false);
  2665. end;
  2666. destructor TMZExeUnifiedLogicalGroup.destroy;
  2667. begin
  2668. FSegmentList.Free;
  2669. inherited destroy;
  2670. end;
  2671. procedure TMZExeUnifiedLogicalGroup.CalcMemPos;
  2672. var
  2673. MinMemPos: qword=high(qword);
  2674. MaxMemPos: qword=0;
  2675. UniSeg: TMZExeUnifiedLogicalSegment;
  2676. i: Integer;
  2677. begin
  2678. if SegmentList.Count=0 then
  2679. internalerror(2015082202);
  2680. for i:=0 to SegmentList.Count-1 do
  2681. begin
  2682. UniSeg:=TMZExeUnifiedLogicalSegment(SegmentList[i]);
  2683. if UniSeg.MemPos<MinMemPos then
  2684. MinMemPos:=UniSeg.MemPos;
  2685. if (UniSeg.MemPos+UniSeg.Size)>MaxMemPos then
  2686. MaxMemPos:=UniSeg.MemPos+UniSeg.Size;
  2687. end;
  2688. { align *down* on a paragraph boundary }
  2689. MemPos:=(MinMemPos shr 4) shl 4;
  2690. Size:=MaxMemPos-MemPos;
  2691. end;
  2692. function TMZExeUnifiedLogicalGroup.MemPosStr: string;
  2693. begin
  2694. Result:=HexStr(MemPos shr 4,4)+':'+HexStr(MemPos and $f,4);
  2695. end;
  2696. procedure TMZExeUnifiedLogicalGroup.AddSegment(UniSeg: TMZExeUnifiedLogicalSegment);
  2697. begin
  2698. SegmentList.Add(UniSeg.Name,UniSeg);
  2699. if UniSeg.PrimaryGroup='' then
  2700. UniSeg.PrimaryGroup:=Name;
  2701. end;
  2702. {****************************************************************************
  2703. TMZExeOutput
  2704. ****************************************************************************}
  2705. function TMZExeOutput.GetMZFlatContentSection: TMZExeSection;
  2706. begin
  2707. if not assigned(FMZFlatContentSection) then
  2708. FMZFlatContentSection:=TMZExeSection(FindExeSection('.MZ_flat_content'));
  2709. result:=FMZFlatContentSection;
  2710. end;
  2711. procedure TMZExeOutput.CalcDwarfUnifiedLogicalSegmentsForSection(const SecName: TSymStr);
  2712. var
  2713. ExeSec: TMZExeSection;
  2714. ObjSec: TOmfObjSection;
  2715. UniSeg: TMZExeUnifiedLogicalSegment;
  2716. i: Integer;
  2717. begin
  2718. ExeSec:=TMZExeSection(FindExeSection(SecName));
  2719. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2720. begin
  2721. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2722. UniSeg:=TMZExeUnifiedLogicalSegment(DwarfUnifiedLogicalSegments.Find(ObjSec.Name));
  2723. if not assigned(UniSeg) then
  2724. begin
  2725. UniSeg:=TMZExeUnifiedLogicalSegment.Create(DwarfUnifiedLogicalSegments,ObjSec.Name);
  2726. UniSeg.MemPos:=0;
  2727. end;
  2728. UniSeg.AddObjSection(ObjSec);
  2729. end;
  2730. for i:=0 to DwarfUnifiedLogicalSegments.Count-1 do
  2731. begin
  2732. UniSeg:=TMZExeUnifiedLogicalSegment(DwarfUnifiedLogicalSegments[i]);
  2733. UniSeg.CalcMemPos;
  2734. end;
  2735. end;
  2736. procedure TMZExeOutput.CalcExeUnifiedLogicalSegments;
  2737. var
  2738. ExeSec: TMZExeSection;
  2739. ObjSec: TOmfObjSection;
  2740. UniSeg: TMZExeUnifiedLogicalSegment;
  2741. i: Integer;
  2742. begin
  2743. ExeSec:=MZFlatContentSection;
  2744. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2745. begin
  2746. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2747. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments.Find(ObjSec.Name));
  2748. if not assigned(UniSeg) then
  2749. UniSeg:=TMZExeUnifiedLogicalSegment.Create(ExeUnifiedLogicalSegments,ObjSec.Name);
  2750. UniSeg.AddObjSection(ObjSec);
  2751. end;
  2752. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2753. begin
  2754. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2755. UniSeg.CalcMemPos;
  2756. if UniSeg.Size>$10000 then
  2757. begin
  2758. if current_settings.x86memorymodel=mm_tiny then
  2759. Message1(link_e_program_segment_too_large,IntToStr(UniSeg.Size-$10000))
  2760. else if UniSeg.SegClass='CODE' then
  2761. Message2(link_e_code_segment_too_large,UniSeg.SegName,IntToStr(UniSeg.Size-$10000))
  2762. else if UniSeg.SegClass='DATA' then
  2763. Message2(link_e_data_segment_too_large,UniSeg.SegName,IntToStr(UniSeg.Size-$10000))
  2764. else
  2765. Message2(link_e_segment_too_large,UniSeg.SegName,IntToStr(UniSeg.Size-$10000)+' '+UniSeg.SegName);
  2766. end;
  2767. end;
  2768. end;
  2769. procedure TMZExeOutput.CalcExeGroups;
  2770. procedure AddToGroup(UniSeg:TMZExeUnifiedLogicalSegment;GroupName:TSymStr);
  2771. var
  2772. Group: TMZExeUnifiedLogicalGroup;
  2773. begin
  2774. Group:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(GroupName));
  2775. if not assigned(Group) then
  2776. Group:=TMZExeUnifiedLogicalGroup.Create(ExeUnifiedLogicalGroups,GroupName);
  2777. Group.AddSegment(UniSeg);
  2778. end;
  2779. var
  2780. objdataidx,groupidx,secidx: Integer;
  2781. ObjData: TObjData;
  2782. ObjGroup: TObjSectionGroup;
  2783. ObjSec: TOmfObjSection;
  2784. UniGrp: TMZExeUnifiedLogicalGroup;
  2785. begin
  2786. for objdataidx:=0 to ObjDataList.Count-1 do
  2787. begin
  2788. ObjData:=TObjData(ObjDataList[objdataidx]);
  2789. if assigned(ObjData.GroupsList) then
  2790. for groupidx:=0 to ObjData.GroupsList.Count-1 do
  2791. begin
  2792. ObjGroup:=TObjSectionGroup(ObjData.GroupsList[groupidx]);
  2793. for secidx:=low(ObjGroup.members) to high(ObjGroup.members) do
  2794. begin
  2795. ObjSec:=TOmfObjSection(ObjGroup.members[secidx]);
  2796. if assigned(ObjSec.MZExeUnifiedLogicalSegment) then
  2797. AddToGroup(ObjSec.MZExeUnifiedLogicalSegment,ObjGroup.Name);
  2798. end;
  2799. end;
  2800. end;
  2801. for groupidx:=0 to ExeUnifiedLogicalGroups.Count-1 do
  2802. begin
  2803. UniGrp:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups[groupidx]);
  2804. UniGrp.CalcMemPos;
  2805. if UniGrp.Size>$10000 then
  2806. begin
  2807. if current_settings.x86memorymodel=mm_tiny then
  2808. Message1(link_e_program_segment_too_large,IntToStr(UniGrp.Size-$10000))
  2809. else if UniGrp.Name='DGROUP' then
  2810. Message2(link_e_data_segment_too_large,UniGrp.Name,IntToStr(UniGrp.Size-$10000))
  2811. else
  2812. Message2(link_e_group_too_large,UniGrp.Name,IntToStr(UniGrp.Size-$10000));
  2813. end;
  2814. end;
  2815. end;
  2816. procedure TMZExeOutput.CalcSegments_MemBasePos;
  2817. var
  2818. lastbase:qword=0;
  2819. i: Integer;
  2820. UniSeg: TMZExeUnifiedLogicalSegment;
  2821. begin
  2822. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2823. begin
  2824. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2825. if (UniSeg.PrimaryGroup<>'') or (UniSeg.IsStack) or
  2826. (((UniSeg.MemPos+UniSeg.Size-1)-lastbase)>$ffff) then
  2827. lastbase:=(UniSeg.MemPos shr 4) shl 4;
  2828. UniSeg.MemBasePos:=lastbase;
  2829. end;
  2830. end;
  2831. procedure TMZExeOutput.WriteMap_SegmentsAndGroups;
  2832. var
  2833. i, LongestGroupName, LongestSegmentName, LongestClassName: Integer;
  2834. UniSeg: TMZExeUnifiedLogicalSegment;
  2835. UniGrp: TMZExeUnifiedLogicalGroup;
  2836. GroupColumnSize, SegmentColumnSize, ClassColumnSize: LongInt;
  2837. begin
  2838. LongestGroupName:=0;
  2839. for i:=0 to ExeUnifiedLogicalGroups.Count-1 do
  2840. begin
  2841. UniGrp:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups[i]);
  2842. LongestGroupName:=max(LongestGroupName,Length(UniGrp.Name));
  2843. end;
  2844. LongestSegmentName:=0;
  2845. LongestClassName:=0;
  2846. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2847. begin
  2848. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2849. LongestSegmentName:=max(LongestSegmentName,Length(UniSeg.SegName));
  2850. LongestClassName:=max(LongestClassName,Length(UniSeg.SegClass));
  2851. end;
  2852. GroupColumnSize:=max(32,LongestGroupName+1);
  2853. SegmentColumnSize:=max(23,LongestSegmentName+1);
  2854. ClassColumnSize:=max(15,LongestClassName+1);
  2855. exemap.AddHeader('Groups list');
  2856. exemap.Add('');
  2857. exemap.Add(PadSpace('Group',GroupColumnSize)+PadSpace('Address',21)+'Size');
  2858. exemap.Add(PadSpace('=====',GroupColumnSize)+PadSpace('=======',21)+'====');
  2859. exemap.Add('');
  2860. for i:=0 to ExeUnifiedLogicalGroups.Count-1 do
  2861. begin
  2862. UniGrp:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups[i]);
  2863. exemap.Add(PadSpace(UniGrp.Name,GroupColumnSize)+PadSpace(UniGrp.MemPosStr,21)+HexStr(UniGrp.Size,8));
  2864. end;
  2865. exemap.Add('');
  2866. GroupColumnSize:=max(15,LongestGroupName+1);
  2867. exemap.AddHeader('Segments list');
  2868. exemap.Add('');
  2869. exemap.Add(PadSpace('Segment',SegmentColumnSize)+PadSpace('Class',ClassColumnSize)+PadSpace('Group',GroupColumnSize)+PadSpace('Address',16)+'Size');
  2870. exemap.Add(PadSpace('=======',SegmentColumnSize)+PadSpace('=====',ClassColumnSize)+PadSpace('=====',GroupColumnSize)+PadSpace('=======',16)+'====');
  2871. exemap.Add('');
  2872. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2873. begin
  2874. UniSeg:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2875. exemap.Add(PadSpace(UniSeg.SegName,SegmentColumnSize)+PadSpace(UniSeg.SegClass,ClassColumnSize)+PadSpace(UniSeg.PrimaryGroup,GroupColumnSize)+PadSpace(UniSeg.MemPosStr,16)+HexStr(UniSeg.Size,8));
  2876. end;
  2877. exemap.Add('');
  2878. end;
  2879. procedure TMZExeOutput.WriteMap_HeaderData;
  2880. begin
  2881. exemap.AddHeader('Header data');
  2882. exemap.Add('Loadable image size: '+HexStr(Header.LoadableImageSize,8));
  2883. exemap.Add('Min extra paragraphs: '+HexStr(Header.MinExtraParagraphs,4));
  2884. exemap.Add('Max extra paragraphs: '+HexStr(Header.MaxExtraParagraphs,4));
  2885. exemap.Add('Initial stack pointer: '+HexStr(Header.InitialSS,4)+':'+HexStr(Header.InitialSP,4));
  2886. exemap.Add('Entry point address: '+HexStr(Header.InitialCS,4)+':'+HexStr(Header.InitialIP,4));
  2887. end;
  2888. function TMZExeOutput.FindStackSegment: TMZExeUnifiedLogicalSegment;
  2889. var
  2890. i: Integer;
  2891. stackseg_wannabe: TMZExeUnifiedLogicalSegment;
  2892. begin
  2893. Result:=nil;
  2894. for i:=0 to ExeUnifiedLogicalSegments.Count-1 do
  2895. begin
  2896. stackseg_wannabe:=TMZExeUnifiedLogicalSegment(ExeUnifiedLogicalSegments[i]);
  2897. { if there are multiple stack segments, choose the largest one.
  2898. In theory, we're probably supposed to combine them all and put
  2899. them in a contiguous location in memory, but we don't care }
  2900. if stackseg_wannabe.IsStack and
  2901. (not assigned(result) or (Result.Size<stackseg_wannabe.Size)) then
  2902. Result:=stackseg_wannabe;
  2903. end;
  2904. end;
  2905. procedure TMZExeOutput.FillLoadableImageSize;
  2906. var
  2907. i: Integer;
  2908. ExeSec: TMZExeSection;
  2909. ObjSec: TOmfObjSection;
  2910. begin
  2911. Header.LoadableImageSize:=0;
  2912. ExeSec:=MZFlatContentSection;
  2913. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2914. begin
  2915. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2916. if (ObjSec.Size>0) and assigned(ObjSec.Data) then
  2917. if (ObjSec.MemPos+ObjSec.Size)>Header.LoadableImageSize then
  2918. Header.LoadableImageSize:=ObjSec.MemPos+ObjSec.Size;
  2919. end;
  2920. end;
  2921. procedure TMZExeOutput.FillMinExtraParagraphs;
  2922. var
  2923. ExeSec: TMZExeSection;
  2924. begin
  2925. ExeSec:=MZFlatContentSection;
  2926. Header.MinExtraParagraphs:=(align(ExeSec.Size,16)-align(Header.LoadableImageSize,16)) div 16;
  2927. end;
  2928. procedure TMZExeOutput.FillMaxExtraParagraphs;
  2929. var
  2930. heapmin_paragraphs: Integer;
  2931. heapmax_paragraphs: Integer;
  2932. begin
  2933. if current_settings.x86memorymodel in x86_far_data_models then
  2934. begin
  2935. { calculate the additional number of paragraphs needed }
  2936. heapmin_paragraphs:=(heapsize + 15) div 16;
  2937. heapmax_paragraphs:=(maxheapsize + 15) div 16;
  2938. Header.MaxExtraParagraphs:=min(Header.MinExtraParagraphs-heapmin_paragraphs+heapmax_paragraphs,$FFFF);
  2939. end
  2940. else
  2941. Header.MaxExtraParagraphs:=$FFFF;
  2942. end;
  2943. procedure TMZExeOutput.FillStartAddress;
  2944. var
  2945. EntryMemPos: qword;
  2946. EntryMemBasePos: qword;
  2947. begin
  2948. EntryMemPos:=EntrySym.address;
  2949. if assigned(EntrySym.group) then
  2950. EntryMemBasePos:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(EntrySym.group.Name)).MemPos
  2951. else
  2952. EntryMemBasePos:=TOmfObjSection(EntrySym.objsection).MZExeUnifiedLogicalSegment.MemBasePos;
  2953. Header.InitialIP:=EntryMemPos-EntryMemBasePos;
  2954. Header.InitialCS:=EntryMemBasePos shr 4;
  2955. end;
  2956. procedure TMZExeOutput.FillStackAddress;
  2957. var
  2958. stackseg: TMZExeUnifiedLogicalSegment;
  2959. begin
  2960. stackseg:=FindStackSegment;
  2961. if assigned(stackseg) then
  2962. begin
  2963. Header.InitialSS:=stackseg.MemBasePos shr 4;
  2964. Header.InitialSP:=stackseg.MemPos+stackseg.Size-stackseg.MemBasePos;
  2965. end
  2966. else
  2967. begin
  2968. Header.InitialSS:=0;
  2969. Header.InitialSP:=0;
  2970. end;
  2971. end;
  2972. procedure TMZExeOutput.FillHeaderData;
  2973. begin
  2974. Header.MaxExtraParagraphs:=$FFFF;
  2975. FillLoadableImageSize;
  2976. FillMinExtraParagraphs;
  2977. FillMaxExtraParagraphs;
  2978. FillStartAddress;
  2979. FillStackAddress;
  2980. if assigned(exemap) then
  2981. WriteMap_HeaderData;
  2982. end;
  2983. function TMZExeOutput.writeExe: boolean;
  2984. var
  2985. ExeSec: TMZExeSection;
  2986. i: Integer;
  2987. ObjSec: TOmfObjSection;
  2988. begin
  2989. Result:=False;
  2990. FillHeaderData;
  2991. Header.WriteTo(FWriter);
  2992. ExeSec:=MZFlatContentSection;
  2993. ExeSec.DataPos:=FWriter.Size;
  2994. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  2995. begin
  2996. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  2997. if ObjSec.MemPos<Header.LoadableImageSize then
  2998. begin
  2999. FWriter.WriteZeros(max(0,ObjSec.MemPos-FWriter.Size+ExeSec.DataPos));
  3000. if assigned(ObjSec.Data) then
  3001. FWriter.writearray(ObjSec.Data);
  3002. end;
  3003. end;
  3004. Result:=True;
  3005. end;
  3006. function TMZExeOutput.writeCom: boolean;
  3007. const
  3008. ComFileOffset=$100;
  3009. var
  3010. i: Integer;
  3011. ExeSec: TMZExeSection;
  3012. ObjSec: TOmfObjSection;
  3013. buf: array [0..1023] of byte;
  3014. bytesread: LongWord;
  3015. begin
  3016. FillHeaderData;
  3017. if Length(Header.Relocations)>0 then
  3018. begin
  3019. Message(link_e_com_program_uses_segment_relocations);
  3020. exit(False);
  3021. end;
  3022. ExeSec:=MZFlatContentSection;
  3023. for i:=0 to ExeSec.ObjSectionList.Count-1 do
  3024. begin
  3025. ObjSec:=TOmfObjSection(ExeSec.ObjSectionList[i]);
  3026. if ObjSec.MemPos<Header.LoadableImageSize then
  3027. begin
  3028. FWriter.WriteZeros(max(0,int64(ObjSec.MemPos)-ComFileOffset-int64(FWriter.Size)));
  3029. if assigned(ObjSec.Data) then
  3030. begin
  3031. if ObjSec.MemPos<ComFileOffset then
  3032. begin
  3033. ObjSec.Data.seek(ComFileOffset-ObjSec.MemPos);
  3034. repeat
  3035. bytesread:=ObjSec.Data.read(buf,sizeof(buf));
  3036. if bytesread<>0 then
  3037. FWriter.write(buf,bytesread);
  3038. until bytesread=0;
  3039. end
  3040. else
  3041. FWriter.writearray(ObjSec.Data);
  3042. end;
  3043. end;
  3044. end;
  3045. Result:=True;
  3046. end;
  3047. function TMZExeOutput.writeDebugElf: boolean;
  3048. label
  3049. cleanup;
  3050. var
  3051. debugsections: array of TMZExeSection;
  3052. debugsections_count: Word;
  3053. elfsections_count: Word;
  3054. elfsechdrs: array of TElf32sechdr;
  3055. shstrndx: Word;
  3056. next_section_ofs, elf_start_pos, elf_end_pos: LongWord;
  3057. ElfHeader: TElf32header;
  3058. shstrtabsect_data: TDynamicArray=Nil;
  3059. I, elfsecidx, J: Integer;
  3060. ObjSec: TOmfObjSection;
  3061. tis_trailer: TTISTrailer;
  3062. begin
  3063. debugsections:=nil;
  3064. elfsechdrs:=nil;
  3065. { mark the offset of the start of the ELF image }
  3066. elf_start_pos:=Writer.Size;
  3067. { count the debug sections }
  3068. debugsections_count:=0;
  3069. for I:=0 to ExeSectionList.Count-1 do
  3070. if oso_debug in TMZExeSection(ExeSectionList[I]).SecOptions then
  3071. Inc(debugsections_count);
  3072. { extract them into the debugsections array }
  3073. SetLength(debugsections,debugsections_count);
  3074. debugsections_count:=0;
  3075. for I:=0 to ExeSectionList.Count-1 do
  3076. if oso_debug in TMZExeSection(ExeSectionList[I]).SecOptions then
  3077. begin
  3078. debugsections[debugsections_count]:=TMZExeSection(ExeSectionList[I]);
  3079. Inc(debugsections_count);
  3080. end;
  3081. { prepare/allocate elf section headers }
  3082. elfsections_count:=debugsections_count+2;
  3083. SetLength(elfsechdrs,elfsections_count);
  3084. for I:=0 to elfsections_count-1 do
  3085. FillChar(elfsechdrs[I],SizeOf(elfsechdrs[I]),0);
  3086. shstrndx:=elfsections_count-1;
  3087. shstrtabsect_data:=tdynamicarray.Create(SectionDataMaxGrow);
  3088. shstrtabsect_data.writestr(#0);
  3089. next_section_ofs:=SizeOf(ElfHeader)+elfsections_count*SizeOf(TElf32sechdr);
  3090. for I:=0 to debugsections_count-1 do
  3091. begin
  3092. elfsecidx:=I+1;
  3093. with elfsechdrs[elfsecidx] do
  3094. begin
  3095. sh_name:=shstrtabsect_data.Pos;
  3096. sh_type:=SHT_PROGBITS;
  3097. sh_flags:=0;
  3098. sh_addr:=0;
  3099. sh_offset:=next_section_ofs;
  3100. sh_size:=debugsections[I].Size;
  3101. sh_link:=0;
  3102. sh_info:=0;
  3103. sh_addralign:=0;
  3104. sh_entsize:=0;
  3105. end;
  3106. Inc(next_section_ofs,debugsections[I].Size);
  3107. shstrtabsect_data.writestr(debugsections[I].Name+#0);
  3108. end;
  3109. with elfsechdrs[shstrndx] do
  3110. begin
  3111. sh_name:=shstrtabsect_data.Pos;
  3112. shstrtabsect_data.writestr('.shstrtab'#0);
  3113. sh_type:=SHT_STRTAB;
  3114. sh_flags:=0;
  3115. sh_addr:=0;
  3116. sh_offset:=next_section_ofs;
  3117. sh_size:=shstrtabsect_data.Size;
  3118. sh_link:=0;
  3119. sh_info:=0;
  3120. sh_addralign:=0;
  3121. sh_entsize:=0;
  3122. end;
  3123. { write header }
  3124. FillChar(ElfHeader,SizeOf(ElfHeader),0);
  3125. ElfHeader.e_ident[EI_MAG0]:=ELFMAG0; { = #127'ELF' }
  3126. ElfHeader.e_ident[EI_MAG1]:=ELFMAG1;
  3127. ElfHeader.e_ident[EI_MAG2]:=ELFMAG2;
  3128. ElfHeader.e_ident[EI_MAG3]:=ELFMAG3;
  3129. ElfHeader.e_ident[EI_CLASS]:=ELFCLASS32;
  3130. ElfHeader.e_ident[EI_DATA]:=ELFDATA2LSB;
  3131. ElfHeader.e_ident[EI_VERSION]:=1;
  3132. ElfHeader.e_ident[EI_OSABI]:=ELFOSABI_NONE;
  3133. ElfHeader.e_ident[EI_ABIVERSION]:=0;
  3134. ElfHeader.e_type:=ET_EXEC;
  3135. ElfHeader.e_machine:=EM_386;
  3136. ElfHeader.e_version:=1;
  3137. ElfHeader.e_entry:=0;
  3138. ElfHeader.e_phoff:=0;
  3139. ElfHeader.e_shoff:=SizeOf(ElfHeader);
  3140. ElfHeader.e_flags:=0;
  3141. ElfHeader.e_ehsize:=SizeOf(ElfHeader);
  3142. ElfHeader.e_phentsize:=SizeOf(TElf32proghdr);
  3143. ElfHeader.e_phnum:=0;
  3144. ElfHeader.e_shentsize:=SizeOf(TElf32sechdr);
  3145. ElfHeader.e_shnum:=elfsections_count;
  3146. ElfHeader.e_shstrndx:=shstrndx;
  3147. MaybeSwapHeader(ElfHeader);
  3148. Writer.write(ElfHeader,sizeof(ElfHeader));
  3149. { write section headers }
  3150. for I:=0 to elfsections_count-1 do
  3151. begin
  3152. MaybeSwapSecHeader(elfsechdrs[I]);
  3153. Writer.write(elfsechdrs[I],SizeOf(elfsechdrs[I]));
  3154. end;
  3155. { write section data }
  3156. for J:=0 to debugsections_count-1 do
  3157. begin
  3158. debugsections[J].DataPos:=Writer.Size;
  3159. for i:=0 to debugsections[J].ObjSectionList.Count-1 do
  3160. begin
  3161. ObjSec:=TOmfObjSection(debugsections[J].ObjSectionList[i]);
  3162. if assigned(ObjSec.Data) then
  3163. FWriter.writearray(ObjSec.Data);
  3164. end;
  3165. end;
  3166. { write .shstrtab section data }
  3167. Writer.writearray(shstrtabsect_data);
  3168. { mark the offset past the end of the ELF image }
  3169. elf_end_pos:=Writer.Size;
  3170. { write TIS trailer (not part of the ELF image) }
  3171. FillChar(tis_trailer,sizeof(tis_trailer),0);
  3172. with tis_trailer do
  3173. begin
  3174. tis_signature:=TIS_TRAILER_SIGNATURE;
  3175. tis_vendor:=TIS_TRAILER_VENDOR_TIS;
  3176. tis_type:=TIS_TRAILER_TYPE_TIS_DWARF;
  3177. tis_size:=(elf_end_pos-elf_start_pos)+sizeof(tis_trailer);
  3178. end;
  3179. MayBeSwapTISTrailer(tis_trailer);
  3180. Writer.write(tis_trailer,sizeof(tis_trailer));
  3181. Result:=True;
  3182. cleanup:
  3183. shstrtabsect_data.Free;
  3184. end;
  3185. procedure TMZExeOutput.Load_Symbol(const aname: string);
  3186. var
  3187. dgroup: TObjSectionGroup;
  3188. sym: TObjSymbol;
  3189. begin
  3190. { special handling for the '_edata' and '_end' symbols, which are
  3191. internally added by the linker }
  3192. if (aname='_edata') or (aname='_end') then
  3193. begin
  3194. { create an internal segment with the 'BSS' class }
  3195. internalObjData.createsection('*'+aname+'||BSS',0,[]);
  3196. { add to group 'DGROUP' }
  3197. dgroup:=nil;
  3198. if assigned(internalObjData.GroupsList) then
  3199. dgroup:=TObjSectionGroup(internalObjData.GroupsList.Find('DGROUP'));
  3200. if dgroup=nil then
  3201. dgroup:=internalObjData.createsectiongroup('DGROUP');
  3202. SetLength(dgroup.members,Length(dgroup.members)+1);
  3203. dgroup.members[Length(dgroup.members)-1]:=internalObjData.CurrObjSec;
  3204. { define the symbol itself }
  3205. sym:=internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_DATA);
  3206. sym.group:=dgroup;
  3207. end
  3208. else
  3209. inherited;
  3210. end;
  3211. procedure TMZExeOutput.DoRelocationFixup(objsec: TObjSection);
  3212. var
  3213. i: Integer;
  3214. omfsec: TOmfObjSection absolute objsec;
  3215. objreloc: TOmfRelocation;
  3216. target: DWord;
  3217. framebase: DWord;
  3218. fixupamount: Integer;
  3219. target_group: TMZExeUnifiedLogicalGroup;
  3220. procedure FixupOffset;
  3221. var
  3222. w: Word;
  3223. begin
  3224. omfsec.Data.seek(objreloc.DataOffset);
  3225. omfsec.Data.read(w,2);
  3226. w:=LEtoN(w);
  3227. Inc(w,fixupamount);
  3228. w:=LEtoN(w);
  3229. omfsec.Data.seek(objreloc.DataOffset);
  3230. omfsec.Data.write(w,2);
  3231. end;
  3232. procedure FixupOffset32;
  3233. var
  3234. lw: LongWord;
  3235. begin
  3236. omfsec.Data.seek(objreloc.DataOffset);
  3237. omfsec.Data.read(lw,4);
  3238. lw:=LEtoN(lw);
  3239. Inc(lw,fixupamount);
  3240. lw:=LEtoN(lw);
  3241. omfsec.Data.seek(objreloc.DataOffset);
  3242. omfsec.Data.write(lw,4);
  3243. end;
  3244. procedure FixupBase(DataOffset: LongWord);
  3245. var
  3246. w: Word;
  3247. begin
  3248. omfsec.Data.seek(DataOffset);
  3249. omfsec.Data.read(w,2);
  3250. w:=LEtoN(w);
  3251. Inc(w,framebase shr 4);
  3252. w:=LEtoN(w);
  3253. omfsec.Data.seek(DataOffset);
  3254. omfsec.Data.write(w,2);
  3255. Header.AddRelocation(omfsec.MZExeUnifiedLogicalSegment.MemBasePos shr 4,
  3256. omfsec.MemPos+DataOffset-omfsec.MZExeUnifiedLogicalSegment.MemBasePos);
  3257. end;
  3258. begin
  3259. for i:=0 to objsec.ObjRelocations.Count-1 do
  3260. begin
  3261. objreloc:=TOmfRelocation(objsec.ObjRelocations[i]);
  3262. if assigned(objreloc.symbol) then
  3263. begin
  3264. target:=objreloc.symbol.address;
  3265. if objreloc.FrameGroup<>'' then
  3266. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  3267. else if assigned(objreloc.symbol.group) then
  3268. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.symbol.group.Name)).MemPos
  3269. else
  3270. if assigned(TOmfObjSection(objreloc.symbol.objsection).MZExeUnifiedLogicalSegment) then
  3271. framebase:=TOmfObjSection(objreloc.symbol.objsection).MZExeUnifiedLogicalSegment.MemBasePos
  3272. else
  3273. begin
  3274. framebase:=0;
  3275. Comment(V_Warning,'Encountered an OMF reference to a symbol, that is not present in the final executable: '+objreloc.symbol.Name);
  3276. end;
  3277. case objreloc.typ of
  3278. RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG,RELOC_FARPTR,RELOC_FARPTR48:
  3279. fixupamount:=target-framebase;
  3280. RELOC_RELATIVE16,RELOC_SEGREL,RELOC_FARPTR_RELATIVEOFFSET:
  3281. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  3282. RELOC_RELATIVE32,RELOC_FARPTR48_RELATIVEOFFSET:
  3283. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-4;
  3284. else
  3285. internalerror(2015082402);
  3286. end;
  3287. case objreloc.typ of
  3288. RELOC_ABSOLUTE16,
  3289. RELOC_RELATIVE16:
  3290. FixupOffset;
  3291. RELOC_ABSOLUTE32,
  3292. RELOC_RELATIVE32:
  3293. FixupOffset32;
  3294. RELOC_SEG,
  3295. RELOC_SEGREL:
  3296. FixupBase(objreloc.DataOffset);
  3297. RELOC_FARPTR,
  3298. RELOC_FARPTR_RELATIVEOFFSET:
  3299. begin
  3300. FixupOffset;
  3301. FixupBase(objreloc.DataOffset+2);
  3302. end;
  3303. RELOC_FARPTR48,
  3304. RELOC_FARPTR48_RELATIVEOFFSET:
  3305. begin
  3306. FixupOffset32;
  3307. FixupBase(objreloc.DataOffset+4);
  3308. end;
  3309. else
  3310. internalerror(2015082403);
  3311. end;
  3312. end
  3313. else if assigned(objreloc.objsection) then
  3314. begin
  3315. target:=objreloc.objsection.MemPos;
  3316. if objreloc.FrameGroup<>'' then
  3317. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  3318. else
  3319. begin
  3320. if assigned(TOmfObjSection(objreloc.objsection).MZExeUnifiedLogicalSegment) then
  3321. framebase:=TOmfObjSection(objreloc.objsection).MZExeUnifiedLogicalSegment.MemBasePos
  3322. else
  3323. begin
  3324. framebase:=0;
  3325. Comment(V_Warning,'Encountered an OMF reference to a section, that is not present in the final executable: '+TOmfObjSection(objreloc.objsection).Name);
  3326. end;
  3327. end;
  3328. case objreloc.typ of
  3329. RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG,RELOC_FARPTR,RELOC_FARPTR48:
  3330. fixupamount:=target-framebase;
  3331. RELOC_RELATIVE16,RELOC_SEGREL,RELOC_FARPTR_RELATIVEOFFSET:
  3332. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  3333. RELOC_RELATIVE32,RELOC_FARPTR48_RELATIVEOFFSET:
  3334. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-4;
  3335. else
  3336. internalerror(2015082405);
  3337. end;
  3338. case objreloc.typ of
  3339. RELOC_ABSOLUTE16,
  3340. RELOC_RELATIVE16:
  3341. FixupOffset;
  3342. RELOC_ABSOLUTE32,
  3343. RELOC_RELATIVE32:
  3344. FixupOffset32;
  3345. RELOC_SEG,
  3346. RELOC_SEGREL:
  3347. FixupBase(objreloc.DataOffset);
  3348. RELOC_FARPTR,
  3349. RELOC_FARPTR_RELATIVEOFFSET:
  3350. begin
  3351. FixupOffset;
  3352. FixupBase(objreloc.DataOffset+2);
  3353. end;
  3354. RELOC_FARPTR48,
  3355. RELOC_FARPTR48_RELATIVEOFFSET:
  3356. begin
  3357. FixupOffset32;
  3358. FixupBase(objreloc.DataOffset+4);
  3359. end;
  3360. else
  3361. internalerror(2015082406);
  3362. end;
  3363. end
  3364. else if assigned(objreloc.group) then
  3365. begin
  3366. target_group:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.group.Name));
  3367. target:=target_group.MemPos;
  3368. if objreloc.FrameGroup<>'' then
  3369. framebase:=TMZExeUnifiedLogicalGroup(ExeUnifiedLogicalGroups.Find(objreloc.FrameGroup)).MemPos
  3370. else
  3371. framebase:=target_group.MemPos;
  3372. case objreloc.typ of
  3373. RELOC_ABSOLUTE16,RELOC_ABSOLUTE32,RELOC_SEG,RELOC_FARPTR,RELOC_FARPTR48:
  3374. fixupamount:=target-framebase;
  3375. RELOC_RELATIVE16,RELOC_SEGREL,RELOC_FARPTR_RELATIVEOFFSET:
  3376. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-2;
  3377. RELOC_RELATIVE32,RELOC_FARPTR48_RELATIVEOFFSET:
  3378. fixupamount:=target-(omfsec.MemPos+objreloc.DataOffset)-4;
  3379. else
  3380. internalerror(2015111202);
  3381. end;
  3382. case objreloc.typ of
  3383. RELOC_ABSOLUTE16,
  3384. RELOC_RELATIVE16:
  3385. FixupOffset;
  3386. RELOC_ABSOLUTE32,
  3387. RELOC_RELATIVE32:
  3388. FixupOffset32;
  3389. RELOC_SEG,
  3390. RELOC_SEGREL:
  3391. FixupBase(objreloc.DataOffset);
  3392. RELOC_FARPTR,
  3393. RELOC_FARPTR_RELATIVEOFFSET:
  3394. begin
  3395. FixupOffset;
  3396. FixupBase(objreloc.DataOffset+2);
  3397. end;
  3398. RELOC_FARPTR48,
  3399. RELOC_FARPTR48_RELATIVEOFFSET:
  3400. begin
  3401. FixupOffset32;
  3402. FixupBase(objreloc.DataOffset+4);
  3403. end;
  3404. else
  3405. internalerror(2015111203);
  3406. end;
  3407. end
  3408. else
  3409. internalerror(2015082407);
  3410. end;
  3411. end;
  3412. function IOmfObjSectionClassNameCompare(Item1, Item2: Pointer): Integer;
  3413. var
  3414. I1 : TOmfObjSection absolute Item1;
  3415. I2 : TOmfObjSection absolute Item2;
  3416. begin
  3417. Result:=CompareStr(I1.ClassName,I2.ClassName);
  3418. if Result=0 then
  3419. Result:=CompareStr(I1.Name,I2.Name);
  3420. if Result=0 then
  3421. Result:=I1.SortOrder-I2.SortOrder;
  3422. end;
  3423. procedure TMZExeOutput.Order_ObjSectionList(ObjSectionList: TFPObjectList; const aPattern: string);
  3424. var
  3425. i: Integer;
  3426. begin
  3427. for i:=0 to ObjSectionList.Count-1 do
  3428. TOmfObjSection(ObjSectionList[i]).SortOrder:=i;
  3429. ObjSectionList.Sort(@IOmfObjSectionClassNameCompare);
  3430. end;
  3431. procedure TMZExeOutput.MemPos_ExeSection(const aname: string);
  3432. begin
  3433. { overlay all .exe sections on top of each other. In practice, the MZ
  3434. formats doesn't have sections, so really, everything goes to a single
  3435. section, called .MZ_flat_content. All the remaining sections, that we
  3436. use are the debug sections, which go to a separate ELF file, appended
  3437. after the end of the .exe. They live in a separate address space, with
  3438. each section starting at virtual offset 0. So, that's why we always
  3439. set CurrMemPos to 0 before each section here. }
  3440. CurrMemPos:=0;
  3441. inherited MemPos_ExeSection(aname);
  3442. end;
  3443. procedure TMZExeOutput.MemPos_EndExeSection;
  3444. var
  3445. SecName: TSymStr='';
  3446. begin
  3447. if assigned(CurrExeSec) then
  3448. SecName:=CurrExeSec.Name;
  3449. inherited MemPos_EndExeSection;
  3450. case SecName of
  3451. '.MZ_flat_content':
  3452. begin
  3453. CalcExeUnifiedLogicalSegments;
  3454. CalcExeGroups;
  3455. CalcSegments_MemBasePos;
  3456. if assigned(exemap) then
  3457. WriteMap_SegmentsAndGroups;
  3458. end;
  3459. '.debug_info',
  3460. '.debug_abbrev',
  3461. '.debug_line',
  3462. '.debug_aranges':
  3463. begin
  3464. CalcDwarfUnifiedLogicalSegmentsForSection(SecName);
  3465. with TMZExeSection(FindExeSection(SecName)) do
  3466. SecOptions:=SecOptions+[oso_debug];
  3467. end;
  3468. '':
  3469. {nothing to do};
  3470. else
  3471. internalerror(2018061401);
  3472. end;
  3473. end;
  3474. function TMZExeOutput.writeData: boolean;
  3475. begin
  3476. Result:=False;
  3477. if ExeWriteMode in [ewm_exefull,ewm_exeonly] then
  3478. begin
  3479. if apptype=app_com then
  3480. Result:=WriteCom
  3481. else
  3482. Result:=WriteExe;
  3483. if not Result then
  3484. exit;
  3485. end;
  3486. if ((cs_debuginfo in current_settings.moduleswitches) and
  3487. (target_dbg.id in [dbg_dwarf2,dbg_dwarf3,dbg_dwarf4])) and
  3488. ((ExeWriteMode=ewm_dbgonly) or
  3489. ((ExeWriteMode=ewm_exefull) and
  3490. not(cs_link_strip in current_settings.globalswitches))) then
  3491. Result:=writeDebugElf;
  3492. end;
  3493. constructor TMZExeOutput.create;
  3494. begin
  3495. inherited create;
  3496. CExeSection:=TMZExeSection;
  3497. CObjData:=TOmfObjData;
  3498. CObjSymbol:=TOmfObjSymbol;
  3499. { "640K ought to be enough for anybody" :) }
  3500. MaxMemPos:=$9FFFF;
  3501. FExeUnifiedLogicalSegments:=TFPHashObjectList.Create;
  3502. FExeUnifiedLogicalGroups:=TFPHashObjectList.Create;
  3503. FDwarfUnifiedLogicalSegments:=TFPHashObjectList.Create;
  3504. FHeader:=TMZExeHeader.Create;
  3505. end;
  3506. destructor TMZExeOutput.destroy;
  3507. begin
  3508. FHeader.Free;
  3509. FDwarfUnifiedLogicalSegments.Free;
  3510. FExeUnifiedLogicalGroups.Free;
  3511. FExeUnifiedLogicalSegments.Free;
  3512. inherited destroy;
  3513. end;
  3514. {****************************************************************************
  3515. TNewExeHeader
  3516. ****************************************************************************}
  3517. constructor TNewExeHeader.Create;
  3518. begin
  3519. SetLength(FMsDosStub,High(win16stub)-Low(win16stub)+1);
  3520. Move(win16stub[Low(win16stub)],FMsDosStub[0],High(win16stub)-Low(win16stub)+1);
  3521. { BP7 identifies itself as linker version 6.1 in the Win16 .exe files it produces }
  3522. LinkerVersion:=6;
  3523. LinkerRevision:=1;
  3524. LogicalSectorAlignmentShiftCount:=8; { 256-byte logical sectors }
  3525. TargetOS:=netoWindows;
  3526. ExpectedWindowsVersion:=$0300;
  3527. Flags:=[nehfNotWindowAPICompatible,nehfWindowAPICompatible,nehfMultipleData,nehfProtectedModeOnly];
  3528. AdditionalFlags:=[];
  3529. GangLoadAreaStart:=0;
  3530. GangLoadAreaLength:=0;
  3531. Reserved:=0;
  3532. Reserved2:=0;
  3533. end;
  3534. procedure TNewExeHeader.WriteTo(aWriter: TObjectWriter);
  3535. var
  3536. HeaderBytes: array [0..$3F] of Byte;
  3537. begin
  3538. aWriter.write(MsDosStub[0],Length(MsDosStub));
  3539. HeaderBytes[$00]:=$4E; { 'N' }
  3540. HeaderBytes[$01]:=$45; { 'E' }
  3541. HeaderBytes[$02]:=Byte(LinkerVersion);
  3542. HeaderBytes[$03]:=Byte(LinkerRevision);
  3543. unaligned(PUint16(@HeaderBytes[$04{..$05}])^):=NtoLE(uint16(EntryTableOffset));
  3544. unaligned(PUint16(@HeaderBytes[$06{..$07}])^):=NtoLE(uint16(EntryTableLength));
  3545. unaligned(PUint32(@HeaderBytes[$08{..$0B}])^):=NtoLE(uint32(Reserved));
  3546. unaligned(PUint16(@HeaderBytes[$0C{..$0D}])^):=NtoLE(uint16(Flags));
  3547. unaligned(PUint16(@HeaderBytes[$0E{..$0F}])^):=NtoLE(uint16(AutoDataSegmentNumber));
  3548. unaligned(PUint16(@HeaderBytes[$10{..$11}])^):=NtoLE(uint16(InitialLocalHeapSize));
  3549. unaligned(PUint16(@HeaderBytes[$12{..$13}])^):=NtoLE(uint16(InitialStackSize));
  3550. unaligned(PUint16(@HeaderBytes[$14{..$15}])^):=NtoLE(uint16(InitialIP));
  3551. unaligned(PUint16(@HeaderBytes[$16{..$17}])^):=NtoLE(uint16(InitialCS));
  3552. unaligned(PUint16(@HeaderBytes[$18{..$19}])^):=NtoLE(uint16(InitialSP));
  3553. unaligned(PUint16(@HeaderBytes[$1A{..$1B}])^):=NtoLE(uint16(InitialSS));
  3554. unaligned(PUint16(@HeaderBytes[$1C{..$1D}])^):=NtoLE(uint16(SegmentTableEntriesCount));
  3555. unaligned(PUint16(@HeaderBytes[$1E{..$1F}])^):=NtoLE(uint16(ModuleReferenceTableEntriesCount));
  3556. unaligned(PUint16(@HeaderBytes[$20{..$21}])^):=NtoLE(uint16(NonresidentNameTableLength));
  3557. unaligned(PUint16(@HeaderBytes[$22{..$23}])^):=NtoLE(uint16(SegmentTableStart));
  3558. unaligned(PUint16(@HeaderBytes[$24{..$25}])^):=NtoLE(uint16(ResourceTableStart));
  3559. unaligned(PUint16(@HeaderBytes[$26{..$27}])^):=NtoLE(uint16(ResidentNameTableStart));
  3560. unaligned(PUint16(@HeaderBytes[$28{..$29}])^):=NtoLE(uint16(ModuleReferenceTableStart));
  3561. unaligned(PUint16(@HeaderBytes[$2A{..$2B}])^):=NtoLE(uint16(ImportedNameTableStart));
  3562. unaligned(PUint32(@HeaderBytes[$2C{..$2F}])^):=NtoLE(uint32(NonresidentNameTableStart));
  3563. unaligned(PUint16(@HeaderBytes[$30{..$31}])^):=NtoLE(uint16(MovableEntryPointsCount));
  3564. unaligned(PUint16(@HeaderBytes[$32{..$33}])^):=NtoLE(uint16(LogicalSectorAlignmentShiftCount));
  3565. unaligned(PUint16(@HeaderBytes[$34{..$35}])^):=NtoLE(uint16(ResourceSegmentsCount));
  3566. HeaderBytes[$36]:=Byte(Ord(TargetOS));
  3567. HeaderBytes[$37]:=Byte(AdditionalFlags);
  3568. unaligned(PUint16(@HeaderBytes[$38{..$39}])^):=NtoLE(uint16(GangLoadAreaStart));
  3569. unaligned(PUint16(@HeaderBytes[$3A{..$3B}])^):=NtoLE(uint16(GangLoadAreaLength));
  3570. unaligned(PUint16(@HeaderBytes[$3C{..$3D}])^):=NtoLE(uint16(Reserved2));
  3571. unaligned(PUint16(@HeaderBytes[$3E{..$3F}])^):=NtoLE(uint16(ExpectedWindowsVersion));
  3572. aWriter.write(HeaderBytes[0],$40);
  3573. end;
  3574. {****************************************************************************
  3575. TNewExeResourceTable
  3576. ****************************************************************************}
  3577. function TNewExeResourceTable.GetSize: QWord;
  3578. begin
  3579. Result:=5;
  3580. end;
  3581. constructor TNewExeResourceTable.Create;
  3582. begin
  3583. ResourceDataAlignmentShiftCount:=8;
  3584. end;
  3585. procedure TNewExeResourceTable.WriteTo(aWriter: TObjectWriter);
  3586. procedure WriteAlignShift;
  3587. var
  3588. AlignShiftBytes: array [0..1] of Byte;
  3589. begin
  3590. unaligned(PUint16(@AlignShiftBytes[0{..1}])^):=NtoLE(uint16(ResourceDataAlignmentShiftCount));
  3591. aWriter.write(AlignShiftBytes[0],2);
  3592. end;
  3593. procedure WriteEndTypes;
  3594. const
  3595. EndTypesBytes: array [0..1] of Byte = (0, 0);
  3596. begin
  3597. aWriter.write(EndTypesBytes[0],2);
  3598. end;
  3599. procedure WriteEndNames;
  3600. const
  3601. EndNames: Byte = 0;
  3602. begin
  3603. aWriter.write(EndNames,1);
  3604. end;
  3605. begin
  3606. WriteAlignShift;
  3607. WriteEndTypes;
  3608. WriteEndNames;
  3609. end;
  3610. {****************************************************************************
  3611. TNewExeExportNameTableEntry
  3612. ****************************************************************************}
  3613. constructor TNewExeExportNameTableEntry.Create(HashObjectList:TFPHashObjectList;const s:TSymStr;OrdNr:Word);
  3614. begin
  3615. inherited Create(HashObjectList,s);
  3616. OrdinalNr:=OrdNr;
  3617. end;
  3618. {****************************************************************************
  3619. TNewExeExportNameTable
  3620. ****************************************************************************}
  3621. function TNewExeExportNameTable.GetSize: QWord;
  3622. var
  3623. i: Integer;
  3624. begin
  3625. { the end of table mark is 1 byte }
  3626. Result:=1;
  3627. { each entry is 3 bytes, plus the length of the name }
  3628. for i:=0 to Count-1 do
  3629. Inc(Result,3+Length(TNewExeExportNameTableEntry(Items[i]).Name));
  3630. end;
  3631. procedure TNewExeExportNameTable.WriteTo(aWriter: TObjectWriter);
  3632. var
  3633. i: Integer;
  3634. rn: TNewExeExportNameTableEntry;
  3635. slen: Byte;
  3636. OrdNrBuf: array [0..1] of Byte;
  3637. begin
  3638. for i:=0 to Count-1 do
  3639. begin
  3640. rn:=TNewExeExportNameTableEntry(Items[i]);
  3641. slen:=Length(rn.Name);
  3642. if slen=0 then
  3643. internalerror(2019080801);
  3644. aWriter.write(slen,1);
  3645. aWriter.write(rn.Name[1],slen);
  3646. unaligned(PUint16(@OrdNrBuf[0{..1}])^):=NtoLE(uint16(rn.OrdinalNr));
  3647. aWriter.write(OrdNrBuf[0],2);
  3648. end;
  3649. { end of table mark }
  3650. slen:=0;
  3651. aWriter.write(slen,1);
  3652. end;
  3653. {****************************************************************************
  3654. TNewExeModuleReferenceTable
  3655. ****************************************************************************}
  3656. function TNewExeModuleReferenceTable.GetSize: QWord;
  3657. begin
  3658. Result:=Count*2;
  3659. end;
  3660. procedure TNewExeModuleReferenceTable.AddModuleReference(const dllname:TSymStr);
  3661. begin
  3662. if not Assigned(Find(dllname)) then
  3663. TNewExeModuleReferenceTableEntry.Create(Self,dllname);
  3664. end;
  3665. procedure TNewExeModuleReferenceTable.WriteTo(aWriter: TObjectWriter;imptbl: TNewExeImportedNameTable);
  3666. var
  3667. buf: array of Byte;
  3668. i: Integer;
  3669. ImpTblEntry: TNewExeImportedNameTableEntry;
  3670. begin
  3671. SetLength(buf,Size);
  3672. for i:=0 to Count-1 do
  3673. begin
  3674. ImpTblEntry:=TNewExeImportedNameTableEntry(imptbl.Find(TNewExeModuleReferenceTableEntry(Items[i]).Name));
  3675. if not Assigned(ImpTblEntry) then
  3676. internalerror(2019080903);
  3677. unaligned(PUint16(@buf[2*i{..2*i+1}])^):=NtoLE(uint16(ImpTblEntry.TableOffset));
  3678. end;
  3679. aWriter.write(buf[0],Length(buf));
  3680. end;
  3681. {****************************************************************************
  3682. TNewExeImportedNameTable
  3683. ****************************************************************************}
  3684. function TNewExeImportedNameTable.GetSize: QWord;
  3685. var
  3686. i: Integer;
  3687. begin
  3688. { the table starts with an empty entry, which takes 1 byte }
  3689. Result:=1;
  3690. { each entry is 1 byte, plus the length of the name }
  3691. for i:=0 to Count-1 do
  3692. Inc(Result,1+Length(TNewExeImportedNameTableEntry(Items[i]).Name));
  3693. end;
  3694. procedure TNewExeImportedNameTable.AddImportedName(const name: TSymStr);
  3695. begin
  3696. if not Assigned(Find(name)) then
  3697. TNewExeImportedNameTableEntry.Create(Self,name);
  3698. end;
  3699. procedure TNewExeImportedNameTable.CalcTableOffsets;
  3700. var
  3701. cofs: LongInt;
  3702. i: Integer;
  3703. entry: TNewExeImportedNameTableEntry;
  3704. begin
  3705. { the table starts with an empty entry, which takes 1 byte }
  3706. cofs:=1;
  3707. for i:=0 to Count-1 do
  3708. begin
  3709. entry:=TNewExeImportedNameTableEntry(Items[i]);
  3710. entry.TableOffset:=cofs;
  3711. Inc(cofs,1+Length(entry.Name));
  3712. if cofs>High(Word) then
  3713. internalerror(2019080902);
  3714. end;
  3715. end;
  3716. procedure TNewExeImportedNameTable.WriteTo(aWriter: TObjectWriter);
  3717. var
  3718. i: Integer;
  3719. entry: TNewExeImportedNameTableEntry;
  3720. slen: Byte;
  3721. begin
  3722. { the table starts with an empty entry }
  3723. slen:=0;
  3724. aWriter.write(slen,1);
  3725. for i:=0 to Count-1 do
  3726. begin
  3727. entry:=TNewExeImportedNameTableEntry(Items[i]);
  3728. slen:=Length(entry.Name);
  3729. if slen=0 then
  3730. internalerror(2019080901);
  3731. aWriter.write(slen,1);
  3732. aWriter.write(entry.Name[1],slen);
  3733. end;
  3734. end;
  3735. {****************************************************************************
  3736. TNewExeEntryPoint
  3737. ****************************************************************************}
  3738. function TNewExeEntryPoint.GetFlagsByte: Byte;
  3739. begin
  3740. Result:=Byte(ParmCount shl 3);
  3741. if neepfExported in Flags then
  3742. Result:=Result or 1;
  3743. if neepfSingleData in Flags then
  3744. Result:=Result or 2;
  3745. end;
  3746. {****************************************************************************
  3747. TNewExeEntryTable
  3748. ****************************************************************************}
  3749. function TNewExeEntryTable.GetSize: QWord;
  3750. var
  3751. CurBundleStart: Integer;
  3752. CurBundleSize: Byte;
  3753. begin
  3754. Result:=0;
  3755. CurBundleStart:=1;
  3756. repeat
  3757. CurBundleSize:=BundleSize(CurBundleStart);
  3758. Inc(Result,2);
  3759. if CurBundleSize>0 then
  3760. begin
  3761. if Items[CurBundleStart]=nil then
  3762. { a bundle of null entries }
  3763. else if neepfMovableSegment in Items[CurBundleStart].Flags then
  3764. { a bundle of movable segment records }
  3765. Inc(Result,6*CurBundleSize)
  3766. else
  3767. { a bundle of fixed segment records }
  3768. Inc(Result,3*CurBundleSize);
  3769. end;
  3770. Inc(CurBundleStart,CurBundleSize);
  3771. until CurBundleSize=0;
  3772. end;
  3773. procedure TNewExeEntryTable.SetItems(i: Integer; AValue: TNewExeEntryPoint);
  3774. begin
  3775. if (i<1) or (i>Length(FItems)) then
  3776. internalerror(2019081002);
  3777. FItems[i-1]:=AValue;
  3778. end;
  3779. function TNewExeEntryTable.CanBeInSameBundle(i, j: Integer): Boolean;
  3780. begin
  3781. if (Items[i]=nil) or (Items[j]=nil) then
  3782. Result:=(Items[i]=nil) and (Items[j]=nil)
  3783. else if not (neepfMovableSegment in Items[i].Flags) and
  3784. not (neepfMovableSegment in Items[j].Flags) then
  3785. Result:=Items[i].Segment=Items[j].Segment
  3786. else
  3787. Result:=(neepfMovableSegment in Items[i].Flags)=
  3788. (neepfMovableSegment in Items[j].Flags);
  3789. end;
  3790. function TNewExeEntryTable.BundleSize(StartingElement:Integer): Byte;
  3791. begin
  3792. if StartingElement>Count then
  3793. Result:=0
  3794. else
  3795. begin
  3796. Result:=1;
  3797. while (Result<255) and ((StartingElement+Result)<=Count) and CanBeInSameBundle(StartingElement,StartingElement+Result) do
  3798. Inc(Result);
  3799. end;
  3800. end;
  3801. function TNewExeEntryTable.GetCount: Word;
  3802. begin
  3803. Result:=Length(FItems);
  3804. end;
  3805. function TNewExeEntryTable.GetItems(i: Integer): TNewExeEntryPoint;
  3806. begin
  3807. if (i<1) or (i>Length(FItems)) then
  3808. internalerror(2019081011);
  3809. Result:=FItems[i-1];
  3810. end;
  3811. destructor TNewExeEntryTable.Destroy;
  3812. var
  3813. i: Integer;
  3814. begin
  3815. for i:=low(FItems) to high(FItems) do
  3816. FreeAndNil(FItems[i]);
  3817. inherited Destroy;
  3818. end;
  3819. procedure TNewExeEntryTable.WriteTo(aWriter: TObjectWriter);
  3820. var
  3821. CurBundleStart, i: Integer;
  3822. CurBundleSize: Byte;
  3823. buf: array [0..5] of Byte;
  3824. cp: TNewExeEntryPoint;
  3825. begin
  3826. CurBundleStart:=1;
  3827. repeat
  3828. CurBundleSize:=BundleSize(CurBundleStart);
  3829. aWriter.write(CurBundleSize,1);
  3830. if CurBundleSize>0 then
  3831. begin
  3832. if Items[CurBundleStart]=nil then
  3833. begin
  3834. { a bundle of null entries }
  3835. buf[0]:=0;
  3836. aWriter.write(buf[0],1);
  3837. end
  3838. else if neepfMovableSegment in Items[CurBundleStart].Flags then
  3839. begin
  3840. { a bundle of movable segment records }
  3841. buf[0]:=$ff;
  3842. aWriter.write(buf[0],1);
  3843. for i:=CurBundleStart to CurBundleStart+CurBundleSize-1 do
  3844. begin
  3845. cp:=Items[i];
  3846. buf[0]:=cp.FlagsByte;
  3847. buf[1]:=$CD; { INT 3Fh instruction }
  3848. buf[2]:=$3F;
  3849. buf[3]:=Byte(cp.Segment);
  3850. unaligned(PUint16(@buf[4{..5}])^):=NtoLE(uint16(cp.Offset));
  3851. aWriter.write(buf[0],6);
  3852. end;
  3853. end
  3854. else
  3855. begin
  3856. { a bundle of fixed segment records }
  3857. buf[0]:=Items[CurBundleStart].Segment;
  3858. aWriter.write(buf[0],1);
  3859. for i:=CurBundleStart to CurBundleStart+CurBundleSize-1 do
  3860. begin
  3861. cp:=Items[i];
  3862. buf[0]:=cp.FlagsByte;
  3863. unaligned(PUint16(@buf[1{..2}])^):=NtoLE(uint16(cp.Offset));
  3864. aWriter.write(buf[0],3);
  3865. end;
  3866. end;
  3867. end;
  3868. Inc(CurBundleStart,CurBundleSize);
  3869. until CurBundleSize=0;
  3870. { finish the end marker - a null bundle of 0 entries - must be 2 zero
  3871. bytes. The first one was already written by the loop, time to add the
  3872. second one. }
  3873. buf[0]:=0;
  3874. aWriter.write(buf[0],1);
  3875. end;
  3876. procedure TNewExeEntryTable.GrowTo(aNewCount: Word);
  3877. begin
  3878. if aNewCount<Count then
  3879. internalerror(2019081003);
  3880. SetLength(FItems,aNewCount);
  3881. end;
  3882. {****************************************************************************
  3883. TNewExeRelocation
  3884. ****************************************************************************}
  3885. procedure TNewExeRelocation.EncodeTo(dest: PByte);
  3886. begin
  3887. dest[0]:=Ord(AddressType);
  3888. dest[1]:=Ord(RelocationType) or (Ord(IsAdditive) shl 2);
  3889. unaligned(PUint16(@dest[2{..3}])^):=NtoLE(uint16(Offset));
  3890. case RelocationType of
  3891. nertInternalRef:
  3892. begin
  3893. case InternalRefSegmentType of
  3894. neirstFixed:
  3895. begin
  3896. dest[4]:=Byte(InternalRefFixedSegmentNumber);
  3897. dest[5]:=0;
  3898. unaligned(PUint16(@dest[6{..7}])^):=NtoLE(uint16(InternalRefFixedSegmentOffset));
  3899. end;
  3900. neirstMovable:
  3901. begin
  3902. dest[4]:=$FF;
  3903. dest[5]:=0;
  3904. unaligned(PUint16(@dest[6{..7}])^):=NtoLE(uint16(InternalRefMovableSegmentEntryTableIndex));
  3905. end;
  3906. end;
  3907. end;
  3908. nertImportName:
  3909. begin
  3910. unaligned(PUint16(@dest[4{..5}])^):=NtoLE(uint16(ImportModuleIndex));
  3911. unaligned(PUint16(@dest[6{..7}])^):=NtoLE(uint16(ImportNameIndex));
  3912. end;
  3913. nertImportOrdinal:
  3914. begin
  3915. unaligned(PUint16(@dest[4{..5}])^):=NtoLE(uint16(ImportModuleIndex));
  3916. unaligned(PUint16(@dest[6{..7}])^):=NtoLE(uint16(ImportOrdinal));
  3917. end;
  3918. nertOsFixup:
  3919. begin
  3920. unaligned(PUint16(@dest[4{..5}])^):=NtoLE(uint16(Ord(OsFixupType)));
  3921. unaligned(PUint16(@dest[6{..7}])^):=0;
  3922. end;
  3923. end;
  3924. end;
  3925. {****************************************************************************
  3926. TNewExeRelocationList
  3927. ****************************************************************************}
  3928. function TNewExeRelocationList.GetCount: Integer;
  3929. begin
  3930. Result:=FInternalList.Count;
  3931. end;
  3932. function TNewExeRelocationList.GetItem(Index: Integer): TNewExeRelocation;
  3933. begin
  3934. Result:=TNewExeRelocation(FInternalList[Index]);
  3935. end;
  3936. function TNewExeRelocationList.GetSize: QWord;
  3937. begin
  3938. Result:=2+Count*NewExeRelocationRecordSize;
  3939. end;
  3940. procedure TNewExeRelocationList.SetCount(AValue: Integer);
  3941. begin
  3942. FInternalList.Count:=AValue;
  3943. end;
  3944. procedure TNewExeRelocationList.SetItem(Index:Integer;AValue:TNewExeRelocation);
  3945. begin
  3946. FInternalList[Index]:=AValue;
  3947. end;
  3948. constructor TNewExeRelocationList.Create;
  3949. begin
  3950. FInternalList:=TFPObjectList.Create;
  3951. end;
  3952. destructor TNewExeRelocationList.Destroy;
  3953. begin
  3954. FInternalList.Free;
  3955. inherited Destroy;
  3956. end;
  3957. procedure TNewExeRelocationList.WriteTo(aWriter: TObjectWriter);
  3958. var
  3959. buf: array of Byte;
  3960. p: PByte;
  3961. i: Integer;
  3962. begin
  3963. SetLength(buf,Size);
  3964. unaligned(PUint16(@buf[0])^):=NtoLE(uint16(Count));
  3965. p:=@(buf[2]);
  3966. for i:=0 to Count-1 do
  3967. begin
  3968. Items[i].EncodeTo(p);
  3969. Inc(p,NewExeRelocationRecordSize);
  3970. end;
  3971. aWriter.write(buf[0],Size);
  3972. end;
  3973. function TNewExeRelocationList.Add(AObject: TNewExeRelocation): Integer;
  3974. begin
  3975. Result:=FInternalList.Add(AObject);
  3976. end;
  3977. {****************************************************************************
  3978. TNewExeSection
  3979. ****************************************************************************}
  3980. function TNewExeSection.GetMinAllocSize: QWord;
  3981. begin
  3982. Result:=Size-StackSize;
  3983. end;
  3984. function TNewExeSection.GetNewExeSegmentFlags: TNewExeSegmentFlags;
  3985. begin
  3986. Result:=FNewExeSegmentFlags;
  3987. if Relocations.Count>0 then
  3988. Include(Result,nesfHasRelocationData)
  3989. else
  3990. Exclude(Result,nesfHasRelocationData);
  3991. end;
  3992. constructor TNewExeSection.create(AList:TFPHashObjectList;const AName:string);
  3993. begin
  3994. inherited create(AList, AName);
  3995. FRelocations:=TNewExeRelocationList.Create;
  3996. end;
  3997. destructor TNewExeSection.destroy;
  3998. begin
  3999. FRelocations.Free;
  4000. inherited destroy;
  4001. end;
  4002. procedure TNewExeSection.WriteHeaderTo(aWriter: TObjectWriter);
  4003. var
  4004. SegmentHeaderBytes: array [0..7] of Byte;
  4005. begin
  4006. unaligned(PUint16(@SegmentHeaderBytes[0{..1}])^):=NtoLE(uint16(DataPosSectors));
  4007. unaligned(PUint16(@SegmentHeaderBytes[2{..3}])^):=NtoLE(uint16(SizeInFile));
  4008. unaligned(PUint16(@SegmentHeaderBytes[4{..5}])^):=NtoLE(uint16(NewExeSegmentFlags));
  4009. unaligned(PUint16(@SegmentHeaderBytes[6{..7}])^):=NtoLE(uint16(MinAllocSize));
  4010. aWriter.write(SegmentHeaderBytes[0],8);
  4011. end;
  4012. function TNewExeSection.MemPosStr(AImageBase: qword): string;
  4013. begin
  4014. Result:=HexStr(MemBasePos,4)+':'+HexStr(MemPos,4);
  4015. end;
  4016. procedure TNewExeSection.AddObjSection(objsec: TObjSection; ignoreprops: boolean);
  4017. var
  4018. s: TSymStr;
  4019. Separator: SizeInt;
  4020. {SegName,} SegClass: string;
  4021. IsStack, IsBss: Boolean;
  4022. begin
  4023. { allow mixing initialized and uninitialized data in the same section
  4024. => set ignoreprops=true }
  4025. inherited AddObjSection(objsec,true);
  4026. IsBss:=not(oso_Data in objsec.SecOptions);
  4027. s:=objsec.Name;
  4028. { name format is 'SegName||ClassName' }
  4029. Separator:=Pos('||',s);
  4030. if Separator>0 then
  4031. begin
  4032. //SegName:=Copy(s,1,Separator-1);
  4033. SegClass:=Copy(s,Separator+2,Length(s)-Separator-1);
  4034. end
  4035. else
  4036. begin
  4037. //SegName:=s;
  4038. SegClass:='';
  4039. end;
  4040. { wlink recognizes the stack segment by the class name 'STACK' }
  4041. { let's be compatible with wlink }
  4042. IsStack:=SegClass='STACK';
  4043. { tlink (and ms link?) use the scStack segment combination to recognize
  4044. the stack segment.
  4045. let's be compatible with tlink as well }
  4046. if TOmfObjSection(ObjSec).Combination=scStack then
  4047. IsStack:=True;
  4048. if IsStack then
  4049. StackSize:=StackSize+objsec.Size;
  4050. EarlySize:=align_qword(EarlySize,SecAlign)+objsec.Size;
  4051. if (not IsBss) and (not IsStack) then
  4052. SizeInFile:=EarlySize;
  4053. end;
  4054. function TNewExeSection.CanAddObjSection(objsec: TObjSection; ExeSectionLimit: QWord): boolean;
  4055. var
  4056. NewSecAlign: LongInt;
  4057. NewSize: QWord;
  4058. begin
  4059. NewSecAlign:=max(objsec.SecAlign,SecAlign);
  4060. NewSize:=align_qword(EarlySize,NewSecAlign)+objsec.Size;
  4061. Result:=NewSize<=ExeSectionLimit;
  4062. end;
  4063. {****************************************************************************
  4064. TNewExeOutput
  4065. ****************************************************************************}
  4066. procedure TNewExeOutput.AddImportSymbol(const libname, symname,
  4067. symmangledname: TCmdStr; OrdNr: longint; isvar: boolean);
  4068. var
  4069. ImportLibrary: TImportLibrary;
  4070. ImportSymbol: TFPHashObject;
  4071. begin
  4072. ImportLibrary:=TImportLibrary(FImports.Find(libname));
  4073. if not assigned(ImportLibrary) then
  4074. ImportLibrary:=TImportLibrary.Create(FImports,libname);
  4075. ImportSymbol:=TFPHashObject(ImportLibrary.ImportSymbolList.Find(symname));
  4076. if not assigned(ImportSymbol) then
  4077. ImportSymbol:=TImportSymbol.Create(ImportLibrary.ImportSymbolList,symname,symmangledname,OrdNr,isvar);
  4078. end;
  4079. procedure TNewExeOutput.AddImportLibrariesExtractedFromObjectModules;
  4080. var
  4081. i, j, k: Integer;
  4082. ObjData: TOmfObjData;
  4083. ImportLibrary: TImportLibrary;
  4084. ImportSymbol: TImportSymbol;
  4085. begin
  4086. for i:=0 to ObjDataList.Count-1 do
  4087. begin
  4088. ObjData:=TOmfObjData(ObjDataList[i]);
  4089. for j:=0 to ObjData.ImportLibraryList.Count-1 do
  4090. begin
  4091. ImportLibrary:=TImportLibrary(ObjData.ImportLibraryList[j]);
  4092. for k:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4093. begin
  4094. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[k]);
  4095. AddImportSymbol(ImportLibrary.Name,ImportSymbol.Name,ImportSymbol.MangledName,ImportSymbol.OrdNr,ImportSymbol.IsVar);
  4096. end;
  4097. end;
  4098. end;
  4099. end;
  4100. procedure TNewExeOutput.AddNewExeSection;
  4101. var
  4102. SegNr: Integer;
  4103. SecName: string;
  4104. begin
  4105. SegNr:=ExeSectionList.Count+1;
  4106. WriteStr(SecName,'Segment',SegNr,'_',NewExeMetaSection2String[CurrExeMetaSec]);
  4107. inherited Order_ExeSection(SecName);
  4108. TNewExeSection(CurrExeSec).ExeMetaSec:=CurrExeMetaSec;
  4109. TNewExeSection(CurrExeSec).MemBasePos:=SegNr;
  4110. if (CurrExeMetaSec=nemsData) and (Header.AutoDataSegmentNumber=0) then
  4111. Header.AutoDataSegmentNumber:=SegNr;
  4112. case CurrExeMetaSec of
  4113. nemsCode:
  4114. TNewExeSection(CurrExeSec).NewExeSegmentFlags:=[nesfMovable,nesfPreload];
  4115. nemsData:
  4116. TNewExeSection(CurrExeSec).NewExeSegmentFlags:=[nesfData,nesfPreload];
  4117. else
  4118. internalerror(2019070601);
  4119. end;
  4120. end;
  4121. function TNewExeOutput.WriteNewExe: boolean;
  4122. function ExtractModuleName(filename: string): string;
  4123. begin
  4124. Result:=UpCase(ChangeFileExt(filename,''));
  4125. end;
  4126. var
  4127. i: Integer;
  4128. begin
  4129. if IsSharedLibrary then
  4130. Header.Flags:=Header.Flags+[nehfIsDLL,nehfSingleData]-[nehfMultipleData];
  4131. { all exported symbols must have an ordinal }
  4132. AssignOrdinalsToAllExportSymbols;
  4133. AddEntryPointsForAllExportSymbols;
  4134. { the first entry in the resident-name table is the module name }
  4135. TNewExeExportNameTableEntry.Create(ResidentNameTable,ExtractModuleName(current_module.exefilename),0);
  4136. { the first entry in the nonresident-name table is the module description }
  4137. TNewExeExportNameTableEntry.Create(NonresidentNameTable,description,0);
  4138. { add all symbols, exported by name to the resident and nonresident-name tables }
  4139. AddExportedNames;
  4140. FillImportedNameAndModuleReferenceTable;
  4141. ImportedNameTable.CalcTableOffsets;
  4142. Header.InitialIP:=EntrySym.address;
  4143. Header.InitialCS:=TNewExeSection(EntrySym.objsection.ExeSection).MemBasePos;
  4144. Header.InitialSP:=0;
  4145. Header.InitialSS:=Header.AutoDataSegmentNumber;
  4146. Header.InitialStackSize:=TNewExeSection(ExeSectionList[Header.AutoDataSegmentNumber-1]).StackSize;
  4147. Header.InitialLocalHeapSize:=heapsize;
  4148. Header.SegmentTableStart:=NewExeHeaderSize;
  4149. Header.SegmentTableEntriesCount:=ExeSectionList.Count;
  4150. Header.ResourceTableStart:=Header.SegmentTableStart+NewExeSegmentHeaderSize*Header.SegmentTableEntriesCount;
  4151. Header.ResidentNameTableStart:=Header.ResourceTableStart+ResourceTable.Size;
  4152. Header.ModuleReferenceTableStart:=Header.ResidentNameTableStart+ResidentNameTable.Size;
  4153. Header.ModuleReferenceTableEntriesCount:=ModuleReferenceTable.Count;
  4154. Header.ImportedNameTableStart:=Header.ModuleReferenceTableStart+ModuleReferenceTable.Size;
  4155. Header.EntryTableOffset:=Header.ImportedNameTableStart+ImportedNameTable.Size;
  4156. Header.EntryTableLength:=EntryTable.Size;
  4157. Header.NonresidentNameTableStart:=Header.EntryTableOffset+Header.EntryTableLength+Length(Header.MsDosStub);
  4158. Header.NonresidentNameTableLength:=NonresidentNameTable.Size;
  4159. Header.WriteTo(FWriter);
  4160. for i:=0 to ExeSectionList.Count-1 do
  4161. TNewExeSection(ExeSectionList[i]).WriteHeaderTo(FWriter);
  4162. ResourceTable.WriteTo(FWriter);
  4163. ResidentNameTable.WriteTo(FWriter);
  4164. ModuleReferenceTable.WriteTo(FWriter,ImportedNameTable);
  4165. ImportedNameTable.WriteTo(FWriter);
  4166. EntryTable.WriteTo(FWriter);
  4167. NonresidentNameTable.WriteTo(FWriter);
  4168. { todo: write the rest of the file as well }
  4169. Result:=True;
  4170. end;
  4171. procedure TNewExeOutput.FillImportedNameAndModuleReferenceTable;
  4172. var
  4173. i, j: Integer;
  4174. ImportLibrary: TImportLibrary;
  4175. ImportSymbol: TImportSymbol;
  4176. exesym: TExeSymbol;
  4177. LibNameAdded: Boolean;
  4178. dllname: TSymStr;
  4179. begin
  4180. for i:=0 to FImports.Count-1 do
  4181. begin
  4182. ImportLibrary:=TImportLibrary(FImports[i]);
  4183. LibNameAdded:=False;
  4184. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4185. begin
  4186. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4187. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  4188. if assigned(exesym) then
  4189. begin
  4190. if not LibNameAdded then
  4191. begin
  4192. dllname:=StripDllExt(ImportLibrary.Name);
  4193. ImportedNameTable.AddImportedName(dllname);
  4194. ModuleReferenceTable.AddModuleReference(dllname);
  4195. LibNameAdded:=True;
  4196. end;
  4197. if (ImportSymbol.OrdNr=0) and (ImportSymbol.Name<>'') then
  4198. ImportedNameTable.AddImportedName(ImportSymbol.Name);
  4199. end;
  4200. end;
  4201. end;
  4202. end;
  4203. function TNewExeOutput.GetHighestExportSymbolOrdinal: Word;
  4204. var
  4205. i, j: Integer;
  4206. ObjData: TOmfObjData;
  4207. sym: TOmfObjExportedSymbol;
  4208. begin
  4209. Result:=0;
  4210. for i:=0 to ObjDataList.Count-1 do
  4211. begin
  4212. ObjData:=TOmfObjData(ObjDataList[i]);
  4213. for j:=0 to ObjData.ExportedSymbolList.Count-1 do
  4214. begin
  4215. sym:=TOmfObjExportedSymbol(ObjData.ExportedSymbolList[j]);
  4216. if sym.ExportByOrdinal then
  4217. Result:=Max(Result,sym.ExportOrdinal);
  4218. end;
  4219. end;
  4220. end;
  4221. procedure TNewExeOutput.AssignOrdinalsToAllExportSymbols;
  4222. var
  4223. NextOrdinal: LongInt;
  4224. i, j: Integer;
  4225. ObjData: TOmfObjData;
  4226. sym: TOmfObjExportedSymbol;
  4227. begin
  4228. NextOrdinal:=GetHighestExportSymbolOrdinal+1;
  4229. for i:=0 to ObjDataList.Count-1 do
  4230. begin
  4231. ObjData:=TOmfObjData(ObjDataList[i]);
  4232. for j:=0 to ObjData.ExportedSymbolList.Count-1 do
  4233. begin
  4234. sym:=TOmfObjExportedSymbol(ObjData.ExportedSymbolList[j]);
  4235. if not sym.ExportByOrdinal then
  4236. begin
  4237. if NextOrdinal>High(Word) then
  4238. internalerror(2019081001);
  4239. sym.ExportByOrdinal:=True;
  4240. sym.ExportOrdinal:=NextOrdinal;
  4241. Inc(NextOrdinal);
  4242. end;
  4243. end;
  4244. end;
  4245. end;
  4246. procedure TNewExeOutput.AddEntryPointsForAllExportSymbols;
  4247. var
  4248. LastOrdinal: Word;
  4249. i, j: Integer;
  4250. ObjData: TOmfObjData;
  4251. sym: TOmfObjExportedSymbol;
  4252. ent: TNewExeEntryPoint;
  4253. exesym: TExeSymbol;
  4254. sec: TNewExeSection;
  4255. begin
  4256. LastOrdinal:=GetHighestExportSymbolOrdinal;
  4257. EntryTable.GrowTo(LastOrdinal);
  4258. for i:=0 to ObjDataList.Count-1 do
  4259. begin
  4260. ObjData:=TOmfObjData(ObjDataList[i]);
  4261. for j:=0 to ObjData.ExportedSymbolList.Count-1 do
  4262. begin
  4263. sym:=TOmfObjExportedSymbol(ObjData.ExportedSymbolList[j]);
  4264. { all exports must have an ordinal at this point }
  4265. if not sym.ExportByOrdinal then
  4266. internalerror(2019081004);
  4267. { check for duplicated ordinals }
  4268. if Assigned(EntryTable[sym.ExportOrdinal]) then
  4269. internalerror(2019081005);
  4270. ent:=TNewExeEntryPoint.Create;
  4271. EntryTable[sym.ExportOrdinal]:=ent;
  4272. exesym:=TExeSymbol(ExeSymbolList.Find(sym.InternalName));
  4273. if not Assigned(exesym) then
  4274. internalerror(2019081006);
  4275. ent.Flags:=[neepfExported];
  4276. if IsSharedLibrary then
  4277. ent.Flags:=ent.Flags+[neepfSingleData];
  4278. ent.Offset:=exesym.ObjSymbol.address;
  4279. sec:=TNewExeSection(exesym.ObjSymbol.objsection.ExeSection);
  4280. ent.Segment:=sec.MemBasePos;
  4281. if nesfMovable in sec.NewExeSegmentFlags then
  4282. ent.Flags:=ent.Flags+[neepfMovableSegment];
  4283. ent.ParmCount:=sym.ParmCount;
  4284. end;
  4285. end;
  4286. end;
  4287. procedure TNewExeOutput.AddExportedNames;
  4288. var
  4289. i, j: Integer;
  4290. ObjData: TOmfObjData;
  4291. sym: TOmfObjExportedSymbol;
  4292. begin
  4293. for i:=0 to ObjDataList.Count-1 do
  4294. begin
  4295. ObjData:=TOmfObjData(ObjDataList[i]);
  4296. for j:=0 to ObjData.ExportedSymbolList.Count-1 do
  4297. begin
  4298. sym:=TOmfObjExportedSymbol(ObjData.ExportedSymbolList[j]);
  4299. { all exports must have an ordinal at this point }
  4300. if not sym.ExportByOrdinal then
  4301. internalerror(2019081007);
  4302. if sym.ResidentName then
  4303. TNewExeExportNameTableEntry.Create(ResidentNameTable,sym.ExportedName,sym.ExportOrdinal)
  4304. else
  4305. TNewExeExportNameTableEntry.Create(NonresidentNameTable,sym.ExportedName,sym.ExportOrdinal);
  4306. end;
  4307. end;
  4308. end;
  4309. procedure TNewExeOutput.DoRelocationFixup(objsec: TObjSection);
  4310. begin
  4311. {todo}
  4312. end;
  4313. function INewExeOmfObjSectionClassNameCompare(Item1, Item2: Pointer): Integer;
  4314. var
  4315. I1 : TOmfObjSection absolute Item1;
  4316. I2 : TOmfObjSection absolute Item2;
  4317. begin
  4318. Result:=CompareStr(I1.ClassName,I2.ClassName);
  4319. if Result=0 then
  4320. Result:=CompareStr(I1.Name,I2.Name);
  4321. if Result=0 then
  4322. Result:=I1.SortOrder-I2.SortOrder;
  4323. end;
  4324. procedure TNewExeOutput.Order_ObjSectionList(ObjSectionList: TFPObjectList;const aPattern: string);
  4325. var
  4326. i: Integer;
  4327. begin
  4328. for i:=0 to ObjSectionList.Count-1 do
  4329. TOmfObjSection(ObjSectionList[i]).SortOrder:=i;
  4330. ObjSectionList.Sort(@INewExeOmfObjSectionClassNameCompare);
  4331. end;
  4332. constructor TNewExeOutput.create;
  4333. begin
  4334. inherited create;
  4335. CObjData:=TOmfObjData;
  4336. CObjSymbol:=TOmfObjSymbol;
  4337. CExeSection:=TNewExeSection;
  4338. FHeader:=TNewExeHeader.Create;
  4339. MaxMemPos:=$FFFFFFFF;
  4340. CurrExeMetaSec:=nemsNone;
  4341. FResourceTable:=TNewExeResourceTable.Create;
  4342. FResidentNameTable:=TNewExeExportNameTable.Create;
  4343. FNonresidentNameTable:=TNewExeExportNameTable.Create;
  4344. FModuleReferenceTable:=TNewExeModuleReferenceTable.Create;
  4345. FImportedNameTable:=TNewExeImportedNameTable.Create;
  4346. FEntryTable:=TNewExeEntryTable.Create;
  4347. end;
  4348. destructor TNewExeOutput.destroy;
  4349. begin
  4350. FEntryTable.Free;
  4351. FImportedNameTable.Free;
  4352. FModuleReferenceTable.Free;
  4353. FNonresidentNameTable.Free;
  4354. FResidentNameTable.Free;
  4355. FResourceTable.Free;
  4356. FHeader.Free;
  4357. inherited destroy;
  4358. end;
  4359. procedure TNewExeOutput.Order_ExeSection(const aname: string);
  4360. begin
  4361. case aname of
  4362. '.NE_code':
  4363. CurrExeMetaSec:=nemsCode;
  4364. '.NE_data':
  4365. CurrExeMetaSec:=nemsData;
  4366. else
  4367. internalerror(2019080201);
  4368. end;
  4369. end;
  4370. procedure TNewExeOutput.Order_EndExeSection;
  4371. begin
  4372. CurrExeMetaSec:=nemsNone;
  4373. inherited;
  4374. end;
  4375. procedure TNewExeOutput.Order_ObjSection(const aname: string);
  4376. const
  4377. SegmentLimit=$10000;
  4378. var
  4379. i,j : longint;
  4380. ObjData : TObjData;
  4381. objsec : TObjSection;
  4382. TmpObjSectionList : TFPObjectList;
  4383. begin
  4384. if CurrExeMetaSec=nemsNone then
  4385. internalerror(2019080202);
  4386. if not assigned (CurrExeSec) then
  4387. AddNewExeSection;
  4388. TmpObjSectionList:=TFPObjectList.Create(false);
  4389. for i:=0 to ObjDataList.Count-1 do
  4390. begin
  4391. ObjData:=TObjData(ObjDataList[i]);
  4392. for j:=0 to ObjData.ObjSectionList.Count-1 do
  4393. begin
  4394. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  4395. if (not objsec.Used) and
  4396. MatchPattern(aname,objsec.name) then
  4397. TmpObjSectionList.Add(objsec);
  4398. end;
  4399. end;
  4400. { Order list if needed }
  4401. Order_ObjSectionList(TmpObjSectionList,aname);
  4402. { Add the (ordered) list to the current ExeSection }
  4403. for i:=0 to TmpObjSectionList.Count-1 do
  4404. begin
  4405. objsec:=TObjSection(TmpObjSectionList[i]);
  4406. { If there's no room left in the current section, create a new one }
  4407. if not TNewExeSection(CurrExeSec).CanAddObjSection(objsec,SegmentLimit) then
  4408. AddNewExeSection;
  4409. CurrExeSec.AddObjSection(objsec);
  4410. end;
  4411. TmpObjSectionList.Free;
  4412. end;
  4413. procedure TNewExeOutput.MemPos_Start;
  4414. var
  4415. i: Integer;
  4416. begin
  4417. inherited MemPos_Start;
  4418. for i:=0 to ExeSectionList.Count-1 do
  4419. begin
  4420. MemPos_ExeSection(TExeSection(ExeSectionList[i]));
  4421. CurrMemPos:=0;
  4422. end;
  4423. end;
  4424. procedure TNewExeOutput.GenerateLibraryImports(ImportLibraryList: TFPHashObjectList);
  4425. var
  4426. i,j: longint;
  4427. ImportLibrary: TImportLibrary;
  4428. ImportSymbol: TImportSymbol;
  4429. exesym: TExeSymbol;
  4430. begin
  4431. FImports:=ImportLibraryList;
  4432. AddImportLibrariesExtractedFromObjectModules;
  4433. for i:=0 to FImports.Count-1 do
  4434. begin
  4435. ImportLibrary:=TImportLibrary(FImports[i]);
  4436. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  4437. begin
  4438. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  4439. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  4440. if assigned(exesym) and
  4441. (exesym.State<>symstate_defined) then
  4442. begin
  4443. ImportSymbol.CachedExeSymbol:=exesym;
  4444. exesym.State:=symstate_defined;
  4445. end;
  4446. end;
  4447. end;
  4448. PackUnresolvedExeSymbols('after DLL imports');
  4449. end;
  4450. function TNewExeOutput.writeData: boolean;
  4451. begin
  4452. Result:=False;
  4453. if ExeWriteMode in [ewm_exefull,ewm_exeonly] then
  4454. begin
  4455. Result:=WriteNewExe;
  4456. if not Result then
  4457. exit;
  4458. end;
  4459. end;
  4460. {****************************************************************************
  4461. TOmfAssembler
  4462. ****************************************************************************}
  4463. constructor TOmfAssembler.Create(info: pasminfo; smart:boolean);
  4464. begin
  4465. inherited;
  4466. CObjOutput:=TOmfObjOutput;
  4467. CInternalAr:=TOmfLibObjectWriter;
  4468. end;
  4469. {*****************************************************************************
  4470. Procedures and functions
  4471. *****************************************************************************}
  4472. function StripDllExt(const DllName:TSymStr):TSymStr;
  4473. begin
  4474. if UpCase(ExtractFileExt(DllName))='.DLL' then
  4475. Result:=Copy(DllName,1,Length(DllName)-4)
  4476. else
  4477. Result:=DllName;
  4478. end;
  4479. function MaybeAddDllExt(const DllName: TSymStr): TSymStr;
  4480. begin
  4481. if ExtractFileExt(DllName)='' then
  4482. Result:=ChangeFileExt(DllName,'.dll')
  4483. else
  4484. Result:=DllName;
  4485. end;
  4486. {*****************************************************************************
  4487. Initialize
  4488. *****************************************************************************}
  4489. {$ifdef i8086}
  4490. const
  4491. as_i8086_omf_info : tasminfo =
  4492. (
  4493. id : as_i8086_omf;
  4494. idtxt : 'OMF';
  4495. asmbin : '';
  4496. asmcmd : '';
  4497. supported_targets : [system_i8086_msdos,system_i8086_embedded,system_i8086_win16];
  4498. flags : [af_outputbinary,af_smartlink_sections];
  4499. labelprefix : '..@';
  4500. labelmaxlen : -1;
  4501. comment : '; ';
  4502. dollarsign: '$';
  4503. );
  4504. {$endif i8086}
  4505. initialization
  4506. {$ifdef i8086}
  4507. RegisterAssembler(as_i8086_omf_info,TOmfAssembler);
  4508. {$endif i8086}
  4509. end.