t_win.pas 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691
  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[al_imports]=nil then
  94. asmlist[al_imports]:=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[al_imports],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[al_imports].concat(tai_direct.create(p));
  204. p:=strpnew(#9+'import '+hp2.func^+' '+hp1.dllname^+' '+hp2.name^);
  205. asmlist[al_imports].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[al_imports].concat(Tai_cutobject.Create_begin);
  239. new_section(asmlist[al_imports],sec_idata2,'',0);
  240. asmlist[al_imports].concat(Tai_label.Create(lhead));
  241. { pointer to procedure names }
  242. asmlist[al_imports].concat(Tai_const.Create_rva_sym(lidata4));
  243. { two empty entries follow }
  244. asmlist[al_imports].concat(Tai_const.Create_32bit(0));
  245. asmlist[al_imports].concat(Tai_const.Create_32bit(0));
  246. { pointer to dll name }
  247. asmlist[al_imports].concat(Tai_const.Create_rva_sym(lname));
  248. { pointer to fixups }
  249. asmlist[al_imports].concat(Tai_const.Create_rva_sym(lidata5));
  250. { first write the name references }
  251. new_section(asmlist[al_imports],sec_idata4,'',0);
  252. asmlist[al_imports].concat(Tai_const.Create_32bit(0));
  253. asmlist[al_imports].concat(Tai_label.Create(lidata4));
  254. { then the addresses and create also the indirect jump }
  255. new_section(asmlist[al_imports],sec_idata5,'',0);
  256. asmlist[al_imports].concat(Tai_const.Create_32bit(0));
  257. asmlist[al_imports].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[al_imports].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 al_code, insert a code section in the
  272. al_imports to reduce the amount of .s files (PFV) }
  273. new_section(asmlist[al_imports],sec_code,'',0);
  274. {$IfDef GDB}
  275. if (cs_debuginfo in aktmoduleswitches) then
  276. asmlist[al_imports].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[al_imports].concat(Tai_symbol.Createname_global(mangledstring,AT_FUNCTION,0));
  283. {$ifdef ARM}
  284. reference_reset_symbol(href,lpcode,0);
  285. asmlist[al_imports].concat(Taicpu.op_reg_ref(A_LDR,NR_R12,href));
  286. reference_reset_base(href,NR_R12,0);
  287. asmlist[al_imports].concat(Taicpu.op_reg_ref(A_LDR,NR_R15,href));
  288. asmlist[al_imports].concat(Tai_label.Create(lpcode));
  289. reference_reset_symbol(href,lcode,0);
  290. asmlist[al_imports].concat(tai_const.create_sym_offset(href.symbol,href.offset));
  291. {$else ARM}
  292. reference_reset_symbol(href,lcode,0);
  293. asmlist[al_imports].concat(Taicpu.Op_ref(A_JMP,S_NO,href));
  294. asmlist[al_imports].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[al_imports]);
  299. {$EndIf GDB}
  300. end;
  301. { create head link }
  302. new_section(asmlist[al_imports],sec_idata7,'',0);
  303. asmlist[al_imports].concat(Tai_const.Create_rva_sym(lhead));
  304. { fixup }
  305. objectlibrary.getlabel(tasmlabel(hp2.lab));
  306. new_section(asmlist[al_imports],sec_idata4,'',0);
  307. asmlist[al_imports].concat(Tai_const.Create_rva_sym(hp2.lab));
  308. { add jump field to al_imports }
  309. new_section(asmlist[al_imports],sec_idata5,'',0);
  310. if hp2.is_var then
  311. asmlist[al_imports].concat(Tai_symbol.Createname_global(hp2.func^,AT_FUNCTION,0))
  312. else
  313. asmlist[al_imports].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[al_imports].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[al_imports].concat(tai_symbol.createname(importname,AT_FUNCTION,4));
  338. end;
  339. end;
  340. {$endif GDB}
  341. if hp2.name^<>'' then
  342. asmlist[al_imports].concat(Tai_const.Create_rva_sym(hp2.lab))
  343. else
  344. asmlist[al_imports].concat(Tai_const.Create_32bit(longint($80000000) or longint(hp2.ordnr)));
  345. { finally the import information }
  346. new_section(asmlist[al_imports],sec_idata6,'',0);
  347. asmlist[al_imports].concat(Tai_label.Create(hp2.lab));
  348. asmlist[al_imports].concat(Tai_const.Create_16bit(hp2.ordnr));
  349. asmlist[al_imports].concat(Tai_string.Create(hp2.name^+#0));
  350. asmlist[al_imports].concat(Tai_align.Create_op(2,0));
  351. hp2:=twin32imported_item(hp2.next);
  352. end;
  353. { write final section }
  354. asmlist[al_imports].concat(Tai_cutobject.Create_end);
  355. { end of name references }
  356. new_section(asmlist[al_imports],sec_idata4,'',0);
  357. asmlist[al_imports].concat(Tai_const.Create_32bit(0));
  358. { end if addresses }
  359. new_section(asmlist[al_imports],sec_idata5,'',0);
  360. asmlist[al_imports].concat(Tai_const.Create_32bit(0));
  361. { dllname }
  362. new_section(asmlist[al_imports],sec_idata7,'',0);
  363. asmlist[al_imports].concat(Tai_label.Create(lname));
  364. asmlist[al_imports].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 al_code for the jumps }
  389. new_section(asmlist[al_imports],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[al_imports],sec_idata2,'',0);
  395. { pointer to procedure names }
  396. asmlist[al_imports].concat(Tai_const.Create_rva_sym(l2));
  397. { two empty entries follow }
  398. asmlist[al_imports].concat(Tai_const.Create_32bit(0));
  399. asmlist[al_imports].concat(Tai_const.Create_32bit(0));
  400. { pointer to dll name }
  401. asmlist[al_imports].concat(Tai_const.Create_rva_sym(l1));
  402. { pointer to fixups }
  403. asmlist[al_imports].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[al_imports],sec_idata4,'',0);
  408. asmlist[al_imports].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[al_imports].concat(Tai_const.Create_rva_sym(hp2.lab))
  415. else
  416. asmlist[al_imports].concat(Tai_const.Create_32bit(longint($80000000) or hp2.ordnr));
  417. hp2:=twin32imported_item(hp2.next);
  418. end;
  419. { finalize the names ... }
  420. asmlist[al_imports].concat(Tai_const.Create_32bit(0));
  421. { then the addresses and create also the indirect jump }
  422. new_section(asmlist[al_imports],sec_idata5,'',0);
  423. asmlist[al_imports].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 al_code }
  435. new_section(asmlist[al_imports],sec_code,'',0);
  436. {$IfDef GDB}
  437. if (cs_debuginfo in aktmoduleswitches) then
  438. asmlist[al_imports].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[al_imports].concat(Tai_symbol.Createname_global(mangledstring,AT_FUNCTION,0));
  445. {$ifdef ARM}
  446. reference_reset_symbol(href,l5,0);
  447. asmlist[al_imports].concat(Taicpu.op_reg_ref(A_LDR,NR_R12,href));
  448. reference_reset_base(href,NR_R12,0);
  449. asmlist[al_imports].concat(Taicpu.op_reg_ref(A_LDR,NR_R15,href));
  450. asmlist[al_imports].concat(Tai_label.Create(l5));
  451. reference_reset_symbol(href,l4,0);
  452. asmlist[al_imports].concat(tai_const.create_sym_offset(href.symbol,href.offset));
  453. {$else ARM}
  454. reference_reset_symbol(href,l4,0);
  455. asmlist[al_imports].concat(Taicpu.Op_ref(A_JMP,S_NO,href));
  456. asmlist[al_imports].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[al_imports]);
  461. {$EndIf GDB}
  462. { add jump field to al_imports }
  463. new_section(asmlist[al_imports],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[al_imports].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[al_imports].concat(tai_symbol.createname(importname,AT_FUNCTION,4));
  488. end;
  489. end;
  490. {$endif GDB}
  491. asmlist[al_imports].concat(Tai_label.Create(l4));
  492. end
  493. else
  494. begin
  495. asmlist[al_imports].concat(Tai_symbol.Createname_global(hp2.func^,AT_DATA,0));
  496. end;
  497. asmlist[al_imports].concat(Tai_const.Create_rva_sym(hp2.lab));
  498. hp2:=twin32imported_item(hp2.next);
  499. end;
  500. { finalize the addresses }
  501. asmlist[al_imports].concat(Tai_const.Create_32bit(0));
  502. { finally the import information }
  503. new_section(asmlist[al_imports],sec_idata6,'',0);
  504. hp2:=twin32imported_item(hp1.imported_items.first);
  505. while assigned(hp2) do
  506. begin
  507. asmlist[al_imports].concat(Tai_label.Create(hp2.lab));
  508. { the ordinal number }
  509. asmlist[al_imports].concat(Tai_const.Create_16bit(hp2.ordnr));
  510. asmlist[al_imports].concat(Tai_string.Create(hp2.name^+#0));
  511. asmlist[al_imports].concat(Tai_align.Create_op(2,0));
  512. hp2:=twin32imported_item(hp2.next);
  513. end;
  514. { create import dll name }
  515. new_section(asmlist[al_imports],sec_idata7,'',0);
  516. asmlist[al_imports].concat(Tai_label.Create(l1));
  517. asmlist[al_imports].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[al_exports]=nil then
  527. asmlist[al_exports]:=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[al_exports],sec_edata,'',0);
  672. { create label to reference from main so smartlink will include
  673. the .edata section }
  674. asmlist[al_exports].concat(Tai_symbol.Create_global(edatalabel,0));
  675. { export flags }
  676. asmlist[al_exports].concat(Tai_const.Create_32bit(0));
  677. { date/time stamp }
  678. asmlist[al_exports].concat(Tai_const.Create_32bit(0));
  679. { major version }
  680. asmlist[al_exports].concat(Tai_const.Create_16bit(0));
  681. { minor version }
  682. asmlist[al_exports].concat(Tai_const.Create_16bit(0));
  683. { pointer to dll name }
  684. asmlist[al_exports].concat(Tai_const.Create_rva_sym(dll_name_label));
  685. { ordinal base normally set to 1 }
  686. asmlist[al_exports].concat(Tai_const.Create_32bit(ordinal_base));
  687. { number of entries }
  688. asmlist[al_exports].concat(Tai_const.Create_32bit(entries));
  689. { number of named entries }
  690. asmlist[al_exports].concat(Tai_const.Create_32bit(named_entries));
  691. { address of export address table }
  692. asmlist[al_exports].concat(Tai_const.Create_rva_sym(export_address_table));
  693. { address of name pointer pointers }
  694. asmlist[al_exports].concat(Tai_const.Create_rva_sym(export_name_table_pointers));
  695. { address of ordinal number pointers }
  696. asmlist[al_exports].concat(Tai_const.Create_rva_sym(export_ordinal_table));
  697. { the name }
  698. asmlist[al_exports].concat(Tai_label.Create(dll_name_label));
  699. if st='' then
  700. asmlist[al_exports].concat(Tai_string.Create(current_module.modulename^+target_info.sharedlibext+#0))
  701. else
  702. asmlist[al_exports].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[al_exports].concatlist(address_table);
  769. asmlist[al_exports].concatlist(name_table_pointers);
  770. asmlist[al_exports].concatlist(ordinal_table);
  771. asmlist[al_exports].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[al_exports],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[al_exports].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_native :
  1184. cmdstr:='--subsystem native';
  1185. app_gui :
  1186. cmdstr:='--subsystem gui';
  1187. app_cui :
  1188. cmdstr:='--subsystem console';
  1189. end;
  1190. if dllversion<>'' then
  1191. cmdstr:=cmdstr+' --version '+dllversion;
  1192. cmdstr:=cmdstr+' --input '+maybequoted(fn);
  1193. cmdstr:=cmdstr+' --stack '+tostr(stacksize);
  1194. DoExec(FindUtil(utilsprefix+'postw32'),cmdstr,false,false);
  1195. postprocessexecutable:=true;
  1196. exit;
  1197. end;
  1198. { open file }
  1199. assign(f,fn);
  1200. {$I-}
  1201. reset(f,1);
  1202. if ioresult<>0 then
  1203. Message1(execinfo_f_cant_open_executable,fn);
  1204. { read headers }
  1205. blockread(f,dosheader,sizeof(tdosheader));
  1206. peheaderpos:=dosheader.e_lfanew;
  1207. seek(f,peheaderpos);
  1208. blockread(f,peheader,sizeof(tpeheader));
  1209. { write info }
  1210. Message1(execinfo_x_codesize,tostr(peheader.SizeOfCode));
  1211. Message1(execinfo_x_initdatasize,tostr(peheader.SizeOfInitializedData));
  1212. Message1(execinfo_x_uninitdatasize,tostr(peheader.SizeOfUninitializedData));
  1213. { change stack size (PM) }
  1214. { I am not sure that the default value is adequate !! }
  1215. peheader.SizeOfStackReserve:=stacksize;
  1216. { change the header }
  1217. { sub system }
  1218. { gui=2 }
  1219. { cui=3 }
  1220. { wincegui=9 }
  1221. if target_info.system in [system_arm_wince,system_i386_wince] then
  1222. peheader.Subsystem:=9
  1223. else
  1224. case apptype of
  1225. app_native :
  1226. peheader.Subsystem:=1;
  1227. app_gui :
  1228. peheader.Subsystem:=2;
  1229. app_cui :
  1230. peheader.Subsystem:=3;
  1231. end;
  1232. if dllversion<>'' then
  1233. begin
  1234. peheader.MajorImageVersion:=dllmajor;
  1235. peheader.MinorImageVersion:=dllminor;
  1236. end;
  1237. { reset timestamp }
  1238. peheader.TimeDateStamp:=0;
  1239. { write header back }
  1240. seek(f,peheaderpos);
  1241. blockwrite(f,peheader,sizeof(tpeheader));
  1242. if ioresult<>0 then
  1243. Message1(execinfo_f_cant_process_executable,fn);
  1244. seek(f,peheaderpos);
  1245. blockread(f,peheader,sizeof(tpeheader));
  1246. { write the value after the change }
  1247. Message1(execinfo_x_stackreserve,tostr(peheader.SizeOfStackReserve));
  1248. Message1(execinfo_x_stackcommit,tostr(peheader.SizeOfStackCommit));
  1249. { read section info }
  1250. maxfillsize:=0;
  1251. firstsecpos:=0;
  1252. secroot:=nil;
  1253. for l:=1 to peheader.NumberOfSections do
  1254. begin
  1255. blockread(f,coffsec,sizeof(tcoffsechdr));
  1256. if coffsec.datapos>0 then
  1257. begin
  1258. if secroot=nil then
  1259. firstsecpos:=coffsec.datapos;
  1260. new(hsecroot);
  1261. hsecroot^.fillpos:=coffsec.datapos+coffsec.vsize;
  1262. hsecroot^.fillsize:=coffsec.datalen-coffsec.vsize;
  1263. hsecroot^.next:=secroot;
  1264. secroot:=hsecroot;
  1265. if secroot^.fillsize>maxfillsize then
  1266. maxfillsize:=secroot^.fillsize;
  1267. end;
  1268. end;
  1269. if firstsecpos>0 then
  1270. begin
  1271. l:=firstsecpos-filepos(f);
  1272. if l>maxfillsize then
  1273. maxfillsize:=l;
  1274. end
  1275. else
  1276. l:=0;
  1277. { get zero buffer }
  1278. getmem(zerobuf,maxfillsize);
  1279. fillchar(zerobuf^,maxfillsize,0);
  1280. { zero from sectioninfo until first section }
  1281. blockwrite(f,zerobuf^,l);
  1282. { zero section alignments }
  1283. while assigned(secroot) do
  1284. begin
  1285. seek(f,secroot^.fillpos);
  1286. blockwrite(f,zerobuf^,secroot^.fillsize);
  1287. hsecroot:=secroot;
  1288. secroot:=secroot^.next;
  1289. dispose(hsecroot);
  1290. end;
  1291. freemem(zerobuf,maxfillsize);
  1292. close(f);
  1293. {$I+}
  1294. if ioresult<>0 then;
  1295. postprocessexecutable:=true;
  1296. end;
  1297. {****************************************************************************
  1298. TDLLScannerWin32
  1299. ****************************************************************************}
  1300. function tDLLScannerWin32.DOSstubOK(var x:cardinal):boolean;
  1301. begin
  1302. blockread(f,TheWord,2,loaded);
  1303. if loaded<>2 then
  1304. DOSstubOK:=false
  1305. else
  1306. begin
  1307. DOSstubOK:=(TheWord='MZ');
  1308. seek(f,$3C);
  1309. blockread(f,x,4,loaded);
  1310. if(loaded<>4)or(longint(x)>filesize(f))then
  1311. DOSstubOK:=false;
  1312. end;
  1313. end;
  1314. function TDLLScannerWin32.FindDLL(const s:string;var founddll:string):boolean;
  1315. var
  1316. sysdir : string;
  1317. Found : boolean;
  1318. begin
  1319. Found:=false;
  1320. { Look for DLL in:
  1321. 1. Current dir
  1322. 2. Library Path
  1323. 3. windir,windir/system,windir/system32 }
  1324. Found:=FindFile(s,'.'+source_info.DirSep,founddll);
  1325. if (not found) then
  1326. Found:=librarysearchpath.FindFile(s,founddll);
  1327. if (not found) then
  1328. begin
  1329. sysdir:=FixPath(GetEnv('windir'),false);
  1330. Found:=FindFile(s,sysdir+';'+sysdir+'system'+source_info.DirSep+';'+sysdir+'system32'+source_info.DirSep,founddll);
  1331. end;
  1332. if (not found) then
  1333. begin
  1334. message1(exec_w_libfile_not_found,s);
  1335. FoundDll:=s;
  1336. end;
  1337. FindDll:=Found;
  1338. end;
  1339. function tDLLScannerWin32.ExtractDllName(Const Name : string) : string;
  1340. var n : string;
  1341. begin
  1342. n:=Upper(SplitExtension(Name));
  1343. if (n='.DLL') or (n='.DRV') or (n='.EXE') then
  1344. ExtractDllName:=Name
  1345. else
  1346. ExtractDllName:=Name+target_info.sharedlibext;
  1347. end;
  1348. function tDLLScannerWin32.isSuitableFileType(x:cardinal):longbool;
  1349. begin
  1350. seek(f,x);
  1351. blockread(f,TheWord,2,loaded);
  1352. isSuitableFileType:=(loaded=2)and(TheWord='PE');
  1353. end;
  1354. function tDLLScannerWin32.GetEdata(HeaderEntry:cardinal):longbool;
  1355. type
  1356. TObjInfo=packed record
  1357. ObjName:array[0..7]of char;
  1358. VirtSize,
  1359. VirtAddr,
  1360. RawSize,
  1361. RawOffset,
  1362. Reloc,
  1363. LineNum:cardinal;
  1364. RelCount,
  1365. LineCount:word;
  1366. flags:cardinal;
  1367. end;
  1368. var
  1369. i:cardinal;
  1370. ObjOfs:cardinal;
  1371. Obj:TObjInfo;
  1372. APE_obj,APE_Optsize:word;
  1373. ExportRVA:cardinal;
  1374. delta:cardinal;
  1375. const
  1376. IMAGE_SCN_CNT_CODE=$00000020;
  1377. var
  1378. _d:dirstr;
  1379. _n:namestr;
  1380. _e:extstr;
  1381. function isUsedFunction(name:pchar):longbool;
  1382. var
  1383. hp:tExternalsItem;
  1384. begin
  1385. isUsedFunction:=false;
  1386. hp:=tExternalsItem(current_module.Externals.first);
  1387. while assigned(hp)do
  1388. begin
  1389. if(assigned(hp.data))and(not hp.found)then
  1390. if hp.data^=StrPas(name)then
  1391. begin
  1392. isUsedFunction:=true;
  1393. hp.found:=true;
  1394. exit;
  1395. end;
  1396. hp:=tExternalsItem(hp.next);
  1397. end;
  1398. end;
  1399. procedure Store(index:cardinal;name:pchar;isData:longbool);
  1400. begin
  1401. if not isUsedFunction(name)then
  1402. exit;
  1403. if not(current_module.uses_imports) then
  1404. begin
  1405. current_module.uses_imports:=true;
  1406. importlib.preparelib(current_module.modulename^);
  1407. end;
  1408. if IsData then
  1409. timportlibwin32(importlib).importvariable_str(name,_n,name)
  1410. else
  1411. timportlibwin32(importlib).importprocedure_str(name,_n,index,name);
  1412. end;
  1413. procedure ProcessEdata;
  1414. type
  1415. a8=array[0..7]of char;
  1416. function GetSectionName(rva:cardinal;var Flags:cardinal):a8;
  1417. var
  1418. i:cardinal;
  1419. LocObjOfs:cardinal;
  1420. LocObj:TObjInfo;
  1421. begin
  1422. GetSectionName:='';
  1423. Flags:=0;
  1424. LocObjOfs:=APE_OptSize+HeaderOffset+24;
  1425. for i:=1 to APE_obj do
  1426. begin
  1427. seek(f,LocObjOfs);
  1428. blockread(f,LocObj,sizeof(LocObj));
  1429. if(rva>=LocObj.VirtAddr)and(rva<=LocObj.VirtAddr+LocObj.RawSize)then
  1430. begin
  1431. GetSectionName:=a8(LocObj.ObjName);
  1432. Flags:=LocObj.flags;
  1433. end;
  1434. end;
  1435. end;
  1436. var
  1437. j,Fl:cardinal;
  1438. ulongval,procEntry:cardinal;
  1439. Ordinal:word;
  1440. isData:longbool;
  1441. ExpDir:packed record
  1442. flag,
  1443. stamp:cardinal;
  1444. Major,
  1445. Minor:word;
  1446. Name,
  1447. Base,
  1448. NumFuncs,
  1449. NumNames,
  1450. AddrFuncs,
  1451. AddrNames,
  1452. AddrOrds:cardinal;
  1453. end;
  1454. begin
  1455. with Obj do
  1456. begin
  1457. seek(f,RawOffset+delta);
  1458. blockread(f,ExpDir,sizeof(ExpDir));
  1459. fsplit(impname,_d,_n,_e);
  1460. for j:=0 to pred(ExpDir.NumNames)do
  1461. begin
  1462. { Don't know why but this gives serious problems with overflow checking on }
  1463. {$IFOPT Q+}
  1464. {$DEFINE OVERFLOW_CHECK_WAS_ON}
  1465. {$ENDIF}
  1466. {$Q-}
  1467. seek(f,RawOffset-VirtAddr+ExpDir.AddrOrds+j*2);
  1468. blockread(f,Ordinal,2);
  1469. seek(f,RawOffset-VirtAddr+ExpDir.AddrFuncs+cardinal(Ordinal)*4);
  1470. blockread(f,ProcEntry,4);
  1471. seek(f,RawOffset-VirtAddr+ExpDir.AddrNames+j*4);
  1472. blockread(f,ulongval,4);
  1473. seek(f,RawOffset-VirtAddr+ulongval);
  1474. blockread(f,cstring,sizeof(cstring));
  1475. isData:=GetSectionName(procentry,Fl)='';
  1476. {$IFDEF OVERFLOW_CHECK_WAS_ON}
  1477. {$Q+}
  1478. {$ENDIF}
  1479. if not isData then
  1480. isData:=Fl and IMAGE_SCN_CNT_CODE<>IMAGE_SCN_CNT_CODE;
  1481. Store(succ(Ordinal),cstring,isData);
  1482. end;
  1483. end;
  1484. end;
  1485. begin
  1486. GetEdata:=false;
  1487. seek(f,HeaderEntry+120);
  1488. blockread(f,ExportRVA,4);
  1489. seek(f,HeaderEntry+6);
  1490. blockread(f,APE_Obj,2);
  1491. seek(f,HeaderEntry+20);
  1492. blockread(f,APE_OptSize,2);
  1493. ObjOfs:=APE_OptSize+HeaderOffset+24;
  1494. for i:=1 to APE_obj do
  1495. begin
  1496. seek(f,ObjOfs);
  1497. blockread(f,Obj,sizeof(Obj));
  1498. inc(ObjOfs,sizeof(Obj));
  1499. with Obj do
  1500. if(VirtAddr<=ExportRva)and(ExportRva<VirtAddr+VirtSize)then
  1501. begin
  1502. delta:=ExportRva-VirtAddr;
  1503. ProcessEdata;
  1504. GetEdata:=true;
  1505. end;
  1506. end;
  1507. end;
  1508. function tDLLScannerWin32.scan(const binname:string):longbool;
  1509. var
  1510. OldFileMode:longint;
  1511. hs,
  1512. foundimp : string;
  1513. begin
  1514. Scan:=false;
  1515. { is there already an import library the we will use that one }
  1516. if FindLibraryFile(binname,target_info.staticClibprefix,target_info.staticClibext,foundimp) then
  1517. exit;
  1518. { check if we can find the dll }
  1519. hs:=AddExtension(binname,target_info.sharedlibext);
  1520. if not FindDll(hs,impname) then
  1521. exit;
  1522. { read the dll file }
  1523. assign(f,impname);
  1524. OldFileMode:=filemode;
  1525. filemode:=0;
  1526. reset(f,1);
  1527. filemode:=OldFileMode;
  1528. if not DOSstubOK(HeaderOffset)then
  1529. scan:=false
  1530. else if not isSuitableFileType(HeaderOffset)then
  1531. scan:=false
  1532. else
  1533. scan:=GetEdata(HeaderOffset);
  1534. close(f);
  1535. end;
  1536. {*****************************************************************************
  1537. Initialize
  1538. *****************************************************************************}
  1539. initialization
  1540. {$ifdef i386}
  1541. RegisterExternalLinker(system_i386_win32_info,TLinkerWin32);
  1542. RegisterImport(system_i386_win32,TImportLibWin32);
  1543. RegisterExport(system_i386_win32,TExportLibWin32);
  1544. RegisterDLLScanner(system_i386_win32,TDLLScannerWin32);
  1545. RegisterRes(res_gnu_windres_info);
  1546. RegisterTarget(system_i386_win32_info);
  1547. RegisterExternalLinker(system_i386_wince_info,TLinkerWin32);
  1548. RegisterImport(system_i386_wince,TImportLibWin32);
  1549. RegisterExport(system_i386_wince,TExportLibWin32);
  1550. RegisterDLLScanner(system_i386_wince,TDLLScannerWin32);
  1551. RegisterTarget(system_i386_wince_info);
  1552. {$endif i386}
  1553. {$ifdef x86_64}
  1554. RegisterExternalLinker(system_x64_win64_info,TLinkerWin32);
  1555. RegisterImport(system_x86_64_win64,TImportLibWin32);
  1556. RegisterExport(system_x86_64_win64,TExportLibWin32);
  1557. RegisterDLLScanner(system_x86_64_win64,TDLLScannerWin32);
  1558. RegisterRes(res_gnu_windres_info);
  1559. RegisterTarget(system_x64_win64_info);
  1560. {$endif x86_64}
  1561. {$ifdef arm}
  1562. RegisterExternalLinker(system_arm_wince_info,TLinkerWin32);
  1563. RegisterImport(system_arm_wince,TImportLibWin32);
  1564. RegisterExport(system_arm_wince,TExportLibWin32);
  1565. RegisterRes(res_gnu_windres_info);
  1566. RegisterTarget(system_arm_wince_info);
  1567. {$endif arm}
  1568. end.