t_win32.pas 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  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:tvarsym;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:tvarsym;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. varsym :
  723. address_table.concat(Tai_const.Createname_rva(tvarsym(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. varsym :
  754. s:=tvarsym(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. linklibc : boolean;
  799. begin
  800. WriteResponseFile:=False;
  801. linklibc:=false;
  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. LinkRes.AddFileName(MaybeQuoted(FindObjectFile('wprt0','',false)));
  827. while not ObjectFiles.Empty do
  828. begin
  829. s:=ObjectFiles.GetFirst;
  830. if s<>'' then
  831. LinkRes.AddFileName(MaybeQuoted(s));
  832. end;
  833. LinkRes.Add(')');
  834. { Write staticlibraries }
  835. if (not StaticLibFiles.Empty) or (cs_profile in aktmoduleswitches) then
  836. begin
  837. LinkRes.Add('GROUP(');
  838. if (cs_profile in aktmoduleswitches) then
  839. begin
  840. LinkRes.Add('-lgcc');
  841. LinkRes.Add('-lmoldname');
  842. LinkRes.Add('-lmsvcrt');
  843. LinkRes.Add('-lgmon');
  844. LinkRes.Add('-lkernel32');
  845. end;
  846. While not StaticLibFiles.Empty do
  847. begin
  848. S:=StaticLibFiles.GetFirst;
  849. LinkRes.AddFileName(MaybeQuoted(s));
  850. end;
  851. LinkRes.Add(')');
  852. end;
  853. { Write sharedlibraries }
  854. if not SharedLibFiles.Empty then
  855. begin
  856. LinkRes.Add('INPUT(') ;
  857. While not SharedLibFiles.Empty do
  858. begin
  859. S:=SharedLibFiles.GetFirst;
  860. if FindLibraryFile(s,target_info.staticClibprefix,target_info.staticClibext,s2) then
  861. begin
  862. LinkRes.Add(MaybeQuoted(s2));
  863. continue;
  864. end;
  865. if pos(target_info.sharedlibprefix,s)=1 then
  866. s:=copy(s,length(target_info.sharedlibprefix)+1,255);
  867. if s<>'c' then
  868. begin
  869. i:=Pos(target_info.sharedlibext,S);
  870. if i>0 then
  871. Delete(S,i,255);
  872. LinkRes.Add('-l'+s);
  873. end
  874. else
  875. begin
  876. LinkRes.Add('-l'+s);
  877. linklibc:=true;
  878. end;
  879. end;
  880. { be sure that libc is the last lib }
  881. if linklibc then
  882. LinkRes.Add('-lc');
  883. LinkRes.Add(')');
  884. end;
  885. { Write and Close response }
  886. linkres.writetodisk;
  887. LinkRes.Free;
  888. WriteResponseFile:=True;
  889. end;
  890. function TLinkerWin32.MakeExecutable:boolean;
  891. var
  892. binstr : String;
  893. cmdstr : TCmdStr;
  894. success : boolean;
  895. cmds,i : longint;
  896. AsBinStr : string[80];
  897. StripStr,
  898. RelocStr,
  899. AppTypeStr,
  900. ImageBaseStr : string[40];
  901. begin
  902. if not(cs_link_extern in aktglobalswitches) then
  903. Message1(exec_i_linking,current_module.exefilename^);
  904. { Create some replacements }
  905. RelocStr:='';
  906. AppTypeStr:='';
  907. ImageBaseStr:='';
  908. StripStr:='';
  909. AsBinStr:=FindUtil(utilsprefix+'as');
  910. if RelocSection then
  911. RelocStr:='--base-file base.$$$';
  912. if apptype=app_gui then
  913. AppTypeStr:='--subsystem windows';
  914. if assigned(DLLImageBase) then
  915. ImageBaseStr:='--image-base=0x'+DLLImageBase^;
  916. if (cs_link_strip in aktglobalswitches) then
  917. StripStr:='-s';
  918. { Write used files and libraries }
  919. WriteResponseFile(false);
  920. { Call linker }
  921. success:=false;
  922. if RelocSection or (not Deffile.empty) then
  923. cmds:=3
  924. else
  925. cmds:=1;
  926. for i:=1 to cmds do
  927. begin
  928. SplitBinCmd(Info.ExeCmd[i],binstr,cmdstr);
  929. if binstr<>'' then
  930. begin
  931. Replace(cmdstr,'$EXE',maybequoted(current_module.exefilename^));
  932. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  933. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  934. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  935. Replace(cmdstr,'$ASBIN',AsbinStr);
  936. Replace(cmdstr,'$RELOC',RelocStr);
  937. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  938. Replace(cmdstr,'$STRIP',StripStr);
  939. if not DefFile.Empty then
  940. begin
  941. DefFile.WriteFile;
  942. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  943. end
  944. else
  945. Replace(cmdstr,'$DEF','');
  946. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  947. if not success then
  948. break;
  949. end;
  950. end;
  951. { Post process }
  952. if success then
  953. success:=PostProcessExecutable(current_module.exefilename^,false);
  954. { Remove ReponseFile }
  955. if (success) and not(cs_link_extern in aktglobalswitches) then
  956. begin
  957. RemoveFile(outputexedir+Info.ResName);
  958. RemoveFile('base.$$$');
  959. RemoveFile('exp.$$$');
  960. RemoveFile('deffile.$$$');
  961. end;
  962. MakeExecutable:=success; { otherwise a recursive call to link method }
  963. end;
  964. Function TLinkerWin32.MakeSharedLibrary:boolean;
  965. var
  966. binstr : String;
  967. cmdstr : TCmdStr;
  968. success : boolean;
  969. cmds,
  970. i : longint;
  971. AsBinStr : string[80];
  972. StripStr,
  973. RelocStr,
  974. AppTypeStr,
  975. ImageBaseStr : string[40];
  976. begin
  977. MakeSharedLibrary:=false;
  978. if not(cs_link_extern in aktglobalswitches) then
  979. Message1(exec_i_linking,current_module.sharedlibfilename^);
  980. { Create some replacements }
  981. RelocStr:='';
  982. AppTypeStr:='';
  983. ImageBaseStr:='';
  984. StripStr:='';
  985. AsBinStr:=FindUtil(utilsprefix+'as');
  986. if RelocSection then
  987. RelocStr:='--base-file base.$$$';
  988. if apptype=app_gui then
  989. AppTypeStr:='--subsystem windows';
  990. if assigned(DLLImageBase) then
  991. ImageBaseStr:='--image-base=0x'+DLLImageBase^;
  992. if (cs_link_strip in aktglobalswitches) then
  993. StripStr:='-s';
  994. { Write used files and libraries }
  995. WriteResponseFile(true);
  996. { Call linker }
  997. success:=false;
  998. if RelocSection or (not Deffile.empty) then
  999. cmds:=3
  1000. else
  1001. cmds:=1;
  1002. for i:=1 to cmds do
  1003. begin
  1004. SplitBinCmd(Info.DllCmd[i],binstr,cmdstr);
  1005. if binstr<>'' then
  1006. begin
  1007. Replace(cmdstr,'$EXE',maybequoted(current_module.sharedlibfilename^));
  1008. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  1009. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  1010. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  1011. Replace(cmdstr,'$ASBIN',AsbinStr);
  1012. Replace(cmdstr,'$RELOC',RelocStr);
  1013. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  1014. Replace(cmdstr,'$STRIP',StripStr);
  1015. if not DefFile.Empty then
  1016. begin
  1017. DefFile.WriteFile;
  1018. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  1019. end
  1020. else
  1021. Replace(cmdstr,'$DEF','');
  1022. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  1023. if not success then
  1024. break;
  1025. end;
  1026. end;
  1027. { Post process }
  1028. if success then
  1029. success:=PostProcessExecutable(current_module.sharedlibfilename^,true);
  1030. { Remove ReponseFile }
  1031. if (success) and not(cs_link_extern in aktglobalswitches) then
  1032. begin
  1033. RemoveFile(outputexedir+Info.ResName);
  1034. RemoveFile('base.$$$');
  1035. RemoveFile('exp.$$$');
  1036. RemoveFile('deffile.$$$');
  1037. end;
  1038. MakeSharedLibrary:=success; { otherwise a recursive call to link method }
  1039. end;
  1040. function tlinkerwin32.postprocessexecutable(const fn : string;isdll:boolean):boolean;
  1041. type
  1042. tdosheader = packed record
  1043. e_magic : word;
  1044. e_cblp : word;
  1045. e_cp : word;
  1046. e_crlc : word;
  1047. e_cparhdr : word;
  1048. e_minalloc : word;
  1049. e_maxalloc : word;
  1050. e_ss : word;
  1051. e_sp : word;
  1052. e_csum : word;
  1053. e_ip : word;
  1054. e_cs : word;
  1055. e_lfarlc : word;
  1056. e_ovno : word;
  1057. e_res : array[0..3] of word;
  1058. e_oemid : word;
  1059. e_oeminfo : word;
  1060. e_res2 : array[0..9] of word;
  1061. e_lfanew : longint;
  1062. end;
  1063. tpeheader = packed record
  1064. PEMagic : array[0..3] of char;
  1065. Machine : word;
  1066. NumberOfSections : word;
  1067. TimeDateStamp : longint;
  1068. PointerToSymbolTable : longint;
  1069. NumberOfSymbols : longint;
  1070. SizeOfOptionalHeader : word;
  1071. Characteristics : word;
  1072. Magic : word;
  1073. MajorLinkerVersion : byte;
  1074. MinorLinkerVersion : byte;
  1075. SizeOfCode : longint;
  1076. SizeOfInitializedData : longint;
  1077. SizeOfUninitializedData : longint;
  1078. AddressOfEntryPoint : longint;
  1079. BaseOfCode : longint;
  1080. BaseOfData : longint;
  1081. ImageBase : longint;
  1082. SectionAlignment : longint;
  1083. FileAlignment : longint;
  1084. MajorOperatingSystemVersion : word;
  1085. MinorOperatingSystemVersion : word;
  1086. MajorImageVersion : word;
  1087. MinorImageVersion : word;
  1088. MajorSubsystemVersion : word;
  1089. MinorSubsystemVersion : word;
  1090. Reserved1 : longint;
  1091. SizeOfImage : longint;
  1092. SizeOfHeaders : longint;
  1093. CheckSum : longint;
  1094. Subsystem : word;
  1095. DllCharacteristics : word;
  1096. SizeOfStackReserve : longint;
  1097. SizeOfStackCommit : longint;
  1098. SizeOfHeapReserve : longint;
  1099. SizeOfHeapCommit : longint;
  1100. LoaderFlags : longint;
  1101. NumberOfRvaAndSizes : longint;
  1102. DataDirectory : array[1..$80] of byte;
  1103. end;
  1104. tcoffsechdr=packed record
  1105. name : array[0..7] of char;
  1106. vsize : longint;
  1107. rvaofs : longint;
  1108. datalen : longint;
  1109. datapos : longint;
  1110. relocpos : longint;
  1111. lineno1 : longint;
  1112. nrelocs : word;
  1113. lineno2 : word;
  1114. flags : longint;
  1115. end;
  1116. psecfill=^TSecfill;
  1117. TSecfill=record
  1118. fillpos,
  1119. fillsize : longint;
  1120. next : psecfill;
  1121. end;
  1122. var
  1123. f : file;
  1124. cmdstr : string;
  1125. dosheader : tdosheader;
  1126. peheader : tpeheader;
  1127. firstsecpos,
  1128. maxfillsize,
  1129. l,peheaderpos : longint;
  1130. coffsec : tcoffsechdr;
  1131. secroot,hsecroot : psecfill;
  1132. zerobuf : pointer;
  1133. begin
  1134. postprocessexecutable:=false;
  1135. { when -s is used or it's a dll then quit }
  1136. if (cs_link_extern in aktglobalswitches) then
  1137. begin
  1138. case apptype of
  1139. app_gui :
  1140. cmdstr:='--subsystem gui';
  1141. app_cui :
  1142. cmdstr:='--subsystem console';
  1143. end;
  1144. if dllversion<>'' then
  1145. cmdstr:=cmdstr+' --version '+dllversion;
  1146. cmdstr:=cmdstr+' --input '+maybequoted(fn);
  1147. cmdstr:=cmdstr+' --stack '+tostr(stacksize);
  1148. DoExec(FindUtil(utilsprefix+'postw32'),cmdstr,false,false);
  1149. postprocessexecutable:=true;
  1150. exit;
  1151. end;
  1152. { open file }
  1153. assign(f,fn);
  1154. {$I-}
  1155. reset(f,1);
  1156. if ioresult<>0 then
  1157. Message1(execinfo_f_cant_open_executable,fn);
  1158. { read headers }
  1159. blockread(f,dosheader,sizeof(tdosheader));
  1160. peheaderpos:=dosheader.e_lfanew;
  1161. seek(f,peheaderpos);
  1162. blockread(f,peheader,sizeof(tpeheader));
  1163. { write info }
  1164. Message1(execinfo_x_codesize,tostr(peheader.SizeOfCode));
  1165. Message1(execinfo_x_initdatasize,tostr(peheader.SizeOfInitializedData));
  1166. Message1(execinfo_x_uninitdatasize,tostr(peheader.SizeOfUninitializedData));
  1167. { change stack size (PM) }
  1168. { I am not sure that the default value is adequate !! }
  1169. peheader.SizeOfStackReserve:=stacksize;
  1170. { change the header }
  1171. { sub system }
  1172. { gui=2 }
  1173. { cui=3 }
  1174. case apptype of
  1175. app_gui :
  1176. peheader.Subsystem:=2;
  1177. app_cui :
  1178. peheader.Subsystem:=3;
  1179. end;
  1180. if dllversion<>'' then
  1181. begin
  1182. peheader.MajorImageVersion:=dllmajor;
  1183. peheader.MinorImageVersion:=dllminor;
  1184. end;
  1185. { reset timestamp }
  1186. peheader.TimeDateStamp:=0;
  1187. { write header back }
  1188. seek(f,peheaderpos);
  1189. blockwrite(f,peheader,sizeof(tpeheader));
  1190. if ioresult<>0 then
  1191. Message1(execinfo_f_cant_process_executable,fn);
  1192. seek(f,peheaderpos);
  1193. blockread(f,peheader,sizeof(tpeheader));
  1194. { write the value after the change }
  1195. Message1(execinfo_x_stackreserve,tostr(peheader.SizeOfStackReserve));
  1196. Message1(execinfo_x_stackcommit,tostr(peheader.SizeOfStackCommit));
  1197. { read section info }
  1198. maxfillsize:=0;
  1199. firstsecpos:=0;
  1200. secroot:=nil;
  1201. for l:=1 to peheader.NumberOfSections do
  1202. begin
  1203. blockread(f,coffsec,sizeof(tcoffsechdr));
  1204. if coffsec.datapos>0 then
  1205. begin
  1206. if secroot=nil then
  1207. firstsecpos:=coffsec.datapos;
  1208. new(hsecroot);
  1209. hsecroot^.fillpos:=coffsec.datapos+coffsec.vsize;
  1210. hsecroot^.fillsize:=coffsec.datalen-coffsec.vsize;
  1211. hsecroot^.next:=secroot;
  1212. secroot:=hsecroot;
  1213. if secroot^.fillsize>maxfillsize then
  1214. maxfillsize:=secroot^.fillsize;
  1215. end;
  1216. end;
  1217. if firstsecpos>0 then
  1218. begin
  1219. l:=firstsecpos-filepos(f);
  1220. if l>maxfillsize then
  1221. maxfillsize:=l;
  1222. end
  1223. else
  1224. l:=0;
  1225. { get zero buffer }
  1226. getmem(zerobuf,maxfillsize);
  1227. fillchar(zerobuf^,maxfillsize,0);
  1228. { zero from sectioninfo until first section }
  1229. blockwrite(f,zerobuf^,l);
  1230. { zero section alignments }
  1231. while assigned(secroot) do
  1232. begin
  1233. seek(f,secroot^.fillpos);
  1234. blockwrite(f,zerobuf^,secroot^.fillsize);
  1235. hsecroot:=secroot;
  1236. secroot:=secroot^.next;
  1237. dispose(hsecroot);
  1238. end;
  1239. freemem(zerobuf,maxfillsize);
  1240. close(f);
  1241. {$I+}
  1242. if ioresult<>0 then;
  1243. postprocessexecutable:=true;
  1244. end;
  1245. {****************************************************************************
  1246. TDLLScannerWin32
  1247. ****************************************************************************}
  1248. function tDLLScannerWin32.DOSstubOK(var x:cardinal):boolean;
  1249. begin
  1250. blockread(f,TheWord,2,loaded);
  1251. if loaded<>2 then
  1252. DOSstubOK:=false
  1253. else
  1254. begin
  1255. DOSstubOK:=(TheWord='MZ');
  1256. seek(f,$3C);
  1257. blockread(f,x,4,loaded);
  1258. if(loaded<>4)or(longint(x)>filesize(f))then
  1259. DOSstubOK:=false;
  1260. end;
  1261. end;
  1262. function TDLLScannerWin32.FindDLL(const s:string;var founddll:string):boolean;
  1263. var
  1264. sysdir : string;
  1265. Found : boolean;
  1266. begin
  1267. Found:=false;
  1268. { Look for DLL in:
  1269. 1. Current dir
  1270. 2. Library Path
  1271. 3. windir,windir/system,windir/system32 }
  1272. Found:=FindFile(s,'.'+source_info.DirSep,founddll);
  1273. if (not found) then
  1274. Found:=librarysearchpath.FindFile(s,founddll);
  1275. if (not found) then
  1276. begin
  1277. sysdir:=FixPath(GetEnv('windir'),false);
  1278. Found:=FindFile(s,sysdir+';'+sysdir+'system'+source_info.DirSep+';'+sysdir+'system32'+source_info.DirSep,founddll);
  1279. end;
  1280. if (not found) then
  1281. begin
  1282. message1(exec_w_libfile_not_found,s);
  1283. FoundDll:=s;
  1284. end;
  1285. FindDll:=Found;
  1286. end;
  1287. function tDLLScannerWin32.ExtractDllName(Const Name : string) : string;
  1288. var n : string;
  1289. begin
  1290. n:=Upper(SplitExtension(Name));
  1291. if (n='.DLL') or (n='.DRV') or (n='.EXE') then
  1292. ExtractDllName:=Name
  1293. else
  1294. ExtractDllName:=Name+target_info.sharedlibext;
  1295. end;
  1296. function tDLLScannerWin32.isSuitableFileType(x:cardinal):longbool;
  1297. begin
  1298. seek(f,x);
  1299. blockread(f,TheWord,2,loaded);
  1300. isSuitableFileType:=(loaded=2)and(TheWord='PE');
  1301. end;
  1302. function tDLLScannerWin32.GetEdata(HeaderEntry:cardinal):longbool;
  1303. type
  1304. TObjInfo=packed record
  1305. ObjName:array[0..7]of char;
  1306. VirtSize,
  1307. VirtAddr,
  1308. RawSize,
  1309. RawOffset,
  1310. Reloc,
  1311. LineNum:cardinal;
  1312. RelCount,
  1313. LineCount:word;
  1314. flags:cardinal;
  1315. end;
  1316. var
  1317. i:cardinal;
  1318. ObjOfs:cardinal;
  1319. Obj:TObjInfo;
  1320. APE_obj,APE_Optsize:word;
  1321. ExportRVA:cardinal;
  1322. delta:cardinal;
  1323. const
  1324. IMAGE_SCN_CNT_CODE=$00000020;
  1325. var
  1326. _d:dirstr;
  1327. _n:namestr;
  1328. _e:extstr;
  1329. function isUsedFunction(name:pchar):longbool;
  1330. var
  1331. hp:tExternalsItem;
  1332. begin
  1333. isUsedFunction:=false;
  1334. hp:=tExternalsItem(current_module.Externals.first);
  1335. while assigned(hp)do
  1336. begin
  1337. if(assigned(hp.data))and(not hp.found)then
  1338. if hp.data^=StrPas(name)then
  1339. begin
  1340. isUsedFunction:=true;
  1341. hp.found:=true;
  1342. exit;
  1343. end;
  1344. hp:=tExternalsItem(hp.next);
  1345. end;
  1346. end;
  1347. procedure Store(index:cardinal;name:pchar;isData:longbool);
  1348. begin
  1349. if not isUsedFunction(name)then
  1350. exit;
  1351. if not(current_module.uses_imports) then
  1352. begin
  1353. current_module.uses_imports:=true;
  1354. importlib.preparelib(current_module.modulename^);
  1355. end;
  1356. if IsData then
  1357. timportlibwin32(importlib).importvariable_str(name,_n,name)
  1358. else
  1359. timportlibwin32(importlib).importprocedure_str(name,_n,index,name);
  1360. end;
  1361. procedure ProcessEdata;
  1362. type
  1363. a8=array[0..7]of char;
  1364. function GetSectionName(rva:cardinal;var Flags:cardinal):a8;
  1365. var
  1366. i:cardinal;
  1367. LocObjOfs:cardinal;
  1368. LocObj:TObjInfo;
  1369. begin
  1370. GetSectionName:='';
  1371. Flags:=0;
  1372. LocObjOfs:=APE_OptSize+HeaderOffset+24;
  1373. for i:=1 to APE_obj do
  1374. begin
  1375. seek(f,LocObjOfs);
  1376. blockread(f,LocObj,sizeof(LocObj));
  1377. if(rva>=LocObj.VirtAddr)and(rva<=LocObj.VirtAddr+LocObj.RawSize)then
  1378. begin
  1379. GetSectionName:=a8(LocObj.ObjName);
  1380. Flags:=LocObj.flags;
  1381. end;
  1382. end;
  1383. end;
  1384. var
  1385. j,Fl:cardinal;
  1386. ulongval,procEntry:cardinal;
  1387. Ordinal:word;
  1388. isData:longbool;
  1389. ExpDir:packed record
  1390. flag,
  1391. stamp:cardinal;
  1392. Major,
  1393. Minor:word;
  1394. Name,
  1395. Base,
  1396. NumFuncs,
  1397. NumNames,
  1398. AddrFuncs,
  1399. AddrNames,
  1400. AddrOrds:cardinal;
  1401. end;
  1402. begin
  1403. with Obj do
  1404. begin
  1405. seek(f,RawOffset+delta);
  1406. blockread(f,ExpDir,sizeof(ExpDir));
  1407. fsplit(impname,_d,_n,_e);
  1408. for j:=0 to pred(ExpDir.NumNames)do
  1409. begin
  1410. { Don't know why but this gives serious problems with overflow checking on }
  1411. {$IFOPT Q+}
  1412. {$DEFINE OVERFLOW_CHECK_WAS_ON}
  1413. {$ENDIF}
  1414. {$Q-}
  1415. seek(f,RawOffset-VirtAddr+ExpDir.AddrOrds+j*2);
  1416. blockread(f,Ordinal,2);
  1417. seek(f,RawOffset-VirtAddr+ExpDir.AddrFuncs+cardinal(Ordinal)*4);
  1418. blockread(f,ProcEntry,4);
  1419. seek(f,RawOffset-VirtAddr+ExpDir.AddrNames+j*4);
  1420. blockread(f,ulongval,4);
  1421. seek(f,RawOffset-VirtAddr+ulongval);
  1422. blockread(f,cstring,sizeof(cstring));
  1423. isData:=GetSectionName(procentry,Fl)='';
  1424. {$IFDEF OVERFLOW_CHECK_WAS_ON}
  1425. {$Q+}
  1426. {$ENDIF}
  1427. if not isData then
  1428. isData:=Fl and IMAGE_SCN_CNT_CODE<>IMAGE_SCN_CNT_CODE;
  1429. Store(succ(Ordinal),cstring,isData);
  1430. end;
  1431. end;
  1432. end;
  1433. begin
  1434. GetEdata:=false;
  1435. seek(f,HeaderEntry+120);
  1436. blockread(f,ExportRVA,4);
  1437. seek(f,HeaderEntry+6);
  1438. blockread(f,APE_Obj,2);
  1439. seek(f,HeaderEntry+20);
  1440. blockread(f,APE_OptSize,2);
  1441. ObjOfs:=APE_OptSize+HeaderOffset+24;
  1442. for i:=1 to APE_obj do
  1443. begin
  1444. seek(f,ObjOfs);
  1445. blockread(f,Obj,sizeof(Obj));
  1446. inc(ObjOfs,sizeof(Obj));
  1447. with Obj do
  1448. if(VirtAddr<=ExportRva)and(ExportRva<VirtAddr+VirtSize)then
  1449. begin
  1450. delta:=ExportRva-VirtAddr;
  1451. ProcessEdata;
  1452. GetEdata:=true;
  1453. end;
  1454. end;
  1455. end;
  1456. function tDLLScannerWin32.scan(const binname:string):longbool;
  1457. var
  1458. OldFileMode:longint;
  1459. hs,
  1460. foundimp : string;
  1461. begin
  1462. Scan:=false;
  1463. { is there already an import library the we will use that one }
  1464. if FindLibraryFile(binname,target_info.staticClibprefix,target_info.staticClibext,foundimp) then
  1465. exit;
  1466. { check if we can find the dll }
  1467. hs:=AddExtension(binname,target_info.sharedlibext);
  1468. if not FindDll(hs,impname) then
  1469. exit;
  1470. { read the dll file }
  1471. assign(f,impname);
  1472. OldFileMode:=filemode;
  1473. filemode:=0;
  1474. reset(f,1);
  1475. filemode:=OldFileMode;
  1476. if not DOSstubOK(HeaderOffset)then
  1477. scan:=false
  1478. else if not isSuitableFileType(HeaderOffset)then
  1479. scan:=false
  1480. else
  1481. scan:=GetEdata(HeaderOffset);
  1482. close(f);
  1483. end;
  1484. {*****************************************************************************
  1485. Initialize
  1486. *****************************************************************************}
  1487. initialization
  1488. {$ifdef i386}
  1489. RegisterExternalLinker(system_i386_win32_info,TLinkerWin32);
  1490. RegisterImport(system_i386_win32,TImportLibWin32);
  1491. RegisterExport(system_i386_win32,TExportLibWin32);
  1492. RegisterDLLScanner(system_i386_win32,TDLLScannerWin32);
  1493. RegisterRes(res_gnu_windres_info);
  1494. RegisterTarget(system_i386_win32_info);
  1495. {$endif i386}
  1496. end.
  1497. {
  1498. $Log$
  1499. Revision 1.40 2004-10-25 15:38:41 peter
  1500. * heap and heapsize removed
  1501. * checkpointer fixes
  1502. Revision 1.39 2004/10/15 09:24:38 mazen
  1503. - remove $IFDEF DELPHI and related code
  1504. - remove $IFDEF FPCPROCVAR and related code
  1505. Revision 1.38 2004/10/14 18:16:17 mazen
  1506. * USE_SYSUTILS merged successfully : cycles with and without defines
  1507. * Need to be optimized in performance
  1508. Revision 1.37 2004/09/22 15:25:14 mazen
  1509. * Fix error committing : previous version must be in branch USE_SYSUTILS
  1510. Revision 1.35 2004/06/20 08:55:32 florian
  1511. * logs truncated
  1512. Revision 1.34 2004/06/18 15:16:46 peter
  1513. * remove obsolete cardinal() typecasts
  1514. Revision 1.33 2004/06/16 20:07:11 florian
  1515. * dwarf branch merged
  1516. Revision 1.32 2004/04/28 18:02:54 peter
  1517. * add TList to cclasses, remove classes dependency from t_win32
  1518. Revision 1.31 2004/04/24 17:32:05 peter
  1519. index number generation for mixed index-nonindexed fixed, patch by Pavel V. Ozerski
  1520. Revision 1.30.2.5 2004/05/03 14:59:58 peter
  1521. * no dlltool needed for win32 linking executables
  1522. }