t_win.pas 72 KB

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