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