forked from MobiVM/robovm
/
ClassCompiler.java
executable file
·1756 lines (1586 loc) · 78.9 KB
/
ClassCompiler.java
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2012 RoboVM AB
*
* 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, see <http://www.gnu.org/licenses/gpl-2.0.html>.
*/
package org.robovm.compiler;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.robovm.compiler.clazz.Clazz;
import org.robovm.compiler.clazz.ClazzInfo;
import org.robovm.compiler.clazz.Dependency;
import org.robovm.compiler.clazz.MethodInfo;
import org.robovm.compiler.config.Arch;
import org.robovm.compiler.config.Config;
import org.robovm.compiler.config.Environment;
import org.robovm.compiler.config.OS;
import org.robovm.compiler.llvm.Alias;
import org.robovm.compiler.llvm.AliasRef;
import org.robovm.compiler.llvm.And;
import org.robovm.compiler.llvm.ArrayConstant;
import org.robovm.compiler.llvm.ArrayConstantBuilder;
import org.robovm.compiler.llvm.ArrayType;
import org.robovm.compiler.llvm.Bitcast;
import org.robovm.compiler.llvm.Br;
import org.robovm.compiler.llvm.ByteArrayConstant;
import org.robovm.compiler.llvm.Constant;
import org.robovm.compiler.llvm.ConstantBitcast;
import org.robovm.compiler.llvm.Fence;
import org.robovm.compiler.llvm.Function;
import org.robovm.compiler.llvm.FunctionDeclaration;
import org.robovm.compiler.llvm.FunctionRef;
import org.robovm.compiler.llvm.Getelementptr;
import org.robovm.compiler.llvm.Global;
import org.robovm.compiler.llvm.GlobalRef;
import org.robovm.compiler.llvm.Icmp;
import org.robovm.compiler.llvm.IntegerConstant;
import org.robovm.compiler.llvm.Label;
import org.robovm.compiler.llvm.Linkage;
import org.robovm.compiler.llvm.Load;
import org.robovm.compiler.llvm.NullConstant;
import org.robovm.compiler.llvm.Ordering;
import org.robovm.compiler.llvm.PackedStructureConstantBuilder;
import org.robovm.compiler.llvm.PointerType;
import org.robovm.compiler.llvm.Ret;
import org.robovm.compiler.llvm.Store;
import org.robovm.compiler.llvm.StructureConstant;
import org.robovm.compiler.llvm.StructureConstantBuilder;
import org.robovm.compiler.llvm.StructureType;
import org.robovm.compiler.llvm.Type;
import org.robovm.compiler.llvm.Value;
import org.robovm.compiler.llvm.Variable;
import org.robovm.compiler.llvm.VariableRef;
import org.robovm.compiler.plugin.CompilerPlugin;
import org.robovm.debugger.debuginfo.DebuggerDebugObjectFileInfo;
import org.robovm.compiler.plugin.objc.ObjCMemberPlugin;
import org.robovm.compiler.trampoline.Checkcast;
import org.robovm.compiler.trampoline.Instanceof;
import org.robovm.compiler.trampoline.Invoke;
import org.robovm.compiler.trampoline.Invokeinterface;
import org.robovm.compiler.trampoline.Invokevirtual;
import org.robovm.compiler.trampoline.Trampoline;
import org.robovm.compiler.util.io.HfsCompressor;
import org.robovm.llvm.Context;
import org.robovm.llvm.LineInfo;
import org.robovm.llvm.Module;
import org.robovm.llvm.ObjectFile;
import org.robovm.llvm.PassManager;
import org.robovm.llvm.PassManagerBuilder;
import org.robovm.llvm.Symbol;
import org.robovm.llvm.Target;
import org.robovm.llvm.TargetMachine;
import org.robovm.llvm.binding.Attribute;
import org.robovm.llvm.binding.CodeGenFileType;
import org.robovm.llvm.binding.CodeGenOptLevel;
import org.robovm.llvm.binding.RelocMode;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.LongType;
import soot.Modifier;
import soot.PrimType;
import soot.RefLikeType;
import soot.ShortType;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.VoidType;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.internal.JReturnVoidStmt;
import soot.tagkit.ConstantValueTag;
import soot.tagkit.Tag;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.robovm.compiler.Annotations.*;
import static org.robovm.compiler.Functions.*;
import static org.robovm.compiler.StructMemberMethodCompiler.STRUCT_ATTRIBUTES_METHOD;
import static org.robovm.compiler.Types.*;
import static org.robovm.compiler.llvm.Type.*;
/**
*
* @version $Id$
*/
public class ClassCompiler {
private static final int DUMMY_METHOD_SIZE = 0x01abcdef;
public static final int CI_PUBLIC = 0x1;
public static final int CI_FINAL = 0x2;
public static final int CI_INTERFACE = 0x4;
public static final int CI_ABSTRACT = 0x8;
public static final int CI_SYNTHETIC = 0x10;
public static final int CI_ANNOTATION = 0x20;
public static final int CI_ENUM = 0x40;
public static final int CI_ATTRIBUTES = 0x80;
public static final int CI_ERROR = 0x100;
public static final int CI_INITIALIZED = 0x200;
public static final int CI_FINALIZABLE = 0x400;
public static final int CI_ERROR_TYPE_NONE = 0x0;
public static final int CI_ERROR_TYPE_NO_CLASS_DEF_FOUND = 0x1;
public static final int CI_ERROR_TYPE_ILLEGAL_ACCESS = 0x2;
public static final int CI_ERROR_TYPE_INCOMPATIBLE_CLASS_CHANGE = 0x3;
public static final int FI_ACCESS_MASK = 0x3;
public static final int FI_PUBLIC = 0x1;
public static final int FI_PRIVATE = 0x2;
public static final int FI_PROTECTED = 0x3;
public static final int FI_STATIC = 0x4;
public static final int FI_FINAL = 0x8;
public static final int FI_VOLATILE = 0x10;
public static final int FI_TRANSIENT = 0x20;
public static final int FI_SYNTHETIC = 0x40;
public static final int FI_ENUM = 0x80;
public static final int FI_ATTRIBUTES = 0x100;
public static final int MI_ACCESS_MASK = 0x3;
public static final int MI_PUBLIC = 0x1;
public static final int MI_PRIVATE = 0x2;
public static final int MI_PROTECTED = 0x3;
public static final int MI_STATIC = 0x4;
public static final int MI_FINAL = 0x8;
public static final int MI_SYNCHRONIZED = 0x10;
public static final int MI_BRIDGE = 0x20;
public static final int MI_VARARGS = 0x40;
public static final int MI_NATIVE = 0x80;
public static final int MI_ABSTRACT = 0x100;
public static final int MI_STRICT = 0x200;
public static final int MI_SYNTHETIC = 0x400;
public static final int MI_ATTRIBUTES = 0x800;
public static final int MI_BRO_BRIDGE = 0x1000;
public static final int MI_BRO_CALLBACK = 0x2000;
public static final int MI_COMPACT_DESC = 0x4000;
public static final int DESC_B = 1;
public static final int DESC_C = 2;
public static final int DESC_D = 3;
public static final int DESC_F = 4;
public static final int DESC_I = 5;
public static final int DESC_J = 6;
public static final int DESC_S = 7;
public static final int DESC_Z = 8;
public static final int DESC_V = 9;
private SootClass sootClass;
private ModuleBuilder mb;
private Map<Trampoline, List<SootMethod>> trampolines;
private Set<String> catches;
/**
* Contains the class fields of the class being compiled.
*/
private List<SootField> classFields;
/**
* Contains the instance fields of the class being compiled.
*/
private List<SootField> instanceFields;
private StructureType classType;
private StructureType instanceType;
private final Config config;
private final MethodCompiler javaMethodCompiler;
private final BroMethodCompiler bridgeMethodCompiler;
private final CallbackMethodCompiler callbackMethodCompiler;
private final NativeMethodCompiler nativeMethodCompiler;
private final StructMemberMethodCompiler structMemberMethodCompiler;
private final GlobalValueMethodCompiler globalValueMethodCompiler;
private final AttributesEncoder attributesEncoder;
private final TrampolineCompiler trampolineResolver;
private final ObjCMemberPlugin.MethodCompiler objcMethodCompiler;
private final ByteArrayOutputStream output = new ByteArrayOutputStream(256 * 1024);
public ClassCompiler(Config config) {
this.config = config;
this.javaMethodCompiler = new MethodCompiler(config);
this.bridgeMethodCompiler = new BridgeMethodCompiler(config);
this.callbackMethodCompiler = new CallbackMethodCompiler(config);
this.nativeMethodCompiler = new NativeMethodCompiler(config);
this.structMemberMethodCompiler = new StructMemberMethodCompiler(config);
this.globalValueMethodCompiler = new GlobalValueMethodCompiler(config);
this.attributesEncoder = new AttributesEncoder();
this.trampolineResolver = new TrampolineCompiler(config);
this.objcMethodCompiler = new ObjCMemberPlugin.MethodCompiler(config);
}
public boolean mustCompile(Clazz clazz) {
File oFile = config.getOFile(clazz);
if (!oFile.exists() || oFile.lastModified() < clazz.lastModified() || oFile.length() == 0) {
return true;
}
ClazzInfo ci = clazz.getClazzInfo();
if (ci == null) {
return true;
}
Set<Dependency> dependencies = ci.getAllDependencies();
for (Dependency dep : dependencies) {
Clazz depClazz = config.getClazzes().load(dep.getClassName());
if (depClazz == null) {
if (dep.getPath() != null) {
// depClazz was available the last time clazz was compiled but is now gone
return true;
}
} else {
if (dep.getPath() == null) {
// depClazz was not available the last time clazz was compiled but is now available
return true;
}
if (!dep.getPath().equals(depClazz.getPath().getFile().getAbsolutePath())) {
// depClazz was located in another place the last time clazz was built
return true;
}
if (depClazz.isInBootClasspath() != dep.isInBootClasspath()) {
// depClazz has moved to/from the bootclasspath since the last time clazz was built
return true;
}
if (depClazz.lastModified() > oFile.lastModified()) {
// depClazz has been changed since the last time clazz was built
return true;
}
}
}
// No class or interface has zero dependencies (we always add java.lang.Object as a dependency)
// If dependencies is empty it probably means that an error occurred while reading the
// serialized dependencies. By returning true here in that case the class will be recompiled
// and the dependencies regenerated.
return dependencies.isEmpty();
}
public void compile(Clazz clazz, Executor executor, ClassCompilerListener listener) throws IOException {
reset();
Arch arch = config.getArch();
OS os = config.getOs();
Environment env = config.getEnv();
try {
config.getLogger().info("Compiling %s (%s %s%s %s)", clazz, os, arch, env.asLlvmSuffix("-"),
config.isDebug() ? "debug" : "release");
output.reset();
compile(clazz, output);
} catch (Throwable t) {
if (t instanceof IOException) {
throw (IOException) t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
throw new RuntimeException(t);
}
List<String> cCode = new ArrayList<>();
cCode.addAll(bridgeMethodCompiler.getCWrapperFunctions());
cCode.addAll(callbackMethodCompiler.getCWrapperFunctions());
scheduleMachineCodeGeneration(executor, listener, config, clazz, output.toByteArray(), cCode);
}
private static void scheduleMachineCodeGeneration(Executor executor, final ClassCompilerListener listener,
final Config config, final Clazz clazz, final byte[] llData, final List<String> cCode) {
Runnable task = new Runnable() {
@Override
public void run() {
try {
generateMachineCode(config, clazz, llData, cCode);
listener.success(clazz);
} catch (Throwable t) {
listener.failure(clazz, t);
}
}
};
try {
executor.execute(task);
} catch (RejectedExecutionException e) {
if (!(executor instanceof ExecutorService) || !((ExecutorService) executor).isShutdown()) {
// The task was rejected, probably because all workers are busy. Run it in this thread instead.
task.run();
}
}
}
private static void generateMachineCode(Config config, Clazz clazz, byte[] llData, List<String> cCode) throws IOException {
if (config.isDumpIntermediates()) {
File llFile = config.getLlFile(clazz);
llFile.getParentFile().mkdirs();
FileUtils.writeByteArrayToFile(llFile, llData);
File cFile = config.getCFile(clazz);
if (cCode.isEmpty()) {
cFile.delete();
} else {
FileUtils.writeLines(cFile, "ascii", cCode);
}
}
File oFile = config.getOFile(clazz);
try (Context context = new Context()) {
try (Module module = Module.parseIR(context, llData, clazz.getClassName())) {
if (!cCode.isEmpty()) {
int size = 0;
for (String s : cCode) {
size += s.length();
}
StringBuilder sb = new StringBuilder(size);
for (String s : cCode) {
sb.append(s);
}
try (Module m2 = Module.parseClangString(context, sb.toString(), clazz.getClassName() + ".c", config.getClangTriple())) {
module.link(m2);
for (org.robovm.llvm.Function f1 : m2.getFunctions()) {
String name = f1.getName();
org.robovm.llvm.Function f2 = module.getFunctionByName(name);
if (Symbols.isBridgeCSymbol(name) || Symbols.isCallbackCSymbol(name) || Symbols.isCallbackInnerCSymbol(name)) {
f2.setLinkage(org.robovm.llvm.binding.Linkage.PrivateLinkage);
if (Symbols.isCallbackInnerCSymbol(name)) {
// TODO: We should also always inline the bridge functions but for some reason
// that makes the RoboVM tests hang indefinitely.
f2.removeAttribute(Attribute.NoInlineAttribute);
f2.addAttribute(Attribute.AlwaysInlineAttribute);
}
}
}
}
}
try (PassManager passManager = createPassManager(config)) {
passManager.run(module);
}
if (config.isDumpIntermediates()) {
File bcFile = config.getBcFile(clazz);
bcFile.getParentFile().mkdirs();
module.writeBitcode(bcFile);
}
String triple = config.getTriple();
Target target = Target.lookupTarget(triple);
try (TargetMachine targetMachine = target.createTargetMachine(triple,
config.getArch().getLlvmCpu(), null,
config.isDebug()? CodeGenOptLevel.CodeGenLevelNone: null,
RelocMode.RelocPIC, null)) {
targetMachine.setAsmVerbosityDefault(true);
targetMachine.setFunctionSections(true);
targetMachine.setDataSections(true);
targetMachine.getOptions().setNoFramePointerElim(true);
targetMachine.getOptions().setPositionIndependentExecutable(!config.isDebug()); // NOTE: Doesn't have any effect on x86. See #503.
ByteArrayOutputStream output = new ByteArrayOutputStream(256 * 1024);
targetMachine.emit(module, output, CodeGenFileType.AssemblyFile);
byte[] asm = output.toByteArray();
output.reset();
patchAsmWithFunctionSizes(config, clazz, new ByteArrayInputStream(asm), output);
asm = output.toByteArray();
if (config.isDumpIntermediates()) {
File sFile = config.getSFile(clazz);
sFile.getParentFile().mkdirs();
FileUtils.writeByteArrayToFile(sFile, asm);
}
oFile.getParentFile().mkdirs();
ByteArrayOutputStream oFileBytes = new ByteArrayOutputStream();
targetMachine.assemble(asm, clazz.getClassName(), oFileBytes);
new HfsCompressor().compress(oFile, oFileBytes.toByteArray(), config);
ModuleBuilder linesMb;
ModuleBuilder debugInfoMb = null;
try (ObjectFile objectFile = ObjectFile.load(oFile)) {
// notify plugins
for (CompilerPlugin plugin : config.getCompilerPlugins()) {
plugin.afterObjectFile(config, clazz, oFile, objectFile);
}
/*
* Read out line number info from the .o file if any and
* assemble into a separate .o file.
*/
linesMb = buildLineNumberData(config, clazz, objectFile);
/*
* read out debug info binary data amd assemble into a separate .o file
*/
if (config.isDebug()) {
debugInfoMb = buildDebugInfoData(config, clazz, objectFile);
}
}
if (linesMb != null) {
File linesLlFile = config.isDumpIntermediates() ? config.getLinesLlFile(clazz) : null;
File linesOFile = config.getLinesOFile(clazz);
createObjectFileFromData(config, context, targetMachine, linesMb, clazz.getClassName() + ".lines",
linesLlFile, linesOFile);
} else {
// Make sure there's no stale lines.o file lingering
File linesOFile = config.getLinesOFile(clazz);
if (linesOFile.exists()) {
linesOFile.delete();
}
}
if (debugInfoMb != null) {
File debugInfoLlFile = config.isDumpIntermediates() ? config.getDebugInfoLlFile(clazz) : null;
File debugInfoOFile = config.getDebugInfoOFile(clazz);
createObjectFileFromData(config, context, targetMachine, debugInfoMb, clazz.getClassName() + ".debuginfo",
debugInfoLlFile, debugInfoOFile);
} else {
// Make sure there's no stale debuginfo.o file lingering
File debugInfoOFile = config.getDebugInfoOFile(clazz);
if (debugInfoOFile.exists()) {
debugInfoOFile.delete();
}
}
}
}
} catch (Throwable t) {
if (oFile.exists()) {
oFile.delete();
}
if (t instanceof IOException) {
throw (IOException) t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof Error) {
throw (Error) t;
}
throw new CompilerException(t);
}
}
private static void createObjectFileFromData(Config config, Context context, TargetMachine targetMachine, ModuleBuilder mb,
String dataName, File llFile, File oFile) throws IOException, InterruptedException {
byte[] data = mb.build().toString().getBytes(StandardCharsets.UTF_8);
if (llFile != null) {
llFile.getParentFile().mkdirs();
FileUtils.writeByteArrayToFile(llFile, data);
}
try (Module module = Module.parseIR(context, data, dataName)) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
targetMachine.emit(module, bytes, CodeGenFileType.ObjectFile);
new HfsCompressor().compress(oFile, bytes.toByteArray(), config);
}
}
private static ModuleBuilder buildLineNumberData(Config config, Clazz clazz, ObjectFile objectFile) {
ModuleBuilder linesMb = null;
String symbolPrefix = config.getOs().getFamily() == OS.Family.darwin ? "_" : "";
symbolPrefix += Symbols.EXTERNAL_SYMBOL_PREFIX;
for (Symbol symbol : objectFile.getSymbols()) {
if (symbol.getSize() > 0 && symbol.getName().startsWith(symbolPrefix)) {
List<LineInfo> lineInfos = objectFile.getLineInfos(symbol);
if (!lineInfos.isEmpty()) {
Collections.sort(lineInfos, new Comparator<LineInfo>() {
public int compare(LineInfo o1, LineInfo o2) {
return Long.compare(o1.getAddress(), o2.getAddress());
}
});
// The base address of the method which will be used to calculate offsets into the method
long baseAddress = symbol.getAddress();
// The first line number in the method. All other line numbers in the table will be deltas against this.
int firstLineNumber = lineInfos.get(0).getLineNumber();
// Calculate the max address and line number offsets
long maxAddressOffset = 0;
long maxLineOffset = 0;
for (LineInfo lineInfo : lineInfos) {
maxAddressOffset = Math.max(maxAddressOffset, lineInfo.getAddress() - baseAddress);
maxLineOffset = Math.max(maxLineOffset, lineInfo.getLineNumber() - firstLineNumber);
}
// Calculate the number of bytes needed to represent the highest offsets.
// Either 1, 2 or 4 bytes will be used.
int addressOffsetSize = (maxAddressOffset & ~0xff) == 0 ? 1 : ((maxAddressOffset & ~0xffff) == 0 ? 2 : 4);
int lineOffsetSize = (maxLineOffset & ~0xff) == 0 ? 1 : ((maxLineOffset & ~0xffff) == 0 ? 2 : 4);
// The size of the address offsets table. We skip the first LineInfo as its offset is always 0.
int addressOffsetTableSize = addressOffsetSize * (lineInfos.size() - 1);
// Pad size of address offset table to make sure line offsets are aligned properly
int addressOffsetPadding = (lineOffsetSize - (addressOffsetTableSize & (lineOffsetSize - 1))) & (lineOffsetSize - 1);
addressOffsetTableSize += addressOffsetPadding;
// The first 32 bits of the line number info contains the number of line numbers
// minus the first. The 4 most significant bits are used to store the number of
// bytes needed by each entry in each table.
int flags = 0;
flags = addressOffsetSize - 1;
flags <<= 2;
flags |= lineOffsetSize - 1;
flags <<= 28;
flags |= (lineInfos.size() - 1) & 0x0fffffff;
StructureConstantBuilder builder = new StructureConstantBuilder();
builder
.add(new IntegerConstant(flags))
.add(new IntegerConstant(firstLineNumber));
for (LineInfo lineInfo : lineInfos.subList(1, lineInfos.size())) {
if (addressOffsetSize == 1) {
builder.add(new IntegerConstant((byte) (lineInfo.getAddress() - baseAddress)));
} else if (addressOffsetSize == 2) {
builder.add(new IntegerConstant((short) (lineInfo.getAddress() - baseAddress)));
} else {
builder.add(new IntegerConstant((int) (lineInfo.getAddress() - baseAddress)));
}
}
// Padding
for (int i = 0; i < addressOffsetPadding; i++) {
builder.add(new IntegerConstant((byte) 0));
}
for (LineInfo lineInfo : lineInfos.subList(1, lineInfos.size())) {
if (lineOffsetSize == 1) {
builder.add(new IntegerConstant((byte) (lineInfo.getLineNumber() - firstLineNumber)));
} else if (lineOffsetSize == 2) {
builder.add(new IntegerConstant((short) (lineInfo.getLineNumber() - firstLineNumber)));
} else {
builder.add(new IntegerConstant((int) (lineInfo.getLineNumber() - firstLineNumber)));
}
}
// Extract the method's name and descriptor from the symbol and
// build the linetable symbol name.
String methodName = symbol.getName().substring(symbol.getName().lastIndexOf('.') + 1);
methodName = methodName.substring(0, methodName.indexOf('('));
String methodDesc = symbol.getName().substring(symbol.getName().lastIndexOf('('));
String linetableSymbol = Symbols.linetableSymbol(clazz.getInternalName(), methodName, methodDesc);
if (linesMb == null) {
linesMb = new ModuleBuilder();
}
linesMb.addGlobal(new Global(linetableSymbol, builder.build(), true));
}
}
}
// emit bitcode section for line number object file
if (linesMb != null)
emitBitcodeSection(config, linesMb);
return linesMb;
}
private static ModuleBuilder buildDebugInfoData(Config config, Clazz clazz, ObjectFile objectFile) throws IOException {
ModuleBuilder debugInfoMb = null;
DebuggerDebugObjectFileInfo.RawData debugInfo = clazz.getAttachment(DebuggerDebugObjectFileInfo.RawData.class);
if (debugInfo != null) {
// read all binary data to file
byte[] debugDataBytes = DebuggerDebugObjectFileInfo.dumpDebugInfo(debugInfo);
String debugInfoSymbol = Symbols.debugInfoSymbol(clazz.getInternalName());
debugInfoMb = new ModuleBuilder();
Global debugInfoSymbolGlobal = new Global(debugInfoSymbol, new ByteArrayConstant(debugDataBytes), true);
debugInfoMb.addGlobal(debugInfoSymbolGlobal);
// list to keep weak values (such as debugger ones) to be added to llvm.used
List<Value> usedGlobalValues = new ArrayList<>();
usedGlobalValues.add(new ConstantBitcast(debugInfoSymbolGlobal.ref(), Type.I8_PTR));
// also need to add reference to @llvm.used otherwise linker will drop out this data as not used
// dkimitsa: always add it as array even if there is only one element as llvm.used is array of pointers
// and debug version of llvm will crash on assertion while validating type
Global usedGlobal;
ArrayConstant usedValuesArr = new ArrayConstant(new ArrayType(usedGlobalValues.size(), Type.I8_PTR),
usedGlobalValues.toArray(new Value[0]));
usedGlobal = new Global("llvm.used", Linkage.appending, usedValuesArr, false, "llvm.metadata");
debugInfoMb.addGlobal(usedGlobal);
if (config.isDumpIntermediates()) {
File f = new File(config.getDebugInfoOFile(clazz).getAbsolutePath() + ".dump");
DebuggerDebugObjectFileInfo.dumpDebugInfoAsText(debugInfo, f);
}
}
return debugInfoMb;
}
private static PassManager createPassManager(Config config) {
PassManager passManager = new PassManager();
if (config.isDebug()) {
// Minimal passes. Just inline functions marked 'alwaysinline'.
passManager.addAlwaysInlinerPass();
} else {
try (PassManagerBuilder builder = new PassManagerBuilder()) {
builder.setSetOptLevel(2);
builder.setDisableTailCalls(true);
builder.useAlwaysInliner(true);
builder.populateModulePassManager(passManager);
}
}
return passManager;
}
private static void patchAsmWithFunctionSizes(Config config, Clazz clazz, InputStream inStream, OutputStream outStream) throws IOException {
String labelPrefix = config.getOs().getFamily() == OS.Family.darwin ? "_" : "";
String localLabelPrefix = config.getOs().getFamily() == OS.Family.darwin ? "L" : ".L";
Set<String> functionNames = new HashSet<String>();
for (SootMethod method : clazz.getSootClass().getMethods()) {
if (!method.isAbstract()) {
String name = labelPrefix + Symbols.methodSymbol(method);
functionNames.add(name);
}
}
String infoStructLabel = labelPrefix + Symbols.infoStructSymbol(clazz.getInternalName());
Pattern methodImplPattern = Pattern.compile("\\s*\\.(?:quad|long)\\s+\"?("
+ Pattern.quote(labelPrefix + Symbols.methodSymbolPrefix(clazz.getInternalName()))
+ "[^\\s\"]+)\"?.*");
BufferedReader in = null;
BufferedWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8));
out = new BufferedWriter(new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
String line = null;
String currentFunction = null;
while ((line = in.readLine()) != null) {
if (currentFunction == null) {
out.write(line);
out.write('\n');
int colon = line.indexOf(':');
if (colon != -1) {
String label = line.substring(0, colon);
if (label.startsWith("\"") && label.endsWith("\"")) {
label = label.substring(1, label.length() - 1);
}
if (functionNames.contains(label)) {
currentFunction = label;
} else if (label.equals(infoStructLabel)) {
break;
}
}
} else if (line.trim().equals(".cfi_endproc") || line.trim().startsWith(".section") || line.trim().startsWith(".globl")) {
out.write("\"");
out.write(localLabelPrefix);
out.write(currentFunction);
out.write("_end\":\n\n");
currentFunction = null;
out.write(line);
out.write('\n');
} else {
out.write(line);
out.write('\n');
}
}
while ((line = in.readLine()) != null) {
out.write(line);
out.write('\n');
Matcher matcher = methodImplPattern.matcher(line);
if (matcher.matches()) {
String functionName = matcher.group(1);
if (functionNames.contains(functionName)) {
line = in.readLine();
if (line.contains(String.valueOf(DUMMY_METHOD_SIZE))) {
out.write("\t.long\t");
out.write("\"" + localLabelPrefix + functionName + "_end\" - \"" + functionName + "\"");
out.write('\n');
} else {
out.write(line);
out.write('\n');
}
}
}
}
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
private void reset() {
output.reset();
sootClass = null;
mb = null;
trampolines = null;
catches = null;
classFields = null;
instanceFields = null;
classType = null;
instanceType = null;
}
private void compile(Clazz clazz, OutputStream out) throws IOException {
ClazzInfo ci = clazz.resetClazzInfo();
mb = new ModuleBuilder();
for (CompilerPlugin compilerPlugin : config.getCompilerPlugins()) {
compilerPlugin.helloClass(config, clazz);
}
for (CompilerPlugin compilerPlugin : config.getCompilerPlugins()) {
compilerPlugin.beforeClass(config, clazz, mb);
}
// dkimitsa: intentionally moved reset section after compiler plugin beforeClass invocation.
// one reason for this is structMemberMethodCompiler. it tries to resolve structure type
// and find out all marshallers but some of them (like ObjCBlock ones) are generated only
// in beforeClass. so to have all marshallers and generated classes in place, reset section
// is moved here. it shall have no affect as these compilers are not used by plugins itself
javaMethodCompiler.reset(clazz);
bridgeMethodCompiler.reset(clazz);
callbackMethodCompiler.reset(clazz);
nativeMethodCompiler.reset(clazz);
structMemberMethodCompiler.reset(clazz);
globalValueMethodCompiler.reset(clazz);
sootClass = clazz.getSootClass();
trampolines = new HashMap<>();
catches = new HashSet<String>();
classFields = getClassFields(config.getOs(), config.getArch(),sootClass);
instanceFields = getInstanceFields(config.getOs(), config.getArch(),sootClass);
classType = getClassType(mb, config.getOs(), config.getArch(),sootClass);
instanceType = getInstanceType(config.getOs(), config.getArch(),sootClass);
attributesEncoder.encode(mb, sootClass);
// Add a <clinit> method if the class has ConstantValueTags but no <clinit>.
// This has to be done before createInfoStruct() is called otherwise the
// ClassInfoHeader->initializer value will become NULL and constant static fields
// will never be initialized.
if (!sootClass.declaresMethodByName("<clinit>") && hasConstantValueTags(classFields)) {
SootMethod clinit = new SootMethod("<clinit>", Collections.EMPTY_LIST, VoidType.v(), Modifier.STATIC);
JimpleBody body = Jimple.v().newBody(clinit);
clinit.setActiveBody(body);
body.getUnits().add(new JReturnVoidStmt());
this.sootClass.addMethod(clinit);
}
if (isStruct(sootClass)) {
SootMethod _sizeOf = new SootMethod("_sizeOf", Collections.EMPTY_LIST, IntType.v(), Modifier.PROTECTED | Modifier.NATIVE);
sootClass.addMethod(_sizeOf);
SootMethod sizeOf = new SootMethod("sizeOf", Collections.EMPTY_LIST, IntType.v(), Modifier.PUBLIC | Modifier.STATIC | Modifier.NATIVE);
sootClass.addMethod(sizeOf);
// method that will provide meta flags for runtime to help finding out if stret is required
SootMethod stretMeta = new SootMethod(STRUCT_ATTRIBUTES_METHOD, Collections.EMPTY_LIST, IntType.v(), Modifier.PUBLIC | Modifier.STATIC | Modifier.NATIVE);
sootClass.addMethod(stretMeta);
// method that returns offset of struct member
SootMethod offset = new SootMethod("offsetOf", Collections.singletonList(IntType.v()), IntType.v(), Modifier.PUBLIC | Modifier.STATIC | Modifier.NATIVE);
sootClass.addMethod(offset);
}
mb.addInclude(getClass().getClassLoader().getResource(String.format("header-%s-%s.ll", config.getOs().getFamily(), config.getArch())));
mb.addInclude(getClass().getClassLoader().getResource("header.ll"));
mb.addFunction(createLdcClass());
mb.addFunction(createLdcClassWrapper());
Function allocator = createAllocator();
mb.addFunction(allocator);
mb.addFunction(createClassInitWrapperFunction(allocator.ref()));
for (SootField f : sootClass.getFields()) {
Function getter = createFieldGetter(f, classFields, classType, instanceFields, instanceType);
Function setter = createFieldSetter(f, classFields, classType, instanceFields, instanceType);
mb.addFunction(getter);
mb.addFunction(setter);
if (f.isStatic() && !f.isPrivate()) {
mb.addFunction(createClassInitWrapperFunction(getter.ref()));
if (!f.isFinal()) {
mb.addFunction(createClassInitWrapperFunction(setter.ref()));
}
}
}
// After this point no changes to methods/fields may be done by CompilerPlugins.
ci.initClassInfo();
for (SootMethod method : sootClass.getMethods()) {
for (CompilerPlugin compilerPlugin : config.getCompilerPlugins()) {
compilerPlugin.beforeMethod(config, clazz, method, mb);
}
String name = method.getName();
Function function = null;
if (hasBridgeAnnotation(method)) {
// javac generates JVM synthetic bridge methods for covariant return
// and copies @Bridge annotations as well. Don't try to compile bridge methods
// as these are not a subject for RoboVM bridge compiler and it will fail on them
if (!isJvmSyntheticBridgeMethod(method))
function = bridgeMethod(method);
else
function = method(method);
} else if (hasGlobalValueAnnotation(method)) {
function = globalValueMethod(method);
} else if (isStruct(sootClass) && ("_sizeOf".equals(name) || "sizeOf".equals(name) ||
"offsetOf".equals(name) || STRUCT_ATTRIBUTES_METHOD.equals(name) || hasStructMemberAnnotation(method))) {
function = structMember(method);
} else if (method.isNative()) {
function = nativeMethod(method);
} else if (objcMethodCompiler.willCompile(method)) {
function = objcPublishMethod(method);
} else if (!method.isAbstract()) {
function = method(method);
}
if (hasCallbackAnnotation(method)) {
callbackMethod(method);
}
if (!name.equals("<clinit>") && !name.equals("<init>")
&& !method.isPrivate() && !method.isStatic()
&& !Modifier.isFinal(method.getModifiers())
&& !Modifier.isFinal(sootClass.getModifiers())) {
createLookupFunction(method);
}
if (method.isStatic() && !name.equals("<clinit>")) {
String fnName = method.isSynchronized()
? Symbols.synchronizedWrapperSymbol(method)
: Symbols.methodSymbol(method);
FunctionRef fn = new FunctionRef(fnName, getFunctionType(method));
mb.addFunction(createClassInitWrapperFunction(fn));
}
for (CompilerPlugin compilerPlugin : config.getCompilerPlugins()) {
if (function != null) {
compilerPlugin.afterMethod(config, clazz, method, mb, function);
}
}
}
for (Trampoline trampoline : trampolines.keySet()) {
Set<String> deps = new HashSet<String>();
Set<Triple<String, String, String>> mDeps = new HashSet<>();
trampolineResolver.compile(mb, clazz, trampoline, deps, mDeps);
for (SootMethod m : trampolines.get(trampoline)) {
MethodInfo mi = ci.getMethod(m.getName(), getDescriptor(m));
mi.addClassDependencies(deps, false);
mi.addInvokeMethodDependencies(mDeps, false);
}
}
/*
* Add method dependencies from overriding methods to the overridden
* super method(s). These will be reversed by the DependencyGraph to
* create edges from the super/interface method to the overriding
* method.
*/
Map<SootMethod, Set<SootMethod>> overriddenMethods = getOverriddenMethods(this.sootClass);
for (SootMethod from : overriddenMethods.keySet()) {
MethodInfo mi = ci.getMethod(from.getName(), getDescriptor(from));
for (SootMethod to : overriddenMethods.get(from)) {
mi.addSuperMethodDependency(getInternalName(to.getDeclaringClass()), to.getName(), getDescriptor(to), false);
}
}
/*
* Edge case. A method in a superclass might satisfy an interface method
* in the interfaces implemented by this class. See e.g. the abstract
* class HashMap$HashIterator which doesn't implement Iterator but has
* the hasNext() and other methods. We add a dependency from the current
* class to the super method to ensure it's included if the current
* class is linked in.
*/
if (sootClass.hasSuperclass()) {
for (SootClass interfaze : getImmediateInterfaces(sootClass)) {
for (SootMethod m : interfaze.getMethods()) {
if (!m.isStatic()) {
try {
this.sootClass.getMethod(m.getName(), m.getParameterTypes());
} catch (RuntimeException e) {
/*
* Not found. Find the implementation in
* superclasses.
*/
SootMethod superMethod = null;
for (SootClass sc = sootClass.getSuperclass(); sc.hasSuperclass(); sc = sc.getSuperclass()) {
try {
SootMethod candidate = sc.getMethod(m.getName(), m.getParameterTypes());
if (!candidate.isStatic()) {
superMethod = candidate;
break;
}
} catch (RuntimeException e2) {
// Not found.
}
}
if (superMethod != null) {
ci.addSuperMethodDependency(getInternalName(superMethod.getDeclaringClass()),
superMethod.getName(), getDescriptor(superMethod), false);
}
}
}
}
}
}
Global classInfoStruct = null;
try {
if (!sootClass.isInterface()) {
config.getVTableCache().get(sootClass);
}
classInfoStruct = new Global(Symbols.infoStructSymbol(clazz.getInternalName()), Linkage.weak, createClassInfoStruct());
} catch (IllegalArgumentException e) {
// VTable throws this if any of the superclasses of the class is actually an interface.
// Shouldn't happen frequently but the DRLVM test suite has some tests for this.
// The Linker will take care of making sure the class cannot be loaded at runtime.
classInfoStruct = new Global(Symbols.infoStructSymbol(clazz.getInternalName()), I8_PTR, true);
}
mb.addGlobal(classInfoStruct);
/*
* Emit an internal i8* alias for the info struct which MethodCompiler
* can use when referencing this info struct in exception landing pads
* in methods in the same class. See #1007.
*/
mb.addAlias(new Alias(classInfoStruct.getName() + "_i8ptr", Linkage._private, new ConstantBitcast(
classInfoStruct.ref(), I8_PTR)));
Function infoFn = FunctionBuilder.infoStruct(sootClass);
infoFn.add(new Ret(new ConstantBitcast(classInfoStruct.ref(), I8_PTR_PTR)));
mb.addFunction(infoFn);
for (CompilerPlugin compilerPlugin : config.getCompilerPlugins()) {
compilerPlugin.afterClass(config, clazz, mb);
}
// emit bitcode section for class
emitBitcodeSection(config, mb);
OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
mb.build().write(writer);
writer.flush();
ci.setCatchNames(catches);