t_win.pas 71 KB

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