t_win.pas 57 KB

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