t_win.pas 69 KB

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