t_win.pas 69 KB

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