ognlm.pas 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515
  1. {
  2. Copyright (c) 1998-2006 by Peter Vreman
  3. Copyright (c) 2011 by Armin Diehl
  4. Contains the binary netware nlm executable writer
  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 ognlm;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. { common }
  23. cclasses,globtype,
  24. { target }
  25. systems,
  26. aasmbase,assemble,link,
  27. { output }
  28. ogbase,
  29. owbase,
  30. ogcoff;
  31. {*****************************************************************************
  32. NLM File structures and constants
  33. *****************************************************************************}
  34. {
  35. LString0 -> 1 byte Length, Text, #0
  36. LString -> 1 byte length, Text
  37. Basic NLM File Structure:
  38. FixedHeader
  39. nlm32_i386_external_fixed_header 130 bytes
  40. VarHdr1
  41. NLM Description: LString0 2+n bytes
  42. Stacksize 4 bytes
  43. reserved = 0 4 bytes
  44. ' LONG' 5 bytes
  45. NLM screen name: LString0 2+n bytes
  46. NLM thread name: LString0 2+n bytes
  47. Optional Headers beginning with stamp (without '')
  48. 'VeRsIoN#': nlm32_i386_external_version_header 32 bytes
  49. 'CoPyRiGhT=': LString0 2+n bytes
  50. 'MeSsAgEs': nlm32_i386_external_extended_header 124 bytes
  51. 'CuStHeAd': nlm32_i386_external_custom_header
  52. 'CyGnUsEx': nlm32_i386_external_cygnus_ext_header 16 bytes
  53. .text
  54. .data
  55. .relocs=
  56. addr(32),addr(32),...
  57. addr and $80000000 > 0 -> FixupToSeg=.text else .data
  58. addr and $40000000 > 0 -> FixupInSeg=.text else .data
  59. .importedSymbols
  60. name LString 1+n bytes
  61. number of references r 4 bytes
  62. addresses r*4 bytes
  63. .exportedSymbols
  64. name LString 1+n bytes
  65. addr 4 bytes
  66. addr and $80000000 > 0 -> .text else .data
  67. ...
  68. .modules
  69. .nlmdebugrecs
  70. type (0=.data,1=.code,2,..=????) 1 byte
  71. addr 4 bytes
  72. name LString 1+n bytes
  73. ...
  74. }
  75. const NLM_MAX_DESCRIPTION_LENGTH = 127;
  76. NLM_MAX_SCREEN_NAME_LENGTH = 71;
  77. NLM_MAX_THREAD_NAME_LENGTH = 71; // some netware docs limit this to 12 ?
  78. NLM_OLD_THREAD_NAME_LENGTH = 5;
  79. NLM_HEADER_VERSION = 4;
  80. NLM_DEFAULT_STACKSIZE = (32 * 1024);
  81. NLM_VERSION_STAMP = 'VeRsIoN#';
  82. NLM_COPYRIGHT_STAMP = 'CoPyRiGhT=';
  83. NLM_CYGNUS_STAMP = 'CyGnUsEx';
  84. NLM_MESSAGES_STAMP = 'MeSsAgEs';
  85. NLM_CUSTOM_STAMP = 'CuStHeAd';
  86. NLM_SIGNATURE = 'NetWare Loadable Module'#$1A;
  87. NLM_FLAGS_REENTRANT = 1;
  88. NLM_FLAGS_MULTILOAD = 2;
  89. NLM_FLAGS_SYNCHRONIZE = 4;
  90. NLM_FLAGS_PSEUDOPREEMPTION = 8;
  91. NLM_FLAGS_OSDOMAIN = $10;
  92. NLM_FLAGS_AUTOUNLOAD = $40;
  93. type
  94. uint32 = longword;
  95. nlm32_i386_external_fixed_header = packed record
  96. signature : array[0..23] of char;
  97. version : uint32;
  98. (* The name of the module, which must be a DOS name (1-8 characters followed
  99. by a period and a 1-3 character extension). The first byte is the byte
  100. length of the name and the last byte is a null terminator byte. This
  101. field is fixed length, and any unused bytes should be null bytes. The
  102. value is set by the OUTPUT keyword to NLMLINK. *)
  103. moduleName : string[13]; //array[0..13] of byte;
  104. codeImageOffset : uint32; // The byte offset of the code image from the start of the file.
  105. codeImageSize : uint32; // The size of the code image, in bytes.
  106. dataImageOffset : uint32; // The byte offset of the data image from the start of the file.
  107. dataImageSize : uint32; // The size of the data image, in bytes.
  108. uninitializedDataSize : uint32; // The size of the uninitialized data region that the loader has to be
  109. // allocated at load time. Uninitialized data follows the initialized
  110. // data in the NLM address space.
  111. customDataOffset : uint32; // The byte offset of the custom data from the start of the file. The
  112. // custom data is set by the CUSTOM keyword to NLMLINK. It is possible
  113. // for this to be EOF if there is no custom data.
  114. customDataSize : uint32; // The size of the custom data, in bytes.
  115. moduleDependencyOffset : uint32; // The byte offset of the module dependencies from the start of the file.
  116. // The module dependencies are determined by the MODULE keyword in NLMLINK.
  117. numberOfModuleDependencies : uint32; // he number of module dependencies at the moduleDependencyOffset.
  118. relocationFixupOffset : uint32; // The byte offset of the relocation fixup data from the start of the file
  119. numberOfRelocationFixups : uint32;
  120. externalReferencesOffset : uint32;
  121. numberOfExternalReferences : uint32;
  122. publicsOffset : uint32;
  123. numberOfPublics : uint32;
  124. debugInfoOffset : uint32; // The byte offset of the internal debug info from the start of the file.
  125. // It is possible for this to be EOF if there is no debug info.
  126. numberOfDebugRecords : uint32;
  127. codeStartOffset : uint32;
  128. exitProcedureOffset : uint32;
  129. checkUnloadProcedureOffset : uint32;
  130. moduleType : uint32;
  131. flags : uint32;
  132. end;
  133. { The version header is one of the optional auxiliary headers and
  134. follows the fixed length and variable length NLM headers. }
  135. { The header is recognized by "VeRsIoN#" in the stamp field. }
  136. nlm32_i386_external_version_header = packed record
  137. stamp : array[0..7] of char; // VeRsIoN#
  138. majorVersion,
  139. minorVersion,
  140. revision,
  141. year,
  142. month,
  143. day : uint32;
  144. end;
  145. { The header is recognized by "MeSsAgEs" in the stamp field. }
  146. nlm32_i386_external_extended_header = packed record
  147. stamp : array[0..7] of char; // MeSsAgEs
  148. languageID : uint32;
  149. messageFileOffset : uint32;
  150. messageFileLength : uint32;
  151. messageCount : uint32;
  152. helpFileOffset : uint32;
  153. helpFileLength : uint32;
  154. RPCDataOffset : uint32;
  155. RPCDataLength : uint32;
  156. sharedCodeOffset : uint32;
  157. sharedCodeLength : uint32;
  158. sharedDataOffset : uint32;
  159. sharedDataLength : uint32;
  160. sharedRelocationFixupOffset : uint32;
  161. sharedRelocationFixupCount : uint32;
  162. sharedExternalReferenceOffset: uint32;
  163. sharedExternalReferenceCount : uint32;
  164. sharedPublicsOffset : uint32;
  165. sharedPublicsCount : uint32;
  166. sharedDebugRecordOffset : uint32;
  167. sharedDebugRecordCount : uint32;
  168. SharedInitializationOffset : uint32;
  169. SharedExitProcedureOffset : uint32;
  170. productID : longint;
  171. reserved0 : longint;
  172. reserved1 : longint;
  173. reserved2 : longint;
  174. reserved3 : longint;
  175. reserved4 : longint;
  176. reserved5 : longint;
  177. end;
  178. nlm32_i386_external_custom_header = packed record
  179. stamp : array[0..7] of char; // CuStHeAd
  180. hdrLength : uint32;
  181. dataOffset : uint32;
  182. dataLength : uint32;
  183. //dataStamp : array[0..7] of char;
  184. //hdr : uint32;
  185. end;
  186. { The internal Cygnus header is written out externally as a custom
  187. header. We don't try to replicate that structure here. }
  188. { The header is recognized by "CyGnUsEx" in the stamp field. }
  189. { File location of debugging information. }
  190. { Length of debugging information. }
  191. nlm32_i386_external_cygnus_ext_header = packed record
  192. stamp : array[0..7] of char; // CyGnUsEx
  193. offset : uint32;
  194. length : uint32;
  195. end;
  196. //------------------
  197. TNLMExeSection = class(TExeSection)
  198. public
  199. constructor createnw(AList:TFPHashObjectList;const n:string);
  200. end;
  201. TsecType = (Section_text,Section_data,Section_other);
  202. TNLMexeoutput = class(texeoutput)
  203. private
  204. FRelocsGenerated,FImportsGenerated : boolean;
  205. FNumRelocs : longword;
  206. FNumExternals : longword;
  207. FNumModules : longword;
  208. FNumDebugSymbols : longword;
  209. fSizeWoDebugSyms : longword;
  210. FnumExports : longword;
  211. NlmSymbols : TDynamicArray;
  212. ExeSecsListSize : longint;
  213. nlmImpNames, // name of import. module name as import
  214. nlmImports : TFPHashObjectList; // name of import, list of relocs as object
  215. headerAlignBytes : longint;
  216. FexportFunctionOffsets:TFPList; // offsets in .exports for function addresses, an offset of $80000000 is needed
  217. nlmHeader : nlm32_i386_external_fixed_header;
  218. nlmVersionHeader : nlm32_i386_external_version_header;
  219. nlmExtHeader : nlm32_i386_external_extended_header;
  220. nlmCustHeader : nlm32_i386_external_custom_header;
  221. //nlmHelpFileName : TCmdStr;
  222. //nlmMessagesFileName: TCmdStr;
  223. //nlmXdcFileName : TCmdStr;
  224. nlmCopyright : string;
  225. nlmThreadname : string;
  226. nlmScreenname : string;
  227. nlmDescription : string;
  228. function totalheadersize:longword;
  229. procedure createNlm_symbol(const name:shortstring;value:longword;secType:TSecType);
  230. procedure globalsyms_create_symbol(p:TObject;arg:pointer);
  231. procedure ExeSectionList_write_header(p:TObject;arg:pointer);
  232. procedure ExeSectionList_calc_size(p:TObject;arg:pointer);
  233. procedure ExeSectionList_write_data(p:TObject;arg:pointer);
  234. procedure GenerateImports;
  235. procedure GenerateExports;
  236. procedure GenerateRelocs;
  237. procedure ExeSectionList_pass2_header(p:TObject;arg:pointer);
  238. protected
  239. function writedata:boolean;override;
  240. public
  241. constructor create; override;
  242. destructor destroy; override;
  243. procedure MemPos_Header;override;
  244. procedure DataPos_Header;override;
  245. procedure fillNlmVersionHeader;
  246. procedure GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);override;
  247. procedure MemPos_Start;override;
  248. procedure MemPos_ExeSection(const aname:string);override;
  249. procedure NLMwriteString (const s : string; terminateWithZero : boolean);
  250. procedure objNLMwriteString (const s : string; terminateWithZero : boolean);
  251. procedure ParseScript (linkscript:TCmdStrList); override;
  252. end;
  253. var
  254. {for symbols defined in linker script. To generate a fixup we
  255. need to know the segment (.text,.bss or .code) of the symbol
  256. Pointer in list is used as TsecType
  257. Filled by TInternalLinkerNetware.DefaultLinkScript }
  258. nlmSpecialSymbols_Segments : TFPHashList;
  259. type
  260. TNLMCoffObjInput = class(TCoffObjInput)
  261. constructor create;override;
  262. end;
  263. TNLMCoffassembler = class(tinternalassembler)
  264. constructor create(info: pasminfo; smart:boolean);override;
  265. end;
  266. TNLMCoffObjData = class(TCoffObjData)
  267. constructor create(const n:string);override;
  268. end;
  269. TNLMCoffObjOutput = class(TCoffObjOutput)
  270. constructor create(AWriter:TObjectWriter);override;
  271. end;
  272. TNLMCoffObjSection = class(TCoffObjSection)
  273. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);override;
  274. end;
  275. implementation
  276. uses
  277. {$ifdef win32}
  278. Windows,
  279. {$endif win32}
  280. SysUtils,
  281. cutils,verbose,globals,
  282. fmodule,aasmdata,
  283. ogmap,export,owar
  284. ;
  285. {****************************************************************************
  286. Helpers
  287. ****************************************************************************}
  288. type
  289. TStringObj = class (TObject)
  290. fValue : string;
  291. constructor create (value:string);
  292. property value : string read fValue write fValue;
  293. end;
  294. constructor TStringObj.create(value:string);
  295. begin
  296. inherited create;
  297. fValue := value;
  298. end;
  299. function SectionType (aName : string) : TSecType;
  300. var s : string;
  301. seg: ptruint;
  302. begin
  303. s := copy(aName,1,5);
  304. if s = '.text' then result := Section_text else
  305. if (s = '.data') or (copy(s,1,4)='.bss') then result := Section_data else
  306. if s[1] <> '.' then
  307. begin
  308. seg := ptruint(nlmSpecialSymbols_Segments.Find(aName));
  309. if seg <> 0 then
  310. result := TSecType(seg)
  311. else
  312. result := Section_other;
  313. end else
  314. result := Section_other;
  315. end;
  316. {****************************************************************************
  317. TNLMexesection
  318. ****************************************************************************}
  319. constructor TNLMExeSection.createnw(AList:TFPHashObjectList;const n:string);
  320. begin
  321. inherited create(AList,n);
  322. end;
  323. {****************************************************************************
  324. TNLMexeoutput
  325. ****************************************************************************}
  326. constructor TNLMexeoutput.create;
  327. begin
  328. inherited create;
  329. CExeSection:=TNLMExeSection;
  330. CObjData:=TNLMCoffObjData;
  331. MaxMemPos:=$7FFFFFFF;
  332. SectionMemAlign:=$0;
  333. SectionDataAlign:=0;
  334. nlmImports := TFPHashObjectList.create(true);
  335. nlmImpNames := TFPHashObjectList.create(false);
  336. NlmSymbols := TDynamicArray.create(4096);
  337. FexportFunctionOffsets := TFPList.Create;
  338. end;
  339. destructor TNLMexeoutput.destroy;
  340. begin
  341. nlmImports.Free;
  342. nlmImports := nil;
  343. nlmImpNames.Free;
  344. nlmImpNames := nil;
  345. nlmSymbols.Free;
  346. nlmSymbols := nil;
  347. FexportFunctionOffsets.Free;
  348. FexportFunctionOffsets := nil;
  349. inherited destroy;
  350. end;
  351. procedure TNLMexeoutput.createNlm_symbol(const name:shortstring;value:longword;secType:TSecType);
  352. var
  353. b:byte;
  354. begin
  355. //Comment (V_Debug,'TNLMexeoutput.write_symbol '+name);
  356. { type (0=.data,1=.code,2,..=????) 1 byte
  357. addr 4 bytes
  358. name LString 1+n bytes }
  359. case secType of
  360. Section_Text : b := 1;
  361. Section_Data : b := 0
  362. else
  363. exit;
  364. end;
  365. nlmSymbols.write(b,sizeof(b));
  366. assert (sizeof(value)<>4);
  367. nlmSymbols.write(value,sizeof(value));
  368. nlmSymbols.write(name[0],length(name)+1);
  369. inc(FNumDebugSymbols);
  370. end;
  371. procedure TNLMexeoutput.globalsyms_create_symbol(p:TObject;arg:pointer);
  372. var
  373. value : longword;
  374. exesec : TExeSection;
  375. i : integer;
  376. secType : TsecType;
  377. begin
  378. if not assigned(texesymbol(p).objsymbol) then
  379. internalerror(200603053);
  380. with texesymbol(p).objsymbol do
  381. begin
  382. exesec:=TExeSection(objsection.exesection);
  383. { There is no exesection defined for special internal symbols
  384. like __image_base__ }
  385. if assigned(exesec) then
  386. begin
  387. //secval:=exesec.secsymidx;
  388. value:=address-exesec.mempos;
  389. end
  390. else
  391. begin
  392. value:=address;
  393. end;
  394. { reloctype address to the section in the executable }
  395. secType := SectionType(objsection.Name);
  396. if (secType = Section_Text) or (secType = Section_Data) then
  397. begin
  398. i := nlmImports.FindIndexOf(texesymbol(p).name);
  399. if i < 0 then
  400. createNlm_symbol(name,value,secType);
  401. end;
  402. end;
  403. end;
  404. (*
  405. function SecOpts(SecOptions:TObjSectionOptions):string;
  406. begin
  407. result := '[';
  408. if oso_Data in SecOptions then result := result + 'oso_Data ';
  409. { Is loaded into memory }
  410. if oso_load in SecOptions then result := result + 'oso_load ';
  411. { Not loaded into memory }
  412. if oso_noload in SecOptions then result := result + 'oso_noload ';
  413. { Read only }
  414. if oso_readonly in SecOptions then result := result + 'oso_readonly ';
  415. { Read/Write }
  416. if oso_write in SecOptions then result := result + 'oso_write ';
  417. { Contains executable instructions }
  418. if oso_executable in SecOptions then result := result + 'oso_executable ';
  419. { Never discard section }
  420. if oso_keep in SecOptions then result := result + 'oso_keep ';
  421. { Special common symbols }
  422. if oso_common in SecOptions then result := result + 'oso_common ';
  423. { Contains debug info and can be stripped }
  424. if oso_debug in SecOptions then result := result + 'oso_debug ';
  425. { Contains only strings }
  426. if oso_strings in SecOptions then result := result + 'oso_strings ';
  427. result := result + ']';
  428. end;
  429. *)
  430. procedure TNLMexeoutput.ExeSectionList_calc_size(p:TObject;arg:pointer);
  431. var
  432. objsec : TObjSection;
  433. i : longint;
  434. begin
  435. with texesection(p) do
  436. begin
  437. { don't write normal section if writing only debug info }
  438. if (ExeWriteMode=ewm_dbgonly) and
  439. not(oso_debug in SecOptions) then
  440. exit;
  441. if oso_data in secoptions then
  442. begin
  443. inc (fSizeWoDebugSyms,(Align(fSizeWoDebugSyms,SectionDataAlign)-fSizeWoDebugSyms));
  444. for i:=0 to ObjSectionList.Count-1 do
  445. begin
  446. objsec:=TObjSection(ObjSectionList[i]);
  447. if oso_data in objsec.secoptions then
  448. begin
  449. inc(fSizeWoDebugSyms,objsec.size);
  450. inc(fSizeWoDebugSyms,objsec.dataalignbytes);
  451. end;
  452. end;
  453. end;
  454. end;
  455. end;
  456. procedure TNLMexeoutput.ExeSectionList_write_Data(p:TObject;arg:pointer);
  457. var
  458. objsec : TObjSection;
  459. i,j : longint;
  460. b : byte;
  461. dpos,pad: aword;
  462. begin
  463. with texesection(p) do
  464. begin
  465. { don't write normal section if writing only debug info }
  466. if (ExeWriteMode=ewm_dbgonly) and
  467. not(oso_debug in SecOptions) then
  468. exit;
  469. if oso_data in secoptions then
  470. begin
  471. if DataPos<FWriter.Size then
  472. InternalError(2012103001);
  473. //if Align(FWriter.Size,SectionDataAlign)-FWriter.Size>0 then
  474. // writeln (name,' align ',Align(FWriter.Size,SectionDataAlign)-FWriter.Size,' SectionDataAlign:',SectionDataAlign);
  475. FWriter.Writezeros(DataPos-FWriter.Size);
  476. for i:=0 to ObjSectionList.Count-1 do
  477. begin
  478. objsec:=TObjSection(ObjSectionList[i]);
  479. if oso_data in objsec.secoptions then
  480. begin
  481. { objsection must be within SecAlign bytes from the previous one }
  482. dpos:=objsec.MemPos-MemPos+DataPos;
  483. pad:=dpos-FWriter.Size;
  484. if (dpos<FWriter.Size) or
  485. (pad>=max(objsec.SecAlign,1)) then
  486. internalerror(200602251);
  487. if assigned(exemap) then
  488. if objsec.data.size > 0 then
  489. exemap.Add(' 0x'+hexstr(dpos,8)+': '+objsec.name);
  490. //writeln (' ',objsec.name,' size:',objsec.size,' relocs:',objsec.ObjRelocations.count,' DataPos:',objsec.DataPos,' MemPos:',objsec.MemPos);
  491. {for j := 0 to objsec.ObjRelocations.count-1 do
  492. begin
  493. objreloc := TObjRelocation(objsec.ObjRelocations[j]);
  494. with objreloc do
  495. begin
  496. write(' reloc DataOffset: ',DataOffset,' OrgSize:',OrgSize,' typ:',typ);
  497. if assigned(symbol) then
  498. write(' Name: '#39,symbol.Name,#39' bind:',symbol.bind,' address:',symbol.address,' Size:',symbol.size);
  499. writeln;
  500. end;
  501. end;}
  502. if not assigned(objsec.data) then
  503. internalerror(200603042);
  504. if copy (objsec.Name,1,5) = '.text' then
  505. begin // write NOP's instead of zero's for .text, makes disassemble possible
  506. b := $90; // NOP
  507. for j := 1 to pad do
  508. FWriter.write(b,1);
  509. end else
  510. FWriter.writezeros(pad);
  511. FWriter.writearray(objsec.data);
  512. end else
  513. begin
  514. if assigned(exemap) then //TExeMap
  515. exemap.Add(' skipping: '+objsec.name);
  516. end;
  517. end;
  518. end;
  519. end;
  520. end;
  521. function TNLMexeoutput.totalheadersize:longword;
  522. var
  523. varHdrSize,
  524. optHdrSize,
  525. hdrSize: longword;
  526. begin
  527. optHdrSize := 0;
  528. inc(optHdrSize,2+length(nlmDescription));
  529. inc(optHdrSize,8); // Stacksize+reserved
  530. inc(optHdrSize,NLM_OLD_THREAD_NAME_LENGTH);
  531. inc(optHdrSize,2+length(nlmScreenname));
  532. inc(optHdrSize,2+length(nlmThreadname));
  533. varHdrSize := 0;
  534. if nwcopyright <> '' then
  535. inc(varHdrSize,sizeof(NLM_COPYRIGHT_STAMP)+2+length(nlmCopyright));
  536. hdrSize := sizeof(nlm32_i386_external_fixed_header)+
  537. sizeof(nlm32_i386_external_extended_header)+
  538. sizeof(nlm32_i386_external_custom_header)+
  539. sizeof(nlm32_i386_external_version_header)+ // always
  540. sizeof(nlm32_i386_external_cygnus_ext_header)+ // CyGnUsEx
  541. varHdrSize+optHdrSize+
  542. 8; // empty stamp
  543. result := hdrSize;
  544. end;
  545. procedure TNLMexeoutput.MemPos_Header;
  546. begin
  547. { calculate start positions after the headers }
  548. currmempos:=0;
  549. end;
  550. procedure TNLMexeoutput.ExeSectionList_write_header(p:TObject;arg:pointer);
  551. var
  552. nam : string;
  553. u32,al : longword;
  554. alignAmount:longint;
  555. begin
  556. with tExeSection(p) do
  557. begin
  558. //comment (v_debug,'ExeSectionList_write_header: '+name);
  559. nam := name;
  560. alignAmount := 4 - ((length (nam) + 1) MOD 4);
  561. FWriter.write(nam[1],length(nam));
  562. FWriter.WriteZeros(1+alignAmount);
  563. al := 0;
  564. // for .stab we have to ignore leading zeros due to alignment in file
  565. if nam='.stab' then
  566. if assigned(ObjSectionList[0]) then
  567. al := TObjSection(ObjSectionList[0]).dataalignbytes;
  568. u32 := dataPos+al; FWriter.write(u32,sizeof(u32));
  569. u32 := size-al; FWriter.write(u32,sizeof(u32));
  570. end;
  571. end;
  572. procedure TNLMexeoutput.ExeSectionList_pass2_header(p:TObject;arg:pointer);
  573. var len,alignAmount:longint;
  574. begin
  575. {list of sections, extension of binutils,CuStHeAd points to this list
  576. The format of the section information is:
  577. null terminated section name
  578. zeroes to adjust to 4 byte boundary
  579. 4 byte section data file pointer
  580. 4 byte section size }
  581. with TExeSection(p) do
  582. begin
  583. alignAmount := 4 - ((length (Name) + 1) MOD 4);
  584. len := length(name) + 1 + alignAmount + 8;
  585. if ObjSectionList.Count>0 then
  586. inc(len,TObjSection(ObjSectionList[0]).dataalignbytes);
  587. inc(plongint(arg)^,len);
  588. end;
  589. end;
  590. procedure TNLMexeoutput.DataPos_Header;
  591. begin
  592. ExeSecsListSize:=0;
  593. ExeSectionList.ForEachCall(@ExeSectionList_pass2_header,@ExeSecsListSize);
  594. headerAlignBytes := align(totalheadersize+ExeSecsListSize,16)-(totalheadersize+ExeSecsListSize); // align as in TObjData.sectiontype2align
  595. currdatapos:=totalheadersize+ExeSecsListSize+headerAlignBytes;
  596. end;
  597. procedure TNLMexeoutput.fillNlmVersionHeader;
  598. var
  599. hour,min,sec,hsec,Year,Month,Day : word;
  600. begin
  601. DecodeTime(Time,hour,min,sec,hsec);
  602. DecodeDate(Date,year,month,day);
  603. nlmVersionHeader.stamp := NLM_VERSION_STAMP;
  604. if nlmVersionHeader.year = 0 then
  605. begin
  606. nlmVersionHeader.year := Year;
  607. nlmVersionHeader.month := Month;
  608. nlmVersionHeader.day := Day;
  609. end;
  610. end;
  611. function TNLMexeoutput.writedata:boolean;
  612. var
  613. dummyLong : array[0..4] of char;
  614. textExeSec,
  615. dataExeSec,
  616. bssExeSec,
  617. relocsExeSec,
  618. exportsExeSec,
  619. importsExeSec,
  620. xdcExeSec,
  621. messagesExeSec,
  622. helpExeSec,
  623. customExeSec : TExeSection;
  624. hassymbols : boolean;
  625. nlmCygnusHeader : nlm32_i386_external_cygnus_ext_header;
  626. ModuleName : string;
  627. exesym : TExeSymbol;
  628. expOffset : PtrUInt;
  629. expAddr : longword;
  630. i : integer;
  631. begin
  632. result:=false;
  633. textExeSec:=FindExeSection('.text');
  634. dataExeSec:=FindExeSection('.data');
  635. bssExeSec:=FindExeSection('.bss');
  636. relocsExeSec:=FindExeSection('.reloc');
  637. importsExeSec:=FindExeSection('.imports');
  638. exportsExeSec:=FindExeSection('.exports');
  639. xdcExeSec:=FindExeSection('.xdc');
  640. messagesExeSec:=FindExeSection('.messages');
  641. helpExeSec:=FindExeSection('.help');
  642. customExeSec:=FindExeSection('.custom');
  643. // exported function need the upper bit in the address
  644. // to be set (=CODE), do this here to avoid another
  645. // reloc type. The ExportFunctionOffsets list was
  646. // filled in GenerateExports
  647. if FexportFunctionOffsets.Count>0 then
  648. begin
  649. if not assigned(exportsExeSec) then
  650. internalerror(201103201); // we have to have a .export section
  651. if not assigned(exportsExeSec.ObjSectionList[0]) then
  652. internalerror(201103202); // nothing in the .exports section but we have data in FexportFunctionOffsets
  653. for i := 0 to FexportFunctionOffsets.Count-1 do
  654. begin
  655. expOffset := PtrUint(FexportFunctionOffsets[i]);
  656. if TObjSection(exportsExeSec.ObjSectionList[0]).Data.size < expOffset+3 then
  657. internalerror(201103203); // offset in FexportFunctionOffsets out of range
  658. with TObjSection(exportsExeSec.ObjSectionList[0]) do
  659. begin // set the upper bit of address to indicate .text
  660. Data.seek(expOffset);
  661. Data.read(expAddr,4);
  662. Data.seek(expOffset);
  663. expAddr := expAddr or $80000000;
  664. Data.write(expAddr,4);
  665. end;
  666. end;
  667. end;
  668. if not assigned(TextExeSec) or
  669. not assigned(RelocsExeSec) or
  670. not assigned(DataExeSec) then
  671. internalerror(200602231); // we have to have .data, .text and .reloc
  672. { do we need to write symbols? }
  673. hassymbols:=(ExeWriteMode=ewm_dbgonly) or
  674. (
  675. (ExeWriteMode=ewm_exefull) and
  676. not(cs_link_strip in current_settings.globalswitches)
  677. );
  678. { Initial header, will be updated later }
  679. nlmHeader.signature := NLM_SIGNATURE;
  680. nlmHeader.version := NLM_HEADER_VERSION;
  681. moduleName := upperCase(current_module.exefilename);
  682. nlmHeader.moduleName := moduleName;
  683. nlmHeader.codeImageOffset := TextExeSec.DataPos+TObjSection(TextExeSec.ObjSectionList[0]).dataalignbytes; // ??? may be that align has to be moved to fixups/imports
  684. nlmHeader.codeImageSize := TextExeSec.Size;
  685. nlmHeader.dataImageOffset := DataExeSec.DataPos;
  686. nlmHeader.dataImageSize := DataExeSec.Size;
  687. if assigned(BSSExeSec) then
  688. nlmHeader.uninitializedDataSize:=BSSExeSec.Size;
  689. if assigned(customExeSec) then
  690. begin
  691. nlmHeader.customDataOffset := customExeSec.DataPos;
  692. nlmHeader.customDataSize := customExeSec.Size;
  693. end;
  694. if FNumModules > 0 then
  695. begin
  696. nlmHeader.moduleDependencyOffset := FindExeSection('.modules').DataPos+4; // 4 bytes dummy
  697. nlmHeader.numberOfModuleDependencies := FNumModules;
  698. end;
  699. nlmHeader.relocationFixupOffset := relocsExeSec.DataPos;
  700. nlmHeader.numberOfRelocationFixups := FNumRelocs;
  701. nlmHeader.externalReferencesOffset := importsExeSec.DataPos+4; // 4 bytes dummy
  702. nlmHeader.numberOfExternalReferences := FNumExternals;
  703. if assigned(exportsExeSec) then
  704. if exportsExeSec.Size>0 then
  705. begin
  706. nlmHeader.publicsOffset := exportsExeSec.dataPos;
  707. nlmHeader.numberOfPublics := FnumExports;
  708. end;
  709. nlmHeader.codeStartOffset := EntrySym.Address;
  710. {exit function}
  711. exesym:=texesymbol(ExeSymbolList.Find('_Stop'));
  712. if assigned(exesym) then
  713. nlmHeader.exitProcedureOffset := exesym.ObjSymbol.address;
  714. {check exit function}
  715. exesym:=texesymbol(ExeSymbolList.Find('FPC_NW_CHECKFUNCTION'));
  716. if assigned(exesym) then
  717. nlmHeader.checkUnloadProcedureOffset := exesym.ObjSymbol.address;
  718. // calc file pos after all exesections
  719. fSizeWoDebugSyms := totalheadersize + ExeSecsListSize + headerAlignBytes;
  720. ExeSectionList.ForEachCall(@ExeSectionList_calc_size,nil);
  721. nlmExtHeader.stamp := NLM_MESSAGES_STAMP;
  722. //extHeader.languageID // TODO: where to get this from ?
  723. if assigned(messagesExeSec) then
  724. begin
  725. nlmExtHeader.messageFileOffset := messagesExeSec.DataPos;
  726. nlmExtHeader.messageFileLength := messagesExeSec.Size;
  727. end;
  728. //nlmExtHeader.messageCount // TODO: how is messageCount set ?
  729. if assigned(helpExeSec) then
  730. begin
  731. nlmExtHeader.helpFileOffset := helpExeSec.DataPos;
  732. nlmExtHeader.helpFileLength := helpExeSec.Size;
  733. end;
  734. //nlmExtHeader.productID // TODO: were does this came from ?
  735. if assigned(xdcExeSec) then
  736. begin
  737. nlmExtHeader.RPCDataOffset := xdcExeSec.DataPos;
  738. nlmExtHeader.RPCDataLength := xdcExeSec.Size;
  739. end;
  740. if hassymbols then
  741. begin
  742. nlmHeader.debugInfoOffset := fSizeWoDebugSyms;
  743. ExeSymbolList.ForEachCall(@globalsyms_create_symbol,nil);
  744. nlmHeader.numberOfDebugRecords := FNumDebugSymbols;
  745. end;
  746. fillNlmVersionHeader;
  747. FWriter.write(nlmHeader,sizeof(nlmHeader));
  748. { variable header }
  749. NLMWriteString(nlmDescription,true);
  750. if stacksize < NLM_DEFAULT_STACKSIZE then stacksize := NLM_DEFAULT_STACKSIZE;
  751. FWriter.Write(stacksize,4);
  752. FWriter.writezeros(4);
  753. dummyLong := ' LONG';
  754. FWriter.Write(dummyLong,sizeof(dummyLong)); // old thread name
  755. NLMWriteString(nlmScreenname,true);
  756. NLMWriteString(nlmThreadname,true);
  757. {version}
  758. FWriter.Write(nlmVersionHeader,sizeof(nlmVersionHeader));
  759. {copyright}
  760. if nlmCopyright <> '' then
  761. begin
  762. FWriter.write(NLM_COPYRIGHT_STAMP,sizeof(NLM_COPYRIGHT_STAMP));
  763. NLMWriteString(nlmCopyright,true);
  764. end;
  765. {messages}
  766. FWriter.write(nlmExtHeader,sizeof(nlmExtHeader));
  767. {custhead}
  768. nlmCustHeader.stamp := NLM_CUSTOM_STAMP;
  769. nlmCustHeader.dataLength := ExeSecsListSize;
  770. nlmCustHeader.dataOffset := totalheadersize;
  771. nlmCustHeader.hdrLength := $10; // why 16 ?, this is what binutils write
  772. FWriter.write(nlmCustHeader,sizeof(nlmCustHeader));
  773. {CyGnUsEx}
  774. // bfd has a strange way to read the sections:
  775. // the section directory is written under CuStHeAd
  776. // when bfd finds the neader "CyGnUsEx", it uses the
  777. // offset and size from CuStHeAd to read the section table
  778. nlmCygnusHeader.stamp := NLM_CYGNUS_STAMP; // CyGnUsEx
  779. // ld writes some unknown values here, bfd irgnores the values at all
  780. // lets write the offset and length of the segment table
  781. nlmCygnusHeader.offset := nlmCustHeader.dataLength;
  782. nlmCygnusHeader.length := nlmCustHeader.dataOffset;
  783. FWriter.write(nlmCygnusHeader,sizeof(nlmCygnusHeader));
  784. FWriter.WriteZeros(8); // empty stamp + align next to 16 bytes
  785. if FWriter.Size<>totalheadersize then
  786. internalerror(201103061); // headersize <> header written
  787. { Section headers, CuStHeAd points to this section, not needed by
  788. netware. Can be used to find the section in the nlm file, binutils
  789. will use this section }
  790. ExeSectionList.ForEachCall(@ExeSectionList_write_header,nil);
  791. FWriter.WriteZeros(headerAlignBytes);
  792. if FWriter.Size<>totalheadersize+ExeSecsListSize+headerAlignBytes then
  793. internalerror(201103062);
  794. { Section data }
  795. if assigned(exemap) then
  796. begin
  797. exemap.Add('');
  798. exemap.Add('NLM file offsets:');
  799. end;
  800. ExeSectionList.ForEachCall(@ExeSectionList_write_data,nil);
  801. if hassymbols then
  802. FWriter.writearray(NlmSymbols); // specific symbols for the internal netware debugger
  803. result:=true;
  804. end;
  805. procedure TNLMexeoutput.GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);
  806. var
  807. idata5objsection : TObjSection;
  808. basedllname : string;
  809. function AddImport(const afuncname,amangledname:string; isvar:boolean):TObjSymbol;
  810. var
  811. secname:string;
  812. begin
  813. //Comment (V_Debug,'TNLMexeoutput.GenerateLibraryImports.AddImport '+afuncName);
  814. result:=nil;
  815. if assigned(exemap) then
  816. exemap.Add(' Importing Function '+afuncname);
  817. if not isvar then
  818. with internalobjdata do
  819. begin
  820. secname:=basedllname+'_i_'+amangledname;
  821. idata5objsection:=createsection(sec_idata5, secname);
  822. internalobjdata.SetSection(idata5objsection);
  823. result:=internalobjdata.SymbolDefine('_'+amangledname,AB_IMPORT,AT_FUNCTION);
  824. end;
  825. end;
  826. var
  827. i,j : longint;
  828. ImportLibrary : TImportLibrary;
  829. ImportSymbol : TImportSymbol;
  830. exesym : TExeSymbol;
  831. importAddressList : TFPObjectList;
  832. begin
  833. if ImportLibraryList.Count > 0 then
  834. begin
  835. {objsec:=}internalObjData.createsection('.imports',0,[oso_data,oso_keep]);
  836. i := 0;
  837. internalobjdata.writebytes(i,4); // dummy to avoid deletion
  838. {objsec:=}internalObjData.createsection('.modules',0,[oso_data,oso_keep]);
  839. internalobjdata.writebytes(i,4); // dummy to avoid deletion
  840. end;
  841. for i:=0 to ImportLibraryList.Count-1 do
  842. begin
  843. ImportLibrary:=TImportLibrary(ImportLibraryList[i]);
  844. idata5objsection:=nil;
  845. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  846. begin
  847. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  848. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  849. if assigned(exesym) and
  850. (exesym.State<>symstate_defined) then
  851. begin
  852. basedllname:=ExtractFileName(ImportLibrary.Name);
  853. exesym.objsymbol:=AddImport(ImportSymbol.Name,ImportSymbol.MangledName,ImportSymbol.IsVar);
  854. exesym.State:=symstate_defined;
  855. importAddressList := TFPObjectList.create(false);
  856. nlmImports.Add(ImportSymbol.Name,importAddressList);
  857. if pos('.',basedllname) = 0 then
  858. basedllname := basedllname + '.nlm';
  859. nlmImpNames.Add(ImportSymbol.Name,TStringObj.create(lower(basedllname)));
  860. end;
  861. end;
  862. end;
  863. PackUnresolvedExeSymbols('after DLL imports');
  864. GenerateExports;
  865. end;
  866. procedure TNLMexeoutput.GenerateImports;
  867. var
  868. exesec,
  869. impexesec : TExeSection;
  870. objsec : TObjSection;
  871. objreloc : TObjRelocation;
  872. i,j,k : integer;
  873. importAddressList : TFPObjectList;
  874. name,mName : string;
  875. b : byte;
  876. modules : string;
  877. modName : TStringObj;
  878. begin
  879. if FImportsGenerated then exit;
  880. FImportsGenerated := true;
  881. impexesec:=FindExeSection('.imports');
  882. if impexesec=nil then exit;
  883. for i:=0 to ExeSectionList.Count-1 do
  884. begin
  885. exesec:=TExeSection(ExeSectionList[i]);
  886. for j:=0 to exesec.ObjSectionList.count-1 do
  887. begin
  888. objsec:=TObjSection(exesec.ObjSectionList[j]);
  889. if (copy(objsec.name,1,5) <> '.text') and (copy(objsec.name,1,4) <> '.bss') and (copy(objsec.name,1,5) <> '.data') then
  890. continue;
  891. for k:=0 to objsec.ObjRelocations.Count-1 do
  892. begin
  893. objreloc := TObjRelocation(objsec.ObjRelocations[k]);
  894. if assigned(objreloc.symbol) then
  895. begin
  896. //writeln (objreloc.symbol.name,' ',objreloc.symbol.bind);
  897. if objreloc.symbol.bind = AB_IMPORT then
  898. begin
  899. importAddressList := TFPObjectList(nlmImports.Find(objreloc.symbol.name));
  900. if assigned(importAddressList) then
  901. begin
  902. objreloc.objsection := objsec; // points to idata5
  903. importAddressList.Add(objreloc);
  904. end else
  905. begin
  906. comment(v_error,objreloc.symbol.name+' is external but not defined in nlm imports');
  907. end;
  908. end;
  909. end
  910. end;
  911. end;
  912. end;
  913. modules := '';
  914. for i := 0 to nlmImports.count-1 do
  915. begin
  916. importAddressList := TFPObjectList(nlmImports.Items[i]);
  917. if importAddressList.Count > 0 then
  918. begin
  919. name := nlmImports.NameOfIndex(i);
  920. // find the module to be imported and add it to the list
  921. // of modules to be auto loaded
  922. modName := TStringObj(nlmImpNames.Find(name));
  923. if assigned(modName) then
  924. begin
  925. mName := modName.Value;
  926. if mName <> '' then
  927. if copy(mName,1,1) <> '!' then // special, with ! only the imp will be included but no module is autoloaded, needed i.e. for netware.imp
  928. begin
  929. if pos(mName+';',modules) < 1 then
  930. begin
  931. modules := modules + mName + ';';
  932. inc(FNumModules);
  933. end;
  934. end;
  935. end;
  936. internalobjdata.SetSection(TObjSection(impexesec.ObjSectionList[0]));
  937. objNLMwriteString (name,false); // name of symbol
  938. k := importAddressList.Count;
  939. internalobjdata.writebytes(k,sizeof(k)); // number of references
  940. inc(FNumExternals);
  941. for j := 0 to importAddressList.Count-1 do
  942. begin
  943. objreloc := TObjRelocation(importAddressList[j]);
  944. objsec := objreloc.objsection;
  945. if oso_executable in objreloc.objsection.SecOptions then
  946. begin
  947. if objreloc.typ <> RELOC_RELATIVE then comment(v_error,'reference to external symbols must be RELOC_RELATIVE');
  948. // TODO: how to check if size is 4 ????
  949. k := objsec.MemPos + objreloc.DataOffset;
  950. k := k or $40000000;
  951. // TODO: data|code if we support importing data symbols
  952. // i do not know if this is possible with netware
  953. internalobjdata.writebytes(k,sizeof(k)); // address
  954. // the netware loader requires an offset at the import address
  955. // for call = E8 this is -4
  956. // TODO: how can we check the needed offset ??
  957. if objreloc.DataOffset > 0 then
  958. begin
  959. objsec.Data.seek(objreloc.DataOffset-1);
  960. objsec.data.read(b,1);
  961. if b <> $E8 then
  962. comment(v_error,'no rcall (E8) before imported symbol target address');
  963. k := -4;
  964. objsec.Data.write(k,sizeof(k));
  965. end else
  966. begin
  967. objsec.Data.seek(objreloc.DataOffset);
  968. k := 0;
  969. objsec.Data.write(k,sizeof(k));
  970. end;
  971. objreloc.typ := RELOC_NONE; // to avoid that TCoffObjSection.fixuprelocs changes the address again
  972. end else
  973. comment(v_error,'Importing of symbols only supported for .text');
  974. end;
  975. end;
  976. end;
  977. exesec := FindExeSection('.modules');
  978. if not assigned(exesec) then internalerror(201103272); // exe section .modules does not exist ???
  979. internalobjdata.SetSection(TObjSection(exesec.ObjSectionList[0]));
  980. for i := 1 to FNumModules do
  981. begin
  982. name := GetToken(modules,';');
  983. objNLMwriteString (name,false);
  984. end;
  985. end;
  986. procedure TNLMexeoutput.GenerateExports;
  987. var
  988. hp : texported_item; { for exports }
  989. len : byte;
  990. addr: longword;
  991. exesym : texesymbol;
  992. begin
  993. internalObjData.createsection('.exports',0,[oso_data,oso_keep]);
  994. {name LString 1+n bytes
  995. addr 4 bytes
  996. addr and $80000000 > 0 -> .text else .data}
  997. hp:=texported_item(current_module._exports.first);
  998. if assigned(hp) then
  999. if assigned(exemap) then
  1000. exemap.Add('');
  1001. while assigned(hp) do
  1002. begin
  1003. { Export the Symbol }
  1004. if assigned(exemap) then
  1005. exemap.Add(' Exporting Function '+hp.sym.prettyname+' as '+hp.name^);
  1006. len := length(hp.name^);
  1007. internalobjdata.writebytes(len,1);
  1008. internalobjdata.writebytes(hp.name^[1],len);
  1009. exesym:=texesymbol(ExeSymbolList.Find(hp.sym.prettyname));
  1010. if not assigned(exesym) then
  1011. begin
  1012. comment(v_error,'exported symbol '+hp.sym.prettyname+' not found');
  1013. exit;
  1014. end;
  1015. // for exported functions we have to set the upper bit
  1016. // this will be done in .writedata
  1017. if not hp.is_var then
  1018. FexportFunctionOffsets.Add(pointer(PtrUInt(internalobjdata.CurrObjSec.Size)));
  1019. internalobjdata.writereloc(0,4,exesym.ObjSymbol,RELOC_ABSOLUTE32);
  1020. addr := 0;
  1021. internalobjdata.writebytes(addr,4);
  1022. inc(FnumExports);
  1023. hp:=texported_item(hp.next);
  1024. end;
  1025. end;
  1026. procedure TNLMexeoutput.GenerateRelocs;
  1027. var
  1028. exesec : TExeSection;
  1029. objsec : TObjSection;
  1030. objreloc : TObjRelocation;
  1031. i,j,k : longint;
  1032. offset : longword;
  1033. inSec,toSec : TsecType;
  1034. targetSectionName : string;
  1035. begin
  1036. if FRelocsGenerated then
  1037. exit;
  1038. exesec:=FindExeSection('.reloc');
  1039. if exesec=nil then
  1040. exit;
  1041. objsec:=internalObjData.createsection('.reloc',0,[oso_data,oso_load,oso_keep]);
  1042. exesec.AddObjSection(objsec);
  1043. for i:=0 to ExeSectionList.Count-1 do
  1044. begin
  1045. exesec:=TExeSection(ExeSectionList[i]);
  1046. for j:=0 to exesec.ObjSectionList.count-1 do
  1047. begin
  1048. objsec:=TObjSection(exesec.ObjSectionList[j]);
  1049. //writeln ('Relocs for ',exesec.name,' - ',objsec.name);
  1050. { create relocs only for sections which are loaded in memory }
  1051. if not (oso_load in objsec.SecOptions) then
  1052. continue;
  1053. { create relocs only for .text and .data }
  1054. inSec := SectionType (objsec.name);
  1055. if (inSec <> Section_Text) and (inSec <> Section_Data) then
  1056. continue;
  1057. for k:=0 to objsec.ObjRelocations.Count-1 do
  1058. begin
  1059. objreloc:=TObjRelocation(objsec.ObjRelocations[k]);
  1060. if objreloc.typ <> RELOC_ABSOLUTE then
  1061. continue;
  1062. offset:=objsec.MemPos+objreloc.dataoffset;
  1063. targetSectionName := '';
  1064. if objreloc.symbol <> nil then
  1065. begin
  1066. // writeln (' MemPos',objsec.MemPos,
  1067. // ' dataOfs:',objreloc.dataoffset,' ',objsec.name,
  1068. // ' objreloc.symbol: ',objreloc.symbol.name,
  1069. // ' objreloc.symbol.objsection.name: ',objreloc.symbol.objsection.name,
  1070. // ' ',objreloc.symbol.Typ,' ',objrel
  1071. // oc.symbol.bind,' ',objreloc.Typ);
  1072. if objreloc.symbol.objsection.name[1] <> '.' then
  1073. targetSectionName := objreloc.symbol.name // specials like __bss_start__
  1074. else // dont use objsection.name because it begins with *
  1075. targetSectionName := copy(objreloc.symbol.objsection.name,1,5); // all others begin with .segment, we only have to check for .text, .data or .bss
  1076. end else
  1077. internalerror(2011030603);
  1078. toSec := SectionType(targetSectionName);
  1079. if (toSec = Section_Text) or (toSec = Section_Data) then
  1080. begin
  1081. if (inSec = Section_text) then offset := offset or $40000000;
  1082. if (toSec = Section_text) then offset := offset or $80000000;
  1083. internalObjData.writebytes(offset,4);
  1084. inc(FNumRelocs);
  1085. end;
  1086. end;
  1087. end;
  1088. end;
  1089. FRelocsGenerated:=true;
  1090. end;
  1091. procedure TNLMexeoutput.MemPos_Start;
  1092. var
  1093. exesec : TExeSection;
  1094. begin
  1095. exesec:=FindExeSection('.reloc');
  1096. if exesec=nil then
  1097. InternalError(2012072602);
  1098. exesec.Disabled:=false;
  1099. inherited;
  1100. end;
  1101. procedure TNLMexeoutput.MemPos_ExeSection(const aname:string);
  1102. begin
  1103. if aname='.reloc' then
  1104. GenerateRelocs;
  1105. if aname='.imports' then
  1106. GenerateImports;
  1107. if aname='.data' then
  1108. currMemPos := 0; // both, data and code in the nlm have a start offset of 0
  1109. inherited;
  1110. end;
  1111. procedure TNLMexeoutput.NLMwriteString (const s : string; terminateWithZero : boolean);
  1112. var len : byte;
  1113. begin
  1114. if length(s) > 254 then len := 254 else len := length(s);
  1115. FWriter.Write(len,1);
  1116. if len > 0 then
  1117. FWriter.write(s[1],len);
  1118. if terminateWithZero then
  1119. FWriter.writeZeros(1);
  1120. end;
  1121. procedure TNLMexeoutput.objNLMwriteString (const s : string; terminateWithZero : boolean);
  1122. var len : byte;
  1123. begin
  1124. if length(s) > 254 then len := 254 else len := length(s);
  1125. Internalobjdata.writebytes(len,1);
  1126. if len > 0 then
  1127. Internalobjdata.writebytes(s[1],len);
  1128. if terminateWithZero then
  1129. begin
  1130. len := 0;
  1131. Internalobjdata.writebytes(s[1],len);
  1132. end;
  1133. end;
  1134. { parse netware specific linker options }
  1135. procedure TNLMexeoutput.ParseScript (linkscript:TCmdStrList);
  1136. var
  1137. hp : TCmdStrListItem;
  1138. opt,keyword,s : string;
  1139. i : integer;
  1140. function toInteger(s:string; min,max:integer; var res:integer):boolean;
  1141. var
  1142. code:word;
  1143. begin
  1144. result := false;
  1145. val (s,res,code);
  1146. if code<>0 then exit;
  1147. if (res < min) or (res > max) then exit;
  1148. result := true;
  1149. end;
  1150. procedure loadFile (const secName, fileName, Desc : string);
  1151. var
  1152. fileBuf : array [0..4095] of char;
  1153. bytesRead : longint;
  1154. fileH : THandle;
  1155. fn : TCmdStr;
  1156. begin
  1157. fn := fileName;
  1158. if not fileExists(fn) then
  1159. if not unitsearchpath.FindFile(fileName,true,fn) then
  1160. begin
  1161. comment(v_error,'can not find '+desc+' file '+fileName);
  1162. exit;
  1163. end;
  1164. fileH := fileOpen (fn,fmOpenRead);
  1165. if fileH = THandle(-1) then
  1166. begin
  1167. comment(v_error,'can not open '+desc+' file '+fn);
  1168. exit;
  1169. end;
  1170. { load file into section }
  1171. internalObjData.createsection(secName,0,[oso_data,oso_keep]);
  1172. repeat
  1173. bytesRead := fileRead(fileH,fileBuf,sizeof(fileBuf));
  1174. if bytesRead > 0 then
  1175. internalobjdata.writebytes(fileBuf,bytesRead);
  1176. until bytesRead < sizeof(fileBuf);
  1177. fileClose(fileH);
  1178. end;
  1179. begin
  1180. hp:=TCmdStrListItem(linkscript.first);
  1181. while assigned(hp) do
  1182. begin
  1183. opt:=hp.str;
  1184. if (opt='') or (opt[1]='#') then
  1185. continue;
  1186. keyword:=Upper(GetToken(opt,' '));
  1187. if keyword = 'AUTOUNLOAD' then
  1188. begin
  1189. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_AUTOUNLOAD;
  1190. end else
  1191. if keyword = 'COPYRIGHT' then
  1192. begin
  1193. nlmCopyright := GetToken(opt,' ');
  1194. end else
  1195. if keyword = 'CUSTOM' then
  1196. begin
  1197. loadFile ('.custom',GetToken(opt,' '),'custom data');
  1198. end;
  1199. if keyword = 'DATE' then // month day 4-digit-year
  1200. begin
  1201. if not toInteger(GetToken(opt,' '),1,12,i) then comment(v_error,'DATE: invalid month')
  1202. else nlmVersionHeader.month := i;
  1203. if not toInteger(GetToken(opt,' '),1,31,i) then comment(v_error,'DATE: invalid day')
  1204. else nlmVersionHeader.day := i;
  1205. if not toInteger(GetToken(opt,' '),1900,3000,i) then comment(v_error,'DATE: invalid year')
  1206. else nlmVersionHeader.year := i;
  1207. end else
  1208. if keyword = 'DEBUG' then
  1209. begin
  1210. // ignore
  1211. end else
  1212. if keyword = 'DESCRIPTION' then
  1213. begin
  1214. nlmDescription := GetToken(opt,' ');
  1215. if length (nlmDescription) > NLM_MAX_DESCRIPTION_LENGTH then
  1216. nlmDescription := copy (nlmDescription,1,NLM_MAX_DESCRIPTION_LENGTH);
  1217. end else
  1218. if keyword = 'FLAG' then
  1219. begin
  1220. s := upper(GetToken(opt,' '));
  1221. if (not toInteger(GetToken(opt,' '),1,$FFFFFFF,i)) or ((s <> 'ON') and (S <> 'OFF')) then comment(v_error,'FLAG: invalid') else
  1222. if (s='ON') then
  1223. nlmHeader.flags:=nlmHeader.flags or i else
  1224. nlmHeader.flags:=nlmHeader.flags and ($FFFFFFF-i);
  1225. end else
  1226. if keyword = 'HELP' then
  1227. begin
  1228. loadFile ('.help',GetToken(opt,' '),'help');
  1229. end else
  1230. if keyword = 'MESSAGES' then
  1231. begin
  1232. loadFile ('.messages',GetToken(opt,' '),'message');
  1233. end else
  1234. if keyword = 'MULTIPLE' then
  1235. begin
  1236. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_MULTILOAD;
  1237. end else
  1238. if keyword = 'OS_DOMAIN' then
  1239. begin
  1240. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_OSDOMAIN;
  1241. end else
  1242. if keyword = 'PSEUDOPREEMPTION' then
  1243. begin
  1244. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_PSEUDOPREEMPTION;
  1245. end else
  1246. if keyword = 'REENTRANT' then
  1247. begin
  1248. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_REENTRANT;
  1249. end else
  1250. if keyword = 'SCREENNAME' then
  1251. begin
  1252. nlmScreenname := GetToken(opt,' ');
  1253. if length(nlmScreenname) > NLM_MAX_SCREEN_NAME_LENGTH then
  1254. nlmScreenName := copy (nlmScreenName,1,NLM_MAX_SCREEN_NAME_LENGTH);
  1255. end else
  1256. if (keyword = 'STACK') or (keyword = 'STACKSIZE') then
  1257. begin
  1258. if (not toInteger(GetToken(opt,' '),1,$FFFFFFF,i)) then comment(v_error,'invalid stacksize') else
  1259. stacksize := i;
  1260. end else
  1261. if keyword = 'SYNCHRONIZE' then
  1262. begin
  1263. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_SYNCHRONIZE;
  1264. end else
  1265. if keyword = 'THREADNAME' then
  1266. begin
  1267. nlmThreadname := GetToken(opt,' ');
  1268. if length(nlmThreadname) > NLM_MAX_THREAD_NAME_LENGTH then
  1269. nlmThreadname := copy (nlmThreadname,1,NLM_MAX_THREAD_NAME_LENGTH);
  1270. end else
  1271. if keyword = 'TYPE' then
  1272. begin
  1273. if (not toInteger(GetToken(opt,' '),1,16,i)) then comment(v_error,'invalid TYPE') else
  1274. nlmHeader.moduleType := i; // TODO: set executable extension (.DSK, .LAN, ...)
  1275. end else
  1276. if keyword = 'VERSION' then
  1277. begin
  1278. if (not toInteger(GetToken(opt,' '),0,$FFFFFFF,i)) then comment(v_error,'invalid major version') else
  1279. nlmVersionHeader.majorVersion := i;
  1280. if (not toInteger(GetToken(opt,' '),0,99,i)) then comment(v_error,'invalid minor version') else
  1281. nlmVersionHeader.minorVersion := i;
  1282. if (not toInteger(GetToken(opt,' '),0,$FFFFFFF,i)) then comment(v_error,'invalid minor version') else
  1283. if i > 26 then
  1284. nlmVersionHeader.revision := 0 else
  1285. nlmVersionHeader.revision := i;
  1286. end else
  1287. if keyword = 'XDCDATA' then
  1288. begin
  1289. loadFile ('.xdc',GetToken(opt,' '),'xdc');
  1290. end;
  1291. { TODO: check for unknown options. This means all handled option
  1292. (also in link.pas) have to be flagged if processed }
  1293. hp:=TCmdStrListItem(hp.next);
  1294. end;
  1295. end;
  1296. {****************************************************************************
  1297. TNLMCoffObjData
  1298. ****************************************************************************}
  1299. constructor TNLMCoffObjData.create(const n:string);
  1300. begin
  1301. inherited createcoff(n,true,TNLMCoffObjSection);
  1302. end;
  1303. {****************************************************************************
  1304. TNLMoffObjSection
  1305. ****************************************************************************}
  1306. constructor TNLMCoffObjSection.create(AList:TFPHashObjectList;const aname:string;aalign:longint;aoptions:TObjSectionOptions);
  1307. begin
  1308. inherited create(alist,aname,aalign,aoptions);
  1309. end;
  1310. constructor TNLMCoffObjOutput.create(AWriter:TObjectWriter);
  1311. begin
  1312. // ??????
  1313. // if win32=false, .stabs and .stabstr will be written without oso_debug
  1314. // Without oso_debug the sections will be removed by the linker
  1315. inherited createcoff(AWriter,{win32}true);
  1316. cobjdata:=TNLMCoffObjData;
  1317. end;
  1318. {****************************************************************************
  1319. TDJCoffAssembler
  1320. ****************************************************************************}
  1321. constructor TNLMCoffAssembler.Create(info: pasminfo; smart:boolean);
  1322. begin
  1323. inherited;
  1324. CObjOutput:=TNLMCoffObjOutput;
  1325. CInternalAr:=tarobjectwriter;
  1326. end;
  1327. constructor TNLMCoffObjInput.create;
  1328. begin
  1329. inherited createcoff(true);
  1330. cobjdata:=TNLMCoffObjData;
  1331. end;
  1332. {*****************************************************************************
  1333. Initialize
  1334. *****************************************************************************}
  1335. const
  1336. as_i386_nlmcoff_info : tasminfo =
  1337. (
  1338. id : as_i386_nlmcoff;
  1339. idtxt : 'NLMCOFF';
  1340. asmbin : '';
  1341. asmcmd : '';
  1342. supported_targets : [system_i386_Netware,system_i386_netwlibc];
  1343. flags : [af_outputbinary,af_smartlink_sections];
  1344. labelprefix : '.L';
  1345. labelmaxlen : -1;
  1346. comment : '';
  1347. dollarsign: '$';
  1348. );
  1349. initialization
  1350. {$ifdef i386}
  1351. RegisterAssembler(as_i386_nlmcoff_info,TNLMCoffAssembler);
  1352. {$endif i386}
  1353. end.