t_win.pas 69 KB

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