2
0

t_android.pas 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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 -z relro --build-id $OPT -L. -T $RES -o $EXE';
  144. ExeCmd[1]:=s + ' --entry=_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. {$ifdef cpu64bitalu}
  151. DynamicLinker:='/system/bin/linker64';
  152. {$else}
  153. DynamicLinker:='/system/bin/linker';
  154. {$endif cpu64bitalu}
  155. end;
  156. end;
  157. procedure TLinkerAndroid.LoadPredefinedLibraryOrder;
  158. // put your linkorder/linkalias overrides here.
  159. // Note: assumes only called when reordering/aliasing is used.
  160. Begin
  161. if not (cs_link_no_default_lib_order in current_settings.globalswitches) Then
  162. Begin
  163. LinkLibraryOrder.add('gcc','',15);
  164. LinkLibraryOrder.add('c','',100);
  165. LinkLibraryOrder.add('gmon','',120);
  166. LinkLibraryOrder.add('dl','',140);
  167. LinkLibraryOrder.add('pthread','',160);
  168. end;
  169. End;
  170. Procedure TLinkerAndroid.InitSysInitUnitName;
  171. begin
  172. reorder := ReOrderEntries;
  173. if current_module.islibrary then
  174. prtobj:='dllprt0'
  175. else
  176. prtobj:='prt0';
  177. end;
  178. Function TLinkerAndroid.WriteResponseFile(isdll:boolean) : Boolean;
  179. Var
  180. linkres : TLinkRes;
  181. i : longint;
  182. HPath : TCmdStrListItem;
  183. s,s1 : TCmdStr;
  184. begin
  185. result:=False;
  186. { Always link to libc }
  187. AddSharedLibrary('c');
  188. { Open link.res file }
  189. LinkRes:=TLinkRes.Create(outputexedir+Info.ResName,true);
  190. with linkres do
  191. begin
  192. { Write path to search libraries }
  193. HPath:=TCmdStrListItem(current_module.locallibrarysearchpath.First);
  194. while assigned(HPath) do
  195. begin
  196. Add('SEARCH_DIR('+maybequoted(HPath.Str)+')');
  197. HPath:=TCmdStrListItem(HPath.Next);
  198. end;
  199. HPath:=TCmdStrListItem(LibrarySearchPath.First);
  200. while assigned(HPath) do
  201. begin
  202. Add('SEARCH_DIR('+maybequoted(HPath.Str)+')');
  203. HPath:=TCmdStrListItem(HPath.Next);
  204. end;
  205. { force local symbol resolution (i.e., inside the shared }
  206. { library itself) for all non-exorted symbols, otherwise }
  207. { several RTL symbols of FPC-compiled shared libraries }
  208. { will be bound to those of a single shared library or }
  209. { to the main program }
  210. if isdll or (cs_create_pic in current_settings.moduleswitches) then
  211. begin
  212. add('VERSION');
  213. add('{');
  214. add(' {');
  215. if not texportlibunix(exportlib).exportedsymnames.empty then
  216. begin
  217. add(' global:');
  218. repeat
  219. add(' '+texportlibunix(exportlib).exportedsymnames.getfirst+';');
  220. until texportlibunix(exportlib).exportedsymnames.empty;
  221. end;
  222. add(' local:');
  223. add(' *;');
  224. add(' };');
  225. add('}');
  226. end;
  227. StartSection('INPUT(');
  228. { add objectfiles, start with prt0 always }
  229. if not (target_info.system in systems_internal_sysinit) and (prtobj<>'') then
  230. AddFileName(maybequoted(FindObjectFile(prtobj,'',false)));
  231. { Add libc startup object file }
  232. if isdll then
  233. s:='crtbegin_so.o'
  234. else
  235. if cs_link_staticflag in current_settings.globalswitches then
  236. s:='crtbegin_static.o'
  237. else
  238. s:='crtbegin_dynamic.o';
  239. librarysearchpath.FindFile(s,false,s1);
  240. AddFileName(maybequoted(s1));
  241. { main objectfiles }
  242. while not ObjectFiles.Empty do
  243. begin
  244. s:=ObjectFiles.GetFirst;
  245. if s<>'' then
  246. AddFileName(maybequoted(s));
  247. end;
  248. EndSection(')');
  249. { Write staticlibraries }
  250. if not StaticLibFiles.Empty then
  251. begin
  252. Add('GROUP(');
  253. While not StaticLibFiles.Empty do
  254. begin
  255. S:=StaticLibFiles.GetFirst;
  256. AddFileName(maybequoted(s))
  257. end;
  258. Add(')');
  259. end;
  260. // we must reorder here because the result could empty sharedlibfiles
  261. if reorder Then
  262. ExpandAndApplyOrder(SharedLibFiles);
  263. // after this point addition of shared libs not allowed.
  264. if not SharedLibFiles.Empty then
  265. begin
  266. if (SharedLibFiles.Count<>1) or reorder then
  267. begin
  268. Add('INPUT(');
  269. While not SharedLibFiles.Empty do
  270. begin
  271. S:=SharedLibFiles.GetFirst;
  272. i:=Pos(target_info.sharedlibext,S);
  273. if i>0 then
  274. Delete(S,i,255);
  275. Add('-l'+s);
  276. end;
  277. Add(')');
  278. end;
  279. if (cs_link_staticflag in current_settings.globalswitches) or
  280. (not reorder) then
  281. begin
  282. Add('GROUP(');
  283. { when we have -static for the linker the we also need libgcc }
  284. if (cs_link_staticflag in current_settings.globalswitches) then
  285. begin
  286. Add('-lgcc');
  287. if librarysearchpath.FindFile('libgcc_eh.a',false,s1) then
  288. Add('-lgcc_eh');
  289. end;
  290. { be sure that libc is the last lib }
  291. if not reorder then
  292. Add('-lc');
  293. Add(')');
  294. end;
  295. end;
  296. { objects which must be at the end }
  297. { Add libc finalization object file }
  298. Add('INPUT(');
  299. if isdll then
  300. s:='crtend_so.o'
  301. else
  302. s:='crtend_android.o';
  303. librarysearchpath.FindFile(s,false,s1);
  304. AddFileName(maybequoted(s1));
  305. Add(')');
  306. { Additions to the linker script }
  307. add('SECTIONS');
  308. add('{');
  309. add(' .data :');
  310. add(' {');
  311. { extra by FPC }
  312. add(' KEEP (*(.fpc .fpc.n_version .fpc.n_links))');
  313. add(' }');
  314. add('}');
  315. add('INSERT AFTER .data1');
  316. // Define different aliases for normal and JNI libraries
  317. if FJNIOnLoadName <> '' then
  318. begin
  319. s:=FJNIOnLoadName;
  320. s1:='FPC_JNI_LIB_MAIN_ANDROID';
  321. end
  322. else
  323. begin
  324. s:='0';
  325. s1:='PASCALMAIN';
  326. end;
  327. add('FPC_JNI_ON_LOAD = ' + s + ';');
  328. add('FPC_LIB_MAIN_ANDROID = ' + s1 + ';');
  329. { Write and Close response }
  330. writetodisk;
  331. Free;
  332. end;
  333. WriteResponseFile:=True;
  334. end;
  335. function tlinkerandroid.DoLink(IsSharedLib: boolean): boolean;
  336. var
  337. i: longint;
  338. binstr, cmdstr: TCmdStr;
  339. s, opts, outname: string;
  340. success: boolean;
  341. begin
  342. Result:=False;
  343. if IsSharedLib then
  344. outname:=current_module.sharedlibfilename
  345. else
  346. outname:=current_module.exefilename;
  347. if not(cs_link_nolink in current_settings.globalswitches) then
  348. Message1(exec_i_linking, outname);
  349. opts:='';
  350. if not IsSharedLib and (cs_create_pic in current_settings.moduleswitches) then
  351. opts:=opts + ' --pic-executable';
  352. if (cs_link_strip in current_settings.globalswitches) and
  353. not (cs_link_separate_dbg_file in current_settings.globalswitches) then
  354. opts:=opts + ' -s';
  355. if (cs_link_map in current_settings.globalswitches) then
  356. opts:=opts + ' -Map '+maybequoted(ChangeFileExt(outname,'.map'));
  357. if create_smartlink_sections then
  358. opts:=opts + ' --gc-sections';
  359. if (cs_link_staticflag in current_settings.globalswitches) then
  360. opts:=opts + ' -static'
  361. else
  362. if cshared then
  363. opts:=opts + ' -call_shared';
  364. if rlinkpath<>'' then
  365. opts:=opts+' --rpath-link '+rlinkpath;
  366. if not IsSharedLib then
  367. begin
  368. opts:=opts + ' --dynamic-linker ' + Info.DynamicLinker;
  369. { create dynamic symbol table? }
  370. if HasExports then
  371. opts:=opts+' -E';
  372. end;
  373. opts:=Trim(opts + ' ' + Info.ExtraOptions);
  374. { Write used files and libraries }
  375. WriteResponseFile(IsSharedLib);
  376. { Call linker }
  377. if IsSharedLib then
  378. s:=Info.DllCmd[1]
  379. else
  380. s:=Info.ExeCmd[1];
  381. SplitBinCmd(s, binstr, cmdstr);
  382. Replace(cmdstr,'$EXE',maybequoted(outname));
  383. Replace(cmdstr,'$OPT',opts);
  384. Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  385. if IsSharedLib then
  386. Replace(cmdstr,'$SONAME',ExtractFileName(outname));
  387. binstr:=FindUtil(utilsprefix+BinStr);
  388. { We should use BFD version of LD, since GOLD version does not support INSERT command in linker scripts }
  389. if binstr <> '' then begin
  390. { Checking if ld.bfd exists }
  391. s:=ChangeFileExt(binstr, '.bfd' + source_info.exeext);
  392. if FileExists(s, True) then
  393. binstr:=s;
  394. end;
  395. success:=DoExec(binstr,CmdStr,true,false);
  396. { Create external .dbg file with debuginfo }
  397. if success and (cs_link_separate_dbg_file in current_settings.globalswitches) then
  398. begin
  399. for i:=1 to 3 do
  400. begin
  401. SplitBinCmd(Info.ExtDbgCmd[i],binstr,cmdstr);
  402. Replace(cmdstr,'$EXE',maybequoted(outname));
  403. Replace(cmdstr,'$DBGFN',maybequoted(extractfilename(current_module.dbgfilename)));
  404. Replace(cmdstr,'$DBG',maybequoted(current_module.dbgfilename));
  405. success:=DoExec(FindUtil(utilsprefix+BinStr),CmdStr,true,false);
  406. if not success then
  407. break;
  408. end;
  409. end;
  410. { Remove ReponseFile }
  411. if (success) and not(cs_link_nolink in current_settings.globalswitches) then
  412. DeleteFile(outputexedir+Info.ResName);
  413. Result:=success; { otherwise a recursive call to link method }
  414. end;
  415. function TLinkerAndroid.MakeExecutable:boolean;
  416. begin
  417. Result:=DoLink(False);
  418. end;
  419. Function TLinkerAndroid.MakeSharedLibrary:boolean;
  420. begin
  421. Result:=DoLink(True);
  422. end;
  423. {*****************************************************************************
  424. Initialize
  425. *****************************************************************************}
  426. initialization
  427. RegisterLinker(ld_android,TLinkerAndroid);
  428. {$ifdef ARM}
  429. RegisterImport(system_arm_android,timportlibandroid);
  430. RegisterExport(system_arm_android,texportlibandroid);
  431. RegisterTarget(system_arm_android_info);
  432. {$endif ARM}
  433. {$ifdef AARCH64}
  434. RegisterImport(system_aarch64_android,timportlibandroid);
  435. RegisterExport(system_aarch64_android,texportlibandroid);
  436. RegisterTarget(system_aarch64_android_info);
  437. {$endif AARCH64}
  438. {$ifdef I386}
  439. RegisterImport(system_i386_android,timportlibandroid);
  440. RegisterExport(system_i386_android,texportlibandroid);
  441. RegisterTarget(system_i386_android_info);
  442. {$endif I386}
  443. {$ifdef X86_64}
  444. RegisterImport(system_x86_64_android,timportlibandroid);
  445. RegisterExport(system_x86_64_android,texportlibandroid);
  446. RegisterTarget(system_x86_64_android_info);
  447. {$endif X86_64}
  448. {$ifdef MIPSEL}
  449. RegisterImport(system_mipsel_android,timportlibandroid);
  450. RegisterExport(system_mipsel_android,texportlibandroid);
  451. RegisterTarget(system_mipsel_android_info);
  452. {$endif MIPSEL}
  453. RegisterRes(res_elf_info,TWinLikeResourceFile);
  454. end.