t_win.pas 57 KB

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