t_win.pas 69 KB

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