t_win.pas 72 KB

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