ognlm.pas 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510
  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(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:shortint;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
  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. nlmImpNames.Free;
  343. nlmSymbols.Free;
  344. FexportFunctionOffsets.Free;
  345. inherited destroy;
  346. end;
  347. procedure TNLMexeoutput.createNlm_symbol(const name:shortstring;value:longword;secType:TSecType);
  348. var
  349. b:byte;
  350. begin
  351. //Comment (V_Debug,'TNLMexeoutput.write_symbol '+name);
  352. { type (0=.data,1=.code,2,..=????) 1 byte
  353. addr 4 bytes
  354. name LString 1+n bytes }
  355. case secType of
  356. Section_Text : b := 1;
  357. Section_Data : b := 0
  358. else
  359. exit;
  360. end;
  361. nlmSymbols.write(b,sizeof(b));
  362. assert (sizeof(value)<>4);
  363. nlmSymbols.write(value,sizeof(value));
  364. nlmSymbols.write(name[0],length(name)+1);
  365. inc(FNumDebugSymbols);
  366. end;
  367. procedure TNLMexeoutput.globalsyms_create_symbol(p:TObject;arg:pointer);
  368. var
  369. value : longword;
  370. exesec : TExeSection;
  371. i : integer;
  372. secType : TsecType;
  373. begin
  374. if not assigned(texesymbol(p).objsymbol) then
  375. internalerror(200603053);
  376. with texesymbol(p).objsymbol do
  377. begin
  378. exesec:=TExeSection(objsection.exesection);
  379. { There is no exesection defined for special internal symbols
  380. like __image_base__ }
  381. if assigned(exesec) then
  382. begin
  383. //secval:=exesec.secsymidx;
  384. value:=address-exesec.mempos;
  385. end
  386. else
  387. begin
  388. value:=address;
  389. end;
  390. { reloctype address to the section in the executable }
  391. secType := SectionType(objsection.Name);
  392. if (secType = Section_Text) or (secType = Section_Data) then
  393. begin
  394. i := nlmImports.FindIndexOf(texesymbol(p).name);
  395. if i < 0 then
  396. createNlm_symbol(name,value,secType);
  397. end;
  398. end;
  399. end;
  400. (*
  401. function SecOpts(SecOptions:TObjSectionOptions):string;
  402. begin
  403. result := '[';
  404. if oso_Data in SecOptions then result := result + 'oso_Data ';
  405. { Is loaded into memory }
  406. if oso_load in SecOptions then result := result + 'oso_load ';
  407. { Not loaded into memory }
  408. if oso_noload in SecOptions then result := result + 'oso_noload ';
  409. { Read only }
  410. if oso_readonly in SecOptions then result := result + 'oso_readonly ';
  411. { Read/Write }
  412. if oso_write in SecOptions then result := result + 'oso_write ';
  413. { Contains executable instructions }
  414. if oso_executable in SecOptions then result := result + 'oso_executable ';
  415. { Never discard section }
  416. if oso_keep in SecOptions then result := result + 'oso_keep ';
  417. { Special common symbols }
  418. if oso_common in SecOptions then result := result + 'oso_common ';
  419. { Contains debug info and can be stripped }
  420. if oso_debug in SecOptions then result := result + 'oso_debug ';
  421. { Contains only strings }
  422. if oso_strings in SecOptions then result := result + 'oso_strings ';
  423. result := result + ']';
  424. end;
  425. *)
  426. procedure TNLMexeoutput.ExeSectionList_calc_size(p:TObject;arg:pointer);
  427. var
  428. objsec : TObjSection;
  429. i : longint;
  430. begin
  431. with texesection(p) do
  432. begin
  433. { don't write normal section if writing only debug info }
  434. if (ExeWriteMode=ewm_dbgonly) and
  435. not(oso_debug in SecOptions) then
  436. exit;
  437. if oso_data in secoptions then
  438. begin
  439. inc (fSizeWoDebugSyms,(Align(fSizeWoDebugSyms,SectionDataAlign)-fSizeWoDebugSyms));
  440. for i:=0 to ObjSectionList.Count-1 do
  441. begin
  442. objsec:=TObjSection(ObjSectionList[i]);
  443. if oso_data in objsec.secoptions then
  444. begin
  445. inc(fSizeWoDebugSyms,objsec.size);
  446. inc(fSizeWoDebugSyms,objsec.dataalignbytes);
  447. end;
  448. end;
  449. end;
  450. end;
  451. end;
  452. procedure TNLMexeoutput.ExeSectionList_write_Data(p:TObject;arg:pointer);
  453. var
  454. objsec : TObjSection;
  455. i,j : longint;
  456. b : byte;
  457. begin
  458. with texesection(p) do
  459. begin
  460. { don't write normal section if writing only debug info }
  461. if (ExeWriteMode=ewm_dbgonly) and
  462. not(oso_debug in SecOptions) then
  463. exit;
  464. if oso_data in secoptions then
  465. begin
  466. //if Align(FWriter.Size,SectionDataAlign)-FWriter.Size>0 then
  467. // writeln (name,' align ',Align(FWriter.Size,SectionDataAlign)-FWriter.Size,' SectionDataAlign:',SectionDataAlign);
  468. FWriter.Writezeros(Align(FWriter.Size,SectionDataAlign)-FWriter.Size);
  469. for i:=0 to ObjSectionList.Count-1 do
  470. begin
  471. objsec:=TObjSection(ObjSectionList[i]);
  472. if oso_data in objsec.secoptions then
  473. begin
  474. if assigned(exemap) then
  475. if objsec.data.size > 0 then
  476. exemap.Add(' 0x'+hexstr(objsec.DataPos,8)+': '+objsec.name);
  477. //writeln (' ',objsec.name,' size:',objsec.size,' relocs:',objsec.ObjRelocations.count,' DataPos:',objsec.DataPos,' MemPos:',objsec.MemPos);
  478. {for j := 0 to objsec.ObjRelocations.count-1 do
  479. begin
  480. objreloc := TObjRelocation(objsec.ObjRelocations[j]);
  481. with objreloc do
  482. begin
  483. write(' reloc DataOffset: ',DataOffset,' OrgSize:',OrgSize,' typ:',typ);
  484. if assigned(symbol) then
  485. write(' Name: '#39,symbol.Name,#39' bind:',symbol.bind,' address:',symbol.address,' Size:',symbol.size);
  486. writeln;
  487. end;
  488. end;}
  489. if not assigned(objsec.data) then
  490. internalerror(200603042);
  491. if copy (objsec.Name,1,5) = '.text' then
  492. begin // write NOP's instead of zero's for .text, makes disassemble possible
  493. b := $90; // NOP
  494. if objsec.DataAlignBytes > 0 then
  495. for j := 1 to objsec.DataAlignBytes do
  496. FWriter.write(b,1);
  497. end else
  498. FWriter.writezeros(objsec.dataalignbytes);
  499. //if objsec.dataalignbytes>0 then
  500. // writeln (' ',name,' alignbytes: ',objsec.dataalignbytes);
  501. if objsec.DataPos<>FWriter.Size then
  502. internalerror(200602251);
  503. FWriter.writearray(objsec.data);
  504. end else
  505. begin
  506. if assigned(exemap) then //TExeMap
  507. exemap.Add(' skipping: '+objsec.name);
  508. end;
  509. end;
  510. end;
  511. end;
  512. end;
  513. function TNLMexeoutput.totalheadersize:longword;
  514. var
  515. varHdrSize,
  516. optHdrSize,
  517. hdrSize: longword;
  518. begin
  519. optHdrSize := 0;
  520. inc(optHdrSize,2+length(nlmDescription));
  521. inc(optHdrSize,8); // Stacksize+reserved
  522. inc(optHdrSize,NLM_OLD_THREAD_NAME_LENGTH);
  523. inc(optHdrSize,2+length(nlmScreenname));
  524. inc(optHdrSize,2+length(nlmThreadname));
  525. varHdrSize := 0;
  526. if nwcopyright <> '' then
  527. inc(varHdrSize,sizeof(NLM_COPYRIGHT_STAMP)+2+length(nlmCopyright));
  528. hdrSize := sizeof(nlm32_i386_external_fixed_header)+
  529. sizeof(nlm32_i386_external_extended_header)+
  530. sizeof(nlm32_i386_external_custom_header)+
  531. sizeof(nlm32_i386_external_version_header)+ // always
  532. sizeof(nlm32_i386_external_cygnus_ext_header)+ // CyGnUsEx
  533. varHdrSize+optHdrSize+
  534. 8; // empty stamp
  535. result := hdrSize;
  536. end;
  537. procedure TNLMexeoutput.MemPos_Header;
  538. begin
  539. { calculate start positions after the headers }
  540. currmempos:=0;
  541. end;
  542. procedure TNLMexeoutput.ExeSectionList_write_header(p:TObject;arg:pointer);
  543. var
  544. nam : string;
  545. u32,al : longword;
  546. alignAmount:longint;
  547. begin
  548. with tExeSection(p) do
  549. begin
  550. //comment (v_debug,'ExeSectionList_write_header: '+name);
  551. nam := name;
  552. alignAmount := 4 - ((length (nam) + 1) MOD 4);
  553. FWriter.write(nam[1],length(nam));
  554. FWriter.WriteZeros(1+alignAmount);
  555. al := 0;
  556. // for .stab we have to ignore leading zeros due to alignment in file
  557. if nam='.stab' then
  558. if assigned(ObjSectionList[0]) then
  559. al := TObjSection(ObjSectionList[0]).dataalignbytes;
  560. u32 := dataPos+al; FWriter.write(u32,sizeof(u32));
  561. u32 := size-al; FWriter.write(u32,sizeof(u32));
  562. end;
  563. end;
  564. procedure TNLMexeoutput.ExeSectionList_pass2_header(p:TObject;arg:pointer);
  565. var len,alignAmount:longint;
  566. begin
  567. {list of sections, extension of binutils,CuStHeAd points to this list
  568. The format of the section information is:
  569. null terminated section name
  570. zeroes to adjust to 4 byte boundary
  571. 4 byte section data file pointer
  572. 4 byte section size }
  573. with TExeSection(p) do
  574. begin
  575. alignAmount := 4 - ((length (Name) + 1) MOD 4);
  576. len := length(name) + 1 + alignAmount + 8;
  577. if ObjSectionList.Count>0 then
  578. inc(len,TObjSection(ObjSectionList[0]).dataalignbytes);
  579. inc(plongint(arg)^,len);
  580. end;
  581. end;
  582. procedure TNLMexeoutput.DataPos_Header;
  583. begin
  584. ExeSecsListSize:=0;
  585. ExeSectionList.ForEachCall(@ExeSectionList_pass2_header,@ExeSecsListSize);
  586. headerAlignBytes := align(totalheadersize+ExeSecsListSize,16)-(totalheadersize+ExeSecsListSize); // align as in TObjData.sectiontype2align
  587. currdatapos:=totalheadersize+ExeSecsListSize+headerAlignBytes;
  588. end;
  589. procedure TNLMexeoutput.fillNlmVersionHeader;
  590. var
  591. hour,min,sec,hsec,Year,Month,Day : word;
  592. begin
  593. DecodeTime(Time,hour,min,sec,hsec);
  594. DecodeDate(Date,year,month,day);
  595. nlmVersionHeader.stamp := NLM_VERSION_STAMP;
  596. if nlmVersionHeader.year = 0 then
  597. begin
  598. nlmVersionHeader.year := Year;
  599. nlmVersionHeader.month := Month;
  600. nlmVersionHeader.day := Day;
  601. end;
  602. end;
  603. function TNLMexeoutput.writedata:boolean;
  604. var
  605. dummyLong : array[0..4] of char;
  606. textExeSec,
  607. dataExeSec,
  608. bssExeSec,
  609. relocsExeSec,
  610. exportsExeSec,
  611. importsExeSec,
  612. xdcExeSec,
  613. messagesExeSec,
  614. helpExeSec,
  615. customExeSec : TExeSection;
  616. hassymbols : boolean;
  617. nlmCygnusHeader : nlm32_i386_external_cygnus_ext_header;
  618. ModuleName : string;
  619. exesym : TExeSymbol;
  620. expOffset : PtrUInt;
  621. expAddr : longword;
  622. i : integer;
  623. begin
  624. result:=false;
  625. textExeSec:=FindExeSection('.text');
  626. dataExeSec:=FindExeSection('.data');
  627. bssExeSec:=FindExeSection('.bss');
  628. relocsExeSec:=FindExeSection('.reloc');
  629. importsExeSec:=FindExeSection('.imports');
  630. exportsExeSec:=FindExeSection('.exports');
  631. xdcExeSec:=FindExeSection('.xdc');
  632. messagesExeSec:=FindExeSection('.messages');
  633. helpExeSec:=FindExeSection('.help');
  634. customExeSec:=FindExeSection('.custom');
  635. // exported function need the upper bit in the address
  636. // to be set (=CODE), do this here to avoid another
  637. // reloc type. The ExportFunctionOffsets list was
  638. // filled in GenerateExports
  639. if FexportFunctionOffsets.Count>0 then
  640. begin
  641. if not assigned(exportsExeSec) then
  642. internalerror(201103201); // we have to have a .export section
  643. if not assigned(exportsExeSec.ObjSectionList[0]) then
  644. internalerror(201103202); // nothing in the .exports section but we have data in FexportFunctionOffsets
  645. for i := 0 to FexportFunctionOffsets.Count-1 do
  646. begin
  647. expOffset := PtrUint(FexportFunctionOffsets[i]);
  648. if TObjSection(exportsExeSec.ObjSectionList[0]).Data.size < expOffset+3 then
  649. internalerror(201103203); // offset in FexportFunctionOffsets out of range
  650. with TObjSection(exportsExeSec.ObjSectionList[0]) do
  651. begin // set the upper bit of address to indicate .text
  652. Data.seek(expOffset);
  653. Data.read(expAddr,4);
  654. Data.seek(expOffset);
  655. expAddr := expAddr or $80000000;
  656. Data.write(expAddr,4);
  657. end;
  658. end;
  659. end;
  660. if not assigned(TextExeSec) or
  661. not assigned(RelocsExeSec) or
  662. not assigned(DataExeSec) then
  663. internalerror(200602231); // we have to have .data, .text and .reloc
  664. { do we need to write symbols? }
  665. hassymbols:=(ExeWriteMode=ewm_dbgonly) or
  666. (
  667. (ExeWriteMode=ewm_exefull) and
  668. not(cs_link_strip in current_settings.globalswitches)
  669. );
  670. { Initial header, will be updated later }
  671. nlmHeader.signature := NLM_SIGNATURE;
  672. nlmHeader.version := NLM_HEADER_VERSION;
  673. moduleName := upperCase(current_module.exefilename);
  674. nlmHeader.moduleName := moduleName;
  675. nlmHeader.codeImageOffset := TextExeSec.DataPos+TObjSection(TextExeSec.ObjSectionList[0]).dataalignbytes; // ??? may be that align has to be moved to fixups/imports
  676. nlmHeader.codeImageSize := TextExeSec.Size;
  677. nlmHeader.dataImageOffset := DataExeSec.DataPos;
  678. nlmHeader.dataImageSize := DataExeSec.Size;
  679. if assigned(BSSExeSec) then
  680. nlmHeader.uninitializedDataSize:=BSSExeSec.Size;
  681. if assigned(customExeSec) then
  682. begin
  683. nlmHeader.customDataOffset := customExeSec.DataPos;
  684. nlmHeader.customDataSize := customExeSec.Size;
  685. end;
  686. if FNumModules > 0 then
  687. begin
  688. nlmHeader.moduleDependencyOffset := FindExeSection('.modules').DataPos+4; // 4 bytes dummy
  689. nlmHeader.numberOfModuleDependencies := FNumModules;
  690. end;
  691. nlmHeader.relocationFixupOffset := relocsExeSec.DataPos;
  692. nlmHeader.numberOfRelocationFixups := FNumRelocs;
  693. nlmHeader.externalReferencesOffset := importsExeSec.DataPos+4; // 4 bytes dummy
  694. nlmHeader.numberOfExternalReferences := FNumExternals;
  695. if assigned(exportsExeSec) then
  696. if exportsExeSec.Size>0 then
  697. begin
  698. nlmHeader.publicsOffset := exportsExeSec.dataPos;
  699. nlmHeader.numberOfPublics := FnumExports;
  700. end;
  701. nlmHeader.codeStartOffset := EntrySym.Address;
  702. {exit function}
  703. exesym:=texesymbol(ExeSymbolList.Find('_Stop'));
  704. if assigned(exesym) then
  705. nlmHeader.exitProcedureOffset := exesym.ObjSymbol.address;
  706. {check exit function}
  707. exesym:=texesymbol(ExeSymbolList.Find('FPC_NW_CHECKFUNCTION'));
  708. if assigned(exesym) then
  709. nlmHeader.checkUnloadProcedureOffset := exesym.ObjSymbol.address;
  710. // calc file pos after all exesections
  711. fSizeWoDebugSyms := totalheadersize + ExeSecsListSize + headerAlignBytes;
  712. ExeSectionList.ForEachCall(@ExeSectionList_calc_size,nil);
  713. nlmExtHeader.stamp := NLM_MESSAGES_STAMP;
  714. //extHeader.languageID // TODO: where to get this from ?
  715. if assigned(messagesExeSec) then
  716. begin
  717. nlmExtHeader.messageFileOffset := messagesExeSec.DataPos;
  718. nlmExtHeader.messageFileLength := messagesExeSec.Size;
  719. end;
  720. //nlmExtHeader.messageCount // TODO: how is messageCount set ?
  721. if assigned(helpExeSec) then
  722. begin
  723. nlmExtHeader.helpFileOffset := helpExeSec.DataPos;
  724. nlmExtHeader.helpFileLength := helpExeSec.Size;
  725. end;
  726. //nlmExtHeader.productID // TODO: were does this came from ?
  727. if assigned(xdcExeSec) then
  728. begin
  729. nlmExtHeader.RPCDataOffset := xdcExeSec.DataPos;
  730. nlmExtHeader.RPCDataLength := xdcExeSec.Size;
  731. end;
  732. if hassymbols then
  733. begin
  734. nlmHeader.debugInfoOffset := fSizeWoDebugSyms;
  735. ExeSymbolList.ForEachCall(@globalsyms_create_symbol,nil);
  736. nlmHeader.numberOfDebugRecords := FNumDebugSymbols;
  737. end;
  738. fillNlmVersionHeader;
  739. FWriter.write(nlmHeader,sizeof(nlmHeader));
  740. { variable header }
  741. NLMWriteString(nlmDescription,true);
  742. if stacksize < NLM_DEFAULT_STACKSIZE then stacksize := NLM_DEFAULT_STACKSIZE;
  743. FWriter.Write(stacksize,4);
  744. FWriter.writezeros(4);
  745. dummyLong := ' LONG';
  746. FWriter.Write(dummyLong,sizeof(dummyLong)); // old thread name
  747. NLMWriteString(nlmScreenname,true);
  748. NLMWriteString(nlmThreadname,true);
  749. {version}
  750. FWriter.Write(nlmVersionHeader,sizeof(nlmVersionHeader));
  751. {copyright}
  752. if nlmCopyright <> '' then
  753. begin
  754. FWriter.write(NLM_COPYRIGHT_STAMP,sizeof(NLM_COPYRIGHT_STAMP));
  755. NLMWriteString(nlmCopyright,true);
  756. end;
  757. {messages}
  758. FWriter.write(nlmExtHeader,sizeof(nlmExtHeader));
  759. {custhead}
  760. nlmCustHeader.stamp := NLM_CUSTOM_STAMP;
  761. nlmCustHeader.dataLength := ExeSecsListSize;
  762. nlmCustHeader.dataOffset := totalheadersize;
  763. nlmCustHeader.hdrLength := $10; // why 16 ?, this is what binutils write
  764. FWriter.write(nlmCustHeader,sizeof(nlmCustHeader));
  765. {CyGnUsEx}
  766. // bfd has a strange way to read the sections:
  767. // the section directory is written under CuStHeAd
  768. // when bfd finds the neader "CyGnUsEx", it uses the
  769. // offset and size from CuStHeAd to read the section table
  770. nlmCygnusHeader.stamp := NLM_CYGNUS_STAMP; // CyGnUsEx
  771. // ld writes some unknown values here, bfd irgnores the values at all
  772. // lets write the offset and length of the segment table
  773. nlmCygnusHeader.offset := nlmCustHeader.dataLength;
  774. nlmCygnusHeader.length := nlmCustHeader.dataOffset;
  775. FWriter.write(nlmCygnusHeader,sizeof(nlmCygnusHeader));
  776. FWriter.WriteZeros(8); // empty stamp + align next to 16 bytes
  777. if FWriter.Size<>totalheadersize then
  778. internalerror(201103061); // headersize <> header written
  779. { Section headers, CuStHeAd points to this section, not needed by
  780. netware. Can be used to find the section in the nlm file, binutils
  781. will use this section }
  782. ExeSectionList.ForEachCall(@ExeSectionList_write_header,nil);
  783. FWriter.WriteZeros(headerAlignBytes);
  784. if FWriter.Size<>totalheadersize+ExeSecsListSize+headerAlignBytes then
  785. internalerror(201103062);
  786. { Section data }
  787. if assigned(exemap) then
  788. begin
  789. exemap.Add('');
  790. exemap.Add('NLM file offsets:');
  791. end;
  792. ExeSectionList.ForEachCall(@ExeSectionList_write_data,nil);
  793. if hassymbols then
  794. FWriter.writearray(NlmSymbols); // specific symbols for the internal netware debugger
  795. result:=true;
  796. end;
  797. procedure TNLMexeoutput.GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);
  798. var
  799. idata5objsection : TObjSection;
  800. basedllname : string;
  801. function AddImport(const afuncname,amangledname:string; isvar:boolean):TObjSymbol;
  802. var
  803. secname:string;
  804. begin
  805. //Comment (V_Debug,'TNLMexeoutput.GenerateLibraryImports.AddImport '+afuncName);
  806. result:=nil;
  807. if assigned(exemap) then
  808. exemap.Add(' Importing Function '+afuncname);
  809. if not isvar then
  810. with internalobjdata do
  811. begin
  812. secname:=basedllname+'_i_'+amangledname;
  813. idata5objsection:=createsection(sec_idata5, secname);
  814. internalobjdata.SetSection(idata5objsection);
  815. result:=internalobjdata.SymbolDefine('_'+amangledname,AB_IMPORT,AT_FUNCTION);
  816. end;
  817. end;
  818. var
  819. i,j : longint;
  820. ImportLibrary : TImportLibrary;
  821. ImportSymbol : TImportSymbol;
  822. exesym : TExeSymbol;
  823. importAddressList : TFPObjectList;
  824. begin
  825. if ImportLibraryList.Count > 0 then
  826. begin
  827. {objsec:=}internalObjData.createsection('.imports',0,[oso_data,oso_keep]);
  828. i := 0;
  829. internalobjdata.writebytes(i,4); // dummy to avoid deletion
  830. {objsec:=}internalObjData.createsection('.modules',0,[oso_data,oso_keep]);
  831. internalobjdata.writebytes(i,4); // dummy to avoid deletion
  832. end;
  833. for i:=0 to ImportLibraryList.Count-1 do
  834. begin
  835. ImportLibrary:=TImportLibrary(ImportLibraryList[i]);
  836. idata5objsection:=nil;
  837. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  838. begin
  839. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  840. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  841. if assigned(exesym) and
  842. (exesym.State<>symstate_defined) then
  843. begin
  844. basedllname:=ExtractFileName(ImportLibrary.Name);
  845. exesym.objsymbol:=AddImport(ImportSymbol.Name,ImportSymbol.MangledName,ImportSymbol.IsVar);
  846. exesym.State:=symstate_defined;
  847. importAddressList := TFPObjectList.create(false);
  848. nlmImports.Add(ImportSymbol.Name,importAddressList);
  849. if pos('.',basedllname) = 0 then
  850. basedllname := basedllname + '.nlm';
  851. nlmImpNames.Add(ImportSymbol.Name,TStringObj.create(lower(basedllname)));
  852. end;
  853. end;
  854. end;
  855. PackUnresolvedExeSymbols('after DLL imports');
  856. GenerateExports;
  857. end;
  858. procedure TNLMexeoutput.GenerateImports;
  859. var
  860. exesec,
  861. impexesec : TExeSection;
  862. objsec : TObjSection;
  863. objreloc : TObjRelocation;
  864. i,j,k : integer;
  865. importAddressList : TFPObjectList;
  866. name,mName : string;
  867. b : byte;
  868. modules : string;
  869. modName : TStringObj;
  870. begin
  871. if FImportsGenerated then exit;
  872. FImportsGenerated := true;
  873. impexesec:=FindExeSection('.imports');
  874. if impexesec=nil then exit;
  875. for i:=0 to ExeSectionList.Count-1 do
  876. begin
  877. exesec:=TExeSection(ExeSectionList[i]);
  878. for j:=0 to exesec.ObjSectionList.count-1 do
  879. begin
  880. objsec:=TObjSection(exesec.ObjSectionList[j]);
  881. if j=0 then
  882. begin
  883. exesec.DataPos:=objSec.DataPos;
  884. exesec.MemPos:=objSec.MemPos;
  885. end;
  886. if (copy(objsec.name,1,5) <> '.text') and (copy(objsec.name,1,4) <> '.bss') and (copy(objsec.name,1,5) <> '.data') then
  887. continue;
  888. for k:=0 to objsec.ObjRelocations.Count-1 do
  889. begin
  890. objreloc := TObjRelocation(objsec.ObjRelocations[k]);
  891. if assigned(objreloc.symbol) then
  892. begin
  893. //writeln (objreloc.symbol.name,' ',objreloc.symbol.bind);
  894. if objreloc.symbol.bind = AB_IMPORT then
  895. begin
  896. importAddressList := TFPObjectList(nlmImports.Find(objreloc.symbol.name));
  897. if assigned(importAddressList) then
  898. begin
  899. objreloc.objsection := objsec; // points to idata5
  900. importAddressList.Add(objreloc);
  901. end else
  902. begin
  903. comment(v_error,objreloc.symbol.name+' is external but not defined in nlm imports');
  904. end;
  905. end;
  906. end
  907. end;
  908. end;
  909. end;
  910. modules := '';
  911. for i := 0 to nlmImports.count-1 do
  912. begin
  913. importAddressList := TFPObjectList(nlmImports.Items[i]);
  914. if importAddressList.Count > 0 then
  915. begin
  916. name := nlmImports.NameOfIndex(i);
  917. // find the module to be imported and add it to the list
  918. // of modules to be auto loaded
  919. modName := TStringObj(nlmImpNames.Find(name));
  920. if assigned(modName) then
  921. begin
  922. mName := modName.Value;
  923. if mName <> '' then
  924. 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
  925. begin
  926. if pos(mName+';',modules) < 1 then
  927. begin
  928. modules := modules + mName + ';';
  929. inc(FNumModules);
  930. end;
  931. end;
  932. end;
  933. internalobjdata.SetSection(TObjSection(impexesec.ObjSectionList[0]));
  934. objNLMwriteString (name,false); // name of symbol
  935. k := importAddressList.Count;
  936. internalobjdata.writebytes(k,sizeof(k)); // number of references
  937. inc(FNumExternals);
  938. for j := 0 to importAddressList.Count-1 do
  939. begin
  940. objreloc := TObjRelocation(importAddressList[j]);
  941. objsec := objreloc.objsection;
  942. if oso_executable in objreloc.objsection.SecOptions then
  943. begin
  944. if objreloc.typ <> RELOC_RELATIVE then comment(v_error,'reference to external symbols must be RELOC_RELATIVE');
  945. // TODO: how to check if size is 4 ????
  946. k := objsec.MemPos + objreloc.DataOffset;
  947. k := k or $40000000;
  948. // TODO: data|code if we support importing data symbols
  949. // i do not know if this is possible with netware
  950. internalobjdata.writebytes(k,sizeof(k)); // address
  951. // the netware loader requires an offset at the import address
  952. // for call = E8 this is -4
  953. // TODO: how can we check the needed offset ??
  954. if objreloc.DataOffset > 0 then
  955. begin
  956. objsec.Data.seek(objreloc.DataOffset-1);
  957. objsec.data.read(b,1);
  958. if b <> $E8 then
  959. comment(v_error,'no rcall (E8) before imported symbol target address');
  960. k := -4;
  961. objsec.Data.write(k,sizeof(k));
  962. end else
  963. begin
  964. objsec.Data.seek(objreloc.DataOffset);
  965. k := 0;
  966. objsec.Data.write(k,sizeof(k));
  967. end;
  968. objreloc.typ := RELOC_NONE; // to avoid that TCoffObjSection.fixuprelocs changes the address again
  969. end else
  970. comment(v_error,'Importing of symbols only supported for .text');
  971. end;
  972. end;
  973. end;
  974. exesec := FindExeSection('.modules');
  975. if not assigned(exesec) then internalerror(201103272); // exe section .modules does not exist ???
  976. internalobjdata.SetSection(TObjSection(exesec.ObjSectionList[0]));
  977. for i := 1 to FNumModules do
  978. begin
  979. name := GetToken(modules,';');
  980. objNLMwriteString (name,false);
  981. end;
  982. end;
  983. procedure TNLMexeoutput.GenerateExports;
  984. var
  985. hp : texported_item; { for exports }
  986. len : byte;
  987. addr: longword;
  988. exesym : texesymbol;
  989. begin
  990. internalObjData.createsection('.exports',0,[oso_data,oso_keep]);
  991. {name LString 1+n bytes
  992. addr 4 bytes
  993. addr and $80000000 > 0 -> .text else .data}
  994. hp:=texported_item(current_module._exports.first);
  995. if assigned(hp) then
  996. if assigned(exemap) then
  997. exemap.Add('');
  998. while assigned(hp) do
  999. begin
  1000. { Export the Symbol }
  1001. if assigned(exemap) then
  1002. exemap.Add(' Exporting Function '+hp.sym.prettyname+' as '+hp.name^);
  1003. len := length(hp.name^);
  1004. internalobjdata.writebytes(len,1);
  1005. internalobjdata.writebytes(hp.name^[1],len);
  1006. exesym:=texesymbol(ExeSymbolList.Find(hp.sym.prettyname));
  1007. if not assigned(exesym) then
  1008. begin
  1009. comment(v_error,'exported symbol '+hp.sym.prettyname+' not found');
  1010. exit;
  1011. end;
  1012. // for exported functions we have to set the upper bit
  1013. // this will be done in .writedata
  1014. if not hp.is_var then
  1015. FexportFunctionOffsets.Add(pointer(PtrUInt(internalobjdata.CurrObjSec.Size)));
  1016. internalobjdata.writereloc(0,4,exesym.ObjSymbol,RELOC_ABSOLUTE32);
  1017. addr := 0;
  1018. internalobjdata.writebytes(addr,4);
  1019. inc(FnumExports);
  1020. hp:=texported_item(hp.next);
  1021. end;
  1022. end;
  1023. procedure TNLMexeoutput.GenerateRelocs;
  1024. var
  1025. exesec : TExeSection;
  1026. objsec : TObjSection;
  1027. objreloc : TObjRelocation;
  1028. i,j,k : longint;
  1029. offset : longword;
  1030. inSec,toSec : TsecType;
  1031. targetSectionName : string;
  1032. begin
  1033. if FRelocsGenerated then
  1034. exit;
  1035. exesec:=FindExeSection('.reloc');
  1036. if exesec=nil then
  1037. exit;
  1038. objsec:=internalObjData.createsection('.reloc',0,[oso_data,oso_load,oso_keep]);
  1039. exesec.AddObjSection(objsec);
  1040. for i:=0 to ExeSectionList.Count-1 do
  1041. begin
  1042. exesec:=TExeSection(ExeSectionList[i]);
  1043. for j:=0 to exesec.ObjSectionList.count-1 do
  1044. begin
  1045. objsec:=TObjSection(exesec.ObjSectionList[j]);
  1046. //writeln ('Relocs for ',exesec.name,' - ',objsec.name);
  1047. { create relocs only for sections which are loaded in memory }
  1048. if not (oso_load in objsec.SecOptions) then
  1049. continue;
  1050. { create relocs only for .text and .data }
  1051. inSec := SectionType (objsec.name);
  1052. if (inSec <> Section_Text) and (inSec <> Section_Data) then
  1053. continue;
  1054. for k:=0 to objsec.ObjRelocations.Count-1 do
  1055. begin
  1056. objreloc:=TObjRelocation(objsec.ObjRelocations[k]);
  1057. if objreloc.typ <> RELOC_ABSOLUTE then
  1058. continue;
  1059. offset:=objsec.MemPos+objreloc.dataoffset;
  1060. targetSectionName := '';
  1061. if objreloc.symbol <> nil then
  1062. begin
  1063. // writeln (' MemPos',objsec.MemPos,
  1064. // ' dataOfs:',objreloc.dataoffset,' ',objsec.name,
  1065. // ' objreloc.symbol: ',objreloc.symbol.name,
  1066. // ' objreloc.symbol.objsection.name: ',objreloc.symbol.objsection.name,
  1067. // ' ',objreloc.symbol.Typ,' ',objrel
  1068. // oc.symbol.bind,' ',objreloc.Typ);
  1069. if objreloc.symbol.objsection.name[1] <> '.' then
  1070. targetSectionName := objreloc.symbol.name // specials like __bss_start__
  1071. else // dont use objsection.name because it begins with *
  1072. targetSectionName := copy(objreloc.symbol.objsection.name,1,5); // all others begin with .segment, we only have to check for .text, .data or .bss
  1073. end else
  1074. internalerror(2011030603);
  1075. toSec := SectionType(targetSectionName);
  1076. if (toSec = Section_Text) or (toSec = Section_Data) then
  1077. begin
  1078. if (inSec = Section_text) then offset := offset or $40000000;
  1079. if (toSec = Section_text) then offset := offset or $80000000;
  1080. internalObjData.writebytes(offset,4);
  1081. inc(FNumRelocs);
  1082. end;
  1083. end;
  1084. end;
  1085. end;
  1086. FRelocsGenerated:=true;
  1087. end;
  1088. procedure TNLMexeoutput.MemPos_Start;
  1089. var
  1090. exesec : TExeSection;
  1091. begin
  1092. exesec:=FindExeSection('.reloc');
  1093. if exesec=nil then
  1094. InternalError(2012072602);
  1095. exesec.SecOptions:=exesec.SecOptions-[oso_disabled];
  1096. inherited;
  1097. end;
  1098. procedure TNLMexeoutput.MemPos_ExeSection(const aname:string);
  1099. begin
  1100. if aname='.reloc' then
  1101. GenerateRelocs;
  1102. if aname='.imports' then
  1103. GenerateImports;
  1104. if aname='.data' then
  1105. currMemPos := 0; // both, data and code in the nlm have a start offset of 0
  1106. inherited;
  1107. end;
  1108. procedure TNLMexeoutput.NLMwriteString (const s : string; terminateWithZero : boolean);
  1109. var len : byte;
  1110. begin
  1111. if length(s) > 254 then len := 254 else len := length(s);
  1112. FWriter.Write(len,1);
  1113. if len > 0 then
  1114. FWriter.write(s[1],len);
  1115. if terminateWithZero then
  1116. FWriter.writeZeros(1);
  1117. end;
  1118. procedure TNLMexeoutput.objNLMwriteString (const s : string; terminateWithZero : boolean);
  1119. var len : byte;
  1120. begin
  1121. if length(s) > 254 then len := 254 else len := length(s);
  1122. Internalobjdata.writebytes(len,1);
  1123. if len > 0 then
  1124. Internalobjdata.writebytes(s[1],len);
  1125. if terminateWithZero then
  1126. begin
  1127. len := 0;
  1128. Internalobjdata.writebytes(s[1],len);
  1129. end;
  1130. end;
  1131. { parse netware specific linker options }
  1132. procedure TNLMexeoutput.ParseScript (linkscript:TCmdStrList);
  1133. var
  1134. hp : TCmdStrListItem;
  1135. opt,keyword,s : string;
  1136. i : integer;
  1137. function toInteger(s:string; min,max:integer; var res:integer):boolean;
  1138. var
  1139. code:word;
  1140. begin
  1141. result := false;
  1142. val (s,res,code);
  1143. if code<>0 then exit;
  1144. if (res < min) or (res > max) then exit;
  1145. result := true;
  1146. end;
  1147. procedure loadFile (const secName, fileName, Desc : string);
  1148. var
  1149. fileBuf : array [0..4095] of char;
  1150. bytesRead : longint;
  1151. fileH : THandle;
  1152. fn : TCmdStr;
  1153. begin
  1154. fn := fileName;
  1155. if not fileExists(fn) then
  1156. if not unitsearchpath.FindFile(fileName,true,fn) then
  1157. begin
  1158. comment(v_error,'can not find '+desc+' file '+fileName);
  1159. exit;
  1160. end;
  1161. fileH := fileOpen (fn,fmOpenRead);
  1162. if fileH = THandle(-1) then
  1163. begin
  1164. comment(v_error,'can not open '+desc+' file '+fn);
  1165. exit;
  1166. end;
  1167. { load file into section }
  1168. internalObjData.createsection(secName,0,[oso_data,oso_keep]);
  1169. repeat
  1170. bytesRead := fileRead(fileH,fileBuf,sizeof(fileBuf));
  1171. if bytesRead > 0 then
  1172. internalobjdata.writebytes(fileBuf,bytesRead);
  1173. until bytesRead < sizeof(fileBuf);
  1174. fileClose(fileH);
  1175. end;
  1176. begin
  1177. hp:=TCmdStrListItem(linkscript.first);
  1178. while assigned(hp) do
  1179. begin
  1180. opt:=hp.str;
  1181. if (opt='') or (opt[1]='#') then
  1182. continue;
  1183. keyword:=Upper(GetToken(opt,' '));
  1184. if keyword = 'AUTOUNLOAD' then
  1185. begin
  1186. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_AUTOUNLOAD;
  1187. end else
  1188. if keyword = 'COPYRIGHT' then
  1189. begin
  1190. nlmCopyright := GetToken(opt,' ');
  1191. end else
  1192. if keyword = 'CUSTOM' then
  1193. begin
  1194. loadFile ('.custom',GetToken(opt,' '),'custom data');
  1195. end;
  1196. if keyword = 'DATE' then // month day 4-digit-year
  1197. begin
  1198. if not toInteger(GetToken(opt,' '),1,12,i) then comment(v_error,'DATE: invalid month')
  1199. else nlmVersionHeader.month := i;
  1200. if not toInteger(GetToken(opt,' '),1,31,i) then comment(v_error,'DATE: invalid day')
  1201. else nlmVersionHeader.day := i;
  1202. if not toInteger(GetToken(opt,' '),1900,3000,i) then comment(v_error,'DATE: invalid year')
  1203. else nlmVersionHeader.year := i;
  1204. end else
  1205. if keyword = 'DEBUG' then
  1206. begin
  1207. // ignore
  1208. end else
  1209. if keyword = 'DESCRIPTION' then
  1210. begin
  1211. nlmDescription := GetToken(opt,' ');
  1212. if length (nlmDescription) > NLM_MAX_DESCRIPTION_LENGTH then
  1213. nlmDescription := copy (nlmDescription,1,NLM_MAX_DESCRIPTION_LENGTH);
  1214. end else
  1215. if keyword = 'FLAG' then
  1216. begin
  1217. s := upper(GetToken(opt,' '));
  1218. if (not toInteger(GetToken(opt,' '),1,$FFFFFFF,i)) or ((s <> 'ON') and (S <> 'OFF')) then comment(v_error,'FLAG: invalid') else
  1219. if (s='ON') then
  1220. nlmHeader.flags:=nlmHeader.flags or i else
  1221. nlmHeader.flags:=nlmHeader.flags and ($FFFFFFF-i);
  1222. end else
  1223. if keyword = 'HELP' then
  1224. begin
  1225. loadFile ('.help',GetToken(opt,' '),'help');
  1226. end else
  1227. if keyword = 'MESSAGES' then
  1228. begin
  1229. loadFile ('.messages',GetToken(opt,' '),'message');
  1230. end else
  1231. if keyword = 'MULTIPLE' then
  1232. begin
  1233. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_MULTILOAD;
  1234. end else
  1235. if keyword = 'OS_DOMAIN' then
  1236. begin
  1237. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_OSDOMAIN;
  1238. end else
  1239. if keyword = 'PSEUDOPREEMPTION' then
  1240. begin
  1241. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_PSEUDOPREEMPTION;
  1242. end else
  1243. if keyword = 'REENTRANT' then
  1244. begin
  1245. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_REENTRANT;
  1246. end else
  1247. if keyword = 'SCREENNAME' then
  1248. begin
  1249. nlmScreenname := GetToken(opt,' ');
  1250. if length(nlmScreenname) > NLM_MAX_SCREEN_NAME_LENGTH then
  1251. nlmScreenName := copy (nlmScreenName,1,NLM_MAX_SCREEN_NAME_LENGTH);
  1252. end else
  1253. if (keyword = 'STACK') or (keyword = 'STACKSIZE') then
  1254. begin
  1255. if (not toInteger(GetToken(opt,' '),1,$FFFFFFF,i)) then comment(v_error,'invalid stacksize') else
  1256. stacksize := i;
  1257. end else
  1258. if keyword = 'SYNCHRONIZE' then
  1259. begin
  1260. nlmHeader.flags:=nlmHeader.flags or NLM_FLAGS_SYNCHRONIZE;
  1261. end else
  1262. if keyword = 'THREADNAME' then
  1263. begin
  1264. nlmThreadname := GetToken(opt,' ');
  1265. if length(nlmThreadname) > NLM_MAX_THREAD_NAME_LENGTH then
  1266. nlmThreadname := copy (nlmThreadname,1,NLM_MAX_THREAD_NAME_LENGTH);
  1267. end else
  1268. if keyword = 'TYPE' then
  1269. begin
  1270. if (not toInteger(GetToken(opt,' '),1,16,i)) then comment(v_error,'invalid TYPE') else
  1271. nlmHeader.moduleType := i; // TODO: set executable extension (.DSK, .LAN, ...)
  1272. end else
  1273. if keyword = 'VERSION' then
  1274. begin
  1275. if (not toInteger(GetToken(opt,' '),0,$FFFFFFF,i)) then comment(v_error,'invalid major version') else
  1276. nlmVersionHeader.majorVersion := i;
  1277. if (not toInteger(GetToken(opt,' '),0,99,i)) then comment(v_error,'invalid minor version') else
  1278. nlmVersionHeader.minorVersion := i;
  1279. if (not toInteger(GetToken(opt,' '),0,$FFFFFFF,i)) then comment(v_error,'invalid minor version') else
  1280. if i > 26 then
  1281. nlmVersionHeader.revision := 0 else
  1282. nlmVersionHeader.revision := i;
  1283. end else
  1284. if keyword = 'XDCDATA' then
  1285. begin
  1286. loadFile ('.xdc',GetToken(opt,' '),'xdc');
  1287. end;
  1288. { TODO: check for unknown options. This means all handled option
  1289. (also in link.pas) have to be flagged if processed }
  1290. hp:=TCmdStrListItem(hp.next);
  1291. end;
  1292. end;
  1293. {****************************************************************************
  1294. TNLMCoffObjData
  1295. ****************************************************************************}
  1296. constructor TNLMCoffObjData.create(const n:string);
  1297. begin
  1298. inherited createcoff(n,true,TNLMCoffObjSection);
  1299. end;
  1300. {****************************************************************************
  1301. TNLMoffObjSection
  1302. ****************************************************************************}
  1303. constructor TNLMCoffObjSection.create(AList:TFPHashObjectList;const aname:string;aalign:shortint;aoptions:TObjSectionOptions);
  1304. begin
  1305. inherited create(alist,aname,aalign,aoptions);
  1306. end;
  1307. constructor TNLMCoffObjOutput.create(AWriter:TObjectWriter);
  1308. begin
  1309. // ??????
  1310. // if win32=false, .stabs and .stabstr will be written without oso_debug
  1311. // Without oso_debug the sections will be removed by the linker
  1312. inherited createcoff(AWriter,{win32}true);
  1313. cobjdata:=TNLMCoffObjData;
  1314. end;
  1315. {****************************************************************************
  1316. TDJCoffAssembler
  1317. ****************************************************************************}
  1318. constructor TNLMCoffAssembler.Create(smart:boolean);
  1319. begin
  1320. inherited Create(smart);
  1321. CObjOutput:=TNLMCoffObjOutput;
  1322. end;
  1323. constructor TNLMCoffObjInput.create;
  1324. begin
  1325. inherited createcoff(true);
  1326. cobjdata:=TNLMCoffObjData;
  1327. end;
  1328. {*****************************************************************************
  1329. Initialize
  1330. *****************************************************************************}
  1331. const
  1332. as_i386_nlmcoff_info : tasminfo =
  1333. (
  1334. id : as_i386_nlmcoff;
  1335. idtxt : 'NLMCOFF';
  1336. asmbin : '';
  1337. asmcmd : '';
  1338. supported_targets : [system_i386_Netware,system_i386_netwlibc];
  1339. flags : [af_outputbinary,af_smartlink_sections];
  1340. labelprefix : '.L';
  1341. comment : '';
  1342. dollarsign: '$';
  1343. );
  1344. initialization
  1345. {$ifdef i386}
  1346. RegisterAssembler(as_i386_nlmcoff_info,TNLMCoffAssembler);
  1347. {$endif i386}
  1348. end.