t_win.pas 53 KB

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