t_win.pas 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780
  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. imagebase:={$ifdef cpu64bitaddr} $100000000 {$else} $400000 {$endif};
  904. end;
  905. Concat('IMAGEBASE $' + hexStr(imagebase, SizeOf(imagebase)*2));
  906. Concat('HEADER');
  907. Concat('EXESECTION .text');
  908. Concat(' SYMBOL __text_start__');
  909. Concat(' OBJSECTION .text*');
  910. Concat(' SYMBOL ___CTOR_LIST__');
  911. Concat(' SYMBOL __CTOR_LIST__');
  912. Concat(' LONG -1');
  913. Concat(' OBJSECTION .ctor*');
  914. Concat(' LONG 0');
  915. Concat(' SYMBOL ___DTOR_LIST__');
  916. Concat(' SYMBOL __DTOR_LIST__');
  917. Concat(' LONG -1');
  918. Concat(' OBJSECTION .dtor*');
  919. Concat(' LONG 0');
  920. Concat(' SYMBOL etext');
  921. Concat('ENDEXESECTION');
  922. Concat('EXESECTION .data');
  923. Concat(' SYMBOL __data_start__');
  924. Concat(' OBJSECTION .data*');
  925. Concat(' OBJSECTION .fpc*');
  926. Concat(' SYMBOL edata');
  927. Concat(' SYMBOL __data_end__');
  928. Concat('ENDEXESECTION');
  929. Concat('EXESECTION .rdata');
  930. Concat(' SYMBOL ___RUNTIME_PSEUDO_RELOC_LIST__');
  931. Concat(' SYMBOL __RUNTIME_PSEUDO_RELOC_LIST__');
  932. Concat(' OBJSECTION .rdata_runtime_pseudo_reloc');
  933. Concat(' SYMBOL ___RUNTIME_PSEUDO_RELOC_LIST_END__');
  934. Concat(' SYMBOL __RUNTIME_PSEUDO_RELOC_LIST_END__');
  935. Concat(' OBJSECTION .rdata*');
  936. Concat(' OBJSECTION .rodata*');
  937. Concat('ENDEXESECTION');
  938. Concat('EXESECTION .pdata');
  939. Concat(' OBJSECTION .pdata');
  940. Concat('ENDEXESECTION');
  941. Concat('EXESECTION .bss');
  942. Concat(' SYMBOL __bss_start__');
  943. Concat(' OBJSECTION .bss*');
  944. Concat(' SYMBOL __bss_end__');
  945. Concat('ENDEXESECTION');
  946. Concat('EXESECTION .idata');
  947. Concat(' OBJSECTION .idata$2*');
  948. Concat(' OBJSECTION .idata$3*');
  949. Concat(' ZEROS 20');
  950. Concat(' OBJSECTION .idata$4*');
  951. Concat(' OBJSECTION .idata$5*');
  952. Concat(' OBJSECTION .idata$6*');
  953. Concat(' OBJSECTION .idata$7*');
  954. Concat('ENDEXESECTION');
  955. secnames:='.edata,.rsrc,.reloc,.gnu_debuglink,'+
  956. '.debug_aranges,.debug_pubnames,.debug_info,.debug_abbrev,.debug_line,.debug_frame,.debug_str,.debug_loc,'+
  957. '.debug_macinfo,.debug_weaknames,.debug_funcnames,.debug_typenames,.debug_varnames,.debug_ranges';
  958. repeat
  959. secname:=gettoken(secnames,',');
  960. if secname='' then
  961. break;
  962. Concat('EXESECTION '+secname);
  963. Concat(' OBJSECTION '+secname+'*');
  964. Concat('ENDEXESECTION');
  965. until false;
  966. { Can't use the generic rules, because that will add also .stabstr to .stab }
  967. Concat('EXESECTION .stab');
  968. Concat(' OBJSECTION .stab');
  969. Concat('ENDEXESECTION');
  970. Concat('EXESECTION .stabstr');
  971. Concat(' OBJSECTION .stabstr');
  972. Concat('ENDEXESECTION');
  973. Concat('STABS');
  974. Concat('SYMBOLS');
  975. end;
  976. end;
  977. procedure TInternalLinkerWin.InitSysInitUnitName;
  978. begin
  979. if target_info.system=system_i386_win32 then
  980. GlobalInitSysInitUnitName(self);
  981. end;
  982. {****************************************************************************
  983. TExternalLinkerWin
  984. ****************************************************************************}
  985. Constructor TExternalLinkerWin.Create;
  986. begin
  987. Inherited Create;
  988. { allow duplicated libs (PM) }
  989. SharedLibFiles.doubles:=true;
  990. StaticLibFiles.doubles:=true;
  991. end;
  992. Procedure TExternalLinkerWin.SetDefaultInfo;
  993. var
  994. targetopts: string;
  995. begin
  996. with Info do
  997. begin
  998. if target_info.system=system_arm_wince then
  999. targetopts:='-m armpe'
  1000. else
  1001. targetopts:='-b pe-i386 -m i386pe';
  1002. ExeCmd[1]:='ld '+targetopts+' $OPT $GCSECTIONS $MAP $STRIP $APPTYPE $ENTRY $IMAGEBASE $RELOC -o $EXE $RES';
  1003. DllCmd[1]:='ld '+targetopts+' $OPT $GCSECTIONS $MAP $STRIP --dll $APPTYPE $ENTRY $IMAGEBASE $RELOC -o $EXE $RES';
  1004. { ExeCmd[2]:='dlltool --as $ASBIN --dllname $EXE --output-exp exp.$$$ $RELOC $DEF';
  1005. use short forms to avoid 128 char limitation problem }
  1006. ExeCmd[2]:='dlltool -S $ASBIN -D $EXE -e exp.$$$ $RELOC $DEF';
  1007. ExeCmd[3]:='ld '+targetopts+' $OPT $STRIP $APPTYPE $ENTRY $IMAGEBASE -o $EXE $RES exp.$$$';
  1008. { DllCmd[2]:='dlltool --as $ASBIN --dllname $EXE --output-exp exp.$$$ $RELOC $DEF'; }
  1009. DllCmd[2]:='dlltool -S $ASBIN -D $EXE -e exp.$$$ $RELOC $DEF';
  1010. DllCmd[3]:='ld '+targetopts+' $OPT $STRIP --dll $APPTYPE $ENTRY $IMAGEBASE -o $EXE $RES exp.$$$';
  1011. end;
  1012. end;
  1013. Function TExternalLinkerWin.WriteResponseFile(isdll:boolean) : Boolean;
  1014. Var
  1015. linkres : TLinkRes;
  1016. HPath : TCmdStrListItem;
  1017. s,s2 : TCmdStr;
  1018. i : integer;
  1019. begin
  1020. WriteResponseFile:=False;
  1021. if (cs_profile in current_settings.moduleswitches) then
  1022. begin
  1023. SharedLibFiles.Concat('gmon');
  1024. SharedLibFiles.Concat('c');
  1025. SharedLibFiles.Concat('gcc');
  1026. SharedLibFiles.Concat('kernel32');
  1027. end;
  1028. { Open link.res file }
  1029. LinkRes:=TLinkres.Create(outputexedir+Info.ResName);
  1030. with linkres do
  1031. begin
  1032. { Write path to search libraries }
  1033. HPath:=TCmdStrListItem(current_module.locallibrarysearchpath.First);
  1034. while assigned(HPath) do
  1035. begin
  1036. Add('SEARCH_DIR('+MaybeQuoted(HPath.Str)+')');
  1037. HPath:=TCmdStrListItem(HPath.Next);
  1038. end;
  1039. HPath:=TCmdStrListItem(LibrarySearchPath.First);
  1040. while assigned(HPath) do
  1041. begin
  1042. Add('SEARCH_DIR('+MaybeQuoted(HPath.Str)+')');
  1043. HPath:=TCmdStrListItem(HPath.Next);
  1044. end;
  1045. { add objectfiles, start with prt0 always }
  1046. { profiling of shared libraries is currently not supported }
  1047. if not ObjectFiles.Empty then
  1048. begin
  1049. Add('INPUT(');
  1050. while not ObjectFiles.Empty do
  1051. begin
  1052. s:=ObjectFiles.GetFirst;
  1053. if s<>'' then
  1054. AddFileName(MaybeQuoted(s));
  1055. end;
  1056. Add(')');
  1057. end;
  1058. { Write staticlibraries }
  1059. if (not StaticLibFiles.Empty) then
  1060. begin
  1061. Add('GROUP(');
  1062. While not StaticLibFiles.Empty do
  1063. begin
  1064. S:=StaticLibFiles.GetFirst;
  1065. AddFileName(MaybeQuoted(s));
  1066. end;
  1067. Add(')');
  1068. end;
  1069. { Write sharedlibraries (=import libraries) }
  1070. if not SharedLibFiles.Empty then
  1071. begin
  1072. Add('INPUT(') ;
  1073. While not SharedLibFiles.Empty do
  1074. begin
  1075. S:=SharedLibFiles.GetFirst;
  1076. if FindLibraryFile(s,target_info.staticClibprefix,target_info.staticClibext,s2) then
  1077. begin
  1078. Add(MaybeQuoted(s2));
  1079. continue;
  1080. end;
  1081. if pos(target_info.sharedlibprefix,s)=1 then
  1082. s:=copy(s,length(target_info.sharedlibprefix)+1,255);
  1083. i:=Pos(target_info.sharedlibext,S);
  1084. if i>0 then
  1085. Delete(S,i,255);
  1086. Add('-l'+s);
  1087. end;
  1088. Add(')');
  1089. end;
  1090. Add('SEARCH_DIR("/usr/i686-pc-cygwin/lib"); SEARCH_DIR("/usr/lib"); SEARCH_DIR("/usr/lib/w32api");');
  1091. Add('OUTPUT_FORMAT(pei-i386)');
  1092. Add('ENTRY(_mainCRTStartup)');
  1093. Add('SECTIONS');
  1094. Add('{');
  1095. Add(' . = SIZEOF_HEADERS;');
  1096. Add(' . = ALIGN(__section_alignment__);');
  1097. Add(' .text __image_base__ + ( __section_alignment__ < 0x1000 ? . : __section_alignment__ ) :');
  1098. Add(' {');
  1099. Add(' *(.init)');
  1100. add(' *(.text .stub .text.* .gnu.linkonce.t.*)');
  1101. Add(' *(SORT(.text$*))');
  1102. Add(' ___CTOR_LIST__ = .; __CTOR_LIST__ = . ;');
  1103. Add(' LONG (-1);*(.ctors); *(.ctor); *(SORT(.ctors.*)); LONG (0);');
  1104. Add(' ___DTOR_LIST__ = .; __DTOR_LIST__ = . ;');
  1105. Add(' LONG (-1); *(.dtors); *(.dtor); *(SORT(.dtors.*)); LONG (0);');
  1106. Add(' *(.fini)');
  1107. Add(' PROVIDE (etext = .);');
  1108. Add(' *(.gcc_except_table)');
  1109. Add(' }');
  1110. Add(' .data BLOCK(__section_alignment__) :');
  1111. Add(' {');
  1112. Add(' __data_start__ = . ;');
  1113. add(' *(.data .data.* .gnu.linkonce.d.* .fpc*)');
  1114. Add(' *(.data2)');
  1115. Add(' *(SORT(.data$*))');
  1116. Add(' __data_end__ = . ;');
  1117. Add(' *(.data_cygwin_nocopy)');
  1118. Add(' }');
  1119. Add(' .rdata BLOCK(__section_alignment__) :');
  1120. Add(' {');
  1121. Add(' *(.rdata)');
  1122. add(' *(.rodata .rodata.* .gnu.linkonce.r.*)');
  1123. Add(' *(SORT(.rdata$*))');
  1124. Add(' *(.eh_frame)');
  1125. Add(' ___RUNTIME_PSEUDO_RELOC_LIST__ = .;');
  1126. Add(' __RUNTIME_PSEUDO_RELOC_LIST__ = .;');
  1127. Add(' *(.rdata_runtime_pseudo_reloc)');
  1128. Add(' ___RUNTIME_PSEUDO_RELOC_LIST_END__ = .;');
  1129. Add(' __RUNTIME_PSEUDO_RELOC_LIST_END__ = .;');
  1130. Add(' }');
  1131. Add(' .pdata BLOCK(__section_alignment__) : { *(.pdata) }');
  1132. Add(' .bss BLOCK(__section_alignment__) :');
  1133. Add(' {');
  1134. Add(' __bss_start__ = . ;');
  1135. Add(' *(.bss .bss.* .gnu.linkonce.b.*)');
  1136. Add(' *(SORT(.bss$*))');
  1137. Add(' *(COMMON)');
  1138. Add(' __bss_end__ = . ;');
  1139. Add(' }');
  1140. Add(' .edata BLOCK(__section_alignment__) : { *(.edata) }');
  1141. Add(' .idata BLOCK(__section_alignment__) :');
  1142. Add(' {');
  1143. Add(' SORT(*)(.idata$2)');
  1144. Add(' SORT(*)(.idata$3)');
  1145. Add(' /* These zeroes mark the end of the import list. */');
  1146. Add(' LONG (0); LONG (0); LONG (0); LONG (0); LONG (0);');
  1147. Add(' SORT(*)(.idata$4)');
  1148. Add(' SORT(*)(.idata$5)');
  1149. Add(' SORT(*)(.idata$6)');
  1150. Add(' SORT(*)(.idata$7)');
  1151. Add(' }');
  1152. Add(' .CRT BLOCK(__section_alignment__) :');
  1153. Add(' {');
  1154. Add(' ___crt_xc_start__ = . ;');
  1155. Add(' *(SORT(.CRT$XC*)) /* C initialization */');
  1156. Add(' ___crt_xc_end__ = . ;');
  1157. Add(' ___crt_xi_start__ = . ;');
  1158. Add(' *(SORT(.CRT$XI*)) /* C++ initialization */');
  1159. Add(' ___crt_xi_end__ = . ;');
  1160. Add(' ___crt_xl_start__ = . ;');
  1161. Add(' *(SORT(.CRT$XL*)) /* TLS callbacks */');
  1162. Add(' /* ___crt_xl_end__ is defined in the TLS Directory support code */');
  1163. Add(' ___crt_xp_start__ = . ;');
  1164. Add(' *(SORT(.CRT$XP*)) /* Pre-termination */');
  1165. Add(' ___crt_xp_end__ = . ;');
  1166. Add(' ___crt_xt_start__ = . ;');
  1167. Add(' *(SORT(.CRT$XT*)) /* Termination */');
  1168. Add(' ___crt_xt_end__ = . ;');
  1169. Add(' }');
  1170. Add(' .tls BLOCK(__section_alignment__) :');
  1171. Add(' {');
  1172. Add(' ___tls_start__ = . ;');
  1173. Add(' *(.tls .tls.*)');
  1174. Add(' *(.tls$)');
  1175. Add(' *(SORT(.tls$*))');
  1176. Add(' ___tls_end__ = . ;');
  1177. Add(' }');
  1178. Add(' .rsrc BLOCK(__section_alignment__) :');
  1179. Add(' {');
  1180. Add(' *(.rsrc)');
  1181. Add(' *(SORT(.rsrc$*))');
  1182. Add(' }');
  1183. Add(' .reloc BLOCK(__section_alignment__) : { *(.reloc) }');
  1184. Add(' .stab BLOCK(__section_alignment__) (NOLOAD) : { *(.stab) }');
  1185. Add(' .stabstr BLOCK(__section_alignment__) (NOLOAD) : { *(.stabstr) }');
  1186. Add(' .debug_aranges BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_aranges) }');
  1187. Add(' .debug_pubnames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_pubnames) }');
  1188. Add(' .debug_info BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_info) *(.gnu.linkonce.wi.*) }');
  1189. Add(' .debug_abbrev BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_abbrev) }');
  1190. Add(' .debug_line BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_line) }');
  1191. Add(' .debug_frame BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_frame) }');
  1192. Add(' .debug_str BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_str) }');
  1193. Add(' .debug_loc BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_loc) }');
  1194. Add(' .debug_macinfo BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_macinfo) }');
  1195. Add(' .debug_weaknames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_weaknames) }');
  1196. Add(' .debug_funcnames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_funcnames) }');
  1197. Add(' .debug_typenames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_typenames) }');
  1198. Add(' .debug_varnames BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_varnames) }');
  1199. Add(' .debug_ranges BLOCK(__section_alignment__) (NOLOAD) : { *(.debug_ranges) }');
  1200. Add('}');
  1201. { Write and Close response }
  1202. writetodisk;
  1203. Free;
  1204. end;
  1205. WriteResponseFile:=True;
  1206. end;
  1207. function TExternalLinkerWin.MakeExecutable:boolean;
  1208. var
  1209. MapStr,
  1210. binstr,
  1211. cmdstr : TCmdStr;
  1212. success : boolean;
  1213. cmds,i : longint;
  1214. AsBinStr : string[80];
  1215. GCSectionsStr,
  1216. StripStr,
  1217. RelocStr,
  1218. AppTypeStr,
  1219. EntryStr,
  1220. ImageBaseStr : string[40];
  1221. begin
  1222. if not(cs_link_nolink in current_settings.globalswitches) then
  1223. Message1(exec_i_linking,current_module.exefilename^);
  1224. { Create some replacements }
  1225. RelocStr:='';
  1226. AppTypeStr:='';
  1227. EntryStr:='';
  1228. ImageBaseStr:='';
  1229. StripStr:='';
  1230. MapStr:='';
  1231. GCSectionsStr:='';
  1232. AsBinStr:=FindUtil(utilsprefix+'as');
  1233. if RelocSection then
  1234. RelocStr:='--base-file base.$$$';
  1235. if create_smartlink_sections then
  1236. GCSectionsStr:='--gc-sections';
  1237. if target_info.system in system_wince then
  1238. AppTypeStr:='--subsystem wince'
  1239. else
  1240. begin
  1241. if apptype=app_gui then
  1242. AppTypeStr:='--subsystem windows';
  1243. end;
  1244. if apptype=app_gui then
  1245. EntryStr:='--entry=_WinMainCRTStartup'
  1246. else
  1247. EntryStr:='--entry=_mainCRTStartup';
  1248. if ImageBaseSetExplicity then
  1249. ImageBaseStr:='--image-base=0x'+hexStr(imagebase, SizeOf(imagebase)*2);
  1250. if (cs_link_strip in current_settings.globalswitches) then
  1251. StripStr:='-s';
  1252. if (cs_link_map in current_settings.globalswitches) then
  1253. MapStr:='-Map '+maybequoted(ChangeFileExt(current_module.exefilename^,'.map'));
  1254. { Write used files and libraries }
  1255. WriteResponseFile(false);
  1256. { Call linker }
  1257. success:=false;
  1258. if RelocSection or (not Deffile.empty) then
  1259. cmds:=3
  1260. else
  1261. cmds:=1;
  1262. for i:=1 to cmds do
  1263. begin
  1264. SplitBinCmd(Info.ExeCmd[i],binstr,cmdstr);
  1265. if binstr<>'' then
  1266. begin
  1267. Replace(cmdstr,'$EXE',maybequoted(current_module.exefilename^));
  1268. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  1269. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  1270. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  1271. Replace(cmdstr,'$ENTRY',EntryStr);
  1272. Replace(cmdstr,'$ASBIN',AsbinStr);
  1273. Replace(cmdstr,'$RELOC',RelocStr);
  1274. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  1275. Replace(cmdstr,'$GCSECTIONS',GCSectionsStr);
  1276. Replace(cmdstr,'$STRIP',StripStr);
  1277. Replace(cmdstr,'$MAP',MapStr);
  1278. if not DefFile.Empty then
  1279. begin
  1280. DefFile.WriteFile;
  1281. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  1282. end
  1283. else
  1284. Replace(cmdstr,'$DEF','');
  1285. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  1286. if not success then
  1287. break;
  1288. end;
  1289. end;
  1290. { Post process }
  1291. if success then
  1292. success:=PostProcessExecutable(current_module.exefilename^,false);
  1293. { Remove ReponseFile }
  1294. if (success) and not(cs_link_nolink in current_settings.globalswitches) then
  1295. begin
  1296. DeleteFile(outputexedir+Info.ResName);
  1297. DeleteFile('base.$$$');
  1298. DeleteFile('exp.$$$');
  1299. DeleteFile('deffile.$$$');
  1300. end;
  1301. MakeExecutable:=success; { otherwise a recursive call to link method }
  1302. end;
  1303. Function TExternalLinkerWin.MakeSharedLibrary:boolean;
  1304. var
  1305. MapStr,
  1306. binstr,
  1307. cmdstr : TCmdStr;
  1308. success : boolean;
  1309. cmds,
  1310. i : longint;
  1311. AsBinStr : string[80];
  1312. StripStr,
  1313. GCSectionsStr,
  1314. RelocStr,
  1315. AppTypeStr,
  1316. EntryStr,
  1317. ImageBaseStr : string[40];
  1318. begin
  1319. MakeSharedLibrary:=false;
  1320. if not(cs_link_nolink in current_settings.globalswitches) then
  1321. Message1(exec_i_linking,current_module.sharedlibfilename^);
  1322. { Create some replacements }
  1323. RelocStr:='';
  1324. AppTypeStr:='';
  1325. EntryStr:='';
  1326. ImageBaseStr:='';
  1327. StripStr:='';
  1328. MapStr:='';
  1329. GCSectionsStr:='';
  1330. AsBinStr:=FindUtil(utilsprefix+'as');
  1331. if RelocSection then
  1332. RelocStr:='--base-file base.$$$';
  1333. if create_smartlink_sections then
  1334. GCSectionsStr:='--gc-sections';
  1335. if apptype=app_gui then
  1336. begin
  1337. AppTypeStr:='--subsystem windows';
  1338. EntryStr:='--entry _DLLWinMainCRTStartup'
  1339. end
  1340. else
  1341. EntryStr:='--entry _DLLMainCRTStartup';
  1342. if ImageBaseSetExplicity then
  1343. ImageBaseStr:='--image-base=0x'+hexStr(imagebase, SizeOf(imagebase)*2);
  1344. if (cs_link_strip in current_settings.globalswitches) then
  1345. StripStr:='-s';
  1346. if (cs_link_map in current_settings.globalswitches) then
  1347. MapStr:='-Map '+maybequoted(ChangeFileExt(current_module.exefilename^,'.map'));
  1348. { Write used files and libraries }
  1349. WriteResponseFile(true);
  1350. { Call linker }
  1351. success:=false;
  1352. if RelocSection or (not Deffile.empty) then
  1353. cmds:=3
  1354. else
  1355. cmds:=1;
  1356. for i:=1 to cmds do
  1357. begin
  1358. SplitBinCmd(Info.DllCmd[i],binstr,cmdstr);
  1359. if binstr<>'' then
  1360. begin
  1361. Replace(cmdstr,'$EXE',maybequoted(current_module.sharedlibfilename^));
  1362. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  1363. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  1364. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  1365. Replace(cmdstr,'$ENTRY',EntryStr);
  1366. Replace(cmdstr,'$ASBIN',AsbinStr);
  1367. Replace(cmdstr,'$RELOC',RelocStr);
  1368. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  1369. Replace(cmdstr,'$STRIP',StripStr);
  1370. Replace(cmdstr,'$GCSECTIONS',GCSectionsStr);
  1371. Replace(cmdstr,'$MAP',MapStr);
  1372. if not DefFile.Empty then
  1373. begin
  1374. DefFile.WriteFile;
  1375. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  1376. end
  1377. else
  1378. Replace(cmdstr,'$DEF','');
  1379. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  1380. if not success then
  1381. break;
  1382. end;
  1383. end;
  1384. { Post process }
  1385. if success then
  1386. success:=PostProcessExecutable(current_module.sharedlibfilename^,true);
  1387. { Remove ReponseFile }
  1388. if (success) and not(cs_link_nolink in current_settings.globalswitches) then
  1389. begin
  1390. DeleteFile(outputexedir+Info.ResName);
  1391. DeleteFile('base.$$$');
  1392. DeleteFile('exp.$$$');
  1393. DeleteFile('deffile.$$$');
  1394. end;
  1395. MakeSharedLibrary:=success; { otherwise a recursive call to link method }
  1396. end;
  1397. function TExternalLinkerWin.postprocessexecutable(const fn : string;isdll:boolean):boolean;
  1398. type
  1399. tdosheader = packed record
  1400. e_magic : word;
  1401. e_cblp : word;
  1402. e_cp : word;
  1403. e_crlc : word;
  1404. e_cparhdr : word;
  1405. e_minalloc : word;
  1406. e_maxalloc : word;
  1407. e_ss : word;
  1408. e_sp : word;
  1409. e_csum : word;
  1410. e_ip : word;
  1411. e_cs : word;
  1412. e_lfarlc : word;
  1413. e_ovno : word;
  1414. e_res : array[0..3] of word;
  1415. e_oemid : word;
  1416. e_oeminfo : word;
  1417. e_res2 : array[0..9] of word;
  1418. e_lfanew : longint;
  1419. end;
  1420. psecfill=^TSecfill;
  1421. TSecfill=record
  1422. fillpos,
  1423. fillsize : longint;
  1424. next : psecfill;
  1425. end;
  1426. var
  1427. f : file;
  1428. cmdstr : string;
  1429. dosheader : tdosheader;
  1430. peheader : tcoffheader;
  1431. peoptheader : tcoffpeoptheader;
  1432. firstsecpos,
  1433. maxfillsize,
  1434. l,peheaderpos : longint;
  1435. coffsec : tcoffsechdr;
  1436. secroot,hsecroot : psecfill;
  1437. zerobuf : pointer;
  1438. begin
  1439. postprocessexecutable:=false;
  1440. { when -s is used or it's a dll then quit }
  1441. if (cs_link_nolink in current_settings.globalswitches) then
  1442. begin
  1443. case apptype of
  1444. app_native :
  1445. cmdstr:='--subsystem native';
  1446. app_gui :
  1447. cmdstr:='--subsystem gui';
  1448. app_cui :
  1449. cmdstr:='--subsystem console';
  1450. end;
  1451. if dllversion<>'' then
  1452. cmdstr:=cmdstr+' --version '+dllversion;
  1453. cmdstr:=cmdstr+' --input '+maybequoted(fn);
  1454. cmdstr:=cmdstr+' --stack '+tostr(stacksize);
  1455. DoExec(FindUtil(utilsprefix+'postw32'),cmdstr,false,false);
  1456. postprocessexecutable:=true;
  1457. exit;
  1458. end;
  1459. { open file }
  1460. assign(f,fn);
  1461. {$I-}
  1462. reset(f,1);
  1463. if ioresult<>0 then
  1464. Message1(execinfo_f_cant_open_executable,fn);
  1465. { read headers }
  1466. blockread(f,dosheader,sizeof(tdosheader));
  1467. peheaderpos:=dosheader.e_lfanew;
  1468. { skip to headerpos and skip pe magic }
  1469. seek(f,peheaderpos+4);
  1470. blockread(f,peheader,sizeof(tcoffheader));
  1471. blockread(f,peoptheader,sizeof(tcoffpeoptheader));
  1472. { write info }
  1473. Message1(execinfo_x_codesize,tostr(peoptheader.tsize));
  1474. Message1(execinfo_x_initdatasize,tostr(peoptheader.dsize));
  1475. Message1(execinfo_x_uninitdatasize,tostr(peoptheader.bsize));
  1476. { change stack size (PM) }
  1477. { I am not sure that the default value is adequate !! }
  1478. peoptheader.SizeOfStackReserve:=stacksize;
  1479. if SetPEFlagsSetExplicity then
  1480. peoptheader.LoaderFlags:=peflags;
  1481. if ImageBaseSetExplicity then
  1482. peoptheader.ImageBase:=imagebase;
  1483. if MinStackSizeSetExplicity then
  1484. peoptheader.SizeOfStackCommit:=minstacksize;
  1485. if MaxStackSizeSetExplicity then
  1486. peoptheader.SizeOfStackReserve:=maxstacksize;
  1487. { change the header }
  1488. { sub system }
  1489. { gui=2 }
  1490. { cui=3 }
  1491. { wincegui=9 }
  1492. if target_info.system in system_wince then
  1493. peoptheader.Subsystem:=9
  1494. else
  1495. case apptype of
  1496. app_native :
  1497. peoptheader.Subsystem:=1;
  1498. app_gui :
  1499. peoptheader.Subsystem:=2;
  1500. app_cui :
  1501. peoptheader.Subsystem:=3;
  1502. end;
  1503. if dllversion<>'' then
  1504. begin
  1505. peoptheader.MajorImageVersion:=dllmajor;
  1506. peoptheader.MinorImageVersion:=dllminor;
  1507. end;
  1508. { reset timestamp }
  1509. peheader.time:=0;
  1510. { write header back, skip pe magic }
  1511. seek(f,peheaderpos+4);
  1512. blockwrite(f,peheader,sizeof(tcoffheader));
  1513. if ioresult<>0 then
  1514. Message1(execinfo_f_cant_process_executable,fn);
  1515. blockwrite(f,peoptheader,sizeof(tcoffpeoptheader));
  1516. if ioresult<>0 then
  1517. Message1(execinfo_f_cant_process_executable,fn);
  1518. { skip to headerpos and skip pe magic }
  1519. seek(f,peheaderpos+4);
  1520. blockread(f,peheader,sizeof(tcoffheader));
  1521. blockread(f,peoptheader,sizeof(tcoffpeoptheader));
  1522. { write the value after the change }
  1523. Message1(execinfo_x_stackreserve,tostr(peoptheader.SizeOfStackReserve));
  1524. Message1(execinfo_x_stackcommit,tostr(peoptheader.SizeOfStackCommit));
  1525. { read section info }
  1526. maxfillsize:=0;
  1527. firstsecpos:=0;
  1528. secroot:=nil;
  1529. for l:=1 to peheader.nsects do
  1530. begin
  1531. blockread(f,coffsec,sizeof(tcoffsechdr));
  1532. if coffsec.datapos>0 then
  1533. begin
  1534. if secroot=nil then
  1535. firstsecpos:=coffsec.datapos;
  1536. new(hsecroot);
  1537. hsecroot^.fillpos:=coffsec.datapos+coffsec.vsize;
  1538. hsecroot^.fillsize:=coffsec.datasize-coffsec.vsize;
  1539. hsecroot^.next:=secroot;
  1540. secroot:=hsecroot;
  1541. if secroot^.fillsize>maxfillsize then
  1542. maxfillsize:=secroot^.fillsize;
  1543. end;
  1544. end;
  1545. if firstsecpos>0 then
  1546. begin
  1547. l:=firstsecpos-filepos(f);
  1548. if l>maxfillsize then
  1549. maxfillsize:=l;
  1550. end
  1551. else
  1552. l:=0;
  1553. { get zero buffer }
  1554. getmem(zerobuf,maxfillsize);
  1555. fillchar(zerobuf^,maxfillsize,0);
  1556. { zero from sectioninfo until first section }
  1557. blockwrite(f,zerobuf^,l);
  1558. { zero section alignments }
  1559. while assigned(secroot) do
  1560. begin
  1561. seek(f,secroot^.fillpos);
  1562. blockwrite(f,zerobuf^,secroot^.fillsize);
  1563. hsecroot:=secroot;
  1564. secroot:=secroot^.next;
  1565. dispose(hsecroot);
  1566. end;
  1567. freemem(zerobuf,maxfillsize);
  1568. close(f);
  1569. {$I+}
  1570. if ioresult<>0 then;
  1571. postprocessexecutable:=true;
  1572. end;
  1573. procedure TExternalLinkerWin.InitSysInitUnitName;
  1574. begin
  1575. if target_info.system=system_i386_win32 then
  1576. GlobalInitSysInitUnitName(self);
  1577. end;
  1578. {****************************************************************************
  1579. TDLLScannerWin
  1580. ****************************************************************************}
  1581. procedure TDLLScannerWin.CheckDLLFunc(const dllname,funcname:string);
  1582. var
  1583. i : longint;
  1584. ExtName : string;
  1585. begin
  1586. for i:=0 to current_module.dllscannerinputlist.count-1 do
  1587. begin
  1588. ExtName:=current_module.dllscannerinputlist.NameOfIndex(i);
  1589. if (ExtName=funcname) then
  1590. begin
  1591. current_module.AddExternalImport(dllname,funcname,0,false,false);
  1592. importfound:=true;
  1593. current_module.dllscannerinputlist.Delete(i);
  1594. exit;
  1595. end;
  1596. end;
  1597. end;
  1598. function TDLLScannerWin.scan(const binname:string):boolean;
  1599. var
  1600. hs,
  1601. dllname : TCmdStr;
  1602. begin
  1603. result:=false;
  1604. { is there already an import library the we will use that one }
  1605. if FindLibraryFile(binname,target_info.staticClibprefix,target_info.staticClibext,hs) then
  1606. exit;
  1607. { check if we can find the dll }
  1608. hs:=binname;
  1609. if ExtractFileExt(hs)='' then
  1610. hs:=ChangeFileExt(hs,target_info.sharedlibext);
  1611. if not FindDll(hs,dllname) then
  1612. exit;
  1613. importfound:=false;
  1614. ReadDLLImports(dllname,@CheckDLLFunc);
  1615. if importfound then
  1616. current_module.dllscannerinputlist.Pack;
  1617. result:=importfound;
  1618. end;
  1619. {*****************************************************************************
  1620. Initialize
  1621. *****************************************************************************}
  1622. initialization
  1623. {$ifdef i386}
  1624. { Win32 }
  1625. RegisterExternalLinker(system_i386_win32_info,TExternalLinkerWin);
  1626. RegisterInternalLinker(system_i386_win32_info,TInternalLinkerWin);
  1627. RegisterImport(system_i386_win32,TImportLibWin);
  1628. RegisterExport(system_i386_win32,TExportLibWin);
  1629. RegisterDLLScanner(system_i386_win32,TDLLScannerWin);
  1630. RegisterRes(res_gnu_windres_info,TWinLikeResourceFile);
  1631. RegisterTarget(system_i386_win32_info);
  1632. { WinCE }
  1633. RegisterExternalLinker(system_i386_wince_info,TExternalLinkerWin);
  1634. RegisterInternalLinker(system_i386_wince_info,TInternalLinkerWin);
  1635. RegisterImport(system_i386_wince,TImportLibWin);
  1636. RegisterExport(system_i386_wince,TExportLibWin);
  1637. RegisterDLLScanner(system_i386_wince,TDLLScannerWin);
  1638. RegisterTarget(system_i386_wince_info);
  1639. {$endif i386}
  1640. {$ifdef x86_64}
  1641. RegisterInternalLinker(system_x64_win64_info,TInternalLinkerWin);
  1642. RegisterImport(system_x86_64_win64,TImportLibWin);
  1643. RegisterExport(system_x86_64_win64,TExportLibWin);
  1644. RegisterDLLScanner(system_x86_64_win64,TDLLScannerWin);
  1645. RegisterRes(res_win64_gorc_info,TWinLikeResourceFile);
  1646. RegisterTarget(system_x64_win64_info);
  1647. {$endif x86_64}
  1648. {$ifdef arm}
  1649. RegisterExternalLinker(system_arm_wince_info,TExternalLinkerWin);
  1650. RegisterInternalLinker(system_arm_wince_info,TInternalLinkerWin);
  1651. RegisterImport(system_arm_wince,TImportLibWin);
  1652. RegisterExport(system_arm_wince,TExportLibWin);
  1653. RegisterRes(res_gnu_windres_info,TWinLikeResourceFile);
  1654. RegisterTarget(system_arm_wince_info);
  1655. {$endif arm}
  1656. end.