2
0

t_win.pas 71 KB

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