2
0

t_win.pas 71 KB

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