2
0

ognlm.pas 59 KB

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