t_win.pas 57 KB

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