t_win.pas 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  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 asmlist[importsection]=nil then
  94. asmlist[importsection]:=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(asmlist[importsection],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. asmlist[importsection].concat(tai_direct.create(p));
  204. p:=strpnew(#9+'import '+hp2.func^+' '+hp1.dllname^+' '+hp2.name^);
  205. asmlist[importsection].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. asmlist[importsection].concat(Tai_cutobject.Create_begin);
  239. new_section(asmlist[importsection],sec_idata2,'',0);
  240. asmlist[importsection].concat(Tai_label.Create(lhead));
  241. { pointer to procedure names }
  242. asmlist[importsection].concat(Tai_const.Create_rva_sym(lidata4));
  243. { two empty entries follow }
  244. asmlist[importsection].concat(Tai_const.Create_32bit(0));
  245. asmlist[importsection].concat(Tai_const.Create_32bit(0));
  246. { pointer to dll name }
  247. asmlist[importsection].concat(Tai_const.Create_rva_sym(lname));
  248. { pointer to fixups }
  249. asmlist[importsection].concat(Tai_const.Create_rva_sym(lidata5));
  250. { first write the name references }
  251. new_section(asmlist[importsection],sec_idata4,'',0);
  252. asmlist[importsection].concat(Tai_const.Create_32bit(0));
  253. asmlist[importsection].concat(Tai_label.Create(lidata4));
  254. { then the addresses and create also the indirect jump }
  255. new_section(asmlist[importsection],sec_idata5,'',0);
  256. asmlist[importsection].concat(Tai_const.Create_32bit(0));
  257. asmlist[importsection].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. asmlist[importsection].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(asmlist[importsection],sec_code,'',0);
  274. {$IfDef GDB}
  275. if (cs_debuginfo in aktmoduleswitches) then
  276. asmlist[importsection].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. asmlist[importsection].concat(Tai_symbol.Createname_global(mangledstring,AT_FUNCTION,0));
  283. {$ifdef ARM}
  284. reference_reset_symbol(href,lpcode,0);
  285. asmlist[importsection].concat(Taicpu.op_reg_ref(A_LDR,NR_R12,href));
  286. reference_reset_base(href,NR_R12,0);
  287. asmlist[importsection].concat(Taicpu.op_reg_ref(A_LDR,NR_R15,href));
  288. asmlist[importsection].concat(Tai_label.Create(lpcode));
  289. reference_reset_symbol(href,lcode,0);
  290. asmlist[importsection].concat(tai_const.create_sym_offset(href.symbol,href.offset));
  291. {$else ARM}
  292. reference_reset_symbol(href,lcode,0);
  293. asmlist[importsection].concat(Taicpu.Op_ref(A_JMP,S_NO,href));
  294. asmlist[importsection].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(asmlist[importsection]);
  299. {$EndIf GDB}
  300. end;
  301. { create head link }
  302. new_section(asmlist[importsection],sec_idata7,'',0);
  303. asmlist[importsection].concat(Tai_const.Create_rva_sym(lhead));
  304. { fixup }
  305. objectlibrary.getlabel(tasmlabel(hp2.lab));
  306. new_section(asmlist[importsection],sec_idata4,'',0);
  307. asmlist[importsection].concat(Tai_const.Create_rva_sym(hp2.lab));
  308. { add jump field to imporTSection }
  309. new_section(asmlist[importsection],sec_idata5,'',0);
  310. if hp2.is_var then
  311. asmlist[importsection].concat(Tai_symbol.Createname_global(hp2.func^,AT_FUNCTION,0))
  312. else
  313. asmlist[importsection].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. asmlist[importsection].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. asmlist[importsection].concat(tai_symbol.createname(importname,AT_FUNCTION,4));
  338. end;
  339. end;
  340. {$endif GDB}
  341. if hp2.name^<>'' then
  342. asmlist[importsection].concat(Tai_const.Create_rva_sym(hp2.lab))
  343. else
  344. asmlist[importsection].concat(Tai_const.Create_32bit(longint($80000000) or longint(hp2.ordnr)));
  345. { finally the import information }
  346. new_section(asmlist[importsection],sec_idata6,'',0);
  347. asmlist[importsection].concat(Tai_label.Create(hp2.lab));
  348. asmlist[importsection].concat(Tai_const.Create_16bit(hp2.ordnr));
  349. asmlist[importsection].concat(Tai_string.Create(hp2.name^+#0));
  350. asmlist[importsection].concat(Tai_align.Create_op(2,0));
  351. hp2:=twin32imported_item(hp2.next);
  352. end;
  353. { write final section }
  354. asmlist[importsection].concat(Tai_cutobject.Create_end);
  355. { end of name references }
  356. new_section(asmlist[importsection],sec_idata4,'',0);
  357. asmlist[importsection].concat(Tai_const.Create_32bit(0));
  358. { end if addresses }
  359. new_section(asmlist[importsection],sec_idata5,'',0);
  360. asmlist[importsection].concat(Tai_const.Create_32bit(0));
  361. { dllname }
  362. new_section(asmlist[importsection],sec_idata7,'',0);
  363. asmlist[importsection].concat(Tai_label.Create(lname));
  364. asmlist[importsection].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(asmlist[importsection],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(asmlist[importsection],sec_idata2,'',0);
  395. { pointer to procedure names }
  396. asmlist[importsection].concat(Tai_const.Create_rva_sym(l2));
  397. { two empty entries follow }
  398. asmlist[importsection].concat(Tai_const.Create_32bit(0));
  399. asmlist[importsection].concat(Tai_const.Create_32bit(0));
  400. { pointer to dll name }
  401. asmlist[importsection].concat(Tai_const.Create_rva_sym(l1));
  402. { pointer to fixups }
  403. asmlist[importsection].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(asmlist[importsection],sec_idata4,'',0);
  408. asmlist[importsection].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. asmlist[importsection].concat(Tai_const.Create_rva_sym(hp2.lab))
  415. else
  416. asmlist[importsection].concat(Tai_const.Create_32bit(longint($80000000) or hp2.ordnr));
  417. hp2:=twin32imported_item(hp2.next);
  418. end;
  419. { finalize the names ... }
  420. asmlist[importsection].concat(Tai_const.Create_32bit(0));
  421. { then the addresses and create also the indirect jump }
  422. new_section(asmlist[importsection],sec_idata5,'',0);
  423. asmlist[importsection].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(asmlist[importsection],sec_code,'',0);
  436. {$IfDef GDB}
  437. if (cs_debuginfo in aktmoduleswitches) then
  438. asmlist[importsection].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. asmlist[importsection].concat(Tai_symbol.Createname_global(mangledstring,AT_FUNCTION,0));
  445. {$ifdef ARM}
  446. reference_reset_symbol(href,l5,0);
  447. asmlist[importsection].concat(Taicpu.op_reg_ref(A_LDR,NR_R12,href));
  448. reference_reset_base(href,NR_R12,0);
  449. asmlist[importsection].concat(Taicpu.op_reg_ref(A_LDR,NR_R15,href));
  450. asmlist[importsection].concat(Tai_label.Create(l5));
  451. reference_reset_symbol(href,l4,0);
  452. asmlist[importsection].concat(tai_const.create_sym_offset(href.symbol,href.offset));
  453. {$else ARM}
  454. reference_reset_symbol(href,l4,0);
  455. asmlist[importsection].concat(Taicpu.Op_ref(A_JMP,S_NO,href));
  456. asmlist[importsection].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(asmlist[importsection]);
  461. {$EndIf GDB}
  462. { add jump field to imporTSection }
  463. new_section(asmlist[importsection],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. asmlist[importsection].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. asmlist[importsection].concat(tai_symbol.createname(importname,AT_FUNCTION,4));
  488. end;
  489. end;
  490. {$endif GDB}
  491. asmlist[importsection].concat(Tai_label.Create(l4));
  492. end
  493. else
  494. begin
  495. asmlist[importsection].concat(Tai_symbol.Createname_global(hp2.func^,AT_DATA,0));
  496. end;
  497. asmlist[importsection].concat(Tai_const.Create_rva_sym(hp2.lab));
  498. hp2:=twin32imported_item(hp2.next);
  499. end;
  500. { finalize the addresses }
  501. asmlist[importsection].concat(Tai_const.Create_32bit(0));
  502. { finally the import information }
  503. new_section(asmlist[importsection],sec_idata6,'',0);
  504. hp2:=twin32imported_item(hp1.imported_items.first);
  505. while assigned(hp2) do
  506. begin
  507. asmlist[importsection].concat(Tai_label.Create(hp2.lab));
  508. { the ordinal number }
  509. asmlist[importsection].concat(Tai_const.Create_16bit(hp2.ordnr));
  510. asmlist[importsection].concat(Tai_string.Create(hp2.name^+#0));
  511. asmlist[importsection].concat(Tai_align.Create_op(2,0));
  512. hp2:=twin32imported_item(hp2.next);
  513. end;
  514. { create import dll name }
  515. new_section(asmlist[importsection],sec_idata7,'',0);
  516. asmlist[importsection].concat(Tai_label.Create(l1));
  517. asmlist[importsection].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 asmlist[exportsection]=nil then
  527. asmlist[exportsection]:=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(asmlist[exportsection],sec_edata,'',0);
  672. { create label to reference from main so smartlink will include
  673. the .edata section }
  674. asmlist[exportsection].concat(Tai_symbol.Create_global(edatalabel,0));
  675. { export flags }
  676. asmlist[exportsection].concat(Tai_const.Create_32bit(0));
  677. { date/time stamp }
  678. asmlist[exportsection].concat(Tai_const.Create_32bit(0));
  679. { major version }
  680. asmlist[exportsection].concat(Tai_const.Create_16bit(0));
  681. { minor version }
  682. asmlist[exportsection].concat(Tai_const.Create_16bit(0));
  683. { pointer to dll name }
  684. asmlist[exportsection].concat(Tai_const.Create_rva_sym(dll_name_label));
  685. { ordinal base normally set to 1 }
  686. asmlist[exportsection].concat(Tai_const.Create_32bit(ordinal_base));
  687. { number of entries }
  688. asmlist[exportsection].concat(Tai_const.Create_32bit(entries));
  689. { number of named entries }
  690. asmlist[exportsection].concat(Tai_const.Create_32bit(named_entries));
  691. { address of export address table }
  692. asmlist[exportsection].concat(Tai_const.Create_rva_sym(export_address_table));
  693. { address of name pointer pointers }
  694. asmlist[exportsection].concat(Tai_const.Create_rva_sym(export_name_table_pointers));
  695. { address of ordinal number pointers }
  696. asmlist[exportsection].concat(Tai_const.Create_rva_sym(export_ordinal_table));
  697. { the name }
  698. asmlist[exportsection].concat(Tai_label.Create(dll_name_label));
  699. if st='' then
  700. asmlist[exportsection].concat(Tai_string.Create(current_module.modulename^+target_info.sharedlibext+#0))
  701. else
  702. asmlist[exportsection].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. asmlist[exportsection].concatlist(address_table);
  769. asmlist[exportsection].concatlist(name_table_pointers);
  770. asmlist[exportsection].concatlist(ordinal_table);
  771. asmlist[exportsection].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(asmlist[exportsection],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. asmlist[exportsection].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. begin
  951. AppTypeStr:='--subsystem wince';
  952. if apptype <> app_gui then
  953. AppTypeStr:=AppTypeStr + ' --entry=mainCRTStartup';
  954. end
  955. else
  956. if apptype=app_gui then
  957. AppTypeStr:='--subsystem windows';
  958. if assigned(DLLImageBase) then
  959. ImageBaseStr:='--image-base=0x'+DLLImageBase^;
  960. if (cs_link_strip in aktglobalswitches) then
  961. StripStr:='-s';
  962. { Write used files and libraries }
  963. WriteResponseFile(false);
  964. { Call linker }
  965. success:=false;
  966. if RelocSection or (not Deffile.empty) then
  967. cmds:=3
  968. else
  969. cmds:=1;
  970. for i:=1 to cmds do
  971. begin
  972. SplitBinCmd(Info.ExeCmd[i],binstr,cmdstr);
  973. if binstr<>'' then
  974. begin
  975. Replace(cmdstr,'$EXE',maybequoted(current_module.exefilename^));
  976. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  977. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  978. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  979. Replace(cmdstr,'$ASBIN',AsbinStr);
  980. Replace(cmdstr,'$RELOC',RelocStr);
  981. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  982. Replace(cmdstr,'$STRIP',StripStr);
  983. if not DefFile.Empty then
  984. begin
  985. DefFile.WriteFile;
  986. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  987. end
  988. else
  989. Replace(cmdstr,'$DEF','');
  990. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  991. if not success then
  992. break;
  993. end;
  994. end;
  995. { Post process }
  996. if success then
  997. success:=PostProcessExecutable(current_module.exefilename^,false);
  998. { Remove ReponseFile }
  999. if (success) and not(cs_link_extern in aktglobalswitches) then
  1000. begin
  1001. RemoveFile(outputexedir+Info.ResName);
  1002. RemoveFile('base.$$$');
  1003. RemoveFile('exp.$$$');
  1004. RemoveFile('deffile.$$$');
  1005. end;
  1006. MakeExecutable:=success; { otherwise a recursive call to link method }
  1007. end;
  1008. Function TLinkerWin32.MakeSharedLibrary:boolean;
  1009. var
  1010. binstr : String;
  1011. cmdstr : TCmdStr;
  1012. success : boolean;
  1013. cmds,
  1014. i : longint;
  1015. AsBinStr : string[80];
  1016. StripStr,
  1017. RelocStr,
  1018. AppTypeStr,
  1019. ImageBaseStr : string[40];
  1020. begin
  1021. MakeSharedLibrary:=false;
  1022. if not(cs_link_extern in aktglobalswitches) then
  1023. Message1(exec_i_linking,current_module.sharedlibfilename^);
  1024. { Create some replacements }
  1025. RelocStr:='';
  1026. AppTypeStr:='';
  1027. ImageBaseStr:='';
  1028. StripStr:='';
  1029. AsBinStr:=FindUtil(utilsprefix+'as');
  1030. if RelocSection then
  1031. RelocStr:='--base-file base.$$$';
  1032. if apptype=app_gui then
  1033. AppTypeStr:='--subsystem windows';
  1034. if assigned(DLLImageBase) then
  1035. ImageBaseStr:='--image-base=0x'+DLLImageBase^;
  1036. if (cs_link_strip in aktglobalswitches) then
  1037. StripStr:='-s';
  1038. { Write used files and libraries }
  1039. WriteResponseFile(true);
  1040. { Call linker }
  1041. success:=false;
  1042. if RelocSection or (not Deffile.empty) then
  1043. cmds:=3
  1044. else
  1045. cmds:=1;
  1046. for i:=1 to cmds do
  1047. begin
  1048. SplitBinCmd(Info.DllCmd[i],binstr,cmdstr);
  1049. if binstr<>'' then
  1050. begin
  1051. Replace(cmdstr,'$EXE',maybequoted(current_module.sharedlibfilename^));
  1052. Replace(cmdstr,'$OPT',Info.ExtraOptions);
  1053. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  1054. Replace(cmdstr,'$APPTYPE',AppTypeStr);
  1055. Replace(cmdstr,'$ASBIN',AsbinStr);
  1056. Replace(cmdstr,'$RELOC',RelocStr);
  1057. Replace(cmdstr,'$IMAGEBASE',ImageBaseStr);
  1058. Replace(cmdstr,'$STRIP',StripStr);
  1059. if not DefFile.Empty then
  1060. begin
  1061. DefFile.WriteFile;
  1062. Replace(cmdstr,'$DEF','-d '+maybequoted(deffile.fname));
  1063. end
  1064. else
  1065. Replace(cmdstr,'$DEF','');
  1066. success:=DoExec(FindUtil(utilsprefix+binstr),cmdstr,(i=1),false);
  1067. if not success then
  1068. break;
  1069. end;
  1070. end;
  1071. { Post process }
  1072. if success then
  1073. success:=PostProcessExecutable(current_module.sharedlibfilename^,true);
  1074. { Remove ReponseFile }
  1075. if (success) and not(cs_link_extern in aktglobalswitches) then
  1076. begin
  1077. RemoveFile(outputexedir+Info.ResName);
  1078. RemoveFile('base.$$$');
  1079. RemoveFile('exp.$$$');
  1080. RemoveFile('deffile.$$$');
  1081. end;
  1082. MakeSharedLibrary:=success; { otherwise a recursive call to link method }
  1083. end;
  1084. function tlinkerwin32.postprocessexecutable(const fn : string;isdll:boolean):boolean;
  1085. type
  1086. tdosheader = packed record
  1087. e_magic : word;
  1088. e_cblp : word;
  1089. e_cp : word;
  1090. e_crlc : word;
  1091. e_cparhdr : word;
  1092. e_minalloc : word;
  1093. e_maxalloc : word;
  1094. e_ss : word;
  1095. e_sp : word;
  1096. e_csum : word;
  1097. e_ip : word;
  1098. e_cs : word;
  1099. e_lfarlc : word;
  1100. e_ovno : word;
  1101. e_res : array[0..3] of word;
  1102. e_oemid : word;
  1103. e_oeminfo : word;
  1104. e_res2 : array[0..9] of word;
  1105. e_lfanew : longint;
  1106. end;
  1107. tpeheader = packed record
  1108. PEMagic : array[0..3] of char;
  1109. Machine : word;
  1110. NumberOfSections : word;
  1111. TimeDateStamp : longint;
  1112. PointerToSymbolTable : longint;
  1113. NumberOfSymbols : longint;
  1114. SizeOfOptionalHeader : word;
  1115. Characteristics : word;
  1116. Magic : word;
  1117. MajorLinkerVersion : byte;
  1118. MinorLinkerVersion : byte;
  1119. SizeOfCode : longint;
  1120. SizeOfInitializedData : longint;
  1121. SizeOfUninitializedData : longint;
  1122. AddressOfEntryPoint : longint;
  1123. BaseOfCode : longint;
  1124. BaseOfData : longint;
  1125. ImageBase : longint;
  1126. SectionAlignment : longint;
  1127. FileAlignment : longint;
  1128. MajorOperatingSystemVersion : word;
  1129. MinorOperatingSystemVersion : word;
  1130. MajorImageVersion : word;
  1131. MinorImageVersion : word;
  1132. MajorSubsystemVersion : word;
  1133. MinorSubsystemVersion : word;
  1134. Reserved1 : longint;
  1135. SizeOfImage : longint;
  1136. SizeOfHeaders : longint;
  1137. CheckSum : longint;
  1138. Subsystem : word;
  1139. DllCharacteristics : word;
  1140. SizeOfStackReserve : longint;
  1141. SizeOfStackCommit : longint;
  1142. SizeOfHeapReserve : longint;
  1143. SizeOfHeapCommit : longint;
  1144. LoaderFlags : longint;
  1145. NumberOfRvaAndSizes : longint;
  1146. DataDirectory : array[1..$80] of byte;
  1147. end;
  1148. tcoffsechdr=packed record
  1149. name : array[0..7] of char;
  1150. vsize : longint;
  1151. rvaofs : longint;
  1152. datalen : longint;
  1153. datapos : longint;
  1154. relocpos : longint;
  1155. lineno1 : longint;
  1156. nrelocs : word;
  1157. lineno2 : word;
  1158. flags : longint;
  1159. end;
  1160. psecfill=^TSecfill;
  1161. TSecfill=record
  1162. fillpos,
  1163. fillsize : longint;
  1164. next : psecfill;
  1165. end;
  1166. var
  1167. f : file;
  1168. cmdstr : string;
  1169. dosheader : tdosheader;
  1170. peheader : tpeheader;
  1171. firstsecpos,
  1172. maxfillsize,
  1173. l,peheaderpos : longint;
  1174. coffsec : tcoffsechdr;
  1175. secroot,hsecroot : psecfill;
  1176. zerobuf : pointer;
  1177. begin
  1178. postprocessexecutable:=false;
  1179. { when -s is used or it's a dll then quit }
  1180. if (cs_link_extern in aktglobalswitches) then
  1181. begin
  1182. case apptype of
  1183. app_gui :
  1184. cmdstr:='--subsystem gui';
  1185. app_cui :
  1186. cmdstr:='--subsystem console';
  1187. end;
  1188. if dllversion<>'' then
  1189. cmdstr:=cmdstr+' --version '+dllversion;
  1190. cmdstr:=cmdstr+' --input '+maybequoted(fn);
  1191. cmdstr:=cmdstr+' --stack '+tostr(stacksize);
  1192. DoExec(FindUtil(utilsprefix+'postw32'),cmdstr,false,false);
  1193. postprocessexecutable:=true;
  1194. exit;
  1195. end;
  1196. { open file }
  1197. assign(f,fn);
  1198. {$I-}
  1199. reset(f,1);
  1200. if ioresult<>0 then
  1201. Message1(execinfo_f_cant_open_executable,fn);
  1202. { read headers }
  1203. blockread(f,dosheader,sizeof(tdosheader));
  1204. peheaderpos:=dosheader.e_lfanew;
  1205. seek(f,peheaderpos);
  1206. blockread(f,peheader,sizeof(tpeheader));
  1207. { write info }
  1208. Message1(execinfo_x_codesize,tostr(peheader.SizeOfCode));
  1209. Message1(execinfo_x_initdatasize,tostr(peheader.SizeOfInitializedData));
  1210. Message1(execinfo_x_uninitdatasize,tostr(peheader.SizeOfUninitializedData));
  1211. { change stack size (PM) }
  1212. { I am not sure that the default value is adequate !! }
  1213. peheader.SizeOfStackReserve:=stacksize;
  1214. { change the header }
  1215. { sub system }
  1216. { gui=2 }
  1217. { cui=3 }
  1218. { wincegui=9 }
  1219. if target_info.system in [system_arm_wince,system_i386_wince] then
  1220. peheader.Subsystem:=9
  1221. else
  1222. case apptype of
  1223. app_gui :
  1224. peheader.Subsystem:=2;
  1225. app_cui :
  1226. peheader.Subsystem:=3;
  1227. end;
  1228. if dllversion<>'' then
  1229. begin
  1230. peheader.MajorImageVersion:=dllmajor;
  1231. peheader.MinorImageVersion:=dllminor;
  1232. end;
  1233. { reset timestamp }
  1234. peheader.TimeDateStamp:=0;
  1235. { write header back }
  1236. seek(f,peheaderpos);
  1237. blockwrite(f,peheader,sizeof(tpeheader));
  1238. if ioresult<>0 then
  1239. Message1(execinfo_f_cant_process_executable,fn);
  1240. seek(f,peheaderpos);
  1241. blockread(f,peheader,sizeof(tpeheader));
  1242. { write the value after the change }
  1243. Message1(execinfo_x_stackreserve,tostr(peheader.SizeOfStackReserve));
  1244. Message1(execinfo_x_stackcommit,tostr(peheader.SizeOfStackCommit));
  1245. { read section info }
  1246. maxfillsize:=0;
  1247. firstsecpos:=0;
  1248. secroot:=nil;
  1249. for l:=1 to peheader.NumberOfSections do
  1250. begin
  1251. blockread(f,coffsec,sizeof(tcoffsechdr));
  1252. if coffsec.datapos>0 then
  1253. begin
  1254. if secroot=nil then
  1255. firstsecpos:=coffsec.datapos;
  1256. new(hsecroot);
  1257. hsecroot^.fillpos:=coffsec.datapos+coffsec.vsize;
  1258. hsecroot^.fillsize:=coffsec.datalen-coffsec.vsize;
  1259. hsecroot^.next:=secroot;
  1260. secroot:=hsecroot;
  1261. if secroot^.fillsize>maxfillsize then
  1262. maxfillsize:=secroot^.fillsize;
  1263. end;
  1264. end;
  1265. if firstsecpos>0 then
  1266. begin
  1267. l:=firstsecpos-filepos(f);
  1268. if l>maxfillsize then
  1269. maxfillsize:=l;
  1270. end
  1271. else
  1272. l:=0;
  1273. { get zero buffer }
  1274. getmem(zerobuf,maxfillsize);
  1275. fillchar(zerobuf^,maxfillsize,0);
  1276. { zero from sectioninfo until first section }
  1277. blockwrite(f,zerobuf^,l);
  1278. { zero section alignments }
  1279. while assigned(secroot) do
  1280. begin
  1281. seek(f,secroot^.fillpos);
  1282. blockwrite(f,zerobuf^,secroot^.fillsize);
  1283. hsecroot:=secroot;
  1284. secroot:=secroot^.next;
  1285. dispose(hsecroot);
  1286. end;
  1287. freemem(zerobuf,maxfillsize);
  1288. close(f);
  1289. {$I+}
  1290. if ioresult<>0 then;
  1291. postprocessexecutable:=true;
  1292. end;
  1293. {****************************************************************************
  1294. TDLLScannerWin32
  1295. ****************************************************************************}
  1296. function tDLLScannerWin32.DOSstubOK(var x:cardinal):boolean;
  1297. begin
  1298. blockread(f,TheWord,2,loaded);
  1299. if loaded<>2 then
  1300. DOSstubOK:=false
  1301. else
  1302. begin
  1303. DOSstubOK:=(TheWord='MZ');
  1304. seek(f,$3C);
  1305. blockread(f,x,4,loaded);
  1306. if(loaded<>4)or(longint(x)>filesize(f))then
  1307. DOSstubOK:=false;
  1308. end;
  1309. end;
  1310. function TDLLScannerWin32.FindDLL(const s:string;var founddll:string):boolean;
  1311. var
  1312. sysdir : string;
  1313. Found : boolean;
  1314. begin
  1315. Found:=false;
  1316. { Look for DLL in:
  1317. 1. Current dir
  1318. 2. Library Path
  1319. 3. windir,windir/system,windir/system32 }
  1320. Found:=FindFile(s,'.'+source_info.DirSep,founddll);
  1321. if (not found) then
  1322. Found:=librarysearchpath.FindFile(s,founddll);
  1323. if (not found) then
  1324. begin
  1325. sysdir:=FixPath(GetEnv('windir'),false);
  1326. Found:=FindFile(s,sysdir+';'+sysdir+'system'+source_info.DirSep+';'+sysdir+'system32'+source_info.DirSep,founddll);
  1327. end;
  1328. if (not found) then
  1329. begin
  1330. message1(exec_w_libfile_not_found,s);
  1331. FoundDll:=s;
  1332. end;
  1333. FindDll:=Found;
  1334. end;
  1335. function tDLLScannerWin32.ExtractDllName(Const Name : string) : string;
  1336. var n : string;
  1337. begin
  1338. n:=Upper(SplitExtension(Name));
  1339. if (n='.DLL') or (n='.DRV') or (n='.EXE') then
  1340. ExtractDllName:=Name
  1341. else
  1342. ExtractDllName:=Name+target_info.sharedlibext;
  1343. end;
  1344. function tDLLScannerWin32.isSuitableFileType(x:cardinal):longbool;
  1345. begin
  1346. seek(f,x);
  1347. blockread(f,TheWord,2,loaded);
  1348. isSuitableFileType:=(loaded=2)and(TheWord='PE');
  1349. end;
  1350. function tDLLScannerWin32.GetEdata(HeaderEntry:cardinal):longbool;
  1351. type
  1352. TObjInfo=packed record
  1353. ObjName:array[0..7]of char;
  1354. VirtSize,
  1355. VirtAddr,
  1356. RawSize,
  1357. RawOffset,
  1358. Reloc,
  1359. LineNum:cardinal;
  1360. RelCount,
  1361. LineCount:word;
  1362. flags:cardinal;
  1363. end;
  1364. var
  1365. i:cardinal;
  1366. ObjOfs:cardinal;
  1367. Obj:TObjInfo;
  1368. APE_obj,APE_Optsize:word;
  1369. ExportRVA:cardinal;
  1370. delta:cardinal;
  1371. const
  1372. IMAGE_SCN_CNT_CODE=$00000020;
  1373. var
  1374. _d:dirstr;
  1375. _n:namestr;
  1376. _e:extstr;
  1377. function isUsedFunction(name:pchar):longbool;
  1378. var
  1379. hp:tExternalsItem;
  1380. begin
  1381. isUsedFunction:=false;
  1382. hp:=tExternalsItem(current_module.Externals.first);
  1383. while assigned(hp)do
  1384. begin
  1385. if(assigned(hp.data))and(not hp.found)then
  1386. if hp.data^=StrPas(name)then
  1387. begin
  1388. isUsedFunction:=true;
  1389. hp.found:=true;
  1390. exit;
  1391. end;
  1392. hp:=tExternalsItem(hp.next);
  1393. end;
  1394. end;
  1395. procedure Store(index:cardinal;name:pchar;isData:longbool);
  1396. begin
  1397. if not isUsedFunction(name)then
  1398. exit;
  1399. if not(current_module.uses_imports) then
  1400. begin
  1401. current_module.uses_imports:=true;
  1402. importlib.preparelib(current_module.modulename^);
  1403. end;
  1404. if IsData then
  1405. timportlibwin32(importlib).importvariable_str(name,_n,name)
  1406. else
  1407. timportlibwin32(importlib).importprocedure_str(name,_n,index,name);
  1408. end;
  1409. procedure ProcessEdata;
  1410. type
  1411. a8=array[0..7]of char;
  1412. function GetSectionName(rva:cardinal;var Flags:cardinal):a8;
  1413. var
  1414. i:cardinal;
  1415. LocObjOfs:cardinal;
  1416. LocObj:TObjInfo;
  1417. begin
  1418. GetSectionName:='';
  1419. Flags:=0;
  1420. LocObjOfs:=APE_OptSize+HeaderOffset+24;
  1421. for i:=1 to APE_obj do
  1422. begin
  1423. seek(f,LocObjOfs);
  1424. blockread(f,LocObj,sizeof(LocObj));
  1425. if(rva>=LocObj.VirtAddr)and(rva<=LocObj.VirtAddr+LocObj.RawSize)then
  1426. begin
  1427. GetSectionName:=a8(LocObj.ObjName);
  1428. Flags:=LocObj.flags;
  1429. end;
  1430. end;
  1431. end;
  1432. var
  1433. j,Fl:cardinal;
  1434. ulongval,procEntry:cardinal;
  1435. Ordinal:word;
  1436. isData:longbool;
  1437. ExpDir:packed record
  1438. flag,
  1439. stamp:cardinal;
  1440. Major,
  1441. Minor:word;
  1442. Name,
  1443. Base,
  1444. NumFuncs,
  1445. NumNames,
  1446. AddrFuncs,
  1447. AddrNames,
  1448. AddrOrds:cardinal;
  1449. end;
  1450. begin
  1451. with Obj do
  1452. begin
  1453. seek(f,RawOffset+delta);
  1454. blockread(f,ExpDir,sizeof(ExpDir));
  1455. fsplit(impname,_d,_n,_e);
  1456. for j:=0 to pred(ExpDir.NumNames)do
  1457. begin
  1458. { Don't know why but this gives serious problems with overflow checking on }
  1459. {$IFOPT Q+}
  1460. {$DEFINE OVERFLOW_CHECK_WAS_ON}
  1461. {$ENDIF}
  1462. {$Q-}
  1463. seek(f,RawOffset-VirtAddr+ExpDir.AddrOrds+j*2);
  1464. blockread(f,Ordinal,2);
  1465. seek(f,RawOffset-VirtAddr+ExpDir.AddrFuncs+cardinal(Ordinal)*4);
  1466. blockread(f,ProcEntry,4);
  1467. seek(f,RawOffset-VirtAddr+ExpDir.AddrNames+j*4);
  1468. blockread(f,ulongval,4);
  1469. seek(f,RawOffset-VirtAddr+ulongval);
  1470. blockread(f,cstring,sizeof(cstring));
  1471. isData:=GetSectionName(procentry,Fl)='';
  1472. {$IFDEF OVERFLOW_CHECK_WAS_ON}
  1473. {$Q+}
  1474. {$ENDIF}
  1475. if not isData then
  1476. isData:=Fl and IMAGE_SCN_CNT_CODE<>IMAGE_SCN_CNT_CODE;
  1477. Store(succ(Ordinal),cstring,isData);
  1478. end;
  1479. end;
  1480. end;
  1481. begin
  1482. GetEdata:=false;
  1483. seek(f,HeaderEntry+120);
  1484. blockread(f,ExportRVA,4);
  1485. seek(f,HeaderEntry+6);
  1486. blockread(f,APE_Obj,2);
  1487. seek(f,HeaderEntry+20);
  1488. blockread(f,APE_OptSize,2);
  1489. ObjOfs:=APE_OptSize+HeaderOffset+24;
  1490. for i:=1 to APE_obj do
  1491. begin
  1492. seek(f,ObjOfs);
  1493. blockread(f,Obj,sizeof(Obj));
  1494. inc(ObjOfs,sizeof(Obj));
  1495. with Obj do
  1496. if(VirtAddr<=ExportRva)and(ExportRva<VirtAddr+VirtSize)then
  1497. begin
  1498. delta:=ExportRva-VirtAddr;
  1499. ProcessEdata;
  1500. GetEdata:=true;
  1501. end;
  1502. end;
  1503. end;
  1504. function tDLLScannerWin32.scan(const binname:string):longbool;
  1505. var
  1506. OldFileMode:longint;
  1507. hs,
  1508. foundimp : string;
  1509. begin
  1510. Scan:=false;
  1511. { is there already an import library the we will use that one }
  1512. if FindLibraryFile(binname,target_info.staticClibprefix,target_info.staticClibext,foundimp) then
  1513. exit;
  1514. { check if we can find the dll }
  1515. hs:=AddExtension(binname,target_info.sharedlibext);
  1516. if not FindDll(hs,impname) then
  1517. exit;
  1518. { read the dll file }
  1519. assign(f,impname);
  1520. OldFileMode:=filemode;
  1521. filemode:=0;
  1522. reset(f,1);
  1523. filemode:=OldFileMode;
  1524. if not DOSstubOK(HeaderOffset)then
  1525. scan:=false
  1526. else if not isSuitableFileType(HeaderOffset)then
  1527. scan:=false
  1528. else
  1529. scan:=GetEdata(HeaderOffset);
  1530. close(f);
  1531. end;
  1532. {*****************************************************************************
  1533. Initialize
  1534. *****************************************************************************}
  1535. initialization
  1536. {$ifdef i386}
  1537. RegisterExternalLinker(system_i386_win32_info,TLinkerWin32);
  1538. RegisterImport(system_i386_win32,TImportLibWin32);
  1539. RegisterExport(system_i386_win32,TExportLibWin32);
  1540. RegisterDLLScanner(system_i386_win32,TDLLScannerWin32);
  1541. RegisterRes(res_gnu_windres_info);
  1542. RegisterTarget(system_i386_win32_info);
  1543. RegisterExternalLinker(system_i386_wince_info,TLinkerWin32);
  1544. RegisterImport(system_i386_wince,TImportLibWin32);
  1545. RegisterExport(system_i386_wince,TExportLibWin32);
  1546. RegisterDLLScanner(system_i386_wince,TDLLScannerWin32);
  1547. RegisterTarget(system_i386_wince_info);
  1548. {$endif i386}
  1549. {$ifdef x86_64}
  1550. RegisterExternalLinker(system_x64_win64_info,TLinkerWin32);
  1551. RegisterImport(system_x86_64_win64,TImportLibWin32);
  1552. RegisterExport(system_x86_64_win64,TExportLibWin32);
  1553. RegisterDLLScanner(system_x86_64_win64,TDLLScannerWin32);
  1554. RegisterRes(res_gnu_windres_info);
  1555. RegisterTarget(system_x64_win64_info);
  1556. {$endif x86_64}
  1557. {$ifdef arm}
  1558. RegisterExternalLinker(system_arm_wince_info,TLinkerWin32);
  1559. RegisterImport(system_arm_wince,TImportLibWin32);
  1560. RegisterExport(system_arm_wince,TExportLibWin32);
  1561. RegisterRes(res_gnu_windres_info);
  1562. RegisterTarget(system_arm_wince_info);
  1563. {$endif arm}
  1564. end.