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
|
// Copyright 2021 Google Inc. All rights reserved.
//
// 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.
package java
import (
"encoding/gob"
"fmt"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"
"github.com/google/blueprint"
"github.com/google/blueprint/depset"
"github.com/google/blueprint/pathtools"
"github.com/google/blueprint/proptools"
"android/soong/android"
"android/soong/dexpreopt"
"android/soong/java/config"
)
// This file contains the definition and the implementation of the base module that most
// source-based Java module structs embed.
// TODO:
// Autogenerated files:
// Renderscript
// Post-jar passes:
// Proguard
// Rmtypedefs
// DroidDoc
// Findbugs
// Properties that are common to most Java modules, i.e. whether it's a host or device module.
type CommonProperties struct {
// list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
// or .aidl files.
Srcs []string `android:"path,arch_variant"`
// list Kotlin of source files containing Kotlin code that should be treated as common code in
// a codebase that supports Kotlin multiplatform. See
// https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
Common_srcs []string `android:"path,arch_variant"`
// list of source files that should not be used to build the Java module.
// This is most useful in the arch/multilib variants to remove non-common files
Exclude_srcs []string `android:"path,arch_variant"`
// list of Kotlin source files that should excluded from the list of common_srcs.
Exclude_common_srcs []string `android:"path,arch_variant"`
// list of directories containing Java resources
Java_resource_dirs []string `android:"arch_variant"`
// list of directories that should be excluded from java_resource_dirs
Exclude_java_resource_dirs []string `android:"arch_variant"`
// list of files to use as Java resources
Java_resources proptools.Configurable[[]string] `android:"path,arch_variant"`
// list of files that should be excluded from java_resources and java_resource_dirs
Exclude_java_resources []string `android:"path,arch_variant"`
// Same as java_resources, but modules added here will use the device variant. Can be useful
// for making a host test that tests the contents of a device built app.
Device_common_java_resources proptools.Configurable[[]string] `android:"path_device_common"`
// Same as java_resources, but modules added here will use the device's os variant and the
// device's first architecture variant. Can be useful for making a host test that tests the
// contents of a native device built app.
Device_first_java_resources proptools.Configurable[[]string] `android:"path_device_first"`
// list of module-specific flags that will be used for javac compiles
Javacflags []string `android:"arch_variant"`
// list of module-specific flags that will be used for kotlinc compiles
Kotlincflags []string `android:"arch_variant"`
// Kotlin language version to target. Currently only 1.9 and 2 are supported.
// See kotlinc's `-language-version` flag.
Kotlin_lang_version *string
// list of java libraries that will be in the classpath
Libs []string `android:"arch_variant"`
// list of java libraries that will be compiled into the resulting jar
Static_libs proptools.Configurable[[]string] `android:"arch_variant"`
// manifest file to be included in resulting jar
Manifest *string `android:"path"`
// if not blank, run jarjar using the specified rules file
Jarjar_rules *string `android:"path,arch_variant"`
// java class names to rename with jarjar when a reverse dependency has a jarjar_prefix
// property.
Jarjar_rename []string
// if not blank, used as prefix to generate repackage rule
Jarjar_prefix *string
// Number of shards for jarjar. It needs to be an integer represented as a string.
// TODO(b/383559945) change it to int, once Configurable supports the type.
Jarjar_shards proptools.Configurable[string]
// If not blank, set the java version passed to javac as -source and -target
Java_version *string
// If set to true, allow this module to be dexed and installed on devices. Has no
// effect on host modules, which are always considered installable.
Installable *bool
// If set to true, include sources used to compile the module in to the final jar
Include_srcs *bool
// If not empty, classes are restricted to the specified packages and their sub-packages.
// This restriction is checked after applying jarjar rules and including static libs.
Permitted_packages []string
// List of modules to use as annotation processors
Plugins []string
// List of modules to use as kotlin plugin
Kotlin_plugins []string
// List of modules to export to libraries that directly depend on this library as annotation
// processors. Note that if the plugins set generates_api: true this will disable the turbine
// optimization on modules that depend on this module, which will reduce parallelism and cause
// more recompilation.
Exported_plugins []string
// The number of Java source entries each Javac instance can process
Javac_shard_size *int64
// Add host jdk tools.jar to bootclasspath
Use_tools_jar *bool
Openjdk9 struct {
// List of source files that should only be used when passing -source 1.9 or higher
Srcs []string `android:"path"`
// List of javac flags that should only be used when passing -source 1.9 or higher
Javacflags []string
}
// When compiling language level 9+ .java code in packages that are part of
// a system module, patch_module names the module that your sources and
// dependencies should be patched into. The Android runtime currently
// doesn't implement the JEP 261 module system so this option is only
// supported at compile time. It should only be needed to compile tests in
// packages that exist in libcore and which are inconvenient to move
// elsewhere.
Patch_module *string
Jacoco struct {
// List of classes to include for instrumentation with jacoco to collect coverage
// information at runtime when building with coverage enabled. If unset defaults to all
// classes.
// Supports '*' as the last character of an entry in the list as a wildcard match.
// If preceded by '.' it matches all classes in the package and subpackages, otherwise
// it matches classes in the package that have the class name as a prefix.
Include_filter []string
// List of classes to exclude from instrumentation with jacoco to collect coverage
// information at runtime when building with coverage enabled. Overrides classes selected
// by the include_filter property.
// Supports '*' as the last character of an entry in the list as a wildcard match.
// If preceded by '.' it matches all classes in the package and subpackages, otherwise
// it matches classes in the package that have the class name as a prefix.
Exclude_filter []string
}
Errorprone struct {
// List of javac flags that should only be used when running errorprone.
Javacflags []string
// List of java_plugin modules that provide extra errorprone checks.
Extra_check_modules []string
// This property can be in 3 states. When set to true, errorprone will
// be run during the regular build. When set to false, errorprone will
// never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
// environment variable is true. Setting this to false will improve build
// performance more than adding -XepDisableAllChecks in javacflags.
Enabled *bool
}
Proto struct {
// List of extra options that will be passed to the proto generator.
Output_params []string
}
// If true, then jacocoagent is automatically added as a libs dependency so that
// r8 will not strip instrumentation classes out of dexed libraries.
Instrument bool `blueprint:"mutated"`
// If true, then the module supports statically including the jacocoagent
// into the library.
Supports_static_instrumentation bool `blueprint:"mutated"`
// List of files to include in the META-INF/services folder of the resulting jar.
Services []string `android:"path,arch_variant"`
// If true, package the kotlin stdlib into the jar. Defaults to true.
Static_kotlin_stdlib *bool `android:"arch_variant"`
// A list of java_library instances that provide additional hiddenapi annotations for the library.
Hiddenapi_additional_annotations []string
// Additional srcJars tacked in by GeneratedJavaLibraryModule
Generated_srcjars []android.Path `android:"mutated"`
// intermediate aconfig cache file tacked in by GeneratedJavaLibraryModule
Aconfig_Cache_files []android.Path `android:"mutated"`
// If true, then only the headers are built and not the implementation jar.
Headers_only *bool
// A list of files or dependencies to make available to the build sandbox. This is
// useful if source files are symlinks, the targets of the symlinks must be listed here.
// Note that currently not all actions implemented by android_apps are sandboxed, so you
// may only see this being necessary in lint builds.
Compile_data []string `android:"path"`
// Property signifying whether the module compiles stubs or not.
// Should be set to true when srcs of this module are stub files.
// This property does not need to be set to true when the module depends on
// the stubs via libs, but should be set to true when the module depends on
// the stubs via static libs.
Is_stubs_module *bool
Ravenizer struct {
// If true, enable the "Ravenizer" tool on the output jar.
// "Ravenizer" is a tool for Ravenwood tests, but it can also be enabled on other kinds
// of java targets.
Enabled *bool
// If true, the "Ravenizer" tool will remove all Mockito and DexMaker
// classes from the output jar.
Strip_mockito *bool
}
// Contributing api surface of the stub module. Is not visible to bp modules, and should
// only be set for stub submodules generated by the java_sdk_library
Stub_contributing_api *string `blueprint:"mutated"`
// If true, enable the "ApiMapper" tool on the output jar. "ApiMapper" is a tool to inject
// bytecode to log API calls.
ApiMapper bool `blueprint:"mutated"`
}
// Properties that are specific to device modules. Host module factories should not add these when
// constructing a new module.
type DeviceProperties struct {
// If not blank, set to the version of the sdk to compile against.
// Defaults to an empty string, which compiles the module against the private platform APIs.
// Values are of one of the following forms:
// 1) numerical API level, "current", "none", or "core_platform"
// 2) An SDK kind with an API level: "<sdk kind>_<API level>"
// See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
// If the SDK kind is empty, it will be set to public.
Sdk_version *string
// if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
// Defaults to empty string "". See sdk_version for possible values.
Max_sdk_version *string
// if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
// Defaults to empty string "". See sdk_version for possible values.
Replace_max_sdk_version_placeholder *string
// if not blank, set the targetSdkVersion in the AndroidManifest.xml.
// Defaults to sdk_version if not set. See sdk_version for possible values.
Target_sdk_version *string
// Whether to compile against the platform APIs instead of an SDK.
// If true, then sdk_version must be empty. The value of this field
// is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Platform_apis *bool
Aidl struct {
// Top level directories to pass to aidl tool
Include_dirs []string
// Directories rooted at the Android.bp file to pass to aidl tool
Local_include_dirs []string
// directories that should be added as include directories for any aidl sources of modules
// that depend on this module, as well as to aidl for this module.
Export_include_dirs []string
// whether to generate traces (for systrace) for this interface
Generate_traces *bool
// whether to generate Binder#GetTransaction name method.
Generate_get_transaction_name *bool
// whether all interfaces should be annotated with required permissions.
Enforce_permissions *bool
// allowlist for interfaces that (temporarily) do not require annotation for permissions.
Enforce_permissions_exceptions []string `android:"path"`
// list of flags that will be passed to the AIDL compiler
Flags []string
}
// If true, export a copy of the module as a -hostdex module for host testing.
Hostdex *bool
Target struct {
Hostdex struct {
// Additional required dependencies to add to -hostdex modules.
Required []string
}
}
// When targeting 1.9 and above, override the modules to use with --system,
// otherwise provides defaults libraries to add to the bootclasspath.
System_modules *string
IsSDKLibrary bool `blueprint:"mutated"`
// If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
// Defaults to false.
V4_signature *bool
// Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
// public stubs library.
SyspropPublicStub string `blueprint:"mutated"`
HiddenAPIPackageProperties
HiddenAPIFlagFileProperties
}
// Properties that can be overridden by overriding module (e.g. override_android_app)
type OverridableProperties struct {
// set the name of the output. If not set, `name` is used.
// To override a module with this property set, overriding module might need to set this as well.
// Otherwise, both the overridden and the overriding modules will have the same output name, which
// can cause the duplicate output error.
Stem *string
// if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
// Defaults to sdk_version if not set. See sdk_version for possible values.
Min_sdk_version *string
}
// Functionality common to Module and Import
//
// It is embedded in Module so its functionality can be used by methods in Module
// but it is currently only initialized by Import and Library.
type embeddableInModuleAndImport struct {
// Functionality related to this being used as a component of a java_sdk_library.
EmbeddableSdkLibraryComponent
}
func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
e.initSdkLibraryComponent(module)
}
// Module/Import's OutgoingDepIsInSameApex(...) delegates to this method.
//
// This cannot implement OutgoingDepIsInSameApex(...) directly as that leads to ambiguity with
// the one provided by ApexModuleBase.
func depIsInSameApex(tag blueprint.DependencyTag) bool {
// dependencies other than the static linkage are all considered crossing APEX boundary
if tag == staticLibTag {
return true
}
return false
}
// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
// or an invalid path describing the reason it is invalid.
//
// It is unset if a dex jar isn't applicable, i.e. no build rule has been
// requested to create one.
//
// If a dex jar has been requested to be built then it is set, and it may be
// either a valid android.Path, or invalid with a reason message. The latter
// happens if the source that should produce the dex file isn't able to.
//
// E.g. it is invalid with a reason message if there is a prebuilt APEX that
// could produce the dex jar through a deapexer module, but the APEX isn't
// installable so doing so wouldn't be safe.
type OptionalDexJarPath struct {
isSet bool
path android.OptionalPath
}
// IsSet returns true if a path has been set, either invalid or valid.
func (o OptionalDexJarPath) IsSet() bool {
return o.isSet
}
// Valid returns true if there is a path that is valid.
func (o OptionalDexJarPath) Valid() bool {
return o.isSet && o.path.Valid()
}
// Path returns the valid path, or panics if it's either not set or is invalid.
func (o OptionalDexJarPath) Path() android.Path {
if !o.isSet {
panic("path isn't set")
}
return o.path.Path()
}
// PathOrNil returns the path if it's set and valid, or else nil.
func (o OptionalDexJarPath) PathOrNil() android.Path {
if o.Valid() {
return o.Path()
}
return nil
}
// InvalidReason returns the reason for an invalid path, which is never "". It
// returns "" for an unset or valid path.
func (o OptionalDexJarPath) InvalidReason() string {
if !o.isSet {
return ""
}
return o.path.InvalidReason()
}
func (o OptionalDexJarPath) String() string {
if !o.isSet {
return "<unset>"
}
return o.path.String()
}
// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
func makeUnsetDexJarPath() OptionalDexJarPath {
return OptionalDexJarPath{isSet: false}
}
// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
// the given OptionalPath, which may be valid or invalid.
func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
return OptionalDexJarPath{isSet: true, path: path}
}
// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
// valid given path. It returns an unset OptionalDexJarPath if the given path is
// nil.
func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
if path == nil {
return makeUnsetDexJarPath()
}
return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
}
// Module contains the properties and members used by all java module types
type Module struct {
android.ModuleBase
android.DefaultableModuleBase
android.ApexModuleBase
// Functionality common to Module and Import.
embeddableInModuleAndImport
properties CommonProperties
protoProperties android.ProtoProperties
deviceProperties DeviceProperties
overridableProperties OverridableProperties
sourceProperties android.SourceProperties
// jar file containing header classes including static library dependencies, suitable for
// inserting into the bootclasspath/classpath of another compile
headerJarFile android.Path
// jar file containing implementation classes including static library dependencies but no
// resources
implementationJarFile android.Path
// args and dependencies to package source files into a srcjar
srcJarArgs []string
srcJarDeps android.Paths
// the source files of this module and all its static dependencies
transitiveSrcFiles depset.DepSet[android.Path]
// jar file containing implementation classes and resources including static library
// dependencies
implementationAndResourcesJar android.Path
// output file containing classes.dex and resources
dexJarFile OptionalDexJarPath
// output file containing uninstrumented classes that will be instrumented by jacoco
jacocoReportClassesFile android.Path
// output file of the module, which may be a classes jar or a dex jar
outputFile android.Path
extraOutputFiles android.Paths
exportAidlIncludeDirs android.Paths
ignoredAidlPermissionList android.Paths
logtagsSrcs android.Paths
// installed file for binary dependency
installFile android.Path
// installed file for hostdex copy
hostdexInstallFile android.InstallPath
// list of unique .java and .kt source files
uniqueSrcFiles android.Paths
// list of srcjars that was passed to javac
compiledSrcJars android.Paths
// manifest file to use instead of properties.Manifest
overrideManifest android.OptionalPath
// list of plugins that this java module is exporting
exportedPluginJars android.Paths
// list of plugins that this java module is exporting
exportedPluginClasses []string
// if true, the exported plugins generate API and require disabling turbine.
exportedDisableTurbine bool
// list of source files, collected from srcFiles with unique java and all kt files,
// will be used by android.IDEInfo struct
expandIDEInfoCompiledSrcs []string
// expanded Jarjar_rules
expandJarjarRules android.Path
// jarjar rule for inherited jarjar rules
repackageJarjarRules android.Path
// Extra files generated by the module type to be added as java resources.
extraResources android.Paths
hiddenAPI
dexer
dexpreopter
usesLibrary
linter
// list of the xref extraction files
kytheFiles android.Paths
kytheKotlinFiles android.Paths
hideApexVariantFromMake bool
sdkVersion android.SdkSpec
minSdkVersion android.ApiLevel
maxSdkVersion android.ApiLevel
sourceExtensions []string
annoSrcJars android.Paths
// output file name based on Stem property.
// This should be set in every ModuleWithStem's GenerateAndroidBuildActions
// or the module should override Stem().
stem string
// Values that will be set in the JarJarProvider data for jarjar repackaging,
// and merged with our dependencies' rules.
jarjarRenameRules map[string]string
stubsLinkType StubsLinkType
// Paths to the aconfig intermediate cache files that are provided by the
// java_aconfig_library or java_library modules that are statically linked
// to this module. Does not contain cache files from all transitive dependencies.
aconfigCacheFiles android.Paths
// List of soong module dependencies required to compile the current module.
// This information is printed out to `Dependencies` field in module_bp_java_deps.json
compileDepNames []string
ravenizer struct {
enabled bool
}
}
var _ android.InstallableModule = (*Module)(nil)
// To satisfy the InstallableModule interface
func (j *Module) StaticDependencyTags() []blueprint.DependencyTag {
return []blueprint.DependencyTag{staticLibTag}
}
// To satisfy the InstallableModule interface
func (j *Module) DynamicDependencyTags() []blueprint.DependencyTag {
return []blueprint.DependencyTag{libTag, sdkLibTag, bootClasspathTag, systemModulesTag,
instrumentationForTag, java9LibTag}
}
// Overrides android.ModuleBase.InstallInProduct()
func (j *Module) InstallInProduct() bool {
return j.ProductSpecific()
}
var _ android.StubsAvailableModule = (*Module)(nil)
// To safisfy the StubsAvailableModule interface
func (j *Module) IsStubsModule() bool {
return proptools.Bool(j.properties.Is_stubs_module)
}
func CheckStableSdkVersion(ctx android.BaseModuleContext, module android.ModuleProxy) error {
if info, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
if info.SdkVersion.Stable() {
return nil
}
if info.SdkVersion.Kind == android.SdkCorePlatform {
if useLegacyCorePlatformApi(ctx, android.OtherModulePointerProviderOrDefault(ctx, module, android.CommonModuleInfoProvider).BaseModuleName) {
return fmt.Errorf("non stable SDK %v - uses legacy core platform", info.SdkVersion)
} else {
// Treat stable core platform as stable.
return nil
}
} else {
return fmt.Errorf("non stable SDK %v", info.SdkVersion)
}
}
return nil
}
// checkSdkVersions enforces restrictions around SDK dependencies.
func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
if j.RequiresStableAPIs(ctx) {
if sc, ok := ctx.Module().(android.SdkContext); ok {
if !sc.SdkVersion(ctx).Specified() {
ctx.PropertyErrorf("sdk_version",
"sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
}
}
}
// Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
// See rank() for details.
ctx.VisitDirectDepsProxy(func(module android.ModuleProxy) {
tag := ctx.OtherModuleDependencyTag(module)
libInfo, isJavaLibrary := android.OtherModuleProvider(ctx, module, JavaLibraryInfoProvider)
_, isAndroidLibrary := android.OtherModuleProvider(ctx, module, AndroidLibraryInfoProvider)
_, isJavaAconfigLibrary := android.OtherModuleProvider(ctx, module, android.CodegenInfoProvider)
// Exclude java_aconfig_library modules to maintain consistency with existing behavior.
if (isJavaLibrary && !libInfo.Prebuilt && !isJavaAconfigLibrary) || isAndroidLibrary {
// TODO(satayev): cover other types as well, e.g. imports
switch tag {
case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
j.checkSdkLinkType(ctx, module)
}
}
})
}
func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
if sc, ok := ctx.Module().(android.SdkContext); ok {
usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
if usePlatformAPI && sdkVersionSpecified {
ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is not empty, which means this module cannot use platform APIs. However platform_apis is set to true.")
} else if !usePlatformAPI && !sdkVersionSpecified {
ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is empty, which means that this module is build against platform APIs. However platform_apis is not set to true")
}
}
}
func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
if _, ok := ctx.Module().(android.SdkContext); ok {
headersOnly := proptools.Bool(j.properties.Headers_only)
installable := proptools.Bool(j.properties.Installable)
if headersOnly && installable {
ctx.PropertyErrorf("headers_only", "This module has conflicting settings. headers_only is true which, which means this module doesn't generate an implementation jar. However installable is set to true.")
}
}
}
func (j *Module) addHostProperties() {
j.AddProperties(
&j.properties,
&j.overridableProperties,
&j.protoProperties,
&j.usesLibraryProperties,
)
}
func (j *Module) addHostAndDeviceProperties() {
j.addHostProperties()
j.AddProperties(
&j.deviceProperties,
&j.dexer.dexProperties,
&j.dexpreoptProperties,
&j.linter.properties,
)
}
// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
// makes it available through the hiddenAPIPropertyInfoProvider.
func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
hiddenAPIInfo := newHiddenAPIPropertyInfo()
// Populate with flag file paths from the properties.
hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
// Populate with package rules from the properties.
hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
android.SetProvider(ctx, hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
}
// helper method for java modules to set OutputFilesProvider
func setOutputFiles(ctx android.ModuleContext, m Module) {
ctx.SetOutputFiles(append(android.PathsIfNonNil(m.outputFile), m.extraOutputFiles...), "")
ctx.SetOutputFiles(android.PathsIfNonNil(m.outputFile), android.DefaultDistTag)
ctx.SetOutputFiles(android.PathsIfNonNil(m.implementationAndResourcesJar), ".jar")
ctx.SetOutputFiles(android.PathsIfNonNil(m.headerJarFile), ".hjar")
if m.dexer.proguardDictionary.Valid() {
ctx.SetOutputFiles(android.Paths{m.dexer.proguardDictionary.Path()}, ".proguard_map")
}
ctx.SetOutputFiles(m.properties.Generated_srcjars, ".generated_srcjars")
}
func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
initJavaModule(module, hod, false)
}
func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
initJavaModule(module, hod, true)
}
func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
multilib := android.MultilibCommon
if multiTargets {
android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
} else {
android.InitAndroidArchModule(module, hod, multilib)
}
android.InitDefaultableModule(module)
}
func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
return j.properties.Instrument &&
ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
}
func (j *Module) shouldApiMapper() bool {
return j.properties.ApiMapper
}
func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
return j.properties.Supports_static_instrumentation &&
j.shouldInstrument(ctx) &&
(ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
ctx.Config().UnbundledBuild())
}
func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
// Force enable the instrumentation for java code that is built for APEXes ...
// except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
// doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
isJacocoAgent := ctx.ModuleName() == "jacocoagent"
compileDex := Bool(j.dexProperties.Compile_dex) || Bool(j.properties.Installable)
if compileDex && !isJacocoAgent && !apexInfo.IsForPlatform() {
if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
return true
} else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
return true
}
}
return false
}
func (j *Module) setInstrument(value bool) {
j.properties.Instrument = value
}
func (j *Module) setApiMapper(value bool) {
j.properties.ApiMapper = value
}
func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
}
func (j *Module) SystemModules() string {
return proptools.String(j.deviceProperties.System_modules)
}
func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
if j.overridableProperties.Min_sdk_version != nil {
return android.ApiLevelFrom(ctx, *j.overridableProperties.Min_sdk_version)
}
return j.SdkVersion(ctx).ApiLevel
}
func (j *Module) GetDeviceProperties() *DeviceProperties {
return &j.deviceProperties
}
func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
if j.deviceProperties.Max_sdk_version != nil {
return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
}
// Default is PrivateApiLevel
return android.SdkSpecPrivate.ApiLevel
}
func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
}
// Default is PrivateApiLevel
return android.SdkSpecPrivate.ApiLevel
}
func (j *Module) MinSdkVersionString() string {
return j.minSdkVersion.String()
}
func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
if j.deviceProperties.Target_sdk_version != nil {
return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
}
return j.SdkVersion(ctx).ApiLevel
}
func (j *Module) AvailableFor(what string) bool {
return android.CheckAvailableForApex(what, j.ApexAvailableFor())
}
func (j *Module) ApexAvailableFor() []string {
list := j.ApexModuleBase.ApexAvailable()
if Bool(j.deviceProperties.Hostdex) {
// Exception: for hostdex: true libraries, the platform variant is created
// even if it's not marked as available to platform. In that case, the platform
// variant is used only for the hostdex and not installed to the device.
list = append(list, android.AvailableToPlatform)
}
return android.FirstUniqueStrings(list)
}
func (j *Module) staticLibs(ctx android.BaseModuleContext) []string {
return j.properties.Static_libs.GetOrDefault(ctx, nil)
}
func (j *Module) deps(ctx android.BottomUpMutatorContext) {
if ctx.Device() {
j.linter.deps(ctx)
sdkDeps(ctx, android.SdkContext(j), j.dexer)
if j.deviceProperties.SyspropPublicStub != "" {
// This is a sysprop implementation library that has a corresponding sysprop public
// stubs library, and a dependency on it so that dependencies on the implementation can
// be forwarded to the public stubs library when necessary.
ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
}
}
libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
ctx.AddVariationDependencies(nil, staticLibTag, j.staticLibs(ctx)...)
// Add dependency on libraries that provide additional hidden api annotations.
ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
// Add dependency on (soft) downstream libs from which to trace references during optimization.
traceRefs := j.dexProperties.Optimize.Trace_references_from.GetOrDefault(ctx, []string{})
ctx.AddVariationDependencies(nil, traceReferencesTag, traceRefs...)
// For library dependencies that are component libraries (like stubs), add the implementation
// as a dependency (dexpreopt needs to be against the implementation library, not stubs).
for _, dep := range libDeps {
if dep != nil {
if component, ok := dep.(SdkLibraryComponentDependency); ok {
if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
// Add library as optional if it's one of the optional compatibility libs or it's
// explicitly listed in the optional_uses_libs property.
tag := usesLibReqTag
if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) ||
android.InList(*lib, j.usesLibrary.usesLibraryProperties.Optional_uses_libs.GetOrDefault(ctx, nil)) {
tag = usesLibOptTag
}
ctx.AddVariationDependencies(nil, tag, *lib)
}
}
}
}
ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag, j.properties.Kotlin_plugins...)
ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
android.ProtoDeps(ctx, &j.protoProperties)
if j.hasSrcExt(".proto") {
protoDeps(ctx, &j.protoProperties)
}
if j.hasSrcExt(".kt") {
// TODO(ccross): move this to a mutator pass that can tell if generated sources contain
// Kotlin files
tag := staticLibTag
if !BoolDefault(j.properties.Static_kotlin_stdlib, true) {
tag = libTag
}
ctx.AddVariationDependencies(nil, tag,
"kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8", "kotlin-annotations")
}
// Framework libraries need special handling in static coverage builds: they should not have
// static dependency on jacoco, otherwise there would be multiple conflicting definitions of
// the same jacoco classes coming from different bootclasspath jars.
if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
j.properties.Instrument = true
}
} else if j.shouldInstrumentStatic(ctx) {
ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
}
if j.useCompose(ctx) {
ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
"kotlin-compose-compiler-plugin")
}
}
func hasSrcExt(srcs []string, ext string) bool {
for _, src := range srcs {
if filepath.Ext(src) == ext {
return true
}
}
return false
}
func (j *Module) hasSrcExt(ext string) bool {
return hasSrcExt(j.properties.Srcs, ext)
}
func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
var flags string
if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
flags = "-Wmissing-permission-annotation -Werror"
}
}
return flags
}
func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
aidlIncludes = append(aidlIncludes,
android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
aidlIncludes = append(aidlIncludes,
android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
var flags []string
var deps android.Paths
var includeDirs android.Paths
flags = append(flags, j.deviceProperties.Aidl.Flags...)
if aidlPreprocess.Valid() {
flags = append(flags, "-p"+aidlPreprocess.String())
deps = append(deps, aidlPreprocess.Path())
} else if len(aidlIncludeDirs) > 0 {
includeDirs = append(includeDirs, aidlIncludeDirs...)
}
if len(j.exportAidlIncludeDirs) > 0 {
includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
}
if len(aidlIncludes) > 0 {
includeDirs = append(includeDirs, aidlIncludes...)
}
includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
includeDirs = append(includeDirs, src.Path())
}
flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
// add flags for dirs containing AIDL srcs that haven't been specified yet
flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
sdkVersion := (j.SdkVersion(ctx)).Kind
defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
flags = append(flags, "-t")
}
if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
flags = append(flags, "--transaction_names")
}
if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
}
aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
return strings.Join(flags, " "), deps
}
func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
var flags javaBuilderFlags
// javaVersion flag.
flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
epEnabled := j.properties.Errorprone.Enabled
if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
}
errorProneFlags := []string{
"-Xplugin:ErrorProne",
"${config.ErrorProneChecks}",
}
errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
"'" + strings.Join(errorProneFlags, " ") + "'"
flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
}
// classpath
flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
flags.classpath = append(flags.classpath, deps.classpath...)
flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
flags.processorPath = append(flags.processorPath, deps.processorPath...)
flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
flags.processors = append(flags.processors, deps.processorClasses...)
flags.processors = android.FirstUniqueStrings(flags.processors)
if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
// Give host-side tools a version of OpenJDK's standard libraries
// close to what they're targeting. As of Dec 2017, AOSP is only
// bundling OpenJDK 8 and 9, so nothing < 8 is available.
//
// When building with OpenJDK 8, the following should have no
// effect since those jars would be available by default.
//
// When building with OpenJDK 9 but targeting a version < 1.8,
// putting them on the bootclasspath means that:
// a) code can't (accidentally) refer to OpenJDK 9 specific APIs
// b) references to existing APIs are not reinterpreted in an
// OpenJDK 9-specific way, eg. calls to subclasses of
// java.nio.Buffer as in http://b/70862583
java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
flags.bootClasspath = append(flags.bootClasspath,
android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
if Bool(j.properties.Use_tools_jar) {
flags.bootClasspath = append(flags.bootClasspath,
android.PathForSource(ctx, java8Home, "lib/tools.jar"))
}
}
// systemModules
flags.systemModules = deps.systemModules
return flags
}
func (j *Module) collectJavacFlags(
ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
// javac flags.
javacFlags := j.properties.Javacflags
var needsDebugInfo bool
needsDebugInfo = false
for _, flag := range javacFlags {
if strings.HasPrefix(flag, "-g") {
needsDebugInfo = true
}
}
if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
// For non-host binaries, override the -g flag passed globally to remove
// local variable debug info to reduce disk and memory usage.
javacFlags = append(javacFlags, "-g:source,lines")
}
javacFlags = append(javacFlags, "-Xlint:-dep-ann")
if flags.javaVersion.usesJavaModules() {
javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
} else if len(j.properties.Openjdk9.Javacflags) > 0 {
// java version defaults higher than openjdk 9, these conditionals should no longer be necessary
ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
}
if flags.javaVersion.usesJavaModules() {
if j.properties.Patch_module != nil {
// Manually specify build directory in case it is not under the repo root.
// (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
// just adding a symlink under the root doesn't help.)
patchPaths := []string{".", ctx.Config().SoongOutDir()}
classPath := flags.classpath.FormJavaClassPath("")
if classPath != "" {
patchPaths = append(patchPaths, classPath)
}
javacFlags = append(
javacFlags,
"--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
}
}
if len(javacFlags) > 0 {
// optimization.
ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
flags.javacFlags = "$javacFlags"
}
return flags
}
func (j *Module) AddJSONData(d *map[string]interface{}) {
(&j.ModuleBase).AddJSONData(d)
(*d)["Java"] = map[string]interface{}{
"SourceExtensions": j.sourceExtensions,
}
}
func (j *Module) addGeneratedSrcJars(path android.Path) {
j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
}
func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars, extraDepCombinedJars android.Paths) *JavaInfo {
// Auto-propagating jarjar rules
jarjarProviderData := j.collectJarJarRules(ctx)
if jarjarProviderData != nil {
android.SetProvider(ctx, JarJarProvider, *jarjarProviderData)
text := getJarJarRuleText(jarjarProviderData)
if text != "" {
ruleTextFile := android.PathForModuleOut(ctx, "repackaged-jarjar", "repackaging.txt")
android.WriteFileRule(ctx, ruleTextFile, text)
j.repackageJarjarRules = ruleTextFile
}
}
j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
// Only override the original value if explicitly set
if j.properties.Ravenizer.Enabled != nil {
j.ravenizer.enabled = *j.properties.Ravenizer.Enabled
}
deps := j.collectDeps(ctx)
flags := j.collectBuilderFlags(ctx, deps)
if flags.javaVersion.usesJavaModules() {
j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
} else if len(j.properties.Openjdk9.Javacflags) > 0 {
// java version defaults higher than openjdk 9, these conditionals should no longer be necessary
ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
}
srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
j.sourceExtensions = []string{}
for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
if hasSrcExt(srcFiles.Strings(), ext) {
j.sourceExtensions = append(j.sourceExtensions, ext)
}
}
if hasSrcExt(srcFiles.Strings(), ".proto") {
flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
}
kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, j.properties.Exclude_common_srcs)
if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
}
aidlSrcs := srcFiles.FilterByExt(".aidl")
flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
srcFiles = j.genSources(ctx, srcFiles, flags)
// Collect javac flags only after computing the full set of srcFiles to
// ensure that the --patch-module lookup paths are complete.
flags = j.collectJavacFlags(ctx, flags, srcFiles)
srcJars := srcFiles.FilterByExt(".srcjar")
srcJars = append(srcJars, deps.srcJars...)
srcJars = append(srcJars, extraSrcJars...)
srcJars = append(srcJars, j.properties.Generated_srcjars...)
srcFiles = srcFiles.FilterOutByExt(".srcjar")
if j.properties.Jarjar_rules != nil {
j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
}
jarName := j.Stem() + ".jar"
var uniqueJavaFiles android.Paths
set := make(map[string]bool)
for _, v := range srcFiles.FilterByExt(".java") {
if _, found := set[v.String()]; !found {
set[v.String()] = true
uniqueJavaFiles = append(uniqueJavaFiles, v)
}
}
var uniqueKtFiles android.Paths
for _, v := range srcFiles.FilterByExt(".kt") {
if _, found := set[v.String()]; !found {
set[v.String()] = true
uniqueKtFiles = append(uniqueKtFiles, v)
}
}
var uniqueSrcFiles android.Paths
uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
j.uniqueSrcFiles = uniqueSrcFiles
// We don't currently run annotation processors in turbine, which means we can't use turbine
// generated header jars when an annotation processor that generates API is enabled. One
// exception (handled further below) is when kotlin sources are enabled, in which case turbine
// is used to run all of the annotation processors.
disableTurbine := deps.disableTurbine
// Collect .java and .kt files for AIDEGen
j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
var kotlinHeaderJars android.Paths
// Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
// any dependencies so that it can override any non-final R classes from dependencies with the
// final R classes from the app.
flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
j.aconfigCacheFiles = append(deps.aconfigProtoFiles, j.properties.Aconfig_Cache_files...)
var localImplementationJars android.Paths
// If compiling headers then compile them and skip the rest
if proptools.Bool(j.properties.Headers_only) {
if srcFiles.HasExt(".kt") {
ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
}
if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
}
transitiveStaticLibsHeaderJars := deps.transitiveStaticLibsHeaderJars
localHeaderJars, combinedHeaderJarFile := j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
extraCombinedJars)
combinedHeaderJarFile, jarjared := j.jarjarIfNecessary(ctx, combinedHeaderJarFile, jarName, "turbine", false)
if jarjared {
localHeaderJars = android.Paths{combinedHeaderJarFile}
transitiveStaticLibsHeaderJars = nil
}
combinedHeaderJarFile, repackaged := j.repackageFlagsIfNecessary(ctx, combinedHeaderJarFile, jarName, "repackage-turbine")
if repackaged {
localHeaderJars = android.Paths{combinedHeaderJarFile}
transitiveStaticLibsHeaderJars = nil
}
if ctx.Failed() {
return nil
}
j.headerJarFile = combinedHeaderJarFile
if len(localHeaderJars) > 0 {
ctx.CheckbuildFile(localHeaderJars...)
} else {
// There are no local sources or resources in this module, so there is nothing to checkbuild.
ctx.UncheckedModule()
}
j.outputFile = j.headerJarFile
return &JavaInfo{
HeaderJars: android.PathsIfNonNil(j.headerJarFile),
LocalHeaderJars: localHeaderJars,
TransitiveStaticLibsHeaderJars: depset.New(depset.PREORDER, localHeaderJars, transitiveStaticLibsHeaderJars),
TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
AidlIncludeDirs: j.exportAidlIncludeDirs,
ExportedPlugins: j.exportedPluginJars,
ExportedPluginClasses: j.exportedPluginClasses,
ExportedPluginDisableTurbine: j.exportedDisableTurbine,
StubsLinkType: j.stubsLinkType,
AconfigIntermediateCacheOutputPaths: deps.aconfigProtoFiles,
SdkVersion: j.SdkVersion(ctx),
}
}
if srcFiles.HasExt(".kt") {
// When using kotlin sources turbine is used to generate annotation processor sources,
// including for annotation processors that generate API, so we can use turbine for
// java sources too.
disableTurbine = false
// user defined kotlin flags.
kotlincFlags := j.properties.Kotlincflags
CheckKotlincFlags(ctx, kotlincFlags)
// Available kotlin versions can be found at
// https://github.com/JetBrains/kotlin/blob/master/compiler/util/src/org/jetbrains/kotlin/config/LanguageVersionSettings.kt#L560
// in the `LanguageVersion` class.
// For now, avoid targeting language versions directly, as we'd like to kee our source
// code version aligned as much as possible. Ideally, after defaulting to "2", we
// can remove the "1.9" option entirely, or at least make it emit a warning.
kotlin_default_lang_version := "1.9"
if build_flag_lang_version, ok := ctx.Config().GetBuildFlag("RELEASE_KOTLIN_LANG_VERSION"); ok {
kotlin_default_lang_version = build_flag_lang_version
}
kotlin_lang_version := proptools.StringDefault(j.properties.Kotlin_lang_version, kotlin_default_lang_version)
switch kotlin_lang_version {
case "1.9":
kotlincFlags = append(kotlincFlags, "-language-version 1.9")
case "2":
kotlincFlags = append(kotlincFlags, "-Xsuppress-version-warnings", "-Xconsistent-data-class-copy-visibility")
default:
ctx.PropertyErrorf("kotlin_lang_version", "Must be one of `1.9` or `2`")
}
// Workaround for KT-46512
kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
// If there are kotlin files, compile them first but pass all the kotlin and java files
// kotlinc will use the java files to resolve types referenced by the kotlin files, but
// won't emit any classes for them.
kotlincFlags = append(kotlincFlags, "-no-stdlib")
if ctx.Device() {
kotlincFlags = append(kotlincFlags, "-no-jdk")
}
for _, plugin := range deps.kotlinPlugins {
kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
}
flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
if len(kotlincFlags) > 0 {
// optimization.
ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
flags.kotlincFlags += "$kotlincFlags"
}
// Collect common .kt files for AIDEGen
j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
if len(flags.processorPath) > 0 {
// Use kapt for annotation processing
kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
srcJars = append(srcJars, kaptSrcJar)
localImplementationJars = append(localImplementationJars, kaptResJar)
// Disable annotation processing in javac, it's already been handled by kapt
flags.processorPath = nil
flags.processors = nil
}
kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
j.kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
if ctx.Failed() {
return nil
}
kotlinJarPath, _ := j.repackageFlagsIfNecessary(ctx, kotlinJar, jarName, "kotlinc")
// Make javac rule depend on the kotlinc rule
flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
localImplementationJars = append(localImplementationJars, kotlinJarPath)
kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
}
j.compiledSrcJars = srcJars
transitiveStaticLibsHeaderJars := deps.transitiveStaticLibsHeaderJars
enableSharding := false
var localHeaderJars android.Paths
var shardingHeaderJars android.Paths
var repackagedHeaderJarFile android.Path
if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
enableSharding = true
// Formerly, there was a check here that prevented annotation processors
// from being used when sharding was enabled, as some annotation processors
// do not function correctly in sharded environments. It was removed to
// allow for the use of annotation processors that do function correctly
// with sharding enabled. See: b/77284273.
}
extraJars := slices.Clone(kotlinHeaderJars)
extraJars = append(extraJars, extraCombinedJars...)
var combinedHeaderJarFile android.Path
localHeaderJars, combinedHeaderJarFile = j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
shardingHeaderJars = localHeaderJars
var jarjared bool
j.headerJarFile, jarjared = j.jarjarIfNecessary(ctx, combinedHeaderJarFile, jarName, "turbine", false)
if jarjared {
// jarjar modifies transitive static dependencies, use the combined header jar and drop the transitive
// static libs header jars.
localHeaderJars = android.Paths{j.headerJarFile}
transitiveStaticLibsHeaderJars = nil
}
var repackaged bool
repackagedHeaderJarFile, repackaged = j.repackageFlagsIfNecessary(ctx, j.headerJarFile, jarName, "turbine")
if repackaged {
// repackage modifies transitive static dependencies, use the combined header jar and drop the transitive
// static libs header jars.
// TODO(b/356688296): this shouldn't export both the unmodified and repackaged header jars
localHeaderJars = android.Paths{j.headerJarFile, repackagedHeaderJarFile}
transitiveStaticLibsHeaderJars = nil
}
}
if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
hasErrorproneableFiles := false
for _, ext := range j.sourceExtensions {
if ext != ".proto" && ext != ".aidl" {
// Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
// compile, and it's not useful to have warnings on these generated sources.
hasErrorproneableFiles = true
break
}
}
var extraJarDeps android.Paths
if Bool(j.properties.Errorprone.Enabled) {
// If error-prone is enabled, enable errorprone flags on the regular
// build.
flags = enableErrorproneFlags(flags)
} else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
if ctx.Config().RunErrorProneInline() {
// On CI, we're not going to toggle back/forth between errorprone and non-errorprone
// builds, so it's faster if we don't compile the module twice and instead always
// compile the module with errorprone.
flags = enableErrorproneFlags(flags)
} else {
// Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
// a new jar file just for compiling with the errorprone compiler to.
// This is because we don't want to cause the java files to get completely
// rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
// We also don't want to run this if errorprone is enabled by default for
// this module, or else we could have duplicated errorprone messages.
errorproneFlags := enableErrorproneFlags(flags)
errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
"errorprone", "errorprone")
extraJarDeps = append(extraJarDeps, errorprone)
}
}
if enableSharding {
if len(shardingHeaderJars) > 0 {
flags.classpath = append(classpath(slices.Clone(shardingHeaderJars)), flags.classpath...)
}
shardSize := int(*(j.properties.Javac_shard_size))
var shardSrcs []android.Paths
if len(uniqueJavaFiles) > 0 {
shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
for idx, shardSrc := range shardSrcs {
classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
nil, flags, extraJarDeps)
classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac-"+strconv.Itoa(idx))
localImplementationJars = append(localImplementationJars, classes)
}
}
// Assume approximately 5 sources per srcjar.
// For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
// of 5.8 sources per srcjar, but a median of 1, a standard deviation of 10, and a max of 48 source files.
if len(srcJars) > 0 {
startIdx := len(shardSrcs)
shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
for idx, shardSrcJars := range shardSrcJarsList {
classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
nil, shardSrcJars, flags, extraJarDeps)
classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac-"+strconv.Itoa(startIdx+idx))
localImplementationJars = append(localImplementationJars, classes)
}
}
} else {
classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac")
localImplementationJars = append(localImplementationJars, classes)
}
if ctx.Failed() {
return nil
}
}
localImplementationJars = append(localImplementationJars, extraCombinedJars...)
j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
var includeSrcJar android.WritablePath
if Bool(j.properties.Include_srcs) {
includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
}
dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources.GetOrDefault(ctx, nil), j.properties.Exclude_java_resources)
fileArgs2, fileDeps2 := ResourceFilesToJarArgs(ctx, j.properties.Device_common_java_resources.GetOrDefault(ctx, nil), nil)
fileArgs3, fileDeps3 := ResourceFilesToJarArgs(ctx, j.properties.Device_first_java_resources.GetOrDefault(ctx, nil), nil)
fileArgs = slices.Concat(fileArgs, fileArgs2, fileArgs3)
fileDeps = slices.Concat(fileDeps, fileDeps2, fileDeps3)
extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
var resArgs []string
var resDeps android.Paths
resArgs = append(resArgs, dirArgs...)
resDeps = append(resDeps, dirDeps...)
resArgs = append(resArgs, fileArgs...)
resDeps = append(resDeps, fileDeps...)
resArgs = append(resArgs, extraArgs...)
resDeps = append(resDeps, extraDeps...)
var localResourceJars android.Paths
if len(resArgs) > 0 {
resourceJar := android.PathForModuleOut(ctx, "res", jarName)
TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
if ctx.Failed() {
return nil
}
localResourceJars = append(localResourceJars, resourceJar)
}
if Bool(j.properties.Include_srcs) {
localResourceJars = append(localResourceJars, includeSrcJar)
}
services := android.PathsForModuleSrc(ctx, j.properties.Services)
if len(services) > 0 {
servicesJar := android.PathForModuleOut(ctx, "services", jarName)
var zipargs []string
for _, file := range services {
serviceFile := file.String()
zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
}
rule := zip
args := map[string]string{
"jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
}
if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
rule = zipRE
args["implicits"] = strings.Join(services.Strings(), ",")
}
ctx.Build(pctx, android.BuildParams{
Rule: rule,
Output: servicesJar,
Implicits: services,
Args: args,
})
localResourceJars = append(localResourceJars, servicesJar)
}
completeStaticLibsResourceJars := depset.New(depset.PREORDER, localResourceJars, deps.transitiveStaticLibsResourceJars)
var combinedResourceJar android.Path
resourceJars := completeStaticLibsResourceJars.ToList()
if len(resourceJars) == 1 {
combinedResourceJar = resourceJars[0]
} else if len(resourceJars) > 0 {
combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
false, nil, nil)
combinedResourceJar = combinedJar
}
manifest := j.overrideManifest
if !manifest.Valid() && j.properties.Manifest != nil {
manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
}
// Combine the classes built from sources, any manifests, and any static libraries into
// classes.jar. If there is only one input jar this step will be skipped.
var outputFile android.Path
completeStaticLibsImplementationJars := depset.New(depset.PREORDER, localImplementationJars, deps.transitiveStaticLibsImplementationJars)
jars := completeStaticLibsImplementationJars.ToList()
jars = append(jars, extraDepCombinedJars...)
if len(jars) == 1 && !manifest.Valid() {
// Optimization: skip the combine step as there is nothing to do
// TODO(ccross): this leaves any module-info.class files, but those should only come from
// prebuilt dependencies until we support modules in the platform build, so there shouldn't be
// any if len(extraJars) == 0.
// moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
// from sdk_library. The TopLevelStubLibrary contains only one static lib,
// either with .from-source or .from-text suffix.
// outputFile should be agnostic to the build configuration,
// thus copy the single input static lib in order to prevent the static lib from being exposed
// to the copy rules.
if stub, _ := moduleStubLinkType(j); stub {
copiedJar := android.PathForModuleOut(ctx, "combined", jarName)
ctx.Build(pctx, android.BuildParams{
Rule: android.Cp,
Input: jars[0],
Output: copiedJar,
})
completeStaticLibsImplementationJars = depset.New(depset.PREORDER, android.Paths{copiedJar}, nil)
outputFile = copiedJar
} else {
outputFile = jars[0]
}
} else {
combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
false, nil, nil)
outputFile = combinedJar
}
// jarjar implementation jar if necessary
jarjarFile, jarjarred := j.jarjarIfNecessary(ctx, outputFile, jarName, "", true)
if jarjarred {
localImplementationJars = android.Paths{jarjarFile}
completeStaticLibsImplementationJars = depset.New(depset.PREORDER, localImplementationJars, nil)
}
outputFile = jarjarFile
// jarjar resource jar if necessary
if combinedResourceJar != nil {
resourceJarJarFile, jarjarred := j.jarjarIfNecessary(ctx, combinedResourceJar, jarName, "resource", false)
combinedResourceJar = resourceJarJarFile
if jarjarred {
localResourceJars = android.Paths{resourceJarJarFile}
completeStaticLibsResourceJars = depset.New(depset.PREORDER, localResourceJars, nil)
}
}
if ctx.Failed() {
return nil
}
if j.ravenizer.enabled {
ravenizerInput := outputFile
ravenizerOutput := android.PathForModuleOut(ctx, "ravenizer", "", jarName)
ravenizerArgs := ""
if proptools.Bool(j.properties.Ravenizer.Strip_mockito) {
ravenizerArgs = "--strip-mockito"
}
TransformRavenizer(ctx, ravenizerOutput, ravenizerInput, ravenizerArgs)
outputFile = ravenizerOutput
localImplementationJars = android.Paths{ravenizerOutput}
completeStaticLibsImplementationJars = depset.New(depset.PREORDER, localImplementationJars, nil)
if combinedResourceJar != nil {
ravenizerInput = combinedResourceJar
ravenizerOutput = android.PathForModuleOut(ctx, "ravenizer", "resources", jarName)
TransformRavenizer(ctx, ravenizerOutput, ravenizerInput, ravenizerArgs)
combinedResourceJar = ravenizerOutput
localResourceJars = android.Paths{ravenizerOutput}
completeStaticLibsResourceJars = depset.New(depset.PREORDER, localResourceJars, nil)
}
}
if j.shouldApiMapper() {
inputFile := outputFile
apiMapperFile := android.PathForModuleOut(ctx, "apimapper", jarName)
ctx.Build(pctx, android.BuildParams{
Rule: apimapper,
Description: "apimapper",
Input: inputFile,
Output: apiMapperFile,
})
outputFile = apiMapperFile
localImplementationJars = android.Paths{apiMapperFile}
completeStaticLibsImplementationJars = depset.New(depset.PREORDER, localImplementationJars, nil)
}
// Check package restrictions if necessary.
if len(j.properties.Permitted_packages) > 0 {
// Time stamp file created by the package check rule.
pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
// Create a rule to copy the output jar to another path and add a validate dependency that
// will check that the jar only contains the permitted packages. The new location will become
// the output file of this module.
inputFile := outputFile
packageCheckOutputFile := android.PathForModuleOut(ctx, "package-check", jarName)
ctx.Build(pctx, android.BuildParams{
Rule: android.Cp,
Input: inputFile,
Output: packageCheckOutputFile,
// Make sure that any dependency on the output file will cause ninja to run the package check
// rule.
Validation: pkgckFile,
})
outputFile = packageCheckOutputFile
localImplementationJars = android.Paths{packageCheckOutputFile}
completeStaticLibsImplementationJars = depset.New(depset.PREORDER, localImplementationJars, nil)
// Check packages and create a timestamp file when complete.
CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
if ctx.Failed() {
return nil
}
}
j.implementationJarFile = outputFile
if j.headerJarFile == nil {
// If this module couldn't generate a header jar (for example due to api generating annotation processors)
// then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
// so that javac on modules that depend on this module don't pick up annotation processors (which may be
// missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
j.headerJarFile = headerJarFile
if len(localImplementationJars) == 1 {
localHeaderJarFile := android.PathForModuleOut(ctx, "local-javac-header", jarName)
convertImplementationJarToHeaderJar(ctx, localImplementationJars[0], localHeaderJarFile)
localHeaderJars = append(localHeaderJars, localHeaderJarFile)
} else {
localHeaderJars = append(localHeaderJars, headerJarFile)
}
}
// enforce syntax check to jacoco filters for any build (http://b/183622051)
specs := j.jacocoModuleToZipCommand(ctx)
if ctx.Failed() {
return nil
}
completeStaticLibsImplementationJarsToCombine := completeStaticLibsImplementationJars
apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
// Enable dex compilation for the APEX variants, unless it is disabled explicitly
compileDex := Bool(j.dexProperties.Compile_dex) || Bool(j.properties.Installable)
if j.shouldInstrument(ctx) && (!ctx.Device() || compileDex) {
instrumentedOutputFile := j.instrument(ctx, flags, outputFile, jarName, specs)
completeStaticLibsImplementationJarsToCombine = depset.New(depset.PREORDER, android.Paths{instrumentedOutputFile}, nil)
outputFile = instrumentedOutputFile
}
// merge implementation jar with resources if necessary
var implementationAndResourcesJarsToCombine android.Paths
combinedResourceJars := completeStaticLibsResourceJars.ToList()
if len(combinedResourceJars) > 0 {
implementationAndResourcesJarsToCombine = slices.Concat(combinedResourceJars,
completeStaticLibsImplementationJarsToCombine.ToList(), extraDepCombinedJars)
}
if len(implementationAndResourcesJarsToCombine) > 0 {
combinedJar := android.PathForModuleOut(ctx, "withres", jarName)
TransformJarsToJar(ctx, combinedJar, "for resources", implementationAndResourcesJarsToCombine, manifest,
false, nil, nil)
outputFile = combinedJar
}
j.implementationAndResourcesJar = outputFile
if ctx.Device() && compileDex {
if j.hasCode(ctx) {
if j.shouldInstrumentStatic(ctx) {
j.dexer.extraProguardFlagsFiles = append(j.dexer.extraProguardFlagsFiles,
android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
}
// Dex compilation
var dexOutputFile android.Path
params := &compileDexParams{
flags: flags,
sdkVersion: j.SdkVersion(ctx),
minSdkVersion: j.MinSdkVersion(ctx),
classesJar: outputFile,
jarName: jarName,
}
if j.GetProfileGuided(ctx) && j.optimizeOrObfuscateEnabled(ctx) && !j.EnableProfileRewriting(ctx) {
ctx.PropertyErrorf("enable_profile_rewriting",
"Enable_profile_rewriting must be true when profile_guided dexpreopt and R8 optimization/obfuscation is turned on. The attached profile should be sourced from an unoptimized/unobfuscated APK.",
)
}
if j.EnableProfileRewriting(ctx) {
profile := j.GetProfile(ctx)
if profile == "" || !j.GetProfileGuided(ctx) {
ctx.PropertyErrorf("enable_profile_rewriting", "Profile and Profile_guided must be set when enable_profile_rewriting is true")
}
params.artProfileInput = &profile
}
dexOutputFile, dexArtProfileOutput := j.dexer.compileDex(ctx, params)
if ctx.Failed() {
return nil
}
// If r8/d8 provides a profile that matches the optimized dex, use that for dexpreopt.
if dexArtProfileOutput != nil {
j.dexpreopter.SetRewrittenProfile(dexArtProfileOutput)
}
// merge dex jar with resources if necessary
if len(combinedResourceJars) > 0 {
dexAndResourceJarsToCombine := append(android.Paths{dexOutputFile}, combinedResourceJars...)
combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName)
TransformJarsToJar(ctx, combinedJar, "for dex resources", dexAndResourceJarsToCombine, android.OptionalPath{},
false, nil, nil)
if *j.dexProperties.Uncompress_dex {
combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName)
TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
dexOutputFile = combinedAlignedJar
} else {
dexOutputFile = combinedJar
}
}
// Initialize the hiddenapi structure.
j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
// Encode hidden API flags in dex file, if needed.
dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
// Dexpreopting
libName := android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName())
if j.SdkLibraryName() != nil && strings.HasSuffix(ctx.ModuleName(), ".impl") {
libName = strings.TrimSuffix(libName, ".impl")
}
j.dexpreopt(ctx, libName, dexOutputFile)
outputFile = dexOutputFile
ctx.CheckbuildFile(dexOutputFile)
} else {
// There is no code to compile into a dex jar, make sure the resources are propagated
// to the APK if this is an app.
j.dexJarFile = makeDexJarPathFromPath(combinedResourceJar)
}
if ctx.Failed() {
return nil
}
}
if ctx.Device() {
lintSDKVersion := func(apiLevel android.ApiLevel) android.ApiLevel {
if !apiLevel.IsPreview() {
return apiLevel
} else {
return ctx.Config().DefaultAppTargetSdk(ctx)
}
}
j.linter.name = ctx.ModuleName()
j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
j.linter.classes = j.implementationJarFile
j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
j.linter.javaLanguageLevel = flags.javaVersion.String()
j.linter.kotlinLanguageLevel = "1.3"
j.linter.compile_data = android.PathsForModuleSrc(ctx, j.properties.Compile_data)
if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
j.linter.buildModuleReportZip = true
}
j.linter.lint(ctx)
}
j.collectTransitiveSrcFiles(ctx, srcFiles)
if len(localImplementationJars) > 0 || len(localResourceJars) > 0 || len(localHeaderJars) > 0 {
ctx.CheckbuildFile(localImplementationJars...)
ctx.CheckbuildFile(localResourceJars...)
ctx.CheckbuildFile(localHeaderJars...)
} else {
// There are no local sources or resources in this module, so there is nothing to checkbuild.
ctx.UncheckedModule()
}
// Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
j.outputFile = outputFile.WithoutRel()
return &JavaInfo{
HeaderJars: android.PathsIfNonNil(j.headerJarFile),
RepackagedHeaderJars: android.PathsIfNonNil(repackagedHeaderJarFile),
LocalHeaderJars: localHeaderJars,
TransitiveStaticLibsHeaderJars: depset.New(depset.PREORDER, localHeaderJars, transitiveStaticLibsHeaderJars),
TransitiveStaticLibsImplementationJars: completeStaticLibsImplementationJars,
TransitiveStaticLibsResourceJars: completeStaticLibsResourceJars,
TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
ResourceJars: android.PathsIfNonNil(combinedResourceJar),
AidlIncludeDirs: j.exportAidlIncludeDirs,
SrcJarArgs: j.srcJarArgs,
SrcJarDeps: j.srcJarDeps,
TransitiveSrcFiles: j.transitiveSrcFiles,
ExportedPlugins: j.exportedPluginJars,
ExportedPluginClasses: j.exportedPluginClasses,
ExportedPluginDisableTurbine: j.exportedDisableTurbine,
JacocoReportClassesFile: j.jacocoReportClassesFile,
StubsLinkType: j.stubsLinkType,
AconfigIntermediateCacheOutputPaths: j.aconfigCacheFiles,
SdkVersion: j.SdkVersion(ctx),
OutputFile: j.outputFile,
}
}
func (j *Module) useCompose(ctx android.BaseModuleContext) bool {
return android.InList("androidx.compose.runtime_runtime", j.staticLibs(ctx))
}
func collectDepProguardSpecInfo(ctx android.ModuleContext) (transitiveProguardFlags, transitiveUnconditionalExportedFlags []depset.DepSet[android.Path]) {
ctx.VisitDirectDepsProxy(func(m android.ModuleProxy) {
depProguardInfo, _ := android.OtherModuleProvider(ctx, m, ProguardSpecInfoProvider)
depTag := ctx.OtherModuleDependencyTag(m)
transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
if depTag == staticLibTag {
transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
}
})
return transitiveProguardFlags, transitiveUnconditionalExportedFlags
}
func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
transitiveProguardFlags, transitiveUnconditionalExportedFlags := collectDepProguardSpecInfo(ctx)
directUnconditionalExportedFlags := android.Paths{}
proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
if exportUnconditionally {
// if we explicitly export, then our unconditional exports are the same as our transitive flags
transitiveUnconditionalExportedFlags = transitiveProguardFlags
directUnconditionalExportedFlags = proguardFlagsForThisModule
}
return ProguardSpecInfo{
Export_proguard_flags_files: exportUnconditionally,
ProguardFlagsFiles: depset.New[android.Path](
depset.POSTORDER,
proguardFlagsForThisModule,
transitiveProguardFlags,
),
UnconditionallyExportedProguardFlags: depset.New[android.Path](
depset.POSTORDER,
directUnconditionalExportedFlags,
transitiveUnconditionalExportedFlags,
),
}
}
// Returns a copy of the supplied flags, but with all the errorprone-related
// fields copied to the regular build's fields.
func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
if len(flags.errorProneExtraJavacFlags) > 0 {
if len(flags.javacFlags) > 0 {
flags.javacFlags += " " + flags.errorProneExtraJavacFlags
} else {
flags.javacFlags = flags.errorProneExtraJavacFlags
}
}
return flags
}
func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.Path {
kzipName := pathtools.ReplaceExtension(jarName, "kzip")
annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
if idx >= 0 {
kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
jarName += strconv.Itoa(idx)
}
classes := android.PathForModuleOut(ctx, "javac", jarName)
TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
if ctx.Config().EmitXrefRules() && ctx.Module() == ctx.PrimaryModule() {
extractionFile := android.PathForModuleOut(ctx, kzipName)
emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
j.kytheFiles = append(j.kytheFiles, extractionFile)
}
if len(flags.processorPath) > 0 {
j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
}
return classes
}
// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
// since some of these flags may be used internally.
func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
for _, flag := range flags {
flag = strings.TrimSpace(flag)
if !strings.HasPrefix(flag, "-") {
ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
} else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
ctx.PropertyErrorf("kotlincflags",
"Bad flag: `%s`, only use internal compiler for consistency.", flag)
} else if slices.ContainsFunc(config.KotlincIllegalFlags, func(f string) bool {
return strings.HasPrefix(flag, f)
}) {
ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
} else if flag == "-include-runtime" {
ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
} else {
args := strings.Split(flag, " ")
if args[0] == "-kotlin-home" {
ctx.PropertyErrorf("kotlincflags",
"Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
}
}
}
}
func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
deps deps, flags javaBuilderFlags, jarName string,
extraJars android.Paths) (localHeaderJars android.Paths, combinedHeaderJar android.Path) {
if len(srcFiles) > 0 || len(srcJars) > 0 {
// Compile java sources into turbine.jar.
turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
localHeaderJars = append(localHeaderJars, turbineJar)
}
localHeaderJars = append(localHeaderJars, extraJars...)
// Combine any static header libraries into classes-header.jar. If there is only
// one input jar this step will be skipped.
depSet := depset.New(depset.PREORDER, localHeaderJars, deps.transitiveStaticLibsHeaderJars)
jars := depSet.ToList()
// we cannot skip the combine step for now if there is only one jar
// since we have to strip META-INF/TRANSITIVE dir from turbine.jar
combinedHeaderJarOutputPath := android.PathForModuleOut(ctx, "turbine-combined", jarName)
TransformJarsToJar(ctx, combinedHeaderJarOutputPath, "for turbine", jars, android.OptionalPath{},
false, nil, []string{"META-INF/TRANSITIVE"})
return localHeaderJars, combinedHeaderJarOutputPath
}
func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
classesJar android.Path, jarName string, specs string) android.Path {
jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName)
jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
j.jacocoReportClassesFile = jacocoReportClassesFile
return instrumentedJar
}
type providesTransitiveHeaderJarsForR8 struct {
// set of header jars for all transitive libs deps
transitiveLibsHeaderJarsForR8 depset.DepSet[android.Path]
// set of header jars for all transitive static libs deps
transitiveStaticLibsHeaderJarsForR8 depset.DepSet[android.Path]
}
// collectTransitiveHeaderJarsForR8 visits direct dependencies and collects all transitive libs and static_libs
// header jars. The semantics of the collected jars are odd (it collects combined jars that contain the static
// libs, but also the static libs, and it collects transitive libs dependencies of static_libs), so these
// are only used to expand the --lib arguments to R8.
func (j *providesTransitiveHeaderJarsForR8) collectTransitiveHeaderJarsForR8(ctx android.ModuleContext) {
directLibs := android.Paths{}
directStaticLibs := android.Paths{}
transitiveLibs := []depset.DepSet[android.Path]{}
transitiveStaticLibs := []depset.DepSet[android.Path]{}
ctx.VisitDirectDepsProxy(func(module android.ModuleProxy) {
// don't add deps of the prebuilt version of the same library
if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
return
}
if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
tag := ctx.OtherModuleDependencyTag(module)
_, isUsesLibDep := tag.(usesLibraryDependencyTag)
if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
directLibs = append(directLibs, dep.HeaderJars...)
} else if tag == staticLibTag {
directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
} else {
// Don't propagate transitive libs for other kinds of dependencies.
return
}
transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJarsForR8)
transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJarsForR8)
}
})
j.transitiveLibsHeaderJarsForR8 = depset.New(depset.POSTORDER, directLibs, transitiveLibs)
j.transitiveStaticLibsHeaderJarsForR8 = depset.New(depset.POSTORDER, directStaticLibs, transitiveStaticLibs)
}
func (j *Module) HeaderJars() android.Paths {
if j.headerJarFile == nil {
return nil
}
return android.Paths{j.headerJarFile}
}
func (j *Module) ImplementationJars() android.Paths {
if j.implementationJarFile == nil {
return nil
}
return android.Paths{j.implementationJarFile}
}
func (j *Module) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
return j.dexJarFile
}
func (j *Module) DexJarInstallPath() android.Path {
return j.installFile
}
func (j *Module) ImplementationAndResourcesJars() android.Paths {
if j.implementationAndResourcesJar == nil {
return nil
}
return android.Paths{j.implementationAndResourcesJar}
}
func (j *Module) AidlIncludeDirs() android.Paths {
// exportAidlIncludeDirs is type android.Paths already
return j.exportAidlIncludeDirs
}
func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
return j.classLoaderContexts
}
// Collect information for opening IDE project files in java/jdeps.go.
func (j *Module) IDEInfo(ctx android.BaseModuleContext, dpInfo *android.IdeInfo) {
if j.expandJarjarRules != nil {
dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
}
if j.headerJarFile != nil {
// Add the header jar so that the rdeps can be resolved to the repackaged classes.
dpInfo.Jars = append(dpInfo.Jars, j.headerJarFile.String())
}
dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
dpInfo.Static_libs = append(dpInfo.Static_libs, j.staticLibs(ctx)...)
dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
}
func (j *Module) CompilerDeps() []string {
return j.compileDepNames
}
func (j *Module) hasCode(ctx android.ModuleContext) bool {
srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
return len(srcFiles) > 0 || len(ctx.GetDirectDepsProxyWithTag(staticLibTag)) > 0
}
// Implements android.ApexModule
func (m *Module) GetDepInSameApexChecker() android.DepInSameApexChecker {
return JavaDepInSameApexChecker{}
}
type JavaDepInSameApexChecker struct {
android.BaseDepInSameApexChecker
}
func (m JavaDepInSameApexChecker) OutgoingDepIsInSameApex(tag blueprint.DependencyTag) bool {
return depIsInSameApex(tag)
}
// Implements android.ApexModule
func (j *Module) MinSdkVersionSupported(ctx android.BaseModuleContext) android.ApiLevel {
sdkVersionSpec := j.SdkVersion(ctx)
minSdkVersion := j.MinSdkVersion(ctx)
// If the module is compiling against core (via sdk_version), skip comparison check.
if sdkVersionSpec.Kind == android.SdkCore {
return android.MinApiLevel
}
return minSdkVersion
}
func (j *Module) Stem() string {
if j.stem == "" {
panic("Stem() called before stem property was set")
}
return j.stem
}
func (j *Module) JacocoReportClassesFile() android.Path {
return j.jacocoReportClassesFile
}
func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
var fromDeps []depset.DepSet[android.Path]
ctx.VisitDirectDepsProxy(func(module android.ModuleProxy) {
tag := ctx.OtherModuleDependencyTag(module)
if tag == staticLibTag {
if depInfo, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
}
}
})
j.transitiveSrcFiles = depset.New(depset.POSTORDER, mine, fromDeps)
}
func (j *Module) IsInstallable() bool {
return Bool(j.properties.Installable)
}
type sdkLinkType int
const (
// TODO(jiyong) rename these for better readability. Make the allowed
// and disallowed link types explicit
// order is important here. See rank()
javaCore sdkLinkType = iota
javaSdk
javaSystem
javaModule
javaSystemServer
javaPlatform
)
func (lt sdkLinkType) String() string {
switch lt {
case javaCore:
return "core Java API"
case javaSdk:
return "Android API"
case javaSystem:
return "system API"
case javaModule:
return "module API"
case javaSystemServer:
return "system server API"
case javaPlatform:
return "private API"
default:
panic(fmt.Errorf("unrecognized linktype: %d", lt))
}
}
// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
// can't statically depend on modules that use Platform API.
func (lt sdkLinkType) rank() int {
return int(lt)
}
type moduleWithSdkDep interface {
android.Module
getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
}
func sdkLinkTypeFromSdkKind(k android.SdkKind) sdkLinkType {
switch k {
case android.SdkCore:
return javaCore
case android.SdkSystem:
return javaSystem
case android.SdkPublic:
return javaSdk
case android.SdkModule:
return javaModule
case android.SdkSystemServer:
return javaSystemServer
case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
return javaPlatform
default:
return javaSdk
}
}
func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
switch name {
case android.SdkCore.DefaultJavaLibraryName(),
"legacy.core.platform.api.stubs",
"stable.core.platform.api.stubs",
"stub-annotations", "private-stub-annotations-jar",
"core-lambda-stubs",
"core-generated-annotation-stubs",
// jacocoagent only uses core APIs, but has to specify a non-core sdk_version so it can use
// a prebuilt SDK to avoid circular dependencies when it statically included in the bootclasspath.
"jacocoagent":
return javaCore, true
case android.SdkPublic.DefaultJavaLibraryName():
return javaSdk, true
case android.SdkSystem.DefaultJavaLibraryName():
return javaSystem, true
case android.SdkModule.DefaultJavaLibraryName():
return javaModule, true
case android.SdkSystemServer.DefaultJavaLibraryName():
return javaSystemServer, true
case android.SdkTest.DefaultJavaLibraryName():
return javaSystem, true
}
if stub, linkType := moduleStubLinkType(m); stub {
return linkType, true
}
ver := m.SdkVersion(ctx)
if !ver.Valid() {
panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
}
return sdkLinkTypeFromSdkKind(ver.Kind), false
}
// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
// this module's. See the comment on rank() for details and an example.
func (j *Module) checkSdkLinkType(
ctx android.ModuleContext, dep android.ModuleProxy) {
if ctx.Host() {
return
}
myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
if stubs {
return
}
info, ok := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
if !ok || info.ModuleWithSdkDepInfo == nil {
panic(fmt.Errorf("dependency doesn't have ModuleWithSdkDepInfo: %v", dep))
}
depLinkType := info.ModuleWithSdkDepInfo.SdkLinkType
if myLinkType.rank() < depLinkType.rank() {
ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
"In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
"property of the source or target module so that target module is built "+
"with the same or smaller API set when compared to the source.",
myLinkType, ctx.OtherModuleName(dep), depLinkType)
}
}
func (j *Module) collectDeps(ctx android.ModuleContext) deps {
var deps deps
sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
j.collectTransitiveHeaderJarsForR8(ctx)
var transitiveBootClasspathHeaderJars []depset.DepSet[android.Path]
var transitiveClasspathHeaderJars []depset.DepSet[android.Path]
var transitiveJava9ClasspathHeaderJars []depset.DepSet[android.Path]
var transitiveStaticJarsHeaderLibs []depset.DepSet[android.Path]
var transitiveStaticJarsImplementationLibs []depset.DepSet[android.Path]
var transitiveStaticJarsResourceLibs []depset.DepSet[android.Path]
ctx.VisitDirectDepsProxy(func(module android.ModuleProxy) {
otherName := ctx.OtherModuleName(module)
tag := ctx.OtherModuleDependencyTag(module)
if IsJniDepTag(tag) {
// Handled by AndroidApp.collectAppDeps
return
}
if tag == certificateTag {
// Handled by AndroidApp.collectAppDeps
return
}
if sdkInfo, ok := android.OtherModuleProvider(ctx, module, SdkLibraryInfoProvider); ok {
switch tag {
case sdkLibTag, libTag, staticLibTag:
generatingLibsString := android.PrettyConcat(
getGeneratingLibs(ctx, j.SdkVersion(ctx), module.Name(), sdkInfo), true, "or")
ctx.ModuleErrorf("cannot depend directly on java_sdk_library %q; try depending on %s instead", module.Name(), generatingLibsString)
}
} else if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
if sdkLinkType != javaPlatform {
if syspropDep, ok := android.OtherModuleProvider(ctx, module, SyspropPublicStubInfoProvider); ok {
// dep is a sysprop implementation library, but this module is not linking against
// the platform, so it gets the sysprop public stubs library instead. Replace
// dep with the JavaInfo from the SyspropPublicStubInfoProvider.
dep = syspropDep.JavaInfo
}
}
switch tag {
case bootClasspathTag:
deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
case sdkLibTag, libTag, instrumentationForTag:
if _, ok := android.OtherModuleProvider(ctx, module, JavaPluginInfoProvider); ok {
ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
}
deps.classpath = append(deps.classpath, dep.HeaderJars...)
deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
if len(dep.RepackagedHeaderJars) == 1 && !slices.Contains(dep.HeaderJars, dep.RepackagedHeaderJars[0]) {
deps.classpath = append(deps.classpath, dep.RepackagedHeaderJars...)
deps.dexClasspath = append(deps.dexClasspath, dep.RepackagedHeaderJars...)
}
deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
case java9LibTag:
deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
transitiveJava9ClasspathHeaderJars = append(transitiveJava9ClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
case staticLibTag:
if _, ok := android.OtherModuleProvider(ctx, module, JavaPluginInfoProvider); ok {
ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
}
deps.classpath = append(deps.classpath, dep.HeaderJars...)
deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
// Turbine doesn't run annotation processors, so any module that uses an
// annotation processor that generates API is incompatible with the turbine
// optimization.
deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
deps.aconfigProtoFiles = append(deps.aconfigProtoFiles, dep.AconfigIntermediateCacheOutputPaths...)
transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
transitiveStaticJarsHeaderLibs = append(transitiveStaticJarsHeaderLibs, dep.TransitiveStaticLibsHeaderJars)
transitiveStaticJarsImplementationLibs = append(transitiveStaticJarsImplementationLibs, dep.TransitiveStaticLibsImplementationJars)
transitiveStaticJarsResourceLibs = append(transitiveStaticJarsResourceLibs, dep.TransitiveStaticLibsResourceJars)
case pluginTag:
if plugin, ok := android.OtherModuleProvider(ctx, module, JavaPluginInfoProvider); ok {
if plugin.ProcessorClass != nil {
addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.ProcessorClass)
} else {
addPlugins(&deps, dep.ImplementationAndResourcesJars)
}
// Turbine doesn't run annotation processors, so any module that uses an
// annotation processor that generates API is incompatible with the turbine
// optimization.
deps.disableTurbine = deps.disableTurbine || plugin.GeneratesApi
} else {
ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
}
case errorpronePluginTag:
if _, ok := android.OtherModuleProvider(ctx, module, JavaPluginInfoProvider); ok {
deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
} else {
ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
}
case exportedPluginTag:
if plugin, ok := android.OtherModuleProvider(ctx, module, JavaPluginInfoProvider); ok {
j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
if plugin.ProcessorClass != nil {
j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.ProcessorClass)
}
// Turbine doesn't run annotation processors, so any module that uses an
// annotation processor that generates API is incompatible with the turbine
// optimization.
j.exportedDisableTurbine = plugin.GeneratesApi
} else {
ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
}
case kotlinPluginTag:
if _, ok := android.OtherModuleProvider(ctx, module, KotlinPluginInfoProvider); ok {
deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
} else {
ctx.PropertyErrorf("kotlin_plugins", "%q is not a kotlin_plugin module", otherName)
}
case syspropPublicStubDepTag:
// This is a sysprop implementation library, forward the JavaInfoProvider from
// the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
android.SetProvider(ctx, SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
JavaInfo: dep,
})
}
} else if dep, ok := android.OtherModuleProvider(ctx, module, android.SourceFilesInfoProvider); ok {
switch tag {
case sdkLibTag, libTag:
checkProducesJars(ctx, dep, module)
deps.classpath = append(deps.classpath, dep.Srcs...)
deps.dexClasspath = append(deps.classpath, dep.Srcs...)
transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars,
depset.New(depset.PREORDER, dep.Srcs, nil))
case staticLibTag:
checkProducesJars(ctx, dep, module)
deps.classpath = append(deps.classpath, dep.Srcs...)
deps.staticJars = append(deps.staticJars, dep.Srcs...)
deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs...)
depHeaderJars := depset.New(depset.PREORDER, dep.Srcs, nil)
transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, depHeaderJars)
transitiveStaticJarsHeaderLibs = append(transitiveStaticJarsHeaderLibs, depHeaderJars)
transitiveStaticJarsImplementationLibs = append(transitiveStaticJarsImplementationLibs, depHeaderJars)
}
} else if dep, ok := android.OtherModuleProvider(ctx, module, android.CodegenInfoProvider); ok {
switch tag {
case staticLibTag:
deps.aconfigProtoFiles = append(deps.aconfigProtoFiles, dep.IntermediateCacheOutputPaths...)
}
} else {
switch tag {
case bootClasspathTag:
// If a system modules dependency has been added to the bootclasspath
// then add its libs to the bootclasspath.
if sm, ok := android.OtherModuleProvider(ctx, module, SystemModulesProvider); ok {
deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars...)
transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars,
sm.TransitiveStaticLibsHeaderJars)
} else {
ctx.PropertyErrorf("boot classpath dependency %q does not provide SystemModulesProvider",
ctx.OtherModuleName(module))
}
case systemModulesTag:
if deps.systemModules != nil {
panic("Found two system module dependencies")
}
if sm, ok := android.OtherModuleProvider(ctx, module, SystemModulesProvider); ok {
deps.systemModules = &systemModules{sm.OutputDir, sm.OutputDirDeps}
} else {
ctx.PropertyErrorf("system modules dependency %q does not provide SystemModulesProvider",
ctx.OtherModuleName(module))
}
case instrumentationForTag:
ctx.PropertyErrorf("instrumentation_for", "dependency %q of type %q does not provide JavaInfo so is unsuitable for use with this property", ctx.OtherModuleName(module), ctx.OtherModuleType(module))
}
}
if android.InList(tag, compileDependencyTags) {
// Add the dependency name to compileDepNames so that it can be recorded in module_bp_java_deps.json
j.compileDepNames = append(j.compileDepNames, otherName)
}
addCLCFromDep(ctx, module, j.classLoaderContexts)
addMissingOptionalUsesLibsFromDep(ctx, module, &j.usesLibrary)
})
deps.transitiveStaticLibsHeaderJars = transitiveStaticJarsHeaderLibs
deps.transitiveStaticLibsImplementationJars = transitiveStaticJarsImplementationLibs
deps.transitiveStaticLibsResourceJars = transitiveStaticJarsResourceLibs
depSet := depset.New(depset.PREORDER, nil, transitiveClasspathHeaderJars)
deps.classpath = depSet.ToList()
depSet = depset.New(depset.PREORDER, nil, transitiveBootClasspathHeaderJars)
deps.bootClasspath = depSet.ToList()
depSet = depset.New(depset.PREORDER, nil, transitiveJava9ClasspathHeaderJars)
deps.java9Classpath = depSet.ToList()
if ctx.Device() {
sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
if sdkDep.invalidVersion {
ctx.AddMissingDependencies(sdkDep.bootclasspath)
ctx.AddMissingDependencies(sdkDep.java9Classpath)
} else if sdkDep.useFiles {
// sdkDep.jar is actually equivalent to turbine header.jar.
deps.classpath = append(slices.Clone(classpath(sdkDep.jars)), deps.classpath...)
deps.dexClasspath = append(slices.Clone(classpath(sdkDep.jars)), deps.dexClasspath...)
deps.aidlPreprocess = sdkDep.aidl
// Add the sdk module dependency to `compileDepNames`.
// This ensures that the dependency is reported in `module_bp_java_deps.json`
// TODO (b/358608607): Move this to decodeSdkDep
sdkSpec := android.SdkContext(j).SdkVersion(ctx)
j.compileDepNames = append(j.compileDepNames, fmt.Sprintf("sdk_%s_%s_android", sdkSpec.Kind.String(), sdkSpec.ApiLevel.String()))
} else {
deps.aidlPreprocess = sdkDep.aidl
}
}
return deps
}
// Provider for jarjar renaming rules.
//
// Modules can set their jarjar renaming rules with addJarJarRenameRule, and those renamings will be
// passed to all rdeps. The typical way that these renamings will NOT be inherited is when a module
// links against stubs -- these are not passed through stubs. The classes will remain unrenamed on
// classes until a module with jarjar_prefix is reached, and all as yet unrenamed classes will then
// be renamed from that module.
// TODO: Add another property to suppress the forwarding of
type DependencyUse int
const (
RenameUseInvalid DependencyUse = iota
RenameUseInclude
RenameUseExclude
)
type JarJarProviderData struct {
// Mapping of class names: original --> renamed. If the value is "", the class will be
// renamed by the next rdep that has the jarjar_prefix attribute (or this module if it has
// attribute). Rdeps of that module will inherit the renaming.
Rename map[string]string
}
func (this JarJarProviderData) GetDebugString() string {
result := ""
for _, k := range android.SortedKeys(this.Rename) {
v := this.Rename[k]
if strings.Contains(k, "android.companion.virtual.flags.FakeFeatureFlagsImpl") {
result += k + "-->" + v + ";"
}
}
return result
}
var JarJarProvider = blueprint.NewProvider[JarJarProviderData]()
var overridableJarJarPrefix = "com.android.internal.hidden_from_bootclasspath"
func init() {
android.SetJarJarPrefixHandler(mergeJarJarPrefixes)
gob.Register(BaseJarJarProviderData{})
}
// BaseJarJarProviderData contains information that will propagate across dependencies regardless of
// whether they are java modules or not.
type BaseJarJarProviderData struct {
JarJarProviderData JarJarProviderData
}
func (this BaseJarJarProviderData) GetDebugString() string {
return this.JarJarProviderData.GetDebugString()
}
var BaseJarJarProvider = blueprint.NewProvider[BaseJarJarProviderData]()
// mergeJarJarPrefixes is called immediately before module.GenerateAndroidBuildActions is called.
// Since there won't be a JarJarProvider, we create the BaseJarJarProvider if any of our deps have
// either JarJarProvider or BaseJarJarProvider.
func mergeJarJarPrefixes(ctx android.ModuleContext) {
mod := ctx.Module()
// Explicitly avoid propagating into some module types.
switch reflect.TypeOf(mod).String() {
case "*java.Droidstubs":
return
}
jarJarData := collectDirectDepsProviders(ctx)
if jarJarData != nil {
providerData := BaseJarJarProviderData{
JarJarProviderData: *jarJarData,
}
android.SetProvider(ctx, BaseJarJarProvider, providerData)
}
}
// Add a jarjar renaming rule to this module, to be inherited to all dependent modules.
func (module *Module) addJarJarRenameRule(original string, renamed string) {
if module.jarjarRenameRules == nil {
module.jarjarRenameRules = make(map[string]string)
}
module.jarjarRenameRules[original] = renamed
}
func collectDirectDepsProviders(ctx android.ModuleContext) (result *JarJarProviderData) {
// Gather repackage information from deps
// If the dep jas a JarJarProvider, it is used. Otherwise, any BaseJarJarProvider is used.
module := ctx.Module()
moduleName := module.Name()
ctx.VisitDirectDepsProxy(func(m android.ModuleProxy) {
tag := ctx.OtherModuleDependencyTag(m)
// This logic mirrors that in (*Module).collectDeps above. There are several places
// where we explicitly return RenameUseExclude, even though it is the default, to
// indicate that it has been verified to be the case.
//
// Note well: there are probably cases that are getting to the unconditional return
// and are therefore wrong.
shouldIncludeRenames := func() DependencyUse {
if moduleName == m.Name() {
return RenameUseInclude // If we have the same module name, include the renames.
}
if sc, ok := module.(android.SdkContext); ok {
if ctx.Device() {
sdkDep := decodeSdkDep(ctx, sc)
if !sdkDep.invalidVersion && sdkDep.useFiles {
return RenameUseExclude
}
}
}
if IsJniDepTag(tag) || tag == certificateTag || tag == proguardRaiseTag {
return RenameUseExclude
}
if _, ok := android.OtherModuleProvider(ctx, m, SdkLibraryInfoProvider); ok {
switch tag {
case sdkLibTag, libTag:
return RenameUseExclude // matches collectDeps()
}
return RenameUseInvalid // dep is not used in collectDeps()
} else if ji, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
switch ji.StubsLinkType {
case Stubs:
return RenameUseExclude
case Implementation:
return RenameUseInclude
default:
//fmt.Printf("collectDirectDepsProviders: %v -> %v StubsLinkType unknown\n", module, m)
// Fall through to the heuristic logic.
}
if _, ok := android.OtherModuleProvider(ctx, m, android.CodegenInfoProvider); ok {
// Probably a java_aconfig_library module.
return RenameUseInclude
}
switch tag {
case bootClasspathTag:
return RenameUseExclude
case sdkLibTag, libTag, instrumentationForTag:
return RenameUseInclude
case java9LibTag:
return RenameUseExclude
case staticLibTag:
return RenameUseInclude
case pluginTag:
return RenameUseInclude
case errorpronePluginTag:
return RenameUseInclude
case exportedPluginTag:
return RenameUseInclude
case kotlinPluginTag:
return RenameUseInclude
default:
return RenameUseExclude
}
} else if _, ok := android.OtherModuleProvider(ctx, m, android.SourceFilesInfoProvider); ok {
switch tag {
case sdkLibTag, libTag, staticLibTag:
return RenameUseInclude
default:
return RenameUseExclude
}
} else if _, ok := android.OtherModuleProvider(ctx, m, android.CodegenInfoProvider); ok {
return RenameUseInclude
} else {
switch tag {
case bootClasspathTag:
return RenameUseExclude
case systemModulesTag:
return RenameUseInclude
}
}
// If we got here, choose the safer option, which may lead to a build failure, rather
// than runtime failures on the device.
return RenameUseExclude
}
if result == nil {
result = &JarJarProviderData{
Rename: make(map[string]string),
}
}
how := shouldIncludeRenames()
if how != RenameUseInclude {
// Nothing to merge.
return
}
merge := func(theirs *JarJarProviderData) {
for orig, renamed := range theirs.Rename {
if preexisting, exists := (*result).Rename[orig]; !exists || preexisting == "" {
result.Rename[orig] = renamed
} else if preexisting != "" && renamed != "" && preexisting != renamed {
if strings.HasPrefix(preexisting, overridableJarJarPrefix) {
result.Rename[orig] = renamed
} else if !strings.HasPrefix(renamed, overridableJarJarPrefix) {
ctx.ModuleErrorf("1. Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting, ctx.ModuleName(), m.Name())
continue
}
}
}
}
if theirs, ok := android.OtherModuleProvider(ctx, m, JarJarProvider); ok {
merge(&theirs)
} else if theirs, ok := android.OtherModuleProvider(ctx, m, BaseJarJarProvider); ok {
// TODO: if every java.Module should have a JarJarProvider, and we find only the
// BaseJarJarProvider, then there is a bug. Consider seeing if m can be cast
// to java.Module.
merge(&theirs.JarJarProviderData)
}
})
return
}
func (this Module) GetDebugString() string {
return "sdk_version=" + proptools.String(this.deviceProperties.Sdk_version)
}
// Merge the jarjar rules we inherit from our dependencies, any that have been added directly to
// us, and if it's been set, apply the jarjar_prefix property to rename them.
func (module *Module) collectJarJarRules(ctx android.ModuleContext) *JarJarProviderData {
// Gather repackage information from deps
result := collectDirectDepsProviders(ctx)
add := func(orig string, renamed string) {
if result == nil {
result = &JarJarProviderData{
Rename: make(map[string]string),
}
}
if renamed != "" {
if preexisting, exists := (*result).Rename[orig]; exists && preexisting != renamed {
ctx.ModuleErrorf("Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting)
return
}
}
(*result).Rename[orig] = renamed
}
// Update that with entries we've stored for ourself
for orig, renamed := range module.jarjarRenameRules {
add(orig, renamed)
}
// Update that with entries given in the jarjar_rename property.
for _, orig := range module.properties.Jarjar_rename {
add(orig, "")
}
// If there are no renamings, then jarjar_prefix does nothing, so skip the extra work.
if result == nil {
return nil
}
// If they've given us a jarjar_prefix property, then we will use that to rename any classes
// that have not yet been renamed.
prefix := proptools.String(module.properties.Jarjar_prefix)
if prefix != "" {
if prefix[0] == '.' {
ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not start with '.'")
return nil
}
if prefix[len(prefix)-1] == '.' {
ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not end with '.'")
return nil
}
var updated map[string]string
for orig, renamed := range (*result).Rename {
if renamed == "" {
if updated == nil {
updated = make(map[string]string)
}
updated[orig] = prefix + "." + orig
}
}
for orig, renamed := range updated {
(*result).Rename[orig] = renamed
}
}
return result
}
// Get the jarjar rule text for a given provider for the fully resolved rules. Classes that map
// to "" won't be in this list because they shouldn't be renamed yet.
func getJarJarRuleText(provider *JarJarProviderData) string {
result := strings.Builder{}
for _, orig := range android.SortedKeys(provider.Rename) {
renamed := provider.Rename[orig]
if renamed != "" {
result.WriteString("rule ")
result.WriteString(orig)
result.WriteString(" ")
result.WriteString(renamed)
result.WriteString("\n")
}
}
return result.String()
}
// Repackage the flags if the jarjar rule txt for the flags is generated
func (j *Module) repackageFlagsIfNecessary(ctx android.ModuleContext, infile android.Path, jarName, info string) (android.Path, bool) {
if j.repackageJarjarRules == nil {
return infile, false
}
repackagedJarjarFile := android.PathForModuleOut(ctx, "repackaged-jarjar", info, jarName)
TransformJarJar(ctx, repackagedJarjarFile, infile, j.repackageJarjarRules)
return repackagedJarjarFile, true
}
func (j *Module) jarjarIfNecessary(ctx android.ModuleContext, infile android.Path, jarName, info string, useShards bool) (android.Path, bool) {
if j.expandJarjarRules == nil {
return infile, false
}
jarjarFile := android.PathForModuleOut(ctx, "jarjar", info, jarName)
totalShards := 1
if useShards {
totalShardsStr := j.properties.Jarjar_shards.GetOrDefault(ctx, "1")
ts, err := strconv.Atoi(totalShardsStr)
if err != nil {
ctx.PropertyErrorf("jarjar_shards", "jarjar_shards must be an integer represented as a string")
return infile, false
}
totalShards = ts
}
TransformJarJarWithShards(ctx, jarjarFile, infile, j.expandJarjarRules, totalShards)
return jarjarFile, true
}
func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
deps.processorPath = append(deps.processorPath, pluginJars...)
deps.processorClasses = append(deps.processorClasses, pluginClasses...)
}
// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
// this interface.
type ProvidesUsesLib interface {
ProvidesUsesLib() *string
}
func (j *Module) ProvidesUsesLib() *string {
return j.usesLibraryProperties.Provides_uses_lib
}
type ModuleWithStem interface {
Stem() string
}
var _ ModuleWithStem = (*Module)(nil)
type ModuleWithUsesLibrary interface {
UsesLibrary() *usesLibrary
}
func (j *Module) UsesLibrary() *usesLibrary {
return &j.usesLibrary
}
var _ ModuleWithUsesLibrary = (*Module)(nil)
|