t_win.pas 72 KB

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