t_win.pas 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898
  1. {
  2. Copyright (c) 1998-2008 by Peter Vreman
  3. This unit implements support import,export,link routines
  4. for the (i386) Win32 target
  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 t_win;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. cutils,cclasses,
  23. aasmbase,aasmtai,aasmdata,aasmcpu,fmodule,globtype,globals,systems,verbose,
  24. symconst,symdef,symsym,
  25. cscript,gendef,
  26. cpubase,
  27. import,export,link,comprsrc,i_win;
  28. const
  29. MAX_DEFAULT_EXTENSIONS = 3;
  30. type
  31. tStr4=array[1..MAX_DEFAULT_EXTENSIONS] of string[4];
  32. pStr4=^tStr4;
  33. TImportLibWin=class(timportlib)
  34. private
  35. procedure generateimportlib;
  36. procedure generateidatasection;
  37. public
  38. procedure generatelib;override;
  39. end;
  40. TExportLibWin=class(texportlib)
  41. private
  42. st : string;
  43. EList_indexed:TFPList;
  44. EList_nonindexed:TFPList;
  45. public
  46. destructor Destroy;override;
  47. procedure preparelib(const s:string);override;
  48. procedure exportprocedure(hp : texported_item);override;
  49. procedure exportvar(hp : texported_item);override;
  50. procedure exportfromlist(hp : texported_item);
  51. procedure generatelib;override;
  52. procedure generatenasmlib;virtual;
  53. end;
  54. TInternalLinkerWin = class(tinternallinker)
  55. constructor create;override;
  56. procedure DefaultLinkScript;override;
  57. procedure InitSysInitUnitName;override;
  58. procedure ConcatEntryName; virtual;
  59. end;
  60. TExternalLinkerWin=class(texternallinker)
  61. private
  62. Function WriteResponseFile(isdll:boolean) : Boolean;
  63. Function PostProcessExecutable(const fn:string;isdll:boolean) : Boolean;
  64. public
  65. Constructor Create;override;
  66. Procedure SetDefaultInfo;override;
  67. function MakeExecutable:boolean;override;
  68. function MakeSharedLibrary:boolean;override;
  69. procedure InitSysInitUnitName;override;
  70. end;
  71. TDLLScannerWin=class(tDLLScanner)
  72. private
  73. importfound : boolean;
  74. procedure CheckDLLFunc(const dllname,funcname:string);
  75. public
  76. function Scan(const binname:string):boolean;override;
  77. end;
  78. implementation
  79. uses
  80. SysUtils,
  81. cfileutl,
  82. cgutils,dbgbase,
  83. owar,ogbase
  84. {$ifdef SUPPORT_OMF}
  85. ,ogomf
  86. {$endif SUPPORT_OMF}
  87. ,ogcoff;
  88. const
  89. res_gnu_windres_info : tresinfo =
  90. (
  91. id : res_gnu_windres;
  92. resbin : 'fpcres';
  93. rescmd : '-o $OBJ -a $ARCH -of coff $DBG';
  94. rcbin : 'windres';
  95. rccmd : '--include $INC -O res -D FPC -o $RES $RC';
  96. resourcefileclass : nil;
  97. resflags : [];
  98. );
  99. {$ifdef x86_64}
  100. res_win64_gorc_info : tresinfo =
  101. (
  102. id : res_win64_gorc;
  103. resbin : 'fpcres';
  104. rescmd : '-o $OBJ -a $ARCH -of coff $DBG';
  105. rcbin : 'gorc';
  106. rccmd : '/machine x64 /nw /ni /r /d FPC /fo $RES $RC';
  107. resourcefileclass : nil;
  108. resflags : [];
  109. );
  110. {$endif x86_64}
  111. Procedure GlobalInitSysInitUnitName(Linker : TLinker);
  112. var
  113. hp : tmodule;
  114. linkcygwin : boolean;
  115. begin
  116. if target_info.system=system_i386_win32 then
  117. begin
  118. linkcygwin := false;
  119. hp:=tmodule(loaded_units.first);
  120. while assigned(hp) do
  121. begin
  122. linkcygwin := hp.linkothersharedlibs.find('cygwin') or hp.linkotherstaticlibs.find('cygwin');
  123. if linkcygwin then
  124. break;
  125. hp:=tmodule(hp.next);
  126. end;
  127. if cs_profile in current_settings.moduleswitches then
  128. linker.sysinitunit:='sysinitgprof'
  129. else if linkcygwin or (Linker.SharedLibFiles.Find('cygwin')<>nil) or (Linker.StaticLibFiles.Find('cygwin')<>nil) then
  130. linker.sysinitunit:='sysinitcyg'
  131. else
  132. linker.sysinitunit:='sysinitpas';
  133. end
  134. else if target_info.system in [system_x86_64_win64,system_aarch64_win64] then
  135. linker.sysinitunit:='sysinit';
  136. end;
  137. {*****************************************************************************
  138. TImportLibWin
  139. *****************************************************************************}
  140. procedure TImportLibWin.generateimportlib;
  141. var
  142. ObjWriter : tarobjectwriter;
  143. ObjOutput : TPECoffObjOutput;
  144. basedllname : string;
  145. AsmPrefix : string;
  146. idatalabnr,
  147. SmartFilesCount,
  148. SmartHeaderCount : longint;
  149. function CreateObjData(place:tcutplace):TObjData;
  150. var
  151. s : string;
  152. begin
  153. s:='';
  154. case place of
  155. cut_begin :
  156. begin
  157. inc(SmartHeaderCount);
  158. s:=asmprefix+tostr(SmartHeaderCount)+'h';
  159. end;
  160. cut_normal :
  161. s:=asmprefix+tostr(SmartHeaderCount)+'s';
  162. cut_end :
  163. s:=asmprefix+tostr(SmartHeaderCount)+'t';
  164. end;
  165. inc(SmartFilesCount);
  166. result:=ObjOutput.NewObjData(FixFileName(s+tostr(SmartFilesCount)+target_info.objext));
  167. ObjOutput.startobjectfile(Result.Name);
  168. end;
  169. procedure WriteObjData(objdata:TObjData);
  170. begin
  171. ObjOutput.writeobjectfile(ObjData);
  172. end;
  173. procedure StartImport(const dllname:string);
  174. var
  175. headlabel,
  176. idata4label,
  177. idata5label,
  178. idata7label : TObjSymbol;
  179. emptyint : longint;
  180. objdata : TObjData;
  181. idata2objsection,
  182. idata4objsection,
  183. idata5objsection : TObjSection;
  184. begin
  185. objdata:=CreateObjData(cut_begin);
  186. idata2objsection:=objdata.createsection(sec_idata2,'');
  187. idata4objsection:=objdata.createsection(sec_idata4,'');
  188. idata5objsection:=objdata.createsection(sec_idata5,'');
  189. emptyint:=0;
  190. basedllname:=ExtractFileName(dllname);
  191. { idata4 }
  192. objdata.SetSection(idata4objsection);
  193. idata4label:=objdata.SymbolDefine(asmprefix+'_names_'+basedllname,AB_GLOBAL,AT_DATA);
  194. { idata5 }
  195. objdata.SetSection(idata5objsection);
  196. idata5label:=objdata.SymbolDefine(asmprefix+'_fixup_'+basedllname,AB_GLOBAL,AT_DATA);
  197. { idata2 }
  198. objdata.SetSection(idata2objsection);
  199. headlabel:=objdata.SymbolDefine(asmprefix+'_head_'+basedllname,AB_GLOBAL,AT_DATA);
  200. ObjOutput.exportsymbol(headlabel);
  201. objdata.writereloc(0,sizeof(longint),idata4label,RELOC_RVA);
  202. objdata.writebytes(emptyint,sizeof(emptyint));
  203. objdata.writebytes(emptyint,sizeof(emptyint));
  204. idata7label:=objdata.SymbolRef(asmprefix+'_dll_'+basedllname);
  205. objdata.writereloc(0,sizeof(longint),idata7label,RELOC_RVA);
  206. objdata.writereloc(0,sizeof(longint),idata5label,RELOC_RVA);
  207. WriteObjData(objdata);
  208. objdata.free;
  209. end;
  210. procedure EndImport;
  211. var
  212. idata7label : TObjSymbol;
  213. emptyint : longint;
  214. objdata : TObjData;
  215. idata4objsection,
  216. idata5objsection,
  217. idata7objsection : TObjSection;
  218. begin
  219. objdata:=CreateObjData(cut_end);
  220. idata4objsection:=objdata.createsection(sec_idata4,'');
  221. idata5objsection:=objdata.createsection(sec_idata5,'');
  222. idata7objsection:=objdata.createsection(sec_idata7,'');
  223. emptyint:=0;
  224. { idata4 }
  225. objdata.SetSection(idata4objsection);
  226. objdata.writebytes(emptyint,sizeof(emptyint));
  227. if target_info.system in systems_peoptplus then
  228. objdata.writebytes(emptyint,sizeof(emptyint));
  229. { idata5 }
  230. objdata.SetSection(idata5objsection);
  231. objdata.writebytes(emptyint,sizeof(emptyint));
  232. if target_info.system in systems_peoptplus then
  233. objdata.writebytes(emptyint,sizeof(emptyint));
  234. { idata7 }
  235. objdata.SetSection(idata7objsection);
  236. idata7label:=objdata.SymbolDefine(asmprefix+'_dll_'+basedllname,AB_GLOBAL,AT_DATA);
  237. objoutput.exportsymbol(idata7label);
  238. objdata.writebytes(basedllname[1],length(basedllname));
  239. objdata.writebytes(emptyint,1);
  240. WriteObjData(objdata);
  241. objdata.free;
  242. end;
  243. procedure AddImport(const afuncname,mangledname:string;ordnr:longint;isvar:boolean);
  244. const
  245. {$if defined(x86_64)}
  246. jmpopcode : array[0..1] of byte = (
  247. $ff,$25 // jmp qword [rip + offset32]
  248. );
  249. {$elseif defined(arm)}
  250. jmpopcode : array[0..7] of byte = (
  251. $00,$c0,$9f,$e5, // ldr ip, [pc, #0]
  252. $00,$f0,$9c,$e5 // ldr pc, [ip]
  253. );
  254. {$elseif defined(aarch64)}
  255. jmpopcode : array[0..11] of byte = (
  256. $70,$00,$00,$58, // ldr ip0, .+12
  257. $10,$02,$40,$F9, // ldr ip0, [ip0]
  258. $00,$02,$1F,$D6 // br ip0
  259. );
  260. {$elseif defined(i386)}
  261. jmpopcode : array[0..1] of byte = (
  262. $ff,$25
  263. );
  264. {$endif}
  265. nopopcodes : array[0..1] of byte = (
  266. $90,$90
  267. );
  268. var
  269. implabel,
  270. idata2label,
  271. idata5label,
  272. idata6label : TObjSymbol;
  273. emptyint : longint;
  274. objdata : TObjData;
  275. textobjsection,
  276. idata4objsection,
  277. idata5objsection,
  278. idata6objsection,
  279. idata7objsection : TObjSection;
  280. absordnr: word;
  281. procedure WriteTableEntry;
  282. var
  283. ordint: dword;
  284. begin
  285. if ordnr <= 0 then
  286. begin
  287. { import by name }
  288. objdata.writereloc(0,sizeof(longint),idata6label,RELOC_RVA);
  289. if target_info.system in systems_peoptplus then
  290. objdata.writebytes(emptyint,sizeof(emptyint));
  291. end
  292. else
  293. begin
  294. { import by ordinal }
  295. ordint:=ordnr;
  296. if target_info.system in systems_peoptplus then
  297. begin
  298. objdata.writeUInt32LE(ordint);
  299. ordint:=$80000000;
  300. objdata.writeUInt32LE(ordint);
  301. end
  302. else
  303. begin
  304. ordint:=ordint or $80000000;
  305. objdata.writeUInt32LE(ordint);
  306. end;
  307. end;
  308. end;
  309. begin
  310. implabel:=nil;
  311. idata5label:=nil;
  312. textobjsection:=nil;
  313. objdata:=CreateObjData(cut_normal);
  314. if not isvar then
  315. textobjsection:=objdata.createsection(sec_code,'');
  316. idata4objsection:=objdata.createsection(sec_idata4,'');
  317. idata5objsection:=objdata.createsection(sec_idata5,'');
  318. idata6objsection:=objdata.createsection(sec_idata6,'');
  319. idata7objsection:=objdata.createsection(sec_idata7,'');
  320. emptyint:=0;
  321. { idata7, link to head }
  322. objdata.SetSection(idata7objsection);
  323. idata2label:=objdata.SymbolRef(asmprefix+'_head_'+basedllname);
  324. objdata.writereloc(0,sizeof(longint),idata2label,RELOC_RVA);
  325. { idata6, import data (ordnr+name) }
  326. objdata.SetSection(idata6objsection);
  327. inc(idatalabnr);
  328. idata6label:=objdata.SymbolDefine(asmprefix+'_'+tostr(idatalabnr),AB_LOCAL,AT_DATA);
  329. absordnr:=Abs(ordnr);
  330. { write index hint }
  331. objdata.writeUInt16LE(absordnr);
  332. if ordnr <= 0 then
  333. objdata.writebytes(afuncname[1],length(afuncname));
  334. objdata.writebytes(emptyint,1);
  335. objdata.writebytes(emptyint,align(objdata.CurrObjSec.size,2)-objdata.CurrObjSec.size);
  336. { idata4, import lookup table }
  337. objdata.SetSection(idata4objsection);
  338. WriteTableEntry;
  339. { idata5, import address table }
  340. objdata.SetSection(idata5objsection);
  341. if isvar then
  342. implabel:=objdata.SymbolDefine(mangledname,AB_GLOBAL,AT_DATA)
  343. else
  344. idata5label:=objdata.SymbolDefine(asmprefix+'_'+mangledname,AB_LOCAL,AT_DATA);
  345. WriteTableEntry;
  346. { text, jmp }
  347. if not isvar then
  348. begin
  349. objdata.SetSection(textobjsection);
  350. if mangledname <> '' then
  351. implabel:=objdata.SymbolDefine(mangledname,AB_GLOBAL,AT_FUNCTION)
  352. else
  353. implabel:=objdata.SymbolDefine(basedllname+'_index_'+tostr(ordnr),AB_GLOBAL,AT_FUNCTION);
  354. objdata.writebytes(jmpopcode,sizeof(jmpopcode));
  355. {$if defined(x86_64)}
  356. objdata.writereloc(0,sizeof(longint),idata5label,RELOC_RELATIVE);
  357. {$elseif defined(aarch64)}
  358. objdata.writereloc(0,sizeof(aint),idata5label,RELOC_ABSOLUTE);
  359. {$else}
  360. objdata.writereloc(0,sizeof(longint),idata5label,RELOC_ABSOLUTE32);
  361. {$endif x86_64 or aarch64}
  362. objdata.writebytes(nopopcodes,align(objdata.CurrObjSec.size,qword(sizeof(nopopcodes)))-objdata.CurrObjSec.size);
  363. end;
  364. ObjOutput.exportsymbol(implabel);
  365. WriteObjData(objdata);
  366. objdata.free;
  367. end;
  368. var
  369. i,j : longint;
  370. ImportLibrary : TImportLibrary;
  371. ImportSymbol : TImportSymbol;
  372. begin
  373. AsmPrefix:='imp'+Lower(current_module.modulename^);
  374. idatalabnr:=0;
  375. SmartFilesCount:=0;
  376. SmartHeaderCount:=0;
  377. current_module.linkotherstaticlibs.add(current_module.importlibfilename,link_always);
  378. ObjWriter:=TARObjectWriter.CreateAr(current_module.importlibfilename);
  379. ObjOutput:=TPECoffObjOutput.Create(ObjWriter);
  380. for i:=0 to current_module.ImportLibraryList.Count-1 do
  381. begin
  382. ImportLibrary:=TImportLibrary(current_module.ImportLibraryList[i]);
  383. StartImport(ImportLibrary.Name);
  384. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  385. begin
  386. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  387. AddImport(ImportSymbol.Name,ImportSymbol.MangledName,ImportSymbol.OrdNr,ImportSymbol.IsVar);
  388. end;
  389. EndImport;
  390. end;
  391. ObjOutput.Free;
  392. ObjWriter.Free;
  393. end;
  394. procedure TImportLibWin.generateidatasection;
  395. var
  396. templab,
  397. l1,l2,l3,l4 {$ifdef ARM} ,l5 {$endif ARM} : tasmlabel;
  398. importname : string;
  399. suffix : integer;
  400. {$ifndef AARCH64}
  401. href : treference;
  402. {$endif AARCH64}
  403. i,j : longint;
  404. ImportLibrary : TImportLibrary;
  405. ImportSymbol : TImportSymbol;
  406. ImportLabels : TFPList;
  407. begin
  408. if current_asmdata.asmlists[al_imports]=nil then
  409. current_asmdata.asmlists[al_imports]:=TAsmList.create;
  410. if (target_asm.id in [as_i386_masm,as_i386_tasm,as_i386_nasmwin32]) then
  411. begin
  412. new_section(current_asmdata.asmlists[al_imports],sec_code,'',0);
  413. for i:=0 to current_module.ImportLibraryList.Count-1 do
  414. begin
  415. ImportLibrary:=TImportLibrary(current_module.ImportLibraryList[i]);
  416. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  417. begin
  418. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  419. current_asmdata.asmlists[al_imports].concat(tai_directive.create(asd_extern,ImportSymbol.Name));
  420. current_asmdata.asmlists[al_imports].concat(tai_directive.create(asd_nasm_import,ImportSymbol.Name+' '+ImportLibrary.Name+' '+ImportSymbol.Name));
  421. end;
  422. end;
  423. exit;
  424. end;
  425. for i:=0 to current_module.ImportLibraryList.Count-1 do
  426. begin
  427. ImportLibrary:=TImportLibrary(current_module.ImportLibraryList[i]);
  428. { align al_procedures for the jumps }
  429. new_section(current_asmdata.asmlists[al_imports],sec_code,'',sizeof(aint));
  430. { Get labels for the sections }
  431. current_asmdata.getjumplabel(l1);
  432. current_asmdata.getjumplabel(l2);
  433. current_asmdata.getjumplabel(l3);
  434. new_section(current_asmdata.asmlists[al_imports],sec_idata2,'',0);
  435. { pointer to procedure names }
  436. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_rva_sym(l2));
  437. { two empty entries follow }
  438. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_32bit(0));
  439. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_32bit(0));
  440. { pointer to dll name }
  441. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_rva_sym(l1));
  442. { pointer to fixups }
  443. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_rva_sym(l3));
  444. { only create one section for each else it will
  445. create a lot of idata* }
  446. { first write the name references }
  447. new_section(current_asmdata.asmlists[al_imports],sec_idata4,'',0);
  448. current_asmdata.asmlists[al_imports].concat(Tai_label.Create(l2));
  449. ImportLabels:=TFPList.Create;
  450. ImportLabels.Count:=ImportLibrary.ImportSymbolList.Count;
  451. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  452. begin
  453. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  454. current_asmdata.getjumplabel(templab);
  455. ImportLabels[j]:=templab;
  456. if ImportSymbol.Name<>'' then
  457. begin
  458. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_rva_sym(TAsmLabel(ImportLabels[j])));
  459. if target_info.system in systems_peoptplus then
  460. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_32bit(0));
  461. end
  462. else
  463. begin
  464. if target_info.system in systems_peoptplus then
  465. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_64bit(int64($8000000000000000) or ImportSymbol.ordnr))
  466. else
  467. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_32bit(longint($80000000) or ImportSymbol.ordnr));
  468. end;
  469. end;
  470. { finalize the names ... }
  471. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_32bit(0));
  472. if target_info.system in systems_peoptplus then
  473. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_32bit(0));
  474. { then the addresses and create also the indirect jump }
  475. new_section(current_asmdata.asmlists[al_imports],sec_idata5,'',0);
  476. current_asmdata.asmlists[al_imports].concat(Tai_label.Create(l3));
  477. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  478. begin
  479. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  480. if not ImportSymbol.IsVar then
  481. begin
  482. current_asmdata.getjumplabel(l4);
  483. {$ifdef ARM}
  484. current_asmdata.getjumplabel(l5);
  485. {$endif ARM}
  486. { create indirect jump and }
  487. { place jump in al_procedures }
  488. new_section(current_asmdata.asmlists[al_imports],sec_code,'',0);
  489. if ImportSymbol.Name <> '' then
  490. current_asmdata.asmlists[al_imports].concat(Tai_symbol.Createname_global(ImportSymbol.MangledName,AT_FUNCTION,0,voidcodepointertype))
  491. else
  492. current_asmdata.asmlists[al_imports].concat(Tai_symbol.Createname_global(ExtractFileName(ImportLibrary.Name)+'_index_'+tostr(ImportSymbol.ordnr),AT_FUNCTION,0,voidcodepointertype));
  493. current_asmdata.asmlists[al_imports].concat(tai_function_name.create(''));
  494. {$if defined(ARM)}
  495. reference_reset_symbol(href,l5,0,sizeof(pint),[]);
  496. current_asmdata.asmlists[al_imports].concat(Taicpu.op_reg_ref(A_LDR,NR_R12,href));
  497. reference_reset_base(href,NR_R12,0,ctempposinvalid,sizeof(pint),[]);
  498. current_asmdata.asmlists[al_imports].concat(Taicpu.op_reg_ref(A_LDR,NR_R15,href));
  499. current_asmdata.asmlists[al_imports].concat(Tai_label.Create(l5));
  500. reference_reset_symbol(href,l4,0,sizeof(pint),[]);
  501. current_asmdata.asmlists[al_imports].concat(tai_const.create_sym_offset(href.symbol,href.offset));
  502. {$elseif defined(AARCH64)}
  503. { ToDo }
  504. internalerror(2020033001);
  505. {$else X86}
  506. reference_reset_symbol(href,l4,0,sizeof(pint),[]);
  507. {$ifdef X86_64}
  508. href.base:=NR_RIP;
  509. {$endif X86_64}
  510. current_asmdata.asmlists[al_imports].concat(Taicpu.Op_ref(A_JMP,S_NO,href));
  511. current_asmdata.asmlists[al_imports].concat(Tai_align.Create_op(4,$90));
  512. {$endif X86}
  513. { add jump field to al_imports }
  514. new_section(current_asmdata.asmlists[al_imports],sec_idata5,'',0);
  515. if (cs_debuginfo in current_settings.moduleswitches) then
  516. begin
  517. if ImportSymbol.MangledName<>'' then
  518. begin
  519. importname:='__imp_'+ImportSymbol.MangledName;
  520. suffix:=0;
  521. while assigned(current_asmdata.getasmsymbol(importname)) do
  522. begin
  523. inc(suffix);
  524. importname:='__imp_'+ImportSymbol.MangledName+'_'+tostr(suffix);
  525. end;
  526. current_asmdata.asmlists[al_imports].concat(tai_symbol.createname(importname,AT_FUNCTION,4,voidcodepointertype));
  527. end
  528. else
  529. begin
  530. importname:='__imp_by_ordinal'+tostr(ImportSymbol.ordnr);
  531. suffix:=0;
  532. while assigned(current_asmdata.getasmsymbol(importname)) do
  533. begin
  534. inc(suffix);
  535. importname:='__imp_by_ordinal'+tostr(ImportSymbol.ordnr)+'_'+tostr(suffix);
  536. end;
  537. current_asmdata.asmlists[al_imports].concat(tai_symbol.createname(importname,AT_FUNCTION,4,voidcodepointertype));
  538. end;
  539. end;
  540. current_asmdata.asmlists[al_imports].concat(Tai_label.Create(l4));
  541. end
  542. else
  543. current_asmdata.asmlists[al_imports].concat(Tai_symbol.Createname_global(ImportSymbol.MangledName,AT_DATA,0,voidpointertype));
  544. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_rva_sym(TAsmLabel(Importlabels[j])));
  545. if target_info.system in systems_peoptplus then
  546. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_32bit(0));
  547. end;
  548. { finalize the addresses }
  549. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_32bit(0));
  550. if target_info.system in systems_peoptplus then
  551. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_32bit(0));
  552. { finally the import information }
  553. new_section(current_asmdata.asmlists[al_imports],sec_idata6,'',0);
  554. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  555. begin
  556. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  557. current_asmdata.asmlists[al_imports].concat(Tai_label.Create(TAsmLabel(ImportLabels[j])));
  558. { the ordinal number }
  559. current_asmdata.asmlists[al_imports].concat(Tai_const.Create_16bit(ImportSymbol.ordnr));
  560. current_asmdata.asmlists[al_imports].concat(Tai_string.Create(ImportSymbol.Name+#0));
  561. current_asmdata.asmlists[al_imports].concat(Tai_align.Create_op(2,0));
  562. end;
  563. { create import dll name }
  564. new_section(current_asmdata.asmlists[al_imports],sec_idata7,'',0);
  565. current_asmdata.asmlists[al_imports].concat(Tai_label.Create(l1));
  566. current_asmdata.asmlists[al_imports].concat(Tai_string.Create(ImportLibrary.Name+#0));
  567. ImportLabels.Free;
  568. ImportLabels:=nil;
  569. end;
  570. end;
  571. procedure TImportLibWin.generatelib;
  572. begin
  573. if GenerateImportSection then
  574. generateidatasection
  575. else
  576. generateimportlib;
  577. end;
  578. {*****************************************************************************
  579. TExportLibWin
  580. *****************************************************************************}
  581. destructor TExportLibWin.Destroy;
  582. begin
  583. EList_indexed.Free;
  584. EList_nonindexed.Free;
  585. inherited;
  586. end;
  587. procedure TExportLibWin.preparelib(const s:string);
  588. begin
  589. if current_asmdata.asmlists[al_exports]=nil then
  590. current_asmdata.asmlists[al_exports]:=TAsmList.create;
  591. if EList_indexed=nil then
  592. EList_indexed:=tFPList.Create;
  593. if EList_nonindexed=nil then
  594. EList_nonindexed:=tFPList.Create;
  595. end;
  596. procedure TExportLibWin.exportvar(hp : texported_item);
  597. begin
  598. { same code used !! PM }
  599. exportprocedure(hp);
  600. end;
  601. var
  602. Gl_DoubleIndex:boolean;
  603. Gl_DoubleIndexValue:longint;
  604. function IdxCompare(Item1, Item2: Pointer): Integer;
  605. var
  606. I1:texported_item absolute Item1;
  607. I2:texported_item absolute Item2;
  608. begin
  609. Result:=I1.index-I2.index;
  610. if(Result=0)and(Item1<>Item2)then
  611. begin
  612. Gl_DoubleIndex:=true;
  613. Gl_DoubleIndexValue:=I1.index;
  614. end;
  615. end;
  616. procedure TExportLibWin.exportprocedure(hp : texported_item);
  617. begin
  618. if (eo_index in hp.options) and ((hp.index<=0) or (hp.index>$ffff)) then
  619. begin
  620. message1(parser_e_export_invalid_index,tostr(hp.index));
  621. exit;
  622. end;
  623. if eo_index in hp.options then
  624. EList_indexed.Add(hp)
  625. else
  626. EList_nonindexed.Add(hp);
  627. end;
  628. procedure TExportLibWin.exportfromlist(hp : texported_item);
  629. //formerly TExportLibWin.exportprocedure
  630. { must be ordered at least for win32 !! }
  631. var
  632. hp2 : texported_item;
  633. begin
  634. hp2:=texported_item(current_module._exports.first);
  635. while assigned(hp2) and
  636. (hp.name^>hp2.name^) do
  637. hp2:=texported_item(hp2.next);
  638. { insert hp there !! }
  639. if hp2=nil then
  640. current_module._exports.concat(hp)
  641. else
  642. begin
  643. if hp2.name^=hp.name^ then
  644. begin
  645. { this is not allowed !! }
  646. duplicatesymbol(hp.name^);
  647. exit;
  648. end;
  649. current_module._exports.insertbefore(hp,hp2);
  650. end;
  651. end;
  652. procedure TExportLibWin.generatelib;
  653. var
  654. ordinal_base,ordinal_max,ordinal_min : longint;
  655. current_index : longint;
  656. entries,named_entries : longint;
  657. name_label,dll_name_label,export_address_table : tasmlabel;
  658. export_name_table_pointers,export_ordinal_table : tasmlabel;
  659. hp,hp2 : texported_item;
  660. temtexport : TLinkedList;
  661. address_table,name_table_pointers,
  662. name_table,ordinal_table : TAsmList;
  663. i,autoindex,ni_high : longint;
  664. hole : boolean;
  665. asmsym : TAsmSymbol;
  666. begin
  667. Gl_DoubleIndex:=false;
  668. ELIst_indexed.Sort(@IdxCompare);
  669. if Gl_DoubleIndex then
  670. begin
  671. message1(parser_e_export_ordinal_double,tostr(Gl_DoubleIndexValue));
  672. FreeAndNil(EList_indexed);
  673. FreeAndNil(EList_nonindexed);
  674. exit;
  675. end;
  676. autoindex:=1;
  677. while EList_nonindexed.Count>0 do
  678. begin
  679. hole:=(EList_indexed.Count>0) and (texported_item(EList_indexed.Items[0]).index>1);
  680. if not hole then
  681. for i:=autoindex to pred(EList_indexed.Count) do
  682. if texported_item(EList_indexed.Items[i]).index-texported_item(EList_indexed.Items[pred(i)]).index>1 then
  683. begin
  684. autoindex:=succ(texported_item(EList_indexed.Items[pred(i)]).index);
  685. hole:=true;
  686. break;
  687. end;
  688. ni_high:=pred(EList_nonindexed.Count);
  689. if not hole then
  690. begin
  691. autoindex:=succ(EList_indexed.Count);
  692. EList_indexed.Add(EList_nonindexed.Items[ni_high]);
  693. end
  694. else
  695. EList_indexed.Insert(pred(AutoIndex),EList_nonindexed.Items[ni_high]);
  696. EList_nonindexed.Delete(ni_high);
  697. texported_item(EList_indexed.Items[pred(AutoIndex)]).index:=autoindex;
  698. end;
  699. FreeAndNil(EList_nonindexed);
  700. for i:=0 to pred(EList_indexed.Count) do
  701. exportfromlist(texported_item(EList_indexed.Items[i]));
  702. FreeAndNil(EList_indexed);
  703. if (target_asm.id in [as_i386_masm,as_i386_tasm,as_i386_nasmwin32]) then
  704. begin
  705. generatenasmlib;
  706. exit;
  707. end;
  708. hp:=texported_item(current_module._exports.first);
  709. if not assigned(hp) then
  710. exit;
  711. ordinal_max:=0;
  712. ordinal_min:=$7FFFFFFF;
  713. entries:=0;
  714. named_entries:=0;
  715. current_asmdata.getjumplabel(dll_name_label);
  716. current_asmdata.getjumplabel(export_address_table);
  717. current_asmdata.getjumplabel(export_name_table_pointers);
  718. current_asmdata.getjumplabel(export_ordinal_table);
  719. { count entries }
  720. while assigned(hp) do
  721. begin
  722. inc(entries);
  723. if (hp.index>ordinal_max) then
  724. ordinal_max:=hp.index;
  725. if (hp.index>0) and (hp.index<ordinal_min) then
  726. ordinal_min:=hp.index;
  727. if assigned(hp.name) then
  728. inc(named_entries);
  729. hp:=texported_item(hp.next);
  730. end;
  731. { no support for higher ordinal base yet !! }
  732. ordinal_base:=1;
  733. current_index:=ordinal_base;
  734. { we must also count the holes !! }
  735. entries:=ordinal_max-ordinal_base+1;
  736. new_section(current_asmdata.asmlists[al_exports],sec_edata,'',0);
  737. { create label to reference from main so smartlink will include
  738. the .edata section }
  739. current_asmdata.asmlists[al_exports].concat(Tai_symbol.Createname_global(make_mangledname('EDATA',current_module.localsymtable,''),AT_METADATA,0,voidpointertype));
  740. { export flags }
  741. current_asmdata.asmlists[al_exports].concat(Tai_const.Create_32bit(0));
  742. { date/time stamp }
  743. current_asmdata.asmlists[al_exports].concat(Tai_const.Create_32bit(0));
  744. { major version }
  745. current_asmdata.asmlists[al_exports].concat(Tai_const.Create_16bit(0));
  746. { minor version }
  747. current_asmdata.asmlists[al_exports].concat(Tai_const.Create_16bit(0));
  748. { pointer to dll name }
  749. current_asmdata.asmlists[al_exports].concat(Tai_const.Create_rva_sym(dll_name_label));
  750. { ordinal base normally set to 1 }
  751. current_asmdata.asmlists[al_exports].concat(Tai_const.Create_32bit(ordinal_base));
  752. { number of entries }
  753. current_asmdata.asmlists[al_exports].concat(Tai_const.Create_32bit(entries));
  754. { number of named entries }
  755. current_asmdata.asmlists[al_exports].concat(Tai_const.Create_32bit(named_entries));
  756. { address of export address table }
  757. current_asmdata.asmlists[al_exports].concat(Tai_const.Create_rva_sym(export_address_table));
  758. { address of name pointer pointers }
  759. current_asmdata.asmlists[al_exports].concat(Tai_const.Create_rva_sym(export_name_table_pointers));
  760. { address of ordinal number pointers }
  761. current_asmdata.asmlists[al_exports].concat(Tai_const.Create_rva_sym(export_ordinal_table));
  762. { the name }
  763. current_asmdata.asmlists[al_exports].concat(Tai_label.Create(dll_name_label));
  764. if st='' then
  765. current_asmdata.asmlists[al_exports].concat(Tai_string.Create(current_module.modulename^+target_info.sharedlibext+#0))
  766. else
  767. current_asmdata.asmlists[al_exports].concat(Tai_string.Create(st+target_info.sharedlibext+#0));
  768. { export address table }
  769. address_table:=TAsmList.create;
  770. address_table.concat(Tai_align.Create_op(4,0));
  771. address_table.concat(Tai_label.Create(export_address_table));
  772. name_table_pointers:=TAsmList.create;
  773. name_table_pointers.concat(Tai_align.Create_op(4,0));
  774. name_table_pointers.concat(Tai_label.Create(export_name_table_pointers));
  775. ordinal_table:=TAsmList.create;
  776. ordinal_table.concat(Tai_align.Create_op(4,0));
  777. ordinal_table.concat(Tai_label.Create(export_ordinal_table));
  778. name_table:=TAsmList.Create;
  779. name_table.concat(Tai_align.Create_op(4,0));
  780. { write each address }
  781. hp:=texported_item(current_module._exports.first);
  782. while assigned(hp) do
  783. begin
  784. if eo_name in hp.options then
  785. begin
  786. current_asmdata.getjumplabel(name_label);
  787. name_table_pointers.concat(Tai_const.Create_rva_sym(name_label));
  788. ordinal_table.concat(Tai_const.Create_16bit(hp.index-ordinal_base));
  789. name_table.concat(Tai_align.Create_op(2,0));
  790. name_table.concat(Tai_label.Create(name_label));
  791. name_table.concat(Tai_string.Create(hp.name^+#0));
  792. end;
  793. hp:=texported_item(hp.next);
  794. end;
  795. { order in increasing ordinal values }
  796. { into temtexport list }
  797. temtexport:=TLinkedList.Create;
  798. hp:=texported_item(current_module._exports.first);
  799. while assigned(hp) do
  800. begin
  801. current_module._exports.remove(hp);
  802. hp2:=texported_item(temtexport.first);
  803. while assigned(hp2) and (hp.index>hp2.index) do
  804. hp2:=texported_item(hp2.next);
  805. if hp2=nil then
  806. temtexport.concat(hp)
  807. else
  808. temtexport.insertbefore(hp,hp2);
  809. hp:=texported_item(current_module._exports.first);
  810. end;
  811. { write the export adress table }
  812. current_index:=ordinal_base;
  813. hp:=texported_item(temtexport.first);
  814. while assigned(hp) do
  815. begin
  816. { fill missing values }
  817. while current_index<hp.index do
  818. begin
  819. address_table.concat(Tai_const.Create_32bit(0));
  820. inc(current_index);
  821. end;
  822. { symbol known? then get a new name }
  823. if assigned(hp.sym) and not (eo_no_sym_name in hp.options) then
  824. case hp.sym.typ of
  825. staticvarsym :
  826. asmsym:=current_asmdata.RefAsmSymbol(tstaticvarsym(hp.sym).mangledname,AT_DATA);
  827. procsym :
  828. asmsym:=current_asmdata.RefAsmSymbol(tprocdef(tprocsym(hp.sym).ProcdefList[0]).mangledname,AT_FUNCTION)
  829. else
  830. internalerror(200709272);
  831. end
  832. else
  833. asmsym:=current_asmdata.RefAsmSymbol(hp.name^,AT_DATA);
  834. address_table.concat(Tai_const.Create_rva_sym(asmsym));
  835. inc(current_index);
  836. hp:=texported_item(hp.next);
  837. end;
  838. current_asmdata.asmlists[al_exports].concatlist(address_table);
  839. current_asmdata.asmlists[al_exports].concatlist(name_table_pointers);
  840. current_asmdata.asmlists[al_exports].concatlist(ordinal_table);
  841. current_asmdata.asmlists[al_exports].concatlist(name_table);
  842. address_table.Free;
  843. name_table_pointers.free;
  844. ordinal_table.free;
  845. name_table.free;
  846. { the package support needs this data later on
  847. to create the import library }
  848. current_module._exports.concatlist(temtexport);
  849. temtexport.free;
  850. end;
  851. procedure TExportLibWin.generatenasmlib;
  852. var
  853. hp : texported_item;
  854. {p : pchar;
  855. s : string;}
  856. begin
  857. new_section(current_asmdata.asmlists[al_exports],sec_code,'',0);
  858. hp:=texported_item(current_module._exports.first);
  859. while assigned(hp) do
  860. begin
  861. { case hp.sym.typ of
  862. staticvarsym :
  863. s:=tstaticvarsym(hp.sym).mangledname;
  864. procsym :
  865. s:=tprocdef(tprocsym(hp.sym).ProcdefList[0]).mangledname;
  866. else
  867. s:='';
  868. end;
  869. p:=strpnew(#9+'export '+s+' '+hp.Name^+' '+tostr(hp.index));
  870. current_asmdata.asmlists[al_exports].concat(tai_direct.create(p));}
  871. hp:=texported_item(hp.next);
  872. end;
  873. end;
  874. {****************************************************************************
  875. TInternalLinkerWin
  876. ****************************************************************************}
  877. constructor TInternalLinkerWin.Create;
  878. begin
  879. inherited Create;
  880. CArObjectReader:=TArObjectReader;
  881. CExeoutput:=TPECoffexeoutput;
  882. CObjInput:=TPECoffObjInput;
  883. end;
  884. procedure TInternalLinkerWin.DefaultLinkScript;
  885. begin
  886. ScriptAddSourceStatements(true);
  887. with LinkScript do
  888. begin
  889. if IsSharedLibrary then
  890. Concat('ISSHAREDLIBRARY');
  891. ConcatEntryName;
  892. if not ImageBaseSetExplicity then
  893. begin
  894. if IsSharedLibrary then
  895. imagebase:={$ifdef cpu64bitaddr} $110000000 {$else} $10000000 {$endif}
  896. else
  897. if target_info.system in systems_wince then
  898. imagebase:=$10000
  899. else
  900. {$ifdef cpu64bitaddr}
  901. if (target_dbg.id = dbg_stabs) then
  902. imagebase:=$400000
  903. else
  904. imagebase:= $100000000;
  905. {$else}
  906. imagebase:=$400000;
  907. {$endif}
  908. end;
  909. Concat('IMAGEBASE $' + hexStr(imagebase, SizeOf(imagebase)*2));
  910. Concat('HEADER');
  911. Concat('EXESECTION .text');
  912. Concat(' SYMBOL __text_start__');
  913. Concat(' OBJSECTION .text*');
  914. Concat(' SYMBOL ___CTOR_LIST__');
  915. Concat(' SYMBOL __CTOR_LIST__');
  916. Concat(' LONG -1');
  917. {$ifdef cpu64}
  918. Concat(' LONG -1');
  919. {$endif cpu64}
  920. Concat(' OBJSECTION .ctor*');
  921. Concat(' LONG 0');
  922. {$ifdef cpu64}
  923. Concat(' LONG 0');
  924. {$endif cpu64}
  925. Concat(' SYMBOL ___DTOR_LIST__');
  926. Concat(' SYMBOL __DTOR_LIST__');
  927. Concat(' LONG -1');
  928. {$ifdef cpu64}
  929. Concat(' LONG -1');
  930. {$endif cpu64}
  931. Concat(' OBJSECTION .dtor*');
  932. Concat(' LONG 0');
  933. {$ifdef cpu64}
  934. Concat(' LONG 0');
  935. {$endif cpu64}
  936. Concat(' SYMBOL etext');
  937. Concat('ENDEXESECTION');
  938. Concat('EXESECTION .data');
  939. Concat(' SYMBOL __data_start__');
  940. Concat(' OBJSECTION .data*');
  941. Concat(' OBJSECTION .fpc*');
  942. Concat(' PROVIDE '+target_info.Cprefix+'_tls_index');
  943. Concat(' LONG 0');
  944. Concat(' SYMBOL edata');
  945. Concat(' SYMBOL __data_end__');
  946. Concat('ENDEXESECTION');
  947. Concat('EXESECTION .rdata');
  948. Concat(' SYMBOL ___RUNTIME_PSEUDO_RELOC_LIST__');
  949. Concat(' SYMBOL __RUNTIME_PSEUDO_RELOC_LIST__');
  950. Concat(' OBJSECTION .rdata_runtime_pseudo_reloc');
  951. Concat(' SYMBOL ___RUNTIME_PSEUDO_RELOC_LIST_END__');
  952. Concat(' SYMBOL __RUNTIME_PSEUDO_RELOC_LIST_END__');
  953. Concat(' OBJSECTION .rdata*');
  954. Concat(' OBJSECTION .rodata*');
  955. Concat(' OBJSECTION .xdata*');
  956. Concat('ENDEXESECTION');
  957. Concat('EXESECTION .pdata');
  958. Concat(' OBJSECTION .pdata*');
  959. Concat('ENDEXESECTION');
  960. Concat('EXESECTION .bss');
  961. Concat(' SYMBOL __bss_start__');
  962. Concat(' OBJSECTION .bss*');
  963. Concat(' SYMBOL __bss_end__');
  964. Concat('ENDEXESECTION');
  965. Concat('EXESECTION .tls');
  966. Concat(' SYMBOL ___tls_start__');
  967. Concat(' OBJSECTION .tls*');
  968. Concat(' SYMBOL ___tls_end__');
  969. Concat('ENDEXESECTION');
  970. Concat('EXESECTION .CRT');
  971. Concat(' SYMBOL ___crt_xc_start__');
  972. Concat(' OBJSECTION .CRT$XC*');{ /* C initialization */');}
  973. Concat(' SYMBOL ___crt_xc_end__');
  974. Concat(' SYMBOL ___crt_xi_start__');
  975. Concat(' OBJSECTION .CRT$XI*');{ /* C++ initialization */');}
  976. Concat(' SYMBOL ___crt_xi_end__');
  977. Concat(' SYMBOL ___crt_xl_start__');
  978. Concat(' OBJSECTION .CRT$XL*'); { /* TLS callbacks */'); }
  979. { In GNU ld, this is defined in the TLS Directory support code }
  980. Concat(' PROVIDE ___crt_xl_end__');
  981. { Add a nil pointer as last element }
  982. Concat(' LONG 0');
  983. {$ifdef cpu64}
  984. Concat(' LONG 0');
  985. {$endif cpu64}
  986. Concat(' SYMBOL ___crt_xp_start__');
  987. Concat(' OBJSECTION .CRT$XP*'); { /* Pre-termination */');}
  988. Concat(' SYMBOL ___crt_xp_end__');
  989. Concat(' SYMBOL ___crt_xt_start__');
  990. Concat(' OBJSECTION .CRT$XT*');{ /* Termination */');}
  991. Concat(' SYMBOL ___crt_xt_end__');
  992. Concat('ENDEXESECTION');
  993. Concat('EXESECTION .idata');
  994. Concat(' OBJSECTION .idata$2*');
  995. Concat(' OBJSECTION .idata$3*');
  996. Concat(' ZEROS 20');
  997. Concat(' OBJSECTION .idata$4*');
  998. Concat(' SYMBOL __IAT_start__');
  999. Concat(' OBJSECTION .idata$5*');
  1000. Concat(' SYMBOL __IAT_end__');
  1001. Concat(' OBJSECTION .idata$6*');
  1002. Concat(' OBJSECTION .idata$7*');
  1003. Concat('ENDEXESECTION');
  1004. ScriptAddGenericSections('.edata,.rsrc,.reloc,.gnu_debuglink,'+
  1005. '.debug_aranges,.debug_pubnames,.debug_info,.debug_abbrev,.debug_line,.debug_frame,.debug_str,.debug_loc,'+
  1006. '.debug_macinfo,.debug_weaknames,.debug_funcnames,.debug_typenames,.debug_varnames,.debug_ranges');
  1007. { Can't use the generic rules, because that will add also .stabstr to .stab }
  1008. Concat('EXESECTION .stab');
  1009. Concat(' OBJSECTION .stab');
  1010. Concat('ENDEXESECTION');
  1011. Concat('EXESECTION .stabstr');
  1012. Concat(' OBJSECTION .stabstr');
  1013. Concat('ENDEXESECTION');
  1014. Concat('STABS');
  1015. Concat('SYMBOLS');
  1016. end;
  1017. end;
  1018. procedure TInternalLinkerWin.InitSysInitUnitName;
  1019. begin
  1020. GlobalInitSysInitUnitName(self)
  1021. end;
  1022. procedure TInternalLinkerWin.ConcatEntryName;
  1023. begin
  1024. with LinkScript do
  1025. begin
  1026. if IsSharedLibrary then
  1027. begin
  1028. Concat('ISSHAREDLIBRARY');
  1029. if apptype=app_gui then
  1030. Concat('ENTRYNAME _DLLWinMainCRTStartup')
  1031. else
  1032. Concat('ENTRYNAME _DLLMainCRTStartup');
  1033. end
  1034. else
  1035. begin
  1036. if apptype=app_gui then
  1037. Concat('ENTRYNAME _WinMainCRTStartup')
  1038. else
  1039. Concat('ENTRYNAME _mainCRTStartup');
  1040. end;
  1041. end;
  1042. end;
  1043. {****************************************************************************
  1044. TExternalLinkerWin
  1045. ****************************************************************************}
  1046. Constructor TExternalLinkerWin.Create;
  1047. begin
  1048. Inherited Create;
  1049. { allow duplicated libs (PM) }
  1050. SharedLibFiles.doubles:=true;
  1051. StaticLibFiles.doubles:=true;
  1052. end;
  1053. Procedure TExternalLinkerWin.SetDefaultInfo;
  1054. var
  1055. targetopts: string;
  1056. begin
  1057. with Info do
  1058. begin
  1059. {$ifdef aarch64}
  1060. targetopts:='-b pei-aarch64-little';
  1061. {$endif aarch64}
  1062. {$ifdef x86_64}
  1063. targetopts:='-b pei-x86-64';
  1064. {$endif x86_64}
  1065. {$ifdef i386}
  1066. targetopts:='-b pei-i386 -m i386pe';
  1067. {$endif i386}
  1068. {$ifdef arm}
  1069. targetopts:='-m arm_wince_pe';
  1070. {$endif arm}
  1071. ExeCmd[1]:='ld '+targetopts+' $OPT $GCSECTIONS $MAP $STRIP $APPTYPE $ENTRY $IMAGEBASE $RELOC -o $EXE -T $RES';
  1072. DllCmd[1]:='ld '+targetopts+' $OPT $GCSECTIONS $MAP $STRIP --dll $APPTYPE $ENTRY $IMAGEBASE $RELOC -o $EXE -T $RES';
  1073. { ExeCmd[2]:='dlltool --as $ASBIN --dllname $EXE --output-exp exp.$$$ $RELOC $DEF';
  1074. use short forms to avoid 128 char limitation problem }
  1075. ExeCmd[2]:='dlltool -S $ASBIN -D $EXE -e exp.$$$ $RELOC $DEF';
  1076. ExeCmd[3]:='ld '+targetopts+' $OPT $STRIP $APPTYPE $ENTRY $IMAGEBASE -o $EXE -T $RES exp.$$$';
  1077. { DllCmd[2]:='dlltool --as $ASBIN --dllname $EXE --output-exp exp.$$$ $RELOC $DEF'; }
  1078. DllCmd[2]:='dlltool -S $ASBIN -D $EXE -e exp.$$$ $RELOC $DEF';
  1079. DllCmd[3]:='ld '+targetopts+' $OPT $STRIP --dll $APPTYPE $ENTRY $IMAGEBASE -o $EXE -T $RES exp.$$$';
  1080. end;
  1081. end;
  1082. Function TExternalLinkerWin.WriteResponseFile(isdll:boolean) : Boolean;
  1083. Var
  1084. linkres : TLinkRes;
  1085. HPath : TCmdStrListItem;
  1086. s,s2 : TCmdStr;
  1087. i : integer;
  1088. begin
  1089. WriteResponseFile:=False;
  1090. if (cs_profile in current_settings.moduleswitches) then
  1091. begin
  1092. SharedLibFiles.Concat('gmon');
  1093. SharedLibFiles.Concat('c');
  1094. SharedLibFiles.Concat('gcc');
  1095. SharedLibFiles.Concat('kernel32');
  1096. end;
  1097. { Open link.res file }
  1098. LinkRes:=TLinkres.Create(outputexedir+Info.ResName,true);
  1099. with linkres do
  1100. begin
  1101. { Write path to search libraries }
  1102. HPath:=TCmdStrListItem(current_module.locallibrarysearchpath.First);
  1103. while assigned(HPath) do
  1104. begin
  1105. Add('SEARCH_DIR("'+HPath.Str+'")');
  1106. HPath:=TCmdStrListItem(HPath.Next);
  1107. end;
  1108. HPath:=TCmdStrListItem(LibrarySearchPath.First);
  1109. while assigned(HPath) do
  1110. begin
  1111. Add('SEARCH_DIR("'+HPath.Str+'")');
  1112. HPath:=TCmdStrListItem(HPath.Next);
  1113. end;
  1114. { add objectfiles, start with prt0 always }
  1115. { profiling of shared libraries is currently not supported }
  1116. if not ObjectFiles.Empty then
  1117. begin
  1118. Add('INPUT(');
  1119. while not ObjectFiles.Empty do
  1120. begin
  1121. s:=ObjectFiles.GetFirst;
  1122. if s<>'' then
  1123. AddFileName(MaybeQuoted(s));
  1124. end;
  1125. Add(')');
  1126. end;
  1127. { Write staticlibraries }
  1128. if (not StaticLibFiles.Empty) then
  1129. begin
  1130. Add('GROUP(');
  1131. While not StaticLibFiles.Empty do
  1132. begin
  1133. S:=StaticLibFiles.GetFirst;
  1134. AddFileName(MaybeQuoted(s));
  1135. end;
  1136. Add(')');
  1137. end;
  1138. { Write sharedlibraries (=import libraries) }
  1139. if not SharedLibFiles.Empty then
  1140. begin
  1141. Add('INPUT(') ;
  1142. While not SharedLibFiles.Empty do
  1143. begin
  1144. S:=SharedLibFiles.GetFirst;
  1145. if FindLibraryFile(s,target_info.staticClibprefix,target_info.staticClibext,s2) then
  1146. begin
  1147. Add(MaybeQuoted(s2));
  1148. continue;
  1149. end;
  1150. if pos(target_info.sharedlibprefix,s)=1 then
  1151. s:=copy(s,length(target_info.sharedlibprefix)+1,255);
  1152. i:=Pos(target_info.sharedlibext,S);
  1153. if i>0 then
  1154. Delete(S,i,255);
  1155. Add('-l'+s);
  1156. end;
  1157. Add(')');
  1158. end;
  1159. Add('SEARCH_DIR("/usr/i686-pc-cygwin/lib"); SEARCH_DIR("/usr/lib"); SEARCH_DIR("/usr/lib/w32api");');
  1160. {$if defined(aarch64)}
  1161. Add('OUTPUT_FORMAT(pei-aarch64-little)');
  1162. {$elseif defined(x86_64)}
  1163. Add('OUTPUT_FORMAT(pei-x86-64)');
  1164. {$else not 86_64}
  1165. Add('OUTPUT_FORMAT(pei-i386)');
  1166. {$endif not x86_64}
  1167. Add('ENTRY(_mainCRTStartup)');
  1168. Add('SECTIONS');
  1169. Add('{');
  1170. Add(' . = SIZEOF_HEADERS;');
  1171. Add(' . = ALIGN(__section_alignment__);');
  1172. Add(' .text __image_base__ + ( __section_alignment__ < 0x1000 ? . : __section_alignment__ ) :');
  1173. Add(' {');
  1174. Add(' __text_start__ = . ;');
  1175. Add(' *(.init)');
  1176. add(' *(.text .stub .text.* .gnu.linkonce.t.*)');
  1177. Add(' *(SORT(.text$*))');
  1178. Add(' *(.glue_7t)');
  1179. Add(' *(.glue_7)');
  1180. Add(' . = ALIGN(8);');
  1181. Add(' ___CTOR_LIST__ = .; __CTOR_LIST__ = . ;');
  1182. Add(' LONG (-1);');
  1183. {$ifdef cpu64}
  1184. Add(' LONG (-1);');
  1185. {$endif cpu64}
  1186. Add(' *(.ctors); *(.ctor); *(SORT(.ctors.*)); LONG (0);');
  1187. {$ifdef cpu64}
  1188. Add(' LONG (0);');
  1189. {$endif cpu64}
  1190. Add(' ___DTOR_LIST__ = .; __DTOR_LIST__ = . ;');
  1191. Add(' LONG (-1);');
  1192. {$ifdef cpu64}
  1193. Add(' LONG (-1);');
  1194. {$endif cpu64}
  1195. Add(' *(.dtors); *(.dtor); *(SORT(.dtors.*)); LONG (0);');
  1196. {$ifdef cpu64}
  1197. Add(' LONG (0);');
  1198. {$endif cpu64}
  1199. Add(' *(.fini)');
  1200. Add(' PROVIDE (etext = .);');
  1201. Add(' *(.gcc_except_table)');
  1202. Add(' }');
  1203. Add(' .data BLOCK(__section_alignment__) :');
  1204. Add(' {');
  1205. Add(' __data_start__ = . ;');
  1206. add(' *(.data .data.* .gnu.linkonce.d.* .fpc*)');
  1207. Add(' *(.data2)');
  1208. Add(' *(SORT(.data$*))');
  1209. Add(' *(.jcr)');
  1210. Add(' PROVIDE ('+target_info.Cprefix+'_tls_index = .);');
  1211. Add(' LONG (0);');
  1212. Add(' __data_end__ = . ;');
  1213. Add(' *(.data_cygwin_nocopy)');
  1214. Add(' }');
  1215. Add(' .rdata BLOCK(__section_alignment__) :');
  1216. Add(' {');
  1217. Add(' *(.rdata)');
  1218. Add(' *(.rdata.*)');
  1219. add(' *(.rodata .rodata.* .gnu.linkonce.r.*)');
  1220. Add(' *(SORT(.rdata$*))');
  1221. Add(' *(.eh_frame)');
  1222. Add(' ___RUNTIME_PSEUDO_RELOC_LIST__ = .;');
  1223. Add(' __RUNTIME_PSEUDO_RELOC_LIST__ = .;');
  1224. Add(' *(.rdata_runtime_pseudo_reloc)');
  1225. Add(' ___RUNTIME_PSEUDO_RELOC_LIST_END__ = .;');
  1226. Add(' __RUNTIME_PSEUDO_RELOC_LIST_END__ = .;');
  1227. Add(' }');
  1228. Add(' .pdata BLOCK(__section_alignment__) : { *(.pdata) }');
  1229. Add(' .bss BLOCK(__section_alignment__) :');
  1230. Add(' {');
  1231. Add(' __bss_start__ = . ;');
  1232. Add(' *(.bss .bss.* .gnu.linkonce.b.*)');
  1233. Add(' *(SORT(.bss$*))');
  1234. Add(' *(COMMON)');
  1235. Add(' __bss_end__ = . ;');
  1236. Add(' }');
  1237. Add(' .edata BLOCK(__section_alignment__) : { *(.edata) }');
  1238. Add(' .idata BLOCK(__section_alignment__) :');
  1239. Add(' {');
  1240. Add(' SORT(*)(.idata$2)');
  1241. Add(' SORT(*)(.idata$3)');
  1242. Add(' /* These zeroes mark the end of the import list. */');
  1243. Add(' LONG (0); LONG (0); LONG (0); LONG (0); LONG (0);');
  1244. Add(' SORT(*)(.idata$4)');
  1245. Add(' SORT(*)(.idata$5)');
  1246. Add(' SORT(*)(.idata$6)');
  1247. Add(' SORT(*)(.idata$7)');
  1248. Add(' }');
  1249. Add(' .CRT BLOCK(__section_alignment__) :');
  1250. Add(' {');
  1251. Add(' ___crt_xc_start__ = . ;');
  1252. Add(' *(SORT(.CRT$XC*)) /* C initialization */');
  1253. Add(' ___crt_xc_end__ = . ;');
  1254. Add(' ___crt_xi_start__ = . ;');
  1255. Add(' *(SORT(.CRT$XI*)) /* C++ initialization */');
  1256. Add(' ___crt_xi_end__ = . ;');
  1257. Add(' ___crt_xl_start__ = . ;');
  1258. Add(' *(SORT(.CRT$XL*)) /* TLS callbacks */');
  1259. Add(' /* ___crt_xl_end__ is defined in the TLS Directory support code */');
  1260. Add(' PROVIDE (___crt_xl_end__ = .);');
  1261. Add(' ___crt_xp_start__ = . ;');
  1262. Add(' *(SORT(.CRT$XP*)) /* Pre-termination */');
  1263. Add(' ___crt_xp_end__ = . ;');
  1264. Add(' ___crt_xt_start__ = . ;');
  1265. Add(' *(SORT(.CRT$XT*)) /* Termination */');
  1266. Add(' ___crt_xt_end__ = . ;');
  1267. Add(' . = . ; /* This forces GNU linker to keep the section even if it is empty */');
  1268. Add(' }');
  1269. Add(' .tls BLOCK(__section_alignment__) :');
  1270. Add(' {');
  1271. Add(' ___tls_start__ = . ;');
  1272. Add(' *(.tls .tls.*)');
  1273. Add(' *(.tls$)');
  1274. Add(' *(SORT(.tls$*))');
  1275. Add(' ___tls_end__ = . ;');
  1276. Add(' . = . ; /* This forces GNU linker to keep the section even if it is empty */');
  1277. Add(' }');
  1278. Add(' .rsrc BLOCK(__section_alignment__) :');
  1279. Add(' {');
  1280. Add(' *(.rsrc)');
  1281. Add(' *(SORT(.rsrc$*))');
  1282. Add(' }');
  1283. Add(' .reloc BLOCK(__section_alignment__) : { *(.reloc) }');
  1284. Add(' .stab BLOCK(__section_alignment__) (NOLOAD) : { *(.stab) }');
  1285. Add(' .stabstr BLOCK(__section_alignment__) (NOLOAD) : { *(.stabstr) }');
  1286. Add(' .debug_aranges BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_aranges) }');
  1287. Add(' .debug_pubnames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_pubnames) }');
  1288. Add(' .debug_info BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_info) *(.gnu.linkonce.wi.*) }');
  1289. Add(' .debug_abbrev BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_abbrev) }');
  1290. Add(' .debug_line BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_line) }');
  1291. Add(' .debug_frame BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_frame) }');
  1292. Add(' .debug_str BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_str) }');
  1293. Add(' .debug_loc BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_loc) }');
  1294. Add(' .debug_macinfo BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_macinfo) }');
  1295. Add(' .debug_weaknames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_weaknames) }');
  1296. Add(' .debug_funcnames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_funcnames) }');
  1297. Add(' .debug_typenames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_typenames) }');
  1298. Add(' .debug_varnames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_varnames) }');
  1299. Add(' .debug_ranges BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_ranges) }');
  1300. Add('}');
  1301. { Write and Close response }
  1302. writetodisk;
  1303. Free;
  1304. end;
  1305. WriteResponseFile:=True;
  1306. end;
  1307. function TExternalLinkerWin.MakeExecutable:boolean;
  1308. var
  1309. MapStr,
  1310. binstr,
  1311. cmdstr : TCmdStr;
  1312. success : boolean;
  1313. cmds,i : longint;
  1314. AsBinStr : string;
  1315. GCSectionsStr,
  1316. StripStr,
  1317. RelocStr,
  1318. AppTypeStr,
  1319. EntryStr,
  1320. ImageBaseStr : string[40];
  1321. begin
  1322. if not(cs_link_nolink in current_settings.globalswitches) then
  1323. Message1(exec_i_linking,current_module.exefilename);
  1324. { Create some replacements }
  1325. RelocStr:='';
  1326. AppTypeStr:='';
  1327. EntryStr:='';
  1328. ImageBaseStr:='';
  1329. StripStr:='';
  1330. MapStr:='';
  1331. GCSectionsStr:='';
  1332. {$ifdef AARCH64}
  1333. AsBinStr:=FindUtil(utilsprefix+'clang');
  1334. {$else not AARCH64}
  1335. AsBinStr:=FindUtil(utilsprefix+'as');
  1336. {$endif AARCH64}
  1337. if RelocSection then
  1338. RelocStr:='--base-file base.$$$';
  1339. if create_smartlink_sections then
  1340. GCSectionsStr:='--gc-sections';
  1341. if target_info.system in systems_wince then
  1342. AppTypeStr:='--subsystem wince'
  1343. else
  1344. begin
  1345. if apptype=app_gui then
  1346. AppTypeStr:='--subsystem windows';
  1347. end;
  1348. if apptype=app_gui then
  1349. EntryStr:='--entry=_WinMainCRTStartup'
  1350. else
  1351. EntryStr:='--entry=_mainCRTStartup';
  1352. if ImageBaseSetExplicity then
  1353. ImageBaseStr:='--image-base=0x'+hexStr(imagebase, SizeOf(imagebase)*2);
  1354. if (cs_link_strip in current_settings.globalswitches) then
  1355. StripStr:='-s';
  1356. if (cs_link_map in current_settings.globalswitches) then
  1357. MapStr:='-Map '+maybequoted(ChangeFileExt(current_module.exefilename,'.map'));
  1358. { Write used files and libraries }
  1359. WriteResponseFile(false);
  1360. { Call linker }
  1361. success:=false;
  1362. if RelocSection or (not Deffile.empty) then
  1363. cmds:=3
  1364. else
  1365. cmds:=1;
  1366. for i:=1 to cmds do
  1367. begin
  1368. SplitBinCmd(Info.ExeCmd[i],binstr,cmdstr);
  1369. if binstr<>'' then
  1370. begin
  1371. Replace(cmdstr,'$EXE',maybequoted(current_module.exefilename));
  1372. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  1373. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  1374. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  1375. Replace(cmdstr,'$ENTRY',EntryStr);
  1376. Replace(cmdstr,'$ASBIN',AsbinStr);
  1377. Replace(cmdstr,'$RELOC',RelocStr);
  1378. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  1379. Replace(cmdstr,'$GCSECTIONS',GCSectionsStr);
  1380. Replace(cmdstr,'$STRIP',StripStr);
  1381. Replace(cmdstr,'$MAP',MapStr);
  1382. if not DefFile.Empty then
  1383. begin
  1384. DefFile.WriteFile;
  1385. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  1386. end
  1387. else
  1388. Replace(cmdstr,'$DEF','');
  1389. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  1390. if not success then
  1391. break;
  1392. end;
  1393. end;
  1394. { Post process }
  1395. if success then
  1396. success:=PostProcessExecutable(current_module.exefilename,false);
  1397. { Remove ReponseFile }
  1398. if (success) and not(cs_link_nolink in current_settings.globalswitches) then
  1399. begin
  1400. DeleteFile(outputexedir+Info.ResName);
  1401. DeleteFile('base.$$$');
  1402. DeleteFile('exp.$$$');
  1403. DeleteFile('deffile.$$$');
  1404. end;
  1405. MakeExecutable:=success; { otherwise a recursive call to link method }
  1406. end;
  1407. Function TExternalLinkerWin.MakeSharedLibrary:boolean;
  1408. var
  1409. MapStr,
  1410. binstr,
  1411. cmdstr : TCmdStr;
  1412. success : boolean;
  1413. cmds,
  1414. i : longint;
  1415. AsBinStr : string;
  1416. StripStr,
  1417. GCSectionsStr,
  1418. RelocStr,
  1419. AppTypeStr,
  1420. EntryStr,
  1421. ImageBaseStr : string[40];
  1422. begin
  1423. MakeSharedLibrary:=false;
  1424. if not(cs_link_nolink in current_settings.globalswitches) then
  1425. Message1(exec_i_linking,current_module.sharedlibfilename);
  1426. { Create some replacements }
  1427. RelocStr:='';
  1428. AppTypeStr:='';
  1429. EntryStr:='';
  1430. ImageBaseStr:='';
  1431. StripStr:='';
  1432. MapStr:='';
  1433. GCSectionsStr:='';
  1434. {$ifdef AARCH64}
  1435. AsBinStr:=FindUtil(utilsprefix+'clang');
  1436. {$else not AARCH64}
  1437. AsBinStr:=FindUtil(utilsprefix+'as');
  1438. {$endif AARCH64}
  1439. if RelocSection then
  1440. RelocStr:='--base-file base.$$$';
  1441. if create_smartlink_sections then
  1442. GCSectionsStr:='--gc-sections';
  1443. if apptype=app_gui then
  1444. begin
  1445. AppTypeStr:='--subsystem windows';
  1446. EntryStr:='--entry _DLLWinMainCRTStartup'
  1447. end
  1448. else
  1449. EntryStr:='--entry _DLLMainCRTStartup';
  1450. if ImageBaseSetExplicity then
  1451. ImageBaseStr:='--image-base=0x'+hexStr(imagebase, SizeOf(imagebase)*2);
  1452. if (cs_link_strip in current_settings.globalswitches) then
  1453. StripStr:='-s';
  1454. if (cs_link_map in current_settings.globalswitches) then
  1455. MapStr:='-Map '+maybequoted(ChangeFileExt(current_module.exefilename,'.map'));
  1456. { Write used files and libraries }
  1457. WriteResponseFile(true);
  1458. { Call linker }
  1459. success:=false;
  1460. if RelocSection or (not Deffile.empty) then
  1461. cmds:=3
  1462. else
  1463. cmds:=1;
  1464. for i:=1 to cmds do
  1465. begin
  1466. SplitBinCmd(Info.DllCmd[i],binstr,cmdstr);
  1467. if binstr<>'' then
  1468. begin
  1469. Replace(cmdstr,'$EXE',maybequoted(current_module.sharedlibfilename));
  1470. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  1471. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  1472. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  1473. Replace(cmdstr,'$ENTRY',EntryStr);
  1474. Replace(cmdstr,'$ASBIN',AsbinStr);
  1475. Replace(cmdstr,'$RELOC',RelocStr);
  1476. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  1477. Replace(cmdstr,'$STRIP',StripStr);
  1478. Replace(cmdstr,'$GCSECTIONS',GCSectionsStr);
  1479. Replace(cmdstr,'$MAP',MapStr);
  1480. if not DefFile.Empty then
  1481. begin
  1482. DefFile.WriteFile;
  1483. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  1484. end
  1485. else
  1486. Replace(cmdstr,'$DEF','');
  1487. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  1488. if not success then
  1489. break;
  1490. end;
  1491. end;
  1492. { Post process }
  1493. if success then
  1494. success:=PostProcessExecutable(current_module.sharedlibfilename,true);
  1495. { Remove ReponseFile }
  1496. if (success) and not(cs_link_nolink in current_settings.globalswitches) then
  1497. begin
  1498. DeleteFile(outputexedir+Info.ResName);
  1499. DeleteFile('base.$$$');
  1500. DeleteFile('exp.$$$');
  1501. DeleteFile('deffile.$$$');
  1502. end;
  1503. MakeSharedLibrary:=success; { otherwise a recursive call to link method }
  1504. end;
  1505. function TExternalLinkerWin.postprocessexecutable(const fn : string;isdll:boolean):boolean;
  1506. type
  1507. tdosheader = packed record
  1508. e_magic : word;
  1509. e_cblp : word;
  1510. e_cp : word;
  1511. e_crlc : word;
  1512. e_cparhdr : word;
  1513. e_minalloc : word;
  1514. e_maxalloc : word;
  1515. e_ss : word;
  1516. e_sp : word;
  1517. e_csum : word;
  1518. e_ip : word;
  1519. e_cs : word;
  1520. e_lfarlc : word;
  1521. e_ovno : word;
  1522. e_res : array[0..3] of word;
  1523. e_oemid : word;
  1524. e_oeminfo : word;
  1525. e_res2 : array[0..9] of word;
  1526. e_lfanew : longint;
  1527. end;
  1528. psecfill=^TSecfill;
  1529. TSecfill=record
  1530. fillpos,
  1531. fillsize : longint;
  1532. next : psecfill;
  1533. end;
  1534. var
  1535. f : file;
  1536. cmdstr : string;
  1537. dosheader : tdosheader;
  1538. peheader : tcoffheader;
  1539. peoptheader : tcoffpeoptheader;
  1540. firstsecpos,
  1541. maxfillsize,
  1542. l,peheaderpos : longint;
  1543. coffsec : tcoffsechdr;
  1544. secroot,hsecroot : psecfill;
  1545. zerobuf : pointer;
  1546. begin
  1547. postprocessexecutable:=false;
  1548. { when -s is used or it's a dll then quit }
  1549. if (cs_link_nolink in current_settings.globalswitches) then
  1550. begin
  1551. case apptype of
  1552. app_native :
  1553. cmdstr:='--subsystem native';
  1554. app_gui :
  1555. cmdstr:='--subsystem gui';
  1556. app_cui :
  1557. cmdstr:='--subsystem console';
  1558. else
  1559. ;
  1560. end;
  1561. if dllversion<>'' then
  1562. cmdstr:=cmdstr+' --version '+dllversion;
  1563. cmdstr:=cmdstr+' --input '+maybequoted(fn);
  1564. cmdstr:=cmdstr+' --stack '+tostr(stacksize);
  1565. if target_info.system in [system_i386_win32, system_i386_wdosx] then
  1566. DoExec(FindUtil(utilsprefix+'postw32'),cmdstr,false,false);
  1567. postprocessexecutable:=true;
  1568. exit;
  1569. end;
  1570. { open file }
  1571. assign(f,fn);
  1572. {$push}{$I-}
  1573. reset(f,1);
  1574. if ioresult<>0 then
  1575. Message1(execinfo_f_cant_open_executable,fn);
  1576. { read headers }
  1577. blockread(f,dosheader,sizeof(tdosheader));
  1578. peheaderpos:=dosheader.e_lfanew;
  1579. { skip to headerpos and skip pe magic }
  1580. seek(f,peheaderpos+4);
  1581. blockread(f,peheader,sizeof(tcoffheader));
  1582. blockread(f,peoptheader,sizeof(tcoffpeoptheader));
  1583. { write info }
  1584. Message1(execinfo_x_codesize,tostr(peoptheader.tsize));
  1585. Message1(execinfo_x_initdatasize,tostr(peoptheader.dsize));
  1586. Message1(execinfo_x_uninitdatasize,tostr(peoptheader.bsize));
  1587. { change stack size (PM) }
  1588. { I am not sure that the default value is adequate !! }
  1589. peoptheader.SizeOfStackReserve:=stacksize;
  1590. if SetPEFlagsSetExplicity then
  1591. peoptheader.LoaderFlags:=peflags;
  1592. if ImageBaseSetExplicity then
  1593. peoptheader.ImageBase:=imagebase;
  1594. if MinStackSizeSetExplicity then
  1595. peoptheader.SizeOfStackCommit:=minstacksize;
  1596. if MaxStackSizeSetExplicity then
  1597. peoptheader.SizeOfStackReserve:=maxstacksize;
  1598. { change the header }
  1599. { sub system }
  1600. { gui=2 }
  1601. { cui=3 }
  1602. { wincegui=9 }
  1603. if target_info.system in systems_wince then
  1604. peoptheader.Subsystem:=9
  1605. else
  1606. case apptype of
  1607. app_native :
  1608. peoptheader.Subsystem:=1;
  1609. app_gui :
  1610. peoptheader.Subsystem:=2;
  1611. app_cui :
  1612. peoptheader.Subsystem:=3;
  1613. else
  1614. ;
  1615. end;
  1616. if dllversion<>'' then
  1617. begin
  1618. peoptheader.MajorImageVersion:=dllmajor;
  1619. peoptheader.MinorImageVersion:=dllminor;
  1620. end;
  1621. { reset timestamp }
  1622. peheader.time:=0;
  1623. { write header back, skip pe magic }
  1624. seek(f,peheaderpos+4);
  1625. blockwrite(f,peheader,sizeof(tcoffheader));
  1626. if ioresult<>0 then
  1627. Message1(execinfo_f_cant_process_executable,fn);
  1628. blockwrite(f,peoptheader,sizeof(tcoffpeoptheader));
  1629. if ioresult<>0 then
  1630. Message1(execinfo_f_cant_process_executable,fn);
  1631. { skip to headerpos and skip pe magic }
  1632. seek(f,peheaderpos+4);
  1633. blockread(f,peheader,sizeof(tcoffheader));
  1634. blockread(f,peoptheader,sizeof(tcoffpeoptheader));
  1635. { write the value after the change }
  1636. Message1(execinfo_x_stackreserve,tostr(peoptheader.SizeOfStackReserve));
  1637. Message1(execinfo_x_stackcommit,tostr(peoptheader.SizeOfStackCommit));
  1638. { read section info }
  1639. maxfillsize:=0;
  1640. firstsecpos:=0;
  1641. secroot:=nil;
  1642. for l:=1 to peheader.nsects do
  1643. begin
  1644. blockread(f,coffsec,sizeof(tcoffsechdr));
  1645. if coffsec.datapos>0 then
  1646. begin
  1647. if secroot=nil then
  1648. firstsecpos:=coffsec.datapos;
  1649. new(hsecroot);
  1650. hsecroot^.fillpos:=coffsec.datapos+coffsec.vsize;
  1651. hsecroot^.fillsize:=coffsec.datasize-coffsec.vsize;
  1652. hsecroot^.next:=secroot;
  1653. secroot:=hsecroot;
  1654. if secroot^.fillsize>maxfillsize then
  1655. maxfillsize:=secroot^.fillsize;
  1656. end;
  1657. end;
  1658. if firstsecpos>0 then
  1659. begin
  1660. l:=firstsecpos-filepos(f);
  1661. if l>maxfillsize then
  1662. maxfillsize:=l;
  1663. end
  1664. else
  1665. l:=0;
  1666. { get zero buffer }
  1667. getmem(zerobuf,maxfillsize);
  1668. fillchar(zerobuf^,maxfillsize,0);
  1669. { zero from sectioninfo until first section }
  1670. blockwrite(f,zerobuf^,l);
  1671. { zero section alignments }
  1672. while assigned(secroot) do
  1673. begin
  1674. seek(f,secroot^.fillpos);
  1675. blockwrite(f,zerobuf^,secroot^.fillsize);
  1676. hsecroot:=secroot;
  1677. secroot:=secroot^.next;
  1678. dispose(hsecroot);
  1679. end;
  1680. freemem(zerobuf,maxfillsize);
  1681. close(f);
  1682. {$pop}
  1683. if ioresult<>0 then;
  1684. postprocessexecutable:=true;
  1685. end;
  1686. procedure TExternalLinkerWin.InitSysInitUnitName;
  1687. begin
  1688. GlobalInitSysInitUnitName(self);
  1689. end;
  1690. {****************************************************************************
  1691. TDLLScannerWin
  1692. ****************************************************************************}
  1693. procedure TDLLScannerWin.CheckDLLFunc(const dllname,funcname:string);
  1694. var
  1695. i : longint;
  1696. ExtName : string;
  1697. begin
  1698. for i:=0 to current_module.dllscannerinputlist.count-1 do
  1699. begin
  1700. ExtName:=current_module.dllscannerinputlist.NameOfIndex(i);
  1701. if (ExtName=funcname) then
  1702. begin
  1703. current_module.AddExternalImport(dllname,funcname,funcname,0,false,false);
  1704. importfound:=true;
  1705. current_module.dllscannerinputlist.Delete(i);
  1706. exit;
  1707. end;
  1708. end;
  1709. end;
  1710. function TDLLScannerWin.scan(const binname:string):boolean;
  1711. var
  1712. hs,
  1713. dllname : TCmdStr;
  1714. begin
  1715. result:=false;
  1716. { is there already an import library the we will use that one }
  1717. if FindLibraryFile(binname,target_info.staticClibprefix,target_info.staticClibext,hs) then
  1718. exit;
  1719. { check if we can find the dll }
  1720. hs:=binname;
  1721. if ExtractFileExt(hs)='' then
  1722. hs:=ChangeFileExt(hs,target_info.sharedlibext);
  1723. if not FindDll(hs,dllname) then
  1724. exit;
  1725. importfound:=false;
  1726. ReadDLLImports(dllname,@CheckDLLFunc);
  1727. if importfound then
  1728. current_module.dllscannerinputlist.Pack;
  1729. result:=importfound;
  1730. end;
  1731. {*****************************************************************************
  1732. Initialize
  1733. *****************************************************************************}
  1734. initialization
  1735. RegisterLinker(ld_int_windows,TInternalLinkerWin);
  1736. RegisterLinker(ld_windows,TExternalLinkerWin);
  1737. {$ifdef i386}
  1738. { Win32 }
  1739. RegisterImport(system_i386_win32,TImportLibWin);
  1740. RegisterExport(system_i386_win32,TExportLibWin);
  1741. RegisterDLLScanner(system_i386_win32,TDLLScannerWin);
  1742. RegisterRes(res_gnu_windres_info,TWinLikeResourceFile);
  1743. RegisterTarget(system_i386_win32_info);
  1744. { WinCE }
  1745. RegisterImport(system_i386_wince,TImportLibWin);
  1746. RegisterExport(system_i386_wince,TExportLibWin);
  1747. RegisterDLLScanner(system_i386_wince,TDLLScannerWin);
  1748. RegisterTarget(system_i386_wince_info);
  1749. {$endif i386}
  1750. {$ifdef x86_64}
  1751. RegisterImport(system_x86_64_win64,TImportLibWin);
  1752. RegisterExport(system_x86_64_win64,TExportLibWin);
  1753. RegisterDLLScanner(system_x86_64_win64,TDLLScannerWin);
  1754. RegisterRes(res_gnu_windres_info,TWinLikeResourceFile);
  1755. RegisterRes(res_win64_gorc_info,TWinLikeResourceFile);
  1756. RegisterTarget(system_x64_win64_info);
  1757. {$endif x86_64}
  1758. {$ifdef arm}
  1759. RegisterImport(system_arm_wince,TImportLibWin);
  1760. RegisterExport(system_arm_wince,TExportLibWin);
  1761. RegisterRes(res_gnu_windres_info,TWinLikeResourceFile);
  1762. RegisterTarget(system_arm_wince_info);
  1763. {$endif arm}
  1764. {$ifdef aarch64}
  1765. RegisterImport(system_aarch64_win64,TImportLibWin);
  1766. RegisterExport(system_aarch64_win64,TExportLibWin);
  1767. RegisterDLLScanner(system_aarch64_win64,TDLLScannerWin);
  1768. // ToDo?
  1769. RegisterRes(res_gnu_windres_info,TWinLikeResourceFile);
  1770. RegisterTarget(system_aarch64_win64_info);
  1771. {$endif aarch64}
  1772. end.