t_win.pas 72 KB

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