t_win.pas 71 KB

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