t_android.pas 16 KB

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