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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "oat_writer.h"
#include <algorithm>
#include <unistd.h>
#include <zlib.h>
#include "arch/arm64/instruction_set_features_arm64.h"
#include "art_method-inl.h"
#include "base/allocator.h"
#include "base/bit_vector-inl.h"
#include "base/enums.h"
#include "base/file_magic.h"
#include "base/file_utils.h"
#include "base/indenter.h"
#include "base/logging.h" // For VLOG
#include "base/os.h"
#include "base/safe_map.h"
#include "base/stl_util.h"
#include "base/unix_file/fd_file.h"
#include "base/zip_archive.h"
#include "class_linker.h"
#include "class_table-inl.h"
#include "compiled_method-inl.h"
#include "debug/method_debug_info.h"
#include "dex/art_dex_file_loader.h"
#include "dex/class_accessor-inl.h"
#include "dex/dex_file-inl.h"
#include "dex/dex_file_loader.h"
#include "dex/dex_file_types.h"
#include "dex/standard_dex_file.h"
#include "dex/type_lookup_table.h"
#include "dex/verification_results.h"
#include "dex_container.h"
#include "dexlayout.h"
#include "driver/compiler_driver-inl.h"
#include "driver/compiler_options.h"
#include "gc/space/image_space.h"
#include "gc/space/space.h"
#include "handle_scope-inl.h"
#include "image_writer.h"
#include "linker/index_bss_mapping_encoder.h"
#include "linker/linker_patch.h"
#include "linker/multi_oat_relative_patcher.h"
#include "mirror/array.h"
#include "mirror/class_loader.h"
#include "mirror/dex_cache-inl.h"
#include "mirror/object-inl.h"
#include "oat.h"
#include "oat_quick_method_header.h"
#include "profile/profile_compilation_info.h"
#include "quicken_info.h"
#include "scoped_thread_state_change-inl.h"
#include "stack_map.h"
#include "stream/buffered_output_stream.h"
#include "stream/file_output_stream.h"
#include "stream/output_stream.h"
#include "vdex_file.h"
#include "verifier/verifier_deps.h"
namespace art {
namespace linker {
namespace { // anonymous namespace
// If we write dex layout info in the oat file.
static constexpr bool kWriteDexLayoutInfo = true;
// Force the OAT method layout to be sorted-by-name instead of
// the default (class_def_idx, method_idx).
//
// Otherwise if profiles are used, that will act as
// the primary sort order.
//
// A bit easier to use for development since oatdump can easily
// show that things are being re-ordered when two methods aren't adjacent.
static constexpr bool kOatWriterForceOatCodeLayout = false;
static constexpr bool kOatWriterDebugOatCodeLayout = false;
using UnalignedDexFileHeader __attribute__((__aligned__(1))) = DexFile::Header;
const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
}
inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
// We want to align the code rather than the preheader.
uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
return aligned_code_offset - unaligned_code_offset;
}
} // anonymous namespace
class OatWriter::ChecksumUpdatingOutputStream : public OutputStream {
public:
ChecksumUpdatingOutputStream(OutputStream* out, OatWriter* writer)
: OutputStream(out->GetLocation()), out_(out), writer_(writer) { }
bool WriteFully(const void* buffer, size_t byte_count) override {
if (buffer != nullptr) {
const uint8_t* bytes = reinterpret_cast<const uint8_t*>(buffer);
uint32_t old_checksum = writer_->oat_checksum_;
writer_->oat_checksum_ = adler32(old_checksum, bytes, byte_count);
} else {
DCHECK_EQ(0U, byte_count);
}
return out_->WriteFully(buffer, byte_count);
}
off_t Seek(off_t offset, Whence whence) override {
return out_->Seek(offset, whence);
}
bool Flush() override {
return out_->Flush();
}
private:
OutputStream* const out_;
OatWriter* const writer_;
};
// Defines the location of the raw dex file to write.
class OatWriter::DexFileSource {
public:
enum Type {
kNone,
kZipEntry,
kRawFile,
kRawData,
};
explicit DexFileSource(ZipEntry* zip_entry)
: type_(kZipEntry), source_(zip_entry) {
DCHECK(source_ != nullptr);
}
explicit DexFileSource(File* raw_file)
: type_(kRawFile), source_(raw_file) {
DCHECK(source_ != nullptr);
}
explicit DexFileSource(const uint8_t* dex_file)
: type_(kRawData), source_(dex_file) {
DCHECK(source_ != nullptr);
}
Type GetType() const { return type_; }
bool IsZipEntry() const { return type_ == kZipEntry; }
bool IsRawFile() const { return type_ == kRawFile; }
bool IsRawData() const { return type_ == kRawData; }
ZipEntry* GetZipEntry() const {
DCHECK(IsZipEntry());
DCHECK(source_ != nullptr);
return static_cast<ZipEntry*>(const_cast<void*>(source_));
}
File* GetRawFile() const {
DCHECK(IsRawFile());
DCHECK(source_ != nullptr);
return static_cast<File*>(const_cast<void*>(source_));
}
const uint8_t* GetRawData() const {
DCHECK(IsRawData());
DCHECK(source_ != nullptr);
return static_cast<const uint8_t*>(source_);
}
void SetDexLayoutData(std::vector<uint8_t>&& dexlayout_data) {
DCHECK_GE(dexlayout_data.size(), sizeof(DexFile::Header));
dexlayout_data_ = std::move(dexlayout_data);
type_ = kRawData;
source_ = dexlayout_data_.data();
}
void Clear() {
type_ = kNone;
source_ = nullptr;
// Release the memory held by `dexlayout_data_`.
std::vector<uint8_t> temp;
temp.swap(dexlayout_data_);
}
private:
Type type_;
const void* source_;
std::vector<uint8_t> dexlayout_data_;
};
// OatClassHeader is the header only part of the oat class that is required even when compilation
// is not enabled.
class OatWriter::OatClassHeader {
public:
OatClassHeader(uint32_t offset,
uint32_t num_non_null_compiled_methods,
uint32_t num_methods,
ClassStatus status)
: status_(enum_cast<uint16_t>(status)),
offset_(offset) {
// We just arbitrarily say that 0 methods means OatClassType::kNoneCompiled and that we won't
// use OatClassType::kAllCompiled unless there is at least one compiled method. This means in
// an interpreter only system, we can assert that all classes are OatClassType::kNoneCompiled.
if (num_non_null_compiled_methods == 0) {
type_ = enum_cast<uint16_t>(OatClassType::kNoneCompiled);
} else if (num_non_null_compiled_methods == num_methods) {
type_ = enum_cast<uint16_t>(OatClassType::kAllCompiled);
} else {
type_ = enum_cast<uint16_t>(OatClassType::kSomeCompiled);
}
}
bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
static size_t SizeOf() {
return sizeof(status_) + sizeof(type_);
}
// Data to write.
static_assert(sizeof(ClassStatus) <= sizeof(uint16_t), "class status won't fit in 16bits");
uint16_t status_;
static_assert(sizeof(OatClassType) <= sizeof(uint16_t), "oat_class type won't fit in 16bits");
uint16_t type_;
// Offset of start of OatClass from beginning of OatHeader. It is
// used to validate file position when writing.
uint32_t offset_;
};
// The actual oat class body contains the information about compiled methods. It is only required
// for compiler filters that have any compilation.
class OatWriter::OatClass {
public:
OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
uint32_t compiled_methods_with_code,
uint16_t oat_class_type);
OatClass(OatClass&& src) = default;
size_t SizeOf() const;
bool Write(OatWriter* oat_writer, OutputStream* out) const;
CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
return compiled_methods_[class_def_method_index];
}
// CompiledMethods for each class_def_method_index, or null if no method is available.
dchecked_vector<CompiledMethod*> compiled_methods_;
// Offset from OatClass::offset_ to the OatMethodOffsets for the
// class_def_method_index. If 0, it means the corresponding
// CompiledMethod entry in OatClass::compiled_methods_ should be
// null and that the OatClass::type_ should be OatClassType::kSomeCompiled.
dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
// Data to write.
// Number of methods recorded in OatClass. For `OatClassType::kNoneCompiled`
// this shall be zero and shall not be written to the file, otherwise it
// shall be the number of methods in the class definition. It is used to
// determine the size of `BitVector` data for `OatClassType::kSomeCompiled` and
// the size of the `OatMethodOffsets` table for `OatClassType::kAllCompiled`.
// (The size of the `OatMethodOffsets` table for `OatClassType::kSomeCompiled`
// is determined by the number of bits set in the `BitVector` data.)
uint32_t num_methods_;
// Bit vector indexed by ClassDef method index. When OatClass::type_ is
// OatClassType::kSomeCompiled, a set bit indicates the method has an
// OatMethodOffsets in methods_offsets_, otherwise
// the entry was omitted to save space. If OatClass::type_ is
// not is OatClassType::kSomeCompiled, the bitmap will be null.
std::unique_ptr<BitVector> method_bitmap_;
// OatMethodOffsets and OatMethodHeaders for each CompiledMethod
// present in the OatClass. Note that some may be missing if
// OatClass::compiled_methods_ contains null values (and
// oat_method_offsets_offsets_from_oat_class_ should contain 0
// values in this case).
dchecked_vector<OatMethodOffsets> method_offsets_;
dchecked_vector<OatQuickMethodHeader> method_headers_;
private:
size_t GetMethodOffsetsRawSize() const {
return method_offsets_.size() * sizeof(method_offsets_[0]);
}
DISALLOW_COPY_AND_ASSIGN(OatClass);
};
class OatWriter::OatDexFile {
public:
OatDexFile(const char* dex_file_location,
DexFileSource source,
uint32_t dex_file_location_checksun,
size_t dex_file_size);
OatDexFile(OatDexFile&& src) = default;
const char* GetLocation() const {
return dex_file_location_data_;
}
size_t SizeOf() const;
bool Write(OatWriter* oat_writer, OutputStream* out) const;
bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
size_t GetClassOffsetsRawSize() const {
return class_offsets_.size() * sizeof(class_offsets_[0]);
}
// The source of the dex file.
DexFileSource source_;
// Dex file size. Passed in the constructor, but could be
// overwritten by LayoutDexFile.
size_t dex_file_size_;
// Offset of start of OatDexFile from beginning of OatHeader. It is
// used to validate file position when writing.
size_t offset_;
///// Start of data to write to vdex/oat file.
const uint32_t dex_file_location_size_;
const char* const dex_file_location_data_;
// The checksum of the dex file.
const uint32_t dex_file_location_checksum_;
// Offset of the dex file in the vdex file. Set when writing dex files in
// SeekToDexFile.
uint32_t dex_file_offset_;
// The lookup table offset in the oat file. Set in WriteTypeLookupTables.
uint32_t lookup_table_offset_;
// Class and BSS offsets set in PrepareLayout.
uint32_t class_offsets_offset_;
uint32_t method_bss_mapping_offset_;
uint32_t type_bss_mapping_offset_;
uint32_t public_type_bss_mapping_offset_;
uint32_t package_type_bss_mapping_offset_;
uint32_t string_bss_mapping_offset_;
// Offset of dex sections that will have different runtime madvise states.
// Set in WriteDexLayoutSections.
uint32_t dex_sections_layout_offset_;
// Data to write to a separate section. We set the length
// of the vector in OpenDexFiles.
dchecked_vector<uint32_t> class_offsets_;
// Dex section layout info to serialize.
DexLayoutSections dex_sections_layout_;
///// End of data to write to vdex/oat file.
private:
DISALLOW_COPY_AND_ASSIGN(OatDexFile);
};
#define DCHECK_OFFSET() \
DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
<< "file_offset=" << file_offset << " relative_offset=" << relative_offset
#define DCHECK_OFFSET_() \
DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
<< "file_offset=" << file_offset << " offset_=" << offset_
OatWriter::OatWriter(const CompilerOptions& compiler_options,
TimingLogger* timings,
ProfileCompilationInfo* info,
CompactDexLevel compact_dex_level)
: write_state_(WriteState::kAddingDexFileSources),
timings_(timings),
raw_dex_files_(),
zip_archives_(),
zipped_dex_files_(),
zipped_dex_file_locations_(),
compiler_driver_(nullptr),
compiler_options_(compiler_options),
image_writer_(nullptr),
extract_dex_files_into_vdex_(true),
vdex_begin_(nullptr),
dex_files_(nullptr),
primary_oat_file_(false),
vdex_size_(0u),
vdex_dex_files_offset_(0u),
vdex_dex_shared_data_offset_(0u),
vdex_verifier_deps_offset_(0u),
vdex_quickening_info_offset_(0u),
vdex_lookup_tables_offset_(0u),
oat_checksum_(adler32(0L, Z_NULL, 0)),
code_size_(0u),
oat_size_(0u),
data_bimg_rel_ro_start_(0u),
data_bimg_rel_ro_size_(0u),
bss_start_(0u),
bss_size_(0u),
bss_methods_offset_(0u),
bss_roots_offset_(0u),
data_bimg_rel_ro_entries_(),
bss_method_entry_references_(),
bss_method_entries_(),
bss_type_entries_(),
bss_public_type_entries_(),
bss_package_type_entries_(),
bss_string_entries_(),
oat_data_offset_(0u),
oat_header_(nullptr),
size_vdex_header_(0),
size_vdex_checksums_(0),
size_dex_file_alignment_(0),
size_quickening_table_offset_(0),
size_executable_offset_alignment_(0),
size_oat_header_(0),
size_oat_header_key_value_store_(0),
size_dex_file_(0),
size_verifier_deps_(0),
size_verifier_deps_alignment_(0),
size_quickening_info_(0),
size_quickening_info_alignment_(0),
size_vdex_lookup_table_alignment_(0),
size_vdex_lookup_table_(0),
size_interpreter_to_interpreter_bridge_(0),
size_interpreter_to_compiled_code_bridge_(0),
size_jni_dlsym_lookup_trampoline_(0),
size_jni_dlsym_lookup_critical_trampoline_(0),
size_quick_generic_jni_trampoline_(0),
size_quick_imt_conflict_trampoline_(0),
size_quick_resolution_trampoline_(0),
size_quick_to_interpreter_bridge_(0),
size_nterp_trampoline_(0),
size_trampoline_alignment_(0),
size_method_header_(0),
size_code_(0),
size_code_alignment_(0),
size_data_bimg_rel_ro_(0),
size_data_bimg_rel_ro_alignment_(0),
size_relative_call_thunks_(0),
size_misc_thunks_(0),
size_vmap_table_(0),
size_method_info_(0),
size_oat_dex_file_location_size_(0),
size_oat_dex_file_location_data_(0),
size_oat_dex_file_location_checksum_(0),
size_oat_dex_file_offset_(0),
size_oat_dex_file_class_offsets_offset_(0),
size_oat_dex_file_lookup_table_offset_(0),
size_oat_dex_file_dex_layout_sections_offset_(0),
size_oat_dex_file_dex_layout_sections_(0),
size_oat_dex_file_dex_layout_sections_alignment_(0),
size_oat_dex_file_method_bss_mapping_offset_(0),
size_oat_dex_file_type_bss_mapping_offset_(0),
size_oat_dex_file_public_type_bss_mapping_offset_(0),
size_oat_dex_file_package_type_bss_mapping_offset_(0),
size_oat_dex_file_string_bss_mapping_offset_(0),
size_oat_class_offsets_alignment_(0),
size_oat_class_offsets_(0),
size_oat_class_type_(0),
size_oat_class_status_(0),
size_oat_class_num_methods_(0),
size_oat_class_method_bitmaps_(0),
size_oat_class_method_offsets_(0),
size_method_bss_mappings_(0u),
size_type_bss_mappings_(0u),
size_public_type_bss_mappings_(0u),
size_package_type_bss_mappings_(0u),
size_string_bss_mappings_(0u),
relative_patcher_(nullptr),
profile_compilation_info_(info),
compact_dex_level_(compact_dex_level) {
// If we have a profile, always use at least the default compact dex level. The reason behind
// this is that CompactDex conversion is not more expensive than normal dexlayout.
if (info != nullptr && compact_dex_level_ == CompactDexLevel::kCompactDexLevelNone) {
compact_dex_level_ = kDefaultCompactDexLevel;
}
}
static bool ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
const bool valid_standard_dex_magic = DexFileLoader::IsMagicValid(raw_header);
if (!valid_standard_dex_magic) {
LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
return false;
}
if (!DexFileLoader::IsVersionAndMagicValid(raw_header)) {
LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
return false;
}
const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
if (header->file_size_ < sizeof(DexFile::Header)) {
LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
<< " File: " << location;
return false;
}
return true;
}
static const UnalignedDexFileHeader* GetDexFileHeader(File* file,
uint8_t* raw_header,
const char* location) {
// Read the dex file header and perform minimal verification.
if (!file->ReadFully(raw_header, sizeof(DexFile::Header))) {
PLOG(ERROR) << "Failed to read dex file header. Actual: "
<< " File: " << location << " Output: " << file->GetPath();
return nullptr;
}
if (!ValidateDexFileHeader(raw_header, location)) {
return nullptr;
}
return AsUnalignedDexFileHeader(raw_header);
}
bool OatWriter::AddDexFileSource(const char* filename, const char* location) {
DCHECK(write_state_ == WriteState::kAddingDexFileSources);
File fd(filename, O_RDONLY, /* check_usage= */ false);
if (fd.Fd() == -1) {
PLOG(ERROR) << "Failed to open dex file: '" << filename << "'";
return false;
}
return AddDexFileSource(std::move(fd), location);
}
// Add dex file source(s) from a file specified by a file handle.
// Note: The `dex_file_fd` specifies a plain dex file or a zip file.
bool OatWriter::AddDexFileSource(File&& dex_file_fd, const char* location) {
DCHECK(write_state_ == WriteState::kAddingDexFileSources);
std::string error_msg;
uint32_t magic;
if (!ReadMagicAndReset(dex_file_fd.Fd(), &magic, &error_msg)) {
LOG(ERROR) << "Failed to read magic number from dex file '" << location << "': " << error_msg;
return false;
}
if (DexFileLoader::IsMagicValid(magic)) {
uint8_t raw_header[sizeof(DexFile::Header)];
const UnalignedDexFileHeader* header = GetDexFileHeader(&dex_file_fd, raw_header, location);
if (header == nullptr) {
LOG(ERROR) << "Failed to get DexFileHeader from file descriptor for '"
<< location << "': " << error_msg;
return false;
}
// The file is open for reading, not writing, so it's OK to let the File destructor
// close it without checking for explicit Close(), so pass checkUsage = false.
raw_dex_files_.emplace_back(new File(dex_file_fd.Release(), location, /* checkUsage */ false));
oat_dex_files_.emplace_back(/* OatDexFile */
location,
DexFileSource(raw_dex_files_.back().get()),
header->checksum_,
header->file_size_);
} else if (IsZipMagic(magic)) {
zip_archives_.emplace_back(ZipArchive::OpenFromFd(dex_file_fd.Release(), location, &error_msg));
ZipArchive* zip_archive = zip_archives_.back().get();
if (zip_archive == nullptr) {
LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
<< error_msg;
return false;
}
for (size_t i = 0; ; ++i) {
std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
if (entry == nullptr) {
break;
}
zipped_dex_files_.push_back(std::move(entry));
zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
const char* full_location = zipped_dex_file_locations_.back().c_str();
// We override the checksum from header with the CRC from ZIP entry.
oat_dex_files_.emplace_back(/* OatDexFile */
full_location,
DexFileSource(zipped_dex_files_.back().get()),
zipped_dex_files_.back()->GetCrc32(),
zipped_dex_files_.back()->GetUncompressedLength());
}
if (zipped_dex_file_locations_.empty()) {
LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
return false;
}
} else {
LOG(ERROR) << "Expected valid zip or dex file: '" << location << "'";
return false;
}
return true;
}
// Add dex file source(s) from a vdex file specified by a file handle.
bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file, const char* location) {
DCHECK(write_state_ == WriteState::kAddingDexFileSources);
DCHECK(vdex_file.HasDexSection());
const uint8_t* current_dex_data = nullptr;
size_t i = 0;
for (; i < vdex_file.GetNumberOfDexFiles(); ++i) {
current_dex_data = vdex_file.GetNextDexFileData(current_dex_data, i);
if (current_dex_data == nullptr) {
LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
return false;
}
if (!DexFileLoader::IsMagicValid(current_dex_data)) {
LOG(ERROR) << "Invalid magic in vdex file created from " << location;
return false;
}
// We used `zipped_dex_file_locations_` to keep the strings in memory.
zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
const char* full_location = zipped_dex_file_locations_.back().c_str();
const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(current_dex_data);
oat_dex_files_.emplace_back(/* OatDexFile */
full_location,
DexFileSource(current_dex_data),
vdex_file.GetLocationChecksum(i),
header->file_size_);
}
if (vdex_file.GetNextDexFileData(current_dex_data, i) != nullptr) {
LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
return false;
}
if (oat_dex_files_.empty()) {
LOG(ERROR) << "No dex files in vdex file created from " << location;
return false;
}
return true;
}
// Add dex file source from raw memory.
bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
const char* location,
uint32_t location_checksum) {
DCHECK(write_state_ == WriteState::kAddingDexFileSources);
if (data.size() < sizeof(DexFile::Header)) {
LOG(ERROR) << "Provided data is shorter than dex file header. size: "
<< data.size() << " File: " << location;
return false;
}
if (!ValidateDexFileHeader(data.data(), location)) {
return false;
}
const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
if (data.size() < header->file_size_) {
LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
<< " file size from header: " << header->file_size_ << " File: " << location;
return false;
}
oat_dex_files_.emplace_back(/* OatDexFile */
location,
DexFileSource(data.data()),
location_checksum,
header->file_size_);
return true;
}
dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
dchecked_vector<std::string> locations;
locations.reserve(oat_dex_files_.size());
for (const OatDexFile& oat_dex_file : oat_dex_files_) {
locations.push_back(oat_dex_file.GetLocation());
}
return locations;
}
bool OatWriter::MayHaveCompiledMethods() const {
return GetCompilerOptions().IsAnyCompilationEnabled();
}
bool OatWriter::WriteAndOpenDexFiles(
File* vdex_file,
bool verify,
bool update_input_vdex,
CopyOption copy_dex_files,
/*out*/ std::vector<MemMap>* opened_dex_files_map,
/*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
CHECK(write_state_ == WriteState::kAddingDexFileSources);
size_vdex_header_ = sizeof(VdexFile::VdexFileHeader) +
VdexSection::kNumberOfSections * sizeof(VdexFile::VdexSectionHeader);
// Reserve space for Vdex header, sections, and checksums.
vdex_size_ = size_vdex_header_ + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
// Write DEX files into VDEX, mmap and open them.
std::vector<MemMap> dex_files_map;
std::vector<std::unique_ptr<const DexFile>> dex_files;
if (!WriteDexFiles(vdex_file, update_input_vdex, copy_dex_files, &dex_files_map) ||
!OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
return false;
}
*opened_dex_files_map = std::move(dex_files_map);
*opened_dex_files = std::move(dex_files);
// Create type lookup tables to speed up lookups during compilation.
InitializeTypeLookupTables(*opened_dex_files);
write_state_ = WriteState::kStartRoData;
return true;
}
bool OatWriter::StartRoData(const std::vector<const DexFile*>& dex_files,
OutputStream* oat_rodata,
SafeMap<std::string, std::string>* key_value_store) {
CHECK(write_state_ == WriteState::kStartRoData);
// Record the ELF rodata section offset, i.e. the beginning of the OAT data.
if (!RecordOatDataOffset(oat_rodata)) {
return false;
}
// Record whether this is the primary oat file.
primary_oat_file_ = (key_value_store != nullptr);
// Initialize OAT header.
oat_size_ = InitOatHeader(dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
key_value_store);
ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, this);
// Write dex layout sections into the oat file.
if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
return false;
}
write_state_ = WriteState::kInitialize;
return true;
}
// Initialize the writer with the given parameters.
void OatWriter::Initialize(const CompilerDriver* compiler_driver,
ImageWriter* image_writer,
const std::vector<const DexFile*>& dex_files) {
CHECK(write_state_ == WriteState::kInitialize);
compiler_driver_ = compiler_driver;
image_writer_ = image_writer;
dex_files_ = &dex_files;
write_state_ = WriteState::kPrepareLayout;
}
void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
CHECK(write_state_ == WriteState::kPrepareLayout);
relative_patcher_ = relative_patcher;
SetMultiOatRelativePatcherAdjustment();
if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension()) {
CHECK(image_writer_ != nullptr);
}
InstructionSet instruction_set = compiler_options_.GetInstructionSet();
CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
{
TimingLogger::ScopedTiming split("InitBssLayout", timings_);
InitBssLayout(instruction_set);
}
uint32_t offset = oat_size_;
{
TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
offset = InitClassOffsets(offset);
}
{
TimingLogger::ScopedTiming split("InitOatClasses", timings_);
offset = InitOatClasses(offset);
}
{
TimingLogger::ScopedTiming split("InitIndexBssMappings", timings_);
offset = InitIndexBssMappings(offset);
}
{
TimingLogger::ScopedTiming split("InitOatMaps", timings_);
offset = InitOatMaps(offset);
}
{
TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
oat_header_->SetOatDexFilesOffset(offset);
offset = InitOatDexFiles(offset);
}
{
TimingLogger::ScopedTiming split("InitOatCode", timings_);
offset = InitOatCode(offset);
}
{
TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
offset = InitOatCodeDexFiles(offset);
code_size_ = offset - GetOatHeader().GetExecutableOffset();
}
{
TimingLogger::ScopedTiming split("InitDataBimgRelRoLayout", timings_);
offset = InitDataBimgRelRoLayout(offset);
}
oat_size_ = offset; // .bss does not count towards oat_size_.
bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
write_state_ = WriteState::kWriteRoData;
}
OatWriter::~OatWriter() {
}
class OatWriter::DexMethodVisitor {
public:
DexMethodVisitor(OatWriter* writer, size_t offset)
: writer_(writer),
offset_(offset),
dex_file_(nullptr),
class_def_index_(dex::kDexNoIndex) {}
virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
DCHECK(dex_file_ == nullptr);
DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
dex_file_ = dex_file;
class_def_index_ = class_def_index;
return true;
}
virtual bool VisitMethod(size_t class_def_method_index, const ClassAccessor::Method& method) = 0;
virtual bool EndClass() {
if (kIsDebugBuild) {
dex_file_ = nullptr;
class_def_index_ = dex::kDexNoIndex;
}
return true;
}
size_t GetOffset() const {
return offset_;
}
protected:
virtual ~DexMethodVisitor() { }
OatWriter* const writer_;
// The offset is usually advanced for each visited method by the derived class.
size_t offset_;
// The dex file and class def index are set in StartClass().
const DexFile* dex_file_;
size_t class_def_index_;
};
class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
public:
OatDexMethodVisitor(OatWriter* writer, size_t offset)
: DexMethodVisitor(writer, offset),
oat_class_index_(0u),
method_offsets_index_(0u) {}
bool StartClass(const DexFile* dex_file, size_t class_def_index) override {
DexMethodVisitor::StartClass(dex_file, class_def_index);
if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
// There are no oat classes if there aren't any compiled methods.
CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
}
method_offsets_index_ = 0u;
return true;
}
bool EndClass() override {
++oat_class_index_;
return DexMethodVisitor::EndClass();
}
protected:
size_t oat_class_index_;
size_t method_offsets_index_;
};
static bool HasCompiledCode(const CompiledMethod* method) {
return method != nullptr && !method->GetQuickCode().empty();
}
class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
public:
explicit InitBssLayoutMethodVisitor(OatWriter* writer)
: DexMethodVisitor(writer, /* offset */ 0u) {}
bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
const ClassAccessor::Method& method) override {
// Look for patches with .bss references and prepare maps with placeholders for their offsets.
CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
MethodReference(dex_file_, method.GetIndex()));
if (HasCompiledCode(compiled_method)) {
for (const LinkerPatch& patch : compiled_method->GetPatches()) {
if (patch.GetType() == LinkerPatch::Type::kDataBimgRelRo) {
writer_->data_bimg_rel_ro_entries_.Overwrite(patch.BootImageOffset(),
/* placeholder */ 0u);
} else if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
MethodReference target_method = patch.TargetMethod();
AddBssReference(target_method,
target_method.dex_file->NumMethodIds(),
&writer_->bss_method_entry_references_);
writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
} else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
AddBssReference(target_type,
target_type.dex_file->NumTypeIds(),
&writer_->bss_type_entry_references_);
writer_->bss_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
} else if (patch.GetType() == LinkerPatch::Type::kPublicTypeBssEntry) {
TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
AddBssReference(target_type,
target_type.dex_file->NumTypeIds(),
&writer_->bss_public_type_entry_references_);
writer_->bss_public_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
} else if (patch.GetType() == LinkerPatch::Type::kPackageTypeBssEntry) {
TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
AddBssReference(target_type,
target_type.dex_file->NumTypeIds(),
&writer_->bss_package_type_entry_references_);
writer_->bss_package_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
} else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
StringReference target_string(patch.TargetStringDexFile(), patch.TargetStringIndex());
AddBssReference(target_string,
target_string.dex_file->NumStringIds(),
&writer_->bss_string_entry_references_);
writer_->bss_string_entries_.Overwrite(target_string, /* placeholder */ 0u);
}
}
} else {
DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
}
return true;
}
private:
void AddBssReference(const DexFileReference& ref,
size_t number_of_indexes,
/*inout*/ SafeMap<const DexFile*, BitVector>* references) {
// We currently support inlining of throwing instructions only when they originate in the
// same dex file as the outer method. All .bss references are used by throwing instructions.
DCHECK_EQ(dex_file_, ref.dex_file);
DCHECK_LT(ref.index, number_of_indexes);
auto refs_it = references->find(ref.dex_file);
if (refs_it == references->end()) {
refs_it = references->Put(
ref.dex_file,
BitVector(number_of_indexes, /* expandable */ false, Allocator::GetMallocAllocator()));
refs_it->second.ClearAllBits();
}
refs_it->second.SetBit(ref.index);
}
};
class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
public:
InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
: DexMethodVisitor(writer, offset),
compiled_methods_(),
compiled_methods_with_code_(0u) {
size_t num_classes = 0u;
for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
num_classes += oat_dex_file.class_offsets_.size();
}
// If we aren't compiling only reserve headers.
writer_->oat_class_headers_.reserve(num_classes);
if (writer->MayHaveCompiledMethods()) {
writer->oat_classes_.reserve(num_classes);
}
compiled_methods_.reserve(256u);
// If there are any classes, the class offsets allocation aligns the offset.
DCHECK(num_classes == 0u || IsAligned<4u>(offset));
}
bool StartClass(const DexFile* dex_file, size_t class_def_index) override {
DexMethodVisitor::StartClass(dex_file, class_def_index);
compiled_methods_.clear();
compiled_methods_with_code_ = 0u;
return true;
}
bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
const ClassAccessor::Method& method) override {
// Fill in the compiled_methods_ array for methods that have a
// CompiledMethod. We track the number of non-null entries in
// compiled_methods_with_code_ since we only want to allocate
// OatMethodOffsets for the compiled methods.
uint32_t method_idx = method.GetIndex();
CompiledMethod* compiled_method =
writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
compiled_methods_.push_back(compiled_method);
if (HasCompiledCode(compiled_method)) {
++compiled_methods_with_code_;
}
return true;
}
bool EndClass() override {
ClassReference class_ref(dex_file_, class_def_index_);
ClassStatus status;
bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
if (!found) {
const VerificationResults* results = writer_->compiler_options_.GetVerificationResults();
if (results != nullptr && results->IsClassRejected(class_ref)) {
// The oat class status is used only for verification of resolved classes,
// so use ClassStatus::kErrorResolved whether the class was resolved or unresolved
// during compile-time verification.
status = ClassStatus::kErrorResolved;
} else {
status = ClassStatus::kNotReady;
}
}
// We never emit kRetryVerificationAtRuntime, instead we mark the class as
// resolved and the class will therefore be re-verified at runtime.
if (status == ClassStatus::kRetryVerificationAtRuntime) {
status = ClassStatus::kResolved;
}
writer_->oat_class_headers_.emplace_back(offset_,
compiled_methods_with_code_,
compiled_methods_.size(),
status);
OatClassHeader& header = writer_->oat_class_headers_.back();
offset_ += header.SizeOf();
if (writer_->MayHaveCompiledMethods()) {
writer_->oat_classes_.emplace_back(compiled_methods_,
compiled_methods_with_code_,
header.type_);
offset_ += writer_->oat_classes_.back().SizeOf();
}
return DexMethodVisitor::EndClass();
}
private:
dchecked_vector<CompiledMethod*> compiled_methods_;
size_t compiled_methods_with_code_;
};
// CompiledMethod + metadata required to do ordered method layout.
//
// See also OrderedMethodVisitor.
struct OatWriter::OrderedMethodData {
ProfileCompilationInfo::MethodHotness method_hotness;
OatClass* oat_class;
CompiledMethod* compiled_method;
MethodReference method_reference;
size_t method_offsets_index;
size_t class_def_index;
uint32_t access_flags;
const dex::CodeItem* code_item;
// A value of -1 denotes missing debug info
static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
// Index into writer_->method_info_
size_t debug_info_idx;
bool HasDebugInfo() const {
return debug_info_idx != kDebugInfoIdxInvalid;
}
// Bin each method according to the profile flags.
//
// Groups by e.g.
// -- not hot at all
// -- hot
// -- hot and startup
// -- hot and post-startup
// -- hot and startup and poststartup
// -- startup
// -- startup and post-startup
// -- post-startup
//
// (See MethodHotness enum definition for up-to-date binning order.)
bool operator<(const OrderedMethodData& other) const {
if (kOatWriterForceOatCodeLayout) {
// Development flag: Override default behavior by sorting by name.
std::string name = method_reference.PrettyMethod();
std::string other_name = other.method_reference.PrettyMethod();
return name < other_name;
}
// Use the profile's method hotness to determine sort order.
if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
return true;
}
// Default: retain the original order.
return false;
}
private:
// Used to determine relative order for OAT code layout when determining
// binning.
size_t GetMethodHotnessOrder() const {
bool hotness[] = {
method_hotness.IsHot(),
method_hotness.IsStartup(),
method_hotness.IsPostStartup()
};
// Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
// any memory, it only goes into the buffer cache and does not grow the PSS until the first
// time that memory is referenced in the process.
size_t hotness_bits = 0;
for (size_t i = 0; i < arraysize(hotness); ++i) {
if (hotness[i]) {
hotness_bits |= (1 << i);
}
}
if (kIsDebugBuild) {
// Check for bins that are always-empty given a real profile.
if (method_hotness.IsHot() &&
!method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
std::string name = method_reference.PrettyMethod();
LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
<< "either start-up or post-startup. Possible corrupted profile?";
// This is not fatal, so only warn.
}
}
return hotness_bits;
}
};
// Given a queue of CompiledMethod in some total order,
// visit each one in that order.
class OatWriter::OrderedMethodVisitor {
public:
explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
: ordered_methods_(std::move(ordered_methods)) {
}
virtual ~OrderedMethodVisitor() {}
// Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
if (!VisitStart()) {
return false;
}
for (const OrderedMethodData& method_data : ordered_methods_) {
if (!VisitMethod(method_data)) {
return false;
}
}
return VisitComplete();
}
// Invoked once at the beginning, prior to visiting anything else.
//
// Return false to abort further visiting.
virtual bool VisitStart() { return true; }
// Invoked repeatedly in the order specified by `ordered_methods`.
//
// Return false to short-circuit and to stop visiting further methods.
virtual bool VisitMethod(const OrderedMethodData& method_data)
REQUIRES_SHARED(Locks::mutator_lock_) = 0;
// Invoked once at the end, after every other method has been successfully visited.
//
// Return false to indicate the overall `Visit` has failed.
virtual bool VisitComplete() = 0;
OrderedMethodList ReleaseOrderedMethods() {
return std::move(ordered_methods_);
}
private:
// List of compiled methods, sorted by the order defined in OrderedMethodData.
// Methods can be inserted more than once in case of duplicated methods.
OrderedMethodList ordered_methods_;
};
// Visit every compiled method in order to determine its order within the OAT file.
// Methods from the same class do not need to be adjacent in the OAT code.
class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
public:
LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
: OatDexMethodVisitor(writer, offset) {
}
bool EndClass() override {
OatDexMethodVisitor::EndClass();
return true;
}
bool VisitMethod(size_t class_def_method_index,
const ClassAccessor::Method& method)
override
REQUIRES_SHARED(Locks::mutator_lock_) {
Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
if (HasCompiledCode(compiled_method)) {
size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
{
const CompilerOptions& compiler_options = writer_->GetCompilerOptions();
ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
uint32_t code_size = quick_code.size() * sizeof(uint8_t);
// Debug method info must be pushed in the original order
// (i.e. all methods from the same class must be adjacent in the debug info sections)
// ElfCompilationUnitWriter::Write requires this.
if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
debug::MethodDebugInfo info = debug::MethodDebugInfo();
writer_->method_info_.push_back(info);
// The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
// once we know the offsets.
//
// Store the index into writer_->method_info_ since future push-backs
// could reallocate and change the underlying data address.
debug_info_idx = writer_->method_info_.size() - 1;
}
}
MethodReference method_ref(dex_file_, method.GetIndex());
// Lookup method hotness from profile, if available.
// Otherwise assume a default of none-hotness.
ProfileCompilationInfo::MethodHotness method_hotness =
writer_->profile_compilation_info_ != nullptr
? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
: ProfileCompilationInfo::MethodHotness();
// Handle duplicate methods by pushing them repeatedly.
OrderedMethodData method_data = {
method_hotness,
oat_class,
compiled_method,
method_ref,
method_offsets_index_,
class_def_index_,
method.GetAccessFlags(),
method.GetCodeItem(),
debug_info_idx
};
ordered_methods_.push_back(method_data);
method_offsets_index_++;
}
return true;
}
OrderedMethodList ReleaseOrderedMethods() {
if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
// Sort by the method ordering criteria (in OrderedMethodData).
// Since most methods will have the same ordering criteria,
// we preserve the original insertion order within the same sort order.
std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
} else {
// The profile-less behavior is as if every method had 0 hotness
// associated with it.
//
// Since sorting all methods with hotness=0 should give back the same
// order as before, don't do anything.
DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
}
return std::move(ordered_methods_);
}
private:
// List of compiled methods, later to be sorted by order defined in OrderedMethodData.
// Methods can be inserted more than once in case of duplicated methods.
OrderedMethodList ordered_methods_;
};
// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
public:
LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
size_t offset,
OrderedMethodList ordered_methods)
: LayoutReserveOffsetCodeMethodVisitor(writer,
offset,
writer->GetCompilerOptions(),
std::move(ordered_methods)) {
}
bool VisitComplete() override {
offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
if (generate_debug_info_) {
std::vector<debug::MethodDebugInfo> thunk_infos =
relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
writer_->method_info_.insert(writer_->method_info_.end(),
std::make_move_iterator(thunk_infos.begin()),
std::make_move_iterator(thunk_infos.end()));
}
return true;
}
bool VisitMethod(const OrderedMethodData& method_data) override
REQUIRES_SHARED(Locks::mutator_lock_) {
OatClass* oat_class = method_data.oat_class;
CompiledMethod* compiled_method = method_data.compiled_method;
const MethodReference& method_ref = method_data.method_reference;
uint16_t method_offsets_index_ = method_data.method_offsets_index;
size_t class_def_index = method_data.class_def_index;
uint32_t access_flags = method_data.access_flags;
bool has_debug_info = method_data.HasDebugInfo();
size_t debug_info_idx = method_data.debug_info_idx;
DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
// Derived from CompiledMethod.
uint32_t quick_code_offset = 0;
ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
uint32_t code_size = quick_code.size() * sizeof(uint8_t);
uint32_t thumb_offset = compiled_method->CodeDelta();
// Deduplicate code arrays if we are not producing debuggable code.
bool deduped = true;
if (debuggable_) {
quick_code_offset = relative_patcher_->GetOffset(method_ref);
if (quick_code_offset != 0u) {
// Duplicate methods, we want the same code for both of them so that the oat writer puts
// the same code in both ArtMethods so that we do not get different oat code at runtime.
} else {
quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
deduped = false;
}
} else {
quick_code_offset = dedupe_map_.GetOrCreate(
compiled_method,
[this, &deduped, compiled_method, &method_ref, thumb_offset]() {
deduped = false;
return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
});
}
if (code_size != 0) {
if (relative_patcher_->GetOffset(method_ref) != 0u) {
// TODO: Should this be a hard failure?
LOG(WARNING) << "Multiple definitions of "
<< method_ref.dex_file->PrettyMethod(method_ref.index)
<< " offsets " << relative_patcher_->GetOffset(method_ref)
<< " " << quick_code_offset;
} else {
relative_patcher_->SetOffset(method_ref, quick_code_offset);
}
}
// Update quick method header.
DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
uint32_t code_info_offset = method_header->GetCodeInfoOffset();
uint32_t code_offset = quick_code_offset - thumb_offset;
CHECK(!compiled_method->GetQuickCode().empty());
// If the code is compiled, we write the offset of the stack map relative
// to the code. The offset was previously stored relative to start of file.
if (code_info_offset != 0u) {
DCHECK_LT(code_info_offset, code_offset);
code_info_offset = code_offset - code_info_offset;
}
*method_header = OatQuickMethodHeader(code_info_offset);
if (!deduped) {
// Update offsets. (Checksum is updated when writing.)
offset_ += sizeof(*method_header); // Method header is prepended before code.
offset_ += code_size;
}
// Exclude quickened dex methods (code_size == 0) since they have no native code.
if (generate_debug_info_ && code_size != 0) {
DCHECK(has_debug_info);
const uint8_t* code_info = compiled_method->GetVmapTable().data();
DCHECK(code_info != nullptr);
// Record debug information for this function if we are doing that.
debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
// Simpleperf relies on art_jni_trampoline to detect jni methods.
info.custom_name = (access_flags & kAccNative) ? "art_jni_trampoline" : "";
info.dex_file = method_ref.dex_file;
info.class_def_index = class_def_index;
info.dex_method_index = method_ref.index;
info.access_flags = access_flags;
// For intrinsics emitted by codegen, the code has no relation to the original code item.
info.code_item = compiled_method->IsIntrinsic() ? nullptr : method_data.code_item;
info.isa = compiled_method->GetInstructionSet();
info.deduped = deduped;
info.is_native_debuggable = native_debuggable_;
info.is_optimized = method_header->IsOptimized();
info.is_code_address_text_relative = true;
info.code_address = code_offset - executable_offset_;
info.code_size = code_size;
info.frame_size_in_bytes = CodeInfo::DecodeFrameInfo(code_info).FrameSizeInBytes();
info.code_info = code_info;
info.cfi = compiled_method->GetCFIInfo();
} else {
DCHECK(!has_debug_info);
}
DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
offsets->code_offset_ = quick_code_offset;
return true;
}
size_t GetOffset() const {
return offset_;
}
private:
LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
size_t offset,
const CompilerOptions& compiler_options,
OrderedMethodList ordered_methods)
: OrderedMethodVisitor(std::move(ordered_methods)),
writer_(writer),
offset_(offset),
relative_patcher_(writer->relative_patcher_),
executable_offset_(writer->oat_header_->GetExecutableOffset()),
debuggable_(compiler_options.GetDebuggable()),
native_debuggable_(compiler_options.GetNativeDebuggable()),
generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {}
struct CodeOffsetsKeyComparator {
bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
// Code is deduplicated by CompilerDriver, compare only data pointers.
if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
}
// If the code is the same, all other fields are likely to be the same as well.
if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
}
if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
return lhs->GetPatches().data() < rhs->GetPatches().data();
}
if (UNLIKELY(lhs->IsIntrinsic() != rhs->IsIntrinsic())) {
return rhs->IsIntrinsic();
}
return false;
}
};
uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
const MethodReference& method_ref,
uint32_t thumb_offset) {
offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
offset_ += CodeAlignmentSize(offset_, *compiled_method);
DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
}
OatWriter* writer_;
// Offset of the code of the compiled methods.
size_t offset_;
// Deduplication is already done on a pointer basis by the compiler driver,
// so we can simply compare the pointers to find out if things are duplicated.
SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
// Cache writer_'s members and compiler options.
MultiOatRelativePatcher* relative_patcher_;
uint32_t executable_offset_;
const bool debuggable_;
const bool native_debuggable_;
const bool generate_debug_info_;
};
class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
public:
InitMapMethodVisitor(OatWriter* writer, size_t offset)
: OatDexMethodVisitor(writer, offset),
dedupe_bit_table_(&writer_->code_info_data_) {
}
bool VisitMethod(size_t class_def_method_index,
const ClassAccessor::Method& method ATTRIBUTE_UNUSED)
override REQUIRES_SHARED(Locks::mutator_lock_) {
OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
if (HasCompiledCode(compiled_method)) {
DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetCodeInfoOffset(), 0u);
ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
if (map.size() != 0u) {
size_t offset = dedupe_code_info_.GetOrCreate(map.data(), [=]() {
// Deduplicate the inner BitTable<>s within the CodeInfo.
return offset_ + dedupe_bit_table_.Dedupe(map.data());
});
// Code offset is not initialized yet, so set file offset for now.
DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
oat_class->method_headers_[method_offsets_index_].SetCodeInfoOffset(offset);
}
++method_offsets_index_;
}
return true;
}
private:
// Deduplicate at CodeInfo level. The value is byte offset within code_info_data_.
// This deduplicates the whole CodeInfo object without going into the inner tables.
// The compiler already deduplicated the pointers but it did not dedupe the tables.
SafeMap<const uint8_t*, size_t> dedupe_code_info_;
// Deduplicate at BitTable level.
CodeInfo::Deduper dedupe_bit_table_;
};
class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
public:
InitImageMethodVisitor(OatWriter* writer,
size_t offset,
const std::vector<const DexFile*>* dex_files)
: OatDexMethodVisitor(writer, offset),
pointer_size_(GetInstructionSetPointerSize(writer_->compiler_options_.GetInstructionSet())),
class_loader_(writer->HasImage() ? writer->image_writer_->GetAppClassLoader() : nullptr),
dex_files_(dex_files),
class_linker_(Runtime::Current()->GetClassLinker()) {}
// Handle copied methods here. Copy pointer to quick code from
// an origin method to a copied method only if they are
// in the same oat file. If the origin and the copied methods are
// in different oat files don't touch the copied method.
// References to other oat files are not supported yet.
bool StartClass(const DexFile* dex_file, size_t class_def_index) override
REQUIRES_SHARED(Locks::mutator_lock_) {
OatDexMethodVisitor::StartClass(dex_file, class_def_index);
// Skip classes that are not in the image.
if (!IsImageClass()) {
return true;
}
ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
const dex::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
ObjPtr<mirror::Class> klass =
class_linker_->LookupResolvedType(class_def.class_idx_, dex_cache, class_loader_);
if (klass != nullptr) {
for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
// Find origin method. Declaring class and dex_method_idx
// in the copied method should be the same as in the origin
// method.
ObjPtr<mirror::Class> declaring_class = method.GetDeclaringClass();
ArtMethod* origin = declaring_class->FindClassMethod(
declaring_class->GetDexCache(),
method.GetDexMethodIndex(),
pointer_size_);
CHECK(origin != nullptr);
CHECK(!origin->IsDirect());
CHECK(origin->GetDeclaringClass() == declaring_class);
if (IsInOatFile(&declaring_class->GetDexFile())) {
const void* code_ptr =
origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
if (code_ptr == nullptr) {
methods_to_process_.push_back(std::make_pair(&method, origin));
} else {
method.SetEntryPointFromQuickCompiledCodePtrSize(
code_ptr, pointer_size_);
}
}
}
}
return true;
}
bool VisitMethod(size_t class_def_method_index, const ClassAccessor::Method& method) override
REQUIRES_SHARED(Locks::mutator_lock_) {
// Skip methods that are not in the image.
if (!IsImageClass()) {
return true;
}
OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
OatMethodOffsets offsets(0u);
if (HasCompiledCode(compiled_method)) {
DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
offsets = oat_class->method_offsets_[method_offsets_index_];
++method_offsets_index_;
}
Thread* self = Thread::Current();
ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
ArtMethod* resolved_method;
if (writer_->GetCompilerOptions().IsBootImage() ||
writer_->GetCompilerOptions().IsBootImageExtension()) {
resolved_method = class_linker_->LookupResolvedMethod(
method.GetIndex(), dex_cache, /*class_loader=*/ nullptr);
if (resolved_method == nullptr) {
LOG(FATAL) << "Unexpected failure to look up a method: "
<< dex_file_->PrettyMethod(method.GetIndex(), true);
UNREACHABLE();
}
} else {
// Should already have been resolved by the compiler.
// It may not be resolved if the class failed to verify, in this case, don't set the
// entrypoint. This is not fatal since we shall use a resolution method.
resolved_method = class_linker_->LookupResolvedMethod(method.GetIndex(),
dex_cache,
class_loader_);
}
if (resolved_method != nullptr &&
compiled_method != nullptr &&
compiled_method->GetQuickCode().size() != 0) {
resolved_method->SetEntryPointFromQuickCompiledCodePtrSize(
reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
}
return true;
}
// Check whether current class is image class
bool IsImageClass() {
const dex::TypeId& type_id =
dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
return writer_->GetCompilerOptions().IsImageClass(class_descriptor);
}
// Check whether specified dex file is in the compiled oat file.
bool IsInOatFile(const DexFile* dex_file) {
return ContainsElement(*dex_files_, dex_file);
}
// Assign a pointer to quick code for copied methods
// not handled in the method StartClass
void Postprocess() REQUIRES_SHARED(Locks::mutator_lock_) {
for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
ArtMethod* method = p.first;
ArtMethod* origin = p.second;
const void* code_ptr =
origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
if (code_ptr != nullptr) {
method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
}
}
}
private:
const PointerSize pointer_size_;
ObjPtr<mirror::ClassLoader> class_loader_;
const std::vector<const DexFile*>* dex_files_;
ClassLinker* const class_linker_;
std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
};
class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
public:
WriteCodeMethodVisitor(OatWriter* writer,
OutputStream* out,
const size_t file_offset,
size_t relative_offset,
OrderedMethodList ordered_methods)
: OrderedMethodVisitor(std::move(ordered_methods)),
writer_(writer),
offset_(relative_offset),
dex_file_(nullptr),
pointer_size_(GetInstructionSetPointerSize(writer_->compiler_options_.GetInstructionSet())),
class_loader_(writer->HasImage() ? writer->image_writer_->GetAppClassLoader() : nullptr),
out_(out),
file_offset_(file_offset),
class_linker_(Runtime::Current()->GetClassLinker()),
dex_cache_(nullptr),
no_thread_suspension_("OatWriter patching") {
patched_code_.reserve(16 * KB);
if (writer_->GetCompilerOptions().IsBootImage() ||
writer_->GetCompilerOptions().IsBootImageExtension()) {
// If we're creating the image, the address space must be ready so that we can apply patches.
CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
}
}
bool VisitStart() override {
return true;
}
void UpdateDexFileAndDexCache(const DexFile* dex_file)
REQUIRES_SHARED(Locks::mutator_lock_) {
dex_file_ = dex_file;
// Ordered method visiting is only for compiled methods.
DCHECK(writer_->MayHaveCompiledMethods());
if (writer_->GetCompilerOptions().IsAotCompilationEnabled()) {
// Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
DCHECK(dex_cache_ != nullptr);
}
}
}
bool VisitComplete() override {
offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
if (UNLIKELY(offset_ == 0u)) {
PLOG(ERROR) << "Failed to write final relative call thunks";
return false;
}
return true;
}
bool VisitMethod(const OrderedMethodData& method_data) override
REQUIRES_SHARED(Locks::mutator_lock_) {
const MethodReference& method_ref = method_data.method_reference;
UpdateDexFileAndDexCache(method_ref.dex_file);
OatClass* oat_class = method_data.oat_class;
CompiledMethod* compiled_method = method_data.compiled_method;
uint16_t method_offsets_index = method_data.method_offsets_index;
// No thread suspension since dex_cache_ that may get invalidated if that occurs.
ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
// TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
size_t file_offset = file_offset_; // Used by DCHECK_OFFSET_ macro.
OutputStream* out = out_;
ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
uint32_t code_size = quick_code.size() * sizeof(uint8_t);
// Deduplicate code arrays.
const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
if (method_offsets.code_offset_ > offset_) {
offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
if (offset_ == 0u) {
ReportWriteFailure("relative call thunk", method_ref);
return false;
}
uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
if (alignment_size != 0) {
if (!writer_->WriteCodeAlignment(out, alignment_size)) {
ReportWriteFailure("code alignment padding", method_ref);
return false;
}
offset_ += alignment_size;
DCHECK_OFFSET_();
}
DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
DCHECK_EQ(method_offsets.code_offset_,
offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
<< dex_file_->PrettyMethod(method_ref.index);
const OatQuickMethodHeader& method_header =
oat_class->method_headers_[method_offsets_index];
if (!out->WriteFully(&method_header, sizeof(method_header))) {
ReportWriteFailure("method header", method_ref);
return false;
}
writer_->size_method_header_ += sizeof(method_header);
offset_ += sizeof(method_header);
DCHECK_OFFSET_();
if (!compiled_method->GetPatches().empty()) {
patched_code_.assign(quick_code.begin(), quick_code.end());
quick_code = ArrayRef<const uint8_t>(patched_code_);
for (const LinkerPatch& patch : compiled_method->GetPatches()) {
uint32_t literal_offset = patch.LiteralOffset();
switch (patch.GetType()) {
case LinkerPatch::Type::kIntrinsicReference: {
uint32_t target_offset = GetTargetIntrinsicReferenceOffset(patch);
writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
patch,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kDataBimgRelRo: {
uint32_t target_offset =
writer_->data_bimg_rel_ro_start_ +
writer_->data_bimg_rel_ro_entries_.Get(patch.BootImageOffset());
writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
patch,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kMethodBssEntry: {
uint32_t target_offset =
writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
patch,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kCallRelative: {
// NOTE: Relative calls across oat files are not supported.
uint32_t target_offset = GetTargetOffset(patch);
writer_->relative_patcher_->PatchCall(&patched_code_,
literal_offset,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kStringRelative: {
uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
patch,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kStringBssEntry: {
StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
uint32_t target_offset =
writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
patch,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kTypeRelative: {
uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
patch,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kTypeBssEntry: {
TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
patch,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kPublicTypeBssEntry: {
TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
uint32_t target_offset =
writer_->bss_start_ + writer_->bss_public_type_entries_.Get(ref);
writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
patch,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kPackageTypeBssEntry: {
TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
uint32_t target_offset =
writer_->bss_start_ + writer_->bss_package_type_entries_.Get(ref);
writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
patch,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kMethodRelative: {
uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
patch,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kJniEntrypointRelative: {
DCHECK(GetTargetMethod(patch)->IsNative());
uint32_t target_offset =
GetTargetMethodOffset(GetTargetMethod(patch)) +
ArtMethod::EntryPointFromJniOffset(pointer_size_).Uint32Value();
writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
patch,
offset_ + literal_offset,
target_offset);
break;
}
case LinkerPatch::Type::kCallEntrypoint: {
writer_->relative_patcher_->PatchEntrypointCall(&patched_code_,
patch,
offset_ + literal_offset);
break;
}
case LinkerPatch::Type::kBakerReadBarrierBranch: {
writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
patch,
offset_ + literal_offset);
break;
}
default: {
DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
break;
}
}
}
}
if (!out->WriteFully(quick_code.data(), code_size)) {
ReportWriteFailure("method code", method_ref);
return false;
}
writer_->size_code_ += code_size;
offset_ += code_size;
}
DCHECK_OFFSET_();
return true;
}
size_t GetOffset() const {
return offset_;
}
private:
OatWriter* const writer_;
// Updated in VisitMethod as methods are written out.
size_t offset_;
// Potentially varies with every different VisitMethod.
// Used to determine which DexCache to use when finding ArtMethods.
const DexFile* dex_file_;
// Pointer size we are compiling to.
const PointerSize pointer_size_;
// The image writer's classloader, if there is one, else null.
ObjPtr<mirror::ClassLoader> class_loader_;
// Stream to output file, where the OAT code will be written to.
OutputStream* const out_;
const size_t file_offset_;
ClassLinker* const class_linker_;
ObjPtr<mirror::DexCache> dex_cache_;
std::vector<uint8_t> patched_code_;
const ScopedAssertNoThreadSuspension no_thread_suspension_;
void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
PLOG(ERROR) << "Failed to write " << what << " for "
<< method_ref.PrettyMethod() << " to " << out_->GetLocation();
}
ArtMethod* GetTargetMethod(const LinkerPatch& patch)
REQUIRES_SHARED(Locks::mutator_lock_) {
MethodReference ref = patch.TargetMethod();
ObjPtr<mirror::DexCache> dex_cache =
(dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
Thread::Current(), *ref.dex_file);
ArtMethod* method =
class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
CHECK(method != nullptr);
return method;
}
uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
// If there's no new compiled code, we need to point to the correct trampoline.
if (UNLIKELY(target_offset == 0)) {
ArtMethod* target = GetTargetMethod(patch);
DCHECK(target != nullptr);
// TODO: Remove kCallRelative? This patch type is currently not in use.
// If we want to use it again, we should make sure that we either use it
// only for target methods that were actually compiled, or call the
// method dispatch thunk. Currently, ARM/ARM64 patchers would emit the
// thunk for far `target_offset` (so we could teach them to use the
// thunk for `target_offset == 0`) but x86/x86-64 patchers do not.
// (When this was originally implemented, every oat file contained
// trampolines, so we could just return their offset here. Now only
// the boot image contains them, so this is not always an option.)
LOG(FATAL) << "The target method was not compiled.";
}
return target_offset;
}
ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
REQUIRES_SHARED(Locks::mutator_lock_) {
return (target_dex_file == dex_file_)
? dex_cache_
: class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
}
ObjPtr<mirror::Class> GetTargetType(const LinkerPatch& patch)
REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(writer_->HasImage());
ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
ObjPtr<mirror::Class> type =
class_linker_->LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
CHECK(type != nullptr);
return type;
}
ObjPtr<mirror::String> GetTargetString(const LinkerPatch& patch)
REQUIRES_SHARED(Locks::mutator_lock_) {
ClassLinker* linker = Runtime::Current()->GetClassLinker();
ObjPtr<mirror::String> string =
linker->LookupString(patch.TargetStringIndex(), GetDexCache(patch.TargetStringDexFile()));
DCHECK(string != nullptr);
DCHECK(writer_->GetCompilerOptions().IsBootImage() ||
writer_->GetCompilerOptions().IsBootImageExtension());
return string;
}
uint32_t GetTargetIntrinsicReferenceOffset(const LinkerPatch& patch)
REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(writer_->GetCompilerOptions().IsBootImage());
const void* address =
writer_->image_writer_->GetIntrinsicReferenceAddress(patch.IntrinsicData());
size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
// TODO: Clean up offset types. The target offset must be treated as signed.
return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(address) - oat_data_begin);
}
uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(writer_->GetCompilerOptions().IsBootImage() ||
writer_->GetCompilerOptions().IsBootImageExtension());
method = writer_->image_writer_->GetImageMethodAddress(method);
size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
// TODO: Clean up offset types. The target offset must be treated as signed.
return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
}
uint32_t GetTargetObjectOffset(ObjPtr<mirror::Object> object)
REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(writer_->GetCompilerOptions().IsBootImage() ||
writer_->GetCompilerOptions().IsBootImageExtension());
object = writer_->image_writer_->GetImageAddress(object.Ptr());
size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
// TODO: Clean up offset types. The target offset must be treated as signed.
return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object.Ptr()) - oat_data_begin);
}
};
// Visit all methods from all classes in all dex files with the specified visitor.
bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
for (const DexFile* dex_file : *dex_files_) {
for (ClassAccessor accessor : dex_file->GetClasses()) {
if (UNLIKELY(!visitor->StartClass(dex_file, accessor.GetClassDefIndex()))) {
return false;
}
if (MayHaveCompiledMethods()) {
size_t class_def_method_index = 0u;
for (const ClassAccessor::Method& method : accessor.GetMethods()) {
if (!visitor->VisitMethod(class_def_method_index, method)) {
return false;
}
++class_def_method_index;
}
}
if (UNLIKELY(!visitor->EndClass())) {
return false;
}
}
}
return true;
}
size_t OatWriter::InitOatHeader(uint32_t num_dex_files,
SafeMap<std::string, std::string>* key_value_store) {
TimingLogger::ScopedTiming split("InitOatHeader", timings_);
// Check that oat version when runtime was compiled matches the oat version
// when dex2oat was compiled. We have seen cases where they got out of sync.
constexpr std::array<uint8_t, 4> dex2oat_oat_version = OatHeader::kOatVersion;
OatHeader::CheckOatVersion(dex2oat_oat_version);
oat_header_.reset(OatHeader::Create(GetCompilerOptions().GetInstructionSet(),
GetCompilerOptions().GetInstructionSetFeatures(),
num_dex_files,
key_value_store));
size_oat_header_ += sizeof(OatHeader);
size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
return oat_header_->GetHeaderSize();
}
size_t OatWriter::InitClassOffsets(size_t offset) {
// Reserve space for class offsets in OAT and update class_offsets_offset_.
for (OatDexFile& oat_dex_file : oat_dex_files_) {
DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
if (!oat_dex_file.class_offsets_.empty()) {
// Class offsets are required to be 4 byte aligned.
offset = RoundUp(offset, 4u);
oat_dex_file.class_offsets_offset_ = offset;
offset += oat_dex_file.GetClassOffsetsRawSize();
DCHECK_ALIGNED(offset, 4u);
}
}
return offset;
}
size_t OatWriter::InitOatClasses(size_t offset) {
// calculate the offsets within OatDexFiles to OatClasses
InitOatClassesMethodVisitor visitor(this, offset);
bool success = VisitDexMethods(&visitor);
CHECK(success);
offset = visitor.GetOffset();
// Update oat_dex_files_.
auto oat_class_it = oat_class_headers_.begin();
for (OatDexFile& oat_dex_file : oat_dex_files_) {
for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
DCHECK(oat_class_it != oat_class_headers_.end());
class_offset = oat_class_it->offset_;
++oat_class_it;
}
}
CHECK(oat_class_it == oat_class_headers_.end());
return offset;
}
size_t OatWriter::InitOatMaps(size_t offset) {
if (!MayHaveCompiledMethods()) {
return offset;
}
{
InitMapMethodVisitor visitor(this, offset);
bool success = VisitDexMethods(&visitor);
DCHECK(success);
code_info_data_.shrink_to_fit();
offset += code_info_data_.size();
}
return offset;
}
template <typename GetBssOffset>
static size_t CalculateNumberOfIndexBssMappingEntries(size_t number_of_indexes,
size_t slot_size,
const BitVector& indexes,
GetBssOffset get_bss_offset) {
IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
size_t number_of_entries = 0u;
bool first_index = true;
for (uint32_t index : indexes.Indexes()) {
uint32_t bss_offset = get_bss_offset(index);
if (first_index || !encoder.TryMerge(index, bss_offset)) {
encoder.Reset(index, bss_offset);
++number_of_entries;
first_index = false;
}
}
DCHECK_NE(number_of_entries, 0u);
return number_of_entries;
}
template <typename GetBssOffset>
static size_t CalculateIndexBssMappingSize(size_t number_of_indexes,
size_t slot_size,
const BitVector& indexes,
GetBssOffset get_bss_offset) {
size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(number_of_indexes,
slot_size,
indexes,
get_bss_offset);
return IndexBssMapping::ComputeSize(number_of_entries);
}
static size_t CalculateIndexBssMappingSize(
const DexFile* dex_file,
const BitVector& type_indexes,
const SafeMap<TypeReference, size_t, TypeReferenceValueComparator>& bss_entries) {
return CalculateIndexBssMappingSize(
dex_file->NumTypeIds(),
sizeof(GcRoot<mirror::Class>),
type_indexes,
[=](uint32_t index) { return bss_entries.Get({dex_file, dex::TypeIndex(index)}); });
}
size_t OatWriter::InitIndexBssMappings(size_t offset) {
if (bss_method_entry_references_.empty() &&
bss_type_entry_references_.empty() &&
bss_public_type_entry_references_.empty() &&
bss_package_type_entry_references_.empty() &&
bss_string_entry_references_.empty()) {
return offset;
}
// If there are any classes, the class offsets allocation aligns the offset
// and we cannot have any index bss mappings without class offsets.
static_assert(alignof(IndexBssMapping) == 4u, "IndexBssMapping alignment check.");
DCHECK_ALIGNED(offset, 4u);
size_t number_of_method_dex_files = 0u;
size_t number_of_type_dex_files = 0u;
size_t number_of_public_type_dex_files = 0u;
size_t number_of_package_type_dex_files = 0u;
size_t number_of_string_dex_files = 0u;
PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
const DexFile* dex_file = (*dex_files_)[i];
auto method_it = bss_method_entry_references_.find(dex_file);
if (method_it != bss_method_entry_references_.end()) {
const BitVector& method_indexes = method_it->second;
++number_of_method_dex_files;
oat_dex_files_[i].method_bss_mapping_offset_ = offset;
offset += CalculateIndexBssMappingSize(
dex_file->NumMethodIds(),
static_cast<size_t>(pointer_size),
method_indexes,
[=](uint32_t index) {
return bss_method_entries_.Get({dex_file, index});
});
}
auto type_it = bss_type_entry_references_.find(dex_file);
if (type_it != bss_type_entry_references_.end()) {
const BitVector& type_indexes = type_it->second;
++number_of_type_dex_files;
oat_dex_files_[i].type_bss_mapping_offset_ = offset;
offset += CalculateIndexBssMappingSize(dex_file, type_indexes, bss_type_entries_);
}
auto public_type_it = bss_public_type_entry_references_.find(dex_file);
if (public_type_it != bss_public_type_entry_references_.end()) {
const BitVector& type_indexes = public_type_it->second;
++number_of_public_type_dex_files;
oat_dex_files_[i].public_type_bss_mapping_offset_ = offset;
offset += CalculateIndexBssMappingSize(dex_file, type_indexes, bss_public_type_entries_);
}
auto package_type_it = bss_package_type_entry_references_.find(dex_file);
if (package_type_it != bss_package_type_entry_references_.end()) {
const BitVector& type_indexes = package_type_it->second;
++number_of_package_type_dex_files;
oat_dex_files_[i].package_type_bss_mapping_offset_ = offset;
offset += CalculateIndexBssMappingSize(dex_file, type_indexes, bss_package_type_entries_);
}
auto string_it = bss_string_entry_references_.find(dex_file);
if (string_it != bss_string_entry_references_.end()) {
const BitVector& string_indexes = string_it->second;
++number_of_string_dex_files;
oat_dex_files_[i].string_bss_mapping_offset_ = offset;
offset += CalculateIndexBssMappingSize(
dex_file->NumStringIds(),
sizeof(GcRoot<mirror::String>),
string_indexes,
[=](uint32_t index) {
return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
});
}
}
// Check that all dex files targeted by bss entries are in `*dex_files_`.
CHECK_EQ(number_of_method_dex_files, bss_method_entry_references_.size());
CHECK_EQ(number_of_type_dex_files, bss_type_entry_references_.size());
CHECK_EQ(number_of_public_type_dex_files, bss_public_type_entry_references_.size());
CHECK_EQ(number_of_package_type_dex_files, bss_package_type_entry_references_.size());
CHECK_EQ(number_of_string_dex_files, bss_string_entry_references_.size());
return offset;
}
size_t OatWriter::InitOatDexFiles(size_t offset) {
// Initialize offsets of oat dex files.
for (OatDexFile& oat_dex_file : oat_dex_files_) {
oat_dex_file.offset_ = offset;
offset += oat_dex_file.SizeOf();
}
return offset;
}
size_t OatWriter::InitOatCode(size_t offset) {
// calculate the offsets within OatHeader to executable code
size_t old_offset = offset;
// required to be on a new page boundary
offset = RoundUp(offset, kPageSize);
oat_header_->SetExecutableOffset(offset);
size_executable_offset_alignment_ = offset - old_offset;
if (GetCompilerOptions().IsBootImage() && primary_oat_file_) {
InstructionSet instruction_set = compiler_options_.GetInstructionSet();
const bool generate_debug_info = GetCompilerOptions().GenerateAnyDebugInfo();
size_t adjusted_offset = offset;
#define DO_TRAMPOLINE(field, fn_name) \
/* Pad with at least four 0xFFs so we can do DCHECKs in OatQuickMethodHeader */ \
offset = CompiledCode::AlignCode(offset + 4, instruction_set); \
adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
(field) = compiler_driver_->Create ## fn_name(); \
if (generate_debug_info) { \
debug::MethodDebugInfo info = {}; \
info.custom_name = #fn_name; \
info.isa = instruction_set; \
info.is_code_address_text_relative = true; \
/* Use the code offset rather than the `adjusted_offset`. */ \
info.code_address = offset - oat_header_->GetExecutableOffset(); \
info.code_size = (field)->size(); \
method_info_.push_back(std::move(info)); \
} \
offset += (field)->size();
DO_TRAMPOLINE(jni_dlsym_lookup_trampoline_, JniDlsymLookupTrampoline);
DO_TRAMPOLINE(jni_dlsym_lookup_critical_trampoline_, JniDlsymLookupCriticalTrampoline);
DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
DO_TRAMPOLINE(nterp_trampoline_, NterpTrampoline);
#undef DO_TRAMPOLINE
} else {
oat_header_->SetJniDlsymLookupTrampolineOffset(0);
oat_header_->SetJniDlsymLookupCriticalTrampolineOffset(0);
oat_header_->SetQuickGenericJniTrampolineOffset(0);
oat_header_->SetQuickImtConflictTrampolineOffset(0);
oat_header_->SetQuickResolutionTrampolineOffset(0);
oat_header_->SetQuickToInterpreterBridgeOffset(0);
oat_header_->SetNterpTrampolineOffset(0);
}
return offset;
}
size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
if (!GetCompilerOptions().IsAnyCompilationEnabled()) {
if (kOatWriterDebugOatCodeLayout) {
LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
<< this << "), "
<< "compilation is disabled";
}
return offset;
}
bool success = false;
{
ScopedObjectAccess soa(Thread::Current());
LayoutCodeMethodVisitor layout_code_visitor(this, offset);
success = VisitDexMethods(&layout_code_visitor);
DCHECK(success);
LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
this,
offset,
layout_code_visitor.ReleaseOrderedMethods());
success = layout_reserve_code_visitor.Visit();
DCHECK(success);
offset = layout_reserve_code_visitor.GetOffset();
// Save the method order because the WriteCodeMethodVisitor will need this
// order again.
DCHECK(ordered_methods_ == nullptr);
ordered_methods_.reset(
new OrderedMethodList(
layout_reserve_code_visitor.ReleaseOrderedMethods()));
if (kOatWriterDebugOatCodeLayout) {
LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
for (const OrderedMethodData& ordered_method : *ordered_methods_) {
std::string pretty_name = ordered_method.method_reference.PrettyMethod();
LOG(INFO) << pretty_name
<< "@ offset "
<< relative_patcher_->GetOffset(ordered_method.method_reference)
<< " X hotness "
<< reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
}
}
}
if (HasImage()) {
ScopedObjectAccess soa(Thread::Current());
ScopedAssertNoThreadSuspension sants("Init image method visitor", Thread::Current());
InitImageMethodVisitor image_visitor(this, offset, dex_files_);
success = VisitDexMethods(&image_visitor);
image_visitor.Postprocess();
DCHECK(success);
offset = image_visitor.GetOffset();
}
return offset;
}
size_t OatWriter::InitDataBimgRelRoLayout(size_t offset) {
DCHECK_EQ(data_bimg_rel_ro_size_, 0u);
if (data_bimg_rel_ro_entries_.empty()) {
// Nothing to put to the .data.bimg.rel.ro section.
return offset;
}
data_bimg_rel_ro_start_ = RoundUp(offset, kPageSize);
for (auto& entry : data_bimg_rel_ro_entries_) {
size_t& entry_offset = entry.second;
entry_offset = data_bimg_rel_ro_size_;
data_bimg_rel_ro_size_ += sizeof(uint32_t);
}
offset = data_bimg_rel_ro_start_ + data_bimg_rel_ro_size_;
return offset;
}
void OatWriter::InitBssLayout(InstructionSet instruction_set) {
{
InitBssLayoutMethodVisitor visitor(this);
bool success = VisitDexMethods(&visitor);
DCHECK(success);
}
DCHECK_EQ(bss_size_, 0u);
if (bss_method_entries_.empty() &&
bss_type_entries_.empty() &&
bss_public_type_entries_.empty() &&
bss_package_type_entries_.empty() &&
bss_string_entries_.empty()) {
// Nothing to put to the .bss section.
return;
}
PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
bss_methods_offset_ = bss_size_;
// Prepare offsets for .bss ArtMethod entries.
for (auto& entry : bss_method_entries_) {
DCHECK_EQ(entry.second, 0u);
entry.second = bss_size_;
bss_size_ += static_cast<size_t>(pointer_size);
}
bss_roots_offset_ = bss_size_;
// Prepare offsets for .bss Class entries.
for (auto& entry : bss_type_entries_) {
DCHECK_EQ(entry.second, 0u);
entry.second = bss_size_;
bss_size_ += sizeof(GcRoot<mirror::Class>);
}
// Prepare offsets for .bss public Class entries.
for (auto& entry : bss_public_type_entries_) {
DCHECK_EQ(entry.second, 0u);
entry.second = bss_size_;
bss_size_ += sizeof(GcRoot<mirror::Class>);
}
// Prepare offsets for .bss package Class entries.
for (auto& entry : bss_package_type_entries_) {
DCHECK_EQ(entry.second, 0u);
entry.second = bss_size_;
bss_size_ += sizeof(GcRoot<mirror::Class>);
}
// Prepare offsets for .bss String entries.
for (auto& entry : bss_string_entries_) {
DCHECK_EQ(entry.second, 0u);
entry.second = bss_size_;
bss_size_ += sizeof(GcRoot<mirror::String>);
}
}
bool OatWriter::WriteRodata(OutputStream* out) {
CHECK(write_state_ == WriteState::kWriteRoData);
size_t file_offset = oat_data_offset_;
off_t current_offset = out->Seek(0, kSeekCurrent);
if (current_offset == static_cast<off_t>(-1)) {
PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
}
DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
size_t relative_offset = current_offset - file_offset;
// Wrap out to update checksum with each write.
ChecksumUpdatingOutputStream checksum_updating_out(out, this);
out = &checksum_updating_out;
relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
if (relative_offset == 0) {
PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
return false;
}
relative_offset = WriteClasses(out, file_offset, relative_offset);
if (relative_offset == 0) {
PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
return false;
}
relative_offset = WriteIndexBssMappings(out, file_offset, relative_offset);
if (relative_offset == 0) {
PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
return false;
}
relative_offset = WriteMaps(out, file_offset, relative_offset);
if (relative_offset == 0) {
PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
return false;
}
relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
if (relative_offset == 0) {
PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
return false;
}
// Write padding.
off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
relative_offset += size_executable_offset_alignment_;
DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
size_t expected_file_offset = file_offset + relative_offset;
if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
<< " Expected: " << expected_file_offset << " File: " << out->GetLocation();
return false;
}
DCHECK_OFFSET();
write_state_ = WriteState::kWriteText;
return true;
}
void OatWriter::WriteQuickeningInfo(/*out*/std::vector<uint8_t>* ATTRIBUTE_UNUSED) {
// Nothing to write. Leave `vdex_size_` untouched and unaligned.
vdex_quickening_info_offset_ = vdex_size_;
size_quickening_info_alignment_ = 0;
}
void OatWriter::WriteVerifierDeps(verifier::VerifierDeps* verifier_deps,
/*out*/std::vector<uint8_t>* buffer) {
if (verifier_deps == nullptr) {
// Nothing to write. Record the offset, but no need
// for alignment.
vdex_verifier_deps_offset_ = vdex_size_;
return;
}
TimingLogger::ScopedTiming split("VDEX verifier deps", timings_);
DCHECK(buffer->empty());
verifier_deps->Encode(*dex_files_, buffer);
size_verifier_deps_ = buffer->size();
// Verifier deps data should be 4 byte aligned.
size_verifier_deps_alignment_ = RoundUp(vdex_size_, 4u) - vdex_size_;
buffer->insert(buffer->begin(), size_verifier_deps_alignment_, 0u);
vdex_size_ += size_verifier_deps_alignment_;
vdex_verifier_deps_offset_ = vdex_size_;
vdex_size_ += size_verifier_deps_;
}
bool OatWriter::WriteCode(OutputStream* out) {
CHECK(write_state_ == WriteState::kWriteText);
// Wrap out to update checksum with each write.
ChecksumUpdatingOutputStream checksum_updating_out(out, this);
out = &checksum_updating_out;
SetMultiOatRelativePatcherAdjustment();
const size_t file_offset = oat_data_offset_;
size_t relative_offset = oat_header_->GetExecutableOffset();
DCHECK_OFFSET();
relative_offset = WriteCode(out, file_offset, relative_offset);
if (relative_offset == 0) {
LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
return false;
}
relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
if (relative_offset == 0) {
LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
return false;
}
if (data_bimg_rel_ro_size_ != 0u) {
write_state_ = WriteState::kWriteDataBimgRelRo;
} else {
if (!CheckOatSize(out, file_offset, relative_offset)) {
return false;
}
write_state_ = WriteState::kWriteHeader;
}
return true;
}
bool OatWriter::WriteDataBimgRelRo(OutputStream* out) {
CHECK(write_state_ == WriteState::kWriteDataBimgRelRo);
// Wrap out to update checksum with each write.
ChecksumUpdatingOutputStream checksum_updating_out(out, this);
out = &checksum_updating_out;
const size_t file_offset = oat_data_offset_;
size_t relative_offset = data_bimg_rel_ro_start_;
// Record the padding before the .data.bimg.rel.ro section.
// Do not write anything, this zero-filled part was skipped (Seek()) when starting the section.
size_t code_end = GetOatHeader().GetExecutableOffset() + code_size_;
DCHECK_EQ(RoundUp(code_end, kPageSize), relative_offset);
size_t padding_size = relative_offset - code_end;
DCHECK_EQ(size_data_bimg_rel_ro_alignment_, 0u);
size_data_bimg_rel_ro_alignment_ = padding_size;
relative_offset = WriteDataBimgRelRo(out, file_offset, relative_offset);
if (relative_offset == 0) {
LOG(ERROR) << "Failed to write boot image relocations to " << out->GetLocation();
return false;
}
if (!CheckOatSize(out, file_offset, relative_offset)) {
return false;
}
write_state_ = WriteState::kWriteHeader;
return true;
}
bool OatWriter::CheckOatSize(OutputStream* out, size_t file_offset, size_t relative_offset) {
const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
if (oat_end_file_offset == static_cast<off_t>(-1)) {
LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
return false;
}
if (kIsDebugBuild) {
uint32_t size_total = 0;
#define DO_STAT(x) \
VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
size_total += (x);
DO_STAT(size_vdex_header_);
DO_STAT(size_vdex_checksums_);
DO_STAT(size_dex_file_alignment_);
DO_STAT(size_quickening_table_offset_);
DO_STAT(size_executable_offset_alignment_);
DO_STAT(size_oat_header_);
DO_STAT(size_oat_header_key_value_store_);
DO_STAT(size_dex_file_);
DO_STAT(size_verifier_deps_);
DO_STAT(size_verifier_deps_alignment_);
DO_STAT(size_vdex_lookup_table_);
DO_STAT(size_vdex_lookup_table_alignment_);
DO_STAT(size_quickening_info_);
DO_STAT(size_quickening_info_alignment_);
DO_STAT(size_interpreter_to_interpreter_bridge_);
DO_STAT(size_interpreter_to_compiled_code_bridge_);
DO_STAT(size_jni_dlsym_lookup_trampoline_);
DO_STAT(size_jni_dlsym_lookup_critical_trampoline_);
DO_STAT(size_quick_generic_jni_trampoline_);
DO_STAT(size_quick_imt_conflict_trampoline_);
DO_STAT(size_quick_resolution_trampoline_);
DO_STAT(size_quick_to_interpreter_bridge_);
DO_STAT(size_nterp_trampoline_);
DO_STAT(size_trampoline_alignment_);
DO_STAT(size_method_header_);
DO_STAT(size_code_);
DO_STAT(size_code_alignment_);
DO_STAT(size_data_bimg_rel_ro_);
DO_STAT(size_data_bimg_rel_ro_alignment_);
DO_STAT(size_relative_call_thunks_);
DO_STAT(size_misc_thunks_);
DO_STAT(size_vmap_table_);
DO_STAT(size_method_info_);
DO_STAT(size_oat_dex_file_location_size_);
DO_STAT(size_oat_dex_file_location_data_);
DO_STAT(size_oat_dex_file_location_checksum_);
DO_STAT(size_oat_dex_file_offset_);
DO_STAT(size_oat_dex_file_class_offsets_offset_);
DO_STAT(size_oat_dex_file_lookup_table_offset_);
DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
DO_STAT(size_oat_dex_file_dex_layout_sections_);
DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
DO_STAT(size_oat_dex_file_type_bss_mapping_offset_);
DO_STAT(size_oat_dex_file_public_type_bss_mapping_offset_);
DO_STAT(size_oat_dex_file_package_type_bss_mapping_offset_);
DO_STAT(size_oat_dex_file_string_bss_mapping_offset_);
DO_STAT(size_oat_class_offsets_alignment_);
DO_STAT(size_oat_class_offsets_);
DO_STAT(size_oat_class_type_);
DO_STAT(size_oat_class_status_);
DO_STAT(size_oat_class_num_methods_);
DO_STAT(size_oat_class_method_bitmaps_);
DO_STAT(size_oat_class_method_offsets_);
DO_STAT(size_method_bss_mappings_);
DO_STAT(size_type_bss_mappings_);
DO_STAT(size_public_type_bss_mappings_);
DO_STAT(size_package_type_bss_mappings_);
DO_STAT(size_string_bss_mappings_);
#undef DO_STAT
VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
CHECK_EQ(vdex_size_ + oat_size_, size_total);
CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
}
CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
CHECK_EQ(oat_size_, relative_offset);
write_state_ = WriteState::kWriteHeader;
return true;
}
bool OatWriter::WriteHeader(OutputStream* out) {
CHECK(write_state_ == WriteState::kWriteHeader);
// Update checksum with header data.
DCHECK_EQ(oat_header_->GetChecksum(), 0u); // For checksum calculation.
const uint8_t* header_begin = reinterpret_cast<const uint8_t*>(oat_header_.get());
const uint8_t* header_end = oat_header_->GetKeyValueStore() + oat_header_->GetKeyValueStoreSize();
uint32_t old_checksum = oat_checksum_;
oat_checksum_ = adler32(old_checksum, header_begin, header_end - header_begin);
oat_header_->SetChecksum(oat_checksum_);
const size_t file_offset = oat_data_offset_;
off_t current_offset = out->Seek(0, kSeekCurrent);
if (current_offset == static_cast<off_t>(-1)) {
PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
return false;
}
if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
return false;
}
DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
// Flush all other data before writing the header.
if (!out->Flush()) {
PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
return false;
}
// Write the header.
size_t header_size = oat_header_->GetHeaderSize();
if (!out->WriteFully(oat_header_.get(), header_size)) {
PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
return false;
}
// Flush the header data.
if (!out->Flush()) {
PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
return false;
}
if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
return false;
}
DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
write_state_ = WriteState::kDone;
return true;
}
size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
for (OatDexFile& oat_dex_file : oat_dex_files_) {
if (oat_dex_file.class_offsets_offset_ != 0u) {
// Class offsets are required to be 4 byte aligned.
if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
return 0u;
}
relative_offset += padding_size;
}
DCHECK_OFFSET();
if (!oat_dex_file.WriteClassOffsets(this, out)) {
return 0u;
}
relative_offset += oat_dex_file.GetClassOffsetsRawSize();
}
}
return relative_offset;
}
size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
const bool may_have_compiled = MayHaveCompiledMethods();
if (may_have_compiled) {
CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
}
for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
// If there are any classes, the class offsets allocation aligns the offset.
DCHECK_ALIGNED(relative_offset, 4u);
DCHECK_OFFSET();
if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
return 0u;
}
relative_offset += oat_class_headers_[i].SizeOf();
if (may_have_compiled) {
if (!oat_classes_[i].Write(this, out)) {
return 0u;
}
relative_offset += oat_classes_[i].SizeOf();
}
}
return relative_offset;
}
size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
{
if (UNLIKELY(!out->WriteFully(code_info_data_.data(), code_info_data_.size()))) {
return 0;
}
relative_offset += code_info_data_.size();
size_vmap_table_ = code_info_data_.size();
DCHECK_OFFSET();
}
return relative_offset;
}
template <typename GetBssOffset>
size_t WriteIndexBssMapping(OutputStream* out,
size_t number_of_indexes,
size_t slot_size,
const BitVector& indexes,
GetBssOffset get_bss_offset) {
// Allocate the IndexBssMapping.
size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(
number_of_indexes, slot_size, indexes, get_bss_offset);
size_t mappings_size = IndexBssMapping::ComputeSize(number_of_entries);
DCHECK_ALIGNED(mappings_size, sizeof(uint32_t));
std::unique_ptr<uint32_t[]> storage(new uint32_t[mappings_size / sizeof(uint32_t)]);
IndexBssMapping* mappings = new(storage.get()) IndexBssMapping(number_of_entries);
mappings->ClearPadding();
// Encode the IndexBssMapping.
IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
auto init_it = mappings->begin();
bool first_index = true;
for (uint32_t index : indexes.Indexes()) {
size_t bss_offset = get_bss_offset(index);
if (first_index) {
first_index = false;
encoder.Reset(index, bss_offset);
} else if (!encoder.TryMerge(index, bss_offset)) {
*init_it = encoder.GetEntry();
++init_it;
encoder.Reset(index, bss_offset);
}
}
// Store the last entry.
*init_it = encoder.GetEntry();
++init_it;
DCHECK(init_it == mappings->end());
if (!out->WriteFully(storage.get(), mappings_size)) {
return 0u;
}
return mappings_size;
}
size_t WriteIndexBssMapping(
OutputStream* out,
const DexFile* dex_file,
const BitVector& type_indexes,
const SafeMap<TypeReference, size_t, TypeReferenceValueComparator>& bss_entries) {
return WriteIndexBssMapping(
out,
dex_file->NumTypeIds(),
sizeof(GcRoot<mirror::Class>),
type_indexes,
[=](uint32_t index) { return bss_entries.Get({dex_file, dex::TypeIndex(index)}); });
}
size_t OatWriter::WriteIndexBssMappings(OutputStream* out,
size_t file_offset,
size_t relative_offset) {
TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
if (bss_method_entry_references_.empty() &&
bss_type_entry_references_.empty() &&
bss_public_type_entry_references_.empty() &&
bss_package_type_entry_references_.empty() &&
bss_string_entry_references_.empty()) {
return relative_offset;
}
// If there are any classes, the class offsets allocation aligns the offset
// and we cannot have method bss mappings without class offsets.
static_assert(alignof(IndexBssMapping) == sizeof(uint32_t),
"IndexBssMapping alignment check.");
DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
const DexFile* dex_file = (*dex_files_)[i];
OatDexFile* oat_dex_file = &oat_dex_files_[i];
auto method_it = bss_method_entry_references_.find(dex_file);
if (method_it != bss_method_entry_references_.end()) {
const BitVector& method_indexes = method_it->second;
DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
DCHECK_OFFSET();
size_t method_mappings_size = WriteIndexBssMapping(
out,
dex_file->NumMethodIds(),
static_cast<size_t>(pointer_size),
method_indexes,
[=](uint32_t index) {
return bss_method_entries_.Get({dex_file, index});
});
if (method_mappings_size == 0u) {
return 0u;
}
size_method_bss_mappings_ += method_mappings_size;
relative_offset += method_mappings_size;
} else {
DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
}
auto type_it = bss_type_entry_references_.find(dex_file);
if (type_it != bss_type_entry_references_.end()) {
const BitVector& type_indexes = type_it->second;
DCHECK_EQ(relative_offset, oat_dex_file->type_bss_mapping_offset_);
DCHECK_OFFSET();
size_t type_mappings_size =
WriteIndexBssMapping(out, dex_file, type_indexes, bss_type_entries_);
if (type_mappings_size == 0u) {
return 0u;
}
size_type_bss_mappings_ += type_mappings_size;
relative_offset += type_mappings_size;
} else {
DCHECK_EQ(0u, oat_dex_file->type_bss_mapping_offset_);
}
auto public_type_it = bss_public_type_entry_references_.find(dex_file);
if (public_type_it != bss_public_type_entry_references_.end()) {
const BitVector& type_indexes = public_type_it->second;
DCHECK_EQ(relative_offset, oat_dex_file->public_type_bss_mapping_offset_);
DCHECK_OFFSET();
size_t public_type_mappings_size =
WriteIndexBssMapping(out, dex_file, type_indexes, bss_public_type_entries_);
if (public_type_mappings_size == 0u) {
return 0u;
}
size_public_type_bss_mappings_ += public_type_mappings_size;
relative_offset += public_type_mappings_size;
} else {
DCHECK_EQ(0u, oat_dex_file->public_type_bss_mapping_offset_);
}
auto package_type_it = bss_package_type_entry_references_.find(dex_file);
if (package_type_it != bss_package_type_entry_references_.end()) {
const BitVector& type_indexes = package_type_it->second;
DCHECK_EQ(relative_offset, oat_dex_file->package_type_bss_mapping_offset_);
DCHECK_OFFSET();
size_t package_type_mappings_size =
WriteIndexBssMapping(out, dex_file, type_indexes, bss_package_type_entries_);
if (package_type_mappings_size == 0u) {
return 0u;
}
size_package_type_bss_mappings_ += package_type_mappings_size;
relative_offset += package_type_mappings_size;
} else {
DCHECK_EQ(0u, oat_dex_file->package_type_bss_mapping_offset_);
}
auto string_it = bss_string_entry_references_.find(dex_file);
if (string_it != bss_string_entry_references_.end()) {
const BitVector& string_indexes = string_it->second;
DCHECK_EQ(relative_offset, oat_dex_file->string_bss_mapping_offset_);
DCHECK_OFFSET();
size_t string_mappings_size = WriteIndexBssMapping(
out,
dex_file->NumStringIds(),
sizeof(GcRoot<mirror::String>),
string_indexes,
[=](uint32_t index) {
return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
});
if (string_mappings_size == 0u) {
return 0u;
}
size_string_bss_mappings_ += string_mappings_size;
relative_offset += string_mappings_size;
} else {
DCHECK_EQ(0u, oat_dex_file->string_bss_mapping_offset_);
}
}
return relative_offset;
}
size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
OatDexFile* oat_dex_file = &oat_dex_files_[i];
DCHECK_EQ(relative_offset, oat_dex_file->offset_);
DCHECK_OFFSET();
// Write OatDexFile.
if (!oat_dex_file->Write(this, out)) {
return 0u;
}
relative_offset += oat_dex_file->SizeOf();
}
return relative_offset;
}
size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
if (GetCompilerOptions().IsBootImage() && primary_oat_file_) {
InstructionSet instruction_set = compiler_options_.GetInstructionSet();
#define DO_TRAMPOLINE(field) \
do { \
/* Pad with at least four 0xFFs so we can do DCHECKs in OatQuickMethodHeader */ \
uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset + 4, instruction_set); \
uint32_t alignment_padding = aligned_offset - relative_offset; \
for (size_t i = 0; i < alignment_padding; i++) { \
uint8_t padding = 0xFF; \
out->WriteFully(&padding, 1); \
} \
size_trampoline_alignment_ += alignment_padding; \
if (!out->WriteFully((field)->data(), (field)->size())) { \
PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
return false; \
} \
size_ ## field += (field)->size(); \
relative_offset += alignment_padding + (field)->size(); \
DCHECK_OFFSET(); \
} while (false)
DO_TRAMPOLINE(jni_dlsym_lookup_trampoline_);
DO_TRAMPOLINE(jni_dlsym_lookup_critical_trampoline_);
DO_TRAMPOLINE(quick_generic_jni_trampoline_);
DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
DO_TRAMPOLINE(quick_resolution_trampoline_);
DO_TRAMPOLINE(quick_to_interpreter_bridge_);
DO_TRAMPOLINE(nterp_trampoline_);
#undef DO_TRAMPOLINE
}
return relative_offset;
}
size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
size_t file_offset,
size_t relative_offset) {
if (!GetCompilerOptions().IsAnyCompilationEnabled()) {
// As with InitOatCodeDexFiles, also skip the writer if
// compilation was disabled.
if (kOatWriterDebugOatCodeLayout) {
LOG(INFO) << "WriteCodeDexFiles: OatWriter("
<< this << "), "
<< "compilation is disabled";
}
return relative_offset;
}
ScopedObjectAccess soa(Thread::Current());
DCHECK(ordered_methods_ != nullptr);
std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
std::move(ordered_methods_);
WriteCodeMethodVisitor visitor(this,
out,
file_offset,
relative_offset,
std::move(*ordered_methods_ptr));
if (UNLIKELY(!visitor.Visit())) {
return 0;
}
relative_offset = visitor.GetOffset();
size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
size_misc_thunks_ += relative_patcher_->MiscThunksSize();
return relative_offset;
}
size_t OatWriter::WriteDataBimgRelRo(OutputStream* out,
size_t file_offset,
size_t relative_offset) {
if (data_bimg_rel_ro_entries_.empty()) {
return relative_offset;
}
// Write the entire .data.bimg.rel.ro with a single WriteFully().
std::vector<uint32_t> data;
data.reserve(data_bimg_rel_ro_entries_.size());
for (const auto& entry : data_bimg_rel_ro_entries_) {
uint32_t boot_image_offset = entry.first;
data.push_back(boot_image_offset);
}
DCHECK_EQ(data.size(), data_bimg_rel_ro_entries_.size());
DCHECK_OFFSET();
if (!out->WriteFully(data.data(), data.size() * sizeof(data[0]))) {
PLOG(ERROR) << "Failed to write .data.bimg.rel.ro in " << out->GetLocation();
return 0u;
}
DCHECK_EQ(size_data_bimg_rel_ro_, 0u);
size_data_bimg_rel_ro_ = data.size() * sizeof(data[0]);
relative_offset += size_data_bimg_rel_ro_;
return relative_offset;
}
bool OatWriter::RecordOatDataOffset(OutputStream* out) {
// Get the elf file offset of the oat file.
const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
if (raw_file_offset == static_cast<off_t>(-1)) {
LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
return false;
}
oat_data_offset_ = static_cast<size_t>(raw_file_offset);
return true;
}
bool OatWriter::WriteDexFiles(File* file,
bool update_input_vdex,
CopyOption copy_dex_files,
/*out*/ std::vector<MemMap>* opened_dex_files_map) {
TimingLogger::ScopedTiming split("Write Dex files", timings_);
// If extraction is enabled, only do it if not all the dex files are aligned and uncompressed.
if (copy_dex_files == CopyOption::kOnlyIfCompressed) {
extract_dex_files_into_vdex_ = false;
for (OatDexFile& oat_dex_file : oat_dex_files_) {
if (!oat_dex_file.source_.IsZipEntry()) {
extract_dex_files_into_vdex_ = true;
break;
}
ZipEntry* entry = oat_dex_file.source_.GetZipEntry();
if (!entry->IsUncompressed() || !entry->IsAlignedTo(alignof(DexFile::Header))) {
extract_dex_files_into_vdex_ = true;
break;
}
}
} else if (copy_dex_files == CopyOption::kAlways) {
extract_dex_files_into_vdex_ = true;
} else {
DCHECK(copy_dex_files == CopyOption::kNever);
extract_dex_files_into_vdex_ = false;
}
if (extract_dex_files_into_vdex_) {
vdex_dex_files_offset_ = vdex_size_;
// Perform dexlayout if requested.
if (profile_compilation_info_ != nullptr ||
compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone) {
for (OatDexFile& oat_dex_file : oat_dex_files_) {
// update_input_vdex disables compact dex and layout.
CHECK(!update_input_vdex)
<< "We should never update the input vdex when doing dexlayout or compact dex";
if (!LayoutDexFile(&oat_dex_file)) {
return false;
}
}
}
// Calculate the total size after the dex files.
size_t vdex_size_with_dex_files = vdex_size_;
for (OatDexFile& oat_dex_file : oat_dex_files_) {
// Dex files are required to be 4 byte aligned.
vdex_size_with_dex_files = RoundUp(vdex_size_with_dex_files, 4u);
// Record offset for the dex file.
oat_dex_file.dex_file_offset_ = vdex_size_with_dex_files;
// Add the size of the dex file.
if (oat_dex_file.dex_file_size_ < sizeof(DexFile::Header)) {
LOG(ERROR) << "Dex file " << oat_dex_file.GetLocation() << " is too short: "
<< oat_dex_file.dex_file_size_ << " < " << sizeof(DexFile::Header);
return false;
}
vdex_size_with_dex_files += oat_dex_file.dex_file_size_;
}
// Add the shared data section size.
const uint8_t* raw_dex_file_shared_data_begin = nullptr;
uint32_t shared_data_size = 0u;
if (dex_container_ != nullptr) {
shared_data_size = dex_container_->GetDataSection()->Size();
} else {
// Dex files from input vdex are represented as raw dex files and they can be
// compact dex files. These need to specify the same shared data section if any.
for (const OatDexFile& oat_dex_file : oat_dex_files_) {
if (!oat_dex_file.source_.IsRawData()) {
continue;
}
const uint8_t* raw_data = oat_dex_file.source_.GetRawData();
const UnalignedDexFileHeader& header = *AsUnalignedDexFileHeader(raw_data);
if (!CompactDexFile::IsMagicValid(header.magic_) || header.data_size_ == 0u) {
// Non compact dex does not have shared data section.
continue;
}
const uint8_t* cur_data_begin = raw_data + header.data_off_;
if (raw_dex_file_shared_data_begin == nullptr) {
raw_dex_file_shared_data_begin = cur_data_begin;
} else if (raw_dex_file_shared_data_begin != cur_data_begin) {
LOG(ERROR) << "Mismatched shared data sections in raw dex files: "
<< static_cast<const void*>(raw_dex_file_shared_data_begin)
<< " != " << static_cast<const void*>(cur_data_begin);
return false;
}
// The different dex files currently can have different data sizes since
// the dex writer writes them one at a time into the shared section.:w
shared_data_size = std::max(shared_data_size, header.data_size_);
}
}
if (shared_data_size != 0u) {
// Shared data section is required to be 4 byte aligned.
vdex_size_with_dex_files = RoundUp(vdex_size_with_dex_files, 4u);
}
vdex_dex_shared_data_offset_ = vdex_size_with_dex_files;
vdex_size_with_dex_files += shared_data_size;
// Extend the file and include the full page at the end as we need to write
// additional data there and do not want to mmap that page twice.
size_t page_aligned_size = RoundUp(vdex_size_with_dex_files, kPageSize);
if (!update_input_vdex) {
if (file->SetLength(page_aligned_size) != 0) {
PLOG(ERROR) << "Failed to resize vdex file " << file->GetPath();
return false;
}
}
std::string error_msg;
MemMap dex_files_map = MemMap::MapFile(
page_aligned_size,
PROT_READ | PROT_WRITE,
MAP_SHARED,
file->Fd(),
/*start=*/ 0u,
/*low_4gb=*/ false,
file->GetPath().c_str(),
&error_msg);
if (!dex_files_map.IsValid()) {
LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
<< " error: " << error_msg;
return false;
}
vdex_begin_ = dex_files_map.Begin();
// Write dex files.
for (OatDexFile& oat_dex_file : oat_dex_files_) {
// Dex files are required to be 4 byte aligned.
size_t old_vdex_size = vdex_size_;
vdex_size_ = RoundUp(vdex_size_, 4u);
size_dex_file_alignment_ += vdex_size_ - old_vdex_size;
// Write the actual dex file.
if (!WriteDexFile(file, &oat_dex_file, update_input_vdex)) {
return false;
}
}
// Write shared dex file data section and fix up the dex file headers.
if (shared_data_size != 0u) {
DCHECK_EQ(RoundUp(vdex_size_, 4u), vdex_dex_shared_data_offset_);
if (!update_input_vdex) {
memset(vdex_begin_ + vdex_size_, 0, vdex_dex_shared_data_offset_ - vdex_size_);
}
size_dex_file_alignment_ += vdex_dex_shared_data_offset_ - vdex_size_;
vdex_size_ = vdex_dex_shared_data_offset_;
if (dex_container_ != nullptr) {
CHECK(!update_input_vdex) << "Update input vdex should have empty dex container";
CHECK(compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone);
DexContainer::Section* const section = dex_container_->GetDataSection();
DCHECK_EQ(shared_data_size, section->Size());
memcpy(vdex_begin_ + vdex_size_, section->Begin(), shared_data_size);
section->Clear();
dex_container_.reset();
} else if (!update_input_vdex) {
// If we are not updating the input vdex, write out the shared data section.
memcpy(vdex_begin_ + vdex_size_, raw_dex_file_shared_data_begin, shared_data_size);
}
vdex_size_ += shared_data_size;
size_dex_file_ += shared_data_size;
if (!update_input_vdex) {
// Fix up the dex headers to have correct offsets to the data section.
for (OatDexFile& oat_dex_file : oat_dex_files_) {
DexFile::Header* header =
reinterpret_cast<DexFile::Header*>(vdex_begin_ + oat_dex_file.dex_file_offset_);
if (!CompactDexFile::IsMagicValid(header->magic_)) {
// Non-compact dex file, probably failed to convert due to duplicate methods.
continue;
}
CHECK_GT(vdex_dex_shared_data_offset_, oat_dex_file.dex_file_offset_);
// Offset is from the dex file base.
header->data_off_ = vdex_dex_shared_data_offset_ - oat_dex_file.dex_file_offset_;
// The size should already be what part of the data buffer may be used by the dex.
CHECK_LE(header->data_size_, shared_data_size);
}
}
}
opened_dex_files_map->push_back(std::move(dex_files_map));
} else {
vdex_dex_shared_data_offset_ = vdex_size_;
}
return true;
}
void OatWriter::CloseSources() {
for (OatDexFile& oat_dex_file : oat_dex_files_) {
oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
}
zipped_dex_files_.clear();
zip_archives_.clear();
raw_dex_files_.clear();
}
bool OatWriter::WriteDexFile(File* file,
OatDexFile* oat_dex_file,
bool update_input_vdex) {
DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
if (oat_dex_file->source_.IsZipEntry()) {
DCHECK(!update_input_vdex);
if (!WriteDexFile(file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
return false;
}
} else if (oat_dex_file->source_.IsRawFile()) {
DCHECK(!update_input_vdex);
if (!WriteDexFile(file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
return false;
}
} else {
DCHECK(oat_dex_file->source_.IsRawData());
const uint8_t* raw_data = oat_dex_file->source_.GetRawData();
if (!WriteDexFile(oat_dex_file, raw_data, update_input_vdex)) {
return false;
}
}
// Update current size and account for the written data.
vdex_size_ += oat_dex_file->dex_file_size_;
size_dex_file_ += oat_dex_file->dex_file_size_;
return true;
}
bool OatWriter::LayoutDexFile(OatDexFile* oat_dex_file) {
TimingLogger::ScopedTiming split("Dex Layout", timings_);
std::string error_msg;
std::string location(oat_dex_file->GetLocation());
std::unique_ptr<const DexFile> dex_file;
const ArtDexFileLoader dex_file_loader;
if (oat_dex_file->source_.IsZipEntry()) {
ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
MemMap mem_map;
{
TimingLogger::ScopedTiming extract("Unzip", timings_);
mem_map = zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg);
}
if (!mem_map.IsValid()) {
LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
return false;
}
TimingLogger::ScopedTiming extract("Open", timings_);
dex_file = dex_file_loader.Open(location,
zip_entry->GetCrc32(),
std::move(mem_map),
/*verify=*/ true,
/*verify_checksum=*/ true,
&error_msg);
} else if (oat_dex_file->source_.IsRawFile()) {
File* raw_file = oat_dex_file->source_.GetRawFile();
int dup_fd = DupCloexec(raw_file->Fd());
if (dup_fd < 0) {
PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
return false;
}
TimingLogger::ScopedTiming extract("Open", timings_);
dex_file = dex_file_loader.OpenDex(dup_fd, location,
/*verify=*/ true,
/*verify_checksum=*/ true,
/*mmap_shared=*/ false,
&error_msg);
} else {
// The source data is a vdex file.
CHECK(oat_dex_file->source_.IsRawData())
<< static_cast<size_t>(oat_dex_file->source_.GetType());
const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
// Note: The raw data has already been checked to contain the header
// and all the data that the header specifies as the file size.
DCHECK(raw_dex_file != nullptr);
DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
// Since the source may have had its layout changed, or may be quickened, don't verify it.
dex_file = dex_file_loader.Open(raw_dex_file,
header->file_size_,
location,
oat_dex_file->dex_file_location_checksum_,
nullptr,
/*verify=*/ false,
/*verify_checksum=*/ false,
&error_msg);
}
if (dex_file == nullptr) {
LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
return false;
}
Options options;
options.compact_dex_level_ = compact_dex_level_;
options.update_checksum_ = true;
DexLayout dex_layout(options, profile_compilation_info_, /*file*/ nullptr, /*header*/ nullptr);
{
TimingLogger::ScopedTiming extract("ProcessDexFile", timings_);
if (dex_layout.ProcessDexFile(location.c_str(),
dex_file.get(),
0,
&dex_container_,
&error_msg)) {
oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
oat_dex_file->source_.SetDexLayoutData(dex_container_->GetMainSection()->ReleaseData());
// Dex layout can affect the size of the dex file, so we update here what we have set
// when adding the dex file as a source.
const UnalignedDexFileHeader* header =
AsUnalignedDexFileHeader(oat_dex_file->source_.GetRawData());
oat_dex_file->dex_file_size_ = header->file_size_;
} else {
LOG(WARNING) << "Failed to run dex layout, reason:" << error_msg;
// Since we failed to convert the dex, just copy the input dex.
if (dex_container_ != nullptr) {
// Clear the main section before processing next dex file in case we have written some data.
dex_container_->GetMainSection()->Clear();
}
}
}
CHECK_EQ(oat_dex_file->dex_file_location_checksum_, dex_file->GetLocationChecksum());
return true;
}
bool OatWriter::WriteDexFile(File* file,
OatDexFile* oat_dex_file,
ZipEntry* dex_file) {
uint8_t* raw_output = vdex_begin_ + oat_dex_file->dex_file_offset_;
// Extract the dex file.
std::string error_msg;
if (!dex_file->ExtractToMemory(raw_output, &error_msg)) {
LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
<< " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
return false;
}
return true;
}
bool OatWriter::WriteDexFile(File* file,
OatDexFile* oat_dex_file,
File* dex_file) {
uint8_t* raw_output = vdex_begin_ + oat_dex_file->dex_file_offset_;
if (!dex_file->PreadFully(raw_output, oat_dex_file->dex_file_size_, /*offset=*/ 0u)) {
PLOG(ERROR) << "Failed to copy dex file to vdex file."
<< " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
return false;
}
return true;
}
bool OatWriter::WriteDexFile(OatDexFile* oat_dex_file,
const uint8_t* dex_file,
bool update_input_vdex) {
// Note: The raw data has already been checked to contain the header
// and all the data that the header specifies as the file size.
DCHECK(dex_file != nullptr);
DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
DCHECK_EQ(oat_dex_file->dex_file_size_, AsUnalignedDexFileHeader(dex_file)->file_size_);
if (update_input_vdex) {
// The vdex already contains the dex code, no need to write it again.
} else {
uint8_t* raw_output = vdex_begin_ + oat_dex_file->dex_file_offset_;
memcpy(raw_output, dex_file, oat_dex_file->dex_file_size_);
}
return true;
}
bool OatWriter::OpenDexFiles(
File* file,
bool verify,
/*inout*/ std::vector<MemMap>* opened_dex_files_map,
/*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
if (oat_dex_files_.empty()) {
// Nothing to do.
return true;
}
if (!extract_dex_files_into_vdex_) {
DCHECK_EQ(opened_dex_files_map->size(), 0u);
std::vector<std::unique_ptr<const DexFile>> dex_files;
std::vector<MemMap> maps;
for (OatDexFile& oat_dex_file : oat_dex_files_) {
std::string error_msg;
maps.emplace_back(oat_dex_file.source_.GetZipEntry()->MapDirectlyOrExtract(
oat_dex_file.dex_file_location_data_, "zipped dex", &error_msg, alignof(DexFile)));
MemMap* map = &maps.back();
if (!map->IsValid()) {
LOG(ERROR) << error_msg;
return false;
}
// Now, open the dex file.
const ArtDexFileLoader dex_file_loader;
dex_files.emplace_back(dex_file_loader.Open(map->Begin(),
map->Size(),
oat_dex_file.GetLocation(),
oat_dex_file.dex_file_location_checksum_,
/* oat_dex_file */ nullptr,
verify,
verify,
&error_msg));
if (dex_files.back() == nullptr) {
LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
<< " Error: " << error_msg;
return false;
}
oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
}
*opened_dex_files_map = std::move(maps);
*opened_dex_files = std::move(dex_files);
CloseSources();
return true;
}
// We could have closed the sources at the point of writing the dex files, but to
// make it consistent with the case we're not writing the dex files, we close them now.
CloseSources();
DCHECK_EQ(opened_dex_files_map->size(), 1u);
DCHECK(vdex_begin_ == opened_dex_files_map->front().Begin());
const ArtDexFileLoader dex_file_loader;
std::vector<std::unique_ptr<const DexFile>> dex_files;
for (OatDexFile& oat_dex_file : oat_dex_files_) {
const uint8_t* raw_dex_file = vdex_begin_ + oat_dex_file.dex_file_offset_;
if (kIsDebugBuild) {
// Check the validity of the input files.
// Note that ValidateDexFileHeader() logs error messages.
CHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation()))
<< "Failed to verify written dex file header!"
<< " Output: " << file->GetPath()
<< " ~ " << std::hex << static_cast<const void*>(raw_dex_file);
const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
CHECK_EQ(header->file_size_, oat_dex_file.dex_file_size_)
<< "File size mismatch in written dex file header! Expected: "
<< oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
<< " Output: " << file->GetPath();
}
// Now, open the dex file.
std::string error_msg;
dex_files.emplace_back(dex_file_loader.Open(raw_dex_file,
oat_dex_file.dex_file_size_,
oat_dex_file.GetLocation(),
oat_dex_file.dex_file_location_checksum_,
/* oat_dex_file */ nullptr,
verify,
verify,
&error_msg));
if (dex_files.back() == nullptr) {
LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
<< " Error: " << error_msg;
return false;
}
// Set the class_offsets size now that we have easy access to the DexFile and
// it has been verified in dex_file_loader.Open.
oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
}
*opened_dex_files = std::move(dex_files);
return true;
}
void OatWriter::InitializeTypeLookupTables(
const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
TimingLogger::ScopedTiming split("InitializeTypeLookupTables", timings_);
DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
OatDexFile* oat_dex_file = &oat_dex_files_[i];
DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
if (table_size == 0u) {
// We want a 1:1 mapping between `dex_files_` and `type_lookup_table_oat_dex_files_`,
// to simplify `WriteTypeLookupTables`. We push a null entry to notify
// that the dex file at index `i` does not have a type lookup table.
type_lookup_table_oat_dex_files_.push_back(nullptr);
continue;
}
const DexFile& dex_file = *opened_dex_files[i].get();
TypeLookupTable type_lookup_table = TypeLookupTable::Create(dex_file);
type_lookup_table_oat_dex_files_.push_back(
std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
}
}
bool OatWriter::WriteDexLayoutSections(OutputStream* oat_rodata,
const std::vector<const DexFile*>& opened_dex_files) {
TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
if (!kWriteDexLayoutInfo) {
return true;
}
uint32_t expected_offset = oat_data_offset_ + oat_size_;
off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
if (static_cast<uint32_t>(actual_offset) != expected_offset) {
PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
<< " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
return false;
}
DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
size_t rodata_offset = oat_size_;
for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
OatDexFile* oat_dex_file = &oat_dex_files_[i];
DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
// Write dex layout section alignment bytes.
const size_t padding_size =
RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
if (padding_size != 0u) {
std::vector<uint8_t> buffer(padding_size, 0u);
if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
PLOG(ERROR) << "Failed to write lookup table alignment padding."
<< " File: " << oat_dex_file->GetLocation()
<< " Output: " << oat_rodata->GetLocation();
return false;
}
size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
rodata_offset += padding_size;
}
DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
DCHECK_EQ(oat_data_offset_ + rodata_offset,
static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
DCHECK(oat_dex_file != nullptr);
if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
sizeof(oat_dex_file->dex_sections_layout_))) {
PLOG(ERROR) << "Failed to write dex layout sections."
<< " File: " << oat_dex_file->GetLocation()
<< " Output: " << oat_rodata->GetLocation();
return false;
}
oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
}
oat_size_ = rodata_offset;
if (!oat_rodata->Flush()) {
PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
<< " File: " << oat_rodata->GetLocation();
return false;
}
return true;
}
void OatWriter::WriteTypeLookupTables(/*out*/std::vector<uint8_t>* buffer) {
TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
size_t type_lookup_table_size = 0u;
for (const DexFile* dex_file : *dex_files_) {
type_lookup_table_size +=
sizeof(uint32_t) + TypeLookupTable::RawDataLength(dex_file->NumClassDefs());
}
// Reserve the space to avoid reallocations later on.
buffer->reserve(buffer->size() + type_lookup_table_size);
// Align the start of the first type lookup table.
size_t initial_offset = vdex_size_;
size_t table_offset = RoundUp(initial_offset, 4);
size_t padding_size = table_offset - initial_offset;
size_vdex_lookup_table_alignment_ += padding_size;
for (uint32_t j = 0; j < padding_size; ++j) {
buffer->push_back(0);
}
vdex_size_ += padding_size;
vdex_lookup_tables_offset_ = vdex_size_;
for (size_t i = 0, size = type_lookup_table_oat_dex_files_.size(); i != size; ++i) {
OatDexFile* oat_dex_file = &oat_dex_files_[i];
if (type_lookup_table_oat_dex_files_[i] == nullptr) {
buffer->insert(buffer->end(), {0u, 0u, 0u, 0u});
size_vdex_lookup_table_ += sizeof(uint32_t);
vdex_size_ += sizeof(uint32_t);
oat_dex_file->lookup_table_offset_ = 0u;
} else {
oat_dex_file->lookup_table_offset_ = vdex_size_ + sizeof(uint32_t);
const TypeLookupTable& table = type_lookup_table_oat_dex_files_[i]->GetTypeLookupTable();
uint32_t table_size = table.RawDataLength();
DCHECK_NE(0u, table_size);
DCHECK_ALIGNED(table_size, 4);
size_t old_buffer_size = buffer->size();
buffer->resize(old_buffer_size + table.RawDataLength() + sizeof(uint32_t), 0u);
memcpy(buffer->data() + old_buffer_size, &table_size, sizeof(uint32_t));
memcpy(buffer->data() + old_buffer_size + sizeof(uint32_t), table.RawData(), table_size);
vdex_size_ += table_size + sizeof(uint32_t);
size_vdex_lookup_table_ += table_size + sizeof(uint32_t);
}
}
}
bool OatWriter::FinishVdexFile(File* vdex_file, verifier::VerifierDeps* verifier_deps) {
size_t old_vdex_size = vdex_size_;
std::vector<uint8_t> buffer;
buffer.reserve(64 * KB);
WriteVerifierDeps(verifier_deps, &buffer);
WriteTypeLookupTables(&buffer);
DCHECK_EQ(vdex_size_, old_vdex_size + buffer.size());
// Resize the vdex file.
if (vdex_file->SetLength(vdex_size_) != 0) {
PLOG(ERROR) << "Failed to resize vdex file " << vdex_file->GetPath();
return false;
}
uint8_t* vdex_begin = vdex_begin_;
MemMap extra_map;
if (extract_dex_files_into_vdex_) {
DCHECK(vdex_begin != nullptr);
// Write data to the last already mmapped page of the vdex file.
size_t mmapped_vdex_size = RoundUp(old_vdex_size, kPageSize);
size_t first_chunk_size = std::min(buffer.size(), mmapped_vdex_size - old_vdex_size);
memcpy(vdex_begin + old_vdex_size, buffer.data(), first_chunk_size);
if (first_chunk_size != buffer.size()) {
size_t tail_size = buffer.size() - first_chunk_size;
std::string error_msg;
extra_map = MemMap::MapFile(
tail_size,
PROT_READ | PROT_WRITE,
MAP_SHARED,
vdex_file->Fd(),
/*start=*/ mmapped_vdex_size,
/*low_4gb=*/ false,
vdex_file->GetPath().c_str(),
&error_msg);
if (!extra_map.IsValid()) {
LOG(ERROR) << "Failed to mmap() vdex file tail. File: " << vdex_file->GetPath()
<< " error: " << error_msg;
return false;
}
memcpy(extra_map.Begin(), buffer.data() + first_chunk_size, tail_size);
}
} else {
DCHECK(vdex_begin == nullptr);
std::string error_msg;
extra_map = MemMap::MapFile(
vdex_size_,
PROT_READ | PROT_WRITE,
MAP_SHARED,
vdex_file->Fd(),
/*start=*/ 0u,
/*low_4gb=*/ false,
vdex_file->GetPath().c_str(),
&error_msg);
if (!extra_map.IsValid()) {
LOG(ERROR) << "Failed to mmap() vdex file. File: " << vdex_file->GetPath()
<< " error: " << error_msg;
return false;
}
vdex_begin = extra_map.Begin();
memcpy(vdex_begin + old_vdex_size, buffer.data(), buffer.size());
}
// Write checksums
off_t checksums_offset = VdexFile::GetChecksumsOffset();
VdexFile::VdexChecksum* checksums_data =
reinterpret_cast<VdexFile::VdexChecksum*>(vdex_begin + checksums_offset);
for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
OatDexFile* oat_dex_file = &oat_dex_files_[i];
checksums_data[i] = oat_dex_file->dex_file_location_checksum_;
size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
}
// Write sections.
uint8_t* ptr = vdex_begin + sizeof(VdexFile::VdexFileHeader);
// Checksums section.
new (ptr) VdexFile::VdexSectionHeader(VdexSection::kChecksumSection,
checksums_offset,
size_vdex_checksums_);
ptr += sizeof(VdexFile::VdexSectionHeader);
// Dex section.
new (ptr) VdexFile::VdexSectionHeader(
VdexSection::kDexFileSection,
extract_dex_files_into_vdex_ ? vdex_dex_files_offset_ : 0u,
extract_dex_files_into_vdex_ ? vdex_verifier_deps_offset_ - vdex_dex_files_offset_ : 0u);
ptr += sizeof(VdexFile::VdexSectionHeader);
// VerifierDeps section.
new (ptr) VdexFile::VdexSectionHeader(VdexSection::kVerifierDepsSection,
vdex_verifier_deps_offset_,
size_verifier_deps_);
ptr += sizeof(VdexFile::VdexSectionHeader);
// TypeLookupTable section.
new (ptr) VdexFile::VdexSectionHeader(VdexSection::kTypeLookupTableSection,
vdex_lookup_tables_offset_,
vdex_size_ - vdex_lookup_tables_offset_);
// All the contents (except the header) of the vdex file has been emitted in memory. Flush it
// to disk.
{
TimingLogger::ScopedTiming split("VDEX flush contents", timings_);
// Sync the data to the disk while the header is invalid. We do not want to end up with
// a valid header and invalid data if the process is suddenly killed.
if (extract_dex_files_into_vdex_) {
// Note: We passed the ownership of the vdex dex file MemMap to the caller,
// so we need to use msync() for the range explicitly.
if (msync(vdex_begin, RoundUp(old_vdex_size, kPageSize), MS_SYNC) != 0) {
PLOG(ERROR) << "Failed to sync vdex file contents" << vdex_file->GetPath();
return false;
}
}
if (extra_map.IsValid() && !extra_map.Sync()) {
PLOG(ERROR) << "Failed to sync vdex file contents" << vdex_file->GetPath();
return false;
}
}
// Now that we know all contents have been flushed to disk, we can write
// the header which will mke the vdex usable.
bool has_dex_section = extract_dex_files_into_vdex_;
new (vdex_begin) VdexFile::VdexFileHeader(has_dex_section);
// Note: If `extract_dex_files_into_vdex_`, we passed the ownership of the vdex dex file
// MemMap to the caller, so we need to use msync() for the range explicitly.
if (msync(vdex_begin, kPageSize, MS_SYNC) != 0) {
PLOG(ERROR) << "Failed to sync vdex file header " << vdex_file->GetPath();
return false;
}
return true;
}
bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
}
bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
static const uint8_t kPadding[] = {
0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
};
DCHECK_LE(size, sizeof(kPadding));
if (UNLIKELY(!out->WriteFully(kPadding, size))) {
return false;
}
*stat += size;
return true;
}
void OatWriter::SetMultiOatRelativePatcherAdjustment() {
DCHECK(dex_files_ != nullptr);
DCHECK(relative_patcher_ != nullptr);
DCHECK_NE(oat_data_offset_, 0u);
if (image_writer_ != nullptr && !dex_files_->empty()) {
// The oat data begin may not be initialized yet but the oat file offset is ready.
size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
}
}
OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
DexFileSource source,
uint32_t dex_file_location_checksum,
size_t dex_file_size)
: source_(std::move(source)),
dex_file_size_(dex_file_size),
offset_(0),
dex_file_location_size_(strlen(dex_file_location)),
dex_file_location_data_(dex_file_location),
dex_file_location_checksum_(dex_file_location_checksum),
dex_file_offset_(0u),
lookup_table_offset_(0u),
class_offsets_offset_(0u),
method_bss_mapping_offset_(0u),
type_bss_mapping_offset_(0u),
public_type_bss_mapping_offset_(0u),
package_type_bss_mapping_offset_(0u),
string_bss_mapping_offset_(0u),
dex_sections_layout_offset_(0u),
class_offsets_() {
}
size_t OatWriter::OatDexFile::SizeOf() const {
return sizeof(dex_file_location_size_)
+ dex_file_location_size_
+ sizeof(dex_file_location_checksum_)
+ sizeof(dex_file_offset_)
+ sizeof(class_offsets_offset_)
+ sizeof(lookup_table_offset_)
+ sizeof(method_bss_mapping_offset_)
+ sizeof(type_bss_mapping_offset_)
+ sizeof(public_type_bss_mapping_offset_)
+ sizeof(package_type_bss_mapping_offset_)
+ sizeof(string_bss_mapping_offset_)
+ sizeof(dex_sections_layout_offset_);
}
bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
const size_t file_offset = oat_writer->oat_data_offset_;
DCHECK_OFFSET_();
if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
if (!out->WriteFully(&type_bss_mapping_offset_, sizeof(type_bss_mapping_offset_))) {
PLOG(ERROR) << "Failed to write type bss mapping offset to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_type_bss_mapping_offset_ += sizeof(type_bss_mapping_offset_);
if (!out->WriteFully(&public_type_bss_mapping_offset_, sizeof(public_type_bss_mapping_offset_))) {
PLOG(ERROR) << "Failed to write public type bss mapping offset to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_public_type_bss_mapping_offset_ +=
sizeof(public_type_bss_mapping_offset_);
if (!out->WriteFully(&package_type_bss_mapping_offset_,
sizeof(package_type_bss_mapping_offset_))) {
PLOG(ERROR) << "Failed to write package type bss mapping offset to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_package_type_bss_mapping_offset_ +=
sizeof(package_type_bss_mapping_offset_);
if (!out->WriteFully(&string_bss_mapping_offset_, sizeof(string_bss_mapping_offset_))) {
PLOG(ERROR) << "Failed to write string bss mapping offset to " << out->GetLocation();
return false;
}
oat_writer->size_oat_dex_file_string_bss_mapping_offset_ += sizeof(string_bss_mapping_offset_);
return true;
}
bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
<< " to " << out->GetLocation();
return false;
}
oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
return true;
}
OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
uint32_t compiled_methods_with_code,
uint16_t oat_class_type)
: compiled_methods_(compiled_methods) {
const uint32_t num_methods = compiled_methods.size();
CHECK_LE(compiled_methods_with_code, num_methods);
oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
method_offsets_.resize(compiled_methods_with_code);
method_headers_.resize(compiled_methods_with_code);
uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
// We only write method-related data if there are at least some compiled methods.
num_methods_ = 0u;
DCHECK(method_bitmap_ == nullptr);
if (oat_class_type != enum_cast<uint16_t>(OatClassType::kNoneCompiled)) {
num_methods_ = num_methods;
oat_method_offsets_offset_from_oat_class += sizeof(num_methods_);
if (oat_class_type == enum_cast<uint16_t>(OatClassType::kSomeCompiled)) {
method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
uint32_t bitmap_size = BitVector::BitsToWords(num_methods) * BitVector::kWordBytes;
DCHECK_EQ(bitmap_size, method_bitmap_->GetSizeOf());
oat_method_offsets_offset_from_oat_class += bitmap_size;
}
}
for (size_t i = 0; i < num_methods; i++) {
CompiledMethod* compiled_method = compiled_methods_[i];
if (HasCompiledCode(compiled_method)) {
oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
if (oat_class_type == enum_cast<uint16_t>(OatClassType::kSomeCompiled)) {
method_bitmap_->SetBit(i);
}
} else {
oat_method_offsets_offsets_from_oat_class_[i] = 0;
}
}
}
size_t OatWriter::OatClass::SizeOf() const {
return ((num_methods_ == 0) ? 0 : sizeof(num_methods_)) +
((method_bitmap_ != nullptr) ? method_bitmap_->GetSizeOf() : 0u) +
(sizeof(method_offsets_[0]) * method_offsets_.size());
}
bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
OutputStream* out,
const size_t file_offset) const {
DCHECK_OFFSET_();
if (!out->WriteFully(&status_, sizeof(status_))) {
PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
return false;
}
oat_writer->size_oat_class_status_ += sizeof(status_);
if (!out->WriteFully(&type_, sizeof(type_))) {
PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
return false;
}
oat_writer->size_oat_class_type_ += sizeof(type_);
return true;
}
bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
if (num_methods_ != 0u) {
if (!out->WriteFully(&num_methods_, sizeof(num_methods_))) {
PLOG(ERROR) << "Failed to write number of methods to " << out->GetLocation();
return false;
}
oat_writer->size_oat_class_num_methods_ += sizeof(num_methods_);
}
if (method_bitmap_ != nullptr) {
if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_->GetSizeOf())) {
PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
return false;
}
oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_->GetSizeOf();
}
if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
return false;
}
oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
return true;
}
debug::DebugInfo OatWriter::GetDebugInfo() const {
debug::DebugInfo debug_info{};
debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_info_);
if (VdexWillContainDexFiles()) {
DCHECK_EQ(dex_files_->size(), oat_dex_files_.size());
for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
const DexFile* dex_file = (*dex_files_)[i];
const OatDexFile& oat_dex_file = oat_dex_files_[i];
uint32_t dex_file_offset = oat_dex_file.dex_file_offset_;
if (dex_file_offset != 0) {
debug_info.dex_files.emplace(dex_file_offset, dex_file);
}
}
}
return debug_info;
}
} // namespace linker
} // namespace art
|