t_win.pas 71 KB

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