t_win32.pas 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  1. {
  2. $Id$
  3. Copyright (c) 1998-2002 by Peter Vreman
  4. This unit implements support import,export,link routines
  5. for the (i386) Win32 target
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software
  16. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17. ****************************************************************************
  18. }
  19. unit t_win32;
  20. {$i fpcdefs.inc}
  21. interface
  22. uses
  23. dos,
  24. cutils,cclasses,
  25. aasmbase,aasmtai,aasmcpu,fmodule,globtype,globals,systems,verbose,
  26. symconst,symdef,symsym,
  27. script,gendef,
  28. cpubase,
  29. {$ifdef GDB}
  30. gdb,
  31. {$endif}
  32. import,export,link,cgobj,i_win32;
  33. const
  34. MAX_DEFAULT_EXTENSIONS = 3;
  35. type
  36. tStr4=array[1..MAX_DEFAULT_EXTENSIONS]of string[4];
  37. pStr4=^tStr4;
  38. twin32imported_item = class(timported_item)
  39. procdef : tprocdef;
  40. end;
  41. timportlibwin32=class(timportlib)
  42. private
  43. procedure win32importproc(aprocdef:tprocdef;const func,module : string;index : longint;const name : string);
  44. procedure importvariable_str(const s:string;const name,module:string);
  45. procedure importprocedure_str(const func,module:string;index:longint;const name:string);
  46. public
  47. procedure preparelib(const s:string);override;
  48. procedure importprocedure(aprocdef:tprocdef;const module:string;index:longint;const name:string);override;
  49. procedure importvariable(vs:tglobalvarsym;const name,module:string);override;
  50. procedure generatelib;override;
  51. procedure generatenasmlib;virtual;
  52. procedure generatesmartlib;override;
  53. end;
  54. texportlibwin32=class(texportlib)
  55. st : string;
  56. EList_indexed:tList;
  57. EList_nonindexed:tList;
  58. procedure preparelib(const s:string);override;
  59. procedure exportprocedure(hp : texported_item);override;
  60. procedure exportvar(hp : texported_item);override;
  61. procedure exportfromlist(hp : texported_item);
  62. procedure generatelib;override;
  63. procedure generatenasmlib;virtual;
  64. end;
  65. tlinkerwin32=class(texternallinker)
  66. private
  67. Function WriteResponseFile(isdll:boolean) : Boolean;
  68. Function PostProcessExecutable(const fn:string;isdll:boolean) : Boolean;
  69. public
  70. Constructor Create;override;
  71. Procedure SetDefaultInfo;override;
  72. function MakeExecutable:boolean;override;
  73. function MakeSharedLibrary:boolean;override;
  74. end;
  75. tDLLScannerWin32=class(tDLLScanner)
  76. private
  77. cstring : array[0..127]of char;
  78. function DOSstubOK(var x:cardinal):boolean;
  79. function FindDLL(const s:string;var founddll:string):boolean;
  80. function ExtractDllName(Const Name : string) : string;
  81. public
  82. function isSuitableFileType(x:cardinal):longbool;override;
  83. function GetEdata(HeaderEntry:cardinal):longbool;override;
  84. function Scan(const binname:string):longbool;override;
  85. end;
  86. implementation
  87. uses
  88. cpuinfo,cgutils;
  89. {*****************************************************************************
  90. TIMPORTLIBWIN32
  91. *****************************************************************************}
  92. procedure timportlibwin32.preparelib(const s : string);
  93. begin
  94. if not(assigned(importssection)) then
  95. importssection:=TAAsmoutput.create;
  96. end;
  97. procedure timportlibwin32.win32importproc(aprocdef:tprocdef;const func,module : string;index : longint;const name : string);
  98. var
  99. hp1 : timportlist;
  100. hp2 : twin32imported_item;
  101. hs : string;
  102. begin
  103. { force the current mangledname }
  104. if assigned(aprocdef) then
  105. aprocdef.has_mangledname:=true;
  106. { append extension if required }
  107. hs:=AddExtension(module,target_info.sharedlibext);
  108. { search for the module }
  109. hp1:=timportlist(current_module.imports.first);
  110. while assigned(hp1) do
  111. begin
  112. if hs=hp1.dllname^ then
  113. break;
  114. hp1:=timportlist(hp1.next);
  115. end;
  116. { generate a new item ? }
  117. if not(assigned(hp1)) then
  118. begin
  119. hp1:=timportlist.create(hs);
  120. current_module.imports.concat(hp1);
  121. end;
  122. { search for reuse of old import item }
  123. hp2:=twin32imported_item(hp1.imported_items.first);
  124. while assigned(hp2) do
  125. begin
  126. if hp2.func^=func then
  127. break;
  128. hp2:=twin32imported_item(hp2.next);
  129. end;
  130. if not assigned(hp2) then
  131. begin
  132. hp2:=twin32imported_item.create(func,name,index);
  133. hp2.procdef:=aprocdef;
  134. hp1.imported_items.concat(hp2);
  135. end;
  136. end;
  137. procedure timportlibwin32.importprocedure(aprocdef:tprocdef;const module : string;index : longint;const name : string);
  138. begin
  139. win32importproc(aprocdef,aprocdef.mangledname,module,index,name);
  140. end;
  141. procedure timportlibwin32.importprocedure_str(const func,module : string;index : longint;const name : string);
  142. begin
  143. win32importproc(nil,func,module,index,name);
  144. end;
  145. procedure timportlibwin32.importvariable(vs:tglobalvarsym;const name,module:string);
  146. begin
  147. importvariable_str(vs.mangledname,name,module);
  148. end;
  149. procedure timportlibwin32.importvariable_str(const s:string;const name,module:string);
  150. var
  151. hp1 : timportlist;
  152. hp2 : twin32imported_item;
  153. hs : string;
  154. begin
  155. hs:=AddExtension(module,target_info.sharedlibext);
  156. { search for the module }
  157. hp1:=timportlist(current_module.imports.first);
  158. while assigned(hp1) do
  159. begin
  160. if hs=hp1.dllname^ then
  161. break;
  162. hp1:=timportlist(hp1.next);
  163. end;
  164. { generate a new item ? }
  165. if not(assigned(hp1)) then
  166. begin
  167. hp1:=timportlist.create(hs);
  168. current_module.imports.concat(hp1);
  169. end;
  170. hp2:=twin32imported_item.create_var(s,name);
  171. hp2.procdef:=nil;
  172. hp1.imported_items.concat(hp2);
  173. end;
  174. procedure timportlibwin32.generatenasmlib;
  175. var
  176. hp1 : timportlist;
  177. hp2 : twin32imported_item;
  178. p : pchar;
  179. begin
  180. new_section(importssection,sec_code,'',0);
  181. hp1:=timportlist(current_module.imports.first);
  182. while assigned(hp1) do
  183. begin
  184. hp2:=twin32imported_item(hp1.imported_items.first);
  185. while assigned(hp2) do
  186. begin
  187. if (aktoutputformat in [as_i386_tasm,as_i386_masm]) then
  188. p:=strpnew(#9+'EXTRN '+hp2.func^)
  189. else
  190. p:=strpnew(#9+'EXTERN '+hp2.func^);
  191. importssection.concat(tai_direct.create(p));
  192. p:=strpnew(#9+'import '+hp2.func^+' '+hp1.dllname^+' '+hp2.name^);
  193. importssection.concat(tai_direct.create(p));
  194. hp2:=twin32imported_item(hp2.next);
  195. end;
  196. hp1:=timportlist(hp1.next);
  197. end;
  198. end;
  199. procedure timportlibwin32.generatesmartlib;
  200. var
  201. hp1 : timportlist;
  202. {$ifdef GDB}
  203. importname : string;
  204. mangledstring : string;
  205. suffix : integer;
  206. {$endif GDB}
  207. hp2 : twin32imported_item;
  208. lhead,lname,lcode,
  209. lidata4,lidata5 : tasmlabel;
  210. href : treference;
  211. begin
  212. if (aktoutputformat in [as_i386_masm,as_i386_tasm,as_i386_nasmwin32]) then
  213. begin
  214. generatenasmlib;
  215. exit;
  216. end;
  217. hp1:=timportlist(current_module.imports.first);
  218. while assigned(hp1) do
  219. begin
  220. { Get labels for the sections }
  221. objectlibrary.getdatalabel(lhead);
  222. objectlibrary.getdatalabel(lname);
  223. objectlibrary.getaddrlabel(lidata4);
  224. objectlibrary.getaddrlabel(lidata5);
  225. { create header for this importmodule }
  226. importsSection.concat(Tai_cutobject.Create_begin);
  227. new_section(importsSection,sec_idata2,'',0);
  228. importsSection.concat(Tai_label.Create(lhead));
  229. { pointer to procedure names }
  230. importsSection.concat(Tai_const.Create_rva_sym(lidata4));
  231. { two empty entries follow }
  232. importsSection.concat(Tai_const.Create_32bit(0));
  233. importsSection.concat(Tai_const.Create_32bit(0));
  234. { pointer to dll name }
  235. importsSection.concat(Tai_const.Create_rva_sym(lname));
  236. { pointer to fixups }
  237. importsSection.concat(Tai_const.Create_rva_sym(lidata5));
  238. { first write the name references }
  239. new_section(importsSection,sec_idata4,'',0);
  240. importsSection.concat(Tai_const.Create_32bit(0));
  241. importsSection.concat(Tai_label.Create(lidata4));
  242. { then the addresses and create also the indirect jump }
  243. new_section(importsSection,sec_idata5,'',0);
  244. importsSection.concat(Tai_const.Create_32bit(0));
  245. importsSection.concat(Tai_label.Create(lidata5));
  246. { create procedures }
  247. hp2:=twin32imported_item(hp1.imported_items.first);
  248. while assigned(hp2) do
  249. begin
  250. { insert cuts }
  251. importsSection.concat(Tai_cutobject.Create);
  252. { create indirect jump }
  253. if not hp2.is_var then
  254. begin
  255. objectlibrary.getlabel(lcode);
  256. reference_reset_symbol(href,lcode,0);
  257. { place jump in codesegment, insert a code section in the
  258. imporTSection to reduce the amount of .s files (PFV) }
  259. new_section(importsSection,sec_code,'',0);
  260. {$IfDef GDB}
  261. if (cs_debuginfo in aktmoduleswitches) then
  262. importsSection.concat(Tai_stab_function_name.Create(nil));
  263. {$EndIf GDB}
  264. importsSection.concat(Tai_symbol.Createname_global(hp2.func^,AT_FUNCTION,0));
  265. importsSection.concat(Taicpu.Op_ref(A_JMP,S_NO,href));
  266. importsSection.concat(Tai_align.Create_op(4,$90));
  267. {$IfDef GDB}
  268. if (cs_debuginfo in aktmoduleswitches) and assigned(hp2.procdef) then
  269. begin
  270. mangledstring:=hp2.procdef.mangledname;
  271. hp2.procdef.setmangledname(hp2.func^);
  272. hp2.procdef.concatstabto(importssection);
  273. hp2.procdef.setmangledname(mangledstring);
  274. end;
  275. {$EndIf GDB}
  276. end;
  277. { create head link }
  278. new_section(importsSection,sec_idata7,'',0);
  279. importsSection.concat(Tai_const.Create_rva_sym(lhead));
  280. { fixup }
  281. objectlibrary.getlabel(tasmlabel(hp2.lab));
  282. new_section(importsSection,sec_idata4,'',0);
  283. importsSection.concat(Tai_const.Create_rva_sym(hp2.lab));
  284. { add jump field to imporTSection }
  285. new_section(importsSection,sec_idata5,'',0);
  286. if hp2.is_var then
  287. importsSection.concat(Tai_symbol.Createname_global(hp2.func^,AT_FUNCTION,0))
  288. else
  289. importsSection.concat(Tai_label.Create(lcode));
  290. {$ifdef GDB}
  291. if (cs_debuginfo in aktmoduleswitches) then
  292. begin
  293. if assigned(hp2.name) then
  294. begin
  295. importname:='__imp_'+hp2.name^;
  296. suffix:=0;
  297. while assigned(objectlibrary.getasmsymbol(importname)) do
  298. begin
  299. inc(suffix);
  300. importname:='__imp_'+hp2.name^+'_'+tostr(suffix);
  301. end;
  302. importssection.concat(tai_symbol.createname(importname,AT_FUNCTION,4));
  303. end
  304. else
  305. begin
  306. importname:='__imp_by_ordinal'+tostr(hp2.ordnr);
  307. suffix:=0;
  308. while assigned(objectlibrary.getasmsymbol(importname)) do
  309. begin
  310. inc(suffix);
  311. importname:='__imp_by_ordinal'+tostr(hp2.ordnr)+'_'+tostr(suffix);
  312. end;
  313. importssection.concat(tai_symbol.createname(importname,AT_FUNCTION,4));
  314. end;
  315. end;
  316. {$endif GDB}
  317. if hp2.name^<>'' then
  318. importsSection.concat(Tai_const.Create_rva_sym(hp2.lab))
  319. else
  320. importsSection.concat(Tai_const.Create_32bit(longint($80000000) or longint(hp2.ordnr)));
  321. { finally the import information }
  322. new_section(importsSection,sec_idata6,'',0);
  323. importsSection.concat(Tai_label.Create(hp2.lab));
  324. importsSection.concat(Tai_const.Create_16bit(hp2.ordnr));
  325. importsSection.concat(Tai_string.Create(hp2.name^+#0));
  326. importsSection.concat(Tai_align.Create_op(2,0));
  327. hp2:=twin32imported_item(hp2.next);
  328. end;
  329. { write final section }
  330. importsSection.concat(Tai_cutobject.Create_end);
  331. { end of name references }
  332. new_section(importsSection,sec_idata4,'',0);
  333. importsSection.concat(Tai_const.Create_32bit(0));
  334. { end if addresses }
  335. new_section(importsSection,sec_idata5,'',0);
  336. importsSection.concat(Tai_const.Create_32bit(0));
  337. { dllname }
  338. new_section(importsSection,sec_idata7,'',0);
  339. importsSection.concat(Tai_label.Create(lname));
  340. importsSection.concat(Tai_string.Create(hp1.dllname^+#0));
  341. hp1:=timportlist(hp1.next);
  342. end;
  343. end;
  344. procedure timportlibwin32.generatelib;
  345. var
  346. hp1 : timportlist;
  347. hp2 : twin32imported_item;
  348. l1,l2,l3,l4 : tasmlabel;
  349. {$ifdef GDB}
  350. importname : string;
  351. mangledstring : string;
  352. suffix : integer;
  353. {$endif GDB}
  354. href : treference;
  355. begin
  356. if (aktoutputformat in [as_i386_masm,as_i386_tasm,as_i386_nasmwin32]) then
  357. begin
  358. generatenasmlib;
  359. exit;
  360. end;
  361. hp1:=timportlist(current_module.imports.first);
  362. while assigned(hp1) do
  363. begin
  364. { align codesegment for the jumps }
  365. new_section(importsSection,sec_code,'',sizeof(aint));
  366. { Get labels for the sections }
  367. objectlibrary.getlabel(l1);
  368. objectlibrary.getlabel(l2);
  369. objectlibrary.getlabel(l3);
  370. new_section(importsSection,sec_idata2,'',0);
  371. { pointer to procedure names }
  372. importsSection.concat(Tai_const.Create_rva_sym(l2));
  373. { two empty entries follow }
  374. importsSection.concat(Tai_const.Create_32bit(0));
  375. importsSection.concat(Tai_const.Create_32bit(0));
  376. { pointer to dll name }
  377. importsSection.concat(Tai_const.Create_rva_sym(l1));
  378. { pointer to fixups }
  379. importsSection.concat(Tai_const.Create_rva_sym(l3));
  380. { only create one section for each else it will
  381. create a lot of idata* }
  382. { first write the name references }
  383. new_section(importsSection,sec_idata4,'',0);
  384. importsSection.concat(Tai_label.Create(l2));
  385. hp2:=twin32imported_item(hp1.imported_items.first);
  386. while assigned(hp2) do
  387. begin
  388. objectlibrary.getlabel(tasmlabel(hp2.lab));
  389. if hp2.name^<>'' then
  390. importsSection.concat(Tai_const.Create_rva_sym(hp2.lab))
  391. else
  392. importsSection.concat(Tai_const.Create_32bit(longint($80000000) or hp2.ordnr));
  393. hp2:=twin32imported_item(hp2.next);
  394. end;
  395. { finalize the names ... }
  396. importsSection.concat(Tai_const.Create_32bit(0));
  397. { then the addresses and create also the indirect jump }
  398. new_section(importsSection,sec_idata5,'',0);
  399. importsSection.concat(Tai_label.Create(l3));
  400. hp2:=twin32imported_item(hp1.imported_items.first);
  401. while assigned(hp2) do
  402. begin
  403. if not hp2.is_var then
  404. begin
  405. objectlibrary.getlabel(l4);
  406. { create indirect jump }
  407. reference_reset_symbol(href,l4,0);
  408. { place jump in codesegment }
  409. new_section(importsSection,sec_code,'',0);
  410. {$IfDef GDB}
  411. if (cs_debuginfo in aktmoduleswitches) then
  412. importssection.concat(tai_stab_function_name.create(nil));
  413. {$EndIf GDB}
  414. importsSection.concat(Tai_symbol.Createname_global(hp2.func^,AT_FUNCTION,0));
  415. importsSection.concat(Taicpu.Op_ref(A_JMP,S_NO,href));
  416. importsSection.concat(Tai_align.Create_op(4,$90));
  417. {$IfDef GDB}
  418. if (cs_debuginfo in aktmoduleswitches) and assigned(hp2.procdef) then
  419. begin
  420. mangledstring:=hp2.procdef.mangledname;
  421. hp2.procdef.setmangledname(hp2.func^);
  422. hp2.procdef.concatstabto(importssection);
  423. hp2.procdef.setmangledname(mangledstring);
  424. end;
  425. {$EndIf GDB}
  426. { add jump field to imporTSection }
  427. new_section(importsSection,sec_idata5,'',0);
  428. {$ifdef GDB}
  429. if (cs_debuginfo in aktmoduleswitches) then
  430. begin
  431. if assigned(hp2.name) then
  432. begin
  433. importname:='__imp_'+hp2.name^;
  434. suffix:=0;
  435. while assigned(objectlibrary.getasmsymbol(importname)) do
  436. begin
  437. inc(suffix);
  438. importname:='__imp_'+hp2.name^+'_'+tostr(suffix);
  439. end;
  440. importssection.concat(tai_symbol.createname(importname,AT_FUNCTION,4));
  441. end
  442. else
  443. begin
  444. importname:='__imp_by_ordinal'+tostr(hp2.ordnr);
  445. suffix:=0;
  446. while assigned(objectlibrary.getasmsymbol(importname)) do
  447. begin
  448. inc(suffix);
  449. importname:='__imp_by_ordinal'+tostr(hp2.ordnr)+'_'+tostr(suffix);
  450. end;
  451. importssection.concat(tai_symbol.createname(importname,AT_FUNCTION,4));
  452. end;
  453. end;
  454. {$endif GDB}
  455. importsSection.concat(Tai_label.Create(l4));
  456. end
  457. else
  458. begin
  459. importsSection.concat(Tai_symbol.Createname_global(hp2.func^,AT_DATA,0));
  460. end;
  461. importsSection.concat(Tai_const.Create_rva_sym(hp2.lab));
  462. hp2:=twin32imported_item(hp2.next);
  463. end;
  464. { finalize the addresses }
  465. importsSection.concat(Tai_const.Create_32bit(0));
  466. { finally the import information }
  467. new_section(importsSection,sec_idata6,'',0);
  468. hp2:=twin32imported_item(hp1.imported_items.first);
  469. while assigned(hp2) do
  470. begin
  471. importsSection.concat(Tai_label.Create(hp2.lab));
  472. { the ordinal number }
  473. importsSection.concat(Tai_const.Create_16bit(hp2.ordnr));
  474. importsSection.concat(Tai_string.Create(hp2.name^+#0));
  475. importsSection.concat(Tai_align.Create_op(2,0));
  476. hp2:=twin32imported_item(hp2.next);
  477. end;
  478. { create import dll name }
  479. new_section(importsSection,sec_idata7,'',0);
  480. importsSection.concat(Tai_label.Create(l1));
  481. importsSection.concat(Tai_string.Create(hp1.dllname^+#0));
  482. hp1:=timportlist(hp1.next);
  483. end;
  484. end;
  485. {*****************************************************************************
  486. TEXPORTLIBWIN32
  487. *****************************************************************************}
  488. procedure texportlibwin32.preparelib(const s:string);
  489. begin
  490. if not(assigned(exportssection)) then
  491. exportssection:=TAAsmoutput.create;
  492. EList_indexed:=tList.Create;
  493. EList_nonindexed:=tList.Create;
  494. objectlibrary.getdatalabel(edatalabel);
  495. end;
  496. procedure texportlibwin32.exportvar(hp : texported_item);
  497. begin
  498. { same code used !! PM }
  499. exportprocedure(hp);
  500. end;
  501. var
  502. Gl_DoubleIndex:boolean;
  503. Gl_DoubleIndexValue:longint;
  504. function IdxCompare(Item1, Item2: Pointer): Integer;
  505. var
  506. I1:texported_item absolute Item1;
  507. I2:texported_item absolute Item2;
  508. begin
  509. Result:=I1.index-I2.index;
  510. if(Result=0)and(Item1<>Item2)then
  511. begin
  512. Gl_DoubleIndex:=true;
  513. Gl_DoubleIndexValue:=I1.index;
  514. end;
  515. end;
  516. procedure texportlibwin32.exportprocedure(hp : texported_item);
  517. begin
  518. if ((hp.options and eo_index)<>0)and((hp.index<=0) or (hp.index>$ffff)) then
  519. begin
  520. message1(parser_e_export_invalid_index,tostr(hp.index));
  521. exit;
  522. end;
  523. if hp.options and eo_index=eo_index then
  524. EList_indexed.Add(hp)
  525. else
  526. EList_nonindexed.Add(hp);
  527. end;
  528. procedure texportlibwin32.exportfromlist(hp : texported_item);
  529. //formerly texportlibwin32.exportprocedure
  530. { must be ordered at least for win32 !! }
  531. var
  532. hp2 : texported_item;
  533. begin
  534. hp2:=texported_item(current_module._exports.first);
  535. while assigned(hp2) and
  536. (hp.name^>hp2.name^) do
  537. hp2:=texported_item(hp2.next);
  538. { insert hp there !! }
  539. if hp2=nil then
  540. current_module._exports.concat(hp)
  541. else
  542. begin
  543. if hp2.name^=hp.name^ then
  544. begin
  545. { this is not allowed !! }
  546. message1(parser_e_export_name_double,hp.name^);
  547. exit;
  548. end;
  549. current_module._exports.insertbefore(hp,hp2);
  550. end;
  551. end;
  552. procedure texportlibwin32.generatelib;
  553. var
  554. ordinal_base,ordinal_max,ordinal_min : longint;
  555. current_index : longint;
  556. entries,named_entries : longint;
  557. name_label,dll_name_label,export_address_table : tasmlabel;
  558. export_name_table_pointers,export_ordinal_table : tasmlabel;
  559. hp,hp2 : texported_item;
  560. temtexport : TLinkedList;
  561. address_table,name_table_pointers,
  562. name_table,ordinal_table : TAAsmoutput;
  563. i,autoindex,ni_high : longint;
  564. hole : boolean;
  565. begin
  566. Gl_DoubleIndex:=false;
  567. ELIst_indexed.Sort(@IdxCompare);
  568. if Gl_DoubleIndex then
  569. begin
  570. message1(parser_e_export_ordinal_double,tostr(Gl_DoubleIndexValue));
  571. EList_indexed.Free;
  572. EList_nonindexed.Free;
  573. exit;
  574. end;
  575. autoindex:=1;
  576. while EList_nonindexed.Count>0 do
  577. begin
  578. hole:=(EList_indexed.Count>0)and(texported_item(EList_indexed.Items[0]).index>1);
  579. if not hole then
  580. for i:=autoindex to pred(EList_indexed.Count)do
  581. if texported_item(EList_indexed.Items[i]).index-texported_item(EList_indexed.Items[pred(i)]).index>1 then
  582. begin
  583. autoindex:=succ(texported_item(EList_indexed.Items[pred(i)]).index);
  584. hole:=true;
  585. break;
  586. end;
  587. ni_high:=pred(EList_nonindexed.Count);
  588. if not hole then
  589. begin
  590. autoindex:=succ(EList_indexed.Count);
  591. EList_indexed.Add(EList_nonindexed.Items[ni_high]);
  592. end
  593. else
  594. EList_indexed.Insert(pred(AutoIndex),EList_nonindexed.Items[ni_high]);
  595. EList_nonindexed.Delete(ni_high);
  596. texported_item(EList_indexed.Items[pred(AutoIndex)]).index:=autoindex;
  597. end;
  598. EList_nonindexed.Free;
  599. for i:=0 to pred(EList_indexed.Count)do
  600. exportfromlist(texported_item(EList_indexed.Items[i]));
  601. EList_indexed.Free;
  602. if (aktoutputformat in [as_i386_masm,as_i386_tasm,as_i386_nasmwin32]) then
  603. begin
  604. generatenasmlib;
  605. exit;
  606. end;
  607. hp:=texported_item(current_module._exports.first);
  608. if not assigned(hp) then
  609. exit;
  610. ordinal_max:=0;
  611. ordinal_min:=$7FFFFFFF;
  612. entries:=0;
  613. named_entries:=0;
  614. objectlibrary.getlabel(dll_name_label);
  615. objectlibrary.getlabel(export_address_table);
  616. objectlibrary.getlabel(export_name_table_pointers);
  617. objectlibrary.getlabel(export_ordinal_table);
  618. { count entries }
  619. while assigned(hp) do
  620. begin
  621. inc(entries);
  622. if (hp.index>ordinal_max) then
  623. ordinal_max:=hp.index;
  624. if (hp.index>0) and (hp.index<ordinal_min) then
  625. ordinal_min:=hp.index;
  626. if assigned(hp.name) then
  627. inc(named_entries);
  628. hp:=texported_item(hp.next);
  629. end;
  630. { no support for higher ordinal base yet !! }
  631. ordinal_base:=1;
  632. current_index:=ordinal_base;
  633. { we must also count the holes !! }
  634. entries:=ordinal_max-ordinal_base+1;
  635. new_section(exportsSection,sec_edata,'',0);
  636. { create label to reference from main so smartlink will include
  637. the .edata section }
  638. exportsSection.concat(Tai_symbol.Create_global(edatalabel,0));
  639. { export flags }
  640. exportsSection.concat(Tai_const.Create_32bit(0));
  641. { date/time stamp }
  642. exportsSection.concat(Tai_const.Create_32bit(0));
  643. { major version }
  644. exportsSection.concat(Tai_const.Create_16bit(0));
  645. { minor version }
  646. exportsSection.concat(Tai_const.Create_16bit(0));
  647. { pointer to dll name }
  648. exportsSection.concat(Tai_const.Create_rva_sym(dll_name_label));
  649. { ordinal base normally set to 1 }
  650. exportsSection.concat(Tai_const.Create_32bit(ordinal_base));
  651. { number of entries }
  652. exportsSection.concat(Tai_const.Create_32bit(entries));
  653. { number of named entries }
  654. exportsSection.concat(Tai_const.Create_32bit(named_entries));
  655. { address of export address table }
  656. exportsSection.concat(Tai_const.Create_rva_sym(export_address_table));
  657. { address of name pointer pointers }
  658. exportsSection.concat(Tai_const.Create_rva_sym(export_name_table_pointers));
  659. { address of ordinal number pointers }
  660. exportsSection.concat(Tai_const.Create_rva_sym(export_ordinal_table));
  661. { the name }
  662. exportsSection.concat(Tai_label.Create(dll_name_label));
  663. if st='' then
  664. exportsSection.concat(Tai_string.Create(current_module.modulename^+target_info.sharedlibext+#0))
  665. else
  666. exportsSection.concat(Tai_string.Create(st+target_info.sharedlibext+#0));
  667. { export address table }
  668. address_table:=TAAsmoutput.create;
  669. address_table.concat(Tai_align.Create_op(4,0));
  670. address_table.concat(Tai_label.Create(export_address_table));
  671. name_table_pointers:=TAAsmoutput.create;
  672. name_table_pointers.concat(Tai_align.Create_op(4,0));
  673. name_table_pointers.concat(Tai_label.Create(export_name_table_pointers));
  674. ordinal_table:=TAAsmoutput.create;
  675. ordinal_table.concat(Tai_align.Create_op(4,0));
  676. ordinal_table.concat(Tai_label.Create(export_ordinal_table));
  677. name_table:=TAAsmoutput.Create;
  678. name_table.concat(Tai_align.Create_op(4,0));
  679. { write each address }
  680. hp:=texported_item(current_module._exports.first);
  681. while assigned(hp) do
  682. begin
  683. if (hp.options and eo_name)<>0 then
  684. begin
  685. objectlibrary.getlabel(name_label);
  686. name_table_pointers.concat(Tai_const.Create_rva_sym(name_label));
  687. ordinal_table.concat(Tai_const.Create_16bit(hp.index-ordinal_base));
  688. name_table.concat(Tai_align.Create_op(2,0));
  689. name_table.concat(Tai_label.Create(name_label));
  690. name_table.concat(Tai_string.Create(hp.name^+#0));
  691. end;
  692. hp:=texported_item(hp.next);
  693. end;
  694. { order in increasing ordinal values }
  695. { into temtexport list }
  696. temtexport:=TLinkedList.Create;
  697. hp:=texported_item(current_module._exports.first);
  698. while assigned(hp) do
  699. begin
  700. current_module._exports.remove(hp);
  701. hp2:=texported_item(temtexport.first);
  702. while assigned(hp2) and (hp.index>hp2.index) do
  703. hp2:=texported_item(hp2.next);
  704. if hp2=nil then
  705. temtexport.concat(hp)
  706. else
  707. temtexport.insertbefore(hp,hp2);
  708. hp:=texported_item(current_module._exports.first);;
  709. end;
  710. { write the export adress table }
  711. current_index:=ordinal_base;
  712. hp:=texported_item(temtexport.first);
  713. while assigned(hp) do
  714. begin
  715. { fill missing values }
  716. while current_index<hp.index do
  717. begin
  718. address_table.concat(Tai_const.Create_32bit(0));
  719. inc(current_index);
  720. end;
  721. case hp.sym.typ of
  722. globalvarsym :
  723. address_table.concat(Tai_const.Createname_rva(tglobalvarsym(hp.sym).mangledname));
  724. typedconstsym :
  725. address_table.concat(Tai_const.Createname_rva(ttypedconstsym(hp.sym).mangledname));
  726. procsym :
  727. address_table.concat(Tai_const.Createname_rva(tprocsym(hp.sym).first_procdef.mangledname));
  728. end;
  729. inc(current_index);
  730. hp:=texported_item(hp.next);
  731. end;
  732. exportsSection.concatlist(address_table);
  733. exportsSection.concatlist(name_table_pointers);
  734. exportsSection.concatlist(ordinal_table);
  735. exportsSection.concatlist(name_table);
  736. address_table.Free;
  737. name_table_pointers.free;
  738. ordinal_table.free;
  739. name_table.free;
  740. temtexport.free;
  741. end;
  742. procedure texportlibwin32.generatenasmlib;
  743. var
  744. hp : texported_item;
  745. p : pchar;
  746. s : string;
  747. begin
  748. new_section(exportssection,sec_code,'',0);
  749. hp:=texported_item(current_module._exports.first);
  750. while assigned(hp) do
  751. begin
  752. case hp.sym.typ of
  753. globalvarsym :
  754. s:=tglobalvarsym(hp.sym).mangledname;
  755. typedconstsym :
  756. s:=ttypedconstsym(hp.sym).mangledname;
  757. procsym :
  758. s:=tprocsym(hp.sym).first_procdef.mangledname;
  759. else
  760. s:='';
  761. end;
  762. p:=strpnew(#9+'export '+s+' '+hp.name^+' '+tostr(hp.index));
  763. exportssection.concat(tai_direct.create(p));
  764. hp:=texported_item(hp.next);
  765. end;
  766. end;
  767. {****************************************************************************
  768. TLINKERWIN32
  769. ****************************************************************************}
  770. Constructor TLinkerWin32.Create;
  771. begin
  772. Inherited Create;
  773. { allow duplicated libs (PM) }
  774. SharedLibFiles.doubles:=true;
  775. StaticLibFiles.doubles:=true;
  776. end;
  777. Procedure TLinkerWin32.SetDefaultInfo;
  778. begin
  779. with Info do
  780. begin
  781. ExeCmd[1]:='ld $OPT $STRIP $APPTYPE $IMAGEBASE $RELOC -o $EXE $RES';
  782. DllCmd[1]:='ld $OPT $STRIP --dll $APPTYPE $IMAGEBASE $RELOC -o $EXE $RES';
  783. { ExeCmd[2]:='dlltool --as $ASBIN --dllname $EXE --output-exp exp.$$$ $RELOC $DEF';
  784. use short forms to avoid 128 char limitation problem }
  785. ExeCmd[2]:='dlltool -S $ASBIN -D $EXE -e exp.$$$ $RELOC $DEF';
  786. ExeCmd[3]:='ld $OPT $STRIP $APPTYPE $IMAGEBASE -o $EXE $RES exp.$$$';
  787. { DllCmd[2]:='dlltool --as $ASBIN --dllname $EXE --output-exp exp.$$$ $RELOC $DEF'; }
  788. DllCmd[2]:='dlltool -S $ASBIN -D $EXE -e exp.$$$ $RELOC $DEF';
  789. DllCmd[3]:='ld $OPT $STRIP --dll $APPTYPE $IMAGEBASE -o $EXE $RES exp.$$$';
  790. end;
  791. end;
  792. Function TLinkerWin32.WriteResponseFile(isdll:boolean) : Boolean;
  793. Var
  794. linkres : TLinkRes;
  795. HPath : TStringListItem;
  796. s,s2 : string;
  797. i : integer;
  798. linklibcygwin : boolean;
  799. begin
  800. WriteResponseFile:=False;
  801. linklibcygwin:=(SharedLibFiles.Find('cygwin')<>nil);
  802. { Open link.res file }
  803. LinkRes:=TLinkRes.Create(outputexedir+Info.ResName);
  804. { Write path to search libraries }
  805. HPath:=TStringListItem(current_module.locallibrarysearchpath.First);
  806. while assigned(HPath) do
  807. begin
  808. LinkRes.Add('SEARCH_DIR('+MaybeQuoted(HPath.Str)+')');
  809. HPath:=TStringListItem(HPath.Next);
  810. end;
  811. HPath:=TStringListItem(LibrarySearchPath.First);
  812. while assigned(HPath) do
  813. begin
  814. LinkRes.Add('SEARCH_DIR('+MaybeQuoted(HPath.Str)+')');
  815. HPath:=TStringListItem(HPath.Next);
  816. end;
  817. { add objectfiles, start with prt0 always }
  818. { profiling of shared libraries is currently not supported }
  819. LinkRes.Add('INPUT(');
  820. if isdll then
  821. LinkRes.AddFileName(MaybeQuoted(FindObjectFile('wdllprt0','',false)))
  822. else
  823. if (cs_profile in aktmoduleswitches) then
  824. LinkRes.AddFileName(MaybeQuoted(FindObjectFile('gprt0','',false)))
  825. else
  826. begin
  827. if linklibcygwin then
  828. LinkRes.AddFileName(MaybeQuoted(FindObjectFile('wcygprt0','',false)))
  829. else
  830. LinkRes.AddFileName(MaybeQuoted(FindObjectFile('wprt0','',false)));
  831. end;
  832. while not ObjectFiles.Empty do
  833. begin
  834. s:=ObjectFiles.GetFirst;
  835. if s<>'' then
  836. LinkRes.AddFileName(MaybeQuoted(s));
  837. end;
  838. LinkRes.Add(')');
  839. { Write staticlibraries }
  840. if (not StaticLibFiles.Empty) or (cs_profile in aktmoduleswitches) then
  841. begin
  842. LinkRes.Add('GROUP(');
  843. if (cs_profile in aktmoduleswitches) then
  844. begin
  845. LinkRes.Add('-lgcc');
  846. LinkRes.Add('-lmoldname');
  847. LinkRes.Add('-lmsvcrt');
  848. LinkRes.Add('-lgmon');
  849. LinkRes.Add('-lkernel32');
  850. end;
  851. While not StaticLibFiles.Empty do
  852. begin
  853. S:=StaticLibFiles.GetFirst;
  854. LinkRes.AddFileName(MaybeQuoted(s));
  855. end;
  856. LinkRes.Add(')');
  857. end;
  858. { Write sharedlibraries }
  859. if not SharedLibFiles.Empty then
  860. begin
  861. LinkRes.Add('INPUT(') ;
  862. While not SharedLibFiles.Empty do
  863. begin
  864. S:=SharedLibFiles.GetFirst;
  865. if FindLibraryFile(s,target_info.staticClibprefix,target_info.staticClibext,s2) then
  866. begin
  867. LinkRes.Add(MaybeQuoted(s2));
  868. continue;
  869. end;
  870. if pos(target_info.sharedlibprefix,s)=1 then
  871. s:=copy(s,length(target_info.sharedlibprefix)+1,255);
  872. i:=Pos(target_info.sharedlibext,S);
  873. if i>0 then
  874. Delete(S,i,255);
  875. LinkRes.Add('-l'+s);
  876. end;
  877. LinkRes.Add(')');
  878. end;
  879. { Write and Close response }
  880. linkres.writetodisk;
  881. LinkRes.Free;
  882. WriteResponseFile:=True;
  883. end;
  884. function TLinkerWin32.MakeExecutable:boolean;
  885. var
  886. binstr : String;
  887. cmdstr : TCmdStr;
  888. success : boolean;
  889. cmds,i : longint;
  890. AsBinStr : string[80];
  891. StripStr,
  892. RelocStr,
  893. AppTypeStr,
  894. ImageBaseStr : string[40];
  895. begin
  896. if not(cs_link_extern in aktglobalswitches) then
  897. Message1(exec_i_linking,current_module.exefilename^);
  898. { Create some replacements }
  899. RelocStr:='';
  900. AppTypeStr:='';
  901. ImageBaseStr:='';
  902. StripStr:='';
  903. AsBinStr:=FindUtil(utilsprefix+'as');
  904. if RelocSection then
  905. RelocStr:='--base-file base.$$$';
  906. if apptype=app_gui then
  907. AppTypeStr:='--subsystem windows';
  908. if assigned(DLLImageBase) then
  909. ImageBaseStr:='--image-base=0x'+DLLImageBase^;
  910. if (cs_link_strip in aktglobalswitches) then
  911. StripStr:='-s';
  912. { Write used files and libraries }
  913. WriteResponseFile(false);
  914. { Call linker }
  915. success:=false;
  916. if RelocSection or (not Deffile.empty) then
  917. cmds:=3
  918. else
  919. cmds:=1;
  920. for i:=1 to cmds do
  921. begin
  922. SplitBinCmd(Info.ExeCmd[i],binstr,cmdstr);
  923. if binstr<>'' then
  924. begin
  925. Replace(cmdstr,'$EXE',maybequoted(current_module.exefilename^));
  926. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  927. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  928. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  929. Replace(cmdstr,'$ASBIN',AsbinStr);
  930. Replace(cmdstr,'$RELOC',RelocStr);
  931. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  932. Replace(cmdstr,'$STRIP',StripStr);
  933. if not DefFile.Empty then
  934. begin
  935. DefFile.WriteFile;
  936. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  937. end
  938. else
  939. Replace(cmdstr,'$DEF','');
  940. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  941. if not success then
  942. break;
  943. end;
  944. end;
  945. { Post process }
  946. if success then
  947. success:=PostProcessExecutable(current_module.exefilename^,false);
  948. { Remove ReponseFile }
  949. if (success) and not(cs_link_extern in aktglobalswitches) then
  950. begin
  951. RemoveFile(outputexedir+Info.ResName);
  952. RemoveFile('base.$$$');
  953. RemoveFile('exp.$$$');
  954. RemoveFile('deffile.$$$');
  955. end;
  956. MakeExecutable:=success; { otherwise a recursive call to link method }
  957. end;
  958. Function TLinkerWin32.MakeSharedLibrary:boolean;
  959. var
  960. binstr : String;
  961. cmdstr : TCmdStr;
  962. success : boolean;
  963. cmds,
  964. i : longint;
  965. AsBinStr : string[80];
  966. StripStr,
  967. RelocStr,
  968. AppTypeStr,
  969. ImageBaseStr : string[40];
  970. begin
  971. MakeSharedLibrary:=false;
  972. if not(cs_link_extern in aktglobalswitches) then
  973. Message1(exec_i_linking,current_module.sharedlibfilename^);
  974. { Create some replacements }
  975. RelocStr:='';
  976. AppTypeStr:='';
  977. ImageBaseStr:='';
  978. StripStr:='';
  979. AsBinStr:=FindUtil(utilsprefix+'as');
  980. if RelocSection then
  981. RelocStr:='--base-file base.$$$';
  982. if apptype=app_gui then
  983. AppTypeStr:='--subsystem windows';
  984. if assigned(DLLImageBase) then
  985. ImageBaseStr:='--image-base=0x'+DLLImageBase^;
  986. if (cs_link_strip in aktglobalswitches) then
  987. StripStr:='-s';
  988. { Write used files and libraries }
  989. WriteResponseFile(true);
  990. { Call linker }
  991. success:=false;
  992. if RelocSection or (not Deffile.empty) then
  993. cmds:=3
  994. else
  995. cmds:=1;
  996. for i:=1 to cmds do
  997. begin
  998. SplitBinCmd(Info.DllCmd[i],binstr,cmdstr);
  999. if binstr<>'' then
  1000. begin
  1001. Replace(cmdstr,'$EXE',maybequoted(current_module.sharedlibfilename^));
  1002. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  1003. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  1004. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  1005. Replace(cmdstr,'$ASBIN',AsbinStr);
  1006. Replace(cmdstr,'$RELOC',RelocStr);
  1007. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  1008. Replace(cmdstr,'$STRIP',StripStr);
  1009. if not DefFile.Empty then
  1010. begin
  1011. DefFile.WriteFile;
  1012. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  1013. end
  1014. else
  1015. Replace(cmdstr,'$DEF','');
  1016. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  1017. if not success then
  1018. break;
  1019. end;
  1020. end;
  1021. { Post process }
  1022. if success then
  1023. success:=PostProcessExecutable(current_module.sharedlibfilename^,true);
  1024. { Remove ReponseFile }
  1025. if (success) and not(cs_link_extern in aktglobalswitches) then
  1026. begin
  1027. RemoveFile(outputexedir+Info.ResName);
  1028. RemoveFile('base.$$$');
  1029. RemoveFile('exp.$$$');
  1030. RemoveFile('deffile.$$$');
  1031. end;
  1032. MakeSharedLibrary:=success; { otherwise a recursive call to link method }
  1033. end;
  1034. function tlinkerwin32.postprocessexecutable(const fn : string;isdll:boolean):boolean;
  1035. type
  1036. tdosheader = packed record
  1037. e_magic : word;
  1038. e_cblp : word;
  1039. e_cp : word;
  1040. e_crlc : word;
  1041. e_cparhdr : word;
  1042. e_minalloc : word;
  1043. e_maxalloc : word;
  1044. e_ss : word;
  1045. e_sp : word;
  1046. e_csum : word;
  1047. e_ip : word;
  1048. e_cs : word;
  1049. e_lfarlc : word;
  1050. e_ovno : word;
  1051. e_res : array[0..3] of word;
  1052. e_oemid : word;
  1053. e_oeminfo : word;
  1054. e_res2 : array[0..9] of word;
  1055. e_lfanew : longint;
  1056. end;
  1057. tpeheader = packed record
  1058. PEMagic : array[0..3] of char;
  1059. Machine : word;
  1060. NumberOfSections : word;
  1061. TimeDateStamp : longint;
  1062. PointerToSymbolTable : longint;
  1063. NumberOfSymbols : longint;
  1064. SizeOfOptionalHeader : word;
  1065. Characteristics : word;
  1066. Magic : word;
  1067. MajorLinkerVersion : byte;
  1068. MinorLinkerVersion : byte;
  1069. SizeOfCode : longint;
  1070. SizeOfInitializedData : longint;
  1071. SizeOfUninitializedData : longint;
  1072. AddressOfEntryPoint : longint;
  1073. BaseOfCode : longint;
  1074. BaseOfData : longint;
  1075. ImageBase : longint;
  1076. SectionAlignment : longint;
  1077. FileAlignment : longint;
  1078. MajorOperatingSystemVersion : word;
  1079. MinorOperatingSystemVersion : word;
  1080. MajorImageVersion : word;
  1081. MinorImageVersion : word;
  1082. MajorSubsystemVersion : word;
  1083. MinorSubsystemVersion : word;
  1084. Reserved1 : longint;
  1085. SizeOfImage : longint;
  1086. SizeOfHeaders : longint;
  1087. CheckSum : longint;
  1088. Subsystem : word;
  1089. DllCharacteristics : word;
  1090. SizeOfStackReserve : longint;
  1091. SizeOfStackCommit : longint;
  1092. SizeOfHeapReserve : longint;
  1093. SizeOfHeapCommit : longint;
  1094. LoaderFlags : longint;
  1095. NumberOfRvaAndSizes : longint;
  1096. DataDirectory : array[1..$80] of byte;
  1097. end;
  1098. tcoffsechdr=packed record
  1099. name : array[0..7] of char;
  1100. vsize : longint;
  1101. rvaofs : longint;
  1102. datalen : longint;
  1103. datapos : longint;
  1104. relocpos : longint;
  1105. lineno1 : longint;
  1106. nrelocs : word;
  1107. lineno2 : word;
  1108. flags : longint;
  1109. end;
  1110. psecfill=^TSecfill;
  1111. TSecfill=record
  1112. fillpos,
  1113. fillsize : longint;
  1114. next : psecfill;
  1115. end;
  1116. var
  1117. f : file;
  1118. cmdstr : string;
  1119. dosheader : tdosheader;
  1120. peheader : tpeheader;
  1121. firstsecpos,
  1122. maxfillsize,
  1123. l,peheaderpos : longint;
  1124. coffsec : tcoffsechdr;
  1125. secroot,hsecroot : psecfill;
  1126. zerobuf : pointer;
  1127. begin
  1128. postprocessexecutable:=false;
  1129. { when -s is used or it's a dll then quit }
  1130. if (cs_link_extern in aktglobalswitches) then
  1131. begin
  1132. case apptype of
  1133. app_gui :
  1134. cmdstr:='--subsystem gui';
  1135. app_cui :
  1136. cmdstr:='--subsystem console';
  1137. end;
  1138. if dllversion<>'' then
  1139. cmdstr:=cmdstr+' --version '+dllversion;
  1140. cmdstr:=cmdstr+' --input '+maybequoted(fn);
  1141. cmdstr:=cmdstr+' --stack '+tostr(stacksize);
  1142. DoExec(FindUtil(utilsprefix+'postw32'),cmdstr,false,false);
  1143. postprocessexecutable:=true;
  1144. exit;
  1145. end;
  1146. { open file }
  1147. assign(f,fn);
  1148. {$I-}
  1149. reset(f,1);
  1150. if ioresult<>0 then
  1151. Message1(execinfo_f_cant_open_executable,fn);
  1152. { read headers }
  1153. blockread(f,dosheader,sizeof(tdosheader));
  1154. peheaderpos:=dosheader.e_lfanew;
  1155. seek(f,peheaderpos);
  1156. blockread(f,peheader,sizeof(tpeheader));
  1157. { write info }
  1158. Message1(execinfo_x_codesize,tostr(peheader.SizeOfCode));
  1159. Message1(execinfo_x_initdatasize,tostr(peheader.SizeOfInitializedData));
  1160. Message1(execinfo_x_uninitdatasize,tostr(peheader.SizeOfUninitializedData));
  1161. { change stack size (PM) }
  1162. { I am not sure that the default value is adequate !! }
  1163. peheader.SizeOfStackReserve:=stacksize;
  1164. { change the header }
  1165. { sub system }
  1166. { gui=2 }
  1167. { cui=3 }
  1168. case apptype of
  1169. app_gui :
  1170. peheader.Subsystem:=2;
  1171. app_cui :
  1172. peheader.Subsystem:=3;
  1173. end;
  1174. if dllversion<>'' then
  1175. begin
  1176. peheader.MajorImageVersion:=dllmajor;
  1177. peheader.MinorImageVersion:=dllminor;
  1178. end;
  1179. { reset timestamp }
  1180. peheader.TimeDateStamp:=0;
  1181. { write header back }
  1182. seek(f,peheaderpos);
  1183. blockwrite(f,peheader,sizeof(tpeheader));
  1184. if ioresult<>0 then
  1185. Message1(execinfo_f_cant_process_executable,fn);
  1186. seek(f,peheaderpos);
  1187. blockread(f,peheader,sizeof(tpeheader));
  1188. { write the value after the change }
  1189. Message1(execinfo_x_stackreserve,tostr(peheader.SizeOfStackReserve));
  1190. Message1(execinfo_x_stackcommit,tostr(peheader.SizeOfStackCommit));
  1191. { read section info }
  1192. maxfillsize:=0;
  1193. firstsecpos:=0;
  1194. secroot:=nil;
  1195. for l:=1 to peheader.NumberOfSections do
  1196. begin
  1197. blockread(f,coffsec,sizeof(tcoffsechdr));
  1198. if coffsec.datapos>0 then
  1199. begin
  1200. if secroot=nil then
  1201. firstsecpos:=coffsec.datapos;
  1202. new(hsecroot);
  1203. hsecroot^.fillpos:=coffsec.datapos+coffsec.vsize;
  1204. hsecroot^.fillsize:=coffsec.datalen-coffsec.vsize;
  1205. hsecroot^.next:=secroot;
  1206. secroot:=hsecroot;
  1207. if secroot^.fillsize>maxfillsize then
  1208. maxfillsize:=secroot^.fillsize;
  1209. end;
  1210. end;
  1211. if firstsecpos>0 then
  1212. begin
  1213. l:=firstsecpos-filepos(f);
  1214. if l>maxfillsize then
  1215. maxfillsize:=l;
  1216. end
  1217. else
  1218. l:=0;
  1219. { get zero buffer }
  1220. getmem(zerobuf,maxfillsize);
  1221. fillchar(zerobuf^,maxfillsize,0);
  1222. { zero from sectioninfo until first section }
  1223. blockwrite(f,zerobuf^,l);
  1224. { zero section alignments }
  1225. while assigned(secroot) do
  1226. begin
  1227. seek(f,secroot^.fillpos);
  1228. blockwrite(f,zerobuf^,secroot^.fillsize);
  1229. hsecroot:=secroot;
  1230. secroot:=secroot^.next;
  1231. dispose(hsecroot);
  1232. end;
  1233. freemem(zerobuf,maxfillsize);
  1234. close(f);
  1235. {$I+}
  1236. if ioresult<>0 then;
  1237. postprocessexecutable:=true;
  1238. end;
  1239. {****************************************************************************
  1240. TDLLScannerWin32
  1241. ****************************************************************************}
  1242. function tDLLScannerWin32.DOSstubOK(var x:cardinal):boolean;
  1243. begin
  1244. blockread(f,TheWord,2,loaded);
  1245. if loaded<>2 then
  1246. DOSstubOK:=false
  1247. else
  1248. begin
  1249. DOSstubOK:=(TheWord='MZ');
  1250. seek(f,$3C);
  1251. blockread(f,x,4,loaded);
  1252. if(loaded<>4)or(longint(x)>filesize(f))then
  1253. DOSstubOK:=false;
  1254. end;
  1255. end;
  1256. function TDLLScannerWin32.FindDLL(const s:string;var founddll:string):boolean;
  1257. var
  1258. sysdir : string;
  1259. Found : boolean;
  1260. begin
  1261. Found:=false;
  1262. { Look for DLL in:
  1263. 1. Current dir
  1264. 2. Library Path
  1265. 3. windir,windir/system,windir/system32 }
  1266. Found:=FindFile(s,'.'+source_info.DirSep,founddll);
  1267. if (not found) then
  1268. Found:=librarysearchpath.FindFile(s,founddll);
  1269. if (not found) then
  1270. begin
  1271. sysdir:=FixPath(GetEnv('windir'),false);
  1272. Found:=FindFile(s,sysdir+';'+sysdir+'system'+source_info.DirSep+';'+sysdir+'system32'+source_info.DirSep,founddll);
  1273. end;
  1274. if (not found) then
  1275. begin
  1276. message1(exec_w_libfile_not_found,s);
  1277. FoundDll:=s;
  1278. end;
  1279. FindDll:=Found;
  1280. end;
  1281. function tDLLScannerWin32.ExtractDllName(Const Name : string) : string;
  1282. var n : string;
  1283. begin
  1284. n:=Upper(SplitExtension(Name));
  1285. if (n='.DLL') or (n='.DRV') or (n='.EXE') then
  1286. ExtractDllName:=Name
  1287. else
  1288. ExtractDllName:=Name+target_info.sharedlibext;
  1289. end;
  1290. function tDLLScannerWin32.isSuitableFileType(x:cardinal):longbool;
  1291. begin
  1292. seek(f,x);
  1293. blockread(f,TheWord,2,loaded);
  1294. isSuitableFileType:=(loaded=2)and(TheWord='PE');
  1295. end;
  1296. function tDLLScannerWin32.GetEdata(HeaderEntry:cardinal):longbool;
  1297. type
  1298. TObjInfo=packed record
  1299. ObjName:array[0..7]of char;
  1300. VirtSize,
  1301. VirtAddr,
  1302. RawSize,
  1303. RawOffset,
  1304. Reloc,
  1305. LineNum:cardinal;
  1306. RelCount,
  1307. LineCount:word;
  1308. flags:cardinal;
  1309. end;
  1310. var
  1311. i:cardinal;
  1312. ObjOfs:cardinal;
  1313. Obj:TObjInfo;
  1314. APE_obj,APE_Optsize:word;
  1315. ExportRVA:cardinal;
  1316. delta:cardinal;
  1317. const
  1318. IMAGE_SCN_CNT_CODE=$00000020;
  1319. var
  1320. _d:dirstr;
  1321. _n:namestr;
  1322. _e:extstr;
  1323. function isUsedFunction(name:pchar):longbool;
  1324. var
  1325. hp:tExternalsItem;
  1326. begin
  1327. isUsedFunction:=false;
  1328. hp:=tExternalsItem(current_module.Externals.first);
  1329. while assigned(hp)do
  1330. begin
  1331. if(assigned(hp.data))and(not hp.found)then
  1332. if hp.data^=StrPas(name)then
  1333. begin
  1334. isUsedFunction:=true;
  1335. hp.found:=true;
  1336. exit;
  1337. end;
  1338. hp:=tExternalsItem(hp.next);
  1339. end;
  1340. end;
  1341. procedure Store(index:cardinal;name:pchar;isData:longbool);
  1342. begin
  1343. if not isUsedFunction(name)then
  1344. exit;
  1345. if not(current_module.uses_imports) then
  1346. begin
  1347. current_module.uses_imports:=true;
  1348. importlib.preparelib(current_module.modulename^);
  1349. end;
  1350. if IsData then
  1351. timportlibwin32(importlib).importvariable_str(name,_n,name)
  1352. else
  1353. timportlibwin32(importlib).importprocedure_str(name,_n,index,name);
  1354. end;
  1355. procedure ProcessEdata;
  1356. type
  1357. a8=array[0..7]of char;
  1358. function GetSectionName(rva:cardinal;var Flags:cardinal):a8;
  1359. var
  1360. i:cardinal;
  1361. LocObjOfs:cardinal;
  1362. LocObj:TObjInfo;
  1363. begin
  1364. GetSectionName:='';
  1365. Flags:=0;
  1366. LocObjOfs:=APE_OptSize+HeaderOffset+24;
  1367. for i:=1 to APE_obj do
  1368. begin
  1369. seek(f,LocObjOfs);
  1370. blockread(f,LocObj,sizeof(LocObj));
  1371. if(rva>=LocObj.VirtAddr)and(rva<=LocObj.VirtAddr+LocObj.RawSize)then
  1372. begin
  1373. GetSectionName:=a8(LocObj.ObjName);
  1374. Flags:=LocObj.flags;
  1375. end;
  1376. end;
  1377. end;
  1378. var
  1379. j,Fl:cardinal;
  1380. ulongval,procEntry:cardinal;
  1381. Ordinal:word;
  1382. isData:longbool;
  1383. ExpDir:packed record
  1384. flag,
  1385. stamp:cardinal;
  1386. Major,
  1387. Minor:word;
  1388. Name,
  1389. Base,
  1390. NumFuncs,
  1391. NumNames,
  1392. AddrFuncs,
  1393. AddrNames,
  1394. AddrOrds:cardinal;
  1395. end;
  1396. begin
  1397. with Obj do
  1398. begin
  1399. seek(f,RawOffset+delta);
  1400. blockread(f,ExpDir,sizeof(ExpDir));
  1401. fsplit(impname,_d,_n,_e);
  1402. for j:=0 to pred(ExpDir.NumNames)do
  1403. begin
  1404. { Don't know why but this gives serious problems with overflow checking on }
  1405. {$IFOPT Q+}
  1406. {$DEFINE OVERFLOW_CHECK_WAS_ON}
  1407. {$ENDIF}
  1408. {$Q-}
  1409. seek(f,RawOffset-VirtAddr+ExpDir.AddrOrds+j*2);
  1410. blockread(f,Ordinal,2);
  1411. seek(f,RawOffset-VirtAddr+ExpDir.AddrFuncs+cardinal(Ordinal)*4);
  1412. blockread(f,ProcEntry,4);
  1413. seek(f,RawOffset-VirtAddr+ExpDir.AddrNames+j*4);
  1414. blockread(f,ulongval,4);
  1415. seek(f,RawOffset-VirtAddr+ulongval);
  1416. blockread(f,cstring,sizeof(cstring));
  1417. isData:=GetSectionName(procentry,Fl)='';
  1418. {$IFDEF OVERFLOW_CHECK_WAS_ON}
  1419. {$Q+}
  1420. {$ENDIF}
  1421. if not isData then
  1422. isData:=Fl and IMAGE_SCN_CNT_CODE<>IMAGE_SCN_CNT_CODE;
  1423. Store(succ(Ordinal),cstring,isData);
  1424. end;
  1425. end;
  1426. end;
  1427. begin
  1428. GetEdata:=false;
  1429. seek(f,HeaderEntry+120);
  1430. blockread(f,ExportRVA,4);
  1431. seek(f,HeaderEntry+6);
  1432. blockread(f,APE_Obj,2);
  1433. seek(f,HeaderEntry+20);
  1434. blockread(f,APE_OptSize,2);
  1435. ObjOfs:=APE_OptSize+HeaderOffset+24;
  1436. for i:=1 to APE_obj do
  1437. begin
  1438. seek(f,ObjOfs);
  1439. blockread(f,Obj,sizeof(Obj));
  1440. inc(ObjOfs,sizeof(Obj));
  1441. with Obj do
  1442. if(VirtAddr<=ExportRva)and(ExportRva<VirtAddr+VirtSize)then
  1443. begin
  1444. delta:=ExportRva-VirtAddr;
  1445. ProcessEdata;
  1446. GetEdata:=true;
  1447. end;
  1448. end;
  1449. end;
  1450. function tDLLScannerWin32.scan(const binname:string):longbool;
  1451. var
  1452. OldFileMode:longint;
  1453. hs,
  1454. foundimp : string;
  1455. begin
  1456. Scan:=false;
  1457. { is there already an import library the we will use that one }
  1458. if FindLibraryFile(binname,target_info.staticClibprefix,target_info.staticClibext,foundimp) then
  1459. exit;
  1460. { check if we can find the dll }
  1461. hs:=AddExtension(binname,target_info.sharedlibext);
  1462. if not FindDll(hs,impname) then
  1463. exit;
  1464. { read the dll file }
  1465. assign(f,impname);
  1466. OldFileMode:=filemode;
  1467. filemode:=0;
  1468. reset(f,1);
  1469. filemode:=OldFileMode;
  1470. if not DOSstubOK(HeaderOffset)then
  1471. scan:=false
  1472. else if not isSuitableFileType(HeaderOffset)then
  1473. scan:=false
  1474. else
  1475. scan:=GetEdata(HeaderOffset);
  1476. close(f);
  1477. end;
  1478. {*****************************************************************************
  1479. Initialize
  1480. *****************************************************************************}
  1481. initialization
  1482. {$ifdef i386}
  1483. RegisterExternalLinker(system_i386_win32_info,TLinkerWin32);
  1484. RegisterImport(system_i386_win32,TImportLibWin32);
  1485. RegisterExport(system_i386_win32,TExportLibWin32);
  1486. RegisterDLLScanner(system_i386_win32,TDLLScannerWin32);
  1487. RegisterRes(res_gnu_windres_info);
  1488. RegisterTarget(system_i386_win32_info);
  1489. {$endif i386}
  1490. end.
  1491. {
  1492. $Log$
  1493. Revision 1.42 2004-11-08 22:09:59 peter
  1494. * tvarsym splitted
  1495. Revision 1.41 2004/11/04 17:12:52 peter
  1496. linking with cygwin fixed
  1497. Revision 1.40 2004/10/25 15:38:41 peter
  1498. * heap and heapsize removed
  1499. * checkpointer fixes
  1500. Revision 1.39 2004/10/15 09:24:38 mazen
  1501. - remove $IFDEF DELPHI and related code
  1502. - remove $IFDEF FPCPROCVAR and related code
  1503. Revision 1.38 2004/10/14 18:16:17 mazen
  1504. * USE_SYSUTILS merged successfully : cycles with and without defines
  1505. * Need to be optimized in performance
  1506. Revision 1.37 2004/09/22 15:25:14 mazen
  1507. * Fix error committing : previous version must be in branch USE_SYSUTILS
  1508. Revision 1.35 2004/06/20 08:55:32 florian
  1509. * logs truncated
  1510. Revision 1.34 2004/06/18 15:16:46 peter
  1511. * remove obsolete cardinal() typecasts
  1512. Revision 1.33 2004/06/16 20:07:11 florian
  1513. * dwarf branch merged
  1514. Revision 1.32 2004/04/28 18:02:54 peter
  1515. * add TList to cclasses, remove classes dependency from t_win32
  1516. Revision 1.31 2004/04/24 17:32:05 peter
  1517. index number generation for mixed index-nonindexed fixed, patch by Pavel V. Ozerski
  1518. Revision 1.30.2.5 2004/05/03 14:59:58 peter
  1519. * no dlltool needed for win32 linking executables
  1520. }