t_win.pas 68 KB

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