t_win.pas 56 KB

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