t_android.pas 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. {
  2. Copyright (c) 1998-2008 by Peter Vreman
  3. This unit implements support import,export,link routines
  4. for the Android 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_android;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. globtype,
  23. aasmdata,
  24. symsym,symdef,ppu,
  25. import,export,expunix,link;
  26. type
  27. timportlibandroid=class(timportlib)
  28. procedure generatelib;override;
  29. end;
  30. { texportlibandroid }
  31. texportlibandroid=class(texportlibunix)
  32. public
  33. procedure setfininame(list: TAsmList; const s: string); override;
  34. procedure exportprocedure(hp: texported_item); override;
  35. procedure generatelib; override;
  36. end;
  37. { tlinkerandroid }
  38. tlinkerandroid=class(texternallinker)
  39. private
  40. prtobj : string[80];
  41. reorder : boolean;
  42. FJNIOnLoadName: TSymStr;
  43. Function WriteResponseFile(isdll:boolean) : Boolean;
  44. function DoLink(IsSharedLib: boolean): boolean;
  45. public
  46. constructor Create;override;
  47. procedure SetDefaultInfo;override;
  48. procedure InitSysInitUnitName;override;
  49. function MakeExecutable:boolean;override;
  50. function MakeSharedLibrary:boolean;override;
  51. procedure LoadPredefinedLibraryOrder; override;
  52. end;
  53. implementation
  54. uses
  55. SysUtils,
  56. cutils,cfileutl,cclasses,
  57. verbose,systems,globals,
  58. symconst,cscript,
  59. fmodule,
  60. aasmbase,aasmtai,aasmcpu,cpubase,hlcgcpu,hlcgobj,
  61. cgbase,cgobj,cgutils,ogbase,ncgutil,
  62. comprsrc,
  63. rescmn, i_android
  64. ;
  65. const
  66. SJNI_OnLoad = 'JNI_OnLoad';
  67. {*****************************************************************************
  68. TIMPORTLIBANDROID
  69. *****************************************************************************}
  70. procedure timportlibandroid.generatelib;
  71. var
  72. i : longint;
  73. ImportLibrary : TImportLibrary;
  74. begin
  75. for i:=0 to current_module.ImportLibraryList.Count-1 do
  76. begin
  77. ImportLibrary:=TImportLibrary(current_module.ImportLibraryList[i]);
  78. current_module.linkothersharedlibs.add(ImportLibrary.Name,link_always);
  79. end;
  80. end;
  81. {*****************************************************************************
  82. TEXPORTLIBANDROID
  83. *****************************************************************************}
  84. procedure texportlibandroid.setfininame(list: TAsmList; const s: string);
  85. begin
  86. { the problem with not having a .fini section is that a finalization
  87. routine in regular code can get "smart" linked away -> reference it
  88. just like the debug info }
  89. new_section(list,sec_fpc,'links',0);
  90. list.concat(Tai_const.Createname(s,0));
  91. inherited setfininame(list,s);
  92. end;
  93. procedure texportlibandroid.exportprocedure(hp: texported_item);
  94. begin
  95. {
  96. Android versions prior to 4.1 do not support recursive dlopen() calls.
  97. Therefore if a shared library is loaded by JVM ( using dlopen() ),
  98. it is not possible to use dlopen() in a units initialization code -
  99. dlopen() simply hangs.
  100. To workaround this issue, if a library exports JNI_OnLoad(), then
  101. no unit initialization is performed during library load.
  102. The initialization is called when JVM has loaded the library and calls
  103. JNI_OnLoad().
  104. }
  105. // Check for the JNI_OnLoad export
  106. if current_module.islibrary and not hp.is_var and assigned(hp.sym) and
  107. (hp.sym.typ = procsym) and (eo_name in hp.options) and
  108. (hp.name^ = SJNI_OnLoad) and (tprocsym(hp.sym).procdeflist.count = 1) then
  109. begin
  110. // Save the JNI_OnLoad procdef
  111. tlinkerandroid(Linker).FJNIOnLoadName:=tprocdef(tprocsym(hp.sym).procdeflist[0]).mangledname;
  112. hp.Free;
  113. exit;
  114. end;
  115. inherited exportprocedure(hp);
  116. end;
  117. procedure texportlibandroid.generatelib;
  118. begin
  119. inherited generatelib;
  120. if tlinkerandroid(Linker).FJNIOnLoadName = '' then
  121. exit;
  122. // If JNI_OnLoad is exported, export a system proxy function instead
  123. create_hlcodegen;
  124. new_section(current_asmdata.asmlists[al_procedures],sec_code,'',0);
  125. hlcg.g_external_wrapper(current_asmdata.asmlists[al_procedures],nil,SJNI_OnLoad,'FPC_JNI_ON_LOAD_PROXY',true);
  126. destroy_hlcodegen;
  127. exportedsymnames.insert(SJNI_OnLoad);
  128. end;
  129. {*****************************************************************************
  130. TLINKERANDROID
  131. *****************************************************************************}
  132. Constructor TLinkerAndroid.Create;
  133. begin
  134. Inherited Create;
  135. end;
  136. procedure TLinkerAndroid.SetDefaultInfo;
  137. var
  138. s: string;
  139. begin
  140. with Info do
  141. begin
  142. { Specify correct max-page-size and common-page-size to prevent big gaps between sections in resulting executable }
  143. s:='ld -z max-page-size=0x1000 -z common-page-size=0x1000 -z noexecstack -z now $OPT -L. -T $RES -o $EXE';
  144. ExeCmd[1]:=s + ' --entry=_fpc_start';
  145. DllCmd[1]:=s + ' -shared -soname $SONAME';
  146. DllCmd[2]:='strip --strip-unneeded $EXE';
  147. ExtDbgCmd[1]:='objcopy --only-keep-debug $EXE $DBG';
  148. ExtDbgCmd[2]:='objcopy --add-gnu-debuglink=$DBG $EXE';
  149. ExtDbgCmd[3]:='strip --strip-unneeded $EXE';
  150. DynamicLinker:='/system/bin/linker';
  151. end;
  152. end;
  153. procedure TLinkerAndroid.LoadPredefinedLibraryOrder;
  154. // put your linkorder/linkalias overrides here.
  155. // Note: assumes only called when reordering/aliasing is used.
  156. Begin
  157. if not (cs_link_no_default_lib_order in current_settings.globalswitches) Then
  158. Begin
  159. LinkLibraryOrder.add('gcc','',15);
  160. LinkLibraryOrder.add('c','',100);
  161. LinkLibraryOrder.add('gmon','',120);
  162. LinkLibraryOrder.add('dl','',140);
  163. LinkLibraryOrder.add('pthread','',160);
  164. end;
  165. End;
  166. Procedure TLinkerAndroid.InitSysInitUnitName;
  167. begin
  168. reorder := ReOrderEntries;
  169. if current_module.islibrary then
  170. prtobj:='dllprt0'
  171. else
  172. prtobj:='prt0';
  173. end;
  174. Function TLinkerAndroid.WriteResponseFile(isdll:boolean) : Boolean;
  175. Var
  176. linkres : TLinkRes;
  177. i : longint;
  178. HPath : TCmdStrListItem;
  179. s,s1 : TCmdStr;
  180. begin
  181. result:=False;
  182. { Always link to libc }
  183. AddSharedLibrary('c');
  184. { Open link.res file }
  185. LinkRes:=TLinkRes.Create(outputexedir+Info.ResName,true);
  186. with linkres do
  187. begin
  188. { Write path to search libraries }
  189. HPath:=TCmdStrListItem(current_module.locallibrarysearchpath.First);
  190. while assigned(HPath) do
  191. begin
  192. Add('SEARCH_DIR('+maybequoted(HPath.Str)+')');
  193. HPath:=TCmdStrListItem(HPath.Next);
  194. end;
  195. HPath:=TCmdStrListItem(LibrarySearchPath.First);
  196. while assigned(HPath) do
  197. begin
  198. Add('SEARCH_DIR('+maybequoted(HPath.Str)+')');
  199. HPath:=TCmdStrListItem(HPath.Next);
  200. end;
  201. { force local symbol resolution (i.e., inside the shared }
  202. { library itself) for all non-exorted symbols, otherwise }
  203. { several RTL symbols of FPC-compiled shared libraries }
  204. { will be bound to those of a single shared library or }
  205. { to the main program }
  206. if isdll or (cs_create_pic in current_settings.moduleswitches) then
  207. begin
  208. add('VERSION');
  209. add('{');
  210. add(' {');
  211. if not texportlibunix(exportlib).exportedsymnames.empty then
  212. begin
  213. add(' global:');
  214. repeat
  215. add(' '+texportlibunix(exportlib).exportedsymnames.getfirst+';');
  216. until texportlibunix(exportlib).exportedsymnames.empty;
  217. end;
  218. add(' local:');
  219. add(' *;');
  220. add(' };');
  221. add('}');
  222. end;
  223. StartSection('INPUT(');
  224. { add objectfiles, start with prt0 always }
  225. if not (target_info.system in systems_internal_sysinit) and (prtobj<>'') then
  226. AddFileName(maybequoted(FindObjectFile(prtobj,'',false)));
  227. { Add libc startup object file }
  228. if isdll then
  229. s:='crtbegin_so.o'
  230. else
  231. if cs_link_staticflag in current_settings.globalswitches then
  232. s:='crtbegin_static.o'
  233. else
  234. s:='crtbegin_dynamic.o';
  235. librarysearchpath.FindFile(s,false,s1);
  236. AddFileName(maybequoted(s1));
  237. { main objectfiles }
  238. while not ObjectFiles.Empty do
  239. begin
  240. s:=ObjectFiles.GetFirst;
  241. if s<>'' then
  242. AddFileName(maybequoted(s));
  243. end;
  244. EndSection(')');
  245. { Write staticlibraries }
  246. if not StaticLibFiles.Empty then
  247. begin
  248. Add('GROUP(');
  249. While not StaticLibFiles.Empty do
  250. begin
  251. S:=StaticLibFiles.GetFirst;
  252. AddFileName(maybequoted(s))
  253. end;
  254. Add(')');
  255. end;
  256. // we must reorder here because the result could empty sharedlibfiles
  257. if reorder Then
  258. ExpandAndApplyOrder(SharedLibFiles);
  259. // after this point addition of shared libs not allowed.
  260. if not SharedLibFiles.Empty then
  261. begin
  262. if (SharedLibFiles.Count<>1) or reorder then
  263. begin
  264. Add('INPUT(');
  265. While not SharedLibFiles.Empty do
  266. begin
  267. S:=SharedLibFiles.GetFirst;
  268. i:=Pos(target_info.sharedlibext,S);
  269. if i>0 then
  270. Delete(S,i,255);
  271. Add('-l'+s);
  272. end;
  273. Add(')');
  274. end;
  275. if (cs_link_staticflag in current_settings.globalswitches) or
  276. (not reorder) then
  277. begin
  278. Add('GROUP(');
  279. { when we have -static for the linker the we also need libgcc }
  280. if (cs_link_staticflag in current_settings.globalswitches) then
  281. begin
  282. Add('-lgcc');
  283. if librarysearchpath.FindFile('libgcc_eh.a',false,s1) then
  284. Add('-lgcc_eh');
  285. end;
  286. { be sure that libc is the last lib }
  287. if not reorder then
  288. Add('-lc');
  289. Add(')');
  290. end;
  291. end;
  292. { objects which must be at the end }
  293. { Add libc finalization object file }
  294. Add('INPUT(');
  295. if isdll then
  296. s:='crtend_so.o'
  297. else
  298. s:='crtend_android.o';
  299. librarysearchpath.FindFile(s,false,s1);
  300. AddFileName(maybequoted(s1));
  301. Add(')');
  302. { Additions to the linker script }
  303. add('SECTIONS');
  304. add('{');
  305. add(' .data :');
  306. add(' {');
  307. { extra by FPC }
  308. add(' KEEP (*(.fpc .fpc.n_version .fpc.n_links))');
  309. add(' }');
  310. add('}');
  311. add('INSERT BEFORE .data1');
  312. // Define different aliases for normal and JNI libraries
  313. if FJNIOnLoadName <> '' then
  314. begin
  315. s:=FJNIOnLoadName;
  316. s1:='FPC_JNI_LIB_MAIN_ANDROID';
  317. end
  318. else
  319. begin
  320. s:='0';
  321. s1:='PASCALMAIN';
  322. end;
  323. add('FPC_JNI_ON_LOAD = ' + s + ';');
  324. add('FPC_LIB_MAIN_ANDROID = ' + s1 + ';');
  325. { Write and Close response }
  326. writetodisk;
  327. Free;
  328. end;
  329. WriteResponseFile:=True;
  330. end;
  331. function tlinkerandroid.DoLink(IsSharedLib: boolean): boolean;
  332. var
  333. i: longint;
  334. binstr, cmdstr: TCmdStr;
  335. s, opts, outname: string;
  336. success: boolean;
  337. begin
  338. Result:=False;
  339. if IsSharedLib then
  340. outname:=current_module.sharedlibfilename
  341. else
  342. outname:=current_module.exefilename;
  343. if not(cs_link_nolink in current_settings.globalswitches) then
  344. Message1(exec_i_linking, outname);
  345. opts:='';
  346. if not IsSharedLib and (cs_create_pic in current_settings.moduleswitches) then
  347. opts:=opts + ' --pic-executable';
  348. if (cs_link_strip in current_settings.globalswitches) and
  349. not (cs_link_separate_dbg_file in current_settings.globalswitches) then
  350. opts:=opts + ' -s';
  351. if (cs_link_map in current_settings.globalswitches) then
  352. opts:=opts + ' -Map '+maybequoted(ChangeFileExt(outname,'.map'));
  353. if create_smartlink_sections then
  354. opts:=opts + ' --gc-sections';
  355. if (cs_link_staticflag in current_settings.globalswitches) then
  356. opts:=opts + ' -static'
  357. else
  358. if cshared then
  359. opts:=opts + ' -call_shared';
  360. if rlinkpath<>'' then
  361. opts:=opts+' --rpath-link '+rlinkpath;
  362. if not IsSharedLib then
  363. begin
  364. opts:=opts + ' --dynamic-linker ' + Info.DynamicLinker;
  365. { create dynamic symbol table? }
  366. if HasExports then
  367. opts:=opts+' -E';
  368. end;
  369. opts:=Trim(opts + ' ' + Info.ExtraOptions);
  370. { Write used files and libraries }
  371. WriteResponseFile(IsSharedLib);
  372. { Call linker }
  373. if IsSharedLib then
  374. s:=Info.DllCmd[1]
  375. else
  376. s:=Info.ExeCmd[1];
  377. SplitBinCmd(s, binstr, cmdstr);
  378. Replace(cmdstr,'$EXE',maybequoted(outname));
  379. Replace(cmdstr,'$OPT',opts);
  380. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  381. if IsSharedLib then
  382. Replace(cmdstr,'$SONAME',ExtractFileName(outname));
  383. binstr:=FindUtil(utilsprefix+BinStr);
  384. { We should use BFD version of LD, since GOLD version does not support INSERT command in linker scripts }
  385. if binstr <> '' then begin
  386. { Checking if ld.bfd exists }
  387. s:=ChangeFileExt(binstr, '.bfd' + source_info.exeext);
  388. if FileExists(s, True) then
  389. binstr:=s;
  390. end;
  391. success:=DoExec(binstr,CmdStr,true,false);
  392. { Create external .dbg file with debuginfo }
  393. if success and (cs_link_separate_dbg_file in current_settings.globalswitches) then
  394. begin
  395. for i:=1 to 3 do
  396. begin
  397. SplitBinCmd(Info.ExtDbgCmd[i],binstr,cmdstr);
  398. Replace(cmdstr,'$EXE',maybequoted(outname));
  399. Replace(cmdstr,'$DBGFN',maybequoted(extractfilename(current_module.dbgfilename)));
  400. Replace(cmdstr,'$DBG',maybequoted(current_module.dbgfilename));
  401. success:=DoExec(FindUtil(utilsprefix+BinStr),CmdStr,true,false);
  402. if not success then
  403. break;
  404. end;
  405. end;
  406. { Remove ReponseFile }
  407. if (success) and not(cs_link_nolink in current_settings.globalswitches) then
  408. DeleteFile(outputexedir+Info.ResName);
  409. Result:=success; { otherwise a recursive call to link method }
  410. end;
  411. function TLinkerAndroid.MakeExecutable:boolean;
  412. begin
  413. Result:=DoLink(False);
  414. end;
  415. Function TLinkerAndroid.MakeSharedLibrary:boolean;
  416. begin
  417. Result:=DoLink(True);
  418. end;
  419. {*****************************************************************************
  420. Initialize
  421. *****************************************************************************}
  422. initialization
  423. RegisterLinker(ld_android,TLinkerAndroid);
  424. {$ifdef ARM}
  425. RegisterImport(system_arm_android,timportlibandroid);
  426. RegisterExport(system_arm_android,texportlibandroid);
  427. RegisterTarget(system_arm_android_info);
  428. {$endif ARM}
  429. {$ifdef I386}
  430. RegisterImport(system_i386_android,timportlibandroid);
  431. RegisterExport(system_i386_android,texportlibandroid);
  432. RegisterTarget(system_i386_android_info);
  433. {$endif I386}
  434. {$ifdef MIPSEL}
  435. RegisterImport(system_mipsel_android,timportlibandroid);
  436. RegisterExport(system_mipsel_android,texportlibandroid);
  437. RegisterTarget(system_mipsel_android_info);
  438. {$endif MIPSEL}
  439. RegisterRes(res_elf_info,TWinLikeResourceFile);
  440. end.