t_win.pas 57 KB

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