1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Owen1212055 <23108066+Owen1212055@users.noreply.github.com>
Date: Wed, 6 Jul 2022 23:00:31 -0400
Subject: [PATCH] Paper Plugins
Co-authored-by: Micah Rao <micah.s.rao@gmail.com>
diff --git a/src/main/java/io/papermc/paper/command/PaperCommand.java b/src/main/java/io/papermc/paper/command/PaperCommand.java
index 8ccc59473bac983ced6b9e4a57e0ec4ebd2b0f32..6d06b772ffb9d47d6a717462a4b2b494544e80ae 100644
--- a/src/main/java/io/papermc/paper/command/PaperCommand.java
+++ b/src/main/java/io/papermc/paper/command/PaperCommand.java
@@ -37,6 +37,7 @@ public final class PaperCommand extends Command {
commands.put(Set.of("entity"), new EntityCommand());
commands.put(Set.of("reload"), new ReloadCommand());
commands.put(Set.of("version"), new VersionCommand());
+ commands.put(Set.of("dumpplugins"), new DumpPluginsCommand());
return commands.entrySet().stream()
.flatMap(entry -> entry.getKey().stream().map(s -> Map.entry(s, entry.getValue())))
diff --git a/src/main/java/io/papermc/paper/command/PaperCommands.java b/src/main/java/io/papermc/paper/command/PaperCommands.java
index 5e5ec700a368cfdaa1ea0b3f0fa82089895d4b92..72f2e81b9905a0d57ed8e2a88578f62d5235c456 100644
--- a/src/main/java/io/papermc/paper/command/PaperCommands.java
+++ b/src/main/java/io/papermc/paper/command/PaperCommands.java
@@ -24,5 +24,6 @@ public final class PaperCommands {
COMMANDS.forEach((s, command) -> {
server.server.getCommandMap().register(s, "Paper", command);
});
+ server.server.getCommandMap().register("bukkit", new PaperPluginsCommand());
}
}
diff --git a/src/main/java/io/papermc/paper/command/PaperPluginsCommand.java b/src/main/java/io/papermc/paper/command/PaperPluginsCommand.java
new file mode 100644
index 0000000000000000000000000000000000000000..f0fce4113fb07c64adbec029d177c236cbdcbae8
--- /dev/null
+++ b/src/main/java/io/papermc/paper/command/PaperPluginsCommand.java
@@ -0,0 +1,215 @@
+package io.papermc.paper.command;
+
+import com.google.common.collect.Lists;
+import io.leangen.geantyref.GenericTypeReflector;
+import io.leangen.geantyref.TypeToken;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.entrypoint.Entrypoint;
+import io.papermc.paper.plugin.entrypoint.LaunchEntryPointHandler;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.ProviderStatus;
+import io.papermc.paper.plugin.provider.ProviderStatusHolder;
+import io.papermc.paper.plugin.provider.type.paper.PaperPluginParent;
+import io.papermc.paper.plugin.provider.type.spigot.SpigotPluginProvider;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.JoinConfiguration;
+import net.kyori.adventure.text.TextComponent;
+import net.kyori.adventure.text.event.ClickEvent;
+import net.kyori.adventure.text.format.NamedTextColor;
+import net.kyori.adventure.text.format.TextColor;
+import org.bukkit.Bukkit;
+import org.bukkit.command.CommandSender;
+import org.bukkit.command.defaults.BukkitCommand;
+import org.bukkit.craftbukkit.util.CraftMagicNumbers;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.jetbrains.annotations.NotNull;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.TreeMap;
+
+public class PaperPluginsCommand extends BukkitCommand {
+
+ private static final TextColor INFO_COLOR = TextColor.color(52, 159, 218);
+
+ // TODO: LINK?
+ private static final Component SERVER_PLUGIN_INFO = Component.text("ℹ What is a server plugin?", INFO_COLOR)
+ .append(asPlainComponents("""
+ Server plugins can add new behavior to your server!
+ You can find new plugins on Paper's plugin repository, Hangar.
+
+ <link to hangar>
+ """));
+
+ private static final Component SERVER_INITIALIZER_INFO = Component.text("ℹ What is a server initializer?", INFO_COLOR)
+ .append(asPlainComponents("""
+ Server initializers are ran before your server
+ starts and are provided by paper plugins.
+ """));
+
+ private static final Component LEGACY_PLUGIN_INFO = Component.text("ℹ What is a legacy plugin?", INFO_COLOR)
+ .append(asPlainComponents("""
+ A legacy plugin is a plugin that was made on
+ very old unsupported versions of the game.
+
+ It is encouraged that you replace this plugin,
+ as they might not work in the future and may cause
+ performance issues.
+ """));
+
+ private static final Component LEGACY_PLUGIN_STAR = Component.text('*', TextColor.color(255, 212, 42)).hoverEvent(LEGACY_PLUGIN_INFO);
+ private static final Component INFO_ICON_START = Component.text("ℹ ", INFO_COLOR);
+ private static final Component PAPER_HEADER = Component.text("Paper Plugins:", TextColor.color(2, 136, 209));
+ private static final Component BUKKIT_HEADER = Component.text("Bukkit Plugins:", TextColor.color(237, 129, 6));
+ private static final Component PLUGIN_TICK = Component.text("- ", NamedTextColor.DARK_GRAY);
+ private static final Component PLUGIN_TICK_EMPTY = Component.text(" ");
+
+ private static final Type JAVA_PLUGIN_PROVIDER_TYPE = new TypeToken<PluginProvider<JavaPlugin>>() {}.getType();
+
+ public PaperPluginsCommand() {
+ super("plugins");
+ this.description = "Gets a list of plugins running on the server";
+ this.usageMessage = "/plugins";
+ this.setPermission("bukkit.command.plugins");
+ this.setAliases(Arrays.asList("pl"));
+ }
+
+ private static <T> List<Component> formatProviders(TreeMap<String, PluginProvider<T>> plugins) {
+ List<Component> components = new ArrayList<>(plugins.size());
+ for (PluginProvider<T> entry : plugins.values()) {
+ components.add(formatProvider(entry));
+ }
+
+ boolean isFirst = true;
+ List<Component> formattedSublists = new ArrayList<>();
+ /*
+ Split up the plugin list for each 10 plugins to get size down
+
+ Plugin List:
+ - Plugin 1, Plugin 2, .... Plugin 10,
+ Plugin 11, Plugin 12 ... Plugin 20,
+ */
+ for (List<Component> componentSublist : Lists.partition(components, 10)) {
+ Component component = Component.space();
+ if (isFirst) {
+ component = component.append(PLUGIN_TICK);
+ isFirst = false;
+ } else {
+ component = PLUGIN_TICK_EMPTY;
+ //formattedSublists.add(Component.empty()); // Add an empty line, the auto chat wrapping and this makes it quite jarring.
+ }
+
+ formattedSublists.add(component.append(Component.join(JoinConfiguration.commas(true), componentSublist)));
+ }
+
+ return formattedSublists;
+ }
+
+ private static Component formatProvider(PluginProvider<?> provider) {
+ TextComponent.Builder builder = Component.text();
+ if (provider instanceof SpigotPluginProvider spigotPluginProvider && CraftMagicNumbers.isLegacy(spigotPluginProvider.getMeta())) {
+ builder.append(LEGACY_PLUGIN_STAR);
+ }
+
+ String name = provider.getMeta().getName();
+ Component pluginName = Component.text(name, fromStatus(provider))
+ .clickEvent(ClickEvent.runCommand("/version " + name));
+
+ builder.append(pluginName);
+
+ return builder.build();
+ }
+
+ private static Component asPlainComponents(String strings) {
+ net.kyori.adventure.text.TextComponent.Builder builder = Component.text();
+ for (String string : strings.split("\n")) {
+ builder.append(Component.newline());
+ builder.append(Component.text(string, NamedTextColor.WHITE));
+ }
+
+ return builder.build();
+ }
+
+ private static TextColor fromStatus(PluginProvider<?> provider) {
+ if (provider instanceof ProviderStatusHolder statusHolder && statusHolder.getLastProvidedStatus() != null) {
+ ProviderStatus status = statusHolder.getLastProvidedStatus();
+
+ // Handle enabled/disabled game plugins
+ if (status == ProviderStatus.INITIALIZED && GenericTypeReflector.isSuperType(JAVA_PLUGIN_PROVIDER_TYPE, provider.getClass())) {
+ Plugin plugin = Bukkit.getPluginManager().getPlugin(provider.getMeta().getName());
+ // Plugin doesn't exist? Could be due to it being removed.
+ if (plugin == null) {
+ return NamedTextColor.RED;
+ }
+
+ return plugin.isEnabled() ? NamedTextColor.GREEN : NamedTextColor.RED;
+ }
+
+ return switch (status) {
+ case INITIALIZED -> NamedTextColor.GREEN;
+ case ERRORED -> NamedTextColor.RED;
+ };
+ } else if (provider instanceof PaperPluginParent.PaperServerPluginProvider serverPluginProvider && serverPluginProvider.shouldSkipCreation()) {
+ // Paper plugins will be skipped if their provider is skipped due to their initializer failing.
+ // Show them as red
+ return NamedTextColor.RED;
+ } else {
+ // Separated for future logic choice, but this indicated a provider that failed to load due to
+ // dependency issues or what not.
+ return NamedTextColor.RED;
+ }
+ }
+
+ @Override
+ public boolean execute(@NotNull CommandSender sender, @NotNull String currentAlias, @NotNull String[] args) {
+ if (!this.testPermission(sender)) return true;
+
+ TreeMap<String, PluginProvider<JavaPlugin>> paperPlugins = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+ TreeMap<String, PluginProvider<JavaPlugin>> spigotPlugins = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+
+
+ for (PluginProvider<JavaPlugin> provider : LaunchEntryPointHandler.INSTANCE.get(Entrypoint.PLUGIN).getRegisteredProviders()) {
+ PluginMeta configuration = provider.getMeta();
+
+ if (provider instanceof SpigotPluginProvider) {
+ spigotPlugins.put(configuration.getDisplayName(), provider);
+ } else if (provider instanceof PaperPluginParent.PaperServerPluginProvider) {
+ paperPlugins.put(configuration.getDisplayName(), provider);
+ }
+ }
+
+ Component infoMessage = Component.text("Server Plugins (%s):".formatted(paperPlugins.size() + spigotPlugins.size()), NamedTextColor.WHITE);
+ //.append(INFO_ICON_START.hoverEvent(SERVER_PLUGIN_INFO)); TODO: Add docs
+
+ sender.sendMessage(infoMessage);
+
+ if (!paperPlugins.isEmpty()) {
+ sender.sendMessage(PAPER_HEADER);
+ }
+
+ for (Component component : formatProviders(paperPlugins)) {
+ sender.sendMessage(component);
+ }
+
+ if (!spigotPlugins.isEmpty()) {
+ sender.sendMessage(BUKKIT_HEADER);
+ }
+
+ for (Component component : formatProviders(spigotPlugins)) {
+ sender.sendMessage(component);
+ }
+
+ return true;
+ }
+
+ @NotNull
+ @Override
+ public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException {
+ return Collections.emptyList();
+ }
+
+}
diff --git a/src/main/java/io/papermc/paper/command/subcommands/DumpPluginsCommand.java b/src/main/java/io/papermc/paper/command/subcommands/DumpPluginsCommand.java
new file mode 100644
index 0000000000000000000000000000000000000000..d4a092243e587e3a555fbc0f00c8f78c00b3d1c6
--- /dev/null
+++ b/src/main/java/io/papermc/paper/command/subcommands/DumpPluginsCommand.java
@@ -0,0 +1,203 @@
+package io.papermc.paper.command.subcommands;
+
+import com.google.common.graph.GraphBuilder;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.internal.Streams;
+import com.google.gson.stream.JsonWriter;
+import io.papermc.paper.command.PaperSubcommand;
+import io.papermc.paper.plugin.entrypoint.Entrypoint;
+import io.papermc.paper.plugin.entrypoint.LaunchEntryPointHandler;
+import io.papermc.paper.plugin.entrypoint.classloader.group.LockingClassLoaderGroup;
+import io.papermc.paper.plugin.entrypoint.classloader.group.PaperPluginClassLoaderStorage;
+import io.papermc.paper.plugin.entrypoint.classloader.group.SimpleListPluginClassLoaderGroup;
+import io.papermc.paper.plugin.entrypoint.classloader.group.SpigotPluginClassLoaderGroup;
+import io.papermc.paper.plugin.entrypoint.classloader.group.StaticPluginClassLoaderGroup;
+import io.papermc.paper.plugin.entrypoint.dependency.GraphDependencyContext;
+import io.papermc.paper.plugin.entrypoint.dependency.SimpleMetaDependencyTree;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+import io.papermc.paper.plugin.entrypoint.strategy.modern.ModernPluginLoadingStrategy;
+import io.papermc.paper.plugin.entrypoint.strategy.ProviderConfiguration;
+import io.papermc.paper.plugin.manager.PaperPluginManagerImpl;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
+import io.papermc.paper.plugin.provider.classloader.PaperClassLoaderStorage;
+import io.papermc.paper.plugin.provider.classloader.PluginClassLoaderGroup;
+import io.papermc.paper.plugin.storage.ConfiguredProviderStorage;
+import io.papermc.paper.plugin.storage.ProviderStorage;
+import net.minecraft.server.MinecraftServer;
+import org.bukkit.command.CommandSender;
+import org.bukkit.plugin.Plugin;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.framework.qual.DefaultQualifier;
+
+import java.io.PrintStream;
+import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import static net.kyori.adventure.text.Component.text;
+import static net.kyori.adventure.text.format.NamedTextColor.GREEN;
+import static net.kyori.adventure.text.format.NamedTextColor.RED;
+
+@DefaultQualifier(NonNull.class)
+public final class DumpPluginsCommand implements PaperSubcommand {
+ @Override
+ public boolean execute(final CommandSender sender, final String subCommand, final String[] args) {
+ this.dumpPlugins(sender, args);
+ return true;
+ }
+
+ private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss");
+
+ private void dumpPlugins(final CommandSender sender, final String[] args) {
+ Path parent = Path.of("debug");
+ Path path = parent.resolve("plugin-info-" + FORMATTER.format(LocalDateTime.now()) + ".txt");
+ try {
+ Files.createDirectories(parent);
+ Files.createFile(path);
+ sender.sendMessage(text("Writing plugin information to " + path, GREEN));
+
+ final JsonObject data = this.writeDebug();
+
+ StringWriter stringWriter = new StringWriter();
+ JsonWriter jsonWriter = new JsonWriter(stringWriter);
+ jsonWriter.setIndent(" ");
+ jsonWriter.setLenient(false);
+ Streams.write(data, jsonWriter);
+
+ try (PrintStream out = new PrintStream(Files.newOutputStream(path), false, StandardCharsets.UTF_8)) {
+ out.print(stringWriter);
+ }
+ sender.sendMessage(text("Successfully written plugin debug information!", GREEN));
+ } catch (Throwable e) {
+ sender.sendMessage(text("Failed to write plugin information! See the console for more info.", RED));
+ MinecraftServer.LOGGER.warn("Error occurred while dumping plugin info", e);
+ }
+ }
+
+ private JsonObject writeDebug() {
+ JsonObject root = new JsonObject();
+ if (ConfiguredProviderStorage.LEGACY_PLUGIN_LOADING) {
+ root.addProperty("legacy-loading-strategy", true);
+ }
+
+ this.writeProviders(root);
+ this.writePlugins(root);
+ this.writeClassloaders(root);
+
+ return root;
+ }
+
+ private void writeProviders(JsonObject root) {
+ JsonObject rootProviders = new JsonObject();
+ root.add("providers", rootProviders);
+
+ for (Map.Entry<Entrypoint<?>, ProviderStorage<?>> entry : LaunchEntryPointHandler.INSTANCE.getStorage().entrySet()) {
+ JsonObject entrypoint = new JsonObject();
+
+ JsonArray providers = new JsonArray();
+ entrypoint.add("providers", providers);
+
+ List<PluginProvider<Object>> pluginProviders = new ArrayList<>();
+ for (PluginProvider<?> provider : entry.getValue().getRegisteredProviders()) {
+ JsonObject providerObj = new JsonObject();
+ providerObj.addProperty("name", provider.getMeta().getName());
+ providerObj.addProperty("version", provider.getMeta().getVersion());
+ providerObj.addProperty("dependencies", provider.getMeta().getPluginDependencies().toString());
+ providerObj.addProperty("soft-dependencies", provider.getMeta().getPluginSoftDependencies().toString());
+ providerObj.addProperty("load-before", provider.getMeta().getLoadBeforePlugins().toString());
+
+
+ providers.add(providerObj);
+ pluginProviders.add((PluginProvider<Object>) provider);
+ }
+
+ JsonArray loadOrder = new JsonArray();
+ entrypoint.add("load-order", loadOrder);
+
+ ModernPluginLoadingStrategy<Object> modernPluginLoadingStrategy = new ModernPluginLoadingStrategy<>(new ProviderConfiguration<>() {
+ @Override
+ public void applyContext(PluginProvider<Object> provider, DependencyContext dependencyContext) {
+ }
+
+ @Override
+ public boolean load(PluginProvider<Object> provider, Object provided) {
+ return true;
+ }
+
+ @Override
+ public boolean preloadProvider(PluginProvider<Object> provider) {
+ // Don't load provider
+ loadOrder.add(provider.getMeta().getName());
+ return false;
+ }
+ });
+ modernPluginLoadingStrategy.loadProviders(pluginProviders, new SimpleMetaDependencyTree(GraphBuilder.directed().build()));
+
+ rootProviders.add(entry.getKey().getDebugName(), entrypoint);
+ }
+ }
+
+ private void writePlugins(JsonObject root) {
+ JsonArray rootPlugins = new JsonArray();
+ root.add("plugins", rootPlugins);
+
+ for (Plugin plugin : PaperPluginManagerImpl.getInstance().getPlugins()) {
+ rootPlugins.add(plugin.toString());
+ }
+ }
+
+ private void writeClassloaders(JsonObject root) {
+ JsonObject classLoadersRoot = new JsonObject();
+ root.add("classloaders", classLoadersRoot);
+
+ PaperPluginClassLoaderStorage storage = (PaperPluginClassLoaderStorage) PaperClassLoaderStorage.instance();
+ classLoadersRoot.addProperty("global", storage.getGlobalGroup().toString());
+ classLoadersRoot.addProperty("dependency_graph", PaperPluginManagerImpl.getInstance().getInstanceManagerGraph().toString());
+
+ JsonArray array = new JsonArray();
+ classLoadersRoot.add("children", array);
+ for (PluginClassLoaderGroup group : storage.getGroups()) {
+ array.add(this.writeClassloader(group));
+ }
+ }
+
+ private JsonObject writeClassloader(PluginClassLoaderGroup group) {
+ JsonObject classLoadersRoot = new JsonObject();
+ if (group instanceof SimpleListPluginClassLoaderGroup listGroup) {
+ JsonArray array = new JsonArray();
+ classLoadersRoot.addProperty("main", listGroup.toString());
+ if (group instanceof StaticPluginClassLoaderGroup staticPluginClassLoaderGroup) {
+ classLoadersRoot.addProperty("plugin-holder", staticPluginClassLoaderGroup.getPluginClassloader().toString());
+ } else if (group instanceof SpigotPluginClassLoaderGroup spigotPluginClassLoaderGroup) {
+ classLoadersRoot.addProperty("plugin-holder", spigotPluginClassLoaderGroup.getPluginClassLoader().toString());
+ }
+
+ classLoadersRoot.add("children", array);
+ for (ConfiguredPluginClassLoader innerGroup : listGroup.getClassLoaders()) {
+ array.add(this.writeClassloader(innerGroup));
+ }
+
+ } else if (group instanceof LockingClassLoaderGroup locking) {
+ // Unwrap
+ return this.writeClassloader(locking.getParent());
+ } else {
+ classLoadersRoot.addProperty("raw", group.toString());
+ }
+
+ return classLoadersRoot;
+ }
+
+ private JsonElement writeClassloader(ConfiguredPluginClassLoader innerGroup) {
+ return new JsonPrimitive(innerGroup.toString());
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/PluginInitializerManager.java b/src/main/java/io/papermc/paper/plugin/PluginInitializerManager.java
new file mode 100644
index 0000000000000000000000000000000000000000..708e5bb9bbf0476fcc2c4b92c6830b094703b43e
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/PluginInitializerManager.java
@@ -0,0 +1,134 @@
+package io.papermc.paper.plugin;
+
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.configuration.PaperConfigurations;
+import io.papermc.paper.plugin.entrypoint.Entrypoint;
+import io.papermc.paper.plugin.entrypoint.LaunchEntryPointHandler;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.type.paper.PaperPluginParent;
+import joptsimple.OptionSet;
+import net.minecraft.server.dedicated.DedicatedServer;
+import org.bukkit.configuration.file.YamlConfiguration;
+import org.bukkit.craftbukkit.CraftServer;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.slf4j.Logger;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+public class PluginInitializerManager {
+
+ private static final Logger LOGGER = LogUtils.getClassLogger();
+ private static PluginInitializerManager impl;
+ private final Path pluginDirectory;
+ private final Path updateDirectory;
+
+ PluginInitializerManager(final Path pluginDirectory, final Path updateDirectory) {
+ this.pluginDirectory = pluginDirectory;
+ this.updateDirectory = updateDirectory;
+ }
+
+ private static PluginInitializerManager parse(@NotNull final OptionSet minecraftOptionSet) throws Exception {
+ // We have to load the bukkit configuration inorder to get the update folder location.
+ final File configFileLocationBukkit = (File) minecraftOptionSet.valueOf("bukkit-settings");
+
+ final Path pluginDirectory = ((File) minecraftOptionSet.valueOf("plugins")).toPath();
+
+ final YamlConfiguration configuration = PaperConfigurations.loadLegacyConfigFile(configFileLocationBukkit);
+
+ final String updateDirectoryName = configuration.getString("settings.update-folder", "update");
+ if (updateDirectoryName.isBlank()) {
+ return new PluginInitializerManager(pluginDirectory, null);
+ }
+
+ final Path resolvedUpdateDirectory = pluginDirectory.resolve(updateDirectoryName);
+ if (!Files.isDirectory(resolvedUpdateDirectory)) {
+ if (Files.exists(resolvedUpdateDirectory)) {
+ LOGGER.error("Misconfigured update directory!");
+ LOGGER.error("Your configured update directory ({}) in bukkit.yml is pointing to a non-directory path. " +
+ "Auto updating functionality will not work.", resolvedUpdateDirectory);
+ }
+ return new PluginInitializerManager(pluginDirectory, null);
+ }
+
+ boolean isSameFile;
+ try {
+ isSameFile = Files.isSameFile(resolvedUpdateDirectory, pluginDirectory);
+ } catch (final IOException e) {
+ LOGGER.error("Misconfigured update directory!");
+ LOGGER.error("Failed to compare update/plugin directory", e);
+ return new PluginInitializerManager(pluginDirectory, null);
+ }
+
+ if (isSameFile) {
+ LOGGER.error("Misconfigured update directory!");
+ LOGGER.error(("Your configured update directory (%s) in bukkit.yml is pointing to the same location as the plugin directory (%s). " +
+ "Disabling auto updating functionality.").formatted(resolvedUpdateDirectory, pluginDirectory));
+
+ return new PluginInitializerManager(pluginDirectory, null);
+ }
+
+ return new PluginInitializerManager(pluginDirectory, resolvedUpdateDirectory);
+ }
+
+ public static PluginInitializerManager init(final OptionSet optionSet) throws Exception {
+ impl = parse(optionSet);
+ return impl;
+ }
+
+ public static PluginInitializerManager instance() {
+ return impl;
+ }
+
+ @NotNull
+ public Path pluginDirectoryPath() {
+ return pluginDirectory;
+ }
+
+ @Nullable
+ public Path pluginUpdatePath() {
+ return updateDirectory;
+ }
+
+ public static void load(OptionSet optionSet) throws Exception {
+ // We have to load the bukkit configuration inorder to get the update folder location.
+ io.papermc.paper.plugin.PluginInitializerManager pluginSystem = io.papermc.paper.plugin.PluginInitializerManager.init(optionSet);
+
+ // Register the default plugin directory
+ io.papermc.paper.plugin.util.EntrypointUtil.registerProvidersFromSource(io.papermc.paper.plugin.provider.source.DirectoryProviderSource.INSTANCE, pluginSystem.pluginDirectoryPath());
+
+ // Register plugins from the flag
+ @SuppressWarnings("unchecked")
+ java.util.List<Path> files = ((java.util.List<File>) optionSet.valuesOf("add-plugin")).stream().map(File::toPath).toList();
+ io.papermc.paper.plugin.util.EntrypointUtil.registerProvidersFromSource(io.papermc.paper.plugin.provider.source.PluginFlagProviderSource.INSTANCE, files);
+ }
+
+ // This will be the end of me...
+ public static void reload(DedicatedServer dedicatedServer) {
+ // Wipe the provider storage
+ LaunchEntryPointHandler.INSTANCE.populateProviderStorage();
+ try {
+ load(dedicatedServer.options);
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to reload!", e);
+ }
+
+ boolean hasPaperPlugin = false;
+ for (PluginProvider<?> provider : LaunchEntryPointHandler.INSTANCE.getStorage().get(Entrypoint.PLUGIN).getRegisteredProviders()) {
+ if (provider instanceof PaperPluginParent.PaperServerPluginProvider) {
+ hasPaperPlugin = true;
+ break;
+ }
+ }
+
+ if (hasPaperPlugin) {
+ LOGGER.warn("======== WARNING ========");
+ LOGGER.warn("You are reloading while having Paper plugins installed on your server.");
+ LOGGER.warn("Paper plugins do NOT support being reloaded. This will cause some unexpected issues.");
+ LOGGER.warn("=========================");
+ }
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/bootstrap/PluginBootstrapContextImpl.java b/src/main/java/io/papermc/paper/plugin/bootstrap/PluginBootstrapContextImpl.java
new file mode 100644
index 0000000000000000000000000000000000000000..30b50e6294c6eaade5e17cfaf34600d122e6251c
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/bootstrap/PluginBootstrapContextImpl.java
@@ -0,0 +1,48 @@
+package io.papermc.paper.plugin.bootstrap;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import java.nio.file.Path;
+import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
+import org.jetbrains.annotations.NotNull;
+
+public final class PluginBootstrapContextImpl implements BootstrapContext {
+
+ private final PluginMeta config;
+ private final Path dataFolder;
+ private final ComponentLogger logger;
+ private final Path pluginSource;
+
+ public PluginBootstrapContextImpl(PluginMeta config, Path dataFolder, ComponentLogger logger, Path pluginSource) {
+ this.config = config;
+ this.dataFolder = dataFolder;
+ this.logger = logger;
+ this.pluginSource = pluginSource;
+ }
+
+ public static PluginBootstrapContextImpl create(PluginProvider<?> provider, Path pluginFolder) {
+ Path dataFolder = pluginFolder.resolve(provider.getMeta().getName());
+
+ return new PluginBootstrapContextImpl(provider.getMeta(), dataFolder, provider.getLogger(), provider.getSource());
+ }
+
+ @Override
+ public @NotNull PluginMeta getConfiguration() {
+ return this.config;
+ }
+
+ @Override
+ public @NotNull Path getDataDirectory() {
+ return this.dataFolder;
+ }
+
+ @Override
+ public @NotNull ComponentLogger getLogger() {
+ return this.logger;
+ }
+
+ @Override
+ public @NotNull Path getPluginSource() {
+ return this.pluginSource;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/bootstrap/PluginProviderContextImpl.java b/src/main/java/io/papermc/paper/plugin/bootstrap/PluginProviderContextImpl.java
new file mode 100644
index 0000000000000000000000000000000000000000..ef74ca64c589c9158909a2356e73a23f4f01faa2
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/bootstrap/PluginProviderContextImpl.java
@@ -0,0 +1,49 @@
+package io.papermc.paper.plugin.bootstrap;
+
+import io.papermc.paper.plugin.PluginInitializerManager;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
+import org.jetbrains.annotations.NotNull;
+
+import java.nio.file.Path;
+
+public final class PluginProviderContextImpl implements PluginProviderContext {
+
+ private final PluginMeta config;
+ private final Path dataFolder;
+ private final ComponentLogger logger;
+ private final Path pluginSource;
+
+ public PluginProviderContextImpl(PluginMeta config, Path dataFolder, ComponentLogger logger, Path pluginSource) {
+ this.config = config;
+ this.dataFolder = dataFolder;
+ this.logger = logger;
+ this.pluginSource = pluginSource;
+ }
+
+ public static PluginProviderContextImpl create(PluginMeta config, ComponentLogger logger, Path pluginSource) {
+ Path dataFolder = PluginInitializerManager.instance().pluginDirectoryPath().resolve(config.getName());
+
+ return new PluginProviderContextImpl(config, dataFolder, logger, pluginSource);
+ }
+
+ @Override
+ public @NotNull PluginMeta getConfiguration() {
+ return this.config;
+ }
+
+ @Override
+ public @NotNull Path getDataDirectory() {
+ return this.dataFolder;
+ }
+
+ @Override
+ public @NotNull ComponentLogger getLogger() {
+ return this.logger;
+ }
+
+ @Override
+ public @NotNull Path getPluginSource() {
+ return this.pluginSource;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/Entrypoint.java b/src/main/java/io/papermc/paper/plugin/entrypoint/Entrypoint.java
new file mode 100644
index 0000000000000000000000000000000000000000..125008ac7db8b9f3fb57c49f8e4facc4ad4bb136
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/Entrypoint.java
@@ -0,0 +1,25 @@
+package io.papermc.paper.plugin.entrypoint;
+
+import io.papermc.paper.plugin.bootstrap.PluginBootstrap;
+import org.bukkit.plugin.java.JavaPlugin;
+
+/**
+ * Used to mark a certain place that {@link EntrypointHandler} will register {@link io.papermc.paper.plugin.provider.PluginProvider} under.
+ * Used for loading only certain providers at a certain time.
+ * @param <T> provider type
+ */
+public final class Entrypoint<T> {
+
+ public static final Entrypoint<PluginBootstrap> BOOTSTRAPPER = new Entrypoint<>("bootstrapper");
+ public static final Entrypoint<JavaPlugin> PLUGIN = new Entrypoint<>("plugin");
+
+ private final String debugName;
+
+ private Entrypoint(String debugName) {
+ this.debugName = debugName;
+ }
+
+ public String getDebugName() {
+ return debugName;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/EntrypointHandler.java b/src/main/java/io/papermc/paper/plugin/entrypoint/EntrypointHandler.java
new file mode 100644
index 0000000000000000000000000000000000000000..b38e1e0f3d3055086f51bb191fd4b60ecf32d016
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/EntrypointHandler.java
@@ -0,0 +1,14 @@
+package io.papermc.paper.plugin.entrypoint;
+
+import io.papermc.paper.plugin.provider.PluginProvider;
+
+/**
+ * Represents a register that will register providers at a certain {@link Entrypoint},
+ * where then when the given {@link Entrypoint} is registered those will be loaded.
+ */
+public interface EntrypointHandler {
+
+ <T> void register(Entrypoint<T> entrypoint, PluginProvider<T> provider);
+
+ void enter(Entrypoint<?> entrypoint);
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/LaunchEntryPointHandler.java b/src/main/java/io/papermc/paper/plugin/entrypoint/LaunchEntryPointHandler.java
new file mode 100644
index 0000000000000000000000000000000000000000..6c0f2c315387734f8dd4a7eca633aa0a9856dd17
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/LaunchEntryPointHandler.java
@@ -0,0 +1,65 @@
+package io.papermc.paper.plugin.entrypoint;
+
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.storage.BootstrapProviderStorage;
+import io.papermc.paper.plugin.storage.ProviderStorage;
+import io.papermc.paper.plugin.storage.ServerPluginProviderStorage;
+import org.jetbrains.annotations.ApiStatus;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Used by the server to register/load plugin bootstrappers and plugins.
+ */
+public class LaunchEntryPointHandler implements EntrypointHandler {
+
+ public static final LaunchEntryPointHandler INSTANCE = new LaunchEntryPointHandler();
+ private final Map<Entrypoint<?>, ProviderStorage<?>> storage = new HashMap<>();
+
+ LaunchEntryPointHandler() {
+ this.populateProviderStorage();
+ }
+
+ // Utility
+ public static void enterBootstrappers() {
+ LaunchEntryPointHandler.INSTANCE.enter(Entrypoint.BOOTSTRAPPER);
+ }
+
+ @Override
+ public void enter(Entrypoint<?> entrypoint) {
+ ProviderStorage<?> storage = this.storage.get(entrypoint);
+ if (storage == null) {
+ throw new IllegalArgumentException("No storage registered for entrypoint %s.".formatted(entrypoint));
+ }
+
+ storage.enter();
+ }
+
+ @Override
+ public <T> void register(Entrypoint<T> entrypoint, PluginProvider<T> provider) {
+ ProviderStorage<T> storage = this.get(entrypoint);
+ if (storage == null) {
+ throw new IllegalArgumentException("No storage registered for entrypoint %s.".formatted(entrypoint));
+ }
+
+ storage.register(provider);
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> ProviderStorage<T> get(Entrypoint<T> entrypoint) {
+ return (ProviderStorage<T>) this.storage.get(entrypoint);
+ }
+
+ // Debug only
+ @ApiStatus.Internal
+ public Map<Entrypoint<?>, ProviderStorage<?>> getStorage() {
+ return storage;
+ }
+
+ // Reload only
+ public void populateProviderStorage() {
+ this.storage.put(Entrypoint.BOOTSTRAPPER, new BootstrapProviderStorage());
+ this.storage.put(Entrypoint.PLUGIN, new ServerPluginProviderStorage());
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/ClassloaderBytecodeModifier.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/ClassloaderBytecodeModifier.java
new file mode 100644
index 0000000000000000000000000000000000000000..93b5196a960f3efbe0d28f5527ea2752426213ce
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/ClassloaderBytecodeModifier.java
@@ -0,0 +1,22 @@
+package io.papermc.paper.plugin.entrypoint.classloader;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import net.kyori.adventure.util.Services;
+import org.jetbrains.annotations.ApiStatus;
+
+@ApiStatus.Internal
+public interface ClassloaderBytecodeModifier {
+
+ static ClassloaderBytecodeModifier bytecodeModifier() {
+ return Provider.INSTANCE;
+ }
+
+ byte[] modify(PluginMeta config, byte[] bytecode);
+
+ class Provider {
+
+ private static final ClassloaderBytecodeModifier INSTANCE = Services.service(ClassloaderBytecodeModifier.class).orElseThrow();
+
+ }
+
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/PaperClassloaderBytecodeModifier.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/PaperClassloaderBytecodeModifier.java
new file mode 100644
index 0000000000000000000000000000000000000000..f9a2c55a354c877749db3f92956de802ae575788
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/PaperClassloaderBytecodeModifier.java
@@ -0,0 +1,12 @@
+package io.papermc.paper.plugin.entrypoint.classloader;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+
+// Stub, implement in future.
+public class PaperClassloaderBytecodeModifier implements ClassloaderBytecodeModifier {
+
+ @Override
+ public byte[] modify(PluginMeta configuration, byte[] bytecode) {
+ return bytecode;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/PaperPluginClassLoader.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/PaperPluginClassLoader.java
new file mode 100644
index 0000000000000000000000000000000000000000..5a00e5c41274ded6b837fb81fa8f54616f2b7bc8
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/PaperPluginClassLoader.java
@@ -0,0 +1,205 @@
+package io.papermc.paper.plugin.entrypoint.classloader;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
+import io.papermc.paper.plugin.entrypoint.classloader.group.PaperPluginClassLoaderStorage;
+import io.papermc.paper.plugin.provider.classloader.PaperClassLoaderStorage;
+import io.papermc.paper.plugin.provider.classloader.PluginClassLoaderGroup;
+import io.papermc.paper.plugin.provider.configuration.PaperPluginMeta;
+import org.bukkit.Bukkit;
+import org.bukkit.plugin.PluginDescriptionFile;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.jar.JarFile;
+import java.util.logging.Logger;
+
+/**
+ * This is similar to a {@link org.bukkit.plugin.java.PluginClassLoader} but is completely kept hidden from the api.
+ * This is only used with Paper plugins.
+ *
+ * @see PaperPluginClassLoaderStorage
+ */
+public class PaperPluginClassLoader extends PaperSimplePluginClassLoader implements ConfiguredPluginClassLoader {
+
+ static {
+ registerAsParallelCapable();
+ }
+
+ private final URLClassLoader libraryLoader;
+ private final Set<String> seenIllegalAccess = Collections.newSetFromMap(new ConcurrentHashMap<>());
+ private final Logger logger;
+ @Nullable
+ private JavaPlugin loadedJavaPlugin;
+ @Nullable
+ private PluginClassLoaderGroup group;
+
+ public PaperPluginClassLoader(Logger logger, Path source, JarFile file, PaperPluginMeta configuration, ClassLoader parentLoader, URLClassLoader libraryLoader) throws IOException {
+ super(source, file, configuration, parentLoader);
+ this.libraryLoader = libraryLoader;
+
+ this.logger = logger;
+ if (this.configuration.hasOpenClassloader()) {
+ this.group = PaperClassLoaderStorage.instance().registerOpenGroup(this);
+ }
+ }
+
+ public void refreshClassloaderDependencyTree(DependencyContext dependencyContext) {
+ if (this.configuration.hasOpenClassloader()) {
+ return;
+ }
+ if (this.group != null) {
+ // We need to unregister the classloader inorder to allow for dependencies
+ // to be recalculated
+ PaperClassLoaderStorage.instance().unregisterClassloader(this);
+ }
+
+ this.group = PaperClassLoaderStorage.instance().registerAccessBackedGroup(this, (classLoader) -> {
+ return dependencyContext.isTransitiveDependency(PaperPluginClassLoader.this.configuration, classLoader.getConfiguration());
+ });
+ }
+
+ @Override
+ public URL getResource(String name) {
+ URL resource = findResource(name);
+ if (resource == null && this.libraryLoader != null) {
+ return this.libraryLoader.getResource(name);
+ }
+ return resource;
+ }
+
+ @Override
+ public Enumeration<URL> getResources(String name) throws IOException {
+ List<URL> resources = new ArrayList<>();
+ this.addEnumeration(resources, this.findResources(name));
+ if (this.libraryLoader != null) {
+ addEnumeration(resources, this.libraryLoader.getResources(name));
+ }
+ return Collections.enumeration(resources);
+ }
+
+ private <T> void addEnumeration(List<T> list, Enumeration<T> enumeration) {
+ while (enumeration.hasMoreElements()) {
+ list.add(enumeration.nextElement());
+ }
+ }
+
+ @Override
+ protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
+ return this.loadClass(name, resolve, true, true);
+ }
+
+ @Override
+ public PluginMeta getConfiguration() {
+ return this.configuration;
+ }
+
+ @Override
+ public Class<?> loadClass(@NotNull String name, boolean resolve, boolean checkGroup, boolean checkLibraries) throws ClassNotFoundException {
+ try {
+ Class<?> result = super.loadClass(name, resolve);
+
+ // SPIGOT-6749: Library classes will appear in the above, but we don't want to return them to other plugins
+ if (checkGroup || result.getClassLoader() == this) {
+ return result;
+ }
+ } catch (ClassNotFoundException ignored) {
+ }
+
+ if (checkLibraries) {
+ try {
+ return this.libraryLoader.loadClass(name);
+ } catch (ClassNotFoundException ignored) {
+ }
+ }
+
+ if (checkGroup) {
+ // This ignores the libraries of other plugins, unless they are transitive dependencies.
+ if (this.group == null) {
+ throw new IllegalStateException("Tried to resolve class while group was not yet initialized");
+ }
+
+ Class<?> clazz = this.group.getClassByName(name, resolve, this);
+ if (clazz != null) {
+ return clazz;
+ }
+ }
+
+ throw new ClassNotFoundException(name);
+ }
+
+ @Override
+ public void init(JavaPlugin plugin) {
+ PluginMeta config = this.configuration;
+ PluginDescriptionFile pluginDescriptionFile = new PluginDescriptionFile(
+ config.getName(),
+ config.getName(),
+ config.getProvidedPlugins(),
+ config.getMainClass(),
+ "", // Classloader load order api
+ config.getPluginDependencies(), // Dependencies
+ config.getPluginSoftDependencies(), // Soft Depends
+ config.getLoadBeforePlugins(), // Load Before
+ config.getVersion(),
+ Map.of(), // Commands, we use a separate system
+ config.getDescription(),
+ config.getAuthors(),
+ config.getContributors(),
+ config.getWebsite(),
+ config.getLoggerPrefix(),
+ config.getLoadOrder(),
+ config.getPermissions(),
+ config.getPermissionDefault(),
+ Set.of(), // Aware api
+ config.getAPIVersion(),
+ List.of() // Libraries
+ );
+
+ File dataFolder = new File(Bukkit.getPluginsFolder(), pluginDescriptionFile.getName());
+
+ plugin.init(Bukkit.getServer(), pluginDescriptionFile, dataFolder, this.source.toFile(), this, config, this.logger);
+
+ this.loadedJavaPlugin = plugin;
+ }
+
+ @Nullable
+ @Override
+ public JavaPlugin getPlugin() {
+ return this.loadedJavaPlugin;
+ }
+
+ @Override
+ public String toString() {
+ return "PaperPluginClassLoader{" +
+ "libraryLoader=" + this.libraryLoader +
+ ", seenIllegalAccess=" + this.seenIllegalAccess +
+ ", loadedJavaPlugin=" + this.loadedJavaPlugin +
+ '}';
+ }
+
+ @Override
+ public void close() throws IOException {
+ try (this.jar; this.libraryLoader) {
+ super.close();
+ }
+ }
+
+ @Override
+ public @Nullable PluginClassLoaderGroup getGroup() {
+ return this.group;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/PaperSimplePluginClassLoader.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/PaperSimplePluginClassLoader.java
new file mode 100644
index 0000000000000000000000000000000000000000..6688f2af4a32c2f79785f162e2eac0330d439ac1
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/PaperSimplePluginClassLoader.java
@@ -0,0 +1,116 @@
+package io.papermc.paper.plugin.entrypoint.classloader;
+
+import io.papermc.paper.plugin.provider.configuration.PaperPluginMeta;
+import io.papermc.paper.plugin.util.NamespaceChecker;
+import org.jetbrains.annotations.ApiStatus;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.Path;
+import java.security.CodeSigner;
+import java.security.CodeSource;
+import java.util.Enumeration;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+
+/**
+ * Represents a simple classloader used for paper plugin bootstrappers.
+ */
+@ApiStatus.Internal
+public class PaperSimplePluginClassLoader extends URLClassLoader {
+
+ static {
+ ClassLoader.registerAsParallelCapable();
+ }
+
+ protected final PaperPluginMeta configuration;
+ protected final Path source;
+ protected final Manifest jarManifest;
+ protected final URL jarUrl;
+ protected final JarFile jar;
+
+ public PaperSimplePluginClassLoader(Path source, JarFile file, PaperPluginMeta configuration, ClassLoader parentLoader) throws IOException {
+ super(source.getFileName().toString(), new URL[]{source.toUri().toURL()}, parentLoader);
+
+ this.source = source;
+ this.jarManifest = file.getManifest();
+ this.jarUrl = source.toUri().toURL();
+ this.configuration = configuration;
+ this.jar = file;
+ }
+
+ @Override
+ public URL getResource(String name) {
+ return this.findResource(name);
+ }
+
+ @Override
+ public Enumeration<URL> getResources(String name) throws IOException {
+ return this.findResources(name);
+ }
+
+ // Bytecode modification supported loader
+ @Override
+ protected Class<?> findClass(String name) throws ClassNotFoundException {
+ NamespaceChecker.validateNameSpaceForClassloading(name);
+
+ // See UrlClassLoader#findClass(String)
+ String path = name.replace('.', '/').concat(".class");
+ JarEntry entry = this.jar.getJarEntry(path);
+ if (entry == null) {
+ throw new ClassNotFoundException();
+ }
+
+ // See URLClassLoader#defineClass(String, Resource)
+ byte[] classBytes;
+
+ try (InputStream is = this.jar.getInputStream(entry)) {
+ classBytes = is.readAllBytes();
+ } catch (IOException ex) {
+ throw new ClassNotFoundException(name, ex);
+ }
+
+ classBytes = ClassloaderBytecodeModifier.bytecodeModifier().modify(this.configuration, classBytes);
+
+ int dot = name.lastIndexOf('.');
+ if (dot != -1) {
+ String pkgName = name.substring(0, dot);
+ // Get defined package does not correctly handle sealed packages.
+ if (this.getDefinedPackage(pkgName) == null) {
+ try {
+ if (this.jarManifest != null) {
+ this.definePackage(pkgName, this.jarManifest, this.jarUrl);
+ } else {
+ this.definePackage(pkgName, null, null, null, null, null, null, null);
+ }
+ } catch (IllegalArgumentException ex) {
+ // parallel-capable class loaders: re-verify in case of a
+ // race condition
+ if (this.getDefinedPackage(pkgName) == null) {
+ // Should never happen
+ throw new IllegalStateException("Cannot find package " + pkgName);
+ }
+ }
+ }
+ }
+
+ CodeSigner[] signers = entry.getCodeSigners();
+ CodeSource source = new CodeSource(this.jarUrl, signers);
+
+ return this.defineClass(name, classBytes, 0, classBytes.length, source);
+ }
+
+ @Override
+ public String toString() {
+ return "PaperSimplePluginClassLoader{" +
+ "configuration=" + this.configuration +
+ ", source=" + this.source +
+ ", jarManifest=" + this.jarManifest +
+ ", jarUrl=" + this.jarUrl +
+ ", jar=" + this.jar +
+ '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/DependencyBasedPluginClassLoaderGroup.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/DependencyBasedPluginClassLoaderGroup.java
new file mode 100644
index 0000000000000000000000000000000000000000..eaf5c794cbe8d6138c9d60eaae20f5fc7711f541
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/DependencyBasedPluginClassLoaderGroup.java
@@ -0,0 +1,47 @@
+package io.papermc.paper.plugin.entrypoint.classloader.group;
+
+import io.papermc.paper.plugin.provider.classloader.ClassLoaderAccess;
+import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
+import org.jetbrains.annotations.ApiStatus;
+
+import java.util.ArrayList;
+
+@ApiStatus.Internal
+public class DependencyBasedPluginClassLoaderGroup extends SimpleListPluginClassLoaderGroup {
+
+ private final GlobalPluginClassLoaderGroup globalPluginClassLoaderGroup;
+ private final ClassLoaderAccess access;
+
+ public DependencyBasedPluginClassLoaderGroup(GlobalPluginClassLoaderGroup globalPluginClassLoaderGroup, ClassLoaderAccess access) {
+ super(new ArrayList<>());
+ this.access = access;
+ this.globalPluginClassLoaderGroup = globalPluginClassLoaderGroup;
+ }
+
+ /**
+ * This will refresh the dependencies of the current classloader.
+ */
+ public void populateDependencies() {
+ this.classloaders.clear();
+ for (ConfiguredPluginClassLoader configuredPluginClassLoader : this.globalPluginClassLoaderGroup.getClassLoaders()) {
+ if (this.access.canAccess(configuredPluginClassLoader)) {
+ this.classloaders.add(configuredPluginClassLoader);
+ }
+ }
+
+ }
+
+ @Override
+ public ClassLoaderAccess getAccess() {
+ return this.access;
+ }
+
+ @Override
+ public String toString() {
+ return "DependencyBasedPluginClassLoaderGroup{" +
+ "globalPluginClassLoaderGroup=" + this.globalPluginClassLoaderGroup +
+ ", access=" + this.access +
+ ", classloaders=" + this.classloaders +
+ '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/GlobalPluginClassLoaderGroup.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/GlobalPluginClassLoaderGroup.java
new file mode 100644
index 0000000000000000000000000000000000000000..2a4933088928a51c8135a3a60b7447d9d10c66c4
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/GlobalPluginClassLoaderGroup.java
@@ -0,0 +1,18 @@
+package io.papermc.paper.plugin.entrypoint.classloader.group;
+
+import io.papermc.paper.plugin.provider.classloader.ClassLoaderAccess;
+import org.jetbrains.annotations.ApiStatus;
+
+@ApiStatus.Internal
+public class GlobalPluginClassLoaderGroup extends SimpleListPluginClassLoaderGroup {
+
+ @Override
+ public ClassLoaderAccess getAccess() {
+ return (v) -> true;
+ }
+
+ @Override
+ public String toString() {
+ return "GLOBAL:" + super.toString();
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/LockingClassLoaderGroup.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/LockingClassLoaderGroup.java
new file mode 100644
index 0000000000000000000000000000000000000000..aae50ebba6ba1579b75af5370c8b020d2a927b2c
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/LockingClassLoaderGroup.java
@@ -0,0 +1,76 @@
+package io.papermc.paper.plugin.entrypoint.classloader.group;
+
+import io.papermc.paper.plugin.provider.classloader.ClassLoaderAccess;
+import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
+import io.papermc.paper.plugin.provider.classloader.PluginClassLoaderGroup;
+import org.jetbrains.annotations.ApiStatus;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+@ApiStatus.Internal
+public class LockingClassLoaderGroup implements PluginClassLoaderGroup {
+
+ private final PluginClassLoaderGroup parent;
+ private final Map<String, ClassLockEntry> classLoadLock = new HashMap<>();
+
+ public LockingClassLoaderGroup(PluginClassLoaderGroup parent) {
+ this.parent = parent;
+ }
+
+ @Override
+ public @Nullable Class<?> getClassByName(String name, boolean resolve, ConfiguredPluginClassLoader requester) {
+ // make MT safe
+ ClassLockEntry lock;
+ synchronized (this.classLoadLock) {
+ lock = this.classLoadLock.computeIfAbsent(name, (x) -> new ClassLockEntry(new AtomicInteger(0), new java.util.concurrent.locks.ReentrantReadWriteLock()));
+ lock.count.incrementAndGet();
+ }
+ lock.reentrantReadWriteLock.writeLock().lock();
+ try {
+ return parent.getClassByName(name, resolve, requester);
+ } finally {
+ synchronized (this.classLoadLock) {
+ lock.reentrantReadWriteLock.writeLock().unlock();
+ if (lock.count.get() == 1) {
+ this.classLoadLock.remove(name);
+ } else {
+ lock.count.decrementAndGet();
+ }
+ }
+ }
+ }
+
+ @Override
+ public void remove(ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ this.parent.remove(configuredPluginClassLoader);
+ }
+
+ @Override
+ public void add(ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ this.parent.add(configuredPluginClassLoader);
+ }
+
+ @Override
+ public ClassLoaderAccess getAccess() {
+ return this.parent.getAccess();
+ }
+
+ public PluginClassLoaderGroup getParent() {
+ return parent;
+ }
+
+ record ClassLockEntry(AtomicInteger count, ReentrantReadWriteLock reentrantReadWriteLock) {
+ }
+
+ @Override
+ public String toString() {
+ return "LockingClassLoaderGroup{" +
+ "parent=" + this.parent +
+ ", classLoadLock=" + this.classLoadLock +
+ '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/PaperPluginClassLoaderStorage.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/PaperPluginClassLoaderStorage.java
new file mode 100644
index 0000000000000000000000000000000000000000..e6fcdeb96356ff4713627b1458ac8bbfad1866b1
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/PaperPluginClassLoaderStorage.java
@@ -0,0 +1,93 @@
+package io.papermc.paper.plugin.entrypoint.classloader.group;
+
+import io.papermc.paper.plugin.provider.classloader.ClassLoaderAccess;
+import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
+import io.papermc.paper.plugin.provider.classloader.PaperClassLoaderStorage;
+import io.papermc.paper.plugin.provider.classloader.PluginClassLoaderGroup;
+import org.bukkit.plugin.java.PluginClassLoader;
+import org.jetbrains.annotations.ApiStatus;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * This is used for connecting multiple classloaders.
+ */
+public final class PaperPluginClassLoaderStorage implements PaperClassLoaderStorage {
+
+ private final GlobalPluginClassLoaderGroup globalGroup = new GlobalPluginClassLoaderGroup();
+ private final List<PluginClassLoaderGroup> groups = new CopyOnWriteArrayList<>();
+
+ public PaperPluginClassLoaderStorage() {
+ this.groups.add(this.globalGroup);
+ }
+
+ @Override
+ public PluginClassLoaderGroup registerSpigotGroup(PluginClassLoader pluginClassLoader) {
+ return this.registerGroup(pluginClassLoader, new SpigotPluginClassLoaderGroup(this.globalGroup, (library) -> {
+ return pluginClassLoader.dependencyContext.isTransitiveDependency(pluginClassLoader.getConfiguration(), library.getConfiguration());
+ }, pluginClassLoader));
+ }
+
+ @Override
+ public PluginClassLoaderGroup registerOpenGroup(ConfiguredPluginClassLoader classLoader) {
+ return this.registerGroup(classLoader, this.globalGroup);
+ }
+
+ @Override
+ public PluginClassLoaderGroup registerAccessBackedGroup(ConfiguredPluginClassLoader classLoader, ClassLoaderAccess access) {
+ List<ConfiguredPluginClassLoader> allowedLoaders = new ArrayList<>();
+ for (ConfiguredPluginClassLoader configuredPluginClassLoader : this.globalGroup.getClassLoaders()) {
+ if (access.canAccess(configuredPluginClassLoader)) {
+ allowedLoaders.add(configuredPluginClassLoader);
+ }
+ }
+
+ return this.registerGroup(classLoader, new StaticPluginClassLoaderGroup(allowedLoaders, access, classLoader));
+ }
+
+ private PluginClassLoaderGroup registerGroup(ConfiguredPluginClassLoader classLoader, PluginClassLoaderGroup group) {
+ // Now add this classloader to any groups that allows it (includes global)
+ for (PluginClassLoaderGroup loaderGroup : this.groups) {
+ if (loaderGroup.getAccess().canAccess(classLoader)) {
+ loaderGroup.add(classLoader);
+ }
+ }
+
+ group = new LockingClassLoaderGroup(group);
+ this.groups.add(group);
+ return group;
+ }
+
+ @Override
+ public void unregisterClassloader(ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ this.globalGroup.remove(configuredPluginClassLoader);
+ this.groups.remove(configuredPluginClassLoader.getGroup());
+ for (PluginClassLoaderGroup group : this.groups) {
+ group.remove(configuredPluginClassLoader);
+ }
+ }
+
+ @Override
+ public boolean registerUnsafePlugin(ConfiguredPluginClassLoader pluginLoader) {
+ if (this.globalGroup.getClassLoaders().contains(pluginLoader)) {
+ return false;
+ } else {
+ this.globalGroup.add(pluginLoader);
+ return true;
+ }
+ }
+
+ // Debug only
+ @ApiStatus.Internal
+ public GlobalPluginClassLoaderGroup getGlobalGroup() {
+ return this.globalGroup;
+ }
+
+ // Debug only
+ @ApiStatus.Internal
+ public List<PluginClassLoaderGroup> getGroups() {
+ return this.groups;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/SimpleListPluginClassLoaderGroup.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/SimpleListPluginClassLoaderGroup.java
new file mode 100644
index 0000000000000000000000000000000000000000..23b6cb297f46c9c2b2944a3ab4031c31414620ad
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/SimpleListPluginClassLoaderGroup.java
@@ -0,0 +1,69 @@
+package io.papermc.paper.plugin.entrypoint.classloader.group;
+
+import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
+import io.papermc.paper.plugin.provider.classloader.PluginClassLoaderGroup;
+import org.jetbrains.annotations.ApiStatus;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+@ApiStatus.Internal
+public abstract class SimpleListPluginClassLoaderGroup implements PluginClassLoaderGroup {
+
+ private static final boolean DISABLE_CLASS_PRIORITIZATION = Boolean.getBoolean("Paper.DisableClassPrioritization");
+
+ protected final List<ConfiguredPluginClassLoader> classloaders;
+
+ protected SimpleListPluginClassLoaderGroup() {
+ this(new CopyOnWriteArrayList<>());
+ }
+
+ protected SimpleListPluginClassLoaderGroup(List<ConfiguredPluginClassLoader> classloaders) {
+ this.classloaders = classloaders;
+ }
+
+ @Override
+ public @Nullable Class<?> getClassByName(String name, boolean resolve, ConfiguredPluginClassLoader requester) {
+ if (!DISABLE_CLASS_PRIORITIZATION) {
+ try {
+ return this.lookupClass(name, false, requester); // First check the requester
+ } catch (ClassNotFoundException ignored) {
+ }
+ }
+
+ for (ConfiguredPluginClassLoader loader : this.classloaders) {
+ try {
+ return this.lookupClass(name, resolve, loader);
+ } catch (ClassNotFoundException ignored) {
+ }
+ }
+
+ return null;
+ }
+
+ protected Class<?> lookupClass(String name, boolean resolve, ConfiguredPluginClassLoader current) throws ClassNotFoundException {
+ return current.loadClass(name, resolve, false, true);
+ }
+
+ @Override
+ public void remove(ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ this.classloaders.remove(configuredPluginClassLoader);
+ }
+
+ @Override
+ public void add(ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ this.classloaders.add(configuredPluginClassLoader);
+ }
+
+ public List<ConfiguredPluginClassLoader> getClassLoaders() {
+ return classloaders;
+ }
+
+ @Override
+ public String toString() {
+ return "SimpleListPluginClassLoaderGroup{" +
+ "classloaders=" + this.classloaders +
+ '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/SingletonPluginClassLoaderGroup.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/SingletonPluginClassLoaderGroup.java
new file mode 100644
index 0000000000000000000000000000000000000000..3b670bd6b35ae7f56488a9b50df54709a0b28901
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/SingletonPluginClassLoaderGroup.java
@@ -0,0 +1,60 @@
+package io.papermc.paper.plugin.entrypoint.classloader.group;
+
+import io.papermc.paper.plugin.provider.classloader.ClassLoaderAccess;
+import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
+import io.papermc.paper.plugin.provider.classloader.PluginClassLoaderGroup;
+import org.jetbrains.annotations.ApiStatus;
+import org.jetbrains.annotations.Nullable;
+
+@ApiStatus.Internal
+public class SingletonPluginClassLoaderGroup implements PluginClassLoaderGroup {
+
+ private final ConfiguredPluginClassLoader configuredPluginClassLoader;
+ private final Access access;
+
+ public SingletonPluginClassLoaderGroup(ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ this.configuredPluginClassLoader = configuredPluginClassLoader;
+ this.access = new Access();
+ }
+
+ @Override
+ public @Nullable Class<?> getClassByName(String name, boolean resolve, ConfiguredPluginClassLoader requester) {
+ try {
+ return this.configuredPluginClassLoader.loadClass(name, resolve, false, true);
+ } catch (ClassNotFoundException ignored) {
+ }
+
+ return null;
+ }
+
+ @Override
+ public void remove(ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ }
+
+ @Override
+ public void add(ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ }
+
+ @Override
+ public ClassLoaderAccess getAccess() {
+ return this.access;
+ }
+
+ @ApiStatus.Internal
+ private class Access implements ClassLoaderAccess {
+
+ @Override
+ public boolean canAccess(ConfiguredPluginClassLoader classLoader) {
+ return SingletonPluginClassLoaderGroup.this.configuredPluginClassLoader == classLoader;
+ }
+
+ }
+
+ @Override
+ public String toString() {
+ return "SingletonPluginClassLoaderGroup{" +
+ "configuredPluginClassLoader=" + this.configuredPluginClassLoader +
+ ", access=" + this.access +
+ '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/SpigotPluginClassLoaderGroup.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/SpigotPluginClassLoaderGroup.java
new file mode 100644
index 0000000000000000000000000000000000000000..5a9f5b18e24a89dd642149a7a3d49390328b864b
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/SpigotPluginClassLoaderGroup.java
@@ -0,0 +1,58 @@
+package io.papermc.paper.plugin.entrypoint.classloader.group;
+
+import io.papermc.paper.plugin.provider.classloader.ClassLoaderAccess;
+import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
+import org.bukkit.plugin.java.PluginClassLoader;
+import org.jetbrains.annotations.ApiStatus;
+
+import java.util.function.Predicate;
+
+/**
+ * Spigot classloaders have the ability to see everything.
+ * However, libraries are ONLY shared depending on their dependencies.
+ */
+@ApiStatus.Internal
+public class SpigotPluginClassLoaderGroup extends SimpleListPluginClassLoaderGroup {
+
+ private final Predicate<ConfiguredPluginClassLoader> libraryClassloaderPredicate;
+ private final PluginClassLoader pluginClassLoader;
+
+ public SpigotPluginClassLoaderGroup(GlobalPluginClassLoaderGroup globalPluginClassLoaderGroup, Predicate<ConfiguredPluginClassLoader> libraryClassloaderPredicate, PluginClassLoader pluginClassLoader) {
+ super(globalPluginClassLoaderGroup.getClassLoaders());
+ this.libraryClassloaderPredicate = libraryClassloaderPredicate;
+ this.pluginClassLoader = pluginClassLoader;
+ }
+
+ // Mirrors global list
+ @Override
+ public void add(ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ }
+
+ @Override
+ public void remove(ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ }
+
+ // Don't allow other plugins to access spigot dependencies, they should instead reference the global list
+ @Override
+ public ClassLoaderAccess getAccess() {
+ return v -> false;
+ }
+
+ @Override
+ protected Class<?> lookupClass(String name, boolean resolve, ConfiguredPluginClassLoader current) throws ClassNotFoundException {
+ return current.loadClass(name, resolve, false, this.libraryClassloaderPredicate.test(current));
+ }
+
+ // DEBUG
+ public PluginClassLoader getPluginClassLoader() {
+ return pluginClassLoader;
+ }
+
+ @Override
+ public String toString() {
+ return "SpigotPluginClassLoaderGroup{" +
+ "libraryClassloaderPredicate=" + this.libraryClassloaderPredicate +
+ ", classloaders=" + this.classloaders +
+ '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/StaticPluginClassLoaderGroup.java b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/StaticPluginClassLoaderGroup.java
new file mode 100644
index 0000000000000000000000000000000000000000..2412155ddfd559023f42ff534b8f06a52588e1e0
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/classloader/group/StaticPluginClassLoaderGroup.java
@@ -0,0 +1,40 @@
+package io.papermc.paper.plugin.entrypoint.classloader.group;
+
+import io.papermc.paper.plugin.provider.classloader.ClassLoaderAccess;
+import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
+import org.jetbrains.annotations.ApiStatus;
+
+import java.util.List;
+
+@ApiStatus.Internal
+public class StaticPluginClassLoaderGroup extends SimpleListPluginClassLoaderGroup {
+
+ private final ClassLoaderAccess access;
+ // Debug only
+ private final ConfiguredPluginClassLoader mainClassloaderHolder;
+
+ public StaticPluginClassLoaderGroup(List<ConfiguredPluginClassLoader> classloaders, ClassLoaderAccess access, ConfiguredPluginClassLoader mainClassloaderHolder) {
+ super(classloaders);
+ this.access = access;
+ this.mainClassloaderHolder = mainClassloaderHolder;
+ }
+
+ @Override
+ public ClassLoaderAccess getAccess() {
+ return this.access;
+ }
+
+ // DEBUG
+ @ApiStatus.Internal
+ public ConfiguredPluginClassLoader getPluginClassloader() {
+ return this.mainClassloaderHolder;
+ }
+
+ @Override
+ public String toString() {
+ return "StaticPluginClassLoaderGroup{" +
+ "access=" + this.access +
+ ", classloaders=" + this.classloaders +
+ '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/BootstrapMetaDependencyTree.java b/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/BootstrapMetaDependencyTree.java
new file mode 100644
index 0000000000000000000000000000000000000000..74bf07be300d4893402614c9e9d9ac97dc574ac7
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/BootstrapMetaDependencyTree.java
@@ -0,0 +1,44 @@
+package io.papermc.paper.plugin.entrypoint.dependency;
+
+import com.google.common.graph.GraphBuilder;
+import com.google.common.graph.MutableGraph;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.configuration.PaperPluginMeta;
+
+public class BootstrapMetaDependencyTree extends MetaDependencyTree {
+ public BootstrapMetaDependencyTree() {
+ this(GraphBuilder.directed().build());
+ }
+
+ public BootstrapMetaDependencyTree(MutableGraph<String> graph) {
+ super(graph);
+ }
+
+ @Override
+ protected void registerDependencies(final String identifier, final PluginMeta meta) {
+ if (!(meta instanceof PaperPluginMeta paperPluginMeta)) {
+ throw new IllegalStateException("Only paper plugins can have a bootstrapper!");
+ }
+ // Build a validated provider's dependencies into the graph
+ for (String dependency : paperPluginMeta.getBoostrapDependencies().keySet()) {
+ this.graph.putEdge(identifier, dependency);
+ }
+ }
+
+ @Override
+ protected void unregisterDependencies(final String identifier, final PluginMeta meta) {
+ if (!(meta instanceof PaperPluginMeta paperPluginMeta)) {
+ throw new IllegalStateException("PluginMeta must be a PaperPluginMeta");
+ }
+
+ // Build a validated provider's dependencies into the graph
+ for (String dependency : paperPluginMeta.getBoostrapDependencies().keySet()) {
+ this.graph.removeEdge(identifier, dependency);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "BootstrapDependencyTree{" + "graph=" + this.graph + '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/DependencyContextHolder.java b/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/DependencyContextHolder.java
new file mode 100644
index 0000000000000000000000000000000000000000..f43295fdeaa587cf30c35a1d545167071d58ce4b
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/DependencyContextHolder.java
@@ -0,0 +1,9 @@
+package io.papermc.paper.plugin.entrypoint.dependency;
+
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+
+public interface DependencyContextHolder {
+
+ void setContext(DependencyContext context);
+
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/GraphDependencyContext.java b/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/GraphDependencyContext.java
new file mode 100644
index 0000000000000000000000000000000000000000..a2fa8406bc3f0dcab6805633ae984d031d24692a
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/GraphDependencyContext.java
@@ -0,0 +1,54 @@
+package io.papermc.paper.plugin.entrypoint.dependency;
+
+import com.google.common.graph.Graph;
+import com.google.common.graph.Graphs;
+import com.google.common.graph.MutableGraph;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+
+import java.util.Set;
+
+@SuppressWarnings("UnstableApiUsage")
+public class GraphDependencyContext implements DependencyContext {
+
+ private final MutableGraph<String> dependencyGraph;
+
+ public GraphDependencyContext(MutableGraph<String> dependencyGraph) {
+ this.dependencyGraph = dependencyGraph;
+ }
+
+ @Override
+ public boolean isTransitiveDependency(PluginMeta plugin, PluginMeta depend) {
+ String pluginIdentifier = plugin.getName();
+
+ if (this.dependencyGraph.nodes().contains(pluginIdentifier)) {
+ Set<String> reachableNodes = Graphs.reachableNodes(this.dependencyGraph, pluginIdentifier);
+ if (reachableNodes.contains(depend.getName())) {
+ return true;
+ }
+ for (String provided : depend.getProvidedPlugins()) {
+ if (reachableNodes.contains(provided)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean hasDependency(String pluginIdentifier) {
+ return this.dependencyGraph.nodes().contains(pluginIdentifier);
+ }
+
+ public MutableGraph<String> getDependencyGraph() {
+ return dependencyGraph;
+ }
+
+ @Override
+ public String toString() {
+ return "GraphDependencyContext{" +
+ "dependencyGraph=" + this.dependencyGraph +
+ '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/MetaDependencyTree.java b/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/MetaDependencyTree.java
new file mode 100644
index 0000000000000000000000000000000000000000..461ef285764aac88ced32be5e650b48e8fbc6bfd
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/MetaDependencyTree.java
@@ -0,0 +1,110 @@
+package io.papermc.paper.plugin.entrypoint.dependency;
+
+import com.google.common.graph.GraphBuilder;
+import com.google.common.graph.Graphs;
+import com.google.common.graph.MutableGraph;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+import org.jetbrains.annotations.NotNull;
+import java.util.HashSet;
+import java.util.Set;
+
+public abstract class MetaDependencyTree implements DependencyContext {
+
+ protected final MutableGraph<String> graph;
+
+ // We need to upkeep a separate collection since when populating
+ // a graph it adds nodes even if they are not present
+ protected final Set<String> dependencies = new HashSet<>();
+
+ public MetaDependencyTree() {
+ this(GraphBuilder.directed().build());
+ }
+
+ public MetaDependencyTree(MutableGraph<String> graph) {
+ this.graph = graph;
+ }
+
+ public void add(PluginMeta configuration) {
+ String identifier = configuration.getName();
+ // Build a validated provider's dependencies into the graph
+ this.registerDependencies(identifier, configuration);
+
+ this.graph.addNode(identifier); // Make sure dependencies at least have a node
+
+ // Add the provided plugins to the graph as well
+ for (String provides : configuration.getProvidedPlugins()) {
+ this.graph.putEdge(identifier, provides);
+ this.dependencies.add(provides);
+ }
+ this.dependencies.add(identifier);
+ }
+
+ protected abstract void registerDependencies(String identifier, PluginMeta meta);
+
+ public void remove(PluginMeta configuration) {
+ String identifier = configuration.getName();
+ // Remove a validated provider's dependencies into the graph
+ this.unregisterDependencies(identifier, configuration);
+
+ this.graph.removeNode(identifier); // Remove root node
+
+ // Remove the provided plugins to the graph as well
+ for (String provides : configuration.getProvidedPlugins()) {
+ this.graph.removeEdge(identifier, provides);
+ this.dependencies.remove(provides);
+ }
+ this.dependencies.remove(identifier);
+ }
+
+ protected abstract void unregisterDependencies(String identifier, PluginMeta meta);
+
+ @Override
+ public boolean isTransitiveDependency(@NotNull PluginMeta plugin, @NotNull PluginMeta depend) {
+ String pluginIdentifier = plugin.getName();
+
+ if (this.graph.nodes().contains(pluginIdentifier)) {
+ Set<String> reachableNodes = Graphs.reachableNodes(this.graph, pluginIdentifier);
+ if (reachableNodes.contains(depend.getName())) {
+ return true;
+ }
+ for (String provided : depend.getProvidedPlugins()) {
+ if (reachableNodes.contains(provided)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean hasDependency(@NotNull String pluginIdentifier) {
+ return this.dependencies.contains(pluginIdentifier);
+ }
+
+ public void addDirectDependency(String dependency) {
+ this.dependencies.add(dependency);
+ }
+
+ @Override
+ public String toString() {
+ return "SimpleDependencyTree{" +
+ "graph=" + this.graph +
+ '}';
+ }
+
+ public MutableGraph<String> getGraph() {
+ return graph;
+ }
+
+ public void add(PluginProvider<?> provider) {
+ this.add(provider.getMeta());
+ }
+
+ public void remove(PluginProvider<?> provider) {
+ this.remove(provider.getMeta());
+ }
+
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/SimpleMetaDependencyTree.java b/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/SimpleMetaDependencyTree.java
new file mode 100644
index 0000000000000000000000000000000000000000..910caf78636769977dff55dd048c0150a36d218d
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/dependency/SimpleMetaDependencyTree.java
@@ -0,0 +1,40 @@
+package io.papermc.paper.plugin.entrypoint.dependency;
+
+import com.google.common.graph.GraphBuilder;
+import com.google.common.graph.Graphs;
+import com.google.common.graph.MutableGraph;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class SimpleMetaDependencyTree extends MetaDependencyTree {
+
+ public SimpleMetaDependencyTree() {
+ }
+
+ public SimpleMetaDependencyTree(final MutableGraph<String> graph) {
+ super(graph);
+ }
+
+ @Override
+ protected void registerDependencies(final String identifier, final PluginMeta meta) {
+ for (String dependency : meta.getPluginDependencies()) {
+ this.graph.putEdge(identifier, dependency);
+ }
+ for (String dependency : meta.getPluginSoftDependencies()) {
+ this.graph.putEdge(identifier, dependency);
+ }
+ }
+
+ @Override
+ protected void unregisterDependencies(final String identifier, final PluginMeta meta) {
+ for (String dependency : meta.getPluginDependencies()) {
+ this.graph.removeEdge(identifier, dependency);
+ }
+ for (String dependency : meta.getPluginSoftDependencies()) {
+ this.graph.removeEdge(identifier, dependency);
+ }
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/JohnsonSimpleCycles.java b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/JohnsonSimpleCycles.java
new file mode 100644
index 0000000000000000000000000000000000000000..a9bca905eba67972e4d1b07b1d243272b62fec66
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/JohnsonSimpleCycles.java
@@ -0,0 +1,354 @@
+/*
+ * (C) Copyright 2013-2021, by Nikolay Ognyanov and Contributors.
+ *
+ * JGraphT : a free Java graph-theory library
+ *
+ * See the CONTRIBUTORS.md file distributed with this work for additional
+ * information regarding copyright ownership.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License 2.0 which is available at
+ * http://www.eclipse.org/legal/epl-2.0, or the
+ * GNU Lesser General Public License v2.1 or later
+ * which is available at
+ * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.
+ *
+ * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later
+ */
+
+// MODIFICATIONS:
+// - Modified to use a guava graph directly
+
+package io.papermc.paper.plugin.entrypoint.strategy;
+
+import com.google.common.base.Preconditions;
+import com.google.common.graph.Graph;
+import com.google.common.graph.GraphBuilder;
+import com.google.common.graph.MutableGraph;
+import com.mojang.datafixers.util.Pair;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+
+/**
+ * Find all simple cycles of a directed graph using the Johnson's algorithm.
+ *
+ * <p>
+ * See:<br>
+ * D.B.Johnson, Finding all the elementary circuits of a directed graph, SIAM J. Comput., 4 (1975),
+ * pp. 77-84.
+ *
+ * @param <V> the vertex type.
+ *
+ * @author Nikolay Ognyanov
+ */
+public class JohnsonSimpleCycles<V>
+{
+ // The graph.
+ private Graph<V> graph;
+
+ // The main state of the algorithm.
+ private Consumer<List<V>> cycleConsumer = null;
+ private BiConsumer<V, V> cycleVertexSuccessorConsumer = null; // Paper
+ private V[] iToV = null;
+ private Map<V, Integer> vToI = null;
+ private Set<V> blocked = null;
+ private Map<V, Set<V>> bSets = null;
+ private ArrayDeque<V> stack = null;
+
+ // The state of the embedded Tarjan SCC algorithm.
+ private List<Set<V>> foundSCCs = null;
+ private int index = 0;
+ private Map<V, Integer> vIndex = null;
+ private Map<V, Integer> vLowlink = null;
+ private ArrayDeque<V> path = null;
+ private Set<V> pathSet = null;
+
+ /**
+ * Create a simple cycle finder for the specified graph.
+ *
+ * @param graph - the DirectedGraph in which to find cycles.
+ *
+ * @throws IllegalArgumentException if the graph argument is <code>
+ * null</code>.
+ */
+ public JohnsonSimpleCycles(Graph<V> graph)
+ {
+ Preconditions.checkState(graph.isDirected(), "Graph must be directed");
+ this.graph = graph;
+ }
+
+ /**
+ * Find the simple cycles of the graph.
+ *
+ * @return The list of all simple cycles. Possibly empty but never <code>null</code>.
+ */
+ public List<List<V>> findAndRemoveSimpleCycles()
+ {
+ List<List<V>> result = new ArrayList<>();
+ findSimpleCycles(result::add, (v, s) -> ((MutableGraph<V>) graph).removeEdge(v, s)); // Paper
+ return result;
+ }
+
+ /**
+ * Find the simple cycles of the graph.
+ *
+ * @param consumer Consumer that will be called with each cycle found.
+ */
+ public void findSimpleCycles(Consumer<List<V>> consumer, BiConsumer<V, V> vertexSuccessorConsumer) // Paper
+ {
+ if (graph == null) {
+ throw new IllegalArgumentException("Null graph.");
+ }
+ cycleVertexSuccessorConsumer = vertexSuccessorConsumer; // Paper
+ initState(consumer);
+
+ int startIndex = 0;
+ int size = graph.nodes().size();
+ while (startIndex < size) {
+ Pair<Graph<V>, Integer> minSCCGResult = findMinSCSG(startIndex);
+ if (minSCCGResult != null) {
+ startIndex = minSCCGResult.getSecond();
+ Graph<V> scg = minSCCGResult.getFirst();
+ V startV = toV(startIndex);
+ for (V v : scg.successors(startV)) {
+ blocked.remove(v);
+ getBSet(v).clear();
+ }
+ findCyclesInSCG(startIndex, startIndex, scg);
+ startIndex++;
+ } else {
+ break;
+ }
+ }
+
+ clearState();
+ }
+
+ private Pair<Graph<V>, Integer> findMinSCSG(int startIndex)
+ {
+ /*
+ * Per Johnson : "adjacency structure of strong component $K$ with least vertex in subgraph
+ * of $G$ induced by $(s, s + 1, n)$". Or in contemporary terms: the strongly connected
+ * component of the subgraph induced by $(v_1, \dotso ,v_n)$ which contains the minimum
+ * (among those SCCs) vertex index. We return that index together with the graph.
+ */
+ initMinSCGState();
+
+ List<Set<V>> foundSCCs = findSCCS(startIndex);
+
+ // find the SCC with the minimum index
+ int minIndexFound = Integer.MAX_VALUE;
+ Set<V> minSCC = null;
+ for (Set<V> scc : foundSCCs) {
+ for (V v : scc) {
+ int t = toI(v);
+ if (t < minIndexFound) {
+ minIndexFound = t;
+ minSCC = scc;
+ }
+ }
+ }
+ if (minSCC == null) {
+ return null;
+ }
+
+ // build a graph for the SCC found
+ MutableGraph<V> dependencyGraph = GraphBuilder.directed().allowsSelfLoops(true).build();
+
+ for (V v : minSCC) {
+ for (V w : minSCC) {
+ if (graph.hasEdgeConnecting(v, w)) {
+ dependencyGraph.putEdge(v, w);
+ }
+ }
+ }
+
+ Pair<Graph<V>, Integer> result = Pair.of(dependencyGraph, minIndexFound);
+ clearMinSCCState();
+ return result;
+ }
+
+ private List<Set<V>> findSCCS(int startIndex)
+ {
+ // Find SCCs in the subgraph induced
+ // by vertices startIndex and beyond.
+ // A call to StrongConnectivityAlgorithm
+ // would be too expensive because of the
+ // need to materialize the subgraph.
+ // So - do a local search by the Tarjan's
+ // algorithm and pretend that vertices
+ // with an index smaller than startIndex
+ // do not exist.
+ for (V v : graph.nodes()) {
+ int vI = toI(v);
+ if (vI < startIndex) {
+ continue;
+ }
+ if (!vIndex.containsKey(v)) {
+ getSCCs(startIndex, vI);
+ }
+ }
+ List<Set<V>> result = foundSCCs;
+ foundSCCs = null;
+ return result;
+ }
+
+ private void getSCCs(int startIndex, int vertexIndex)
+ {
+ V vertex = toV(vertexIndex);
+ vIndex.put(vertex, index);
+ vLowlink.put(vertex, index);
+ index++;
+ path.push(vertex);
+ pathSet.add(vertex);
+
+ Set<V> edges = graph.successors(vertex);
+ for (V successor : edges) {
+ int successorIndex = toI(successor);
+ if (successorIndex < startIndex) {
+ continue;
+ }
+ if (!vIndex.containsKey(successor)) {
+ getSCCs(startIndex, successorIndex);
+ vLowlink.put(vertex, Math.min(vLowlink.get(vertex), vLowlink.get(successor)));
+ } else if (pathSet.contains(successor)) {
+ vLowlink.put(vertex, Math.min(vLowlink.get(vertex), vIndex.get(successor)));
+ }
+ }
+ if (vLowlink.get(vertex).equals(vIndex.get(vertex))) {
+ Set<V> result = new HashSet<>();
+ V temp;
+ do {
+ temp = path.pop();
+ pathSet.remove(temp);
+ result.add(temp);
+ } while (!vertex.equals(temp));
+ if (result.size() == 1) {
+ V v = result.iterator().next();
+ if (graph.edges().contains(vertex)) {
+ foundSCCs.add(result);
+ }
+ } else {
+ foundSCCs.add(result);
+ }
+ }
+ }
+
+ private boolean findCyclesInSCG(int startIndex, int vertexIndex, Graph<V> scg)
+ {
+ /*
+ * Find cycles in a strongly connected graph per Johnson.
+ */
+ boolean foundCycle = false;
+ V vertex = toV(vertexIndex);
+ stack.push(vertex);
+ blocked.add(vertex);
+
+ for (V successor : scg.successors(vertex)) {
+ int successorIndex = toI(successor);
+ if (successorIndex == startIndex) {
+ List<V> cycle = new ArrayList<>(stack.size());
+ stack.descendingIterator().forEachRemaining(cycle::add);
+ cycleConsumer.accept(cycle);
+ cycleVertexSuccessorConsumer.accept(vertex, successor); // Paper
+ //foundCycle = true; // Paper
+ } else if (!blocked.contains(successor)) {
+ boolean gotCycle = findCyclesInSCG(startIndex, successorIndex, scg);
+ foundCycle = foundCycle || gotCycle;
+ }
+ }
+ if (foundCycle) {
+ unblock(vertex);
+ } else {
+ for (V w : scg.successors(vertex)) {
+ Set<V> bSet = getBSet(w);
+ bSet.add(vertex);
+ }
+ }
+ stack.pop();
+ return foundCycle;
+ }
+
+ private void unblock(V vertex)
+ {
+ blocked.remove(vertex);
+ Set<V> bSet = getBSet(vertex);
+ while (bSet.size() > 0) {
+ V w = bSet.iterator().next();
+ bSet.remove(w);
+ if (blocked.contains(w)) {
+ unblock(w);
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void initState(Consumer<List<V>> consumer)
+ {
+ cycleConsumer = consumer;
+ iToV = (V[]) graph.nodes().toArray();
+ vToI = new HashMap<>();
+ blocked = new HashSet<>();
+ bSets = new HashMap<>();
+ stack = new ArrayDeque<>();
+
+ for (int i = 0; i < iToV.length; i++) {
+ vToI.put(iToV[i], i);
+ }
+ }
+
+ private void clearState()
+ {
+ cycleConsumer = null;
+ iToV = null;
+ vToI = null;
+ blocked = null;
+ bSets = null;
+ stack = null;
+ }
+
+ private void initMinSCGState()
+ {
+ index = 0;
+ foundSCCs = new ArrayList<>();
+ vIndex = new HashMap<>();
+ vLowlink = new HashMap<>();
+ path = new ArrayDeque<>();
+ pathSet = new HashSet<>();
+ }
+
+ private void clearMinSCCState()
+ {
+ index = 0;
+ foundSCCs = null;
+ vIndex = null;
+ vLowlink = null;
+ path = null;
+ pathSet = null;
+ }
+
+ private Integer toI(V vertex)
+ {
+ return vToI.get(vertex);
+ }
+
+ private V toV(Integer i)
+ {
+ return iToV[i];
+ }
+
+ private Set<V> getBSet(V v)
+ {
+ // B sets typically not all needed,
+ // so instantiate lazily.
+ return bSets.computeIfAbsent(v, k -> new HashSet<>());
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/LegacyPluginLoadingStrategy.java b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/LegacyPluginLoadingStrategy.java
new file mode 100644
index 0000000000000000000000000000000000000000..f59f48654eaa299bcac862991b1e2e622264639b
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/LegacyPluginLoadingStrategy.java
@@ -0,0 +1,271 @@
+package io.papermc.paper.plugin.entrypoint.strategy;
+
+import com.google.common.graph.GraphBuilder;
+import com.google.common.graph.MutableGraph;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.entrypoint.dependency.GraphDependencyContext;
+import io.papermc.paper.plugin.entrypoint.dependency.MetaDependencyTree;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.type.paper.PaperPluginParent;
+import org.bukkit.plugin.UnknownDependencyException;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+@SuppressWarnings("UnstableApiUsage")
+public class LegacyPluginLoadingStrategy<T> implements ProviderLoadingStrategy<T> {
+
+ private static final Logger LOGGER = Logger.getLogger("LegacyPluginLoadingStrategy");
+ private final ProviderConfiguration<T> configuration;
+
+ public LegacyPluginLoadingStrategy(ProviderConfiguration<T> onLoad) {
+ this.configuration = onLoad;
+ }
+
+ @Override
+ public List<ProviderPair<T>> loadProviders(List<PluginProvider<T>> providers, MetaDependencyTree dependencyTree) {
+ List<ProviderPair<T>> javapluginsLoaded = new ArrayList<>();
+ MutableGraph<String> dependencyGraph = dependencyTree.getGraph();
+
+ Map<String, PluginProvider<T>> providersToLoad = new HashMap<>();
+ Set<String> loadedPlugins = new HashSet<>();
+ Map<String, String> pluginsProvided = new HashMap<>();
+ Map<String, Collection<String>> dependencies = new HashMap<>();
+ Map<String, Collection<String>> softDependencies = new HashMap<>();
+
+ for (PluginProvider<T> provider : providers) {
+ PluginMeta configuration = provider.getMeta();
+
+ PluginProvider<T> replacedProvider = providersToLoad.put(configuration.getName(), provider);
+ dependencyTree.addDirectDependency(configuration.getName()); // add to dependency tree
+ if (replacedProvider != null) {
+ LOGGER.severe(String.format(
+ "Ambiguous plugin name `%s' for files `%s' and `%s' in `%s'",
+ configuration.getName(),
+ provider.getSource(),
+ replacedProvider.getSource(),
+ replacedProvider.getParentSource()
+ ));
+ }
+
+ String removedProvided = pluginsProvided.remove(configuration.getName());
+ if (removedProvided != null) {
+ LOGGER.warning(String.format(
+ "Ambiguous plugin name `%s'. It is also provided by `%s'",
+ configuration.getName(),
+ removedProvided
+ ));
+ }
+
+ for (String provided : configuration.getProvidedPlugins()) {
+ PluginProvider<T> pluginProvider = providersToLoad.get(provided);
+
+ if (pluginProvider != null) {
+ LOGGER.warning(String.format(
+ "`%s provides `%s' while this is also the name of `%s' in `%s'",
+ provider.getSource(),
+ provided,
+ pluginProvider.getSource(),
+ provider.getParentSource()
+ ));
+ } else {
+ String replacedPlugin = pluginsProvided.put(provided, configuration.getName());
+ dependencyTree.addDirectDependency(provided); // add to dependency tree
+ if (replacedPlugin != null) {
+ LOGGER.warning(String.format(
+ "`%s' is provided by both `%s' and `%s'",
+ provided,
+ configuration.getName(),
+ replacedPlugin
+ ));
+ }
+ }
+ }
+
+ Collection<String> softDependencySet = provider.getMeta().getPluginSoftDependencies();
+ if (softDependencySet != null && !softDependencySet.isEmpty()) {
+ if (softDependencies.containsKey(configuration.getName())) {
+ // Duplicates do not matter, they will be removed together if applicable
+ softDependencies.get(configuration.getName()).addAll(softDependencySet);
+ } else {
+ softDependencies.put(configuration.getName(), new LinkedList<String>(softDependencySet));
+ }
+
+ for (String depend : softDependencySet) {
+ dependencyGraph.putEdge(configuration.getName(), depend);
+ }
+ }
+
+ Collection<String> dependencySet = provider.getMeta().getPluginDependencies();
+ if (dependencySet != null && !dependencySet.isEmpty()) {
+ dependencies.put(configuration.getName(), new LinkedList<String>(dependencySet));
+
+ for (String depend : dependencySet) {
+ dependencyGraph.putEdge(configuration.getName(), depend);
+ }
+ }
+
+ Collection<String> loadBeforeSet = provider.getMeta().getLoadBeforePlugins();
+ if (loadBeforeSet != null && !loadBeforeSet.isEmpty()) {
+ for (String loadBeforeTarget : loadBeforeSet) {
+ if (softDependencies.containsKey(loadBeforeTarget)) {
+ softDependencies.get(loadBeforeTarget).add(configuration.getName());
+ } else {
+ // softDependencies is never iterated, so 'ghost' plugins aren't an issue
+ Collection<String> shortSoftDependency = new LinkedList<String>();
+ shortSoftDependency.add(configuration.getName());
+ softDependencies.put(loadBeforeTarget, shortSoftDependency);
+ }
+
+ dependencyGraph.putEdge(loadBeforeTarget, configuration.getName());
+ }
+ }
+ }
+
+ while (!providersToLoad.isEmpty()) {
+ boolean missingDependency = true;
+ Iterator<Map.Entry<String, PluginProvider<T>>> providerIterator = providersToLoad.entrySet().iterator();
+
+ while (providerIterator.hasNext()) {
+ Map.Entry<String, PluginProvider<T>> entry = providerIterator.next();
+ String providerIdentifier = entry.getKey();
+
+ if (dependencies.containsKey(providerIdentifier)) {
+ Iterator<String> dependencyIterator = dependencies.get(providerIdentifier).iterator();
+ final Set<String> missingHardDependencies = new HashSet<>(dependencies.get(providerIdentifier).size()); // Paper - list all missing hard depends
+
+ while (dependencyIterator.hasNext()) {
+ String dependency = dependencyIterator.next();
+
+ // Dependency loaded
+ if (loadedPlugins.contains(dependency)) {
+ dependencyIterator.remove();
+
+ // We have a dependency not found
+ } else if (!providersToLoad.containsKey(dependency) && !pluginsProvided.containsKey(dependency)) {
+ // Paper start
+ missingHardDependencies.add(dependency);
+ }
+ }
+ if (!missingHardDependencies.isEmpty()) {
+ // Paper end
+ missingDependency = false;
+ providerIterator.remove();
+ pluginsProvided.values().removeIf(s -> s.equals(providerIdentifier)); // Paper - remove provided plugins
+ softDependencies.remove(providerIdentifier);
+ dependencies.remove(providerIdentifier);
+
+ LOGGER.log(
+ Level.SEVERE,
+ "Could not load '" + entry.getValue().getSource() + "' in folder '" + entry.getValue().getParentSource() + "'", // Paper
+ new UnknownDependencyException(missingHardDependencies, providerIdentifier)); // Paper
+ }
+
+ if (dependencies.containsKey(providerIdentifier) && dependencies.get(providerIdentifier).isEmpty()) {
+ dependencies.remove(providerIdentifier);
+ }
+ }
+ if (softDependencies.containsKey(providerIdentifier)) {
+ Iterator<String> softDependencyIterator = softDependencies.get(providerIdentifier).iterator();
+
+ while (softDependencyIterator.hasNext()) {
+ String softDependency = softDependencyIterator.next();
+
+ // Soft depend is no longer around
+ if (!providersToLoad.containsKey(softDependency) && !pluginsProvided.containsKey(softDependency)) {
+ softDependencyIterator.remove();
+ }
+ }
+
+ if (softDependencies.get(providerIdentifier).isEmpty()) {
+ softDependencies.remove(providerIdentifier);
+ }
+ }
+ if (!(dependencies.containsKey(providerIdentifier) || softDependencies.containsKey(providerIdentifier)) && providersToLoad.containsKey(providerIdentifier)) {
+ // We're clear to load, no more soft or hard dependencies left
+ PluginProvider<T> file = providersToLoad.get(providerIdentifier);
+ providerIterator.remove();
+ pluginsProvided.values().removeIf(s -> s.equals(providerIdentifier)); // Paper - remove provided plugins
+ missingDependency = false;
+
+ try {
+ this.configuration.applyContext(file, dependencyTree);
+ T loadedPlugin = file.createInstance();
+ this.warnIfPaperPlugin(file);
+
+ if (this.configuration.load(file, loadedPlugin)) {
+ loadedPlugins.add(file.getMeta().getName());
+ loadedPlugins.addAll(file.getMeta().getProvidedPlugins());
+ javapluginsLoaded.add(new ProviderPair<>(file, loadedPlugin));
+ }
+
+ } catch (Throwable ex) {
+ LOGGER.log(Level.SEVERE, "Could not load '" + file.getSource() + "' in folder '" + file.getParentSource() + "'", ex); // Paper
+ }
+ }
+ }
+
+ if (missingDependency) {
+ // We now iterate over plugins until something loads
+ // This loop will ignore soft dependencies
+ providerIterator = providersToLoad.entrySet().iterator();
+
+ while (providerIterator.hasNext()) {
+ Map.Entry<String, PluginProvider<T>> entry = providerIterator.next();
+ String plugin = entry.getKey();
+
+ if (!dependencies.containsKey(plugin)) {
+ softDependencies.remove(plugin);
+ missingDependency = false;
+ PluginProvider<T> file = entry.getValue();
+ providerIterator.remove();
+
+ try {
+ this.configuration.applyContext(file, dependencyTree);
+ T loadedPlugin = file.createInstance();
+ this.warnIfPaperPlugin(file);
+
+ if (this.configuration.load(file, loadedPlugin)) {
+ loadedPlugins.add(file.getMeta().getName());
+ loadedPlugins.addAll(file.getMeta().getProvidedPlugins());
+ javapluginsLoaded.add(new ProviderPair<>(file, loadedPlugin));
+ }
+ break;
+ } catch (Throwable ex) {
+ LOGGER.log(Level.SEVERE, "Could not load '" + file.getSource() + "' in folder '" + file.getParentSource() + "'", ex); // Paper
+ }
+ }
+ }
+ // We have no plugins left without a depend
+ if (missingDependency) {
+ softDependencies.clear();
+ dependencies.clear();
+ Iterator<PluginProvider<T>> failedPluginIterator = providersToLoad.values().iterator();
+
+ while (failedPluginIterator.hasNext()) {
+ PluginProvider<T> file = failedPluginIterator.next();
+ failedPluginIterator.remove();
+ LOGGER.log(Level.SEVERE, "Could not load '" + file.getSource() + "' in folder '" + file.getParentSource() + "': circular dependency detected"); // Paper
+ }
+ }
+ }
+ }
+
+ return javapluginsLoaded;
+ }
+
+ private void warnIfPaperPlugin(PluginProvider<T> provider) {
+ if (provider instanceof PaperPluginParent.PaperServerPluginProvider) {
+ provider.getLogger().warn("Loading Paper plugin in the legacy plugin loading logic. This is not recommended and may introduce some differences into load order. It's highly recommended you move away from this if you are wanting to use Paper plugins.");
+ }
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/PluginGraphCycleException.java b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/PluginGraphCycleException.java
new file mode 100644
index 0000000000000000000000000000000000000000..2ea978ac957849260e7ca69c9ff56588d0ccc41b
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/PluginGraphCycleException.java
@@ -0,0 +1,19 @@
+package io.papermc.paper.plugin.entrypoint.strategy;
+
+import java.util.List;
+
+/**
+ * Indicates a dependency cycle within a provider loading sequence.
+ */
+public class PluginGraphCycleException extends RuntimeException {
+
+ private final List<List<String>> cycles;
+
+ public PluginGraphCycleException(List<List<String>> cycles) {
+ this.cycles = cycles;
+ }
+
+ public List<List<String>> getCycles() {
+ return this.cycles;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/ProviderConfiguration.java b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/ProviderConfiguration.java
new file mode 100644
index 0000000000000000000000000000000000000000..67c4ef672ee509deba2b4bcaac42d9db24d4c89a
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/ProviderConfiguration.java
@@ -0,0 +1,25 @@
+package io.papermc.paper.plugin.entrypoint.strategy;
+
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+
+/**
+ * Used to share code with the modern and legacy plugin load strategy.
+ *
+ * @param <T>
+ */
+public interface ProviderConfiguration<T> {
+
+ void applyContext(PluginProvider<T> provider, DependencyContext dependencyContext);
+
+ boolean load(PluginProvider<T> provider, T provided);
+
+ default boolean preloadProvider(PluginProvider<T> provider) {
+ return true;
+ }
+
+ default void onGenericError(PluginProvider<T> provider) {
+
+ }
+
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/ProviderLoadingStrategy.java b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/ProviderLoadingStrategy.java
new file mode 100644
index 0000000000000000000000000000000000000000..a79eb9e2c8c42ecf823aecbd859576415e9981dc
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/ProviderLoadingStrategy.java
@@ -0,0 +1,22 @@
+package io.papermc.paper.plugin.entrypoint.strategy;
+
+import io.papermc.paper.plugin.entrypoint.dependency.MetaDependencyTree;
+import io.papermc.paper.plugin.provider.PluginProvider;
+
+import java.util.List;
+
+/**
+ * Used by a {@link io.papermc.paper.plugin.storage.SimpleProviderStorage} to load plugin providers in a certain order.
+ * <p>
+ * Returns providers loaded.
+ *
+ * @param <P> provider type
+ */
+public interface ProviderLoadingStrategy<P> {
+
+ List<ProviderPair<P>> loadProviders(List<PluginProvider<P>> providers, MetaDependencyTree dependencyTree);
+
+ record ProviderPair<P>(PluginProvider<P> provider, P provided) {
+
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/TopographicGraphSorter.java b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/TopographicGraphSorter.java
new file mode 100644
index 0000000000000000000000000000000000000000..52a110044611c8a0ace6d49549e8acc16cbbe83d
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/TopographicGraphSorter.java
@@ -0,0 +1,58 @@
+package io.papermc.paper.plugin.entrypoint.strategy;
+
+import com.google.common.graph.Graph;
+import it.unimi.dsi.fastutil.objects.Object2IntMap;
+import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.List;
+
+public final class TopographicGraphSorter {
+
+ // Topographically sort dependencies
+ public static <N> List<N> sortGraph(Graph<N> graph) throws PluginGraphCycleException {
+ List<N> sorted = new ArrayList<>();
+ Deque<N> roots = new ArrayDeque<>();
+ Object2IntMap<N> nonRoots = new Object2IntOpenHashMap<>();
+
+ for (N node : graph.nodes()) {
+ // Is a node being referred to by any other nodes?
+ int degree = graph.inDegree(node);
+ if (degree == 0) {
+ // Is a root
+ roots.add(node);
+ } else {
+ // Isn't a root, the number represents how many nodes connect to it.
+ nonRoots.put(node, degree);
+ }
+ }
+
+ // Pick from nodes that aren't referred to anywhere else
+ N next;
+ while ((next = roots.poll()) != null) {
+ for (N successor : graph.successors(next)) {
+ // Traverse through, moving down a degree
+ int newInDegree = nonRoots.removeInt(successor) - 1;
+
+ if (newInDegree == 0) {
+ roots.add(successor);
+ } else {
+ nonRoots.put(successor, newInDegree);
+ }
+
+ }
+ sorted.add(next);
+ }
+
+ if (!nonRoots.isEmpty()) {
+ throw new GraphCycleException();
+ }
+
+ return sorted;
+ }
+
+ public static final class GraphCycleException extends RuntimeException {
+
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/modern/LoadOrderTree.java b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/modern/LoadOrderTree.java
new file mode 100644
index 0000000000000000000000000000000000000000..e3f01ec40a704acb46f7ac31d500e9d0185e3db9
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/modern/LoadOrderTree.java
@@ -0,0 +1,121 @@
+package io.papermc.paper.plugin.entrypoint.strategy.modern;
+
+import com.google.common.collect.Lists;
+import com.google.common.graph.MutableGraph;
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.entrypoint.strategy.JohnsonSimpleCycles;
+import io.papermc.paper.plugin.entrypoint.strategy.PluginGraphCycleException;
+import io.papermc.paper.plugin.entrypoint.strategy.TopographicGraphSorter;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.configuration.LoadOrderConfiguration;
+import io.papermc.paper.plugin.provider.configuration.PaperPluginMeta;
+import io.papermc.paper.plugin.provider.type.spigot.SpigotPluginProvider;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+class LoadOrderTree {
+
+ private static final Logger LOGGER = LogUtils.getClassLogger();
+
+ private final Map<String, PluginProvider<?>> providerMap;
+ private final MutableGraph<String> graph;
+
+ public LoadOrderTree(Map<String, PluginProvider<?>> providerMapMirror, MutableGraph<String> graph) {
+ this.providerMap = providerMapMirror;
+ this.graph = graph;
+ }
+
+ public void add(PluginProvider<?> provider) {
+ LoadOrderConfiguration configuration = provider.createConfiguration(this.providerMap);
+
+ // Build a validated provider's load order changes
+ String identifier = configuration.getMeta().getName();
+ for (String dependency : configuration.getLoadAfter()) {
+ if (this.providerMap.containsKey(dependency)) {
+ this.graph.putEdge(identifier, dependency);
+ }
+ }
+
+ for (String loadBeforeTarget : configuration.getLoadBefore()) {
+ if (this.providerMap.containsKey(loadBeforeTarget)) {
+ this.graph.putEdge(loadBeforeTarget, identifier);
+ }
+ }
+
+ this.graph.addNode(identifier); // Make sure load order has at least one node
+ }
+
+ public List<String> getLoadOrder() throws PluginGraphCycleException {
+ List<String> reversedTopographicSort;
+ try {
+ reversedTopographicSort = Lists.reverse(TopographicGraphSorter.sortGraph(this.graph));
+ } catch (TopographicGraphSorter.GraphCycleException exception) {
+ List<List<String>> cycles = new JohnsonSimpleCycles<>(this.graph).findAndRemoveSimpleCycles();
+
+ // Only log an error if at least non-Spigot plugin is present in the cycle
+ // Due to Spigot plugin metadata making no distinction between load order and dependencies (= class loader access), cycles are an unfortunate reality we have to deal with
+ Set<String> cyclingPlugins = new HashSet<>();
+ cycles.forEach(cyclingPlugins::addAll);
+ if (cyclingPlugins.stream().anyMatch(plugin -> {
+ PluginProvider<?> pluginProvider = this.providerMap.get(plugin);
+ return pluginProvider != null && !(pluginProvider instanceof SpigotPluginProvider);
+ })) {
+ logCycleError(cycles, this.providerMap);
+ }
+
+ // Try again after hopefully having removed all cycles
+ try {
+ reversedTopographicSort = Lists.reverse(TopographicGraphSorter.sortGraph(this.graph));
+ } catch (TopographicGraphSorter.GraphCycleException e) {
+ throw new PluginGraphCycleException(cycles);
+ }
+ }
+
+ return reversedTopographicSort;
+ }
+
+ private void logCycleError(List<List<String>> cycles, Map<String, PluginProvider<?>> providerMapMirror) {
+ LOGGER.error("=================================");
+ LOGGER.error("Circular plugin loading detected:");
+ for (int i = 0; i < cycles.size(); i++) {
+ List<String> cycle = cycles.get(i);
+ LOGGER.error("{}) {} -> {}", i + 1, String.join(" -> ", cycle), cycle.get(0));
+ for (String pluginName : cycle) {
+ PluginProvider<?> pluginProvider = providerMapMirror.get(pluginName);
+ if (pluginProvider == null) {
+ return;
+ }
+
+ logPluginInfo(pluginProvider.getMeta());
+ }
+ }
+
+ LOGGER.error("Please report this to the plugin authors of the first plugin of each loop or join the PaperMC Discord server for further help.");
+ LOGGER.error("=================================");
+ }
+
+ private void logPluginInfo(PluginMeta meta) {
+ if (!meta.getLoadBeforePlugins().isEmpty()) {
+ LOGGER.error(" {} loadbefore: {}", meta.getName(), meta.getLoadBeforePlugins());
+ }
+
+ if (meta instanceof PaperPluginMeta paperPluginMeta) {
+ if (!paperPluginMeta.getLoadAfterPlugins().isEmpty()) {
+ LOGGER.error(" {} loadafter: {}", meta.getName(), paperPluginMeta.getLoadAfterPlugins());
+ }
+ } else {
+ List<String> dependencies = new ArrayList<>();
+ dependencies.addAll(meta.getPluginDependencies());
+ dependencies.addAll(meta.getPluginSoftDependencies());
+ if (!dependencies.isEmpty()) {
+ LOGGER.error(" {} depend/softdepend: {}", meta.getName(), dependencies);
+ }
+ }
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/modern/ModernPluginLoadingStrategy.java b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/modern/ModernPluginLoadingStrategy.java
new file mode 100644
index 0000000000000000000000000000000000000000..9af388a8e56806ab44f8c3ef4f97086ce38ef3b4
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/entrypoint/strategy/modern/ModernPluginLoadingStrategy.java
@@ -0,0 +1,138 @@
+package io.papermc.paper.plugin.entrypoint.strategy.modern;
+
+import com.google.common.collect.Maps;
+import com.google.common.graph.GraphBuilder;
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.entrypoint.dependency.GraphDependencyContext;
+import io.papermc.paper.plugin.entrypoint.dependency.MetaDependencyTree;
+import io.papermc.paper.plugin.entrypoint.strategy.ProviderConfiguration;
+import io.papermc.paper.plugin.entrypoint.strategy.ProviderLoadingStrategy;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import org.bukkit.plugin.UnknownDependencyException;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+
+@SuppressWarnings("UnstableApiUsage")
+public class ModernPluginLoadingStrategy<T> implements ProviderLoadingStrategy<T> {
+
+ private static final Logger LOGGER = LogUtils.getClassLogger();
+ private final ProviderConfiguration<T> configuration;
+
+ public ModernPluginLoadingStrategy(ProviderConfiguration<T> onLoad) {
+ this.configuration = onLoad;
+ }
+
+ @Override
+ public List<ProviderPair<T>> loadProviders(List<PluginProvider<T>> pluginProviders, MetaDependencyTree dependencyTree) {
+ Map<String, PluginProviderEntry<T>> providerMap = new HashMap<>();
+ Map<String, PluginProvider<?>> providerMapMirror = Maps.transformValues(providerMap, (entry) -> entry.provider);
+ List<PluginProvider<T>> validatedProviders = new ArrayList<>();
+
+ // Populate provider map
+ for (PluginProvider<T> provider : pluginProviders) {
+ PluginMeta providerConfig = provider.getMeta();
+ PluginProviderEntry<T> entry = new PluginProviderEntry<>(provider);
+
+ PluginProviderEntry<T> replacedProvider = providerMap.put(providerConfig.getName(), entry);
+ if (replacedProvider != null) {
+ LOGGER.error(String.format(
+ "Ambiguous plugin name '%s' for files '%s' and '%s' in '%s'",
+ providerConfig.getName(),
+ provider.getSource(),
+ replacedProvider.provider.getSource(),
+ replacedProvider.provider.getParentSource()
+ ));
+ this.configuration.onGenericError(replacedProvider.provider);
+ }
+
+ for (String extra : providerConfig.getProvidedPlugins()) {
+ PluginProviderEntry<T> replacedExtraProvider = providerMap.putIfAbsent(extra, entry);
+ if (replacedExtraProvider != null) {
+ LOGGER.warn(String.format(
+ "`%s' is provided by both `%s' and `%s'",
+ extra,
+ providerConfig.getName(),
+ replacedExtraProvider.provider.getMeta().getName()
+ ));
+ }
+ }
+ }
+
+ // Populate dependency tree
+ for (PluginProvider<?> validated : pluginProviders) {
+ dependencyTree.add(validated);
+ }
+
+ // Validate providers, ensuring all of them have valid dependencies. Removing those who are invalid
+ for (PluginProvider<T> provider : pluginProviders) {
+ PluginMeta configuration = provider.getMeta();
+
+ // Populate missing dependencies to capture if there are multiple missing ones.
+ List<String> missingDependencies = provider.validateDependencies(dependencyTree);
+
+ if (missingDependencies.isEmpty()) {
+ validatedProviders.add(provider);
+ } else {
+ LOGGER.error("Could not load '%s' in '%s'".formatted(provider.getSource(), provider.getParentSource()), new UnknownDependencyException(missingDependencies, configuration.getName())); // Paper
+ // Because the validator is invalid, remove it from the provider map
+ providerMap.remove(configuration.getName());
+ // Cleanup plugins that failed to load
+ dependencyTree.remove(provider);
+ this.configuration.onGenericError(provider);
+ }
+ }
+
+ LoadOrderTree loadOrderTree = new LoadOrderTree(providerMapMirror, GraphBuilder.directed().build());
+ // Populate load order tree
+ for (PluginProvider<?> validated : validatedProviders) {
+ loadOrderTree.add(validated);
+ }
+
+ // Reverse the topographic search to let us see which providers we can load first.
+ List<String> reversedTopographicSort = loadOrderTree.getLoadOrder();
+ List<ProviderPair<T>> loadedPlugins = new ArrayList<>();
+ for (String providerIdentifier : reversedTopographicSort) {
+ // It's possible that this will be null because the above dependencies for soft/load before aren't validated if they exist.
+ // The graph could be MutableGraph<PluginProvider<T>>, but we would have to check if each dependency exists there... just
+ // nicer to do it here TBH.
+ PluginProviderEntry<T> retrievedProviderEntry = providerMap.get(providerIdentifier);
+ if (retrievedProviderEntry == null || retrievedProviderEntry.provided) {
+ // OR if this was already provided (most likely from a plugin that already "provides" that dependency)
+ // This won't matter since the provided plugin is loaded as a dependency, meaning it should have been loaded correctly anyways
+ continue; // Skip provider that doesn't exist....
+ }
+ retrievedProviderEntry.provided = true;
+ PluginProvider<T> retrievedProvider = retrievedProviderEntry.provider;
+ try {
+ this.configuration.applyContext(retrievedProvider, dependencyTree);
+
+ if (this.configuration.preloadProvider(retrievedProvider)) {
+ T instance = retrievedProvider.createInstance();
+ if (this.configuration.load(retrievedProvider, instance)) {
+ loadedPlugins.add(new ProviderPair<>(retrievedProvider, instance));
+ }
+ }
+ } catch (Throwable ex) {
+ LOGGER.error("Could not load plugin '%s' in folder '%s'".formatted(retrievedProvider.getFileName(), retrievedProvider.getParentSource()), ex); // Paper
+ }
+ }
+
+ return loadedPlugins;
+ }
+
+ private static class PluginProviderEntry<T> {
+
+ private final PluginProvider<T> provider;
+ private boolean provided;
+
+ private PluginProviderEntry(PluginProvider<T> provider) {
+ this.provider = provider;
+ }
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/loader/PaperClasspathBuilder.java b/src/main/java/io/papermc/paper/plugin/loader/PaperClasspathBuilder.java
new file mode 100644
index 0000000000000000000000000000000000000000..f38ecd7f65dc24e4a3f0bc675e3730287ac353f1
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/loader/PaperClasspathBuilder.java
@@ -0,0 +1,64 @@
+package io.papermc.paper.plugin.loader;
+
+import io.papermc.paper.plugin.bootstrap.PluginProviderContext;
+import io.papermc.paper.plugin.loader.library.ClassPathLibrary;
+import io.papermc.paper.plugin.loader.library.PaperLibraryStore;
+import io.papermc.paper.plugin.entrypoint.classloader.PaperPluginClassLoader;
+import io.papermc.paper.plugin.provider.configuration.PaperPluginMeta;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.JarFile;
+import java.util.logging.Logger;
+
+public class PaperClasspathBuilder implements PluginClasspathBuilder {
+
+ private final List<ClassPathLibrary> libraries = new ArrayList<>();
+
+ private final PluginProviderContext context;
+
+ public PaperClasspathBuilder(PluginProviderContext context) {
+ this.context = context;
+ }
+
+ @Override
+ public @NotNull PluginProviderContext getContext() {
+ return this.context;
+ }
+
+ @Override
+ public @NotNull PluginClasspathBuilder addLibrary(@NotNull ClassPathLibrary classPathLibrary) {
+ this.libraries.add(classPathLibrary);
+ return this;
+ }
+
+ public PaperPluginClassLoader buildClassLoader(Logger logger, Path source, JarFile jarFile, PaperPluginMeta configuration) {
+ PaperLibraryStore paperLibraryStore = new PaperLibraryStore();
+ for (ClassPathLibrary library : this.libraries) {
+ library.register(paperLibraryStore);
+ }
+
+ List<Path> paths = paperLibraryStore.getPaths();
+ URL[] urls = new URL[paths.size()];
+ for (int i = 0; i < paths.size(); i++) {
+ Path path = paperLibraryStore.getPaths().get(i);
+ try {
+ urls[i] = path.toUri().toURL();
+ } catch (MalformedURLException e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ try {
+ return new PaperPluginClassLoader(logger, source, jarFile, configuration, this.getClass().getClassLoader(), new URLClassLoader(urls, getClass().getClassLoader()));
+ } catch (IOException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/loader/library/PaperLibraryStore.java b/src/main/java/io/papermc/paper/plugin/loader/library/PaperLibraryStore.java
new file mode 100644
index 0000000000000000000000000000000000000000..5fcce65009f715d46dd3013f1f92ec8393d66e15
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/loader/library/PaperLibraryStore.java
@@ -0,0 +1,21 @@
+package io.papermc.paper.plugin.loader.library;
+
+import org.jetbrains.annotations.NotNull;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+
+public class PaperLibraryStore implements LibraryStore {
+
+ private final List<Path> paths = new ArrayList<>();
+
+ @Override
+ public void addLibrary(@NotNull Path library) {
+ this.paths.add(library);
+ }
+
+ public List<Path> getPaths() {
+ return this.paths;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/manager/DummyBukkitPluginLoader.java b/src/main/java/io/papermc/paper/plugin/manager/DummyBukkitPluginLoader.java
new file mode 100644
index 0000000000000000000000000000000000000000..aef19b44075a3b2e8696315baa89117dd8ebb513
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/manager/DummyBukkitPluginLoader.java
@@ -0,0 +1,82 @@
+package io.papermc.paper.plugin.manager;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.type.PluginFileType;
+import org.bukkit.Bukkit;
+import org.bukkit.event.Event;
+import org.bukkit.event.Listener;
+import org.bukkit.plugin.InvalidDescriptionException;
+import org.bukkit.plugin.InvalidPluginException;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.PluginDescriptionFile;
+import org.bukkit.plugin.PluginLoader;
+import org.bukkit.plugin.RegisteredListener;
+import org.bukkit.plugin.UnknownDependencyException;
+import org.jetbrains.annotations.ApiStatus;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Set;
+import java.util.jar.JarFile;
+import java.util.regex.Pattern;
+
+/**
+ * A purely internal type that implements the now deprecated {@link PluginLoader} after the implementation
+ * of papers new plugin system.
+ */
+@ApiStatus.Internal
+public class DummyBukkitPluginLoader implements PluginLoader {
+
+ private static final Pattern[] PATTERNS = new Pattern[0];
+
+ @Override
+ public @NotNull Plugin loadPlugin(@NotNull File file) throws InvalidPluginException, UnknownDependencyException {
+ try {
+ return PaperPluginManagerImpl.getInstance().loadPlugin(file);
+ } catch (InvalidDescriptionException e) {
+ throw new InvalidPluginException(e);
+ }
+ }
+
+ @Override
+ public @NotNull PluginDescriptionFile getPluginDescription(@NotNull File file) throws InvalidDescriptionException {
+ try (JarFile jar = new JarFile(file)) {
+ PluginFileType<?, ?> type = PluginFileType.guessType(jar);
+ if (type == null) {
+ throw new InvalidDescriptionException(new FileNotFoundException("Jar does not contain plugin.yml"));
+ }
+
+ PluginMeta meta = type.getConfig(jar);
+ if (meta instanceof PluginDescriptionFile pluginDescriptionFile) {
+ return pluginDescriptionFile;
+ } else {
+ throw new InvalidDescriptionException("Plugin type does not use plugin.yml. Cannot read file description.");
+ }
+ } catch (Exception e) {
+ throw new InvalidDescriptionException(e);
+ }
+ }
+
+ @Override
+ public @NotNull Pattern[] getPluginFileFilters() {
+ return PATTERNS;
+ }
+
+ @Override
+ public @NotNull Map<Class<? extends Event>, Set<RegisteredListener>> createRegisteredListeners(@NotNull Listener listener, @NotNull Plugin plugin) {
+ return PaperPluginManagerImpl.getInstance().paperEventManager.createRegisteredListeners(listener, plugin);
+ }
+
+ @Override
+ public void enablePlugin(@NotNull Plugin plugin) {
+ Bukkit.getPluginManager().enablePlugin(plugin);
+ }
+
+ @Override
+ public void disablePlugin(@NotNull Plugin plugin) {
+ Bukkit.getPluginManager().disablePlugin(plugin);
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/manager/MultiRuntimePluginProviderStorage.java b/src/main/java/io/papermc/paper/plugin/manager/MultiRuntimePluginProviderStorage.java
new file mode 100644
index 0000000000000000000000000000000000000000..d681222f355af5c4c26f35aaba484a393aee41c6
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/manager/MultiRuntimePluginProviderStorage.java
@@ -0,0 +1,61 @@
+package io.papermc.paper.plugin.manager;
+
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.plugin.entrypoint.Entrypoint;
+import io.papermc.paper.plugin.entrypoint.LaunchEntryPointHandler;
+import io.papermc.paper.plugin.entrypoint.dependency.GraphDependencyContext;
+import io.papermc.paper.plugin.entrypoint.dependency.MetaDependencyTree;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.type.paper.PaperPluginParent;
+import io.papermc.paper.plugin.storage.ServerPluginProviderStorage;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class MultiRuntimePluginProviderStorage extends ServerPluginProviderStorage {
+
+ private static final Logger LOGGER = LogUtils.getClassLogger();
+ private final List<JavaPlugin> provided = new ArrayList<>();
+
+ private final MetaDependencyTree dependencyTree;
+
+ MultiRuntimePluginProviderStorage(MetaDependencyTree dependencyTree) {
+ this.dependencyTree = dependencyTree;
+ }
+
+ @Override
+ public void register(PluginProvider<JavaPlugin> provider) {
+ if (provider instanceof PaperPluginParent.PaperServerPluginProvider) {
+ LOGGER.warn("Skipping loading of paper plugin requested from SimplePluginManager.");
+ return;
+ }
+ super.register(provider);
+ /*
+ Register the provider into the server entrypoint, this allows it to show in /plugins correctly. Generally it might be better in the future to make a separate storage,
+ as putting it into the entrypoint handlers doesn't make much sense.
+ */
+ LaunchEntryPointHandler.INSTANCE.register(Entrypoint.PLUGIN, provider);
+ }
+
+ @Override
+ public void processProvided(PluginProvider<JavaPlugin> provider, JavaPlugin provided) {
+ super.processProvided(provider, provided);
+ this.provided.add(provided);
+ }
+
+ @Override
+ public boolean throwOnCycle() {
+ return false;
+ }
+
+ public List<JavaPlugin> getLoaded() {
+ return this.provided;
+ }
+
+ @Override
+ public MetaDependencyTree createDependencyTree() {
+ return this.dependencyTree;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/manager/NormalPaperPermissionManager.java b/src/main/java/io/papermc/paper/plugin/manager/NormalPaperPermissionManager.java
new file mode 100644
index 0000000000000000000000000000000000000000..6f6aaab295018017565ba27d6958a1f5c7b69bc8
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/manager/NormalPaperPermissionManager.java
@@ -0,0 +1,43 @@
+package io.papermc.paper.plugin.manager;
+
+import org.bukkit.permissions.Permissible;
+import org.bukkit.permissions.Permission;
+
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.Map;
+import java.util.Set;
+
+class NormalPaperPermissionManager extends PaperPermissionManager {
+
+ private final Map<String, Permission> permissions = new HashMap<>();
+ private final Map<Boolean, Set<Permission>> defaultPerms = new LinkedHashMap<>();
+ private final Map<String, Map<Permissible, Boolean>> permSubs = new HashMap<>();
+ private final Map<Boolean, Map<Permissible, Boolean>> defSubs = new HashMap<>();
+
+ public NormalPaperPermissionManager() {
+ this.defaultPerms().put(true, new LinkedHashSet<>());
+ this.defaultPerms().put(false, new LinkedHashSet<>());
+ }
+
+ @Override
+ public Map<String, Permission> permissions() {
+ return this.permissions;
+ }
+
+ @Override
+ public Map<Boolean, Set<Permission>> defaultPerms() {
+ return this.defaultPerms;
+ }
+
+ @Override
+ public Map<String, Map<Permissible, Boolean>> permSubs() {
+ return this.permSubs;
+ }
+
+ @Override
+ public Map<Boolean, Map<Permissible, Boolean>> defSubs() {
+ return this.defSubs;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/manager/PaperEventManager.java b/src/main/java/io/papermc/paper/plugin/manager/PaperEventManager.java
new file mode 100644
index 0000000000000000000000000000000000000000..7ce9ebba8ce304d1f3f21d4f15ee5f3560d7700b
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/manager/PaperEventManager.java
@@ -0,0 +1,194 @@
+package io.papermc.paper.plugin.manager;
+
+import co.aikar.timings.TimedEventExecutor;
+import com.destroystokyo.paper.event.server.ServerExceptionEvent;
+import com.destroystokyo.paper.exception.ServerEventException;
+import com.google.common.collect.Sets;
+import org.bukkit.Server;
+import org.bukkit.Warning;
+import org.bukkit.event.Event;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.HandlerList;
+import org.bukkit.event.Listener;
+import org.bukkit.plugin.AuthorNagException;
+import org.bukkit.plugin.EventExecutor;
+import org.bukkit.plugin.IllegalPluginAccessException;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.RegisteredListener;
+import org.jetbrains.annotations.NotNull;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Level;
+
+class PaperEventManager {
+
+ private final Server server;
+
+ public PaperEventManager(Server server) {
+ this.server = server;
+ }
+
+ // SimplePluginManager
+ public void callEvent(@NotNull Event event) {
+ if (event.isAsynchronous() && this.server.isPrimaryThread()) {
+ throw new IllegalStateException(event.getEventName() + " may only be triggered asynchronously.");
+ } else if (!event.isAsynchronous() && !this.server.isPrimaryThread() && !this.server.isStopping()) {
+ throw new IllegalStateException(event.getEventName() + " may only be triggered synchronously.");
+ }
+
+ HandlerList handlers = event.getHandlers();
+ RegisteredListener[] listeners = handlers.getRegisteredListeners();
+
+ for (RegisteredListener registration : listeners) {
+ if (!registration.getPlugin().isEnabled()) {
+ continue;
+ }
+
+ try {
+ registration.callEvent(event);
+ } catch (AuthorNagException ex) {
+ Plugin plugin = registration.getPlugin();
+
+ if (plugin.isNaggable()) {
+ plugin.setNaggable(false);
+
+ this.server.getLogger().log(Level.SEVERE, String.format(
+ "Nag author(s): '%s' of '%s' about the following: %s",
+ plugin.getPluginMeta().getAuthors(),
+ plugin.getPluginMeta().getDisplayName(),
+ ex.getMessage()
+ ));
+ }
+ } catch (Throwable ex) {
+ String msg = "Could not pass event " + event.getEventName() + " to " + registration.getPlugin().getPluginMeta().getDisplayName();
+ this.server.getLogger().log(Level.SEVERE, msg, ex);
+ if (!(event instanceof ServerExceptionEvent)) { // We don't want to cause an endless event loop
+ this.callEvent(new ServerExceptionEvent(new ServerEventException(msg, ex, registration.getPlugin(), registration.getListener(), event)));
+ }
+ }
+ }
+ }
+
+ public void registerEvents(@NotNull Listener listener, @NotNull Plugin plugin) {
+ if (!plugin.isEnabled()) {
+ throw new IllegalPluginAccessException("Plugin attempted to register " + listener + " while not enabled");
+ }
+
+ for (Map.Entry<Class<? extends Event>, Set<RegisteredListener>> entry : this.createRegisteredListeners(listener, plugin).entrySet()) {
+ this.getEventListeners(this.getRegistrationClass(entry.getKey())).registerAll(entry.getValue());
+ }
+
+ }
+
+ public void registerEvent(@NotNull Class<? extends Event> event, @NotNull Listener listener, @NotNull EventPriority priority, @NotNull EventExecutor executor, @NotNull Plugin plugin) {
+ this.registerEvent(event, listener, priority, executor, plugin, false);
+ }
+
+ public void registerEvent(@NotNull Class<? extends Event> event, @NotNull Listener listener, @NotNull EventPriority priority, @NotNull EventExecutor executor, @NotNull Plugin plugin, boolean ignoreCancelled) {
+ if (!plugin.isEnabled()) {
+ throw new IllegalPluginAccessException("Plugin attempted to register " + event + " while not enabled");
+ }
+
+ executor = new TimedEventExecutor(executor, plugin, null, event);
+ this.getEventListeners(event).register(new RegisteredListener(listener, executor, priority, plugin, ignoreCancelled));
+ }
+
+ @NotNull
+ private HandlerList getEventListeners(@NotNull Class<? extends Event> type) {
+ try {
+ Method method = this.getRegistrationClass(type).getDeclaredMethod("getHandlerList");
+ method.setAccessible(true);
+ return (HandlerList) method.invoke(null);
+ } catch (Exception e) {
+ throw new IllegalPluginAccessException(e.toString());
+ }
+ }
+
+ @NotNull
+ private Class<? extends Event> getRegistrationClass(@NotNull Class<? extends Event> clazz) {
+ try {
+ clazz.getDeclaredMethod("getHandlerList");
+ return clazz;
+ } catch (NoSuchMethodException e) {
+ if (clazz.getSuperclass() != null
+ && !clazz.getSuperclass().equals(Event.class)
+ && Event.class.isAssignableFrom(clazz.getSuperclass())) {
+ return this.getRegistrationClass(clazz.getSuperclass().asSubclass(Event.class));
+ } else {
+ throw new IllegalPluginAccessException("Unable to find handler list for event " + clazz.getName() + ". Static getHandlerList method required!");
+ }
+ }
+ }
+
+ // JavaPluginLoader
+ @NotNull
+ public Map<Class<? extends Event>, Set<RegisteredListener>> createRegisteredListeners(@NotNull Listener listener, @NotNull final Plugin plugin) {
+ Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<>();
+
+ Set<Method> methods;
+ try {
+ Class<?> listenerClazz = listener.getClass();
+ methods = Sets.union(
+ Set.of(listenerClazz.getMethods()),
+ Set.of(listenerClazz.getDeclaredMethods())
+ );
+ } catch (NoClassDefFoundError e) {
+ plugin.getLogger().severe("Failed to register events for " + listener.getClass() + " because " + e.getMessage() + " does not exist.");
+ return ret;
+ }
+
+ for (final Method method : methods) {
+ final EventHandler eh = method.getAnnotation(EventHandler.class);
+ if (eh == null) continue;
+ // Do not register bridge or synthetic methods to avoid event duplication
+ // Fixes SPIGOT-893
+ if (method.isBridge() || method.isSynthetic()) {
+ continue;
+ }
+ final Class<?> checkClass;
+ if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) {
+ plugin.getLogger().severe(plugin.getPluginMeta().getDisplayName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass());
+ continue;
+ }
+ final Class<? extends Event> eventClass = checkClass.asSubclass(Event.class);
+ method.setAccessible(true);
+ Set<RegisteredListener> eventSet = ret.computeIfAbsent(eventClass, k -> new HashSet<>());
+
+ for (Class<?> clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) {
+ // This loop checks for extending deprecated events
+ if (clazz.getAnnotation(Deprecated.class) != null) {
+ Warning warning = clazz.getAnnotation(Warning.class);
+ Warning.WarningState warningState = this.server.getWarningState();
+ if (!warningState.printFor(warning)) {
+ break;
+ }
+ plugin.getLogger().log(
+ Level.WARNING,
+ String.format(
+ "\"%s\" has registered a listener for %s on method \"%s\", but the event is Deprecated. \"%s\"; please notify the authors %s.",
+ plugin.getPluginMeta().getDisplayName(),
+ clazz.getName(),
+ method.toGenericString(),
+ (warning != null && warning.reason().length() != 0) ? warning.reason() : "Server performance will be affected",
+ Arrays.toString(plugin.getPluginMeta().getAuthors().toArray())),
+ warningState == Warning.WarningState.ON ? new AuthorNagException(null) : null);
+ break;
+ }
+ }
+
+ EventExecutor executor = new TimedEventExecutor(EventExecutor.create(method, eventClass), plugin, method, eventClass);
+ eventSet.add(new RegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled()));
+ }
+ return ret;
+ }
+
+ public void clearEvents() {
+ HandlerList.unregisterAll();
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/manager/PaperPermissionManager.java b/src/main/java/io/papermc/paper/plugin/manager/PaperPermissionManager.java
new file mode 100644
index 0000000000000000000000000000000000000000..92a69677f21b2c1c035119d8e5a6af63fa19b801
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/manager/PaperPermissionManager.java
@@ -0,0 +1,201 @@
+package io.papermc.paper.plugin.manager;
+
+import com.google.common.collect.ImmutableSet;
+import io.papermc.paper.plugin.PermissionManager;
+import org.bukkit.permissions.Permissible;
+import org.bukkit.permissions.Permission;
+import org.bukkit.permissions.PermissionDefault;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.WeakHashMap;
+
+/**
+ * See
+ * {@link StupidSPMPermissionManagerWrapper}
+ */
+abstract class PaperPermissionManager implements PermissionManager {
+
+ public abstract Map<String, Permission> permissions();
+
+ public abstract Map<Boolean, Set<Permission>> defaultPerms();
+
+ public abstract Map<String, Map<Permissible, Boolean>> permSubs();
+
+ public abstract Map<Boolean, Map<Permissible, Boolean>> defSubs();
+
+ @Override
+ @Nullable
+ public Permission getPermission(@NotNull String name) {
+ return this.permissions().get(name.toLowerCase(java.util.Locale.ENGLISH));
+ }
+
+ @Override
+ public void addPermission(@NotNull Permission perm) {
+ this.addPermission(perm, true);
+ }
+
+ @Override
+ public void addPermissions(@NotNull List<Permission> permissions) {
+ for (Permission permission : permissions) {
+ this.addPermission(permission, false);
+ }
+ this.dirtyPermissibles();
+ }
+
+ // Allow suppressing permission default calculations
+ private void addPermission(@NotNull Permission perm, boolean dirty) {
+ String name = perm.getName().toLowerCase(java.util.Locale.ENGLISH);
+
+ if (this.permissions().containsKey(name)) {
+ throw new IllegalArgumentException("The permission " + name + " is already defined!");
+ }
+
+ this.permissions().put(name, perm);
+ this.calculatePermissionDefault(perm, dirty);
+ }
+
+ @Override
+ @NotNull
+ public Set<Permission> getDefaultPermissions(boolean op) {
+ return ImmutableSet.copyOf(this.defaultPerms().get(op));
+ }
+
+
+ @Override
+ public void removePermission(@NotNull Permission perm) {
+ this.removePermission(perm.getName());
+ }
+
+
+ @Override
+ public void removePermission(@NotNull String name) {
+ this.permissions().remove(name.toLowerCase(java.util.Locale.ENGLISH));
+ }
+
+ @Override
+ public void recalculatePermissionDefaults(@NotNull Permission perm) {
+ // we need a null check here because some plugins for some unknown reason pass null into this?
+ if (perm != null && this.permissions().containsKey(perm.getName().toLowerCase(Locale.ENGLISH))) {
+ this.defaultPerms().get(true).remove(perm);
+ this.defaultPerms().get(false).remove(perm);
+
+ this.calculatePermissionDefault(perm, true);
+ }
+ }
+
+ private void calculatePermissionDefault(@NotNull Permission perm, boolean dirty) {
+ if ((perm.getDefault() == PermissionDefault.OP) || (perm.getDefault() == PermissionDefault.TRUE)) {
+ this.defaultPerms().get(true).add(perm);
+ if (dirty) {
+ this.dirtyPermissibles(true);
+ }
+ }
+ if ((perm.getDefault() == PermissionDefault.NOT_OP) || (perm.getDefault() == PermissionDefault.TRUE)) {
+ this.defaultPerms().get(false).add(perm);
+ if (dirty) {
+ this.dirtyPermissibles(false);
+ }
+ }
+ }
+
+
+ @Override
+ public void subscribeToPermission(@NotNull String permission, @NotNull Permissible permissible) {
+ String name = permission.toLowerCase(java.util.Locale.ENGLISH);
+ Map<Permissible, Boolean> map = this.permSubs().computeIfAbsent(name, k -> new WeakHashMap<>());
+
+ map.put(permissible, true);
+ }
+
+ @Override
+ public void unsubscribeFromPermission(@NotNull String permission, @NotNull Permissible permissible) {
+ String name = permission.toLowerCase(java.util.Locale.ENGLISH);
+ Map<Permissible, Boolean> map = this.permSubs().get(name);
+
+ if (map != null) {
+ map.remove(permissible);
+
+ if (map.isEmpty()) {
+ this.permSubs().remove(name);
+ }
+ }
+ }
+
+ @Override
+ @NotNull
+ public Set<Permissible> getPermissionSubscriptions(@NotNull String permission) {
+ String name = permission.toLowerCase(java.util.Locale.ENGLISH);
+ Map<Permissible, Boolean> map = this.permSubs().get(name);
+
+ if (map == null) {
+ return ImmutableSet.of();
+ } else {
+ return ImmutableSet.copyOf(map.keySet());
+ }
+ }
+
+ @Override
+ public void subscribeToDefaultPerms(boolean op, @NotNull Permissible permissible) {
+ Map<Permissible, Boolean> map = this.defSubs().computeIfAbsent(op, k -> new WeakHashMap<>());
+
+ map.put(permissible, true);
+ }
+
+ @Override
+ public void unsubscribeFromDefaultPerms(boolean op, @NotNull Permissible permissible) {
+ Map<Permissible, Boolean> map = this.defSubs().get(op);
+
+ if (map != null) {
+ map.remove(permissible);
+
+ if (map.isEmpty()) {
+ this.defSubs().remove(op);
+ }
+ }
+ }
+
+ @Override
+ @NotNull
+ public Set<Permissible> getDefaultPermSubscriptions(boolean op) {
+ Map<Permissible, Boolean> map = this.defSubs().get(op);
+
+ if (map == null) {
+ return ImmutableSet.of();
+ } else {
+ return ImmutableSet.copyOf(map.keySet());
+ }
+ }
+
+ @Override
+ @NotNull
+ public Set<Permission> getPermissions() {
+ return new HashSet<>(this.permissions().values());
+ }
+
+ @Override
+ public void clearPermissions() {
+ this.permissions().clear();
+ this.defaultPerms().get(true).clear();
+ this.defaultPerms().get(false).clear();
+ }
+
+
+ void dirtyPermissibles(boolean op) {
+ Set<Permissible> permissibles = this.getDefaultPermSubscriptions(op);
+
+ for (Permissible p : permissibles) {
+ p.recalculatePermissions();
+ }
+ }
+
+ void dirtyPermissibles() {
+ this.dirtyPermissibles(true);
+ this.dirtyPermissibles(false);
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/manager/PaperPluginInstanceManager.java b/src/main/java/io/papermc/paper/plugin/manager/PaperPluginInstanceManager.java
new file mode 100644
index 0000000000000000000000000000000000000000..d2dee700f2c5cc7d6a272e751a933901fe7a55b6
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/manager/PaperPluginInstanceManager.java
@@ -0,0 +1,317 @@
+package io.papermc.paper.plugin.manager;
+
+import com.google.common.base.Preconditions;
+import com.google.common.graph.GraphBuilder;
+import com.google.common.graph.MutableGraph;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.entrypoint.Entrypoint;
+import io.papermc.paper.plugin.entrypoint.dependency.MetaDependencyTree;
+import io.papermc.paper.plugin.entrypoint.dependency.SimpleMetaDependencyTree;
+import io.papermc.paper.plugin.entrypoint.strategy.PluginGraphCycleException;
+import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
+import io.papermc.paper.plugin.provider.classloader.PaperClassLoaderStorage;
+import io.papermc.paper.plugin.provider.source.DirectoryProviderSource;
+import io.papermc.paper.plugin.provider.source.FileArrayProviderSource;
+import io.papermc.paper.plugin.provider.source.FileProviderSource;
+import java.io.File;
+import org.bukkit.Bukkit;
+import org.bukkit.Server;
+import org.bukkit.World;
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandMap;
+import org.bukkit.command.PluginCommandYamlParser;
+import org.bukkit.craftbukkit.util.CraftMagicNumbers;
+import org.bukkit.event.HandlerList;
+import org.bukkit.event.server.PluginDisableEvent;
+import org.bukkit.event.server.PluginEnableEvent;
+import org.bukkit.plugin.InvalidPluginException;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.PluginDescriptionFile;
+import org.bukkit.plugin.PluginManager;
+import org.bukkit.plugin.UnknownDependencyException;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.jetbrains.annotations.ApiStatus;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Level;
+
+@SuppressWarnings("UnstableApiUsage")
+class PaperPluginInstanceManager {
+
+ private static final FileProviderSource FILE_PROVIDER_SOURCE = new FileProviderSource("File '%s'"::formatted);
+
+ private final List<Plugin> plugins = new ArrayList<>();
+ private final Map<String, Plugin> lookupNames = new HashMap<>();
+
+ private final PluginManager pluginManager;
+ private final CommandMap commandMap;
+ private final Server server;
+
+ private final MetaDependencyTree dependencyTree = new SimpleMetaDependencyTree(GraphBuilder.directed().build());
+
+ public PaperPluginInstanceManager(PluginManager pluginManager, CommandMap commandMap, Server server) {
+ this.commandMap = commandMap;
+ this.server = server;
+ this.pluginManager = pluginManager;
+ }
+
+ public @Nullable Plugin getPlugin(@NotNull String name) {
+ return this.lookupNames.get(name.replace(' ', '_').toLowerCase(java.util.Locale.ENGLISH)); // Paper
+ }
+
+ public @NotNull Plugin[] getPlugins() {
+ return this.plugins.toArray(new Plugin[0]);
+ }
+
+ public boolean isPluginEnabled(@NotNull String name) {
+ Plugin plugin = this.getPlugin(name);
+
+ return this.isPluginEnabled(plugin);
+ }
+
+ public synchronized boolean isPluginEnabled(@Nullable Plugin plugin) {
+ if ((plugin != null) && (this.plugins.contains(plugin))) {
+ return plugin.isEnabled();
+ } else {
+ return false;
+ }
+ }
+
+ public void loadPlugin(Plugin provided) {
+ PluginMeta configuration = provided.getPluginMeta();
+
+ this.plugins.add(provided);
+ this.lookupNames.put(configuration.getName().toLowerCase(java.util.Locale.ENGLISH), provided);
+ for (String providedPlugin : configuration.getProvidedPlugins()) {
+ this.lookupNames.putIfAbsent(providedPlugin.toLowerCase(java.util.Locale.ENGLISH), provided);
+ }
+
+ this.dependencyTree.add(configuration);
+ }
+
+ // InvalidDescriptionException is never used, because the old JavaPluginLoader would wrap the exception.
+ public @Nullable Plugin loadPlugin(@NotNull Path path) throws InvalidPluginException, UnknownDependencyException {
+ RuntimePluginEntrypointHandler<SingularRuntimePluginProviderStorage> runtimePluginEntrypointHandler = new RuntimePluginEntrypointHandler<>(new SingularRuntimePluginProviderStorage(this.dependencyTree));
+
+ try {
+ path = FILE_PROVIDER_SOURCE.prepareContext(path);
+ FILE_PROVIDER_SOURCE.registerProviders(runtimePluginEntrypointHandler, path);
+ } catch (IllegalArgumentException exception) {
+ return null; // Return null when the plugin file is not valid / plugin type is unknown
+ } catch (PluginGraphCycleException exception) {
+ throw new InvalidPluginException("Cannot import plugin that causes cyclic dependencies!");
+ } catch (Exception e) {
+ throw new InvalidPluginException(e);
+ }
+
+ try {
+ runtimePluginEntrypointHandler.enter(Entrypoint.PLUGIN);
+ } catch (Throwable e) {
+ throw new InvalidPluginException(e);
+ }
+
+ return runtimePluginEntrypointHandler.getPluginProviderStorage().getSingleLoaded()
+ .orElseThrow(() -> new InvalidPluginException("Plugin didn't load any plugin providers?"));
+ }
+
+ public @NotNull Plugin[] loadPlugins(@NotNull File[] files) {
+ RuntimePluginEntrypointHandler<MultiRuntimePluginProviderStorage> runtimePluginEntrypointHandler = new RuntimePluginEntrypointHandler<>(new MultiRuntimePluginProviderStorage(this.dependencyTree));
+ try {
+ List<Path> paths = FileArrayProviderSource.INSTANCE.prepareContext(files);
+ DirectoryProviderSource.INSTANCE.registerProviders(runtimePluginEntrypointHandler, paths);
+ runtimePluginEntrypointHandler.enter(Entrypoint.PLUGIN);
+ } catch (Exception e) {
+ // This should never happen, any errors that occur in this provider should instead be logged.
+ this.server.getLogger().log(Level.SEVERE, "Unknown error occurred while loading plugins through PluginManager.", e);
+ }
+
+ return runtimePluginEntrypointHandler.getPluginProviderStorage().getLoaded().toArray(new JavaPlugin[0]);
+ }
+
+ // The behavior of this is that all errors are logged instead of being thrown
+ public @NotNull Plugin[] loadPlugins(@NotNull Path directory) {
+ Preconditions.checkArgument(Files.isDirectory(directory), "Directory must be a directory"); // Avoid creating a directory if it doesn't exist
+
+ RuntimePluginEntrypointHandler<MultiRuntimePluginProviderStorage> runtimePluginEntrypointHandler = new RuntimePluginEntrypointHandler<>(new MultiRuntimePluginProviderStorage(this.dependencyTree));
+ try {
+ List<Path> files = DirectoryProviderSource.INSTANCE.prepareContext(directory);
+ DirectoryProviderSource.INSTANCE.registerProviders(runtimePluginEntrypointHandler, files);
+ runtimePluginEntrypointHandler.enter(Entrypoint.PLUGIN);
+ } catch (Exception e) {
+ // This should never happen, any errors that occur in this provider should instead be logged.
+ this.server.getLogger().log(Level.SEVERE, "Unknown error occurred while loading plugins through PluginManager.", e);
+ }
+
+ return runtimePluginEntrypointHandler.getPluginProviderStorage().getLoaded().toArray(new JavaPlugin[0]);
+ }
+
+ // Plugins are disabled in order like this inorder to "rougly" prevent
+ // their dependencies unloading first. But, eh.
+ public void disablePlugins() {
+ Plugin[] plugins = this.getPlugins();
+ for (int i = plugins.length - 1; i >= 0; i--) {
+ this.disablePlugin(plugins[i]);
+ }
+ }
+
+ public void clearPlugins() {
+ synchronized (this) {
+ this.disablePlugins();
+ this.plugins.clear();
+ this.lookupNames.clear();
+ }
+ }
+
+ public synchronized void enablePlugin(@NotNull Plugin plugin) {
+ if (plugin.isEnabled()) {
+ return;
+ }
+
+ if (plugin.getPluginMeta() instanceof PluginDescriptionFile) {
+ List<Command> bukkitCommands = PluginCommandYamlParser.parse(plugin);
+
+ if (!bukkitCommands.isEmpty()) {
+ this.commandMap.registerAll(plugin.getPluginMeta().getName(), bukkitCommands);
+ }
+ }
+
+ try {
+ String enableMsg = "Enabling " + plugin.getPluginMeta().getDisplayName();
+ if (plugin.getPluginMeta() instanceof PluginDescriptionFile descriptionFile && CraftMagicNumbers.isLegacy(descriptionFile)) {
+ enableMsg += "*";
+ }
+ plugin.getLogger().info(enableMsg);
+
+ JavaPlugin jPlugin = (JavaPlugin) plugin;
+
+ if (jPlugin.getClass().getClassLoader() instanceof ConfiguredPluginClassLoader classLoader) { // Paper
+ if (PaperClassLoaderStorage.instance().registerUnsafePlugin(classLoader)) {
+ this.server.getLogger().log(Level.WARNING, "Enabled plugin with unregistered ConfiguredPluginClassLoader " + plugin.getPluginMeta().getDisplayName());
+ }
+ } // Paper
+
+ try {
+ jPlugin.setEnabled(true);
+ } catch (Throwable ex) {
+ this.server.getLogger().log(Level.SEVERE, "Error occurred while enabling " + plugin.getPluginMeta().getDisplayName() + " (Is it up to date?)", ex);
+ // Paper start - Disable plugins that fail to load
+ this.server.getPluginManager().disablePlugin(jPlugin);
+ return;
+ // Paper end
+ }
+
+ // Perhaps abort here, rather than continue going, but as it stands,
+ // an abort is not possible the way it's currently written
+ this.server.getPluginManager().callEvent(new PluginEnableEvent(plugin));
+ } catch (Throwable ex) {
+ this.handlePluginException("Error occurred (in the plugin loader) while enabling "
+ + plugin.getPluginMeta().getDisplayName() + " (Is it up to date?)", ex, plugin);
+ }
+
+ HandlerList.bakeAll();
+ }
+
+ public synchronized void disablePlugin(@NotNull Plugin plugin) {
+ if (!(plugin instanceof JavaPlugin javaPlugin)) {
+ throw new IllegalArgumentException("Only expects java plugins.");
+ }
+ if (!plugin.isEnabled()) {
+ return;
+ }
+
+ String pluginName = plugin.getPluginMeta().getDisplayName();
+
+ try {
+ plugin.getLogger().info("Disabling %s".formatted(pluginName));
+
+ this.server.getPluginManager().callEvent(new PluginDisableEvent(plugin));
+ try {
+ javaPlugin.setEnabled(false);
+ } catch (Throwable ex) {
+ this.server.getLogger().log(Level.SEVERE, "Error occurred while disabling " + pluginName, ex);
+ }
+
+ ClassLoader classLoader = plugin.getClass().getClassLoader();
+ if (classLoader instanceof ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ try {
+ configuredPluginClassLoader.close();
+ } catch (IOException ex) {
+ this.server.getLogger().log(Level.WARNING, "Error closing the classloader for '" + pluginName + "'", ex); // Paper - log exception
+ }
+ // Remove from the classloader pool inorder to prevent plugins from trying
+ // to access classes
+ PaperClassLoaderStorage.instance().unregisterClassloader(configuredPluginClassLoader);
+ }
+
+ } catch (Throwable ex) {
+ this.handlePluginException("Error occurred (in the plugin loader) while disabling "
+ + pluginName + " (Is it up to date?)", ex, plugin); // Paper
+ }
+
+ try {
+ this.server.getScheduler().cancelTasks(plugin);
+ } catch (Throwable ex) {
+ this.handlePluginException("Error occurred (in the plugin loader) while cancelling tasks for "
+ + pluginName + " (Is it up to date?)", ex, plugin); // Paper
+ }
+
+ try {
+ this.server.getServicesManager().unregisterAll(plugin);
+ } catch (Throwable ex) {
+ this.handlePluginException("Error occurred (in the plugin loader) while unregistering services for "
+ + pluginName + " (Is it up to date?)", ex, plugin); // Paper
+ }
+
+ try {
+ HandlerList.unregisterAll(plugin);
+ } catch (Throwable ex) {
+ this.handlePluginException("Error occurred (in the plugin loader) while unregistering events for "
+ + pluginName + " (Is it up to date?)", ex, plugin); // Paper
+ }
+
+ try {
+ this.server.getMessenger().unregisterIncomingPluginChannel(plugin);
+ this.server.getMessenger().unregisterOutgoingPluginChannel(plugin);
+ } catch (Throwable ex) {
+ this.handlePluginException("Error occurred (in the plugin loader) while unregistering plugin channels for "
+ + pluginName + " (Is it up to date?)", ex, plugin); // Paper
+ }
+
+ try {
+ for (World world : this.server.getWorlds()) {
+ world.removePluginChunkTickets(plugin);
+ }
+ } catch (Throwable ex) {
+ this.handlePluginException("Error occurred (in the plugin loader) while removing chunk tickets for " + pluginName + " (Is it up to date?)", ex, plugin); // Paper
+ }
+
+ }
+
+ // TODO: Implement event part in future patch (paper patch move up, this patch is lower)
+ private void handlePluginException(String msg, Throwable ex, Plugin plugin) {
+ Bukkit.getServer().getLogger().log(Level.SEVERE, msg, ex);
+ this.pluginManager.callEvent(new com.destroystokyo.paper.event.server.ServerExceptionEvent(new com.destroystokyo.paper.exception.ServerPluginEnableDisableException(msg, ex, plugin)));
+ }
+
+ public boolean isTransitiveDepend(@NotNull PluginMeta plugin, @NotNull PluginMeta depend) {
+ return this.dependencyTree.isTransitiveDependency(plugin, depend);
+ }
+
+ public boolean hasDependency(String pluginIdentifier) {
+ return this.getPlugin(pluginIdentifier) != null;
+ }
+
+ // Debug only
+ @ApiStatus.Internal
+ public MutableGraph<String> getDependencyGraph() {
+ return this.dependencyTree.getGraph();
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/manager/PaperPluginManagerImpl.java b/src/main/java/io/papermc/paper/plugin/manager/PaperPluginManagerImpl.java
new file mode 100644
index 0000000000000000000000000000000000000000..097500a59336db1bbfffcd1aa4cff7a8586e46ec
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/manager/PaperPluginManagerImpl.java
@@ -0,0 +1,246 @@
+package io.papermc.paper.plugin.manager;
+
+import com.google.common.graph.MutableGraph;
+import io.papermc.paper.plugin.PermissionManager;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+import org.bukkit.Bukkit;
+import org.bukkit.Server;
+import org.bukkit.command.CommandMap;
+import org.bukkit.craftbukkit.CraftServer;
+import org.bukkit.event.Event;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.Listener;
+import org.bukkit.permissions.Permissible;
+import org.bukkit.permissions.Permission;
+import org.bukkit.plugin.EventExecutor;
+import org.bukkit.plugin.InvalidDescriptionException;
+import org.bukkit.plugin.InvalidPluginException;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.PluginLoader;
+import org.bukkit.plugin.PluginManager;
+import org.bukkit.plugin.SimplePluginManager;
+import org.bukkit.plugin.UnknownDependencyException;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.File;
+import java.util.List;
+import java.util.Set;
+
+public class PaperPluginManagerImpl implements PluginManager, DependencyContext {
+
+ final PaperPluginInstanceManager instanceManager;
+ final PaperEventManager paperEventManager;
+ PermissionManager permissionManager;
+
+ public PaperPluginManagerImpl(Server server, CommandMap commandMap, @Nullable SimplePluginManager permissionManager) {
+ this.instanceManager = new PaperPluginInstanceManager(this, commandMap, server);
+ this.paperEventManager = new PaperEventManager(server);
+
+ if (permissionManager == null) {
+ this.permissionManager = new NormalPaperPermissionManager();
+ } else {
+ this.permissionManager = new StupidSPMPermissionManagerWrapper(permissionManager); // TODO: See comment when SimplePermissionManager is removed
+ }
+ }
+
+ // REMOVE THIS WHEN SimplePluginManager is removed.
+ // Just cast and use Bukkit.getServer().getPluginManager()
+ public static PaperPluginManagerImpl getInstance() {
+ return ((CraftServer) (Bukkit.getServer())).paperPluginManager;
+ }
+
+ // Plugin Manipulation
+
+ @Override
+ public @Nullable Plugin getPlugin(@NotNull String name) {
+ return this.instanceManager.getPlugin(name);
+ }
+
+ @Override
+ public @NotNull Plugin[] getPlugins() {
+ return this.instanceManager.getPlugins();
+ }
+
+ @Override
+ public boolean isPluginEnabled(@NotNull String name) {
+ return this.instanceManager.isPluginEnabled(name);
+ }
+
+ @Override
+ public boolean isPluginEnabled(@Nullable Plugin plugin) {
+ return this.instanceManager.isPluginEnabled(plugin);
+ }
+
+ public void loadPlugin(Plugin plugin) {
+ this.instanceManager.loadPlugin(plugin);
+ }
+
+ @Override
+ public @Nullable Plugin loadPlugin(@NotNull File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException {
+ return this.instanceManager.loadPlugin(file.toPath());
+ }
+
+ @Override
+ public @NotNull Plugin[] loadPlugins(@NotNull File directory) {
+ return this.instanceManager.loadPlugins(directory.toPath());
+ }
+
+ @Override
+ public @NotNull Plugin[] loadPlugins(final @NotNull File[] files) {
+ return this.instanceManager.loadPlugins(files);
+ }
+
+ @Override
+ public void disablePlugins() {
+ this.instanceManager.disablePlugins();
+ }
+
+ @Override
+ public synchronized void clearPlugins() {
+ this.instanceManager.clearPlugins();
+ this.permissionManager.clearPermissions();
+ this.paperEventManager.clearEvents();
+ }
+
+ @Override
+ public void enablePlugin(@NotNull Plugin plugin) {
+ this.instanceManager.enablePlugin(plugin);
+ }
+
+ @Override
+ public void disablePlugin(@NotNull Plugin plugin) {
+ this.instanceManager.disablePlugin(plugin);
+ }
+
+ @Override
+ public boolean isTransitiveDependency(PluginMeta pluginMeta, PluginMeta dependencyConfig) {
+ return this.instanceManager.isTransitiveDepend(pluginMeta, dependencyConfig);
+ }
+
+ @Override
+ public boolean hasDependency(String pluginIdentifier) {
+ return this.instanceManager.hasDependency(pluginIdentifier);
+ }
+
+ // Event manipulation
+
+ @Override
+ public void callEvent(@NotNull Event event) throws IllegalStateException {
+ this.paperEventManager.callEvent(event);
+ }
+
+ @Override
+ public void registerEvents(@NotNull Listener listener, @NotNull Plugin plugin) {
+ this.paperEventManager.registerEvents(listener, plugin);
+ }
+
+ @Override
+ public void registerEvent(@NotNull Class<? extends Event> event, @NotNull Listener listener, @NotNull EventPriority priority, @NotNull EventExecutor executor, @NotNull Plugin plugin) {
+ this.paperEventManager.registerEvent(event, listener, priority, executor, plugin);
+ }
+
+ @Override
+ public void registerEvent(@NotNull Class<? extends Event> event, @NotNull Listener listener, @NotNull EventPriority priority, @NotNull EventExecutor executor, @NotNull Plugin plugin, boolean ignoreCancelled) {
+ this.paperEventManager.registerEvent(event, listener, priority, executor, plugin, ignoreCancelled);
+ }
+
+ // Permission manipulation
+
+ @Override
+ public @Nullable Permission getPermission(@NotNull String name) {
+ return this.permissionManager.getPermission(name);
+ }
+
+ @Override
+ public void addPermission(@NotNull Permission perm) {
+ this.permissionManager.addPermission(perm);
+ }
+
+ @Override
+ public void removePermission(@NotNull Permission perm) {
+ this.permissionManager.removePermission(perm);
+ }
+
+ @Override
+ public void removePermission(@NotNull String name) {
+ this.permissionManager.removePermission(name);
+ }
+
+ @Override
+ public @NotNull Set<Permission> getDefaultPermissions(boolean op) {
+ return this.permissionManager.getDefaultPermissions(op);
+ }
+
+ @Override
+ public void recalculatePermissionDefaults(@NotNull Permission perm) {
+ this.permissionManager.recalculatePermissionDefaults(perm);
+ }
+
+ @Override
+ public void subscribeToPermission(@NotNull String permission, @NotNull Permissible permissible) {
+ this.permissionManager.subscribeToPermission(permission, permissible);
+ }
+
+ @Override
+ public void unsubscribeFromPermission(@NotNull String permission, @NotNull Permissible permissible) {
+ this.permissionManager.unsubscribeFromPermission(permission, permissible);
+ }
+
+ @Override
+ public @NotNull Set<Permissible> getPermissionSubscriptions(@NotNull String permission) {
+ return this.permissionManager.getPermissionSubscriptions(permission);
+ }
+
+ @Override
+ public void subscribeToDefaultPerms(boolean op, @NotNull Permissible permissible) {
+ this.permissionManager.subscribeToDefaultPerms(op, permissible);
+ }
+
+ @Override
+ public void unsubscribeFromDefaultPerms(boolean op, @NotNull Permissible permissible) {
+ this.permissionManager.unsubscribeFromDefaultPerms(op, permissible);
+ }
+
+ @Override
+ public @NotNull Set<Permissible> getDefaultPermSubscriptions(boolean op) {
+ return this.permissionManager.getDefaultPermSubscriptions(op);
+ }
+
+ @Override
+ public @NotNull Set<Permission> getPermissions() {
+ return this.permissionManager.getPermissions();
+ }
+
+ @Override
+ public void addPermissions(@NotNull List<Permission> perm) {
+ this.permissionManager.addPermissions(perm);
+ }
+
+ @Override
+ public void clearPermissions() {
+ this.permissionManager.clearPermissions();
+ }
+
+ @Override
+ public void overridePermissionManager(@NotNull Plugin plugin, @Nullable PermissionManager permissionManager) {
+ this.permissionManager = permissionManager;
+ }
+
+ // Etc
+
+ @Override
+ public boolean useTimings() {
+ return co.aikar.timings.Timings.isTimingsEnabled();
+ }
+
+ @Override
+ public void registerInterface(@NotNull Class<? extends PluginLoader> loader) throws IllegalArgumentException {
+ throw new UnsupportedOperationException();
+ }
+
+ public MutableGraph<String> getInstanceManagerGraph() {
+ return instanceManager.getDependencyGraph();
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/manager/RuntimePluginEntrypointHandler.java b/src/main/java/io/papermc/paper/plugin/manager/RuntimePluginEntrypointHandler.java
new file mode 100644
index 0000000000000000000000000000000000000000..5d50d1d312388e979c0e1cd53a6bf5977ca6e549
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/manager/RuntimePluginEntrypointHandler.java
@@ -0,0 +1,47 @@
+package io.papermc.paper.plugin.manager;
+
+import com.destroystokyo.paper.util.SneakyThrow;
+import io.papermc.paper.plugin.entrypoint.Entrypoint;
+import io.papermc.paper.plugin.entrypoint.EntrypointHandler;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.storage.ProviderStorage;
+import org.bukkit.plugin.InvalidPluginException;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Used for loading plugins during runtime, only supporting providers that are plugins.
+ * This is only used for the plugin manager, as it only allows plugins to be
+ * registered to a provider storage.
+ */
+class RuntimePluginEntrypointHandler<T extends ProviderStorage<JavaPlugin>> implements EntrypointHandler {
+
+ private final T providerStorage;
+
+ RuntimePluginEntrypointHandler(T providerStorage) {
+ this.providerStorage = providerStorage;
+ }
+
+ @Override
+ public <T> void register(Entrypoint<T> entrypoint, PluginProvider<T> provider) {
+ if (!entrypoint.equals(Entrypoint.PLUGIN)) {
+ SneakyThrow.sneaky(new InvalidPluginException("Plugin cannot register entrypoints other than PLUGIN during runtime. Tried registering %s!".formatted(entrypoint)));
+ // We have to throw an invalid plugin exception for legacy reasons
+ }
+
+ this.providerStorage.register((PluginProvider<JavaPlugin>) provider);
+ }
+
+ @Override
+ public void enter(Entrypoint<?> entrypoint) {
+ if (entrypoint != Entrypoint.PLUGIN) {
+ throw new IllegalArgumentException("Only plugin entrypoint supported");
+ }
+ this.providerStorage.enter();
+ }
+
+ @NotNull
+ public T getPluginProviderStorage() {
+ return this.providerStorage;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/manager/SingularRuntimePluginProviderStorage.java b/src/main/java/io/papermc/paper/plugin/manager/SingularRuntimePluginProviderStorage.java
new file mode 100644
index 0000000000000000000000000000000000000000..b0e723bcda9b1fc01e6aa5e53e57c09ea4f1a1c8
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/manager/SingularRuntimePluginProviderStorage.java
@@ -0,0 +1,79 @@
+package io.papermc.paper.plugin.manager;
+
+import com.destroystokyo.paper.util.SneakyThrow;
+import io.papermc.paper.plugin.entrypoint.Entrypoint;
+import io.papermc.paper.plugin.entrypoint.LaunchEntryPointHandler;
+import io.papermc.paper.plugin.entrypoint.dependency.GraphDependencyContext;
+import io.papermc.paper.plugin.entrypoint.dependency.MetaDependencyTree;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.type.paper.PaperPluginParent;
+import io.papermc.paper.plugin.storage.ServerPluginProviderStorage;
+import org.bukkit.plugin.InvalidPluginException;
+import org.bukkit.plugin.PluginDescriptionFile;
+import org.bukkit.plugin.UnknownDependencyException;
+import org.bukkit.plugin.java.JavaPlugin;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Used for registering a single plugin provider.
+ * This has special behavior in that some errors are thrown instead of logged.
+ */
+class SingularRuntimePluginProviderStorage extends ServerPluginProviderStorage {
+
+ private final MetaDependencyTree dependencyTree;
+ private PluginProvider<JavaPlugin> lastProvider;
+ private JavaPlugin singleLoaded;
+
+ SingularRuntimePluginProviderStorage(MetaDependencyTree dependencyTree) {
+ this.dependencyTree = dependencyTree;
+ }
+
+ @Override
+ public void register(PluginProvider<JavaPlugin> provider) {
+ super.register(provider);
+ if (this.lastProvider != null) {
+ SneakyThrow.sneaky(new InvalidPluginException("Plugin registered two JavaPlugins"));
+ }
+ if (provider instanceof PaperPluginParent.PaperServerPluginProvider) {
+ throw new IllegalStateException("Cannot register paper plugins during runtime!");
+ }
+ this.lastProvider = provider;
+ // Register the provider into the server entrypoint, this allows it to show in /plugins correctly.
+ // Generally it might be better in the future to make a separate storage, as putting it into the entrypoint handlers doesn't make much sense.
+ LaunchEntryPointHandler.INSTANCE.register(Entrypoint.PLUGIN, provider);
+ }
+
+ @Override
+ public void enter() {
+ PluginProvider<JavaPlugin> provider = this.lastProvider;
+ if (provider == null) {
+ return;
+ }
+
+ // Go through normal plugin loading logic
+ super.enter();
+ }
+
+ @Override
+ public void processProvided(PluginProvider<JavaPlugin> provider, JavaPlugin provided) {
+ super.processProvided(provider, provided);
+ this.singleLoaded = provided;
+ }
+
+ @Override
+ public boolean throwOnCycle() {
+ return false;
+ }
+
+ public Optional<JavaPlugin> getSingleLoaded() {
+ return Optional.ofNullable(this.singleLoaded);
+ }
+
+ @Override
+ public MetaDependencyTree createDependencyTree() {
+ return this.dependencyTree;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/manager/StupidSPMPermissionManagerWrapper.java b/src/main/java/io/papermc/paper/plugin/manager/StupidSPMPermissionManagerWrapper.java
new file mode 100644
index 0000000000000000000000000000000000000000..ea8cf22c35242eb9f3914b95df00e20504aef5c1
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/manager/StupidSPMPermissionManagerWrapper.java
@@ -0,0 +1,42 @@
+package io.papermc.paper.plugin.manager;
+
+import org.bukkit.permissions.Permissible;
+import org.bukkit.permissions.Permission;
+import org.bukkit.plugin.SimplePluginManager;
+
+import java.util.Map;
+import java.util.Set;
+
+/*
+This is actually so cursed I hate it.
+We need to wrap these in fields as people override the fields, so we need to access them lazily at all times.
+// TODO: When SimplePluginManager is GONE remove this and cleanup the PaperPermissionManager to use actual fields.
+ */
+class StupidSPMPermissionManagerWrapper extends PaperPermissionManager {
+
+ private final SimplePluginManager simplePluginManager;
+
+ public StupidSPMPermissionManagerWrapper(SimplePluginManager simplePluginManager) {
+ this.simplePluginManager = simplePluginManager;
+ }
+
+ @Override
+ public Map<String, Permission> permissions() {
+ return this.simplePluginManager.permissions;
+ }
+
+ @Override
+ public Map<Boolean, Set<Permission>> defaultPerms() {
+ return this.simplePluginManager.defaultPerms;
+ }
+
+ @Override
+ public Map<String, Map<Permissible, Boolean>> permSubs() {
+ return this.simplePluginManager.permSubs;
+ }
+
+ @Override
+ public Map<Boolean, Map<Permissible, Boolean>> defSubs() {
+ return this.simplePluginManager.defSubs;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/PluginProvider.java b/src/main/java/io/papermc/paper/plugin/provider/PluginProvider.java
new file mode 100644
index 0000000000000000000000000000000000000000..fd9748c693a029c0d75f6ad813ea46a2b528d140
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/PluginProvider.java
@@ -0,0 +1,56 @@
+package io.papermc.paper.plugin.provider;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.configuration.LoadOrderConfiguration;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
+import org.jetbrains.annotations.ApiStatus;
+import org.jetbrains.annotations.NotNull;
+
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.JarFile;
+
+/**
+ * PluginProviders are created by a {@link io.papermc.paper.plugin.provider.source.ProviderSource},
+ * which is loaded into an {@link io.papermc.paper.plugin.entrypoint.EntrypointHandler}.
+ * <p>
+ * A PluginProvider is responsible for providing part of a plugin, whether it's a Bootstrapper or Server Plugin.
+ * The point of this class is to be able to create the actual instance later, as at the time this is created the server
+ * may be missing some key parts. For example, the Bukkit singleton will not be initialized yet, therefor we need to
+ * have a PluginServerProvider load the server plugin later.
+ * <p>
+ * Plugin providers are currently not exposed in any way of the api. It is preferred that this stays this way,
+ * as providers are only needed for initialization.
+ *
+ * @param <T> provider type
+ */
+@ApiStatus.Internal
+public interface PluginProvider<T> {
+
+ @NotNull
+ Path getSource();
+
+ default Path getFileName() {
+ return this.getSource().getFileName();
+ }
+
+ default Path getParentSource() {
+ return this.getSource().getParent();
+ }
+
+ JarFile file();
+
+ T createInstance();
+
+ PluginMeta getMeta();
+
+ ComponentLogger getLogger();
+
+ LoadOrderConfiguration createConfiguration(@NotNull Map<String, PluginProvider<?>> toLoad);
+
+ // Returns a list of missing dependencies
+ List<String> validateDependencies(@NotNull DependencyContext context);
+
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/ProviderStatus.java b/src/main/java/io/papermc/paper/plugin/provider/ProviderStatus.java
new file mode 100644
index 0000000000000000000000000000000000000000..6154e864b0ff01cb70acaaeee5ca8c9f4a90a90e
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/ProviderStatus.java
@@ -0,0 +1,13 @@
+package io.papermc.paper.plugin.provider;
+
+import org.jetbrains.annotations.ApiStatus;
+
+/**
+ * This is used for the /plugins command, where it will look in the {@link io.papermc.paper.plugin.entrypoint.LaunchEntryPointHandler} and
+ * use the provider statuses to determine the color.
+ */
+@ApiStatus.Internal
+public enum ProviderStatus {
+ INITIALIZED,
+ ERRORED,
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/ProviderStatusHolder.java b/src/main/java/io/papermc/paper/plugin/provider/ProviderStatusHolder.java
new file mode 100644
index 0000000000000000000000000000000000000000..17284d0f61c459dff765c0adae4ad2c641e054c1
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/ProviderStatusHolder.java
@@ -0,0 +1,11 @@
+package io.papermc.paper.plugin.provider;
+
+/**
+ * This is used to mark that a plugin provider is able to hold a status for the /plugins command.
+ */
+public interface ProviderStatusHolder {
+
+ ProviderStatus getLastProvidedStatus();
+
+ void setStatus(ProviderStatus status);
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/FlattenedResolver.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/FlattenedResolver.java
new file mode 100644
index 0000000000000000000000000000000000000000..6ba3bcc468c0a60c76d6d0f0243bda661c737f2f
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/FlattenedResolver.java
@@ -0,0 +1,29 @@
+package io.papermc.paper.plugin.provider.configuration;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.spongepowered.configurate.objectmapping.meta.NodeResolver;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.AnnotatedElement;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.FIELD)
+public @interface FlattenedResolver {
+
+ final class Factory implements NodeResolver.Factory {
+
+ @Override
+ public @Nullable NodeResolver make(String name, AnnotatedElement element) {
+ if (element.isAnnotationPresent(FlattenedResolver.class)) {
+ return (node) -> node;
+ } else {
+ return null;
+ }
+ }
+ }
+
+
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/LegacyPaperMeta.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/LegacyPaperMeta.java
new file mode 100644
index 0000000000000000000000000000000000000000..8cd649c977172f6b757d68565fcbb9eb8ae100a3
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/LegacyPaperMeta.java
@@ -0,0 +1,147 @@
+package io.papermc.paper.plugin.provider.configuration;
+
+import com.google.gson.reflect.TypeToken;
+import io.papermc.paper.plugin.provider.configuration.type.DependencyConfiguration;
+import io.papermc.paper.plugin.provider.configuration.type.PluginDependencyLifeCycle;
+import org.spongepowered.configurate.CommentedConfigurationNode;
+import org.spongepowered.configurate.ConfigurateException;
+import org.spongepowered.configurate.NodePath;
+import org.spongepowered.configurate.objectmapping.ConfigSerializable;
+import org.spongepowered.configurate.objectmapping.meta.Required;
+import org.spongepowered.configurate.serialize.SerializationException;
+import org.spongepowered.configurate.transformation.ConfigurationTransformation;
+
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+class LegacyPaperMeta {
+
+
+ private static final TypeToken<Map<PluginDependencyLifeCycle, Map<String, DependencyConfiguration>>> TYPE_TOKEN = new TypeToken<>() {
+ };
+
+ public static void migrate(CommentedConfigurationNode node) throws ConfigurateException {
+ ConfigurationTransformation.chain(notVersioned()).apply(node);
+ }
+
+ private static ConfigurationTransformation notVersioned() {
+ return ConfigurationTransformation.builder()
+ .addAction(NodePath.path(), (path, value) -> {
+ boolean bootstrapSubSection = value.hasChild("bootstrap");
+ boolean serverSubSection = value.hasChild("server");
+
+ // Ignore if using newer format
+ if (bootstrapSubSection || serverSubSection) {
+ return null;
+ }
+
+ // First collect all load before elements
+ LegacyConfiguration legacyConfiguration;
+ try {
+ legacyConfiguration = value.require(LegacyConfiguration.class);
+ } catch (SerializationException exception) {
+ // Ignore if not present
+ return null;
+ }
+
+ Map<PluginDependencyLifeCycle, Map<String, DependencyConfiguration>> dependencies = new EnumMap<>(PluginDependencyLifeCycle.class);
+ dependencies.put(PluginDependencyLifeCycle.BOOTSTRAP, new HashMap<>());
+ dependencies.put(PluginDependencyLifeCycle.SERVER, new HashMap<>());
+
+ Map<PluginDependencyLifeCycle, Map<String, Set<DependencyFlag>>> dependencyConfigurationMap = new HashMap<>();
+ dependencyConfigurationMap.put(PluginDependencyLifeCycle.BOOTSTRAP, new HashMap<>());
+ dependencyConfigurationMap.put(PluginDependencyLifeCycle.SERVER, new HashMap<>());
+
+ // Migrate loadafter
+ for (LegacyLoadConfiguration legacyConfig : legacyConfiguration.loadAfter) {
+ Set<DependencyFlag> dependencyFlags = dependencyConfigurationMap
+ .get(legacyConfig.bootstrap ? PluginDependencyLifeCycle.BOOTSTRAP : PluginDependencyLifeCycle.SERVER)
+ .computeIfAbsent(legacyConfig.name, s -> EnumSet.noneOf(DependencyFlag.class));
+
+ dependencyFlags.add(DependencyFlag.LOAD_AFTER);
+ }
+
+ // Migrate loadbefore
+ for (LegacyLoadConfiguration legacyConfig : legacyConfiguration.loadBefore) {
+ Set<DependencyFlag> dependencyFlags = dependencyConfigurationMap
+ .get(legacyConfig.bootstrap ? PluginDependencyLifeCycle.BOOTSTRAP : PluginDependencyLifeCycle.SERVER)
+ .computeIfAbsent(legacyConfig.name, s -> EnumSet.noneOf(DependencyFlag.class));
+
+ dependencyFlags.add(DependencyFlag.LOAD_BEFORE);
+ }
+
+ // Migrate dependencies
+ for (LegacyDependencyConfiguration legacyConfig : legacyConfiguration.dependencies) {
+ Set<DependencyFlag> dependencyFlags = dependencyConfigurationMap
+ .get(legacyConfig.bootstrap ? PluginDependencyLifeCycle.BOOTSTRAP : PluginDependencyLifeCycle.SERVER)
+ .computeIfAbsent(legacyConfig.name, s -> EnumSet.noneOf(DependencyFlag.class));
+
+ dependencyFlags.add(DependencyFlag.DEPENDENCY);
+ if (legacyConfig.required) {
+ dependencyFlags.add(DependencyFlag.REQUIRED);
+ }
+ }
+ for (Map.Entry<PluginDependencyLifeCycle, Map<String, Set<DependencyFlag>>> legacyTypes : dependencyConfigurationMap.entrySet()) {
+ Map<String, DependencyConfiguration> flagMap = dependencies.get(legacyTypes.getKey());
+ for (Map.Entry<String, Set<DependencyFlag>> entry : legacyTypes.getValue().entrySet()) {
+ Set<DependencyFlag> flags = entry.getValue();
+
+
+ DependencyConfiguration.LoadOrder loadOrder = DependencyConfiguration.LoadOrder.OMIT;
+ // These meanings are now swapped
+ if (flags.contains(DependencyFlag.LOAD_BEFORE)) {
+ loadOrder = DependencyConfiguration.LoadOrder.AFTER;
+ } else if (flags.contains(DependencyFlag.LOAD_AFTER)) {
+ loadOrder = DependencyConfiguration.LoadOrder.BEFORE;
+ }
+
+ flagMap.put(entry.getKey(), new DependencyConfiguration(
+ loadOrder,
+ flags.contains(DependencyFlag.REQUIRED),
+ flags.contains(DependencyFlag.DEPENDENCY)
+ ));
+ }
+ }
+
+ value.node("dependencies").set(TYPE_TOKEN.getType(), dependencies);
+ return null;
+ })
+ .build();
+ }
+
+ @ConfigSerializable
+ record LegacyLoadConfiguration(
+ @Required String name,
+ boolean bootstrap
+ ) {
+ }
+
+ @ConfigSerializable
+ private static class LegacyConfiguration {
+
+ private List<LegacyLoadConfiguration> loadAfter = List.of();
+ private List<LegacyLoadConfiguration> loadBefore = List.of();
+ private List<LegacyDependencyConfiguration> dependencies = List.of();
+ }
+
+
+ @ConfigSerializable
+ public record LegacyDependencyConfiguration(
+ @Required String name,
+ boolean required,
+ boolean bootstrap
+ ) {
+ }
+
+ enum DependencyFlag {
+ LOAD_AFTER,
+ LOAD_BEFORE,
+ REQUIRED,
+ DEPENDENCY
+ }
+
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/LoadOrderConfiguration.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/LoadOrderConfiguration.java
new file mode 100644
index 0000000000000000000000000000000000000000..e3430f535e8e9c3b8b44bf2daece8c47e8b14db7
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/LoadOrderConfiguration.java
@@ -0,0 +1,38 @@
+package io.papermc.paper.plugin.provider.configuration;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.List;
+
+/**
+ * This is used for plugins to configure the load order of strategies.
+ */
+public interface LoadOrderConfiguration {
+
+ /**
+ * Provides a list of plugins that THIS configuration should load
+ * before.
+ *
+ * @return list of plugins
+ */
+ @NotNull
+ List<String> getLoadBefore();
+
+ /**
+ * Provides a list of plugins that THIS configuration should load
+ * before.
+ *
+ * @return list of plugins
+ */
+ @NotNull
+ List<String> getLoadAfter();
+
+ /**
+ * Gets the responsible plugin provider's meta.
+ *
+ * @return meta
+ */
+ @NotNull
+ PluginMeta getMeta();
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/PaperPluginMeta.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/PaperPluginMeta.java
new file mode 100644
index 0000000000000000000000000000000000000000..45bd29b70782e29eb11c36eaca0f940aee49799b
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/PaperPluginMeta.java
@@ -0,0 +1,248 @@
+package io.papermc.paper.plugin.provider.configuration;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import io.papermc.paper.configuration.constraint.Constraint;
+import io.papermc.paper.configuration.serializer.ComponentSerializer;
+import io.papermc.paper.configuration.serializer.EnumValueSerializer;
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.configuration.serializer.PermissionConfigurationSerializer;
+import io.papermc.paper.plugin.provider.configuration.serializer.constraints.PluginConfigConstraints;
+import io.papermc.paper.plugin.provider.configuration.type.DependencyConfiguration;
+import io.papermc.paper.plugin.provider.configuration.type.PermissionConfiguration;
+import io.papermc.paper.plugin.provider.configuration.type.PluginDependencyLifeCycle;
+import org.bukkit.permissions.Permission;
+import org.bukkit.permissions.PermissionDefault;
+import org.bukkit.plugin.PluginLoadOrder;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.TestOnly;
+import org.spongepowered.configurate.CommentedConfigurationNode;
+import org.spongepowered.configurate.ConfigurateException;
+import org.spongepowered.configurate.loader.HeaderMode;
+import org.spongepowered.configurate.objectmapping.ConfigSerializable;
+import org.spongepowered.configurate.objectmapping.ObjectMapper;
+import org.spongepowered.configurate.objectmapping.meta.Required;
+import org.spongepowered.configurate.yaml.NodeStyle;
+import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
+
+import java.io.BufferedReader;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+
+@SuppressWarnings({"CanBeFinal", "FieldCanBeLocal", "FieldMayBeFinal", "NotNullFieldNotInitialized", "InnerClassMayBeStatic"})
+@ConfigSerializable
+public class PaperPluginMeta implements PluginMeta {
+
+ @PluginConfigConstraints.PluginName
+ @Required
+ private String name;
+ @Required
+ @PluginConfigConstraints.PluginNameSpace
+ private String main;
+ @PluginConfigConstraints.PluginNameSpace
+ private String bootstrapper;
+ @PluginConfigConstraints.PluginNameSpace
+ private String loader;
+ private List<String> provides = List.of();
+ private boolean hasOpenClassloader = false;
+ @Required
+ private String version;
+ private String description;
+ private List<String> authors = List.of();
+ private List<String> contributors = List.of();
+ private String website;
+ private String prefix;
+ private PluginLoadOrder load = PluginLoadOrder.POSTWORLD;
+ @FlattenedResolver
+ private PermissionConfiguration permissionConfiguration = new PermissionConfiguration(PermissionDefault.OP, List.of());
+ @Required
+ @PluginConfigConstraints.PluginVersion
+ private String apiVersion;
+
+ private Map<PluginDependencyLifeCycle, Map<String, DependencyConfiguration>> dependencies = new EnumMap<>(PluginDependencyLifeCycle.class);
+
+ public PaperPluginMeta() {
+ }
+
+ public static PaperPluginMeta create(BufferedReader reader) throws ConfigurateException {
+ YamlConfigurationLoader loader = YamlConfigurationLoader.builder()
+ .indent(2)
+ .nodeStyle(NodeStyle.BLOCK)
+ .headerMode(HeaderMode.NONE)
+ .source(() -> reader)
+ .defaultOptions((options) -> {
+
+ return options.serializers((serializers) -> {
+ serializers
+ .register(new EnumValueSerializer())
+ .register(PermissionConfiguration.class, PermissionConfigurationSerializer.SERIALIZER)
+ .register(new ComponentSerializer())
+ .registerAnnotatedObjects(
+ ObjectMapper.factoryBuilder()
+ .addConstraint(Constraint.class, new Constraint.Factory())
+ .addConstraint(PluginConfigConstraints.PluginName.class, String.class, new PluginConfigConstraints.PluginName.Factory())
+ .addConstraint(PluginConfigConstraints.PluginVersion.class, String.class, new PluginConfigConstraints.PluginVersion.Factory())
+ .addConstraint(PluginConfigConstraints.PluginNameSpace.class, String.class, new PluginConfigConstraints.PluginNameSpace.Factory())
+ .addNodeResolver(new FlattenedResolver.Factory())
+ .build()
+ );
+
+ });
+ })
+ .build();
+ CommentedConfigurationNode node = loader.load();
+ LegacyPaperMeta.migrate(node);
+ PaperPluginMeta pluginConfiguration = node.require(PaperPluginMeta.class);
+
+ if (!node.node("author").virtual()) {
+ pluginConfiguration.authors = ImmutableList.<String>builder()
+ .addAll(pluginConfiguration.authors)
+ .add(node.node("author").getString())
+ .build();
+ }
+
+ return pluginConfiguration;
+ }
+
+ @Override
+ public @NotNull String getName() {
+ return this.name;
+ }
+
+ @TestOnly
+ public void setName(@NotNull String name) {
+ Preconditions.checkNotNull(name, "name");
+ this.name = name;
+ }
+
+ @Override
+ public @NotNull String getMainClass() {
+ return this.main;
+ }
+
+ @Override
+ public @NotNull String getVersion() {
+ return this.version;
+ }
+
+ @TestOnly
+ public void setVersion(@NotNull String version) {
+ Preconditions.checkNotNull(version, "version");
+ this.version = version;
+ }
+
+ @Override
+ public @Nullable String getLoggerPrefix() {
+ return this.prefix;
+ }
+
+ @Override
+ public @NotNull List<String> getPluginDependencies() {
+ return this.dependencies.getOrDefault(PluginDependencyLifeCycle.SERVER, Map.of())
+ .entrySet()
+ .stream()
+ .filter((entry) -> entry.getValue().required() && entry.getValue().joinClasspath())
+ .map(Map.Entry::getKey)
+ .toList();
+ }
+
+ @Override
+ public @NotNull List<String> getPluginSoftDependencies() {
+ return this.dependencies.getOrDefault(PluginDependencyLifeCycle.SERVER, Map.of())
+ .entrySet()
+ .stream()
+ .filter((entry) -> !entry.getValue().required() && entry.getValue().joinClasspath())
+ .map(Map.Entry::getKey)
+ .toList();
+ }
+
+ @Override
+ public @NotNull List<String> getLoadBeforePlugins() {
+ return this.dependencies.getOrDefault(PluginDependencyLifeCycle.SERVER, Map.of())
+ .entrySet()
+ .stream()
+ // This plugin will load BEFORE all dependencies (so dependencies will load AFTER plugin)
+ .filter((entry) -> entry.getValue().load() == DependencyConfiguration.LoadOrder.AFTER)
+ .map(Map.Entry::getKey)
+ .toList();
+ }
+
+ public @NotNull List<String> getLoadAfterPlugins() {
+ return this.dependencies.getOrDefault(PluginDependencyLifeCycle.SERVER, Map.of())
+ .entrySet()
+ .stream()
+ // This plugin will load AFTER all dependencies (so dependencies will load BEFORE plugin)
+ .filter((entry) -> entry.getValue().load() == DependencyConfiguration.LoadOrder.BEFORE)
+ .map(Map.Entry::getKey)
+ .toList();
+ }
+
+
+ public Map<String, DependencyConfiguration> getServerDependencies() {
+ return this.dependencies.getOrDefault(PluginDependencyLifeCycle.SERVER, Map.of());
+ }
+
+ public Map<String, DependencyConfiguration> getBoostrapDependencies() {
+ return this.dependencies.getOrDefault(PluginDependencyLifeCycle.BOOTSTRAP, Map.of());
+ }
+
+ @Override
+ public @NotNull PluginLoadOrder getLoadOrder() {
+ return this.load;
+ }
+
+ @Override
+ public @NotNull String getDescription() {
+ return this.description;
+ }
+
+ @Override
+ public @NotNull List<String> getAuthors() {
+ return this.authors;
+ }
+
+ @Override
+ public @NotNull List<String> getContributors() {
+ return this.contributors;
+ }
+
+ @Override
+ public String getWebsite() {
+ return this.website;
+ }
+
+ @Override
+ public @NotNull List<Permission> getPermissions() {
+ return this.permissionConfiguration.permissions();
+ }
+
+ @Override
+ public @NotNull PermissionDefault getPermissionDefault() {
+ return this.permissionConfiguration.defaultPerm();
+ }
+
+ @Override
+ public @NotNull String getAPIVersion() {
+ return this.apiVersion;
+ }
+
+ @Override
+ public @NotNull List<String> getProvidedPlugins() {
+ return this.provides;
+ }
+
+ public String getBootstrapper() {
+ return this.bootstrapper;
+ }
+
+ public String getLoader() {
+ return this.loader;
+ }
+
+ public boolean hasOpenClassloader() {
+ return this.hasOpenClassloader;
+ }
+
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/ImmutableCollectionSerializer.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/ImmutableCollectionSerializer.java
new file mode 100644
index 0000000000000000000000000000000000000000..f0cdb1bab30faaa438aa3e6de6125ade3fae98c2
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/ImmutableCollectionSerializer.java
@@ -0,0 +1,90 @@
+package io.papermc.paper.plugin.provider.configuration.serializer;
+
+import com.google.common.collect.ImmutableCollection;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.spongepowered.configurate.ConfigurationNode;
+import org.spongepowered.configurate.ConfigurationOptions;
+import org.spongepowered.configurate.serialize.SerializationException;
+import org.spongepowered.configurate.serialize.TypeSerializer;
+import org.spongepowered.configurate.util.CheckedConsumer;
+
+import java.lang.reflect.Type;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+@SuppressWarnings("unchecked")
+public abstract class ImmutableCollectionSerializer<B extends ImmutableCollection.Builder<?>, T extends Collection<?>> implements TypeSerializer<T> {
+
+ protected ImmutableCollectionSerializer() {
+ }
+
+ @Override
+ public final T deserialize(final Type type, final ConfigurationNode node) throws SerializationException {
+ final Type entryType = this.elementType(type);
+ final @Nullable TypeSerializer<?> entrySerial = node.options().serializers().get(entryType);
+ if (entrySerial == null) {
+ throw new SerializationException(node, entryType, "No applicable type serializer for type");
+ }
+
+ if (node.isList()) {
+ final List<? extends ConfigurationNode> values = node.childrenList();
+ final B builder = this.createNew(values.size());
+ for (ConfigurationNode value : values) {
+ try {
+ this.deserializeSingle(builder, entrySerial.deserialize(entryType, value));
+ } catch (final SerializationException ex) {
+ ex.initPath(value::path);
+ throw ex;
+ }
+ }
+ return (T) builder.build();
+ } else {
+ final @Nullable Object unwrappedVal = node.raw();
+ if (unwrappedVal != null) {
+ final B builder = this.createNew(1);
+ this.deserializeSingle(builder, entrySerial.deserialize(entryType, node));
+ return (T) builder.build();
+ }
+ }
+ return this.emptyValue(type, null);
+ }
+
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ @Override
+ public final void serialize(final Type type, final @Nullable T obj, final ConfigurationNode node) throws SerializationException {
+ final Type entryType = this.elementType(type);
+ final @Nullable TypeSerializer entrySerial = node.options().serializers().get(entryType);
+ if (entrySerial == null) {
+ throw new SerializationException(node, entryType, "No applicable type serializer for type");
+ }
+
+ node.raw(Collections.emptyList());
+ if (obj != null) {
+ this.forEachElement(obj, el -> {
+ final ConfigurationNode child = node.appendListNode();
+ try {
+ entrySerial.serialize(entryType, el, child);
+ } catch (final SerializationException ex) {
+ ex.initPath(child::path);
+ throw ex;
+ }
+ });
+ }
+ }
+
+ @SuppressWarnings({"unchecked"})
+ @Override
+ public @Nullable T emptyValue(final Type specificType, final ConfigurationOptions options) {
+ return (T) this.createNew(0).build();
+ }
+
+ protected abstract Type elementType(Type containerType) throws SerializationException;
+
+ protected abstract B createNew(int size);
+
+ protected abstract void forEachElement(T collection, CheckedConsumer<Object, SerializationException> action) throws SerializationException;
+
+ protected abstract void deserializeSingle(B builder, @Nullable Object deserialized) throws SerializationException;
+
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/ImmutableListSerializer.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/ImmutableListSerializer.java
new file mode 100644
index 0000000000000000000000000000000000000000..7757d7df70e39a6fe4d92d02b6f905a22f80dbf3
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/ImmutableListSerializer.java
@@ -0,0 +1,43 @@
+package io.papermc.paper.plugin.provider.configuration.serializer;
+
+import com.google.common.collect.ImmutableList;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.spongepowered.configurate.serialize.SerializationException;
+import org.spongepowered.configurate.util.CheckedConsumer;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.List;
+
+public class ImmutableListSerializer extends ImmutableCollectionSerializer<ImmutableList.Builder<?>, List<?>> {
+
+ @Override
+ protected Type elementType(Type containerType) throws SerializationException {
+ if (!(containerType instanceof ParameterizedType)) {
+ throw new SerializationException(containerType, "Raw types are not supported for collections");
+ }
+ return ((ParameterizedType) containerType).getActualTypeArguments()[0];
+ }
+
+ @Override
+ protected ImmutableList.Builder<?> createNew(int size) {
+ return ImmutableList.builderWithExpectedSize(size);
+ }
+
+ @Override
+ protected void forEachElement(List<?> collection, CheckedConsumer<Object, SerializationException> action) throws SerializationException {
+ for (Object obj : collection) {
+ action.accept(obj);
+ }
+ }
+
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ @Override
+ protected void deserializeSingle(ImmutableList.Builder<?> builder, @Nullable Object deserialized) throws SerializationException {
+ if (deserialized == null) {
+ return;
+ }
+
+ ((ImmutableList.Builder) builder).add(deserialized);
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/PermissionConfigurationSerializer.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/PermissionConfigurationSerializer.java
new file mode 100644
index 0000000000000000000000000000000000000000..f951f4024745503e9cdfa7ff17b9313ac6d7b4c4
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/PermissionConfigurationSerializer.java
@@ -0,0 +1,56 @@
+package io.papermc.paper.plugin.provider.configuration.serializer;
+
+import io.papermc.paper.plugin.provider.configuration.type.PermissionConfiguration;
+import org.bukkit.permissions.Permission;
+import org.bukkit.permissions.PermissionDefault;
+import org.spongepowered.configurate.ConfigurationNode;
+import org.spongepowered.configurate.serialize.SerializationException;
+import org.spongepowered.configurate.serialize.TypeSerializer;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class PermissionConfigurationSerializer {
+
+ public static final Serializer SERIALIZER = new Serializer();
+
+ private static final class Serializer implements TypeSerializer<PermissionConfiguration> {
+ private Serializer() {
+ super();
+ }
+
+ @Override
+ public PermissionConfiguration deserialize(Type type, ConfigurationNode node) throws SerializationException {
+ Map<?, ?> map = (Map<?, ?>) node.node("permissions").raw();
+
+ PermissionDefault permissionDefault;
+ ConfigurationNode permNode = node.node("defaultPerm");
+ if (permNode.virtual()) {
+ permissionDefault = PermissionDefault.OP;
+ } else {
+ permissionDefault = PermissionDefault.getByName(permNode.getString());
+ }
+
+ List<Permission> result = new ArrayList<>();
+ if (map != null) {
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
+ try {
+ result.add(Permission.loadPermission(entry.getKey().toString(), (Map<?, ?>) entry.getValue(), permissionDefault, result));
+ } catch (Throwable ex) {
+ throw new SerializationException((Type) null, "Error loading permission %s".formatted(entry.getKey()), ex);
+ }
+ }
+ }
+
+ return new PermissionConfiguration(permissionDefault, List.copyOf(result));
+ }
+
+ @Override
+ public void serialize(Type type, @org.checkerframework.checker.nullness.qual.Nullable PermissionConfiguration obj, ConfigurationNode node) throws SerializationException {
+
+ }
+
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/constraints/PluginConfigConstraints.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/constraints/PluginConfigConstraints.java
new file mode 100644
index 0000000000000000000000000000000000000000..2e02f73b857c530a0cce3a8d6aae46e3b0966486
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/serializer/constraints/PluginConfigConstraints.java
@@ -0,0 +1,86 @@
+package io.papermc.paper.plugin.provider.configuration.serializer.constraints;
+
+import io.papermc.paper.plugin.util.NamespaceChecker;
+import org.spongepowered.configurate.objectmapping.meta.Constraint;
+import org.spongepowered.configurate.serialize.SerializationException;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.Type;
+import java.util.Locale;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+public final class PluginConfigConstraints {
+
+ public static final Set<String> RESERVED_KEYS = Set.of("bukkit", "minecraft", "mojang", "spigot", "paper");
+ public static final Set<String> VALID_PAPER_VERSIONS = Set.of("1.19", "1.20");
+
+ @Documented
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target(ElementType.FIELD)
+ public @interface PluginName {
+
+ final class Factory implements Constraint.Factory<PluginName, String> {
+
+ private static final Pattern VALID_NAME = Pattern.compile("^[A-Za-z\\d _.-]+$");
+
+ @Override
+ public Constraint<String> make(PluginName data, Type type) {
+ return value -> {
+ if (value != null) {
+ if (RESERVED_KEYS.contains(value.toLowerCase(Locale.ROOT))) {
+ throw new SerializationException("Restricted name, cannot use '%s' as a plugin name.".formatted(data));
+ } else if (value.indexOf(' ') != -1) {
+ // For legacy reasons, the space condition has a separate exception message.
+ throw new SerializationException("Restricted name, cannot use 0x20 (space character) in a plugin name.");
+ }
+
+ if (!VALID_NAME.matcher(value).matches()) {
+ throw new SerializationException("name '" + value + "' contains invalid characters.");
+ }
+ }
+ };
+ }
+ }
+ }
+
+ @Documented
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target(ElementType.FIELD)
+ public @interface PluginNameSpace {
+
+ final class Factory implements Constraint.Factory<PluginNameSpace, String> {
+
+ @Override
+ public Constraint<String> make(PluginNameSpace data, Type type) {
+ return value -> {
+ if (value != null && !NamespaceChecker.isValidNameSpace(value)) {
+ throw new SerializationException("provided class '%s' is in an invalid namespace.".formatted(value));
+ }
+ };
+ }
+ }
+ }
+
+ @Documented
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target(ElementType.FIELD)
+ public @interface PluginVersion {
+
+ final class Factory implements Constraint.Factory<PluginVersion, String> {
+
+ @Override
+ public Constraint<String> make(PluginVersion data, Type type) {
+ return value -> {
+ if (value != null && !VALID_PAPER_VERSIONS.contains(value)) {
+ throw new SerializationException("Provided plugin's version (%s) is not supported on this version.".formatted(value));
+ }
+ };
+ }
+ }
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/type/DependencyConfiguration.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/type/DependencyConfiguration.java
new file mode 100644
index 0000000000000000000000000000000000000000..957fb5e60ba6bd8760e8f6016d7bb6e8a405e163
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/type/DependencyConfiguration.java
@@ -0,0 +1,30 @@
+package io.papermc.paper.plugin.provider.configuration.type;
+
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.framework.qual.DefaultQualifier;
+import org.spongepowered.configurate.objectmapping.ConfigSerializable;
+
+import static java.util.Objects.requireNonNullElse;
+
+@DefaultQualifier(NonNull.class)
+@ConfigSerializable
+public record DependencyConfiguration(
+ LoadOrder load,
+ Boolean required,
+ Boolean joinClasspath
+) {
+ @SuppressWarnings("DataFlowIssue") // incorrect intellij inspections
+ public DependencyConfiguration {
+ required = requireNonNullElse(required, true);
+ joinClasspath = requireNonNullElse(joinClasspath, true);
+ }
+
+ @ConfigSerializable
+ public enum LoadOrder {
+ // dependency will now load BEFORE your plugin
+ BEFORE,
+ // the dependency will now load AFTER your plugin
+ AFTER,
+ OMIT
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/type/LoadConfiguration.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/type/LoadConfiguration.java
new file mode 100644
index 0000000000000000000000000000000000000000..4184e4232c59f15ef8bbc98f82f501fc524f37c7
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/type/LoadConfiguration.java
@@ -0,0 +1,11 @@
+package io.papermc.paper.plugin.provider.configuration.type;
+
+import org.spongepowered.configurate.objectmapping.ConfigSerializable;
+import org.spongepowered.configurate.objectmapping.meta.Required;
+
+@ConfigSerializable
+public record LoadConfiguration(
+ @Required String name,
+ boolean bootstrap
+) {
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/type/PermissionConfiguration.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/type/PermissionConfiguration.java
new file mode 100644
index 0000000000000000000000000000000000000000..a180612a1ec395202dbae1ca5b97ec01382097e4
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/type/PermissionConfiguration.java
@@ -0,0 +1,14 @@
+package io.papermc.paper.plugin.provider.configuration.type;
+
+import org.bukkit.permissions.Permission;
+import org.bukkit.permissions.PermissionDefault;
+import org.spongepowered.configurate.objectmapping.ConfigSerializable;
+
+import java.util.List;
+
+// Record components used for deserialization!!!!
+@ConfigSerializable
+public record PermissionConfiguration(
+ PermissionDefault defaultPerm,
+ List<Permission> permissions) {
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/configuration/type/PluginDependencyLifeCycle.java b/src/main/java/io/papermc/paper/plugin/provider/configuration/type/PluginDependencyLifeCycle.java
new file mode 100644
index 0000000000000000000000000000000000000000..49a087381307eab263f7dad43aaa25980db33cc2
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/configuration/type/PluginDependencyLifeCycle.java
@@ -0,0 +1,6 @@
+package io.papermc.paper.plugin.provider.configuration.type;
+
+public enum PluginDependencyLifeCycle {
+ BOOTSTRAP,
+ SERVER
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/source/DirectoryProviderSource.java b/src/main/java/io/papermc/paper/plugin/provider/source/DirectoryProviderSource.java
new file mode 100644
index 0000000000000000000000000000000000000000..226f457db6c1461c943c157b2b91e7450abc9dc6
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/source/DirectoryProviderSource.java
@@ -0,0 +1,66 @@
+package io.papermc.paper.plugin.provider.source;
+
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.plugin.entrypoint.EntrypointHandler;
+import java.io.IOException;
+import java.nio.file.FileVisitOption;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Consumer;
+import org.slf4j.Logger;
+
+/**
+ * Loads all plugin providers in the given directory.
+ */
+public class DirectoryProviderSource implements ProviderSource<Path, List<Path>> {
+
+ public static final DirectoryProviderSource INSTANCE = new DirectoryProviderSource();
+ private static final FileProviderSource FILE_PROVIDER_SOURCE = new FileProviderSource("Directory '%s'"::formatted);
+ private static final Logger LOGGER = LogUtils.getClassLogger();
+
+ @Override
+ public List<Path> prepareContext(Path context) throws IOException {
+ // Symlink happy, create file if missing.
+ if (!Files.isDirectory(context)) {
+ Files.createDirectories(context);
+ }
+
+ final List<Path> files = new ArrayList<>();
+ this.walkFiles(context, path -> {
+ try {
+ files.add(FILE_PROVIDER_SOURCE.prepareContext(path));
+ } catch (IllegalArgumentException ignored) {
+ // Ignore illegal argument exceptions from jar checking
+ } catch (final Exception e) {
+ LOGGER.error("Error preparing plugin context: " + e.getMessage(), e);
+ }
+ });
+ return files;
+ }
+
+ @Override
+ public void registerProviders(EntrypointHandler entrypointHandler, List<Path> context) {
+ for (Path path : context) {
+ try {
+ FILE_PROVIDER_SOURCE.registerProviders(entrypointHandler, path);
+ } catch (IllegalArgumentException ignored) {
+ // Ignore illegal argument exceptions from jar checking
+ } catch (Exception e) {
+ LOGGER.error("Error loading plugin: " + e.getMessage(), e);
+ }
+ }
+ }
+
+ private void walkFiles(Path context, Consumer<Path> consumer) throws IOException {
+ Files.walk(context, 1, FileVisitOption.FOLLOW_LINKS)
+ .filter(this::isValidFile)
+ .forEach(consumer);
+ }
+
+ public boolean isValidFile(Path path) {
+ // Avoid loading plugins that start with a dot
+ return Files.isRegularFile(path) && !path.startsWith(".");
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/source/FileArrayProviderSource.java b/src/main/java/io/papermc/paper/plugin/provider/source/FileArrayProviderSource.java
new file mode 100644
index 0000000000000000000000000000000000000000..b2ec31fdb2ba8f18c29f2014c03c96a15ec995ad
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/source/FileArrayProviderSource.java
@@ -0,0 +1,44 @@
+package io.papermc.paper.plugin.provider.source;
+
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.plugin.entrypoint.EntrypointHandler;
+import java.io.File;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import org.slf4j.Logger;
+
+public class FileArrayProviderSource implements ProviderSource<File[], List<Path>> {
+
+ public static final FileArrayProviderSource INSTANCE = new FileArrayProviderSource();
+ private static final FileProviderSource FILE_PROVIDER_SOURCE = new FileProviderSource("File '%s'"::formatted);
+ private static final Logger LOGGER = LogUtils.getClassLogger();
+
+ @Override
+ public List<Path> prepareContext(File[] context) {
+ final List<Path> files = new ArrayList<>();
+ for (File file : context) {
+ try {
+ files.add(FILE_PROVIDER_SOURCE.prepareContext(file.toPath()));
+ } catch (IllegalArgumentException ignored) {
+ // Ignore illegal argument exceptions from jar checking
+ } catch (final Exception e) {
+ LOGGER.error("Error preparing plugin context: " + e.getMessage(), e);
+ }
+ }
+ return files;
+ }
+
+ @Override
+ public void registerProviders(EntrypointHandler entrypointHandler, List<Path> context) {
+ for (Path path : context) {
+ try {
+ FILE_PROVIDER_SOURCE.registerProviders(entrypointHandler, path);
+ } catch (IllegalArgumentException ignored) {
+ // Ignore illegal argument exceptions from jar checking
+ } catch (Exception e) {
+ LOGGER.error("Error loading plugin: " + e.getMessage(), e);
+ }
+ }
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/source/FileProviderSource.java b/src/main/java/io/papermc/paper/plugin/provider/source/FileProviderSource.java
new file mode 100644
index 0000000000000000000000000000000000000000..5b58df8df7efca0f67e3a14dd71051dfd7a26079
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/source/FileProviderSource.java
@@ -0,0 +1,171 @@
+package io.papermc.paper.plugin.provider.source;
+
+import io.papermc.paper.plugin.PluginInitializerManager;
+import io.papermc.paper.plugin.entrypoint.EntrypointHandler;
+import io.papermc.paper.plugin.provider.type.PluginFileType;
+import org.bukkit.plugin.InvalidPluginException;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.FileVisitor;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.jar.JarFile;
+
+/**
+ * Loads a plugin provider at the given plugin jar file path.
+ */
+public class FileProviderSource implements ProviderSource<Path, Path> {
+
+ private final Function<Path, String> contextChecker;
+
+ public FileProviderSource(Function<Path, String> contextChecker) {
+ this.contextChecker = contextChecker;
+ }
+
+ @Override
+ public Path prepareContext(Path context) throws IOException {
+ String source = this.contextChecker.apply(context);
+
+ if (Files.notExists(context)) {
+ throw new IllegalArgumentException(source + " does not exist, cannot load a plugin from it!");
+ }
+
+ if (!Files.isRegularFile(context)) {
+ throw new IllegalArgumentException(source + " is not a file, cannot load a plugin from it!");
+ }
+
+ if (!context.getFileName().toString().endsWith(".jar")) {
+ throw new IllegalArgumentException(source + " is not a jar file, cannot load a plugin from it!");
+ }
+
+ try {
+ context = this.checkUpdate(context);
+ } catch (Exception exception) {
+ throw new RuntimeException(source + " failed to update!", exception);
+ }
+ return context;
+ }
+
+ @Override
+ public void registerProviders(EntrypointHandler entrypointHandler, Path context) throws Exception {
+ String source = this.contextChecker.apply(context);
+
+ JarFile file = new JarFile(context.toFile(), true, JarFile.OPEN_READ, JarFile.runtimeVersion());
+ PluginFileType<?, ?> type = PluginFileType.guessType(file);
+ if (type == null) {
+ // Throw IAE wrapped in RE to prevent callers from considering this a "invalid parameter" as caller ignores IAE.
+ // TODO: This needs some heavy rework, using illegal argument exception to signal an actual failure is less than ideal.
+ if (file.getEntry("META-INF/versions.list") != null) {
+ throw new RuntimeException(new IllegalArgumentException(context + " appears to be a server jar! Server jars do not belong in the plugin folder."));
+ }
+
+ throw new RuntimeException(
+ new IllegalArgumentException(source + " does not contain a " + String.join(" or ", PluginFileType.getConfigTypes()) + "! Could not determine plugin type, cannot load a plugin from it!")
+ );
+ }
+
+ type.register(entrypointHandler, file, context);
+ }
+
+ /**
+ * Replaces a plugin with a plugin of the same plugin name in the update folder.
+ *
+ * @param file
+ */
+ private Path checkUpdate(Path file) throws InvalidPluginException {
+ PluginInitializerManager pluginSystem = PluginInitializerManager.instance();
+ Path updateDirectory = pluginSystem.pluginUpdatePath();
+ if (updateDirectory == null || !Files.isDirectory(updateDirectory)) {
+ return file;
+ }
+
+ try {
+ String pluginName = this.getPluginName(file);
+ UpdateFileVisitor visitor = new UpdateFileVisitor(pluginName);
+ Files.walkFileTree(updateDirectory, Set.of(), 1, visitor);
+ if (visitor.getValidPlugin() != null) {
+ Path updateLocation = visitor.getValidPlugin();
+
+ try {
+ Files.copy(updateLocation, file, StandardCopyOption.REPLACE_EXISTING);
+ } catch (IOException exception) {
+ throw new RuntimeException("Could not copy '" + updateLocation + "' to '" + file + "' in update plugin process", exception);
+ }
+
+ // Idk what this is about, TODO
+ File newName = new File(file.toFile().getParentFile(), updateLocation.toFile().getName());
+ file.toFile().renameTo(newName);
+ updateLocation.toFile().delete();
+ return newName.toPath();
+ }
+ } catch (Exception e) {
+ throw new InvalidPluginException(e);
+ }
+ return file;
+ }
+
+ private String getPluginName(Path path) throws Exception {
+ try (JarFile file = new JarFile(path.toFile())) {
+ PluginFileType<?, ?> type = PluginFileType.guessType(file);
+ if (type == null) {
+ throw new IllegalArgumentException(path + " does not contain a " + String.join(" or ", PluginFileType.getConfigTypes()) + "! Could not determine plugin type, cannot load a plugin from it!");
+ }
+
+ return type.getConfig(file).getName();
+ }
+ }
+
+ private class UpdateFileVisitor implements FileVisitor<Path> {
+
+ private final String targetName;
+ @Nullable
+ private Path validPlugin;
+
+ private UpdateFileVisitor(String targetName) {
+ this.targetName = targetName;
+ }
+
+ @Override
+ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+ try {
+ String updatePluginName = FileProviderSource.this.getPluginName(file);
+ if (this.targetName.equals(updatePluginName)) {
+ this.validPlugin = file;
+ return FileVisitResult.TERMINATE;
+ }
+ } catch (Exception e) {
+ // We failed to load this data for some reason, so, we'll skip over this
+ }
+
+
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Nullable
+ public Path getValidPlugin() {
+ return validPlugin;
+ }
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/source/PluginFlagProviderSource.java b/src/main/java/io/papermc/paper/plugin/provider/source/PluginFlagProviderSource.java
new file mode 100644
index 0000000000000000000000000000000000000000..ac55ae0e30119556f01e2e36c20fc63a111fae5f
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/source/PluginFlagProviderSource.java
@@ -0,0 +1,43 @@
+package io.papermc.paper.plugin.provider.source;
+
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.plugin.entrypoint.EntrypointHandler;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import org.slf4j.Logger;
+
+import java.util.List;
+
+/**
+ * Registers providers at the provided files in the add-plugin argument.
+ */
+public class PluginFlagProviderSource implements ProviderSource<List<Path>, List<Path>> {
+
+ public static final PluginFlagProviderSource INSTANCE = new PluginFlagProviderSource();
+ private static final FileProviderSource FILE_PROVIDER_SOURCE = new FileProviderSource("File '%s' specified through 'add-plugin' argument"::formatted);
+ private static final Logger LOGGER = LogUtils.getClassLogger();
+
+ @Override
+ public List<Path> prepareContext(List<Path> context) {
+ final List<Path> files = new ArrayList<>();
+ for (Path path : context) {
+ try {
+ files.add(FILE_PROVIDER_SOURCE.prepareContext(path));
+ } catch (Exception e) {
+ LOGGER.error("Error preparing plugin context: " + e.getMessage(), e);
+ }
+ }
+ return files;
+ }
+
+ @Override
+ public void registerProviders(EntrypointHandler entrypointHandler, List<Path> context) {
+ for (Path path : context) {
+ try {
+ FILE_PROVIDER_SOURCE.registerProviders(entrypointHandler, path);
+ } catch (Exception e) {
+ LOGGER.error("Error loading plugin: " + e.getMessage(), e);
+ }
+ }
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/source/ProviderSource.java b/src/main/java/io/papermc/paper/plugin/provider/source/ProviderSource.java
new file mode 100644
index 0000000000000000000000000000000000000000..6b09813c75fad02fe9b8deb0bf86ad0b148fa770
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/source/ProviderSource.java
@@ -0,0 +1,32 @@
+package io.papermc.paper.plugin.provider.source;
+
+import io.papermc.paper.plugin.entrypoint.EntrypointHandler;
+import java.io.IOException;
+
+/**
+ * A provider source is responsible for giving PluginTypes an EntrypointHandler for
+ * registering providers at.
+ *
+ * @param <I> input context
+ * @param <C> context
+ */
+public interface ProviderSource<I, C> {
+
+ /**
+ * Prepares the context for use in {@link #registerProviders(EntrypointHandler, Object)}.
+ *
+ * @param context the context to prepare
+ * @return the prepared context, ready for use in {@link #registerProviders(EntrypointHandler, Object)}
+ * @throws IOException if an error occurs while preparing the context
+ */
+ C prepareContext(I context) throws IOException;
+
+ /**
+ * Uses the prepared context to register providers at the given entrypoint handler.
+ *
+ * @param entrypointHandler the entrypoint handler to register providers at
+ * @param context the context to register providers at
+ * @throws Exception if an error occurs while registering providers
+ */
+ void registerProviders(EntrypointHandler entrypointHandler, C context) throws Exception;
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/type/PluginFileType.java b/src/main/java/io/papermc/paper/plugin/provider/type/PluginFileType.java
new file mode 100644
index 0000000000000000000000000000000000000000..87128685015d550440a798028f50be24bc755f6c
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/type/PluginFileType.java
@@ -0,0 +1,85 @@
+package io.papermc.paper.plugin.provider.type;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.entrypoint.Entrypoint;
+import io.papermc.paper.plugin.entrypoint.EntrypointHandler;
+import io.papermc.paper.plugin.provider.configuration.PaperPluginMeta;
+import io.papermc.paper.plugin.provider.type.paper.PaperPluginParent;
+import io.papermc.paper.plugin.provider.type.spigot.SpigotPluginProvider;
+import org.bukkit.plugin.PluginDescriptionFile;
+import org.jetbrains.annotations.Nullable;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+/**
+ * This is where spigot/paper plugins are registered.
+ * This will get the jar and find a certain config file, create an object
+ * then registering it into a {@link EntrypointHandler} at a certain {@link Entrypoint}.
+ */
+public abstract class PluginFileType<T, C extends PluginMeta> {
+
+ private static final List<String> CONFIG_TYPES = new ArrayList<>();
+
+ public static final PluginFileType<PaperPluginParent, PaperPluginMeta> PAPER = new PluginFileType<>("paper-plugin.yml", PaperPluginParent.FACTORY) {
+ @Override
+ protected void register(EntrypointHandler entrypointHandler, PaperPluginParent parent) {
+ PaperPluginParent.PaperBootstrapProvider bootstrapPluginProvider = null;
+ if (parent.shouldCreateBootstrap()) {
+ bootstrapPluginProvider = parent.createBootstrapProvider();
+ entrypointHandler.register(Entrypoint.BOOTSTRAPPER, bootstrapPluginProvider);
+ }
+
+ entrypointHandler.register(Entrypoint.PLUGIN, parent.createPluginProvider(bootstrapPluginProvider));
+ }
+ };
+ public static final PluginFileType<SpigotPluginProvider, PluginDescriptionFile> SPIGOT = new PluginFileType<>("plugin.yml", SpigotPluginProvider.FACTORY) {
+ @Override
+ protected void register(EntrypointHandler entrypointHandler, SpigotPluginProvider provider) {
+ entrypointHandler.register(Entrypoint.PLUGIN, provider);
+ }
+ };
+
+ private static final List<PluginFileType<?, ?>> VALUES = List.of(PAPER, SPIGOT);
+
+ private final String config;
+ private final PluginTypeFactory<T, C> factory;
+
+ PluginFileType(String config, PluginTypeFactory<T, C> factory) {
+ this.config = config;
+ this.factory = factory;
+ CONFIG_TYPES.add(config);
+ }
+
+ @Nullable
+ public static PluginFileType<?, ?> guessType(JarFile file) {
+ for (PluginFileType<?, ?> type : VALUES) {
+ JarEntry entry = file.getJarEntry(type.config);
+ if (entry != null) {
+ return type;
+ }
+ }
+
+ return null;
+ }
+
+ public T register(EntrypointHandler entrypointHandler, JarFile file, Path context) throws Exception {
+ C config = this.getConfig(file);
+ T provider = this.factory.build(file, config, context);
+ this.register(entrypointHandler, provider);
+ return provider;
+ }
+
+ public C getConfig(JarFile file) throws Exception {
+ return this.factory.create(file, file.getJarEntry(this.config));
+ }
+
+ protected abstract void register(EntrypointHandler entrypointHandler, T provider);
+
+ public static List<String> getConfigTypes() {
+ return CONFIG_TYPES;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/type/PluginTypeFactory.java b/src/main/java/io/papermc/paper/plugin/provider/type/PluginTypeFactory.java
new file mode 100644
index 0000000000000000000000000000000000000000..32f230d66f6953520b59ccbf3079c5a6242ca92c
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/type/PluginTypeFactory.java
@@ -0,0 +1,21 @@
+package io.papermc.paper.plugin.provider.type;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+
+import java.nio.file.Path;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+/**
+ * A plugin type factory is responsible for building an object
+ * and config for a certain plugin type.
+ *
+ * @param <T> plugin provider type (may not be a plugin provider)
+ * @param <C> config type
+ */
+public interface PluginTypeFactory<T, C extends PluginMeta> {
+
+ T build(JarFile file, C configuration, Path source) throws Exception;
+
+ C create(JarFile file, JarEntry config) throws Exception;
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperBootstrapOrderConfiguration.java b/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperBootstrapOrderConfiguration.java
new file mode 100644
index 0000000000000000000000000000000000000000..e34656fb0573ff6d826eb4d4dcfd517e01589206
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperBootstrapOrderConfiguration.java
@@ -0,0 +1,50 @@
+package io.papermc.paper.plugin.provider.type.paper;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.configuration.LoadOrderConfiguration;
+import io.papermc.paper.plugin.provider.configuration.PaperPluginMeta;
+import io.papermc.paper.plugin.provider.configuration.type.DependencyConfiguration;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class PaperBootstrapOrderConfiguration implements LoadOrderConfiguration {
+
+ private final PaperPluginMeta paperPluginMeta;
+ private final List<String> loadBefore = new ArrayList<>();
+ private final List<String> loadAfter = new ArrayList<>();
+
+ public PaperBootstrapOrderConfiguration(PaperPluginMeta paperPluginMeta) {
+ this.paperPluginMeta = paperPluginMeta;
+
+ for (Map.Entry<String, DependencyConfiguration> configuration : paperPluginMeta.getBoostrapDependencies().entrySet()) {
+ String name = configuration.getKey();
+ DependencyConfiguration dependencyConfiguration = configuration.getValue();
+
+ if (dependencyConfiguration.load() == DependencyConfiguration.LoadOrder.AFTER) {
+ // This plugin will load BEFORE all dependencies (so dependencies will load AFTER plugin)
+ this.loadBefore.add(name);
+ } else if (dependencyConfiguration.load() == DependencyConfiguration.LoadOrder.BEFORE) {
+ // This plugin will load AFTER all dependencies (so dependencies will load BEFORE plugin)
+ this.loadAfter.add(name);
+ }
+ }
+ }
+
+ @Override
+ public @NotNull List<String> getLoadBefore() {
+ return this.loadBefore;
+ }
+
+ @Override
+ public @NotNull List<String> getLoadAfter() {
+ return this.loadAfter;
+ }
+
+ @Override
+ public @NotNull PluginMeta getMeta() {
+ return this.paperPluginMeta;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperLoadOrderConfiguration.java b/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperLoadOrderConfiguration.java
new file mode 100644
index 0000000000000000000000000000000000000000..b7e8a5ba375a558e0442aa9facf96954a9bb135f
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperLoadOrderConfiguration.java
@@ -0,0 +1,44 @@
+package io.papermc.paper.plugin.provider.type.paper;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.configuration.LoadOrderConfiguration;
+import io.papermc.paper.plugin.provider.configuration.PaperPluginMeta;
+import io.papermc.paper.plugin.provider.type.spigot.SpigotPluginProvider;
+import org.bukkit.plugin.PluginDescriptionFile;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+public class PaperLoadOrderConfiguration implements LoadOrderConfiguration {
+
+ private final PaperPluginMeta meta;
+ private final List<String> loadBefore;
+ private final List<String> loadAfter;
+
+ public PaperLoadOrderConfiguration(PaperPluginMeta meta) {
+ this.meta = meta;
+
+ this.loadBefore = this.meta.getLoadBeforePlugins();
+ this.loadAfter = this.meta.getLoadAfterPlugins();
+ }
+
+ @Override
+ public @NotNull List<String> getLoadBefore() {
+ return this.loadBefore;
+ }
+
+ @Override
+ public @NotNull List<String> getLoadAfter() {
+ return this.loadAfter;
+ }
+
+ @Override
+ public @NotNull PluginMeta getMeta() {
+ return this.meta;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperPluginParent.java b/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperPluginParent.java
new file mode 100644
index 0000000000000000000000000000000000000000..f2bc4d0b55d4c9877a442529e0b144656497dae6
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperPluginParent.java
@@ -0,0 +1,264 @@
+package io.papermc.paper.plugin.provider.type.paper;
+
+import com.destroystokyo.paper.util.SneakyThrow;
+import io.papermc.paper.plugin.bootstrap.PluginProviderContext;
+import io.papermc.paper.plugin.provider.configuration.LoadOrderConfiguration;
+import io.papermc.paper.plugin.provider.configuration.type.DependencyConfiguration;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+import io.papermc.paper.plugin.entrypoint.dependency.DependencyContextHolder;
+import io.papermc.paper.plugin.bootstrap.PluginBootstrap;
+import io.papermc.paper.plugin.entrypoint.classloader.PaperPluginClassLoader;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.ProviderStatus;
+import io.papermc.paper.plugin.provider.ProviderStatusHolder;
+import io.papermc.paper.plugin.provider.configuration.PaperPluginMeta;
+import io.papermc.paper.plugin.provider.type.PluginTypeFactory;
+import io.papermc.paper.plugin.provider.util.ProviderUtil;
+import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.jetbrains.annotations.NotNull;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.JarFile;
+
+public class PaperPluginParent {
+
+ public static final PluginTypeFactory<PaperPluginParent, PaperPluginMeta> FACTORY = new PaperPluginProviderFactory();
+ private final Path path;
+ private final JarFile jarFile;
+ private final PaperPluginMeta description;
+ private final PaperPluginClassLoader classLoader;
+ private final PluginProviderContext context;
+ private final ComponentLogger logger;
+
+ public PaperPluginParent(Path path, JarFile jarFile, PaperPluginMeta description, PaperPluginClassLoader classLoader, PluginProviderContext context) {
+ this.path = path;
+ this.jarFile = jarFile;
+ this.description = description;
+ this.classLoader = classLoader;
+ this.context = context;
+ this.logger = context.getLogger();
+ }
+
+ public boolean shouldCreateBootstrap() {
+ return this.description.getBootstrapper() != null;
+ }
+
+ public PaperBootstrapProvider createBootstrapProvider() {
+ return new PaperBootstrapProvider();
+ }
+
+ public PaperServerPluginProvider createPluginProvider(PaperBootstrapProvider provider) {
+ return new PaperServerPluginProvider(provider);
+ }
+
+ public class PaperBootstrapProvider implements PluginProvider<PluginBootstrap>, ProviderStatusHolder, DependencyContextHolder {
+
+ private ProviderStatus status;
+ private PluginBootstrap lastProvided;
+
+ @Override
+ public @NotNull Path getSource() {
+ return PaperPluginParent.this.path;
+ }
+
+ @Override
+ public JarFile file() {
+ return PaperPluginParent.this.jarFile;
+ }
+
+ @Override
+ public PluginBootstrap createInstance() {
+ PluginBootstrap bootstrap = ProviderUtil.loadClass(PaperPluginParent.this.description.getBootstrapper(),
+ PluginBootstrap.class, PaperPluginParent.this.classLoader, () -> this.status = ProviderStatus.ERRORED);
+ this.status = ProviderStatus.INITIALIZED;
+ this.lastProvided = bootstrap;
+ return bootstrap;
+ }
+
+ @Override
+ public PaperPluginMeta getMeta() {
+ return PaperPluginParent.this.description;
+ }
+
+ @Override
+ public ComponentLogger getLogger() {
+ return PaperPluginParent.this.logger;
+ }
+
+ @Override
+ public LoadOrderConfiguration createConfiguration(@NotNull Map<String, PluginProvider<?>> toLoad) {
+ return new PaperBootstrapOrderConfiguration(PaperPluginParent.this.description);
+ }
+
+ @Override
+ public List<String> validateDependencies(@NotNull DependencyContext context) {
+ List<String> missingDependencies = new ArrayList<>();
+ for (Map.Entry<String, DependencyConfiguration> configuration : this.getMeta().getBoostrapDependencies().entrySet()) {
+ String dependency = configuration.getKey();
+ if (configuration.getValue().required() && !context.hasDependency(dependency)) {
+ missingDependencies.add(dependency);
+ }
+ }
+
+ return missingDependencies;
+ }
+
+ @Override
+ public ProviderStatus getLastProvidedStatus() {
+ return this.status;
+ }
+
+ @Override
+ public void setStatus(ProviderStatus status) {
+ this.status = status;
+ }
+
+ public PluginBootstrap getLastProvided() {
+ return this.lastProvided;
+ }
+
+ @Override
+ public void setContext(DependencyContext context) {
+ PaperPluginParent.this.classLoader.refreshClassloaderDependencyTree(context);
+ }
+
+ @Override
+ public String toString() {
+ return "PaperBootstrapProvider{" +
+ "parent=" + PaperPluginParent.this +
+ "status=" + status +
+ ", lastProvided=" + lastProvided +
+ '}';
+ }
+ }
+
+ public class PaperServerPluginProvider implements PluginProvider<JavaPlugin>, ProviderStatusHolder, DependencyContextHolder {
+
+ private final PaperBootstrapProvider bootstrapProvider;
+
+ private ProviderStatus status;
+
+ PaperServerPluginProvider(PaperBootstrapProvider bootstrapProvider) {
+ this.bootstrapProvider = bootstrapProvider;
+ }
+
+ @Override
+ public @NotNull Path getSource() {
+ return PaperPluginParent.this.path;
+ }
+
+ @Override
+ public JarFile file() {
+ return PaperPluginParent.this.jarFile;
+ }
+
+ @Override
+ public JavaPlugin createInstance() {
+ PluginBootstrap bootstrap = null;
+ if (this.bootstrapProvider != null && this.bootstrapProvider.getLastProvided() != null) {
+ bootstrap = this.bootstrapProvider.getLastProvided();
+ }
+
+ try {
+ JavaPlugin plugin;
+ if (bootstrap == null) {
+ plugin = ProviderUtil.loadClass(PaperPluginParent.this.description.getMainClass(), JavaPlugin.class, PaperPluginParent.this.classLoader);
+ } else {
+ plugin = bootstrap.createPlugin(PaperPluginParent.this.context);
+ }
+
+ if (!plugin.getClass().isAssignableFrom(Class.forName(PaperPluginParent.this.description.getMainClass(), true, plugin.getClass().getClassLoader()))) {
+ logger.info("Bootstrap of plugin " + PaperPluginParent.this.description.getName() + " provided a plugin instance of class " + plugin.getClass().getName() + " which does not match the plugin declared main class");
+ }
+
+ this.status = ProviderStatus.INITIALIZED;
+ return plugin;
+ } catch (Throwable throwable) {
+ this.status = ProviderStatus.ERRORED;
+ SneakyThrow.sneaky(throwable);
+ }
+
+ throw new AssertionError(); // Impossible
+ }
+
+ @Override
+ public PaperPluginMeta getMeta() {
+ return PaperPluginParent.this.description;
+ }
+
+ @Override
+ public ComponentLogger getLogger() {
+ return PaperPluginParent.this.logger;
+ }
+
+ @Override
+ public LoadOrderConfiguration createConfiguration(@NotNull Map<String, PluginProvider<?>> toLoad) {
+ return new PaperLoadOrderConfiguration(PaperPluginParent.this.description);
+ }
+
+ @Override
+ public List<String> validateDependencies(@NotNull DependencyContext context) {
+ List<String> missingDependencies = new ArrayList<>();
+ for (Map.Entry<String, DependencyConfiguration> dependency : this.getMeta().getServerDependencies().entrySet()) {
+ String name = dependency.getKey();
+ if (dependency.getValue().required() && !context.hasDependency(name)) {
+ missingDependencies.add(name);
+ }
+ }
+
+ return missingDependencies;
+ }
+
+ @Override
+ public ProviderStatus getLastProvidedStatus() {
+ return this.status;
+ }
+
+ @Override
+ public void setStatus(ProviderStatus status) {
+ this.status = status;
+ }
+
+ public boolean shouldSkipCreation() {
+ if (this.bootstrapProvider == null) {
+ return false;
+ }
+
+ return this.bootstrapProvider.getLastProvidedStatus() == ProviderStatus.ERRORED;
+ }
+
+ /*
+ The plugin has to reuse the classloader in order to share the bootstrapper.
+ However, a plugin may have totally separate dependencies during bootstrapping.
+ This is a bit yuck, but in general we have to treat bootstrapping and normal game as connected.
+ */
+ @Override
+ public void setContext(DependencyContext context) {
+ PaperPluginParent.this.classLoader.refreshClassloaderDependencyTree(context);
+ }
+
+ @Override
+ public String toString() {
+ return "PaperServerPluginProvider{" +
+ "parent=" + PaperPluginParent.this +
+ "bootstrapProvider=" + bootstrapProvider +
+ ", status=" + status +
+ '}';
+ }
+ }
+
+
+ @Override
+ public String toString() {
+ return "PaperPluginParent{" +
+ "path=" + path +
+ ", jarFile=" + jarFile +
+ ", description=" + description +
+ ", classLoader=" + classLoader +
+ '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperPluginProviderFactory.java b/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperPluginProviderFactory.java
new file mode 100644
index 0000000000000000000000000000000000000000..0a27b468560ccf4b9588cd12d50c02e442f3024f
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/type/paper/PaperPluginProviderFactory.java
@@ -0,0 +1,56 @@
+package io.papermc.paper.plugin.provider.type.paper;
+
+import com.destroystokyo.paper.utils.PaperPluginLogger;
+import io.papermc.paper.plugin.bootstrap.PluginProviderContext;
+import io.papermc.paper.plugin.bootstrap.PluginProviderContextImpl;
+import io.papermc.paper.plugin.entrypoint.classloader.PaperPluginClassLoader;
+import io.papermc.paper.plugin.entrypoint.classloader.PaperSimplePluginClassLoader;
+import io.papermc.paper.plugin.loader.PaperClasspathBuilder;
+import io.papermc.paper.plugin.loader.PluginLoader;
+import io.papermc.paper.plugin.provider.configuration.PaperPluginMeta;
+import io.papermc.paper.plugin.provider.type.PluginTypeFactory;
+import io.papermc.paper.plugin.provider.util.ProviderUtil;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.file.Path;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.logging.Logger;
+import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
+
+class PaperPluginProviderFactory implements PluginTypeFactory<PaperPluginParent, PaperPluginMeta> {
+
+ @Override
+ public PaperPluginParent build(JarFile file, PaperPluginMeta configuration, Path source) {
+ Logger jul = PaperPluginLogger.getLogger(configuration);
+ ComponentLogger logger = ComponentLogger.logger(jul.getName());
+ PluginProviderContext context = PluginProviderContextImpl.create(configuration, logger, source);
+
+ PaperClasspathBuilder builder = new PaperClasspathBuilder(context);
+
+ if (configuration.getLoader() != null) {
+ try (
+ PaperSimplePluginClassLoader simplePluginClassLoader = new PaperSimplePluginClassLoader(source, file, configuration, this.getClass().getClassLoader())
+ ) {
+ PluginLoader loader = ProviderUtil.loadClass(configuration.getLoader(), PluginLoader.class, simplePluginClassLoader);
+ loader.classloader(builder);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ PaperPluginClassLoader classLoader = builder.buildClassLoader(jul, source, file, configuration);
+ return new PaperPluginParent(source, file, configuration, classLoader, context);
+ }
+
+ @Override
+ public PaperPluginMeta create(JarFile file, JarEntry config) throws IOException {
+ PaperPluginMeta configuration;
+ try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream(config)))) {
+ configuration = PaperPluginMeta.create(bufferedReader);
+ }
+ return configuration;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/type/spigot/SpigotLoadOrderConfiguration.java b/src/main/java/io/papermc/paper/plugin/provider/type/spigot/SpigotLoadOrderConfiguration.java
new file mode 100644
index 0000000000000000000000000000000000000000..b2a6544e321fa61c58bdf5684231de1020884fcc
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/type/spigot/SpigotLoadOrderConfiguration.java
@@ -0,0 +1,72 @@
+package io.papermc.paper.plugin.provider.type.spigot;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.configuration.LoadOrderConfiguration;
+import org.bukkit.plugin.PluginDescriptionFile;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class SpigotLoadOrderConfiguration implements LoadOrderConfiguration {
+
+ private final PluginDescriptionFile meta;
+ private final List<String> loadBefore;
+ private final List<String> loadAfter;
+
+ public SpigotLoadOrderConfiguration(SpigotPluginProvider spigotPluginProvider, Map<String, PluginProvider<?>> toLoad) {
+ this.meta = spigotPluginProvider.getMeta();
+
+ this.loadBefore = meta.getLoadBeforePlugins();
+ this.loadAfter = new ArrayList<>();
+ this.loadAfter.addAll(meta.getDepend());
+ this.loadAfter.addAll(meta.getSoftDepend());
+
+ // First: Remove as load after IF already in loadbefore
+ // Some plugins would put a plugin both in depends and in loadbefore,
+ // so in this case, we just ignore the effects of depend.
+ for (String loadBefore : this.loadBefore) {
+ this.loadAfter.remove(loadBefore);
+ }
+
+ // Second: Do a basic check to see if any other dependencies refer back to this plugin.
+ Iterator<String> iterators = this.loadAfter.iterator();
+ while (iterators.hasNext()) {
+ String loadAfter = iterators.next();
+ PluginProvider<?> provider = toLoad.get(loadAfter);
+ if (provider != null) {
+ PluginMeta configuration = provider.getMeta();
+ // Does a configuration refer back to this plugin?
+ Set<String> dependencies = new HashSet<>();
+ dependencies.addAll(configuration.getPluginDependencies());
+ dependencies.addAll(configuration.getPluginSoftDependencies());
+
+ if (configuration.getName().equals(this.meta.getName()) || dependencies.contains(this.meta.getName())) {
+ iterators.remove(); // Let the other config deal with it
+ }
+ }
+ }
+
+ }
+
+ @Override
+ public @NotNull List<String> getLoadBefore() {
+ return this.loadBefore;
+ }
+
+ @Override
+ public @NotNull List<String> getLoadAfter() {
+ return this.loadAfter;
+ }
+
+ @Override
+ public @NotNull PluginMeta getMeta() {
+ return this.meta;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/type/spigot/SpigotPluginProvider.java b/src/main/java/io/papermc/paper/plugin/provider/type/spigot/SpigotPluginProvider.java
new file mode 100644
index 0000000000000000000000000000000000000000..75a2b687d58d76b94f8bec111df8613f120ff74b
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/type/spigot/SpigotPluginProvider.java
@@ -0,0 +1,197 @@
+package io.papermc.paper.plugin.provider.type.spigot;
+
+import com.destroystokyo.paper.util.SneakyThrow;
+import com.destroystokyo.paper.utils.PaperPluginLogger;
+import io.papermc.paper.plugin.manager.PaperPluginManagerImpl;
+import io.papermc.paper.plugin.provider.configuration.LoadOrderConfiguration;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+import io.papermc.paper.plugin.entrypoint.dependency.DependencyContextHolder;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.ProviderStatus;
+import io.papermc.paper.plugin.provider.ProviderStatusHolder;
+import io.papermc.paper.plugin.provider.type.PluginTypeFactory;
+import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
+import org.bukkit.Bukkit;
+import org.bukkit.Server;
+import org.bukkit.plugin.InvalidPluginException;
+import org.bukkit.plugin.PluginDescriptionFile;
+import org.bukkit.plugin.UnknownDependencyException;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.bukkit.plugin.java.LibraryLoader;
+import org.bukkit.plugin.java.PluginClassLoader;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.File;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.jar.JarFile;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class SpigotPluginProvider implements PluginProvider<JavaPlugin>, ProviderStatusHolder, DependencyContextHolder {
+
+ public static final PluginTypeFactory<SpigotPluginProvider, PluginDescriptionFile> FACTORY = new SpigotPluginProviderFactory();
+ private static final LibraryLoader LIBRARY_LOADER = new LibraryLoader(Logger.getLogger("SpigotLibraryLoader"));
+ private final Path path;
+ private final PluginDescriptionFile description;
+ private final JarFile jarFile;
+ private final Logger logger;
+ private final ComponentLogger componentLogger;
+ private ProviderStatus status;
+ private DependencyContext dependencyContext;
+
+ SpigotPluginProvider(Path path, JarFile file, PluginDescriptionFile description) {
+ this.path = path;
+ this.jarFile = file;
+ this.description = description;
+ this.logger = PaperPluginLogger.getLogger(description);
+ this.componentLogger = ComponentLogger.logger(this.logger.getName());
+ }
+
+ @Override
+ public @NotNull Path getSource() {
+ return this.path;
+ }
+
+ @Override
+ public JarFile file() {
+ return this.jarFile;
+ }
+
+ @Override
+ public JavaPlugin createInstance() {
+ Server server = Bukkit.getServer();
+ try {
+
+ final File parentFile = server.getPluginsFolder(); // Paper
+ final File dataFolder = new File(parentFile, this.description.getName());
+ @SuppressWarnings("deprecation") final File oldDataFolder = new File(parentFile, this.description.getRawName());
+
+ // Found old data folder
+ if (dataFolder.equals(oldDataFolder)) {
+ // They are equal -- nothing needs to be done!
+ } else if (dataFolder.isDirectory() && oldDataFolder.isDirectory()) {
+ server.getLogger().warning(String.format(
+ "While loading %s (%s) found old-data folder: `%s' next to the new one `%s'",
+ this.description.getFullName(),
+ this.path,
+ oldDataFolder,
+ dataFolder
+ ));
+ } else if (oldDataFolder.isDirectory() && !dataFolder.exists()) {
+ if (!oldDataFolder.renameTo(dataFolder)) {
+ throw new InvalidPluginException("Unable to rename old data folder: `" + oldDataFolder + "' to: `" + dataFolder + "'");
+ }
+ server.getLogger().log(Level.INFO, String.format(
+ "While loading %s (%s) renamed data folder: `%s' to `%s'",
+ this.description.getFullName(),
+ this.path,
+ oldDataFolder,
+ dataFolder
+ ));
+ }
+
+ if (dataFolder.exists() && !dataFolder.isDirectory()) {
+ throw new InvalidPluginException(String.format(
+ "Projected datafolder: `%s' for %s (%s) exists and is not a directory",
+ dataFolder,
+ this.description.getFullName(),
+ this.path
+ ));
+ }
+
+ Set<String> missingHardDependencies = new HashSet<>(this.description.getDepend().size()); // Paper - list all missing hard depends
+ for (final String pluginName : this.description.getDepend()) {
+ if (!this.dependencyContext.hasDependency(pluginName)) {
+ missingHardDependencies.add(pluginName); // Paper - list all missing hard depends
+ }
+ }
+ // Paper start - list all missing hard depends
+ if (!missingHardDependencies.isEmpty()) {
+ throw new UnknownDependencyException(missingHardDependencies, this.description.getFullName());
+ }
+ // Paper end
+
+ server.getUnsafe().checkSupported(this.description);
+
+ final PluginClassLoader loader;
+ try {
+ loader = new PluginClassLoader(this.getClass().getClassLoader(), this.description, dataFolder, this.path.toFile(), LIBRARY_LOADER.createLoader(this.description), this.jarFile, this.dependencyContext); // Paper
+ } catch (InvalidPluginException ex) {
+ throw ex;
+ } catch (Throwable ex) {
+ throw new InvalidPluginException(ex);
+ }
+
+ // Override dependency context.
+ // We must provide a temporary context in order to properly handle dependencies on the plugin classloader constructor.
+ loader.dependencyContext = PaperPluginManagerImpl.getInstance();
+
+
+ this.status = ProviderStatus.INITIALIZED;
+ return loader.getPlugin();
+ } catch (Throwable ex) {
+ this.status = ProviderStatus.ERRORED;
+ SneakyThrow.sneaky(ex);
+ }
+
+ throw new AssertionError(); // Shouldn't happen
+ }
+
+ @Override
+ public PluginDescriptionFile getMeta() {
+ return this.description;
+ }
+
+ @Override
+ public ComponentLogger getLogger() {
+ return this.componentLogger;
+ }
+
+ @Override
+ public LoadOrderConfiguration createConfiguration(@NotNull Map<String, PluginProvider<?>> toLoad) {
+ return new SpigotLoadOrderConfiguration(this, toLoad);
+ }
+
+ @Override
+ public List<String> validateDependencies(@NotNull DependencyContext context) {
+ List<String> missingDependencies = new ArrayList<>();
+ for (String hardDependency : this.getMeta().getPluginDependencies()) {
+ if (!context.hasDependency(hardDependency)) {
+ missingDependencies.add(hardDependency);
+ }
+ }
+
+ return missingDependencies;
+ }
+
+ @Override
+ public ProviderStatus getLastProvidedStatus() {
+ return this.status;
+ }
+
+ @Override
+ public void setStatus(ProviderStatus status) {
+ this.status = status;
+ }
+
+ @Override
+ public void setContext(DependencyContext context) {
+ this.dependencyContext = context;
+ }
+
+ @Override
+ public String toString() {
+ return "SpigotPluginProvider{" +
+ "path=" + path +
+ ", description=" + description +
+ ", jarFile=" + jarFile +
+ ", status=" + status +
+ ", dependencyContext=" + dependencyContext +
+ '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/provider/type/spigot/SpigotPluginProviderFactory.java b/src/main/java/io/papermc/paper/plugin/provider/type/spigot/SpigotPluginProviderFactory.java
new file mode 100644
index 0000000000000000000000000000000000000000..bdd9bc8a414719b9f1d6f01f90539ddb8603a878
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/provider/type/spigot/SpigotPluginProviderFactory.java
@@ -0,0 +1,45 @@
+package io.papermc.paper.plugin.provider.type.spigot;
+
+import io.papermc.paper.plugin.provider.configuration.serializer.constraints.PluginConfigConstraints;
+import io.papermc.paper.plugin.provider.type.PluginTypeFactory;
+import org.bukkit.plugin.InvalidDescriptionException;
+import org.bukkit.plugin.PluginDescriptionFile;
+import org.yaml.snakeyaml.error.YAMLException;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.util.Locale;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+class SpigotPluginProviderFactory implements PluginTypeFactory<SpigotPluginProvider, PluginDescriptionFile> {
+
+ @Override
+ public SpigotPluginProvider build(JarFile file, PluginDescriptionFile configuration, Path source) throws InvalidDescriptionException {
+ // Copied from SimplePluginManager#loadPlugins
+ // Spigot doesn't validate the name when the config is created, and instead when the plugin is loaded.
+ // Paper plugin configuration will do these checks in config serializer instead of when this is created.
+ String name = configuration.getRawName();
+ if (PluginConfigConstraints.RESERVED_KEYS.contains(name.toLowerCase(Locale.ROOT))) {
+ throw new InvalidDescriptionException("Restricted name, cannot use %s as a plugin name.".formatted(name));
+ } else if (name.indexOf(' ') != -1) {
+ throw new InvalidDescriptionException("Restricted name, cannot use 0x20 (space character) in a plugin name.");
+ }
+
+ return new SpigotPluginProvider(source, file, configuration);
+ }
+
+ @Override
+ public PluginDescriptionFile create(JarFile file, JarEntry config) throws InvalidDescriptionException {
+ PluginDescriptionFile descriptionFile;
+ try (InputStream inputStream = file.getInputStream(config)) {
+ descriptionFile = new PluginDescriptionFile(inputStream);
+ } catch (IOException | YAMLException ex) {
+ throw new InvalidDescriptionException(ex);
+ }
+
+ return descriptionFile;
+ }
+}
+
diff --git a/src/main/java/io/papermc/paper/plugin/storage/BootstrapProviderStorage.java b/src/main/java/io/papermc/paper/plugin/storage/BootstrapProviderStorage.java
new file mode 100644
index 0000000000000000000000000000000000000000..2e96308696e131f3f013469a395e5ddda2c5d529
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/storage/BootstrapProviderStorage.java
@@ -0,0 +1,65 @@
+package io.papermc.paper.plugin.storage;
+
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.plugin.PluginInitializerManager;
+import io.papermc.paper.plugin.bootstrap.BootstrapContext;
+import io.papermc.paper.plugin.bootstrap.PluginBootstrap;
+import io.papermc.paper.plugin.bootstrap.PluginBootstrapContextImpl;
+import io.papermc.paper.plugin.entrypoint.dependency.BootstrapMetaDependencyTree;
+import io.papermc.paper.plugin.entrypoint.dependency.DependencyContextHolder;
+import io.papermc.paper.plugin.entrypoint.dependency.MetaDependencyTree;
+import io.papermc.paper.plugin.entrypoint.strategy.ProviderConfiguration;
+import io.papermc.paper.plugin.entrypoint.strategy.modern.ModernPluginLoadingStrategy;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.ProviderStatus;
+import io.papermc.paper.plugin.provider.ProviderStatusHolder;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+import org.slf4j.Logger;
+
+public class BootstrapProviderStorage extends SimpleProviderStorage<PluginBootstrap> {
+
+ private static final Logger LOGGER = LogUtils.getClassLogger();
+
+ public BootstrapProviderStorage() {
+ super(new ModernPluginLoadingStrategy<>(new ProviderConfiguration<>() {
+ @Override
+ public void applyContext(PluginProvider<PluginBootstrap> provider, DependencyContext dependencyContext) {
+ if (provider instanceof DependencyContextHolder contextHolder) {
+ contextHolder.setContext(dependencyContext);
+ }
+ }
+
+ @Override
+ public boolean load(PluginProvider<PluginBootstrap> provider, PluginBootstrap provided) {
+ try {
+ BootstrapContext context = PluginBootstrapContextImpl.create(provider, PluginInitializerManager.instance().pluginDirectoryPath());
+ provided.bootstrap(context);
+ return true;
+ } catch (Throwable e) {
+ LOGGER.error("Failed to run bootstrapper for %s. This plugin will not be loaded.".formatted(provider.getSource()), e);
+ if (provider instanceof ProviderStatusHolder statusHolder) {
+ statusHolder.setStatus(ProviderStatus.ERRORED);
+ }
+ return false;
+ }
+ }
+
+ @Override
+ public void onGenericError(PluginProvider<PluginBootstrap> provider) {
+ if (provider instanceof ProviderStatusHolder statusHolder) {
+ statusHolder.setStatus(ProviderStatus.ERRORED);
+ }
+ }
+ }));
+ }
+
+ @Override
+ public MetaDependencyTree createDependencyTree() {
+ return new BootstrapMetaDependencyTree();
+ }
+
+ @Override
+ public String toString() {
+ return "BOOTSTRAP:" + super.toString();
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/storage/ConfiguredProviderStorage.java b/src/main/java/io/papermc/paper/plugin/storage/ConfiguredProviderStorage.java
new file mode 100644
index 0000000000000000000000000000000000000000..8ef4806cadabe56264dd861f1a1854b2354b3b5c
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/storage/ConfiguredProviderStorage.java
@@ -0,0 +1,17 @@
+package io.papermc.paper.plugin.storage;
+
+import io.papermc.paper.plugin.entrypoint.strategy.LegacyPluginLoadingStrategy;
+import io.papermc.paper.plugin.entrypoint.strategy.modern.ModernPluginLoadingStrategy;
+import io.papermc.paper.plugin.entrypoint.strategy.ProviderConfiguration;
+
+public abstract class ConfiguredProviderStorage<T> extends SimpleProviderStorage<T> {
+
+ public static final boolean LEGACY_PLUGIN_LOADING = Boolean.getBoolean("paper.useLegacyPluginLoading");
+
+ protected ConfiguredProviderStorage(ProviderConfiguration<T> onLoad) {
+ // This doesn't work with reloading.
+ // Should we care?
+ super(LEGACY_PLUGIN_LOADING ? new LegacyPluginLoadingStrategy<>(onLoad) : new ModernPluginLoadingStrategy<>(onLoad));
+ }
+
+}
diff --git a/src/main/java/io/papermc/paper/plugin/storage/ProviderStorage.java b/src/main/java/io/papermc/paper/plugin/storage/ProviderStorage.java
new file mode 100644
index 0000000000000000000000000000000000000000..39cd3acd3f76b3b0d065e0efb04a3eacea1c2e6b
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/storage/ProviderStorage.java
@@ -0,0 +1,21 @@
+package io.papermc.paper.plugin.storage;
+
+import io.papermc.paper.plugin.entrypoint.dependency.MetaDependencyTree;
+import io.papermc.paper.plugin.provider.PluginProvider;
+
+/**
+ * A provider storage is meant to be a singleton that stores providers.
+ *
+ * @param <T> provider type
+ */
+public interface ProviderStorage<T> {
+
+ void register(PluginProvider<T> provider);
+
+ MetaDependencyTree createDependencyTree();
+
+ void enter();
+
+ Iterable<PluginProvider<T>> getRegisteredProviders();
+
+}
diff --git a/src/main/java/io/papermc/paper/plugin/storage/ServerPluginProviderStorage.java b/src/main/java/io/papermc/paper/plugin/storage/ServerPluginProviderStorage.java
new file mode 100644
index 0000000000000000000000000000000000000000..cb9b13522a976b82bcb71cef486f11f4172e3e99
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/storage/ServerPluginProviderStorage.java
@@ -0,0 +1,70 @@
+package io.papermc.paper.plugin.storage;
+
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+import io.papermc.paper.plugin.entrypoint.dependency.DependencyContextHolder;
+import io.papermc.paper.plugin.entrypoint.strategy.ProviderConfiguration;
+import io.papermc.paper.plugin.manager.PaperPluginManagerImpl;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.ProviderStatus;
+import io.papermc.paper.plugin.provider.ProviderStatusHolder;
+import io.papermc.paper.plugin.provider.type.paper.PaperPluginParent;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.slf4j.Logger;
+
+import java.util.List;
+
+public class ServerPluginProviderStorage extends ConfiguredProviderStorage<JavaPlugin> {
+
+ private static final Logger LOGGER = LogUtils.getClassLogger();
+
+ public ServerPluginProviderStorage() {
+ super(new ProviderConfiguration<>() {
+ @Override
+ public void applyContext(PluginProvider<JavaPlugin> provider, DependencyContext dependencyContext) {
+ Plugin alreadyLoadedPlugin = PaperPluginManagerImpl.getInstance().getPlugin(provider.getMeta().getName());
+ if (alreadyLoadedPlugin != null) {
+ throw new IllegalStateException("Provider " + provider + " attempted to add duplicate plugin identifier " + alreadyLoadedPlugin + " THIS WILL CREATE BUGS!!!");
+ }
+
+ if (provider instanceof DependencyContextHolder contextHolder) {
+ contextHolder.setContext(dependencyContext);
+ }
+ }
+
+ @Override
+ public boolean load(PluginProvider<JavaPlugin> provider, JavaPlugin provided) {
+ // Add it to the map here, we have to run the actual loading logic later.
+ PaperPluginManagerImpl.getInstance().loadPlugin(provided);
+ return true;
+ }
+ });
+ }
+
+ @Override
+ protected void filterLoadingProviders(List<PluginProvider<JavaPlugin>> pluginProviders) {
+ /*
+ Have to do this to prevent loading plugin providers that have failed initializers.
+ This is a hack and a better solution here would be to store failed plugin providers elsewhere.
+ */
+ pluginProviders.removeIf((provider) -> (provider instanceof PaperPluginParent.PaperServerPluginProvider pluginProvider && pluginProvider.shouldSkipCreation()));
+ }
+
+ // We need to call the load methods AFTER all plugins are constructed
+ @Override
+ public void processProvided(PluginProvider<JavaPlugin> provider, JavaPlugin provided) {
+ try {
+ provided.getLogger().info(String.format("Loading server plugin %s", provided.getPluginMeta().getDisplayName()));
+ provided.onLoad();
+ } catch (Throwable ex) {
+ // Don't mark that provider as ERRORED, as this apparently still needs to run the onEnable logic.
+ provided.getSLF4JLogger().error("Error initializing plugin '%s' in folder '%s' (Is it up to date?)".formatted(provider.getFileName(), provider.getParentSource()), ex);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "PLUGIN:" + super.toString();
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/storage/SimpleProviderStorage.java b/src/main/java/io/papermc/paper/plugin/storage/SimpleProviderStorage.java
new file mode 100644
index 0000000000000000000000000000000000000000..26422904751647a061397ce978bba752149003cd
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/storage/SimpleProviderStorage.java
@@ -0,0 +1,93 @@
+package io.papermc.paper.plugin.storage;
+
+import com.google.common.graph.GraphBuilder;
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.plugin.entrypoint.dependency.MetaDependencyTree;
+import io.papermc.paper.plugin.entrypoint.dependency.SimpleMetaDependencyTree;
+import io.papermc.paper.plugin.entrypoint.strategy.PluginGraphCycleException;
+import io.papermc.paper.plugin.entrypoint.strategy.ProviderLoadingStrategy;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public abstract class SimpleProviderStorage<T> implements ProviderStorage<T> {
+
+ private static final Logger LOGGER = LogUtils.getClassLogger();
+
+ protected final List<PluginProvider<T>> providers = new ArrayList<>();
+ protected ProviderLoadingStrategy<T> strategy;
+
+ protected SimpleProviderStorage(ProviderLoadingStrategy<T> strategy) {
+ this.strategy = strategy;
+ }
+
+ @Override
+ public void register(PluginProvider<T> provider) {
+ this.providers.add(provider);
+ }
+
+ @Override
+ public void enter() {
+ List<PluginProvider<T>> providerList = new ArrayList<>(this.providers);
+ this.filterLoadingProviders(providerList);
+
+ try {
+ for (ProviderLoadingStrategy.ProviderPair<T> providerPair : this.strategy.loadProviders(providerList, this.createDependencyTree())) {
+ this.processProvided(providerPair.provider(), providerPair.provided());
+ }
+ } catch (PluginGraphCycleException exception) {
+ this.handleCycle(exception);
+ }
+ }
+
+ @Override
+ public MetaDependencyTree createDependencyTree() {
+ return new SimpleMetaDependencyTree(GraphBuilder.directed().build());
+ }
+
+ @Override
+ public Iterable<PluginProvider<T>> getRegisteredProviders() {
+ return this.providers;
+ }
+
+ public void processProvided(PluginProvider<T> provider, T provided) {
+ }
+
+ // Mutable enter
+ protected void filterLoadingProviders(List<PluginProvider<T>> providers) {
+ }
+
+ protected void handleCycle(PluginGraphCycleException exception) {
+ List<String> logMessages = new ArrayList<>();
+ for (List<String> list : exception.getCycles()) {
+ logMessages.add(String.join(" -> ", list) + " -> " + list.get(0));
+ }
+
+ LOGGER.error("Circular plugin loading detected!");
+ LOGGER.error("Circular load order:");
+ for (String logMessage : logMessages) {
+ LOGGER.error(" {}", logMessage);
+ }
+ LOGGER.error("Please report this to the plugin authors of the first plugin of each loop or join the PaperMC Discord server for further help.");
+ LOGGER.error("If you would like to still load these plugins, acknowledging that there may be unexpected plugin loading issues, run the server with -Dpaper.useLegacyPluginLoading=true");
+
+ if (this.throwOnCycle()) {
+ throw new IllegalStateException("Circular plugin loading from plugins " + exception.getCycles().stream().map(cycle -> cycle.get(0)).collect(Collectors.joining(", ")));
+ }
+ }
+
+ public boolean throwOnCycle() {
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "SimpleProviderStorage{" +
+ "providers=" + this.providers +
+ ", strategy=" + this.strategy +
+ '}';
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/storage/package-info.java b/src/main/java/io/papermc/paper/plugin/storage/package-info.java
new file mode 100644
index 0000000000000000000000000000000000000000..c1114675137e862ac9682b635bfdbfbc1d7c6e67
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/storage/package-info.java
@@ -0,0 +1,5 @@
+/**
+ * Classes in this package are supposed to connect components of {@link io.papermc.paper.plugin.entrypoint} and {@link io.papermc.paper.plugin.provider} packages.
+ * @see io.papermc.paper.plugin.entrypoint.Entrypoint
+ */
+package io.papermc.paper.plugin.storage;
diff --git a/src/main/java/io/papermc/paper/plugin/util/EntrypointUtil.java b/src/main/java/io/papermc/paper/plugin/util/EntrypointUtil.java
new file mode 100644
index 0000000000000000000000000000000000000000..01c88a23755618b98c1a1cdeb8e404e79401940b
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/util/EntrypointUtil.java
@@ -0,0 +1,20 @@
+package io.papermc.paper.plugin.util;
+
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.plugin.entrypoint.LaunchEntryPointHandler;
+import io.papermc.paper.plugin.provider.source.ProviderSource;
+import org.slf4j.Logger;
+
+public final class EntrypointUtil {
+
+ private static final Logger LOGGER = LogUtils.getClassLogger();
+
+ public static <I, C> void registerProvidersFromSource(ProviderSource<I, C> source, I contextInput) {
+ try {
+ C context = source.prepareContext(contextInput);
+ source.registerProviders(LaunchEntryPointHandler.INSTANCE, context);
+ } catch (Throwable e) {
+ LOGGER.error(e.getMessage(), e);
+ }
+ }
+}
diff --git a/src/main/java/io/papermc/paper/plugin/util/NamespaceChecker.java b/src/main/java/io/papermc/paper/plugin/util/NamespaceChecker.java
new file mode 100644
index 0000000000000000000000000000000000000000..fd55fd1d6518ebd1bc2513dd331f072018fd4782
--- /dev/null
+++ b/src/main/java/io/papermc/paper/plugin/util/NamespaceChecker.java
@@ -0,0 +1,37 @@
+package io.papermc.paper.plugin.util;
+
+import org.jetbrains.annotations.ApiStatus;
+import org.jetbrains.annotations.NotNull;
+
+@ApiStatus.Internal
+public class NamespaceChecker {
+
+ private static final String[] QUICK_INVALID_NAMESPACES = {
+ "net.minecraft.",
+ "org.bukkit.",
+ "io.papermc.paper.",
+ "com.destroystokoyo.paper."
+ };
+
+ /**
+ * Used for a variety of namespaces that shouldn't be resolved and should instead be moved to
+ * other classloaders. We can assume this because only plugins should be using this classloader.
+ *
+ * @param name namespace
+ */
+ public static void validateNameSpaceForClassloading(@NotNull String name) throws ClassNotFoundException {
+ if (!isValidNameSpace(name)) {
+ throw new ClassNotFoundException(name);
+ }
+ }
+
+ public static boolean isValidNameSpace(@NotNull String name) {
+ for (String string : QUICK_INVALID_NAMESPACES) {
+ if (name.startsWith(string)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+}
diff --git a/src/main/java/io/papermc/paper/util/StackWalkerUtil.java b/src/main/java/io/papermc/paper/util/StackWalkerUtil.java
index f7114d5b8f2f93f62883e24da29afaf9f74ee1a6..8bf0630c0e06950cd99b7ae9898137f70c22063f 100644
--- a/src/main/java/io/papermc/paper/util/StackWalkerUtil.java
+++ b/src/main/java/io/papermc/paper/util/StackWalkerUtil.java
@@ -1,9 +1,10 @@
package io.papermc.paper.util;
+import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
import org.bukkit.plugin.java.JavaPlugin;
-import org.bukkit.plugin.java.PluginClassLoader;
import org.jetbrains.annotations.Nullable;
+import java.util.Objects;
import java.util.Optional;
public class StackWalkerUtil {
@@ -12,11 +13,18 @@ public class StackWalkerUtil {
public static JavaPlugin getFirstPluginCaller() {
Optional<JavaPlugin> foundFrame = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
.walk(stream -> stream
- .filter(frame -> frame.getDeclaringClass().getClassLoader() instanceof PluginClassLoader)
.map((frame) -> {
- PluginClassLoader classLoader = (PluginClassLoader) frame.getDeclaringClass().getClassLoader();
- return classLoader.getPlugin();
+ ClassLoader classLoader = frame.getDeclaringClass().getClassLoader();
+ JavaPlugin plugin;
+ if (classLoader instanceof ConfiguredPluginClassLoader configuredPluginClassLoader) {
+ plugin = configuredPluginClassLoader.getPlugin();
+ } else {
+ plugin = null;
+ }
+
+ return plugin;
})
+ .filter(Objects::nonNull)
.findFirst());
return foundFrame.orElse(null);
diff --git a/src/main/java/net/minecraft/core/registries/BuiltInRegistries.java b/src/main/java/net/minecraft/core/registries/BuiltInRegistries.java
index bc91370654f5da33cbfe7d42431568915c1159d6..b43af53960978ac04bccde08544a562841492791 100644
--- a/src/main/java/net/minecraft/core/registries/BuiltInRegistries.java
+++ b/src/main/java/net/minecraft/core/registries/BuiltInRegistries.java
@@ -304,7 +304,13 @@ public class BuiltInRegistries {
}
public static void bootStrap() {
+ // Paper start
+ bootStrap(() -> {});
+ }
+ public static void bootStrap(Runnable runnable) {
+ // Paper end
createContents();
+ runnable.run(); // Paper
freeze();
validate(REGISTRY);
}
diff --git a/src/main/java/net/minecraft/server/Bootstrap.java b/src/main/java/net/minecraft/server/Bootstrap.java
index 15ee2f2a83bfef2f6891d9bfb2d3a8c14b24ffb1..d0d95d729853fc296c4931a2f73a3fc5f94302c9 100644
--- a/src/main/java/net/minecraft/server/Bootstrap.java
+++ b/src/main/java/net/minecraft/server/Bootstrap.java
@@ -74,7 +74,11 @@ public class Bootstrap {
EntitySelectorOptions.bootStrap();
DispenseItemBehavior.bootStrap();
CauldronInteraction.bootStrap();
- BuiltInRegistries.bootStrap();
+ // Paper start
+ BuiltInRegistries.bootStrap(() -> {
+ io.papermc.paper.plugin.entrypoint.LaunchEntryPointHandler.enterBootstrappers(); // Paper - Entrypoint for bootstrapping
+ });
+ // Paper end
CreativeModeTabs.validate();
Bootstrap.wrapStreams();
Bootstrap.bootstrapDuration.set(Duration.between(instant, Instant.now()).toMillis());
diff --git a/src/main/java/net/minecraft/server/Main.java b/src/main/java/net/minecraft/server/Main.java
index 5b4ac7b4fd0077e900e9f788963f1613bbc9a5d0..6afede80c10503a261d0f735c351d943597be9ff 100644
--- a/src/main/java/net/minecraft/server/Main.java
+++ b/src/main/java/net/minecraft/server/Main.java
@@ -119,6 +119,7 @@ public class Main {
JvmProfiler.INSTANCE.start(Environment.SERVER);
}
+ io.papermc.paper.plugin.PluginInitializerManager.load(optionset); // Paper
Bootstrap.bootStrap();
Bootstrap.validate();
Util.startTimerHackThread();
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
index 3a0f3992e28c3057d598daf78c0b70b1437ae0b0..45160b93a24dc74f6368441e2a4fe659ceaf5bf5 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
@@ -274,7 +274,8 @@ public final class CraftServer implements Server {
private final CraftCommandMap commandMap = new CraftCommandMap(this);
private final SimpleHelpMap helpMap = new SimpleHelpMap(this);
private final StandardMessenger messenger = new StandardMessenger();
- private final SimplePluginManager pluginManager = new SimplePluginManager(this, this.commandMap);
+ private final SimplePluginManager pluginManager = new SimplePluginManager(this, commandMap);
+ public final io.papermc.paper.plugin.manager.PaperPluginManagerImpl paperPluginManager = new io.papermc.paper.plugin.manager.PaperPluginManagerImpl(this, this.commandMap, pluginManager); {this.pluginManager.paperPluginManager = this.paperPluginManager;} // Paper
private final StructureManager structureManager;
protected final DedicatedServer console;
protected final DedicatedPlayerList playerList;
@@ -420,24 +421,7 @@ public final class CraftServer implements Server {
}
public void loadPlugins() {
- this.pluginManager.registerInterface(JavaPluginLoader.class);
-
- File pluginFolder = (File) this.console.options.valueOf("plugins");
-
- if (pluginFolder.exists()) {
- Plugin[] plugins = this.pluginManager.loadPlugins(pluginFolder);
- for (Plugin plugin : plugins) {
- try {
- String message = String.format("Loading %s", plugin.getDescription().getFullName());
- plugin.getLogger().info(message);
- plugin.onLoad();
- } catch (Throwable ex) {
- Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, ex.getMessage() + " initializing " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex);
- }
- }
- } else {
- pluginFolder.mkdir();
- }
+ io.papermc.paper.plugin.entrypoint.LaunchEntryPointHandler.INSTANCE.enter(io.papermc.paper.plugin.entrypoint.Entrypoint.PLUGIN); // Paper - replace implementation
}
public void enablePlugins(PluginLoadOrder type) {
@@ -526,15 +510,17 @@ public final class CraftServer implements Server {
private void enablePlugin(Plugin plugin) {
try {
List<Permission> perms = plugin.getDescription().getPermissions();
-
+ List<Permission> permsToLoad = new ArrayList<>(); // Paper
for (Permission perm : perms) {
- try {
- this.pluginManager.addPermission(perm, false);
- } catch (IllegalArgumentException ex) {
- this.getLogger().log(Level.WARNING, "Plugin " + plugin.getDescription().getFullName() + " tried to register permission '" + perm.getName() + "' but it's already registered", ex);
+ // Paper start
+ if (this.paperPluginManager.getPermission(perm.getName()) == null) {
+ permsToLoad.add(perm);
+ } else {
+ this.getLogger().log(Level.WARNING, "Plugin " + plugin.getDescription().getFullName() + " tried to register permission '" + perm.getName() + "' but it's already registered");
+ // Paper end
}
}
- this.pluginManager.dirtyPermissibles();
+ this.paperPluginManager.addPermissions(permsToLoad); // Paper
this.pluginManager.enablePlugin(plugin);
} catch (Throwable ex) {
@@ -975,6 +961,7 @@ public final class CraftServer implements Server {
"This plugin is not properly shutting down its async tasks when it is being reloaded. This may cause conflicts with the newly loaded version of the plugin"
));
}
+ io.papermc.paper.plugin.PluginInitializerManager.reload(this.console); // Paper
this.loadPlugins();
this.enablePlugins(PluginLoadOrder.STARTUP);
this.enablePlugins(PluginLoadOrder.POSTWORLD);
diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/MinecraftInternalPlugin.java b/src/main/java/org/bukkit/craftbukkit/scheduler/MinecraftInternalPlugin.java
index 909b2c98e7a9117d2f737245e4661792ffafb744..d96399e9bf1a58db5a4a22e58abb99e7660e0694 100644
--- a/src/main/java/org/bukkit/craftbukkit/scheduler/MinecraftInternalPlugin.java
+++ b/src/main/java/org/bukkit/craftbukkit/scheduler/MinecraftInternalPlugin.java
@@ -42,6 +42,12 @@ public class MinecraftInternalPlugin extends PluginBase {
public PluginDescriptionFile getDescription() {
return pdf;
}
+ // Paper start
+ @Override
+ public io.papermc.paper.plugin.configuration.PluginMeta getPluginMeta() {
+ return pdf;
+ }
+ // Paper end
@Override
public FileConfiguration getConfig() {
diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
index da97b4e91b7952f1459e59c74447a659842990bc..adf28b8e77d42267ce41713e031ee316366202e8 100644
--- a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
@@ -421,6 +421,12 @@ public final class CraftMagicNumbers implements UnsafeValues {
net.minecraft.world.item.ItemStack nmsItemStack = CraftItemStack.asNMSCopy(itemStack);
return nmsItemStack.getItem().getDescriptionId(nmsItemStack);
}
+ // Paper start
+ @Override
+ public boolean isSupportedApiVersion(String apiVersion) {
+ return apiVersion != null && SUPPORTED_API.contains(apiVersion);
+ }
+ // Paper end
@Override
public String getTranslationKey(final Attribute attribute) {
diff --git a/src/main/resources/META-INF/services/io.papermc.paper.plugin.entrypoint.classloader.ClassloaderBytecodeModifier b/src/main/resources/META-INF/services/io.papermc.paper.plugin.entrypoint.classloader.ClassloaderBytecodeModifier
new file mode 100644
index 0000000000000000000000000000000000000000..20dbe2775951bfcdb85c5d679ac86c77a93e0847
--- /dev/null
+++ b/src/main/resources/META-INF/services/io.papermc.paper.plugin.entrypoint.classloader.ClassloaderBytecodeModifier
@@ -0,0 +1 @@
+io.papermc.paper.plugin.entrypoint.classloader.PaperClassloaderBytecodeModifier
diff --git a/src/main/resources/META-INF/services/io.papermc.paper.plugin.provider.classloader.PaperClassLoaderStorage b/src/main/resources/META-INF/services/io.papermc.paper.plugin.provider.classloader.PaperClassLoaderStorage
new file mode 100644
index 0000000000000000000000000000000000000000..a22647244037cd92262b3b5a6582f0a11172fdc8
--- /dev/null
+++ b/src/main/resources/META-INF/services/io.papermc.paper.plugin.provider.classloader.PaperClassLoaderStorage
@@ -0,0 +1 @@
+io.papermc.paper.plugin.entrypoint.classloader.group.PaperPluginClassLoaderStorage
diff --git a/src/main/resources/META-INF/services/org.bukkit.plugin.PluginLoader b/src/main/resources/META-INF/services/org.bukkit.plugin.PluginLoader
new file mode 100644
index 0000000000000000000000000000000000000000..4f78bc62d03460463b9694de933e5b73da8df6e3
--- /dev/null
+++ b/src/main/resources/META-INF/services/org.bukkit.plugin.PluginLoader
@@ -0,0 +1 @@
+io.papermc.paper.plugin.manager.DummyBukkitPluginLoader
diff --git a/src/test/java/io/papermc/paper/plugin/PaperTestPlugin.java b/src/test/java/io/papermc/paper/plugin/PaperTestPlugin.java
new file mode 100644
index 0000000000000000000000000000000000000000..1d14f530ef888102e47eeeaf0d1a6076e51871c4
--- /dev/null
+++ b/src/test/java/io/papermc/paper/plugin/PaperTestPlugin.java
@@ -0,0 +1,146 @@
+package io.papermc.paper.plugin;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import org.bukkit.Server;
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandSender;
+import org.bukkit.configuration.file.FileConfiguration;
+import org.bukkit.generator.BiomeProvider;
+import org.bukkit.generator.ChunkGenerator;
+import org.bukkit.plugin.PluginBase;
+import org.bukkit.plugin.PluginDescriptionFile;
+import org.bukkit.plugin.PluginLoader;
+import org.bukkit.plugin.PluginLogger;
+
+import java.io.File;
+import java.io.InputStream;
+import java.util.List;
+
+public class PaperTestPlugin extends PluginBase {
+ private final String pluginName;
+ private boolean enabled = true;
+ private final PluginMeta configuration;
+
+ public PaperTestPlugin(String pluginName) {
+ this.pluginName = pluginName;
+ this.configuration = new TestPluginMeta(pluginName);
+ }
+
+ public PaperTestPlugin(PluginMeta configuration) {
+ this.configuration = configuration;
+ this.pluginName = configuration.getName();
+ }
+
+ @Override
+ public File getDataFolder() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public PluginDescriptionFile getDescription() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public PluginMeta getPluginMeta() {
+ return this.configuration;
+ }
+
+ @Override
+ public FileConfiguration getConfig() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public InputStream getResource(String filename) {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public void saveConfig() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public void saveDefaultConfig() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public void saveResource(String resourcePath, boolean replace) {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public void reloadConfig() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public PluginLogger getLogger() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public PluginLoader getPluginLoader() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public Server getServer() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ @Override
+ public void onDisable() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public void onLoad() {
+ }
+
+ @Override
+ public void onEnable() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public boolean isNaggable() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public void setNaggable(boolean canNag) {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public BiomeProvider getDefaultBiomeProvider(String worldName, String id) {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+}
diff --git a/src/test/java/io/papermc/paper/plugin/PluginDependencyValidationTest.java b/src/test/java/io/papermc/paper/plugin/PluginDependencyValidationTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..83b1274ba56f03bec6cb69a35f33dc04f008cc1e
--- /dev/null
+++ b/src/test/java/io/papermc/paper/plugin/PluginDependencyValidationTest.java
@@ -0,0 +1,60 @@
+package io.papermc.paper.plugin;
+
+import io.papermc.paper.plugin.entrypoint.dependency.MetaDependencyTree;
+import io.papermc.paper.plugin.entrypoint.dependency.SimpleMetaDependencyTree;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class PluginDependencyValidationTest {
+
+ private static final TestPluginMeta MAIN;
+ private static final TestPluginMeta HARD_DEPENDENCY_1;
+ private static final TestPluginMeta SOFT_DEPENDENCY_1;
+
+ public static final String ROOT_NAME = "main";
+
+ public static final String REGISTERED_HARD_DEPEND = "hard1";
+ public static final String REGISTERED_SOFT_DEPEND = "soft1";
+ public static final String UNREGISTERED_HARD_DEPEND = "hard2";
+ public static final String UNREGISTERED_SOFT_DEPEND = "soft2";
+
+ static {
+ MAIN = new TestPluginMeta(ROOT_NAME);
+ MAIN.setSoftDependencies(List.of(REGISTERED_SOFT_DEPEND, UNREGISTERED_SOFT_DEPEND));
+ MAIN.setHardDependencies(List.of(REGISTERED_HARD_DEPEND, UNREGISTERED_HARD_DEPEND));
+
+ HARD_DEPENDENCY_1 = new TestPluginMeta(REGISTERED_HARD_DEPEND);
+ SOFT_DEPENDENCY_1 = new TestPluginMeta(REGISTERED_SOFT_DEPEND);
+ }
+
+ @Test
+ public void testDependencyTree() {
+ MetaDependencyTree tree = new SimpleMetaDependencyTree();
+ tree.add(MAIN);
+ tree.add(HARD_DEPENDENCY_1);
+ tree.add(SOFT_DEPENDENCY_1);
+
+ // Test simple transitive dependencies
+ assertThat("%s was not a transitive dependency of %s".formatted(ROOT_NAME, REGISTERED_SOFT_DEPEND), tree.isTransitiveDependency(MAIN, SOFT_DEPENDENCY_1));
+ assertThat("%s was not a transitive dependency of %s".formatted(ROOT_NAME, REGISTERED_HARD_DEPEND), tree.isTransitiveDependency(MAIN, HARD_DEPENDENCY_1));
+
+ assertThat("%s was a transitive dependency of %s".formatted(REGISTERED_SOFT_DEPEND, ROOT_NAME), !tree.isTransitiveDependency(SOFT_DEPENDENCY_1, MAIN));
+ assertThat("%s was a transitive dependency of %s".formatted(REGISTERED_HARD_DEPEND, ROOT_NAME), !tree.isTransitiveDependency(HARD_DEPENDENCY_1, MAIN));
+
+ // Test to ensure that registered dependencies exist
+ assertThat("tree did not contain dependency %s".formatted(ROOT_NAME), tree.hasDependency(ROOT_NAME));
+ assertThat("tree did not contain dependency %s".formatted(REGISTERED_HARD_DEPEND), tree.hasDependency(REGISTERED_HARD_DEPEND));
+ assertThat("tree did not contain dependency %s".formatted(REGISTERED_SOFT_DEPEND), tree.hasDependency(REGISTERED_SOFT_DEPEND));
+
+ // Test to ensure unregistered dependencies don't exist
+ assertThat("tree contained dependency %s".formatted(UNREGISTERED_HARD_DEPEND), !tree.hasDependency(UNREGISTERED_HARD_DEPEND));
+ assertThat("tree contained dependency %s".formatted(UNREGISTERED_SOFT_DEPEND), !tree.hasDependency(UNREGISTERED_SOFT_DEPEND));
+
+ // Test removal
+ tree.remove(HARD_DEPENDENCY_1);
+ assertThat("tree contained dependency %s".formatted(REGISTERED_HARD_DEPEND), !tree.hasDependency(REGISTERED_HARD_DEPEND));
+ }
+}
diff --git a/src/test/java/io/papermc/paper/plugin/PluginLoadOrderTest.java b/src/test/java/io/papermc/paper/plugin/PluginLoadOrderTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..c2c3c2f24ea802628bc4a36ef180fc08f4e5d288
--- /dev/null
+++ b/src/test/java/io/papermc/paper/plugin/PluginLoadOrderTest.java
@@ -0,0 +1,148 @@
+package io.papermc.paper.plugin;
+
+import com.google.common.graph.GraphBuilder;
+import io.papermc.paper.plugin.entrypoint.dependency.SimpleMetaDependencyTree;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+import io.papermc.paper.plugin.entrypoint.strategy.modern.ModernPluginLoadingStrategy;
+import io.papermc.paper.plugin.entrypoint.strategy.ProviderConfiguration;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class PluginLoadOrderTest {
+
+ private static List<PluginProvider<PaperTestPlugin>> REGISTERED_PROVIDERS = new ArrayList<>();
+ private static Map<String, Integer> LOAD_ORDER = new HashMap<>();
+ private static final String[] EMPTY = {};
+
+ static {
+ setup();
+ }
+
+ private static TestJavaPluginProvider setup(String identifier, String[] loadAfter, String[] loadAfterSoft, String[] before) {
+ TestPluginMeta configuration = new TestPluginMeta(identifier);
+ configuration.setHardDependencies(List.of(loadAfter));
+ configuration.setSoftDependencies(List.of(loadAfterSoft));
+ configuration.setLoadBefore(List.of(before));
+
+ TestJavaPluginProvider provider = new TestJavaPluginProvider(configuration);
+ REGISTERED_PROVIDERS.add(provider);
+ return provider;
+ }
+
+ /**
+ * Obfuscated plugin names, this uses a real dependency tree...
+ */
+ private static void setup() {
+ setup("RedAir", EMPTY, new String[]{"NightShovel", "EmeraldFire"}, new String[]{"GreenShovel", "IronSpork", "BrightBlueShovel", "WireDoor"});
+ setup("BigGrass", EMPTY, new String[]{"IronEarth", "RedAir"}, new String[]{"BlueFire"});
+ setup("BlueFire", EMPTY, EMPTY, EMPTY);
+ setup("BigPaper", EMPTY, new String[]{"BlueFire"}, EMPTY);
+ setup("EmeraldSpork", EMPTY, EMPTY, new String[]{"GoldPaper", "YellowSnow"});
+ setup("GreenShovel", EMPTY, EMPTY, EMPTY);
+ setup("BrightBlueGrass", new String[]{"BigPaper"}, new String[]{"DarkSpork"}, EMPTY);
+ setup("GoldPaper", EMPTY, new String[]{"BlueFire"}, EMPTY);
+ setup("GreenGlass", EMPTY, EMPTY, EMPTY);
+ setup("GoldNeptune", EMPTY, new String[]{"GreenShovel", "GoldNeptuneVersioning"}, EMPTY);
+ setup("RedPaper", EMPTY, new String[]{"GoldPaper", "GoldFire", "EmeraldGrass", "BlueFire", "CopperSpork", "YellowDoor", "OrangeClam", "BlueSponge", "GoldNeptune", "BrightBlueGrass", "DarkSpoon", "BigShovel", "GreenGlass", "IronGlass"}, new String[]{"IronPaper", "YellowFire"});
+ setup("YellowGrass", EMPTY, new String[]{"RedAir"}, EMPTY);
+ setup("WireFire", EMPTY, new String[]{"RedPaper", "WireGrass", "YellowSpork", "NightAir"}, EMPTY);
+ setup("OrangeNeptune", EMPTY, EMPTY, EMPTY);
+ setup("BigSpoon", new String[]{"YellowGrass", "GreenShovel"}, new String[]{"RedAir", "GoldNeptune", "BrightBlueGrass", "LightDoor", "LightSpork", "LightEarth", "NightDoor", "OrangeSpoon", "GoldSponge", "GoldDoor", "DarkPaper", "RedPaper", "GreenGlass", "IronGlass", "NightGlass", "BigGrass", "BlueFire", "YellowSpoon", "DiamondGrass", "DiamondShovel", "DarkSnow", "EmeraldGlass", "EmeraldSpoon", "LightFire", "WireGrass", "RedEarth", "WireFire"}, EMPTY);
+ setup("CopperSnow", EMPTY, new String[]{"RedSnow", "OrangeFire", "WireAir", "GreenGlass", "NightSpork", "EmeraldPaper"}, new String[]{"BlueGrass"});
+ setup("BrightBluePaper", EMPTY, new String[]{"GoldEarth", "BrightBlueSpoon", "CopperGlass", "LightSporkChat", "DarkAir", "LightEarth", "DiamondDoor", "YellowShovel", "BlueAir", "DarkShovel", "GoldPaper", "BlueFire", "GreenGlass", "YellowSpork", "BigGrass", "OrangePaper", "DarkPaper"}, new String[]{"WireShovel"});
+ setup("LightSponge", EMPTY, EMPTY, EMPTY);
+ setup("OrangeShovel", EMPTY, EMPTY, EMPTY);
+ setup("GoldGrass", EMPTY, new String[]{"GreenGlass", "BlueFire"}, EMPTY);
+ setup("IronSponge", EMPTY, new String[]{"DiamondEarth"}, EMPTY);
+ setup("EmeraldSnow", EMPTY, EMPTY, EMPTY);
+ setup("BlueSpoon", new String[]{"BigGrass"}, new String[]{"GreenGlass", "GoldPaper", "GreenShovel", "YellowClam"}, EMPTY);
+ setup("BigSpork", EMPTY, new String[]{"BigPaper"}, EMPTY);
+ setup("BluePaper", EMPTY, new String[]{"BigClam", "RedSpoon", "GreenFire", "WireSnow", "OrangeSnow", "BlueFire", "BrightBlueGrass", "YellowSpork", "GreenGlass"}, EMPTY);
+ setup("OrangeSpork", EMPTY, EMPTY, EMPTY);
+ setup("DiamondNeptune", EMPTY, new String[]{"GreenGlass", "GreenShovel", "YellowNeptune"}, EMPTY);
+ setup("BigFire", EMPTY, new String[]{"BlueFire", "BrightBlueDoor", "GreenGlass"}, EMPTY);
+ setup("NightNeptune", EMPTY, new String[]{"BlueFire", "DarkGlass", "GoldPaper", "YellowNeptune", "BlueShovel"}, EMPTY);
+ setup("YellowEarth", new String[]{"RedAir"}, EMPTY, EMPTY);
+ setup("DiamondClam", EMPTY, EMPTY, EMPTY);
+ setup("CopperAir", EMPTY, new String[]{"BigPaper"}, EMPTY);
+ setup("NightSpoon", new String[]{"OrangeNeptune"}, new String[]{"BlueFire", "GreenGlass", "RedSpork", "GoldPaper", "BigShovel", "YellowSponge", "EmeraldSpork"}, EMPTY);
+ setup("GreenClam", EMPTY, new String[]{"GreenShovel", "BrightBlueEarth", "BigSpoon", "RedPaper", "BlueFire", "GreenGlass", "WireFire", "GreenSnow"}, EMPTY);
+ setup("YellowPaper", EMPTY, EMPTY, EMPTY);
+ setup("WireGlass", new String[]{"YellowGrass"}, new String[]{"YellowGlass", "BigSpoon", "CopperSnow", "GreenGlass", "BlueEarth"}, EMPTY);
+ setup("BlueSpork", EMPTY, new String[]{"BrightBlueGrass"}, EMPTY);
+ setup("CopperShovel", EMPTY, new String[]{"GreenGlass"}, EMPTY);
+ setup("RedClam", EMPTY, EMPTY, EMPTY);
+ setup("EmeraldClam", EMPTY, new String[]{"BlueFire"}, EMPTY);
+ setup("DarkClam", EMPTY, new String[]{"GoldAir", "LightGlass"}, EMPTY);
+ setup("WireSpoon", EMPTY, new String[]{"GoldPaper", "LightSnow"}, EMPTY);
+ setup("CopperNeptune", EMPTY, new String[]{"GreenGlass", "BigGrass"}, EMPTY);
+ setup("RedNeptune", EMPTY, EMPTY, EMPTY);
+ setup("GreenAir", EMPTY, EMPTY, EMPTY);
+ setup("RedFire", new String[]{"BrightBlueGrass", "BigPaper"}, new String[]{"BlueFire", "GreenGlass", "BigGrass"}, EMPTY);
+ }
+
+ @BeforeEach
+ public void loadProviders() {
+ AtomicInteger currentLoad = new AtomicInteger();
+ ModernPluginLoadingStrategy<PaperTestPlugin> modernPluginLoadingStrategy = new ModernPluginLoadingStrategy<>(new ProviderConfiguration<>() {
+ @Override
+ public void applyContext(PluginProvider<PaperTestPlugin> provider, DependencyContext dependencyContext) {
+ }
+
+ @Override
+ public boolean load(PluginProvider<PaperTestPlugin> provider, PaperTestPlugin provided) {
+ LOAD_ORDER.put(provider.getMeta().getName(), currentLoad.getAndIncrement());
+ return false;
+ }
+
+ });
+
+ modernPluginLoadingStrategy.loadProviders(REGISTERED_PROVIDERS, new SimpleMetaDependencyTree(GraphBuilder.directed().build()));
+ }
+
+ @Test
+ public void testDependencies() {
+ for (PluginProvider<PaperTestPlugin> provider : REGISTERED_PROVIDERS) {
+ TestPluginMeta pluginMeta = (TestPluginMeta) provider.getMeta();
+ String identifier = pluginMeta.getName();
+ Assertions.assertTrue(LOAD_ORDER.containsKey(identifier), "Provider wasn't loaded! (%s)".formatted(identifier));
+
+ int index = LOAD_ORDER.get(identifier);
+
+ // Hard dependencies should be loaded BEFORE
+ for (String hardDependency : pluginMeta.getPluginDependencies()) {
+ Assertions.assertTrue(LOAD_ORDER.containsKey(hardDependency), "Plugin (%s) is missing hard dependency (%s)".formatted(identifier, hardDependency));
+
+ int dependencyIndex = LOAD_ORDER.get(hardDependency);
+ Assertions.assertTrue(index > dependencyIndex, "Plugin (%s) was not loaded BEFORE soft dependency. (%s)".formatted(identifier, hardDependency));
+ }
+
+ for (String softDependency : pluginMeta.getPluginSoftDependencies()) {
+ if (!LOAD_ORDER.containsKey(softDependency)) {
+ continue;
+ }
+
+ int dependencyIndex = LOAD_ORDER.get(softDependency);
+
+ Assertions.assertTrue(index > dependencyIndex, "Plugin (%s) was not loaded BEFORE soft dependency. (%s)".formatted(identifier, softDependency));
+ }
+
+ for (String loadBefore : pluginMeta.getLoadBeforePlugins()) {
+ if (!LOAD_ORDER.containsKey(loadBefore)) {
+ continue;
+ }
+
+ int dependencyIndex = LOAD_ORDER.get(loadBefore);
+ Assertions.assertTrue(index < dependencyIndex, "Plugin (%s) was NOT loaded BEFORE loadbefore dependency. (%s)".formatted(identifier, loadBefore));
+ }
+ }
+ }
+}
diff --git a/src/test/java/io/papermc/paper/plugin/PluginManagerTest.java b/src/test/java/io/papermc/paper/plugin/PluginManagerTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..b7d69dda2b88218221a3cca6db4445cb58aa0179
--- /dev/null
+++ b/src/test/java/io/papermc/paper/plugin/PluginManagerTest.java
@@ -0,0 +1,75 @@
+package io.papermc.paper.plugin;
+
+import org.bukkit.Bukkit;
+import org.bukkit.event.Event;
+import org.bukkit.permissions.Permission;
+import org.bukkit.plugin.PluginManager;
+import org.bukkit.support.AbstractTestingBase;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
+
+public class PluginManagerTest extends AbstractTestingBase {
+
+ private static final PluginManager pm = Bukkit.getPluginManager();
+
+ @Test
+ public void testSyncSameThread() {
+ final Event event = new TestEvent(false);
+ pm.callEvent(event);
+ }
+
+ @Test
+ public void testRemovePermissionByNameLower() {
+ this.testRemovePermissionByName("lower");
+ }
+
+ @Test
+ public void testRemovePermissionByNameUpper() {
+ this.testRemovePermissionByName("UPPER");
+ }
+
+ @Test
+ public void testRemovePermissionByNameCamel() {
+ this.testRemovePermissionByName("CaMeL");
+ }
+
+ @Test
+ public void testRemovePermissionByPermissionLower() {
+ this.testRemovePermissionByPermission("lower");
+ }
+
+ @Test
+ public void testRemovePermissionByPermissionUpper() {
+ this.testRemovePermissionByPermission("UPPER");
+ }
+
+ @Test
+ public void testRemovePermissionByPermissionCamel() {
+ this.testRemovePermissionByPermission("CaMeL");
+ }
+
+ private void testRemovePermissionByName(final String name) {
+ final Permission perm = new Permission(name);
+ pm.addPermission(perm);
+ assertThat("Permission \"" + name + "\" was not added", pm.getPermission(name), is(perm));
+ pm.removePermission(name);
+ assertThat("Permission \"" + name + "\" was not removed", pm.getPermission(name), is(nullValue()));
+ }
+
+ private void testRemovePermissionByPermission(final String name) {
+ final Permission perm = new Permission(name);
+ pm.addPermission(perm);
+ assertThat("Permission \"" + name + "\" was not added", pm.getPermission(name), is(perm));
+ pm.removePermission(perm);
+ assertThat("Permission \"" + name + "\" was not removed", pm.getPermission(name), is(nullValue()));
+ }
+
+ @AfterEach
+ public void tearDown() {
+ pm.clearPlugins();
+ assertThat(pm.getPermissions(), is(empty()));
+ }
+}
diff --git a/src/test/java/io/papermc/paper/plugin/PluginNamingTest.java b/src/test/java/io/papermc/paper/plugin/PluginNamingTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..6c3be5b84ae245652261668a52ce49934ef200a9
--- /dev/null
+++ b/src/test/java/io/papermc/paper/plugin/PluginNamingTest.java
@@ -0,0 +1,28 @@
+package io.papermc.paper.plugin;
+
+import io.papermc.paper.plugin.provider.configuration.PaperPluginMeta;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class PluginNamingTest {
+ private static final String TEST_NAME = "Test_Plugin";
+ private static final String TEST_VERSION = "1.0";
+
+ private final PaperPluginMeta pluginMeta;
+
+ public PluginNamingTest() {
+ this.pluginMeta = new PaperPluginMeta();
+ this.pluginMeta.setName(TEST_NAME);
+ this.pluginMeta.setVersion(TEST_VERSION);
+ }
+
+ @Test
+ public void testName() {
+ Assertions.assertEquals(TEST_NAME, this.pluginMeta.getName());
+ }
+
+ @Test
+ public void testDisplayName() {
+ Assertions.assertEquals(TEST_NAME + " v" + TEST_VERSION, this.pluginMeta.getDisplayName());
+ }
+}
diff --git a/src/test/java/io/papermc/paper/plugin/SyntheticEventTest.java b/src/test/java/io/papermc/paper/plugin/SyntheticEventTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..2a7408ed5d9a415333212cadd7fefcd03785afbf
--- /dev/null
+++ b/src/test/java/io/papermc/paper/plugin/SyntheticEventTest.java
@@ -0,0 +1,42 @@
+package io.papermc.paper.plugin;
+
+import io.papermc.paper.plugin.manager.PaperPluginManagerImpl;
+import org.bukkit.Bukkit;
+import org.bukkit.event.Event;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.Listener;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class SyntheticEventTest {
+
+ @Test
+ public void test() {
+ PaperTestPlugin paperTestPlugin = new PaperTestPlugin("synthetictest");
+ PaperPluginManagerImpl paperPluginManager = new PaperPluginManagerImpl(Bukkit.getServer(), null, null);
+
+ TestEvent event = new TestEvent(false);
+ Impl impl = new Impl();
+
+ paperPluginManager.registerEvents(impl, paperTestPlugin);
+ paperPluginManager.callEvent(event);
+
+ Assertions.assertEquals(1, impl.callCount);
+ }
+
+ public abstract static class Base<E extends Event> implements Listener {
+ int callCount = 0;
+
+ public void accept(E evt) {
+ callCount++;
+ }
+ }
+
+ public static class Impl extends Base<TestEvent> {
+ @Override
+ @EventHandler
+ public void accept(TestEvent evt) {
+ super.accept(evt);
+ }
+ }
+}
diff --git a/src/test/java/io/papermc/paper/plugin/TestEvent.java b/src/test/java/io/papermc/paper/plugin/TestEvent.java
new file mode 100644
index 0000000000000000000000000000000000000000..04903794a8ee4dd73162ae240862ff6dc4cb4e24
--- /dev/null
+++ b/src/test/java/io/papermc/paper/plugin/TestEvent.java
@@ -0,0 +1,22 @@
+package io.papermc.paper.plugin;
+
+
+import org.bukkit.event.Event;
+import org.bukkit.event.HandlerList;
+
+public class TestEvent extends Event {
+ private static final HandlerList handlers = new HandlerList();
+
+ public TestEvent(boolean async) {
+ super(async);
+ }
+
+ @Override
+ public HandlerList getHandlers() {
+ return handlers;
+ }
+
+ public static HandlerList getHandlerList() {
+ return handlers;
+ }
+}
diff --git a/src/test/java/io/papermc/paper/plugin/TestJavaPluginProvider.java b/src/test/java/io/papermc/paper/plugin/TestJavaPluginProvider.java
new file mode 100644
index 0000000000000000000000000000000000000000..349932b582349c988f3244552b6e6da5dede3d1d
--- /dev/null
+++ b/src/test/java/io/papermc/paper/plugin/TestJavaPluginProvider.java
@@ -0,0 +1,83 @@
+package io.papermc.paper.plugin;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import io.papermc.paper.plugin.provider.PluginProvider;
+import io.papermc.paper.plugin.provider.configuration.LoadOrderConfiguration;
+import io.papermc.paper.plugin.provider.entrypoint.DependencyContext;
+import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
+import org.jetbrains.annotations.NotNull;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.JarFile;
+
+public class TestJavaPluginProvider implements PluginProvider<PaperTestPlugin> {
+
+ private final TestPluginMeta testPluginConfiguration;
+
+ public TestJavaPluginProvider(TestPluginMeta testPluginConfiguration) {
+ this.testPluginConfiguration = testPluginConfiguration;
+ }
+
+ @Override
+ public @NotNull Path getSource() {
+ return Path.of("dummy");
+ }
+
+ @Override
+ public JarFile file() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public PaperTestPlugin createInstance() {
+ return new PaperTestPlugin(this.testPluginConfiguration);
+ }
+
+ @Override
+ public TestPluginMeta getMeta() {
+ return this.testPluginConfiguration;
+ }
+
+ @Override
+ public ComponentLogger getLogger() {
+ return ComponentLogger.logger("TestPlugin");
+ }
+
+ @Override
+ public LoadOrderConfiguration createConfiguration(@NotNull Map<String, PluginProvider<?>> toLoad) {
+ return new LoadOrderConfiguration() {
+ @Override
+ public @NotNull List<String> getLoadBefore() {
+ return TestJavaPluginProvider.this.testPluginConfiguration.getLoadBeforePlugins();
+ }
+
+ @Override
+ public @NotNull List<String> getLoadAfter() {
+ List<String> loadAfter = new ArrayList<>();
+ loadAfter.addAll(TestJavaPluginProvider.this.testPluginConfiguration.getPluginDependencies());
+ loadAfter.addAll(TestJavaPluginProvider.this.testPluginConfiguration.getPluginSoftDependencies());
+ return loadAfter;
+ }
+
+ @Override
+ public @NotNull PluginMeta getMeta() {
+ return TestJavaPluginProvider.this.testPluginConfiguration;
+ }
+ };
+ }
+
+ @Override
+ public List<String> validateDependencies(@NotNull DependencyContext context) {
+ List<String> missingDependencies = new ArrayList<>();
+ for (String hardDependency : this.getMeta().getPluginDependencies()) {
+ if (!context.hasDependency(hardDependency)) {
+ missingDependencies.add(hardDependency);
+ }
+ }
+
+ return missingDependencies;
+ }
+}
diff --git a/src/test/java/io/papermc/paper/plugin/TestPluginMeta.java b/src/test/java/io/papermc/paper/plugin/TestPluginMeta.java
new file mode 100644
index 0000000000000000000000000000000000000000..ba271c35eb2804f94cfc893bf94affb9ae13d3ba
--- /dev/null
+++ b/src/test/java/io/papermc/paper/plugin/TestPluginMeta.java
@@ -0,0 +1,114 @@
+package io.papermc.paper.plugin;
+
+import io.papermc.paper.plugin.configuration.PluginMeta;
+import org.bukkit.permissions.Permission;
+import org.bukkit.permissions.PermissionDefault;
+import org.bukkit.plugin.PluginLoadOrder;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.List;
+
+public class TestPluginMeta implements PluginMeta {
+
+ private final String identifier;
+ private List<String> hardDependencies = List.of();
+ private List<String> softDependencies = List.of();
+ private List<String> loadBefore = List.of();
+
+ public TestPluginMeta(String identifier) {
+ this.identifier = identifier;
+ }
+
+ @Override
+ public @NotNull String getName() {
+ return this.identifier;
+ }
+
+ @Override
+ public @NotNull String getMainClass() {
+ return "null";
+ }
+
+ @Override
+ public @NotNull PluginLoadOrder getLoadOrder() {
+ return PluginLoadOrder.POSTWORLD;
+ }
+
+ @Override
+ public @NotNull String getVersion() {
+ return "1.0";
+ }
+
+ @Override
+ public @Nullable String getLoggerPrefix() {
+ return this.identifier;
+ }
+
+ public void setHardDependencies(List<String> hardDependencies) {
+ this.hardDependencies = hardDependencies;
+ }
+
+ @Override
+ public @NotNull List<String> getPluginDependencies() {
+ return this.hardDependencies;
+ }
+
+ public void setSoftDependencies(List<String> softDependencies) {
+ this.softDependencies = softDependencies;
+ }
+
+ @Override
+ public @NotNull List<String> getPluginSoftDependencies() {
+ return this.softDependencies;
+ }
+
+ public void setLoadBefore(List<String> loadBefore) {
+ this.loadBefore = loadBefore;
+ }
+
+ @Override
+ public @NotNull List<String> getLoadBeforePlugins() {
+ return this.loadBefore;
+ }
+
+ @Override
+ public @NotNull List<String> getProvidedPlugins() {
+ return List.of();
+ }
+
+ @Override
+ public @NotNull List<String> getAuthors() {
+ return List.of();
+ }
+
+ @Override
+ public @NotNull List<String> getContributors() {
+ return List.of();
+ }
+
+ @Override
+ public @Nullable String getDescription() {
+ return "null";
+ }
+
+ @Override
+ public @Nullable String getWebsite() {
+ return "null";
+ }
+
+ @Override
+ public @NotNull List<Permission> getPermissions() {
+ return List.of();
+ }
+
+ @Override
+ public @NotNull PermissionDefault getPermissionDefault() {
+ return PermissionDefault.TRUE;
+ }
+
+ @Override
+ public @NotNull String getAPIVersion() {
+ return "null";
+ }
+}
diff --git a/src/test/java/org/bukkit/support/DummyServer.java b/src/test/java/org/bukkit/support/DummyServer.java
index 02a8e6b45bf304b6e0f88043a25188aa16b3d6bf..7a4681155f740a98ecafa0b992eae1fb5524551f 100644
--- a/src/test/java/org/bukkit/support/DummyServer.java
+++ b/src/test/java/org/bukkit/support/DummyServer.java
@@ -54,7 +54,7 @@ public final class DummyServer {
final Thread currentThread = Thread.currentThread();
when(instance.isPrimaryThread()).thenAnswer(ignored -> Thread.currentThread().equals(currentThread));
- final org.bukkit.plugin.PluginManager pluginManager = new org.bukkit.plugin.SimplePluginManager(instance, new org.bukkit.command.SimpleCommandMap(instance));
+ final org.bukkit.plugin.PluginManager pluginManager = new io.papermc.paper.plugin.manager.PaperPluginManagerImpl(instance, new org.bukkit.command.SimpleCommandMap(instance), null);
when(instance.getPluginManager()).thenReturn(pluginManager);
when(instance.getTag(anyString(), any(org.bukkit.NamespacedKey.class), any())).thenAnswer(ignored -> new io.papermc.paper.util.EmptyTag());
// paper end - testing additions
|