t_win.pas 69 KB

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