t_win.pas 71 KB

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