t_win.pas 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820
  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. cfileutl,
  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. { symbol known? then get a new name }
  801. if assigned(hp.sym) then
  802. case hp.sym.typ of
  803. staticvarsym :
  804. asmsym:=current_asmdata.RefAsmSymbol(tstaticvarsym(hp.sym).mangledname);
  805. procsym :
  806. asmsym:=current_asmdata.RefAsmSymbol(tprocdef(tprocsym(hp.sym).ProcdefList[0]).mangledname)
  807. else
  808. internalerror(200709272);
  809. end
  810. else
  811. asmsym:=current_asmdata.RefAsmSymbol(hp.name^);
  812. address_table.concat(Tai_const.Create_rva_sym(asmsym));
  813. inc(current_index);
  814. hp:=texported_item(hp.next);
  815. end;
  816. current_asmdata.asmlists[al_exports].concatlist(address_table);
  817. current_asmdata.asmlists[al_exports].concatlist(name_table_pointers);
  818. current_asmdata.asmlists[al_exports].concatlist(ordinal_table);
  819. current_asmdata.asmlists[al_exports].concatlist(name_table);
  820. address_table.Free;
  821. name_table_pointers.free;
  822. ordinal_table.free;
  823. name_table.free;
  824. { the package support needs this data later on
  825. to create the import library }
  826. current_module._exports.concatlist(temtexport);
  827. temtexport.free;
  828. end;
  829. procedure TExportLibWin.generatenasmlib;
  830. var
  831. hp : texported_item;
  832. p : pchar;
  833. s : string;
  834. begin
  835. new_section(current_asmdata.asmlists[al_exports],sec_code,'',0);
  836. hp:=texported_item(current_module._exports.first);
  837. while assigned(hp) do
  838. begin
  839. case hp.sym.typ of
  840. staticvarsym :
  841. s:=tstaticvarsym(hp.sym).mangledname;
  842. procsym :
  843. s:=tprocdef(tprocsym(hp.sym).ProcdefList[0]).mangledname;
  844. else
  845. s:='';
  846. end;
  847. p:=strpnew(#9+'export '+s+' '+hp.Name^+' '+tostr(hp.index));
  848. {current_asmdata.asmlists[al_exports].concat(tai_direct.create(p));}
  849. hp:=texported_item(hp.next);
  850. end;
  851. end;
  852. {****************************************************************************
  853. TInternalLinkerWin
  854. ****************************************************************************}
  855. constructor TInternalLinkerWin.Create;
  856. begin
  857. inherited Create;
  858. CExeoutput:=TPECoffexeoutput;
  859. CObjInput:=TPECoffObjInput;
  860. end;
  861. procedure TInternalLinkerWin.DefaultLinkScript;
  862. var
  863. s,s2,
  864. ibase : TCmdStr;
  865. secname,
  866. secnames : string;
  867. begin
  868. with LinkScript do
  869. begin
  870. while not ObjectFiles.Empty do
  871. begin
  872. s:=ObjectFiles.GetFirst;
  873. if s<>'' then
  874. Concat('READOBJECT '+MaybeQuoted(s));
  875. end;
  876. while not StaticLibFiles.Empty do
  877. begin
  878. s:=StaticLibFiles.GetFirst;
  879. if s<>'' then
  880. Concat('READSTATICLIBRARY '+MaybeQuoted(s));
  881. end;
  882. While not SharedLibFiles.Empty do
  883. begin
  884. S:=SharedLibFiles.GetFirst;
  885. if FindLibraryFile(s,target_info.staticClibprefix,target_info.staticClibext,s2) then
  886. Concat('READSTATICLIBRARY '+MaybeQuoted(s2))
  887. else
  888. Comment(V_Error,'Import library not found for '+S);
  889. end;
  890. if IsSharedLibrary then
  891. begin
  892. Concat('ISSHAREDLIBRARY');
  893. if apptype=app_gui then
  894. Concat('ENTRYNAME _DLLWinMainCRTStartup')
  895. else
  896. Concat('ENTRYNAME _DLLMainCRTStartup');
  897. end
  898. else
  899. begin
  900. if apptype=app_gui then
  901. Concat('ENTRYNAME _WinMainCRTStartup')
  902. else
  903. Concat('ENTRYNAME _mainCRTStartup');
  904. end;
  905. ibase:='';
  906. if assigned(DLLImageBase) then
  907. ibase:=DLLImageBase^
  908. else
  909. begin
  910. if IsSharedLibrary then
  911. ibase:='10000000'
  912. else
  913. if target_info.system in [system_arm_wince] then
  914. ibase:='10000'
  915. else
  916. ibase:='400000';
  917. end;
  918. Concat('IMAGEBASE $' + ibase);
  919. Concat('HEADER');
  920. Concat('EXESECTION .text');
  921. Concat(' SYMBOL __text_start__');
  922. Concat(' OBJSECTION .text*');
  923. Concat(' SYMBOL ___CTOR_LIST__');
  924. Concat(' SYMBOL __CTOR_LIST__');
  925. Concat(' LONG -1');
  926. Concat(' OBJSECTION .ctor*');
  927. Concat(' LONG 0');
  928. Concat(' SYMBOL ___DTOR_LIST__');
  929. Concat(' SYMBOL __DTOR_LIST__');
  930. Concat(' LONG -1');
  931. Concat(' OBJSECTION .dtor*');
  932. Concat(' LONG 0');
  933. Concat(' SYMBOL etext');
  934. Concat('ENDEXESECTION');
  935. Concat('EXESECTION .data');
  936. Concat(' SYMBOL __data_start__');
  937. Concat(' OBJSECTION .data*');
  938. Concat(' OBJSECTION .fpc*');
  939. Concat(' SYMBOL edata');
  940. Concat(' SYMBOL __data_end__');
  941. Concat('ENDEXESECTION');
  942. Concat('EXESECTION .rdata');
  943. Concat(' SYMBOL ___RUNTIME_PSEUDO_RELOC_LIST__');
  944. Concat(' SYMBOL __RUNTIME_PSEUDO_RELOC_LIST__');
  945. Concat(' OBJSECTION .rdata_runtime_pseudo_reloc');
  946. Concat(' SYMBOL ___RUNTIME_PSEUDO_RELOC_LIST_END__');
  947. Concat(' SYMBOL __RUNTIME_PSEUDO_RELOC_LIST_END__');
  948. Concat(' OBJSECTION .rdata*');
  949. Concat(' OBJSECTION .rodata*');
  950. Concat('ENDEXESECTION');
  951. Concat('EXESECTION .pdata');
  952. Concat(' OBJSECTION .pdata');
  953. Concat('ENDEXESECTION');
  954. Concat('EXESECTION .bss');
  955. Concat(' SYMBOL __bss_start__');
  956. Concat(' OBJSECTION .bss*');
  957. Concat(' SYMBOL __bss_end__');
  958. Concat('ENDEXESECTION');
  959. Concat('EXESECTION .idata');
  960. Concat(' OBJSECTION .idata$2*');
  961. Concat(' OBJSECTION .idata$3*');
  962. Concat(' ZEROS 20');
  963. Concat(' OBJSECTION .idata$4*');
  964. Concat(' OBJSECTION .idata$5*');
  965. Concat(' OBJSECTION .idata$6*');
  966. Concat(' OBJSECTION .idata$7*');
  967. Concat('ENDEXESECTION');
  968. secnames:='.edata,.rsrc,.reloc,'+
  969. '.debug_aranges,.debug_pubnames,.debug_info,.debug_abbrev,.debug_line,.debug_frame,.debug_str,.debug_loc,'+
  970. '.debug_macinfo,.debug_weaknames,.debug_funcnames,.debug_typenames,.debug_varnames,.debug_ranges';
  971. repeat
  972. secname:=gettoken(secnames,',');
  973. if secname='' then
  974. break;
  975. Concat('EXESECTION '+secname);
  976. Concat(' OBJSECTION '+secname+'*');
  977. Concat('ENDEXESECTION');
  978. until false;
  979. { Can't use the generic rules, because that will add also .stabstr to .stab }
  980. Concat('EXESECTION .stab');
  981. Concat(' OBJSECTION .stab');
  982. Concat('ENDEXESECTION');
  983. Concat('EXESECTION .stabstr');
  984. Concat(' OBJSECTION .stabstr');
  985. Concat('ENDEXESECTION');
  986. Concat('STABS');
  987. Concat('SYMBOLS');
  988. end;
  989. end;
  990. procedure TInternalLinkerWin.InitSysInitUnitName;
  991. begin
  992. if target_info.system=system_i386_win32 then
  993. GlobalInitSysInitUnitName(self);
  994. end;
  995. {****************************************************************************
  996. TExternalLinkerWin
  997. ****************************************************************************}
  998. Constructor TExternalLinkerWin.Create;
  999. begin
  1000. Inherited Create;
  1001. { allow duplicated libs (PM) }
  1002. SharedLibFiles.doubles:=true;
  1003. StaticLibFiles.doubles:=true;
  1004. end;
  1005. Procedure TExternalLinkerWin.SetDefaultInfo;
  1006. var
  1007. targetopts: string;
  1008. begin
  1009. with Info do
  1010. begin
  1011. if target_info.system=system_arm_wince then
  1012. targetopts:='-m armpe'
  1013. else
  1014. targetopts:='-b pe-i386 -m i386pe';
  1015. ExeCmd[1]:='ld '+targetopts+' $OPT $GCSECTIONS $MAP $STRIP $APPTYPE $ENTRY $IMAGEBASE $RELOC -o $EXE $RES';
  1016. DllCmd[1]:='ld '+targetopts+' $OPT $GCSECTIONS $MAP $STRIP --dll $APPTYPE $ENTRY $IMAGEBASE $RELOC -o $EXE $RES';
  1017. { ExeCmd[2]:='dlltool --as $ASBIN --dllname $EXE --output-exp exp.$$$ $RELOC $DEF';
  1018. use short forms to avoid 128 char limitation problem }
  1019. ExeCmd[2]:='dlltool -S $ASBIN -D $EXE -e exp.$$$ $RELOC $DEF';
  1020. ExeCmd[3]:='ld '+targetopts+' $OPT $STRIP $APPTYPE $ENTRY $IMAGEBASE -o $EXE $RES exp.$$$';
  1021. { DllCmd[2]:='dlltool --as $ASBIN --dllname $EXE --output-exp exp.$$$ $RELOC $DEF'; }
  1022. DllCmd[2]:='dlltool -S $ASBIN -D $EXE -e exp.$$$ $RELOC $DEF';
  1023. DllCmd[3]:='ld '+targetopts+' $OPT $STRIP --dll $APPTYPE $ENTRY $IMAGEBASE -o $EXE $RES exp.$$$';
  1024. end;
  1025. end;
  1026. Function TExternalLinkerWin.WriteResponseFile(isdll:boolean) : Boolean;
  1027. Var
  1028. linkres : TLinkRes;
  1029. HPath : TCmdStrListItem;
  1030. s,s2 : TCmdStr;
  1031. i : integer;
  1032. begin
  1033. WriteResponseFile:=False;
  1034. if (cs_profile in current_settings.moduleswitches) then
  1035. begin
  1036. SharedLibFiles.Concat('gmon');
  1037. SharedLibFiles.Concat('c');
  1038. SharedLibFiles.Concat('gcc');
  1039. SharedLibFiles.Concat('kernel32');
  1040. end;
  1041. { Open link.res file }
  1042. LinkRes:=TLinkres.Create(outputexedir+Info.ResName);
  1043. with linkres do
  1044. begin
  1045. { Write path to search libraries }
  1046. HPath:=TCmdStrListItem(current_module.locallibrarysearchpath.First);
  1047. while assigned(HPath) do
  1048. begin
  1049. Add('SEARCH_DIR('+MaybeQuoted(HPath.Str)+')');
  1050. HPath:=TCmdStrListItem(HPath.Next);
  1051. end;
  1052. HPath:=TCmdStrListItem(LibrarySearchPath.First);
  1053. while assigned(HPath) do
  1054. begin
  1055. Add('SEARCH_DIR('+MaybeQuoted(HPath.Str)+')');
  1056. HPath:=TCmdStrListItem(HPath.Next);
  1057. end;
  1058. { add objectfiles, start with prt0 always }
  1059. { profiling of shared libraries is currently not supported }
  1060. if not ObjectFiles.Empty then
  1061. begin
  1062. Add('INPUT(');
  1063. while not ObjectFiles.Empty do
  1064. begin
  1065. s:=ObjectFiles.GetFirst;
  1066. if s<>'' then
  1067. AddFileName(MaybeQuoted(s));
  1068. end;
  1069. Add(')');
  1070. end;
  1071. { Write staticlibraries }
  1072. if (not StaticLibFiles.Empty) then
  1073. begin
  1074. Add('GROUP(');
  1075. While not StaticLibFiles.Empty do
  1076. begin
  1077. S:=StaticLibFiles.GetFirst;
  1078. AddFileName(MaybeQuoted(s));
  1079. end;
  1080. Add(')');
  1081. end;
  1082. { Write sharedlibraries (=import libraries) }
  1083. if not SharedLibFiles.Empty then
  1084. begin
  1085. Add('INPUT(') ;
  1086. While not SharedLibFiles.Empty do
  1087. begin
  1088. S:=SharedLibFiles.GetFirst;
  1089. if FindLibraryFile(s,target_info.staticClibprefix,target_info.staticClibext,s2) then
  1090. begin
  1091. Add(MaybeQuoted(s2));
  1092. continue;
  1093. end;
  1094. if pos(target_info.sharedlibprefix,s)=1 then
  1095. s:=copy(s,length(target_info.sharedlibprefix)+1,255);
  1096. i:=Pos(target_info.sharedlibext,S);
  1097. if i>0 then
  1098. Delete(S,i,255);
  1099. Add('-l'+s);
  1100. end;
  1101. Add(')');
  1102. end;
  1103. Add('SEARCH_DIR("/usr/i686-pc-cygwin/lib"); SEARCH_DIR("/usr/lib"); SEARCH_DIR("/usr/lib/w32api");');
  1104. Add('OUTPUT_FORMAT(pei-i386)');
  1105. Add('ENTRY(_mainCRTStartup)');
  1106. Add('SECTIONS');
  1107. Add('{');
  1108. Add(' . = SIZEOF_HEADERS;');
  1109. Add(' . = ALIGN(__section_alignment__);');
  1110. Add(' .text __image_base__ + ( __section_alignment__ < 0x1000 ? . : __section_alignment__ ) :');
  1111. Add(' {');
  1112. Add(' *(.init)');
  1113. add(' *(.text .stub .text.* .gnu.linkonce.t.*)');
  1114. Add(' *(SORT(.text$*))');
  1115. Add(' ___CTOR_LIST__ = .; __CTOR_LIST__ = . ;');
  1116. Add(' LONG (-1);*(.ctors); *(.ctor); *(SORT(.ctors.*)); LONG (0);');
  1117. Add(' ___DTOR_LIST__ = .; __DTOR_LIST__ = . ;');
  1118. Add(' LONG (-1); *(.dtors); *(.dtor); *(SORT(.dtors.*)); LONG (0);');
  1119. Add(' *(.fini)');
  1120. Add(' PROVIDE (etext = .);');
  1121. Add(' *(.gcc_except_table)');
  1122. Add(' }');
  1123. Add(' .data BLOCK(__section_alignment__) :');
  1124. Add(' {');
  1125. Add(' __data_start__ = . ;');
  1126. add(' *(.data .data.* .gnu.linkonce.d.* .fpc*)');
  1127. Add(' *(.data2)');
  1128. Add(' *(SORT(.data$*))');
  1129. Add(' __data_end__ = . ;');
  1130. Add(' *(.data_cygwin_nocopy)');
  1131. Add(' }');
  1132. Add(' .rdata BLOCK(__section_alignment__) :');
  1133. Add(' {');
  1134. Add(' *(.rdata)');
  1135. add(' *(.rodata .rodata.* .gnu.linkonce.r.*)');
  1136. Add(' *(SORT(.rdata$*))');
  1137. Add(' *(.eh_frame)');
  1138. Add(' ___RUNTIME_PSEUDO_RELOC_LIST__ = .;');
  1139. Add(' __RUNTIME_PSEUDO_RELOC_LIST__ = .;');
  1140. Add(' *(.rdata_runtime_pseudo_reloc)');
  1141. Add(' ___RUNTIME_PSEUDO_RELOC_LIST_END__ = .;');
  1142. Add(' __RUNTIME_PSEUDO_RELOC_LIST_END__ = .;');
  1143. Add(' }');
  1144. Add(' .pdata BLOCK(__section_alignment__) : { *(.pdata) }');
  1145. Add(' .bss BLOCK(__section_alignment__) :');
  1146. Add(' {');
  1147. Add(' __bss_start__ = . ;');
  1148. Add(' *(.bss .bss.* .gnu.linkonce.b.*)');
  1149. Add(' *(SORT(.bss$*))');
  1150. Add(' *(COMMON)');
  1151. Add(' __bss_end__ = . ;');
  1152. Add(' }');
  1153. Add(' .edata BLOCK(__section_alignment__) : { *(.edata) }');
  1154. Add(' .idata BLOCK(__section_alignment__) :');
  1155. Add(' {');
  1156. Add(' SORT(*)(.idata$2)');
  1157. Add(' SORT(*)(.idata$3)');
  1158. Add(' /* These zeroes mark the end of the import list. */');
  1159. Add(' LONG (0); LONG (0); LONG (0); LONG (0); LONG (0);');
  1160. Add(' SORT(*)(.idata$4)');
  1161. Add(' SORT(*)(.idata$5)');
  1162. Add(' SORT(*)(.idata$6)');
  1163. Add(' SORT(*)(.idata$7)');
  1164. Add(' }');
  1165. Add(' .CRT BLOCK(__section_alignment__) :');
  1166. Add(' {');
  1167. Add(' ___crt_xc_start__ = . ;');
  1168. Add(' *(SORT(.CRT$XC*)) /* C initialization */');
  1169. Add(' ___crt_xc_end__ = . ;');
  1170. Add(' ___crt_xi_start__ = . ;');
  1171. Add(' *(SORT(.CRT$XI*)) /* C++ initialization */');
  1172. Add(' ___crt_xi_end__ = . ;');
  1173. Add(' ___crt_xl_start__ = . ;');
  1174. Add(' *(SORT(.CRT$XL*)) /* TLS callbacks */');
  1175. Add(' /* ___crt_xl_end__ is defined in the TLS Directory support code */');
  1176. Add(' ___crt_xp_start__ = . ;');
  1177. Add(' *(SORT(.CRT$XP*)) /* Pre-termination */');
  1178. Add(' ___crt_xp_end__ = . ;');
  1179. Add(' ___crt_xt_start__ = . ;');
  1180. Add(' *(SORT(.CRT$XT*)) /* Termination */');
  1181. Add(' ___crt_xt_end__ = . ;');
  1182. Add(' }');
  1183. Add(' .tls BLOCK(__section_alignment__) :');
  1184. Add(' {');
  1185. Add(' ___tls_start__ = . ;');
  1186. Add(' *(.tls .tls.*)');
  1187. Add(' *(.tls$)');
  1188. Add(' *(SORT(.tls$*))');
  1189. Add(' ___tls_end__ = . ;');
  1190. Add(' }');
  1191. Add(' .rsrc BLOCK(__section_alignment__) :');
  1192. Add(' {');
  1193. Add(' *(.rsrc)');
  1194. Add(' *(SORT(.rsrc$*))');
  1195. Add(' }');
  1196. Add(' .reloc BLOCK(__section_alignment__) : { *(.reloc) }');
  1197. Add(' .stab BLOCK(__section_alignment__) (NOLOAD) : { *(.stab) }');
  1198. Add(' .stabstr BLOCK(__section_alignment__) (NOLOAD) : { *(.stabstr) }');
  1199. Add(' .debug_aranges BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_aranges) }');
  1200. Add(' .debug_pubnames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_pubnames) }');
  1201. Add(' .debug_info BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_info) *(.gnu.linkonce.wi.*) }');
  1202. Add(' .debug_abbrev BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_abbrev) }');
  1203. Add(' .debug_line BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_line) }');
  1204. Add(' .debug_frame BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_frame) }');
  1205. Add(' .debug_str BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_str) }');
  1206. Add(' .debug_loc BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_loc) }');
  1207. Add(' .debug_macinfo BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_macinfo) }');
  1208. Add(' .debug_weaknames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_weaknames) }');
  1209. Add(' .debug_funcnames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_funcnames) }');
  1210. Add(' .debug_typenames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_typenames) }');
  1211. Add(' .debug_varnames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_varnames) }');
  1212. Add(' .debug_ranges BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_ranges) }');
  1213. Add('}');
  1214. { Write and Close response }
  1215. writetodisk;
  1216. Free;
  1217. end;
  1218. WriteResponseFile:=True;
  1219. end;
  1220. function TExternalLinkerWin.MakeExecutable:boolean;
  1221. var
  1222. MapStr,
  1223. binstr,
  1224. cmdstr : TCmdStr;
  1225. success : boolean;
  1226. cmds,i : longint;
  1227. AsBinStr : string[80];
  1228. GCSectionsStr,
  1229. StripStr,
  1230. RelocStr,
  1231. AppTypeStr,
  1232. EntryStr,
  1233. ImageBaseStr : string[40];
  1234. begin
  1235. if not(cs_link_nolink in current_settings.globalswitches) then
  1236. Message1(exec_i_linking,current_module.exefilename^);
  1237. { Create some replacements }
  1238. RelocStr:='';
  1239. AppTypeStr:='';
  1240. EntryStr:='';
  1241. ImageBaseStr:='';
  1242. StripStr:='';
  1243. MapStr:='';
  1244. GCSectionsStr:='';
  1245. AsBinStr:=FindUtil(utilsprefix+'as');
  1246. if RelocSection then
  1247. RelocStr:='--base-file base.$$$';
  1248. if create_smartlink_sections then
  1249. GCSectionsStr:='--gc-sections';
  1250. if target_info.system in [system_arm_wince,system_i386_wince] then
  1251. AppTypeStr:='--subsystem wince'
  1252. else
  1253. begin
  1254. if apptype=app_gui then
  1255. AppTypeStr:='--subsystem windows';
  1256. end;
  1257. if apptype=app_gui then
  1258. EntryStr:='--entry=_WinMainCRTStartup'
  1259. else
  1260. EntryStr:='--entry=_mainCRTStartup';
  1261. if assigned(DLLImageBase) then
  1262. ImageBaseStr:='--image-base=0x'+DLLImageBase^;
  1263. if (cs_link_strip in current_settings.globalswitches) then
  1264. StripStr:='-s';
  1265. if (cs_link_map in current_settings.globalswitches) then
  1266. MapStr:='-Map '+maybequoted(ChangeFileExt(current_module.exefilename^,'.map'));
  1267. { Write used files and libraries }
  1268. WriteResponseFile(false);
  1269. { Call linker }
  1270. success:=false;
  1271. if RelocSection or (not Deffile.empty) then
  1272. cmds:=3
  1273. else
  1274. cmds:=1;
  1275. for i:=1 to cmds do
  1276. begin
  1277. SplitBinCmd(Info.ExeCmd[i],binstr,cmdstr);
  1278. if binstr<>'' then
  1279. begin
  1280. Replace(cmdstr,'$EXE',maybequoted(current_module.exefilename^));
  1281. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  1282. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  1283. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  1284. Replace(cmdstr,'$ENTRY',EntryStr);
  1285. Replace(cmdstr,'$ASBIN',AsbinStr);
  1286. Replace(cmdstr,'$RELOC',RelocStr);
  1287. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  1288. Replace(cmdstr,'$GCSECTIONS',GCSectionsStr);
  1289. Replace(cmdstr,'$STRIP',StripStr);
  1290. Replace(cmdstr,'$MAP',MapStr);
  1291. if not DefFile.Empty then
  1292. begin
  1293. DefFile.WriteFile;
  1294. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  1295. end
  1296. else
  1297. Replace(cmdstr,'$DEF','');
  1298. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  1299. if not success then
  1300. break;
  1301. end;
  1302. end;
  1303. { Post process }
  1304. if success then
  1305. success:=PostProcessExecutable(current_module.exefilename^,false);
  1306. { Remove ReponseFile }
  1307. if (success) and not(cs_link_nolink in current_settings.globalswitches) then
  1308. begin
  1309. DeleteFile(outputexedir+Info.ResName);
  1310. DeleteFile('base.$$$');
  1311. DeleteFile('exp.$$$');
  1312. DeleteFile('deffile.$$$');
  1313. end;
  1314. MakeExecutable:=success; { otherwise a recursive call to link method }
  1315. end;
  1316. Function TExternalLinkerWin.MakeSharedLibrary:boolean;
  1317. var
  1318. MapStr,
  1319. binstr,
  1320. cmdstr : TCmdStr;
  1321. success : boolean;
  1322. cmds,
  1323. i : longint;
  1324. AsBinStr : string[80];
  1325. StripStr,
  1326. GCSectionsStr,
  1327. RelocStr,
  1328. AppTypeStr,
  1329. EntryStr,
  1330. ImageBaseStr : string[40];
  1331. begin
  1332. MakeSharedLibrary:=false;
  1333. if not(cs_link_nolink in current_settings.globalswitches) then
  1334. Message1(exec_i_linking,current_module.sharedlibfilename^);
  1335. { Create some replacements }
  1336. RelocStr:='';
  1337. AppTypeStr:='';
  1338. EntryStr:='';
  1339. ImageBaseStr:='';
  1340. StripStr:='';
  1341. MapStr:='';
  1342. GCSectionsStr:='';
  1343. AsBinStr:=FindUtil(utilsprefix+'as');
  1344. if RelocSection then
  1345. RelocStr:='--base-file base.$$$';
  1346. if create_smartlink_sections then
  1347. GCSectionsStr:='--gc-sections';
  1348. if apptype=app_gui then
  1349. begin
  1350. AppTypeStr:='--subsystem windows';
  1351. EntryStr:='--entry _DLLWinMainCRTStartup'
  1352. end
  1353. else
  1354. EntryStr:='--entry _DLLMainCRTStartup';
  1355. if assigned(DLLImageBase) then
  1356. ImageBaseStr:='--image-base=0x'+DLLImageBase^;
  1357. if (cs_link_strip in current_settings.globalswitches) then
  1358. StripStr:='-s';
  1359. if (cs_link_map in current_settings.globalswitches) then
  1360. MapStr:='-Map '+maybequoted(ChangeFileExt(current_module.exefilename^,'.map'));
  1361. { Write used files and libraries }
  1362. WriteResponseFile(true);
  1363. { Call linker }
  1364. success:=false;
  1365. if RelocSection or (not Deffile.empty) then
  1366. cmds:=3
  1367. else
  1368. cmds:=1;
  1369. for i:=1 to cmds do
  1370. begin
  1371. SplitBinCmd(Info.DllCmd[i],binstr,cmdstr);
  1372. if binstr<>'' then
  1373. begin
  1374. Replace(cmdstr,'$EXE',maybequoted(current_module.sharedlibfilename^));
  1375. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  1376. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  1377. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  1378. Replace(cmdstr,'$ENTRY',EntryStr);
  1379. Replace(cmdstr,'$ASBIN',AsbinStr);
  1380. Replace(cmdstr,'$RELOC',RelocStr);
  1381. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  1382. Replace(cmdstr,'$STRIP',StripStr);
  1383. Replace(cmdstr,'$GCSECTIONS',GCSectionsStr);
  1384. Replace(cmdstr,'$MAP',MapStr);
  1385. if not DefFile.Empty then
  1386. begin
  1387. DefFile.WriteFile;
  1388. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  1389. end
  1390. else
  1391. Replace(cmdstr,'$DEF','');
  1392. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  1393. if not success then
  1394. break;
  1395. end;
  1396. end;
  1397. { Post process }
  1398. if success then
  1399. success:=PostProcessExecutable(current_module.sharedlibfilename^,true);
  1400. { Remove ReponseFile }
  1401. if (success) and not(cs_link_nolink in current_settings.globalswitches) then
  1402. begin
  1403. DeleteFile(outputexedir+Info.ResName);
  1404. DeleteFile('base.$$$');
  1405. DeleteFile('exp.$$$');
  1406. DeleteFile('deffile.$$$');
  1407. end;
  1408. MakeSharedLibrary:=success; { otherwise a recursive call to link method }
  1409. end;
  1410. function TExternalLinkerWin.postprocessexecutable(const fn : string;isdll:boolean):boolean;
  1411. type
  1412. tdosheader = packed record
  1413. e_magic : word;
  1414. e_cblp : word;
  1415. e_cp : word;
  1416. e_crlc : word;
  1417. e_cparhdr : word;
  1418. e_minalloc : word;
  1419. e_maxalloc : word;
  1420. e_ss : word;
  1421. e_sp : word;
  1422. e_csum : word;
  1423. e_ip : word;
  1424. e_cs : word;
  1425. e_lfarlc : word;
  1426. e_ovno : word;
  1427. e_res : array[0..3] of word;
  1428. e_oemid : word;
  1429. e_oeminfo : word;
  1430. e_res2 : array[0..9] of word;
  1431. e_lfanew : longint;
  1432. end;
  1433. psecfill=^TSecfill;
  1434. TSecfill=record
  1435. fillpos,
  1436. fillsize : longint;
  1437. next : psecfill;
  1438. end;
  1439. var
  1440. f : file;
  1441. cmdstr : string;
  1442. dosheader : tdosheader;
  1443. peheader : tcoffheader;
  1444. peoptheader : tcoffpeoptheader;
  1445. firstsecpos,
  1446. maxfillsize,
  1447. l,peheaderpos : longint;
  1448. coffsec : tcoffsechdr;
  1449. secroot,hsecroot : psecfill;
  1450. zerobuf : pointer;
  1451. begin
  1452. postprocessexecutable:=false;
  1453. { when -s is used or it's a dll then quit }
  1454. if (cs_link_nolink in current_settings.globalswitches) then
  1455. begin
  1456. case apptype of
  1457. app_native :
  1458. cmdstr:='--subsystem native';
  1459. app_gui :
  1460. cmdstr:='--subsystem gui';
  1461. app_cui :
  1462. cmdstr:='--subsystem console';
  1463. end;
  1464. if dllversion<>'' then
  1465. cmdstr:=cmdstr+' --version '+dllversion;
  1466. cmdstr:=cmdstr+' --input '+maybequoted(fn);
  1467. cmdstr:=cmdstr+' --stack '+tostr(stacksize);
  1468. DoExec(FindUtil(utilsprefix+'postw32'),cmdstr,false,false);
  1469. postprocessexecutable:=true;
  1470. exit;
  1471. end;
  1472. { open file }
  1473. assign(f,fn);
  1474. {$I-}
  1475. reset(f,1);
  1476. if ioresult<>0 then
  1477. Message1(execinfo_f_cant_open_executable,fn);
  1478. { read headers }
  1479. blockread(f,dosheader,sizeof(tdosheader));
  1480. peheaderpos:=dosheader.e_lfanew;
  1481. { skip to headerpos and skip pe magic }
  1482. seek(f,peheaderpos+4);
  1483. blockread(f,peheader,sizeof(tcoffheader));
  1484. blockread(f,peoptheader,sizeof(tcoffpeoptheader));
  1485. { write info }
  1486. Message1(execinfo_x_codesize,tostr(peoptheader.tsize));
  1487. Message1(execinfo_x_initdatasize,tostr(peoptheader.dsize));
  1488. Message1(execinfo_x_uninitdatasize,tostr(peoptheader.bsize));
  1489. { change stack size (PM) }
  1490. { I am not sure that the default value is adequate !! }
  1491. peoptheader.SizeOfStackReserve:=stacksize;
  1492. if SetPEFlagsSetExplicity then
  1493. peoptheader.LoaderFlags:=peflags;
  1494. if ImageBaseSetExplicity then
  1495. peoptheader.ImageBase:=imagebase;
  1496. if MinStackSizeSetExplicity then
  1497. peoptheader.SizeOfStackCommit:=minstacksize;
  1498. if MaxStackSizeSetExplicity then
  1499. peoptheader.SizeOfStackReserve:=maxstacksize;
  1500. { change the header }
  1501. { sub system }
  1502. { gui=2 }
  1503. { cui=3 }
  1504. { wincegui=9 }
  1505. if target_info.system in [system_arm_wince,system_i386_wince] then
  1506. peoptheader.Subsystem:=9
  1507. else
  1508. case apptype of
  1509. app_native :
  1510. peoptheader.Subsystem:=1;
  1511. app_gui :
  1512. peoptheader.Subsystem:=2;
  1513. app_cui :
  1514. peoptheader.Subsystem:=3;
  1515. end;
  1516. if dllversion<>'' then
  1517. begin
  1518. peoptheader.MajorImageVersion:=dllmajor;
  1519. peoptheader.MinorImageVersion:=dllminor;
  1520. end;
  1521. { reset timestamp }
  1522. peheader.time:=0;
  1523. { write header back, skip pe magic }
  1524. seek(f,peheaderpos+4);
  1525. blockwrite(f,peheader,sizeof(tcoffheader));
  1526. if ioresult<>0 then
  1527. Message1(execinfo_f_cant_process_executable,fn);
  1528. blockwrite(f,peoptheader,sizeof(tcoffpeoptheader));
  1529. if ioresult<>0 then
  1530. Message1(execinfo_f_cant_process_executable,fn);
  1531. { skip to headerpos and skip pe magic }
  1532. seek(f,peheaderpos+4);
  1533. blockread(f,peheader,sizeof(tcoffheader));
  1534. blockread(f,peoptheader,sizeof(tcoffpeoptheader));
  1535. { write the value after the change }
  1536. Message1(execinfo_x_stackreserve,tostr(peoptheader.SizeOfStackReserve));
  1537. Message1(execinfo_x_stackcommit,tostr(peoptheader.SizeOfStackCommit));
  1538. { read section info }
  1539. maxfillsize:=0;
  1540. firstsecpos:=0;
  1541. secroot:=nil;
  1542. for l:=1 to peheader.nsects do
  1543. begin
  1544. blockread(f,coffsec,sizeof(tcoffsechdr));
  1545. if coffsec.datapos>0 then
  1546. begin
  1547. if secroot=nil then
  1548. firstsecpos:=coffsec.datapos;
  1549. new(hsecroot);
  1550. hsecroot^.fillpos:=coffsec.datapos+coffsec.vsize;
  1551. hsecroot^.fillsize:=coffsec.datasize-coffsec.vsize;
  1552. hsecroot^.next:=secroot;
  1553. secroot:=hsecroot;
  1554. if secroot^.fillsize>maxfillsize then
  1555. maxfillsize:=secroot^.fillsize;
  1556. end;
  1557. end;
  1558. if firstsecpos>0 then
  1559. begin
  1560. l:=firstsecpos-filepos(f);
  1561. if l>maxfillsize then
  1562. maxfillsize:=l;
  1563. end
  1564. else
  1565. l:=0;
  1566. { get zero buffer }
  1567. getmem(zerobuf,maxfillsize);
  1568. fillchar(zerobuf^,maxfillsize,0);
  1569. { zero from sectioninfo until first section }
  1570. blockwrite(f,zerobuf^,l);
  1571. { zero section alignments }
  1572. while assigned(secroot) do
  1573. begin
  1574. seek(f,secroot^.fillpos);
  1575. blockwrite(f,zerobuf^,secroot^.fillsize);
  1576. hsecroot:=secroot;
  1577. secroot:=secroot^.next;
  1578. dispose(hsecroot);
  1579. end;
  1580. freemem(zerobuf,maxfillsize);
  1581. close(f);
  1582. {$I+}
  1583. if ioresult<>0 then;
  1584. postprocessexecutable:=true;
  1585. end;
  1586. procedure TExternalLinkerWin.InitSysInitUnitName;
  1587. begin
  1588. if target_info.system=system_i386_win32 then
  1589. GlobalInitSysInitUnitName(self);
  1590. end;
  1591. {****************************************************************************
  1592. TDLLScannerWin
  1593. ****************************************************************************}
  1594. procedure TDLLScannerWin.CheckDLLFunc(const dllname,funcname:string);
  1595. var
  1596. i : longint;
  1597. ExtName : string;
  1598. begin
  1599. for i:=0 to current_module.dllscannerinputlist.count-1 do
  1600. begin
  1601. ExtName:=current_module.dllscannerinputlist.NameOfIndex(i);
  1602. if (ExtName=funcname) then
  1603. begin
  1604. current_module.AddExternalImport(dllname,funcname,0,false,false);
  1605. importfound:=true;
  1606. current_module.dllscannerinputlist.Delete(i);
  1607. exit;
  1608. end;
  1609. end;
  1610. end;
  1611. function TDLLScannerWin.scan(const binname:string):boolean;
  1612. var
  1613. hs,
  1614. dllname : TCmdStr;
  1615. begin
  1616. result:=false;
  1617. { is there already an import library the we will use that one }
  1618. if FindLibraryFile(binname,target_info.staticClibprefix,target_info.staticClibext,hs) then
  1619. exit;
  1620. { check if we can find the dll }
  1621. hs:=binname;
  1622. if ExtractFileExt(hs)='' then
  1623. hs:=ChangeFileExt(hs,target_info.sharedlibext);
  1624. if not FindDll(hs,dllname) then
  1625. exit;
  1626. importfound:=false;
  1627. ReadDLLImports(dllname,@CheckDLLFunc);
  1628. if importfound then
  1629. current_module.dllscannerinputlist.Pack;
  1630. result:=importfound;
  1631. end;
  1632. {****************************************************************************
  1633. TWinResourceFile
  1634. ****************************************************************************}
  1635. procedure TWinResourceFile.PostProcessResourcefile(const s : ansistring);
  1636. {$ifdef arm}
  1637. var
  1638. f : file;
  1639. w : word;
  1640. {$endif arm}
  1641. begin
  1642. {$ifdef arm}
  1643. assign(f,s);
  1644. reset(f,1);
  1645. w:=COFF_MAGIC;
  1646. blockwrite(f,w,2);
  1647. close(f);
  1648. {$endif arm}
  1649. end;
  1650. {*****************************************************************************
  1651. Initialize
  1652. *****************************************************************************}
  1653. initialization
  1654. {$ifdef i386}
  1655. { Win32 }
  1656. RegisterExternalLinker(system_i386_win32_info,TExternalLinkerWin);
  1657. RegisterInternalLinker(system_i386_win32_info,TInternalLinkerWin);
  1658. RegisterImport(system_i386_win32,TImportLibWin);
  1659. RegisterExport(system_i386_win32,TExportLibWin);
  1660. RegisterDLLScanner(system_i386_win32,TDLLScannerWin);
  1661. RegisterRes(res_gnu_windres_info,TWinResourceFile);
  1662. RegisterTarget(system_i386_win32_info);
  1663. { WinCE }
  1664. RegisterExternalLinker(system_i386_wince_info,TExternalLinkerWin);
  1665. RegisterInternalLinker(system_i386_wince_info,TInternalLinkerWin);
  1666. RegisterImport(system_i386_wince,TImportLibWin);
  1667. RegisterExport(system_i386_wince,TExportLibWin);
  1668. RegisterDLLScanner(system_i386_wince,TDLLScannerWin);
  1669. RegisterTarget(system_i386_wince_info);
  1670. {$endif i386}
  1671. {$ifdef x86_64}
  1672. RegisterInternalLinker(system_x64_win64_info,TInternalLinkerWin);
  1673. RegisterImport(system_x86_64_win64,TImportLibWin);
  1674. RegisterExport(system_x86_64_win64,TExportLibWin);
  1675. RegisterDLLScanner(system_x86_64_win64,TDLLScannerWin);
  1676. RegisterRes(res_win64_gorc_info,TWinResourceFile);
  1677. RegisterTarget(system_x64_win64_info);
  1678. {$endif x86_64}
  1679. {$ifdef arm}
  1680. RegisterExternalLinker(system_arm_wince_info,TExternalLinkerWin);
  1681. RegisterInternalLinker(system_arm_wince_info,TInternalLinkerWin);
  1682. RegisterImport(system_arm_wince,TImportLibWin);
  1683. RegisterExport(system_arm_wince,TExportLibWin);
  1684. RegisterRes(res_gnu_wince_windres_info,TWinResourceFile);
  1685. RegisterTarget(system_arm_wince_info);
  1686. {$endif arm}
  1687. end.