t_win.pas 71 KB

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