ognlm.pas 58 KB

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