t_win32.pas 55 KB

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