t_win.pas 72 KB

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