t_win.pas 69 KB

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