t_win.pas 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  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 target_info.system in [system_arm_wince,system_i386_wince] then
  950. AppTypeStr:='--subsystem wince'
  951. else
  952. if apptype=app_gui then
  953. AppTypeStr:='--subsystem windows';
  954. if assigned(DLLImageBase) then
  955. ImageBaseStr:='--image-base=0x'+DLLImageBase^;
  956. if (cs_link_strip in aktglobalswitches) then
  957. StripStr:='-s';
  958. { Write used files and libraries }
  959. WriteResponseFile(false);
  960. { Call linker }
  961. success:=false;
  962. if RelocSection or (not Deffile.empty) then
  963. cmds:=3
  964. else
  965. cmds:=1;
  966. for i:=1 to cmds do
  967. begin
  968. SplitBinCmd(Info.ExeCmd[i],binstr,cmdstr);
  969. if binstr<>'' then
  970. begin
  971. Replace(cmdstr,'$EXE',maybequoted(current_module.exefilename^));
  972. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  973. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  974. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  975. Replace(cmdstr,'$ASBIN',AsbinStr);
  976. Replace(cmdstr,'$RELOC',RelocStr);
  977. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  978. Replace(cmdstr,'$STRIP',StripStr);
  979. if not DefFile.Empty then
  980. begin
  981. DefFile.WriteFile;
  982. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  983. end
  984. else
  985. Replace(cmdstr,'$DEF','');
  986. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  987. if not success then
  988. break;
  989. end;
  990. end;
  991. { Post process }
  992. if success then
  993. success:=PostProcessExecutable(current_module.exefilename^,false);
  994. { Remove ReponseFile }
  995. if (success) and not(cs_link_extern in aktglobalswitches) then
  996. begin
  997. RemoveFile(outputexedir+Info.ResName);
  998. RemoveFile('base.$$$');
  999. RemoveFile('exp.$$$');
  1000. RemoveFile('deffile.$$$');
  1001. end;
  1002. MakeExecutable:=success; { otherwise a recursive call to link method }
  1003. end;
  1004. Function TLinkerWin32.MakeSharedLibrary:boolean;
  1005. var
  1006. binstr : String;
  1007. cmdstr : TCmdStr;
  1008. success : boolean;
  1009. cmds,
  1010. i : longint;
  1011. AsBinStr : string[80];
  1012. StripStr,
  1013. RelocStr,
  1014. AppTypeStr,
  1015. ImageBaseStr : string[40];
  1016. begin
  1017. MakeSharedLibrary:=false;
  1018. if not(cs_link_extern in aktglobalswitches) then
  1019. Message1(exec_i_linking,current_module.sharedlibfilename^);
  1020. { Create some replacements }
  1021. RelocStr:='';
  1022. AppTypeStr:='';
  1023. ImageBaseStr:='';
  1024. StripStr:='';
  1025. AsBinStr:=FindUtil(utilsprefix+'as');
  1026. if RelocSection then
  1027. RelocStr:='--base-file base.$$$';
  1028. if apptype=app_gui then
  1029. AppTypeStr:='--subsystem windows';
  1030. if assigned(DLLImageBase) then
  1031. ImageBaseStr:='--image-base=0x'+DLLImageBase^;
  1032. if (cs_link_strip in aktglobalswitches) then
  1033. StripStr:='-s';
  1034. { Write used files and libraries }
  1035. WriteResponseFile(true);
  1036. { Call linker }
  1037. success:=false;
  1038. if RelocSection or (not Deffile.empty) then
  1039. cmds:=3
  1040. else
  1041. cmds:=1;
  1042. for i:=1 to cmds do
  1043. begin
  1044. SplitBinCmd(Info.DllCmd[i],binstr,cmdstr);
  1045. if binstr<>'' then
  1046. begin
  1047. Replace(cmdstr,'$EXE',maybequoted(current_module.sharedlibfilename^));
  1048. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  1049. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  1050. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  1051. Replace(cmdstr,'$ASBIN',AsbinStr);
  1052. Replace(cmdstr,'$RELOC',RelocStr);
  1053. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  1054. Replace(cmdstr,'$STRIP',StripStr);
  1055. if not DefFile.Empty then
  1056. begin
  1057. DefFile.WriteFile;
  1058. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  1059. end
  1060. else
  1061. Replace(cmdstr,'$DEF','');
  1062. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  1063. if not success then
  1064. break;
  1065. end;
  1066. end;
  1067. { Post process }
  1068. if success then
  1069. success:=PostProcessExecutable(current_module.sharedlibfilename^,true);
  1070. { Remove ReponseFile }
  1071. if (success) and not(cs_link_extern in aktglobalswitches) then
  1072. begin
  1073. RemoveFile(outputexedir+Info.ResName);
  1074. RemoveFile('base.$$$');
  1075. RemoveFile('exp.$$$');
  1076. RemoveFile('deffile.$$$');
  1077. end;
  1078. MakeSharedLibrary:=success; { otherwise a recursive call to link method }
  1079. end;
  1080. function tlinkerwin32.postprocessexecutable(const fn : string;isdll:boolean):boolean;
  1081. type
  1082. tdosheader = packed record
  1083. e_magic : word;
  1084. e_cblp : word;
  1085. e_cp : word;
  1086. e_crlc : word;
  1087. e_cparhdr : word;
  1088. e_minalloc : word;
  1089. e_maxalloc : word;
  1090. e_ss : word;
  1091. e_sp : word;
  1092. e_csum : word;
  1093. e_ip : word;
  1094. e_cs : word;
  1095. e_lfarlc : word;
  1096. e_ovno : word;
  1097. e_res : array[0..3] of word;
  1098. e_oemid : word;
  1099. e_oeminfo : word;
  1100. e_res2 : array[0..9] of word;
  1101. e_lfanew : longint;
  1102. end;
  1103. tpeheader = packed record
  1104. PEMagic : array[0..3] of char;
  1105. Machine : word;
  1106. NumberOfSections : word;
  1107. TimeDateStamp : longint;
  1108. PointerToSymbolTable : longint;
  1109. NumberOfSymbols : longint;
  1110. SizeOfOptionalHeader : word;
  1111. Characteristics : word;
  1112. Magic : word;
  1113. MajorLinkerVersion : byte;
  1114. MinorLinkerVersion : byte;
  1115. SizeOfCode : longint;
  1116. SizeOfInitializedData : longint;
  1117. SizeOfUninitializedData : longint;
  1118. AddressOfEntryPoint : longint;
  1119. BaseOfCode : longint;
  1120. BaseOfData : longint;
  1121. ImageBase : longint;
  1122. SectionAlignment : longint;
  1123. FileAlignment : longint;
  1124. MajorOperatingSystemVersion : word;
  1125. MinorOperatingSystemVersion : word;
  1126. MajorImageVersion : word;
  1127. MinorImageVersion : word;
  1128. MajorSubsystemVersion : word;
  1129. MinorSubsystemVersion : word;
  1130. Reserved1 : longint;
  1131. SizeOfImage : longint;
  1132. SizeOfHeaders : longint;
  1133. CheckSum : longint;
  1134. Subsystem : word;
  1135. DllCharacteristics : word;
  1136. SizeOfStackReserve : longint;
  1137. SizeOfStackCommit : longint;
  1138. SizeOfHeapReserve : longint;
  1139. SizeOfHeapCommit : longint;
  1140. LoaderFlags : longint;
  1141. NumberOfRvaAndSizes : longint;
  1142. DataDirectory : array[1..$80] of byte;
  1143. end;
  1144. tcoffsechdr=packed record
  1145. name : array[0..7] of char;
  1146. vsize : longint;
  1147. rvaofs : longint;
  1148. datalen : longint;
  1149. datapos : longint;
  1150. relocpos : longint;
  1151. lineno1 : longint;
  1152. nrelocs : word;
  1153. lineno2 : word;
  1154. flags : longint;
  1155. end;
  1156. psecfill=^TSecfill;
  1157. TSecfill=record
  1158. fillpos,
  1159. fillsize : longint;
  1160. next : psecfill;
  1161. end;
  1162. var
  1163. f : file;
  1164. cmdstr : string;
  1165. dosheader : tdosheader;
  1166. peheader : tpeheader;
  1167. firstsecpos,
  1168. maxfillsize,
  1169. l,peheaderpos : longint;
  1170. coffsec : tcoffsechdr;
  1171. secroot,hsecroot : psecfill;
  1172. zerobuf : pointer;
  1173. begin
  1174. postprocessexecutable:=false;
  1175. { when -s is used or it's a dll then quit }
  1176. if (cs_link_extern in aktglobalswitches) then
  1177. begin
  1178. case apptype of
  1179. app_gui :
  1180. cmdstr:='--subsystem gui';
  1181. app_cui :
  1182. cmdstr:='--subsystem console';
  1183. end;
  1184. if dllversion<>'' then
  1185. cmdstr:=cmdstr+' --version '+dllversion;
  1186. cmdstr:=cmdstr+' --input '+maybequoted(fn);
  1187. cmdstr:=cmdstr+' --stack '+tostr(stacksize);
  1188. DoExec(FindUtil(utilsprefix+'postw32'),cmdstr,false,false);
  1189. postprocessexecutable:=true;
  1190. exit;
  1191. end;
  1192. { open file }
  1193. assign(f,fn);
  1194. {$I-}
  1195. reset(f,1);
  1196. if ioresult<>0 then
  1197. Message1(execinfo_f_cant_open_executable,fn);
  1198. { read headers }
  1199. blockread(f,dosheader,sizeof(tdosheader));
  1200. peheaderpos:=dosheader.e_lfanew;
  1201. seek(f,peheaderpos);
  1202. blockread(f,peheader,sizeof(tpeheader));
  1203. { write info }
  1204. Message1(execinfo_x_codesize,tostr(peheader.SizeOfCode));
  1205. Message1(execinfo_x_initdatasize,tostr(peheader.SizeOfInitializedData));
  1206. Message1(execinfo_x_uninitdatasize,tostr(peheader.SizeOfUninitializedData));
  1207. { change stack size (PM) }
  1208. { I am not sure that the default value is adequate !! }
  1209. peheader.SizeOfStackReserve:=stacksize;
  1210. { change the header }
  1211. { sub system }
  1212. { gui=2 }
  1213. { cui=3 }
  1214. { wincegui=9 }
  1215. if target_info.system in [system_arm_wince,system_i386_wince] then
  1216. peheader.Subsystem:=9
  1217. else
  1218. case apptype of
  1219. app_gui :
  1220. peheader.Subsystem:=2;
  1221. app_cui :
  1222. peheader.Subsystem:=3;
  1223. end;
  1224. if dllversion<>'' then
  1225. begin
  1226. peheader.MajorImageVersion:=dllmajor;
  1227. peheader.MinorImageVersion:=dllminor;
  1228. end;
  1229. { reset timestamp }
  1230. peheader.TimeDateStamp:=0;
  1231. { write header back }
  1232. seek(f,peheaderpos);
  1233. blockwrite(f,peheader,sizeof(tpeheader));
  1234. if ioresult<>0 then
  1235. Message1(execinfo_f_cant_process_executable,fn);
  1236. seek(f,peheaderpos);
  1237. blockread(f,peheader,sizeof(tpeheader));
  1238. { write the value after the change }
  1239. Message1(execinfo_x_stackreserve,tostr(peheader.SizeOfStackReserve));
  1240. Message1(execinfo_x_stackcommit,tostr(peheader.SizeOfStackCommit));
  1241. { read section info }
  1242. maxfillsize:=0;
  1243. firstsecpos:=0;
  1244. secroot:=nil;
  1245. for l:=1 to peheader.NumberOfSections do
  1246. begin
  1247. blockread(f,coffsec,sizeof(tcoffsechdr));
  1248. if coffsec.datapos>0 then
  1249. begin
  1250. if secroot=nil then
  1251. firstsecpos:=coffsec.datapos;
  1252. new(hsecroot);
  1253. hsecroot^.fillpos:=coffsec.datapos+coffsec.vsize;
  1254. hsecroot^.fillsize:=coffsec.datalen-coffsec.vsize;
  1255. hsecroot^.next:=secroot;
  1256. secroot:=hsecroot;
  1257. if secroot^.fillsize>maxfillsize then
  1258. maxfillsize:=secroot^.fillsize;
  1259. end;
  1260. end;
  1261. if firstsecpos>0 then
  1262. begin
  1263. l:=firstsecpos-filepos(f);
  1264. if l>maxfillsize then
  1265. maxfillsize:=l;
  1266. end
  1267. else
  1268. l:=0;
  1269. { get zero buffer }
  1270. getmem(zerobuf,maxfillsize);
  1271. fillchar(zerobuf^,maxfillsize,0);
  1272. { zero from sectioninfo until first section }
  1273. blockwrite(f,zerobuf^,l);
  1274. { zero section alignments }
  1275. while assigned(secroot) do
  1276. begin
  1277. seek(f,secroot^.fillpos);
  1278. blockwrite(f,zerobuf^,secroot^.fillsize);
  1279. hsecroot:=secroot;
  1280. secroot:=secroot^.next;
  1281. dispose(hsecroot);
  1282. end;
  1283. freemem(zerobuf,maxfillsize);
  1284. close(f);
  1285. {$I+}
  1286. if ioresult<>0 then;
  1287. postprocessexecutable:=true;
  1288. end;
  1289. {****************************************************************************
  1290. TDLLScannerWin32
  1291. ****************************************************************************}
  1292. function tDLLScannerWin32.DOSstubOK(var x:cardinal):boolean;
  1293. begin
  1294. blockread(f,TheWord,2,loaded);
  1295. if loaded<>2 then
  1296. DOSstubOK:=false
  1297. else
  1298. begin
  1299. DOSstubOK:=(TheWord='MZ');
  1300. seek(f,$3C);
  1301. blockread(f,x,4,loaded);
  1302. if(loaded<>4)or(longint(x)>filesize(f))then
  1303. DOSstubOK:=false;
  1304. end;
  1305. end;
  1306. function TDLLScannerWin32.FindDLL(const s:string;var founddll:string):boolean;
  1307. var
  1308. sysdir : string;
  1309. Found : boolean;
  1310. begin
  1311. Found:=false;
  1312. { Look for DLL in:
  1313. 1. Current dir
  1314. 2. Library Path
  1315. 3. windir,windir/system,windir/system32 }
  1316. Found:=FindFile(s,'.'+source_info.DirSep,founddll);
  1317. if (not found) then
  1318. Found:=librarysearchpath.FindFile(s,founddll);
  1319. if (not found) then
  1320. begin
  1321. sysdir:=FixPath(GetEnv('windir'),false);
  1322. Found:=FindFile(s,sysdir+';'+sysdir+'system'+source_info.DirSep+';'+sysdir+'system32'+source_info.DirSep,founddll);
  1323. end;
  1324. if (not found) then
  1325. begin
  1326. message1(exec_w_libfile_not_found,s);
  1327. FoundDll:=s;
  1328. end;
  1329. FindDll:=Found;
  1330. end;
  1331. function tDLLScannerWin32.ExtractDllName(Const Name : string) : string;
  1332. var n : string;
  1333. begin
  1334. n:=Upper(SplitExtension(Name));
  1335. if (n='.DLL') or (n='.DRV') or (n='.EXE') then
  1336. ExtractDllName:=Name
  1337. else
  1338. ExtractDllName:=Name+target_info.sharedlibext;
  1339. end;
  1340. function tDLLScannerWin32.isSuitableFileType(x:cardinal):longbool;
  1341. begin
  1342. seek(f,x);
  1343. blockread(f,TheWord,2,loaded);
  1344. isSuitableFileType:=(loaded=2)and(TheWord='PE');
  1345. end;
  1346. function tDLLScannerWin32.GetEdata(HeaderEntry:cardinal):longbool;
  1347. type
  1348. TObjInfo=packed record
  1349. ObjName:array[0..7]of char;
  1350. VirtSize,
  1351. VirtAddr,
  1352. RawSize,
  1353. RawOffset,
  1354. Reloc,
  1355. LineNum:cardinal;
  1356. RelCount,
  1357. LineCount:word;
  1358. flags:cardinal;
  1359. end;
  1360. var
  1361. i:cardinal;
  1362. ObjOfs:cardinal;
  1363. Obj:TObjInfo;
  1364. APE_obj,APE_Optsize:word;
  1365. ExportRVA:cardinal;
  1366. delta:cardinal;
  1367. const
  1368. IMAGE_SCN_CNT_CODE=$00000020;
  1369. var
  1370. _d:dirstr;
  1371. _n:namestr;
  1372. _e:extstr;
  1373. function isUsedFunction(name:pchar):longbool;
  1374. var
  1375. hp:tExternalsItem;
  1376. begin
  1377. isUsedFunction:=false;
  1378. hp:=tExternalsItem(current_module.Externals.first);
  1379. while assigned(hp)do
  1380. begin
  1381. if(assigned(hp.data))and(not hp.found)then
  1382. if hp.data^=StrPas(name)then
  1383. begin
  1384. isUsedFunction:=true;
  1385. hp.found:=true;
  1386. exit;
  1387. end;
  1388. hp:=tExternalsItem(hp.next);
  1389. end;
  1390. end;
  1391. procedure Store(index:cardinal;name:pchar;isData:longbool);
  1392. begin
  1393. if not isUsedFunction(name)then
  1394. exit;
  1395. if not(current_module.uses_imports) then
  1396. begin
  1397. current_module.uses_imports:=true;
  1398. importlib.preparelib(current_module.modulename^);
  1399. end;
  1400. if IsData then
  1401. timportlibwin32(importlib).importvariable_str(name,_n,name)
  1402. else
  1403. timportlibwin32(importlib).importprocedure_str(name,_n,index,name);
  1404. end;
  1405. procedure ProcessEdata;
  1406. type
  1407. a8=array[0..7]of char;
  1408. function GetSectionName(rva:cardinal;var Flags:cardinal):a8;
  1409. var
  1410. i:cardinal;
  1411. LocObjOfs:cardinal;
  1412. LocObj:TObjInfo;
  1413. begin
  1414. GetSectionName:='';
  1415. Flags:=0;
  1416. LocObjOfs:=APE_OptSize+HeaderOffset+24;
  1417. for i:=1 to APE_obj do
  1418. begin
  1419. seek(f,LocObjOfs);
  1420. blockread(f,LocObj,sizeof(LocObj));
  1421. if(rva>=LocObj.VirtAddr)and(rva<=LocObj.VirtAddr+LocObj.RawSize)then
  1422. begin
  1423. GetSectionName:=a8(LocObj.ObjName);
  1424. Flags:=LocObj.flags;
  1425. end;
  1426. end;
  1427. end;
  1428. var
  1429. j,Fl:cardinal;
  1430. ulongval,procEntry:cardinal;
  1431. Ordinal:word;
  1432. isData:longbool;
  1433. ExpDir:packed record
  1434. flag,
  1435. stamp:cardinal;
  1436. Major,
  1437. Minor:word;
  1438. Name,
  1439. Base,
  1440. NumFuncs,
  1441. NumNames,
  1442. AddrFuncs,
  1443. AddrNames,
  1444. AddrOrds:cardinal;
  1445. end;
  1446. begin
  1447. with Obj do
  1448. begin
  1449. seek(f,RawOffset+delta);
  1450. blockread(f,ExpDir,sizeof(ExpDir));
  1451. fsplit(impname,_d,_n,_e);
  1452. for j:=0 to pred(ExpDir.NumNames)do
  1453. begin
  1454. { Don't know why but this gives serious problems with overflow checking on }
  1455. {$IFOPT Q+}
  1456. {$DEFINE OVERFLOW_CHECK_WAS_ON}
  1457. {$ENDIF}
  1458. {$Q-}
  1459. seek(f,RawOffset-VirtAddr+ExpDir.AddrOrds+j*2);
  1460. blockread(f,Ordinal,2);
  1461. seek(f,RawOffset-VirtAddr+ExpDir.AddrFuncs+cardinal(Ordinal)*4);
  1462. blockread(f,ProcEntry,4);
  1463. seek(f,RawOffset-VirtAddr+ExpDir.AddrNames+j*4);
  1464. blockread(f,ulongval,4);
  1465. seek(f,RawOffset-VirtAddr+ulongval);
  1466. blockread(f,cstring,sizeof(cstring));
  1467. isData:=GetSectionName(procentry,Fl)='';
  1468. {$IFDEF OVERFLOW_CHECK_WAS_ON}
  1469. {$Q+}
  1470. {$ENDIF}
  1471. if not isData then
  1472. isData:=Fl and IMAGE_SCN_CNT_CODE<>IMAGE_SCN_CNT_CODE;
  1473. Store(succ(Ordinal),cstring,isData);
  1474. end;
  1475. end;
  1476. end;
  1477. begin
  1478. GetEdata:=false;
  1479. seek(f,HeaderEntry+120);
  1480. blockread(f,ExportRVA,4);
  1481. seek(f,HeaderEntry+6);
  1482. blockread(f,APE_Obj,2);
  1483. seek(f,HeaderEntry+20);
  1484. blockread(f,APE_OptSize,2);
  1485. ObjOfs:=APE_OptSize+HeaderOffset+24;
  1486. for i:=1 to APE_obj do
  1487. begin
  1488. seek(f,ObjOfs);
  1489. blockread(f,Obj,sizeof(Obj));
  1490. inc(ObjOfs,sizeof(Obj));
  1491. with Obj do
  1492. if(VirtAddr<=ExportRva)and(ExportRva<VirtAddr+VirtSize)then
  1493. begin
  1494. delta:=ExportRva-VirtAddr;
  1495. ProcessEdata;
  1496. GetEdata:=true;
  1497. end;
  1498. end;
  1499. end;
  1500. function tDLLScannerWin32.scan(const binname:string):longbool;
  1501. var
  1502. OldFileMode:longint;
  1503. hs,
  1504. foundimp : string;
  1505. begin
  1506. Scan:=false;
  1507. { is there already an import library the we will use that one }
  1508. if FindLibraryFile(binname,target_info.staticClibprefix,target_info.staticClibext,foundimp) then
  1509. exit;
  1510. { check if we can find the dll }
  1511. hs:=AddExtension(binname,target_info.sharedlibext);
  1512. if not FindDll(hs,impname) then
  1513. exit;
  1514. { read the dll file }
  1515. assign(f,impname);
  1516. OldFileMode:=filemode;
  1517. filemode:=0;
  1518. reset(f,1);
  1519. filemode:=OldFileMode;
  1520. if not DOSstubOK(HeaderOffset)then
  1521. scan:=false
  1522. else if not isSuitableFileType(HeaderOffset)then
  1523. scan:=false
  1524. else
  1525. scan:=GetEdata(HeaderOffset);
  1526. close(f);
  1527. end;
  1528. {*****************************************************************************
  1529. Initialize
  1530. *****************************************************************************}
  1531. initialization
  1532. {$ifdef i386}
  1533. RegisterExternalLinker(system_i386_win32_info,TLinkerWin32);
  1534. RegisterImport(system_i386_win32,TImportLibWin32);
  1535. RegisterExport(system_i386_win32,TExportLibWin32);
  1536. RegisterDLLScanner(system_i386_win32,TDLLScannerWin32);
  1537. RegisterRes(res_gnu_windres_info);
  1538. RegisterTarget(system_i386_win32_info);
  1539. RegisterExternalLinker(system_i386_wince_info,TLinkerWin32);
  1540. RegisterImport(system_i386_wince,TImportLibWin32);
  1541. RegisterExport(system_i386_wince,TExportLibWin32);
  1542. RegisterDLLScanner(system_i386_wince,TDLLScannerWin32);
  1543. RegisterTarget(system_i386_wince_info);
  1544. {$endif i386}
  1545. {$ifdef x86_64}
  1546. RegisterExternalLinker(system_x64_win64_info,TLinkerWin32);
  1547. RegisterImport(system_x86_64_win64,TImportLibWin32);
  1548. RegisterExport(system_x86_64_win64,TExportLibWin32);
  1549. RegisterDLLScanner(system_x86_64_win64,TDLLScannerWin32);
  1550. RegisterRes(res_gnu_windres_info);
  1551. RegisterTarget(system_x64_win64_info);
  1552. {$endif x86_64}
  1553. {$ifdef arm}
  1554. RegisterExternalLinker(system_arm_wince_info,TLinkerWin32);
  1555. RegisterImport(system_arm_wince,TImportLibWin32);
  1556. RegisterExport(system_arm_wince,TExportLibWin32);
  1557. RegisterRes(res_gnu_windres_info);
  1558. RegisterTarget(system_arm_wince_info);
  1559. {$endif arm}
  1560. end.