summaryrefslogtreecommitdiff
path: root/compiler/systems/t_android.pas
blob: 39da9c40f86efe59916562c987cb52dc11147769 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
{
    Copyright (c) 1998-2008 by Peter Vreman

    This unit implements support import,export,link routines
    for the Android target

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

 ****************************************************************************
}
unit t_android;

{$i fpcdefs.inc}

interface

  uses
    globtype,
    aasmdata,
    symsym,symdef,ppu,
    import,export,expunix,link;

  type
    timportlibandroid=class(timportlib)
      procedure generatelib;override;
    end;

    { texportlibandroid }

    texportlibandroid=class(texportlibunix)
    public
      procedure setfininame(list: TAsmList; const s: string); override;
      procedure exportprocedure(hp: texported_item); override;
      procedure generatelib; override;
    end;

    { tlinkerandroid }

    tlinkerandroid=class(texternallinker)
    private
      prtobj  : string[80];
      reorder : boolean;
      FJNIOnLoadName: TSymStr;
      Function  WriteResponseFile(isdll:boolean) : Boolean;
      function DoLink(IsSharedLib: boolean): boolean;
    public
      constructor Create;override;
      procedure SetDefaultInfo;override;
      procedure InitSysInitUnitName;override;
      function  MakeExecutable:boolean;override;
      function  MakeSharedLibrary:boolean;override;
      procedure LoadPredefinedLibraryOrder; override;
    end;


implementation

  uses
    SysUtils,
    cutils,cfileutl,cclasses,
    verbose,systems,globals,
    symconst,cscript,
    fmodule,
    aasmbase,aasmtai,aasmcpu,cpubase,hlcgcpu,hlcgobj,
    cgbase,cgobj,cgutils,ogbase,ncgutil,
    comprsrc,
    rescmn, i_android
    ;

const
  SJNI_OnLoad = 'JNI_OnLoad';

{*****************************************************************************
                               TIMPORTLIBANDROID
*****************************************************************************}

    procedure timportlibandroid.generatelib;
      var
        i : longint;
        ImportLibrary : TImportLibrary;
      begin
        for i:=0 to current_module.ImportLibraryList.Count-1 do
          begin
            ImportLibrary:=TImportLibrary(current_module.ImportLibraryList[i]);
            current_module.linkothersharedlibs.add(ImportLibrary.Name,link_always);
          end;
      end;


{*****************************************************************************
                               TEXPORTLIBANDROID
*****************************************************************************}

    procedure texportlibandroid.setfininame(list: TAsmList; const s: string);
      begin
        { the problem with not having a .fini section is that a finalization
          routine in regular code can get "smart" linked away -> reference it
          just like the debug info }
        new_section(list,sec_fpc,'links',0);
        list.concat(Tai_const.Createname(s,0));
        inherited setfininame(list,s);
      end;

    procedure texportlibandroid.exportprocedure(hp: texported_item);
      begin
        {
          Android versions prior to 4.1 do not support recursive dlopen() calls.
          Therefore if a shared library is loaded by JVM ( using dlopen() ),
          it is not possible to use dlopen() in a units initialization code -
          dlopen() simply hangs.
          To workaround this issue, if a library exports JNI_OnLoad(), then
          no unit initialization is performed during library load.
          The initialization is called when JVM has loaded the library and calls
          JNI_OnLoad().
        }
        // Check for the JNI_OnLoad export
        if current_module.islibrary and not hp.is_var and assigned(hp.sym) and
           (hp.sym.typ = procsym) and (eo_name in hp.options) and
           (hp.name^ = SJNI_OnLoad) and (tprocsym(hp.sym).procdeflist.count = 1) then
          begin
            // Save the JNI_OnLoad procdef
            tlinkerandroid(Linker).FJNIOnLoadName:=tprocdef(tprocsym(hp.sym).procdeflist[0]).mangledname;
            hp.Free;
            exit;
          end;
        inherited exportprocedure(hp);
      end;

    procedure texportlibandroid.generatelib;
      begin
        inherited generatelib;
        if tlinkerandroid(Linker).FJNIOnLoadName = '' then
          exit;
        // If JNI_OnLoad is exported, export a system proxy function instead
        create_hlcodegen;
        new_section(current_asmdata.asmlists[al_procedures],sec_code,'',0);
        hlcg.g_external_wrapper(current_asmdata.asmlists[al_procedures],nil,SJNI_OnLoad,'FPC_JNI_ON_LOAD_PROXY',true);
        destroy_hlcodegen;
        exportedsymnames.insert(SJNI_OnLoad);
      end;

{*****************************************************************************
                                  TLINKERANDROID
*****************************************************************************}

Constructor TLinkerAndroid.Create;
begin
  Inherited Create;
end;


procedure TLinkerAndroid.SetDefaultInfo;
var
  s: string;
begin
  with Info do
   begin
     { Specify correct max-page-size and common-page-size to prevent big gaps between sections in resulting executable }
     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';
     ExeCmd[1]:=s + ' --entry=_start';
     DllCmd[1]:=s + ' -shared -soname $SONAME';
     DllCmd[2]:='strip --strip-unneeded $EXE';
     ExtDbgCmd[1]:='objcopy --only-keep-debug $EXE $DBG';
     ExtDbgCmd[2]:='objcopy --add-gnu-debuglink=$DBG $EXE';
     ExtDbgCmd[3]:='strip --strip-unneeded $EXE';
{$ifdef cpu64bitalu}
     DynamicLinker:='/system/bin/linker64';
{$else}
     DynamicLinker:='/system/bin/linker';
{$endif cpu64bitalu}
   end;
end;


procedure TLinkerAndroid.LoadPredefinedLibraryOrder;
// put your linkorder/linkalias overrides here.
// Note: assumes only called when reordering/aliasing is used.
Begin
   if not (cs_link_no_default_lib_order in  current_settings.globalswitches) Then
        Begin
          LinkLibraryOrder.add('gcc','',15);
          LinkLibraryOrder.add('c','',100);
          LinkLibraryOrder.add('gmon','',120);
          LinkLibraryOrder.add('dl','',140);
          LinkLibraryOrder.add('pthread','',160);
         end;
End;

Procedure TLinkerAndroid.InitSysInitUnitName;
begin
  reorder := ReOrderEntries;
  if current_module.islibrary then
    prtobj:='dllprt0'
  else
    prtobj:='prt0';
end;

Function TLinkerAndroid.WriteResponseFile(isdll:boolean) : Boolean;
Var
  linkres      : TLinkRes;
  i            : longint;
  HPath        : TCmdStrListItem;
  s,s1         : TCmdStr;
begin
  result:=False;
  { Always link to libc }
  AddSharedLibrary('c');

  { Open link.res file }
  LinkRes:=TLinkRes.Create(outputexedir+Info.ResName,true);
  with linkres do
    begin
      { Write path to search libraries }
      HPath:=TCmdStrListItem(current_module.locallibrarysearchpath.First);
      while assigned(HPath) do
       begin
         Add('SEARCH_DIR('+maybequoted(HPath.Str)+')');
         HPath:=TCmdStrListItem(HPath.Next);
       end;
      HPath:=TCmdStrListItem(LibrarySearchPath.First);
      while assigned(HPath) do
       begin
         Add('SEARCH_DIR('+maybequoted(HPath.Str)+')');
         HPath:=TCmdStrListItem(HPath.Next);
       end;

      { force local symbol resolution (i.e., inside the shared }
      { library itself) for all non-exorted symbols, otherwise }
      { several RTL symbols of FPC-compiled shared libraries   }
      { will be bound to those of a single shared library or   }
      { to the main program                                    }
      if isdll or (cs_create_pic in current_settings.moduleswitches) then
        begin
          add('VERSION');
          add('{');
          add('  {');
          if not texportlibunix(exportlib).exportedsymnames.empty then
            begin
              add('    global:');
              repeat
                add('      '+texportlibunix(exportlib).exportedsymnames.getfirst+';');
              until texportlibunix(exportlib).exportedsymnames.empty;
            end;
          add('    local:');
          add('      *;');
          add('  };');
          add('}');
        end;

      StartSection('INPUT(');
      { add objectfiles, start with prt0 always }
      if not (target_info.system in systems_internal_sysinit) and (prtobj<>'') then
        AddFileName(maybequoted(FindObjectFile(prtobj,'',false)));
      { Add libc startup object file }
      if isdll then
        s:='crtbegin_so.o'
      else
        if cs_link_staticflag in current_settings.globalswitches then
          s:='crtbegin_static.o'
        else
          s:='crtbegin_dynamic.o';
      librarysearchpath.FindFile(s,false,s1);
      AddFileName(maybequoted(s1));
      { main objectfiles }
      while not ObjectFiles.Empty do
       begin
         s:=ObjectFiles.GetFirst;
         if s<>'' then
          AddFileName(maybequoted(s));
       end;
      EndSection(')');

      { Write staticlibraries }
      if not StaticLibFiles.Empty then
       begin
         Add('GROUP(');
         While not StaticLibFiles.Empty do
          begin
            S:=StaticLibFiles.GetFirst;
            AddFileName(maybequoted(s))
          end;
         Add(')');
       end;

      // we must reorder here because the result could empty sharedlibfiles
      if reorder Then
        ExpandAndApplyOrder(SharedLibFiles);
      // after this point addition of shared libs not allowed.

      if not SharedLibFiles.Empty then
       begin
         if (SharedLibFiles.Count<>1) or reorder then
           begin
             Add('INPUT(');
             While not SharedLibFiles.Empty do
              begin
                S:=SharedLibFiles.GetFirst;
                i:=Pos(target_info.sharedlibext,S);
                if i>0 then
                  Delete(S,i,255);
                Add('-l'+s);
              end;
             Add(')');
           end;

         if (cs_link_staticflag in current_settings.globalswitches) or
            (not reorder) then
           begin
             Add('GROUP(');
             { when we have -static for the linker the we also need libgcc }
             if (cs_link_staticflag in current_settings.globalswitches) then
               begin
                 Add('-lgcc');
                 if librarysearchpath.FindFile('libgcc_eh.a',false,s1) then
                   Add('-lgcc_eh');
               end;
             { be sure that libc is the last lib }
             if not reorder then
               Add('-lc');
             Add(')');
           end;
       end;

      { objects which must be at the end }
      { Add libc finalization object file }
      Add('INPUT(');
      if isdll then
        s:='crtend_so.o'
      else
        s:='crtend_android.o';
      librarysearchpath.FindFile(s,false,s1);
      AddFileName(maybequoted(s1));
      Add(')');

      { Additions to the linker script }

      add('SECTIONS');
      add('{');
      add('  .data           :');
      add('  {');
      { extra by FPC }
      add('    KEEP (*(.fpc .fpc.n_version .fpc.n_links))');
      add('  }');
      add('}');
      add('INSERT AFTER .data1');

      // Define different aliases for normal and JNI libraries
      if FJNIOnLoadName <> '' then
        begin
          s:=FJNIOnLoadName;
          s1:='FPC_JNI_LIB_MAIN_ANDROID';
        end
      else
        begin
          s:='0';
          s1:='PASCALMAIN';
        end;
      add('FPC_JNI_ON_LOAD = ' + s + ';');
      add('FPC_LIB_MAIN_ANDROID = ' + s1 + ';');

      { Write and Close response }
      writetodisk;
      Free;
    end;

  WriteResponseFile:=True;
end;

function tlinkerandroid.DoLink(IsSharedLib: boolean): boolean;
var
  i: longint;
  binstr, cmdstr: TCmdStr;
  s, opts, outname: string;
  success: boolean;
begin
  Result:=False;
  if IsSharedLib then
    outname:=current_module.sharedlibfilename
  else
    outname:=current_module.exefilename;
  if not(cs_link_nolink in current_settings.globalswitches) then
    Message1(exec_i_linking, outname);

  opts:='';
  if not IsSharedLib and (cs_create_pic in current_settings.moduleswitches) then
    opts:=opts + ' --pic-executable';
  if (cs_link_strip in current_settings.globalswitches) and
     not (cs_link_separate_dbg_file in current_settings.globalswitches) then
    opts:=opts + ' -s';
  if (cs_link_map in current_settings.globalswitches) then
    opts:=opts + ' -Map '+maybequoted(ChangeFileExt(outname,'.map'));
  if create_smartlink_sections then
    opts:=opts + ' --gc-sections';
  if (cs_link_staticflag in current_settings.globalswitches) then
    opts:=opts + ' -static'
  else
    if cshared then
      opts:=opts + ' -call_shared';
  if rlinkpath<>'' then
    opts:=opts+' --rpath-link '+rlinkpath;

  if not IsSharedLib then
    begin
      opts:=opts + ' --dynamic-linker ' + Info.DynamicLinker;
      { create dynamic symbol table? }
      if HasExports then
        opts:=opts+' -E';
    end;

  opts:=Trim(opts + ' ' + Info.ExtraOptions);

{ Write used files and libraries }
  WriteResponseFile(IsSharedLib);

{ Call linker }
  if IsSharedLib then
    s:=Info.DllCmd[1]
  else
    s:=Info.ExeCmd[1];
  SplitBinCmd(s, binstr, cmdstr);
  Replace(cmdstr,'$EXE',maybequoted(outname));
  Replace(cmdstr,'$OPT',opts);
  Replace(cmdstr,'$RES',maybequoted(outputexedir+Info.ResName));
  if IsSharedLib then
    Replace(cmdstr,'$SONAME',ExtractFileName(outname));

  binstr:=FindUtil(utilsprefix+BinStr);
  { We should use BFD version of LD, since GOLD version does not support INSERT command in linker scripts }
  if binstr <> '' then begin
    { Checking if ld.bfd exists }
    s:=ChangeFileExt(binstr, '.bfd' + source_info.exeext);
    if FileExists(s, True) then
      binstr:=s;
  end;

  success:=DoExec(binstr,CmdStr,true,false);

  { Create external .dbg file with debuginfo }
  if success and (cs_link_separate_dbg_file in current_settings.globalswitches) then
    begin
      for i:=1 to 3 do
        begin
          SplitBinCmd(Info.ExtDbgCmd[i],binstr,cmdstr);
          Replace(cmdstr,'$EXE',maybequoted(outname));
          Replace(cmdstr,'$DBGFN',maybequoted(extractfilename(current_module.dbgfilename)));
          Replace(cmdstr,'$DBG',maybequoted(current_module.dbgfilename));
          success:=DoExec(FindUtil(utilsprefix+BinStr),CmdStr,true,false);
          if not success then
            break;
        end;
    end;

  { Remove ReponseFile }
  if (success) and not(cs_link_nolink in current_settings.globalswitches) then
    DeleteFile(outputexedir+Info.ResName);

  Result:=success;   { otherwise a recursive call to link method }
end;

function TLinkerAndroid.MakeExecutable:boolean;
begin
  Result:=DoLink(False);
end;

Function TLinkerAndroid.MakeSharedLibrary:boolean;
begin
  Result:=DoLink(True);
end;

{*****************************************************************************
                                  Initialize
*****************************************************************************}

initialization
  RegisterLinker(ld_android,TLinkerAndroid);
{$ifdef ARM}
  RegisterImport(system_arm_android,timportlibandroid);
  RegisterExport(system_arm_android,texportlibandroid);
  RegisterTarget(system_arm_android_info);
{$endif ARM}
{$ifdef AARCH64}
  RegisterImport(system_aarch64_android,timportlibandroid);
  RegisterExport(system_aarch64_android,texportlibandroid);
  RegisterTarget(system_aarch64_android_info);
{$endif AARCH64}
{$ifdef I386}
  RegisterImport(system_i386_android,timportlibandroid);
  RegisterExport(system_i386_android,texportlibandroid);
  RegisterTarget(system_i386_android_info);
{$endif I386}
{$ifdef X86_64}
  RegisterImport(system_x86_64_android,timportlibandroid);
  RegisterExport(system_x86_64_android,texportlibandroid);
  RegisterTarget(system_x86_64_android_info);
{$endif X86_64}
{$ifdef MIPSEL}
  RegisterImport(system_mipsel_android,timportlibandroid);
  RegisterExport(system_mipsel_android,texportlibandroid);
  RegisterTarget(system_mipsel_android_info);
{$endif MIPSEL}
  RegisterRes(res_elf_info,TWinLikeResourceFile);
end.