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

#include "precomp.h"

#define PlanDumpLevel REPORT_DEBUG

// internal struct definitions


// internal function definitions

static void PlannedExecutePackage(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage
    );
static void UninitializeRegistrationAction(
    __in BURN_DEPENDENT_REGISTRATION_ACTION* pAction
    );
static void UninitializeCacheAction(
    __in BURN_CACHE_ACTION* pCacheAction
    );
static void ResetPlannedContainerState(
    __in BURN_CONTAINER* pContainer
    );
static void ResetPlannedPayloadsState(
    __in BURN_PAYLOADS* pPayloads
    );
static void ResetPlannedPayloadGroupState(
    __in BURN_PAYLOAD_GROUP* pPayloadGroup
    );
static void ResetPlannedPackageState(
    __in BURN_PACKAGE* pPackage
    );
static void ResetPlannedRollbackBoundaryState(
    __in BURN_ROLLBACK_BOUNDARY* pRollbackBoundary
    );
static HRESULT PlanPackagesHelper(
    __in BURN_PACKAGE* rgPackages,
    __in DWORD cPackages,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_PLAN* pPlan,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables
    );
static HRESULT InitializePackage(
    __in BURN_PLAN* pPlan,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_VARIABLES* pVariables,
    __in BURN_PACKAGE* pPackage
    );
static HRESULT ProcessPackage(
    __in BOOL fBundlePerMachine,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables,
    __inout BURN_ROLLBACK_BOUNDARY** ppRollbackBoundary
    );
static HRESULT ProcessPackageRollbackBoundary(
    __in BURN_PLAN* pPlan,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables,
    __in_opt BURN_ROLLBACK_BOUNDARY* pEffectiveRollbackBoundary,
    __inout BURN_ROLLBACK_BOUNDARY** ppRollbackBoundary
    );
static HRESULT GetActionDefaultRequestState(
    __in BOOTSTRAPPER_ACTION action,
    __in BOOTSTRAPPER_PACKAGE_STATE currentState,
    __out BOOTSTRAPPER_REQUEST_STATE* pRequestState
    );
static HRESULT AddRegistrationAction(
    __in BURN_PLAN* pPlan,
    __in BURN_DEPENDENT_REGISTRATION_ACTION_TYPE type,
    __in_z LPCWSTR wzDependentProviderKey,
    __in_z LPCWSTR wzOwnerBundleId
    );
static HRESULT AddCachePackage(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage,
    __in BOOL fVital
    );
static HRESULT AddCachePackageHelper(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage,
    __in BOOL fVital
    );
static HRESULT AddCacheSlipstreamMsps(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage
    );
static DWORD GetNextCheckpointId(
    __in BURN_PLAN* pPlan
    );
static HRESULT AppendCacheAction(
    __in BURN_PLAN* pPlan,
    __out BURN_CACHE_ACTION** ppCacheAction
    );
static HRESULT AppendRollbackCacheAction(
    __in BURN_PLAN* pPlan,
    __out BURN_CACHE_ACTION** ppCacheAction
    );
static HRESULT AppendCleanAction(
    __in BURN_PLAN* pPlan,
    __out BURN_CLEAN_ACTION** ppCleanAction
    );
static HRESULT AppendRestoreRelatedBundleAction(
    __in BURN_PLAN* pPlan,
    __out BURN_EXECUTE_ACTION** ppExecuteAction
    );
static HRESULT ProcessPayloadGroup(
    __in BURN_PLAN* pPlan,
    __in BURN_PAYLOAD_GROUP* pPayloadGroup
    );
static void RemoveUnnecessaryActions(
    __in BOOL fExecute,
    __in BURN_EXECUTE_ACTION* rgActions,
    __in DWORD cActions
    );
static void FinalizePatchActions(
    __in BOOL fExecute,
    __in BURN_EXECUTE_ACTION* rgActions,
    __in DWORD cActions
    );
static void CalculateExpectedRegistrationStates(
    __in BURN_PACKAGE* rgPackages,
    __in DWORD cPackages
    );
static HRESULT PlanDependencyActions(
    __in BOOL fBundlePerMachine,
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage
    );
static HRESULT CalculateExecuteActions(
    __in BURN_PACKAGE* pPackage,
    __in_opt BURN_ROLLBACK_BOUNDARY* pActiveRollbackBoundary
    );
static BURN_CACHE_PACKAGE_TYPE GetCachePackageType(
    __in BURN_PACKAGE* pPackage,
    __in BOOL fExecute
    );
static BOOL ForceCache(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage
    );

// function definitions

extern "C" void PlanReset(
    __in BURN_PLAN* pPlan,
    __in BURN_VARIABLES* pVariables,
    __in BURN_CONTAINERS* pContainers,
    __in BURN_PACKAGES* pPackages,
    __in BURN_PAYLOAD_GROUP* pLayoutPayloads
    )
{
    ReleaseNullStr(pPlan->sczLayoutDirectory);
    PackageUninitialize(&pPlan->forwardCompatibleBundle);

    if (pPlan->rgRegistrationActions)
    {
        for (DWORD i = 0; i < pPlan->cRegistrationActions; ++i)
        {
            UninitializeRegistrationAction(&pPlan->rgRegistrationActions[i]);
        }
        MemFree(pPlan->rgRegistrationActions);
    }

    if (pPlan->rgRollbackRegistrationActions)
    {
        for (DWORD i = 0; i < pPlan->cRollbackRegistrationActions; ++i)
        {
            UninitializeRegistrationAction(&pPlan->rgRollbackRegistrationActions[i]);
        }
        MemFree(pPlan->rgRollbackRegistrationActions);
    }

    if (pPlan->rgCacheActions)
    {
        for (DWORD i = 0; i < pPlan->cCacheActions; ++i)
        {
            UninitializeCacheAction(&pPlan->rgCacheActions[i]);
        }
        MemFree(pPlan->rgCacheActions);
    }

    if (pPlan->rgExecuteActions)
    {
        for (DWORD i = 0; i < pPlan->cExecuteActions; ++i)
        {
            PlanUninitializeExecuteAction(&pPlan->rgExecuteActions[i]);
        }
        MemFree(pPlan->rgExecuteActions);
    }

    if (pPlan->rgRollbackActions)
    {
        for (DWORD i = 0; i < pPlan->cRollbackActions; ++i)
        {
            PlanUninitializeExecuteAction(&pPlan->rgRollbackActions[i]);
        }
        MemFree(pPlan->rgRollbackActions);
    }

    if (pPlan->rgRestoreRelatedBundleActions)
    {
        for (DWORD i = 0; i < pPlan->cRestoreRelatedBundleActions; ++i)
        {
            PlanUninitializeExecuteAction(&pPlan->rgRestoreRelatedBundleActions[i]);
        }
        MemFree(pPlan->rgRestoreRelatedBundleActions);
    }

    if (pPlan->rgCleanActions)
    {
        // Nothing needs to be freed inside clean actions today.
        MemFree(pPlan->rgCleanActions);
    }

    if (pPlan->rgPlannedProviders)
    {
        ReleaseDependencyArray(pPlan->rgPlannedProviders, pPlan->cPlannedProviders);
    }

    if (pPlan->rgContainerProgress)
    {
        MemFree(pPlan->rgContainerProgress);
    }

    if (pPlan->shContainerProgress)
    {
        ReleaseDict(pPlan->shContainerProgress);
    }

    if (pPlan->rgPayloadProgress)
    {
        MemFree(pPlan->rgPayloadProgress);
    }

    if (pPlan->shPayloadProgress)
    {
        ReleaseDict(pPlan->shPayloadProgress);
    }

    if (pPlan->pPayloads)
    {
        ResetPlannedPayloadsState(pPlan->pPayloads);
    }

    memset(pPlan, 0, sizeof(BURN_PLAN));

    if (pContainers->rgContainers)
    {
        for (DWORD i = 0; i < pContainers->cContainers; ++i)
        {
            ResetPlannedContainerState(&pContainers->rgContainers[i]);
        }
    }

    // Reset the planned actions for each package.
    if (pPackages->rgPackages)
    {
        for (DWORD i = 0; i < pPackages->cPackages; ++i)
        {
            ResetPlannedPackageState(&pPackages->rgPackages[i]);
        }
    }

    ResetPlannedPayloadGroupState(pLayoutPayloads);

    // Reset the planned state for each rollback boundary.
    if (pPackages->rgRollbackBoundaries)
    {
        for (DWORD i = 0; i < pPackages->cRollbackBoundaries; ++i)
        {
            ResetPlannedRollbackBoundaryState(&pPackages->rgRollbackBoundaries[i]);
        }
    }

    PlanSetVariables(BOOTSTRAPPER_ACTION_UNKNOWN, pVariables);
}

extern "C" void PlanUninitializeExecuteAction(
    __in BURN_EXECUTE_ACTION* pExecuteAction
    )
{
    switch (pExecuteAction->type)
    {
    case BURN_EXECUTE_ACTION_TYPE_RELATED_BUNDLE:
        ReleaseStr(pExecuteAction->relatedBundle.sczIgnoreDependencies);
        ReleaseStr(pExecuteAction->relatedBundle.sczAncestors);
        ReleaseStr(pExecuteAction->relatedBundle.sczEngineWorkingDirectory);
        break;

    case BURN_EXECUTE_ACTION_TYPE_BUNDLE_PACKAGE:
        ReleaseStr(pExecuteAction->bundlePackage.sczParent);
        ReleaseStr(pExecuteAction->bundlePackage.sczIgnoreDependencies);
        ReleaseStr(pExecuteAction->bundlePackage.sczAncestors);
        ReleaseStr(pExecuteAction->bundlePackage.sczEngineWorkingDirectory);
        break;

    case BURN_EXECUTE_ACTION_TYPE_EXE_PACKAGE:
        ReleaseStr(pExecuteAction->exePackage.sczAncestors);
        ReleaseStr(pExecuteAction->exePackage.sczEngineWorkingDirectory);
        break;

    case BURN_EXECUTE_ACTION_TYPE_MSI_PACKAGE:
        ReleaseStr(pExecuteAction->msiPackage.sczLogPath);
        ReleaseMem(pExecuteAction->msiPackage.rgFeatures);
        break;

    case BURN_EXECUTE_ACTION_TYPE_MSP_TARGET:
        ReleaseStr(pExecuteAction->mspTarget.sczTargetProductCode);
        ReleaseStr(pExecuteAction->mspTarget.sczLogPath);
        ReleaseMem(pExecuteAction->mspTarget.rgOrderedPatches);
        break;

    case BURN_EXECUTE_ACTION_TYPE_MSU_PACKAGE:
        ReleaseStr(pExecuteAction->msuPackage.sczLogPath);
        break;

    case BURN_EXECUTE_ACTION_TYPE_PACKAGE_DEPENDENCY:
        ReleaseStr(pExecuteAction->packageDependency.sczBundleProviderKey);
        break;

    case BURN_EXECUTE_ACTION_TYPE_UNINSTALL_MSI_COMPATIBLE_PACKAGE:
        ReleaseStr(pExecuteAction->uninstallMsiCompatiblePackage.sczLogPath);
        break;
    }
}

extern "C" HRESULT PlanSetVariables(
    __in BOOTSTRAPPER_ACTION action,
    __in BURN_VARIABLES* pVariables
    )
{
    HRESULT hr = S_OK;

    hr = VariableSetNumeric(pVariables, BURN_BUNDLE_ACTION, action, TRUE);
    ExitOnFailure(hr, "Failed to set the bundle action built-in variable.");

LExit:
    return hr;
}

extern "C" HRESULT PlanDefaultPackageRequestState(
    __in BURN_PACKAGE_TYPE packageType,
    __in BOOTSTRAPPER_PACKAGE_STATE currentState,
    __in BOOTSTRAPPER_ACTION action,
    __in BOOTSTRAPPER_PACKAGE_CONDITION_RESULT installCondition,
    __in BOOTSTRAPPER_PACKAGE_CONDITION_RESULT repairCondition,
    __in BOOTSTRAPPER_RELATION_TYPE relationType,
    __out BOOTSTRAPPER_REQUEST_STATE* pRequestState
    )
{
    HRESULT hr = S_OK;
    BOOTSTRAPPER_REQUEST_STATE defaultRequestState = BOOTSTRAPPER_REQUEST_STATE_NONE;

    // If doing layout, then always default to requesting the package be cached.
    if (BOOTSTRAPPER_ACTION_LAYOUT == action)
    {
        *pRequestState = BOOTSTRAPPER_REQUEST_STATE_CACHE;
    }
    else if (BOOTSTRAPPER_ACTION_CACHE == action)
    {
        switch (currentState)
        {
        case BOOTSTRAPPER_PACKAGE_STATE_PRESENT: __fallthrough;
        case BOOTSTRAPPER_PACKAGE_STATE_SUPERSEDED:
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_PRESENT;
            break;

        default:
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_CACHE;
            break;
        }
    }
    else if (BOOTSTRAPPER_RELATION_PATCH == relationType && BURN_PACKAGE_TYPE_MSP == packageType)
    {
        // For patch related bundles, only install a patch if currently absent during install, modify, or repair.
        if (BOOTSTRAPPER_PACKAGE_STATE_ABSENT != currentState)
        {
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_NONE;
        }
        else if (BOOTSTRAPPER_ACTION_INSTALL == action ||
                 BOOTSTRAPPER_ACTION_MODIFY == action ||
                 BOOTSTRAPPER_ACTION_REPAIR == action)
        {
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_PRESENT;
        }
    }
    else // pick the best option for the action state and install condition.
    {
        hr = GetActionDefaultRequestState(action, currentState, &defaultRequestState);
        ExitOnFailure(hr, "Failed to get default request state for action.");

        if (BOOTSTRAPPER_ACTION_UNINSTALL != action && BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL != action)
        {
            // If we're not doing an uninstall, use the install condition
            // to determine whether to use the default request state or make the package absent.
            if (BOOTSTRAPPER_PACKAGE_CONDITION_FALSE == installCondition)
            {
                defaultRequestState = BOOTSTRAPPER_REQUEST_STATE_ABSENT;
            }
            // Obsolete means the package is not on the machine and should not be installed,
            // *except* patches can be obsolete and present.
            // Superseded means the package is on the machine but not active, so only uninstall operations are allowed.
            // All other operations do nothing.
            else if (BOOTSTRAPPER_PACKAGE_STATE_OBSOLETE == currentState || BOOTSTRAPPER_PACKAGE_STATE_SUPERSEDED == currentState)
            {
                defaultRequestState = BOOTSTRAPPER_REQUEST_STATE_PRESENT <= defaultRequestState ? BOOTSTRAPPER_REQUEST_STATE_NONE : defaultRequestState;
            }
            else if (BOOTSTRAPPER_ACTION_REPAIR == action && BOOTSTRAPPER_PACKAGE_CONDITION_FALSE == repairCondition)
            {
                defaultRequestState = BOOTSTRAPPER_REQUEST_STATE_PRESENT;
            }
        }

        *pRequestState = defaultRequestState;
    }

LExit:
    return hr;
}

extern "C" HRESULT PlanLayoutBundle(
    __in BURN_PLAN* pPlan,
    __in_z LPCWSTR wzExecutableName,
    __in DWORD64 qwBundleSize,
    __in BURN_VARIABLES* pVariables,
    __in BURN_PAYLOAD_GROUP* pLayoutPayloads
    )
{
    HRESULT hr = S_OK;
    BURN_CACHE_ACTION* pCacheAction = NULL;
    LPWSTR sczLayoutDirectory = NULL;
    LPWSTR sczExecutablePath = NULL;

    // Get the layout directory.
    hr = VariableGetString(pVariables, BURN_BUNDLE_LAYOUT_DIRECTORY, &sczLayoutDirectory);
    if (E_NOTFOUND == hr) // if not set, use the current directory as the layout directory.
    {
        hr = VariableGetString(pVariables, BURN_BUNDLE_SOURCE_PROCESS_FOLDER, &sczLayoutDirectory);
        if (E_NOTFOUND == hr) // if not set, use the current directory as the layout directory.
        {
            hr = PathForCurrentProcess(&sczExecutablePath, NULL);
            ExitOnFailure(hr, "Failed to get path for current executing process as layout directory.");

            hr = PathGetDirectory(sczExecutablePath, &sczLayoutDirectory);
            ExitOnFailure(hr, "Failed to get executing process as layout directory.");
        }
    }
    ExitOnFailure(hr, "Failed to get bundle layout directory property.");

    hr = PathGetFullPathName(sczLayoutDirectory, &pPlan->sczLayoutDirectory, NULL, NULL);
    ExitOnFailure(hr, "Failed to ensure layout directory is fully qualified.");

    hr = PathBackslashTerminate(&pPlan->sczLayoutDirectory);
    ExitOnFailure(hr, "Failed to ensure layout directory is backslash terminated.");

    hr = ProcessPayloadGroup(pPlan, pLayoutPayloads);
    ExitOnFailure(hr, "Failed to process payload group for bundle.");

    // Plan the layout of the bundle engine itself.
    hr = AppendCacheAction(pPlan, &pCacheAction);
    ExitOnFailure(hr, "Failed to append bundle start action.");

    pCacheAction->type = BURN_CACHE_ACTION_TYPE_LAYOUT_BUNDLE;

    hr = StrAllocString(&pCacheAction->bundleLayout.sczExecutableName, wzExecutableName, 0);
    ExitOnFailure(hr, "Failed to to copy executable name for bundle.");

    hr = CacheCalculateBundleLayoutWorkingPath(pPlan->pCache, pPlan->wzBundleId, &pCacheAction->bundleLayout.sczUnverifiedPath);
    ExitOnFailure(hr, "Failed to calculate bundle layout working path.");

    pCacheAction->bundleLayout.qwBundleSize = qwBundleSize;
    pCacheAction->bundleLayout.pPayloadGroup = pLayoutPayloads;

    // Acquire + Verify + Finalize
    pPlan->qwCacheSizeTotal += 3 * qwBundleSize;

    ++pPlan->cOverallProgressTicksTotal;

LExit:
    ReleaseStr(sczExecutablePath);
    ReleaseStr(sczLayoutDirectory);

    return hr;
}

extern "C" HRESULT PlanForwardCompatibleBundles(
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_PLAN* pPlan,
    __in BURN_REGISTRATION* pRegistration
    )
{
    HRESULT hr = S_OK;
    BOOL fRecommendIgnore = TRUE;
    BOOL fIgnoreBundle = FALSE;
    BOOTSTRAPPER_ACTION action = pPlan->action;

    if (!pRegistration->fForwardCompatibleBundleExists)
    {
        ExitFunction();
    }

    // Only change the recommendation if an active parent was provided.
    if (pPlan->pInternalCommand->sczActiveParent && *pPlan->pInternalCommand->sczActiveParent)
    {
        // On install, recommend running the forward compatible bundle because there is an active parent. This
        // will essentially register the parent with the forward compatible bundle.
        if (BOOTSTRAPPER_ACTION_INSTALL == action)
        {
            fRecommendIgnore = FALSE;
        }
        else if (BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL == action ||
                 BOOTSTRAPPER_ACTION_UNINSTALL == action ||
                    BOOTSTRAPPER_ACTION_MODIFY == action ||
                    BOOTSTRAPPER_ACTION_REPAIR == action)
        {
            // When modifying the bundle, only recommend running the forward compatible bundle if the parent
            // is already registered as a dependent of the provider key.
            if (pRegistration->fParentRegisteredAsDependent)
            {
                fRecommendIgnore = FALSE;
            }
        }
    }

    for (DWORD iRelatedBundle = 0; iRelatedBundle < pRegistration->relatedBundles.cRelatedBundles; ++iRelatedBundle)
    {
        BURN_RELATED_BUNDLE* pRelatedBundle = pRegistration->relatedBundles.rgRelatedBundles + iRelatedBundle;
        if (!pRelatedBundle->fForwardCompatible)
        {
            continue;
        }

        fIgnoreBundle = fRecommendIgnore;

        hr = UserExperienceOnPlanForwardCompatibleBundle(pUX, pRelatedBundle->package.sczId, pRelatedBundle->detectRelationType, pRelatedBundle->sczTag, pRelatedBundle->package.fPerMachine, pRelatedBundle->pVersion, &fIgnoreBundle);
        ExitOnRootFailure(hr, "BA aborted plan forward compatible bundle.");

        if (!fIgnoreBundle)
        {
            hr = PseudoBundleInitializePassthrough(&pPlan->forwardCompatibleBundle, pPlan->pInternalCommand, pPlan->pCommand, &pRelatedBundle->package);
            ExitOnFailure(hr, "Failed to initialize pass through bundle.");

            pPlan->fEnabledForwardCompatibleBundle = TRUE;
            break;
        }
    }

LExit:
    return hr;
}

extern "C" HRESULT PlanPackages(
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_PACKAGES* pPackages,
    __in BURN_PLAN* pPlan,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables
    )
{
    HRESULT hr = S_OK;
    
    hr = PlanPackagesHelper(pPackages->rgPackages, pPackages->cPackages, pUX, pPlan, pLog, pVariables);

    return hr;
}

extern "C" HRESULT PlanRegistration(
    __in BURN_PLAN* pPlan,
    __in BURN_REGISTRATION* pRegistration,
    __in BURN_DEPENDENCIES* pDependencies,
    __in BOOTSTRAPPER_RESUME_TYPE /*resumeType*/,
    __in BOOTSTRAPPER_RELATION_TYPE relationType,
    __inout BOOL* pfContinuePlanning
    )
{
    HRESULT hr = S_OK;
    STRINGDICT_HANDLE sdBundleDependents = NULL;
    STRINGDICT_HANDLE sdIgnoreDependents = NULL;
    BOOL fDependentBlocksUninstall = FALSE;

    pPlan->fCanAffectMachineState = TRUE; // register the bundle since we're modifying machine state.
    pPlan->fDisallowRemoval = FALSE; // by default the bundle can be planned to be removed

    // Ensure the bundle is cached if not running from the cache.
    if (!CacheBundleRunningFromCache(pPlan->pCache))
    {
        pPlan->dwRegistrationOperations |= BURN_REGISTRATION_ACTION_OPERATIONS_CACHE_BUNDLE;
    }

    if (pPlan->pInternalCommand->fArpSystemComponent)
    {
        pPlan->dwRegistrationOperations |= BURN_REGISTRATION_ACTION_OPERATIONS_ARP_SYSTEM_COMPONENT;
    }

    if (BOOTSTRAPPER_ACTION_UNINSTALL == pPlan->action || BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL == pPlan->action)
    {
        // If our provider key was not owned by a different bundle,
        // then plan to write our provider key registration to "fix it" if broken
        // in case the bundle isn't successfully uninstalled.
        if (!pRegistration->fDetectedForeignProviderKeyBundleId)
        {
            pPlan->dwRegistrationOperations |= BURN_REGISTRATION_ACTION_OPERATIONS_WRITE_PROVIDER_KEY;
        }

        // Create the dictionary of dependents that should be ignored.
        hr = DictCreateStringList(&sdIgnoreDependents, 5, DICT_FLAG_CASEINSENSITIVE);
        ExitOnFailure(hr, "Failed to create the string dictionary.");

        // If the self-dependent dependent exists, plan its removal. If we did not do this, we
        // would prevent self-removal.
        if (pRegistration->fSelfRegisteredAsDependent)
        {
            hr = AddRegistrationAction(pPlan, BURN_DEPENDENT_REGISTRATION_ACTION_TYPE_UNREGISTER, pDependencies->wzSelfDependent, pRegistration->sczId);
            ExitOnFailure(hr, "Failed to allocate registration action.");

            hr = DependencyAddIgnoreDependencies(sdIgnoreDependents, pDependencies->wzSelfDependent);
            ExitOnFailure(hr, "Failed to add self-dependent to ignore dependents.");
        }

        if (!pDependencies->fIgnoreAllDependents)
        {
            // If we are not doing an upgrade, we check to see if there are still dependents on us and if so we skip planning.
            // However, when being upgraded, we always execute our uninstall because a newer version of us is probably
            // already on the machine and we need to clean up the stuff specific to this bundle.
            if (BOOTSTRAPPER_RELATION_UPGRADE != relationType)
            {
                // If there were other dependencies to ignore, add them.
                for (DWORD iDependency = 0; iDependency < pDependencies->cIgnoredDependencies; ++iDependency)
                {
                    DEPENDENCY* pDependency = pDependencies->rgIgnoredDependencies + iDependency;

                    hr = DictKeyExists(sdIgnoreDependents, pDependency->sczKey);
                    if (E_NOTFOUND != hr)
                    {
                        ExitOnFailure(hr, "Failed to check the dictionary of ignored dependents.");
                    }
                    else
                    {
                        hr = DictAddKey(sdIgnoreDependents, pDependency->sczKey);
                        ExitOnFailure(hr, "Failed to add dependent key to ignored dependents.");
                    }
                }

                // For addon or patch bundles, dependent related bundles should be ignored. This allows
                // that addon or patch to be removed even though bundles it targets still are registered.
                for (DWORD i = 0; i < pRegistration->relatedBundles.cRelatedBundles; ++i)
                {
                    const BURN_RELATED_BUNDLE* pRelatedBundle = pRegistration->relatedBundles.rgRelatedBundles + i;

                    if (BOOTSTRAPPER_RELATION_DEPENDENT_ADDON == pRelatedBundle->planRelationType ||
                        BOOTSTRAPPER_RELATION_DEPENDENT_PATCH == pRelatedBundle->planRelationType)
                    {
                        for (DWORD j = 0; j < pRelatedBundle->package.cDependencyProviders; ++j)
                        {
                            const BURN_DEPENDENCY_PROVIDER* pProvider = pRelatedBundle->package.rgDependencyProviders + j;

                            hr = DependencyAddIgnoreDependencies(sdIgnoreDependents, pProvider->sczKey);
                            ExitOnFailure(hr, "Failed to add dependent bundle provider key to ignore dependents.");
                        }
                    }
                }

                // If there are any (non-ignored and not-planned-to-be-removed) dependents left, skip planning.
                for (DWORD iDependent = 0; iDependent < pRegistration->cDependents; ++iDependent)
                {
                    DEPENDENCY* pDependent = pRegistration->rgDependents + iDependent;

                    hr = DictKeyExists(sdIgnoreDependents, pDependent->sczKey);
                    if (E_NOTFOUND == hr)
                    {
                        hr = S_OK;

                        // TODO: callback to the BA and let it have the option to ignore this dependent?
                        if (!fDependentBlocksUninstall)
                        {
                            fDependentBlocksUninstall = TRUE;

                            LogId(REPORT_STANDARD, MSG_PLAN_SKIPPED_DUE_TO_DEPENDENTS);
                        }

                        LogId(REPORT_VERBOSE, MSG_DEPENDENCY_BUNDLE_DEPENDENT, pDependent->sczKey, LoggingStringOrUnknownIfNull(pDependent->sczName));
                    }
                    ExitOnFailure(hr, "Failed to check for remaining dependents during planning.");
                }

                if (fDependentBlocksUninstall)
                {
                    if (BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL == pPlan->action)
                    {
                        fDependentBlocksUninstall = FALSE;
                        LogId(REPORT_STANDARD, MSG_PLAN_NOT_SKIPPED_DUE_TO_DEPENDENTS);
                    }
                    else
                    {
                        pPlan->fDisallowRemoval = TRUE; // ensure the registration stays
                        *pfContinuePlanning = FALSE; // skip the rest of planning.
                    }
                }
            }
        }
    }
    else
    {
        BOOL fAddonOrPatchBundle = (pRegistration->cAddonCodes || pRegistration->cPatchCodes);

        // Always plan to write our provider key registration when installing/modify/repair to "fix it"
        // if broken.
        pPlan->dwRegistrationOperations |= BURN_REGISTRATION_ACTION_OPERATIONS_WRITE_PROVIDER_KEY;

        // Create the dictionary of bundle dependents.
        hr = DictCreateStringList(&sdBundleDependents, 5, DICT_FLAG_CASEINSENSITIVE);
        ExitOnFailure(hr, "Failed to create the string dictionary.");

        for (DWORD iDependent = 0; iDependent < pRegistration->cDependents; ++iDependent)
        {
            DEPENDENCY* pDependent = pRegistration->rgDependents + iDependent;

            hr = DictKeyExists(sdBundleDependents, pDependent->sczKey);
            if (E_NOTFOUND == hr)
            {
                hr = DictAddKey(sdBundleDependents, pDependent->sczKey);
                ExitOnFailure(hr, "Failed to add dependent key to bundle dependents.");
            }
            ExitOnFailure(hr, "Failed to check the dictionary of bundle dependents.");
        }

        // Register each dependent related bundle. The ensures that addons and patches are reference
        // counted and stick around until the last targeted bundle is removed.
        for (DWORD i = 0; i < pRegistration->relatedBundles.cRelatedBundles; ++i)
        {
            const BURN_RELATED_BUNDLE* pRelatedBundle = pRegistration->relatedBundles.rgRelatedBundles + i;

            if (BOOTSTRAPPER_RELATION_DEPENDENT_ADDON == pRelatedBundle->planRelationType ||
                BOOTSTRAPPER_RELATION_DEPENDENT_PATCH == pRelatedBundle->planRelationType)
            {
                for (DWORD j = 0; j < pRelatedBundle->package.cDependencyProviders; ++j)
                {
                    const BURN_DEPENDENCY_PROVIDER* pProvider = pRelatedBundle->package.rgDependencyProviders + j;

                    hr = DictKeyExists(sdBundleDependents, pProvider->sczKey);
                    if (E_NOTFOUND == hr)
                    {
                        hr = DictAddKey(sdBundleDependents, pProvider->sczKey);
                        ExitOnFailure(hr, "Failed to add new dependent key to bundle dependents.");

                        hr = AddRegistrationAction(pPlan, BURN_DEPENDENT_REGISTRATION_ACTION_TYPE_REGISTER, pProvider->sczKey, pRelatedBundle->package.sczId);
                        ExitOnFailure(hr, "Failed to add registration action for dependent related bundle.");
                    }
                    ExitOnFailure(hr, "Failed to check the dictionary of bundle dependents.");
                }
            }
        }

        // Only do the following if we decided there was a dependent self to register. If so and and an explicit parent was
        // provided, register dependent self. Otherwise, if this bundle is not an addon or patch bundle then self-regisiter
        // as our own dependent.
        if (pDependencies->wzSelfDependent && !pRegistration->fSelfRegisteredAsDependent && (pDependencies->wzActiveParent || !fAddonOrPatchBundle))
        {
            hr = AddRegistrationAction(pPlan, BURN_DEPENDENT_REGISTRATION_ACTION_TYPE_REGISTER, pDependencies->wzSelfDependent, pRegistration->sczId);
            ExitOnFailure(hr, "Failed to add registration action for self dependent.");
        }
    }

LExit:
    ReleaseDict(sdBundleDependents);
    ReleaseDict(sdIgnoreDependents);

    return hr;
}

extern "C" HRESULT PlanPassThroughBundle(
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_PACKAGE* pPackage,
    __in BURN_PLAN* pPlan,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables
    )
{
    HRESULT hr = S_OK;

    // Plan passthrough package.
    hr = PlanPackagesHelper(pPackage, 1, pUX, pPlan, pLog, pVariables);
    ExitOnFailure(hr, "Failed to process passthrough package.");

LExit:
    return hr;
}

extern "C" HRESULT PlanUpdateBundle(
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_PACKAGE* pPackage,
    __in BURN_PLAN* pPlan,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables
    )
{
    HRESULT hr = S_OK;

    Assert(!pPackage->fPerMachine);
    Assert(BURN_PACKAGE_TYPE_EXE == pPackage->type);
    pPackage->Exe.fFireAndForget = BOOTSTRAPPER_ACTION_UPDATE_REPLACE == pPlan->action;

    // Plan update package.
    hr = PlanPackagesHelper(pPackage, 1, pUX, pPlan, pLog, pVariables);
    ExitOnFailure(hr, "Failed to process update package.");

LExit:
    return hr;
}

static HRESULT PlanPackagesHelper(
    __in BURN_PACKAGE* rgPackages,
    __in DWORD cPackages,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_PLAN* pPlan,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables
    )
{
    HRESULT hr = S_OK;
    BOOL fBundlePerMachine = pPlan->fPerMachine; // bundle is per-machine if plan starts per-machine.
    BURN_ROLLBACK_BOUNDARY* pRollbackBoundary = NULL;
    BOOL fReverseOrder = BOOTSTRAPPER_ACTION_UNINSTALL == pPlan->action || BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL == pPlan->action;

    // Initialize the packages.
    for (DWORD i = 0; i < cPackages; ++i)
    {
        DWORD iPackage = fReverseOrder ? cPackages - 1 - i : i;
        BURN_PACKAGE* pPackage = rgPackages + iPackage;

        hr = InitializePackage(pPlan, pUX, pVariables, pPackage);
        ExitOnFailure(hr, "Failed to initialize package.");
    }

    // Initialize the patch targets after all packages, since they could rely on the requested state of packages that are after the patch's package in the chain.
    for (DWORD i = 0; i < cPackages; ++i)
    {
        DWORD iPackage = fReverseOrder ? cPackages - 1 - i : i;
        BURN_PACKAGE* pPackage = rgPackages + iPackage;

        if (BURN_PACKAGE_TYPE_MSP == pPackage->type)
        {
            hr = MspEnginePlanInitializePackage(pPackage, pUX);
            ExitOnFailure(hr, "Failed to initialize plan package: %ls", pPackage->sczId);
        }
    }

    // Plan the packages.
    for (DWORD i = 0; i < cPackages; ++i)
    {
        DWORD iPackage = fReverseOrder ? cPackages - 1 - i : i;
        BURN_PACKAGE* pPackage = rgPackages + iPackage;

        hr = ProcessPackage(fBundlePerMachine, pUX, pPlan, pPackage, pLog, pVariables, &pRollbackBoundary);
        ExitOnFailure(hr, "Failed to process package.");
    }

    // If we still have an open rollback boundary, complete it.
    if (pRollbackBoundary)
    {
        hr = PlanRollbackBoundaryComplete(pPlan);
        ExitOnFailure(hr, "Failed to plan final rollback boundary complete.");

        pRollbackBoundary = NULL;
    }

    // Passthrough packages are never cleaned up by the calling bundle (they delete themselves when appropriate).
    if (!pPlan->fEnabledForwardCompatibleBundle && BOOTSTRAPPER_ACTION_LAYOUT != pPlan->action)
    {
        // Plan clean up of packages.
        for (DWORD i = 0; i < cPackages; ++i)
        {
            DWORD iPackage = fReverseOrder ? cPackages - 1 - i : i;
            BURN_PACKAGE* pPackage = rgPackages + iPackage;

            hr = PlanCleanPackage(pPlan, pPackage);
            ExitOnFailure(hr, "Failed to plan clean package.");
        }
    }

    // Remove unnecessary actions.
    hr = PlanFinalizeActions(pPlan);
    ExitOnFailure(hr, "Failed to remove unnecessary actions from plan.");

    CalculateExpectedRegistrationStates(rgPackages, cPackages);

    // Let the BA know the actions that were planned.
    for (DWORD i = 0; i < cPackages; ++i)
    {
        DWORD iPackage = fReverseOrder ? cPackages - 1 - i : i;
        BURN_PACKAGE* pPackage = rgPackages + iPackage;

        UserExperienceOnPlannedPackage(pUX, pPackage->sczId, pPackage->execute, pPackage->rollback, NULL != pPackage->hCacheEvent, pPackage->fPlannedUncache);

        if (pPackage->compatiblePackage.fPlannable)
        {
            UserExperienceOnPlannedCompatiblePackage(pUX, pPackage->sczId, pPackage->compatiblePackage.compatibleEntry.sczId, pPackage->compatiblePackage.fRemove);
        }
    }

LExit:
    return hr;
}

static HRESULT InitializePackage(
    __in BURN_PLAN* pPlan,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_VARIABLES* pVariables,
    __in BURN_PACKAGE* pPackage
    )
{
    HRESULT hr = S_OK;
    BOOTSTRAPPER_PACKAGE_CONDITION_RESULT installCondition = BOOTSTRAPPER_PACKAGE_CONDITION_DEFAULT;
    BOOTSTRAPPER_PACKAGE_CONDITION_RESULT repairCondition = BOOTSTRAPPER_PACKAGE_CONDITION_DEFAULT;
    BOOL fEvaluatedCondition = FALSE;
    BOOL fBeginCalled = FALSE;
    BOOTSTRAPPER_RELATION_TYPE relationType = pPlan->pCommand->relationType;

    if (BURN_PACKAGE_TYPE_EXE == pPackage->type && pPackage->Exe.fPseudoPackage)
    {
        // Exe pseudo packages are not configurable.
        // The BA already requested this package to be executed
        // * by the overall plan action for UpdateReplace
        // * by enabling the forward compatible bundle for Passthrough
        pPackage->defaultRequested = pPackage->requested = BOOTSTRAPPER_REQUEST_STATE_FORCE_PRESENT;
        ExitFunction();
    }

    if (pPackage->fCanAffectRegistration)
    {
        pPackage->expectedCacheRegistrationState = pPackage->cacheRegistrationState;
        pPackage->expectedInstallRegistrationState = pPackage->installRegistrationState;
    }

    if (pPackage->sczInstallCondition && *pPackage->sczInstallCondition)
    {
        hr = ConditionEvaluate(pVariables, pPackage->sczInstallCondition, &fEvaluatedCondition);
        ExitOnFailure(hr, "Failed to evaluate install condition.");

        installCondition = fEvaluatedCondition ? BOOTSTRAPPER_PACKAGE_CONDITION_TRUE : BOOTSTRAPPER_PACKAGE_CONDITION_FALSE;
    }

    if (pPackage->sczRepairCondition && *pPackage->sczRepairCondition)
    {
        hr = ConditionEvaluate(pVariables, pPackage->sczRepairCondition, &fEvaluatedCondition);
        ExitOnFailure(hr, "Failed to evaluate repair condition.");

        repairCondition = fEvaluatedCondition ? BOOTSTRAPPER_PACKAGE_CONDITION_TRUE : BOOTSTRAPPER_PACKAGE_CONDITION_FALSE;
    }

    // Remember the default requested state so the engine doesn't get blamed for planning the wrong thing if the BA changes it.
    hr = PlanDefaultPackageRequestState(pPackage->type, pPackage->currentState, pPlan->action, installCondition, repairCondition, relationType, &pPackage->defaultRequested);
    ExitOnFailure(hr, "Failed to set default package state.");

    pPackage->requested = pPackage->defaultRequested;
    fBeginCalled = TRUE;

    hr = UserExperienceOnPlanPackageBegin(pUX, pPackage->sczId, pPackage->currentState, pPackage->fCached, installCondition, repairCondition, &pPackage->requested, &pPackage->cacheType);
    ExitOnRootFailure(hr, "BA aborted plan package begin.");

    if (BURN_PACKAGE_TYPE_MSI == pPackage->type)
    {
        hr = MsiEnginePlanInitializePackage(pPackage, pPlan->action, pVariables, pUX);
        ExitOnFailure(hr, "Failed to initialize plan package: %ls", pPackage->sczId);
    }

LExit:
    if (fBeginCalled)
    {
        UserExperienceOnPlanPackageComplete(pUX, pPackage->sczId, hr, pPackage->requested);
    }

    return hr;
}

static HRESULT ProcessPackage(
    __in BOOL fBundlePerMachine,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables,
    __inout BURN_ROLLBACK_BOUNDARY** ppRollbackBoundary
    )
{
    HRESULT hr = S_OK;
    BURN_ROLLBACK_BOUNDARY* pEffectiveRollbackBoundary = NULL;
    BOOL fBackward = BOOTSTRAPPER_ACTION_UNINSTALL == pPlan->action || BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL == pPlan->action;

    pEffectiveRollbackBoundary = fBackward ? pPackage->pRollbackBoundaryBackward : pPackage->pRollbackBoundaryForward;
    hr = ProcessPackageRollbackBoundary(pPlan, pUX, pLog, pVariables, pEffectiveRollbackBoundary, ppRollbackBoundary);
    ExitOnFailure(hr, "Failed to process package rollback boundary.");

    if (BOOTSTRAPPER_ACTION_LAYOUT == pPlan->action)
    {
        if (BOOTSTRAPPER_REQUEST_STATE_NONE != pPackage->requested)
        {
            hr = PlanLayoutPackage(pPlan, pPackage, TRUE);
            ExitOnFailure(hr, "Failed to plan layout package.");
        }
    }
    else
    {
        if (BOOTSTRAPPER_REQUEST_STATE_NONE != pPackage->requested || pPackage->compatiblePackage.fRequested)
        {
            // If the package is in a requested state, plan it.
            hr = PlanExecutePackage(fBundlePerMachine, pUX, pPlan, pPackage, pLog, pVariables);
            ExitOnFailure(hr, "Failed to plan execute package.");
        }
        else
        {
            if (ForceCache(pPlan, pPackage))
            {
                hr = AddCachePackage(pPlan, pPackage, TRUE);
                ExitOnFailure(hr, "Failed to plan cache package.");

                if (pPackage->fPerMachine)
                {
                    pPlan->fPerMachine = TRUE;
                }
            }

            // Make sure the package is properly ref-counted even if no plan is requested.
            hr = PlanDependencyActions(fBundlePerMachine, pPlan, pPackage);
            ExitOnFailure(hr, "Failed to plan dependency actions for package: %ls", pPackage->sczId);
        }
    }

    // Add the checkpoint after each package and dependency registration action.
    if (BOOTSTRAPPER_ACTION_STATE_NONE != pPackage->execute || BOOTSTRAPPER_ACTION_STATE_NONE != pPackage->rollback || BURN_DEPENDENCY_ACTION_NONE != pPackage->dependencyExecute)
    {
        hr = PlanExecuteCheckpoint(pPlan);
        ExitOnFailure(hr, "Failed to append execute checkpoint.");
    }

LExit:
    return hr;
}

static HRESULT ProcessPackageRollbackBoundary(
    __in BURN_PLAN* pPlan,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables,
    __in_opt BURN_ROLLBACK_BOUNDARY* pEffectiveRollbackBoundary,
    __inout BURN_ROLLBACK_BOUNDARY** ppRollbackBoundary
    )
{
    HRESULT hr = S_OK;

    // If the package marks the start of a rollback boundary, start a new one.
    if (pEffectiveRollbackBoundary)
    {
        // Complete previous rollback boundary.
        if (*ppRollbackBoundary)
        {
            hr = PlanRollbackBoundaryComplete(pPlan);
            ExitOnFailure(hr, "Failed to plan rollback boundary complete.");
        }

        // Start new rollback boundary.
        hr = PlanRollbackBoundaryBegin(pPlan, pUX, pLog, pVariables, pEffectiveRollbackBoundary);
        ExitOnFailure(hr, "Failed to plan rollback boundary begin.");

        *ppRollbackBoundary = pEffectiveRollbackBoundary;
    }

LExit:
    return hr;
}

extern "C" HRESULT PlanLayoutContainer(
    __in BURN_PLAN* pPlan,
    __in BURN_CONTAINER* pContainer
    )
{
    HRESULT hr = S_OK;
    BURN_CACHE_ACTION* pCacheAction = NULL;

    Assert(!pContainer->fPlanned);
    pContainer->fPlanned = TRUE;

    if (pPlan->sczLayoutDirectory)
    {
        if (!pContainer->fAttached)
        {
            hr = AppendCacheAction(pPlan, &pCacheAction);
            ExitOnFailure(hr, "Failed to append package start action.");

            pCacheAction->type = BURN_CACHE_ACTION_TYPE_CONTAINER;
            pCacheAction->container.pContainer = pContainer;

            // Acquire + Verify + Finalize
            pPlan->qwCacheSizeTotal += 3 * pContainer->qwFileSize;
        }
    }
    else
    {
        if (!pContainer->fActuallyAttached)
        {
            // Acquire
            pPlan->qwCacheSizeTotal += pContainer->qwFileSize;
        }
    }

    if (!pContainer->sczUnverifiedPath)
    {
        if (pContainer->fActuallyAttached)
        {
            hr = PathForCurrentProcess(&pContainer->sczUnverifiedPath, NULL);
            ExitOnFailure(hr, "Failed to get path for executing module as attached container working path.");
        }
        else
        {
            hr = CacheCalculateContainerWorkingPath(pPlan->pCache, pContainer, &pContainer->sczUnverifiedPath);
            ExitOnFailure(hr, "Failed to calculate unverified path for container.");
        }
    }

LExit:
    return hr;
}

extern "C" HRESULT PlanLayoutPackage(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage,
    __in BOOL fVital
    )
{
    HRESULT hr = S_OK;
    BURN_CACHE_ACTION* pCacheAction = NULL;

    AssertSz(!pPlan->fEnabledForwardCompatibleBundle, "Passthrough packages must already be cached");

    hr = ProcessPayloadGroup(pPlan, &pPackage->payloads);
    ExitOnFailure(hr, "Failed to process payload group for package: %ls.", pPackage->sczId);

    hr = AppendCacheAction(pPlan, &pCacheAction);
    ExitOnFailure(hr, "Failed to append package start action.");

    pCacheAction->type = BURN_CACHE_ACTION_TYPE_PACKAGE;
    pCacheAction->package.pPackage = pPackage;
    pPackage->fCacheVital = fVital;

    ++pPlan->cOverallProgressTicksTotal;

LExit:
    return hr;
}

extern "C" HRESULT PlanExecutePackage(
    __in BOOL fPerMachine,
    __in BURN_USER_EXPERIENCE* pUserExperience,
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables
    )
{
    HRESULT hr = S_OK;
    BOOTSTRAPPER_DISPLAY display = pPlan->pCommand->display;
    BOOL fRequestedCache = BOOTSTRAPPER_CACHE_TYPE_REMOVE < pPackage->cacheType && (BOOTSTRAPPER_REQUEST_STATE_CACHE == pPackage->requested || ForceCache(pPlan, pPackage));

    hr = CalculateExecuteActions(pPackage, pPlan->pActiveRollbackBoundary);
    ExitOnFailure(hr, "Failed to calculate plan actions for package: %ls", pPackage->sczId);

    // Calculate package states based on reference count and plan certain dependency actions prior to planning the package execute action.
    hr = DependencyPlanPackageBegin(fPerMachine, pPackage, pPlan);
    ExitOnFailure(hr, "Failed to begin plan dependency actions for package: %ls", pPackage->sczId);

    pPackage->executeCacheType = fRequestedCache ? BURN_CACHE_PACKAGE_TYPE_REQUIRED : GetCachePackageType(pPackage, TRUE);
    pPackage->rollbackCacheType = GetCachePackageType(pPackage, FALSE);

    if (BURN_CACHE_PACKAGE_TYPE_NONE != pPackage->executeCacheType || BURN_CACHE_PACKAGE_TYPE_NONE != pPackage->rollbackCacheType)
    {
        hr = AddCachePackage(pPlan, pPackage, BURN_CACHE_PACKAGE_TYPE_REQUIRED == pPackage->executeCacheType);
        ExitOnFailure(hr, "Failed to plan cache package.");
    }

    // Add execute actions.
    switch (pPackage->type)
    {
    case BURN_PACKAGE_TYPE_BUNDLE:
        hr = BundlePackageEnginePlanAddPackage(pPackage, pPlan, pLog, pVariables);
        break;

    case BURN_PACKAGE_TYPE_EXE:
        hr = ExeEnginePlanAddPackage(pPackage, pPlan, pLog, pVariables);
        break;

    case BURN_PACKAGE_TYPE_MSI:
        hr = MsiEnginePlanAddPackage(display, pUserExperience, pPackage, pPlan, pLog, pVariables);
        break;

    case BURN_PACKAGE_TYPE_MSP:
        hr = MspEnginePlanAddPackage(display, pUserExperience, pPackage, pPlan, pLog, pVariables);
        break;

    case BURN_PACKAGE_TYPE_MSU:
        hr = MsuEnginePlanAddPackage(pPackage, pPlan, pLog, pVariables);
        break;

    default:
        hr = E_UNEXPECTED;
        ExitOnFailure(hr, "Invalid package type.");
    }
    ExitOnFailure(hr, "Failed to add plan actions for package: %ls", pPackage->sczId);

    // Plan certain dependency actions after planning the package execute action.
    hr = DependencyPlanPackageComplete(pPackage, pPlan);
    ExitOnFailure(hr, "Failed to complete plan dependency actions for package: %ls", pPackage->sczId);

    // If we are going to take any action on this package, add progress for it.
    if (BOOTSTRAPPER_ACTION_STATE_NONE != pPackage->execute || BOOTSTRAPPER_ACTION_STATE_NONE != pPackage->rollback)
    {
        PlannedExecutePackage(pPlan, pPackage);
    }

    // If we are going to take any action on the compatible package, add progress for it.
    if (pPackage->compatiblePackage.fRemove)
    {
        PlannedExecutePackage(pPlan, pPackage);
    }

LExit:
    return hr;
}

extern "C" HRESULT PlanDefaultRelatedBundlePlanType(
    __in BOOTSTRAPPER_RELATION_TYPE relatedBundleRelationType,
    __in VERUTIL_VERSION* pRegistrationVersion,
    __in VERUTIL_VERSION* pRelatedBundleVersion,
    __inout BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE* pPlanRelationType
    )
{
    HRESULT hr = S_OK;
    int nCompareResult = 0;

    switch (relatedBundleRelationType)
    {
    case BOOTSTRAPPER_RELATION_UPGRADE:
        hr = VerCompareParsedVersions(pRegistrationVersion, pRelatedBundleVersion, &nCompareResult);
        ExitOnFailure(hr, "Failed to compare bundle version '%ls' to related bundle version '%ls'", pRegistrationVersion->sczVersion, pRelatedBundleVersion->sczVersion);

        if (nCompareResult < 0)
        {
            *pPlanRelationType = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_DOWNGRADE;
        }
        else
        {
            *pPlanRelationType = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_UPGRADE;
        }
        break;
    case BOOTSTRAPPER_RELATION_ADDON:
        *pPlanRelationType = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_ADDON;
        break;
    case BOOTSTRAPPER_RELATION_PATCH:
        *pPlanRelationType = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_PATCH;
        break;
    case BOOTSTRAPPER_RELATION_DEPENDENT_ADDON:
        *pPlanRelationType = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_DEPENDENT_ADDON;
        break;
    case BOOTSTRAPPER_RELATION_DEPENDENT_PATCH:
        *pPlanRelationType = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_DEPENDENT_PATCH;
        break;
    case BOOTSTRAPPER_RELATION_DETECT:
        break;
    default:
        hr = E_UNEXPECTED;
        ExitOnFailure(hr, "Unexpected relation type encountered during plan: %d", relatedBundleRelationType);
        break;
    }

LExit:
    return hr;
}

extern "C" HRESULT PlanDefaultRelatedBundleRequestState(
    __in BOOTSTRAPPER_RELATION_TYPE commandRelationType,
    __in BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE relatedBundleRelationType,
    __in BOOTSTRAPPER_ACTION action,
    __inout BOOTSTRAPPER_REQUEST_STATE* pRequestState
    )
{
    HRESULT hr = S_OK;
    BOOL fUninstalling = BOOTSTRAPPER_ACTION_UNINSTALL == action || BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL == action;

    // Never touch related bundles during Cache.
    if (BOOTSTRAPPER_ACTION_CACHE == action)
    {
        ExitFunction1(*pRequestState = BOOTSTRAPPER_REQUEST_STATE_NONE);
    }

    switch (relatedBundleRelationType)
    {
    case BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_UPGRADE:
        if (BOOTSTRAPPER_RELATION_UPGRADE != commandRelationType && !fUninstalling)
        {
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_ABSENT;
        }
        break;
    case BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_PATCH: __fallthrough;
    case BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_ADDON:
        if (fUninstalling)
        {
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_ABSENT;
        }
        else if (BOOTSTRAPPER_ACTION_INSTALL == action || BOOTSTRAPPER_ACTION_MODIFY == action)
        {
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_FORCE_PRESENT;
        }
        else if (BOOTSTRAPPER_ACTION_REPAIR == action)
        {
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_REPAIR;
        }
        break;
    case BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_DEPENDENT_ADDON: __fallthrough;
    case BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_DEPENDENT_PATCH:
        // Automatically repair dependent bundles to restore missing
        // packages after uninstall unless we're being upgraded with the
        // assumption that upgrades are cumulative (as intended).
        if (BOOTSTRAPPER_RELATION_UPGRADE != commandRelationType && fUninstalling)
        {
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_REPAIR;
        }
        break;
    case BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_DOWNGRADE: __fallthrough;
    case BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_NONE:
        break;
    default:
        hr = E_UNEXPECTED;
        ExitOnFailure(hr, "Unexpected plan relation type encountered during plan: %d", relatedBundleRelationType);
        break;
    }

LExit:
    return hr;
}

extern "C" HRESULT PlanRelatedBundlesInitialize(
    __in BURN_USER_EXPERIENCE* pUserExperience,
    __in BURN_REGISTRATION* pRegistration,
    __in BOOTSTRAPPER_RELATION_TYPE relationType,
    __in BURN_PLAN* pPlan
    )
{
    HRESULT hr = S_OK;
    BOOL fUninstalling = BOOTSTRAPPER_ACTION_UNINSTALL == pPlan->action || BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL == pPlan->action;

    for (DWORD i = 0; i < pRegistration->relatedBundles.cRelatedBundles; ++i)
    {
        BURN_RELATED_BUNDLE* pRelatedBundle = pRegistration->relatedBundles.rgRelatedBundles + i;

        pRelatedBundle->defaultRequestedRestore = BOOTSTRAPPER_REQUEST_STATE_NONE;
        pRelatedBundle->requestedRestore = BOOTSTRAPPER_REQUEST_STATE_NONE;
        pRelatedBundle->restore = BOOTSTRAPPER_ACTION_STATE_NONE;
        pRelatedBundle->package.defaultRequested = BOOTSTRAPPER_REQUEST_STATE_NONE;
        pRelatedBundle->package.requested = BOOTSTRAPPER_REQUEST_STATE_NONE;
        pRelatedBundle->defaultPlanRelationType = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_NONE;
        pRelatedBundle->planRelationType = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_NONE;
        pRelatedBundle->package.executeCacheType = BURN_CACHE_PACKAGE_TYPE_NONE;
        pRelatedBundle->package.rollbackCacheType = BURN_CACHE_PACKAGE_TYPE_NONE;

        // Determine the plan relation type even if later it is ignored due to the planned action, the command relation type, or the related bundle not being plannable.
        // This gives more information to the BA in case it wants to override default behavior.
        // Doing it during plan instead of Detect allows the BA to change its mind without having to go all the way through Detect again.
        hr = PlanDefaultRelatedBundlePlanType(pRelatedBundle->detectRelationType, pRegistration->pVersion, pRelatedBundle->pVersion, &pRelatedBundle->defaultPlanRelationType);
        ExitOnFailure(hr, "Failed to get default plan type for related bundle.");

        pRelatedBundle->planRelationType = pRelatedBundle->defaultPlanRelationType;

        hr = UserExperienceOnPlanRelatedBundleType(pUserExperience, pRelatedBundle->package.sczId, &pRelatedBundle->planRelationType);
        ExitOnRootFailure(hr, "BA aborted plan related bundle type.");

        if (BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_DOWNGRADE == pRelatedBundle->planRelationType &&
            pRelatedBundle->fPlannable && !fUninstalling && BOOTSTRAPPER_RELATION_UPGRADE != relationType)
        {
            if (!pPlan->fDowngrade)
            {
                pPlan->fDowngrade = TRUE;

                LogId(REPORT_STANDARD, MSG_PLAN_SKIPPED_DUE_TO_DOWNGRADE);
            }

            LogId(REPORT_VERBOSE, MSG_UPGRADE_BUNDLE_DOWNGRADE, pRelatedBundle->package.sczId, pRelatedBundle->pVersion->sczVersion);
        }
    }

    RelatedBundlesSortPlan(&pRegistration->relatedBundles);

LExit:
    return hr;
}

extern "C" HRESULT PlanRelatedBundlesBegin(
    __in BURN_USER_EXPERIENCE* pUserExperience,
    __in BURN_REGISTRATION* pRegistration,
    __in BOOTSTRAPPER_RELATION_TYPE relationType,
    __in BURN_PLAN* pPlan
    )
{
    HRESULT hr = S_OK;
    LPWSTR* rgsczAncestors = NULL;
    UINT cAncestors = 0;
    STRINGDICT_HANDLE sdAncestors = NULL;
    BOOL fUninstalling = BOOTSTRAPPER_ACTION_UNINSTALL == pPlan->action || BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL == pPlan->action;

    if (pPlan->pInternalCommand->sczAncestors)
    {
        hr = StrSplitAllocArray(&rgsczAncestors, &cAncestors, pPlan->pInternalCommand->sczAncestors, L";");
        ExitOnFailure(hr, "Failed to create string array from ancestors.");

        hr = DictCreateStringListFromArray(&sdAncestors, rgsczAncestors, cAncestors, DICT_FLAG_CASEINSENSITIVE);
        ExitOnFailure(hr, "Failed to create dictionary from ancestors array.");
    }

    for (DWORD i = 0; i < pRegistration->relatedBundles.cRelatedBundles; ++i)
    {
        BURN_RELATED_BUNDLE* pRelatedBundle = pRegistration->relatedBundles.rgpPlanSortedRelatedBundles[i];

        if (!pRelatedBundle->fPlannable)
        {
            continue;
        }

        BOOL fDependent = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_DEPENDENT_ADDON == pRelatedBundle->planRelationType ||
                          BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_DEPENDENT_PATCH == pRelatedBundle->planRelationType;

        // Do not execute the same bundle twice.
        if (sdAncestors)
        {
            hr = DictKeyExists(sdAncestors, pRelatedBundle->package.sczId);
            if (SUCCEEDED(hr))
            {
                LogId(REPORT_STANDARD, MSG_PLAN_SKIPPED_RELATED_BUNDLE_SCHEDULED, pRelatedBundle->package.sczId);
                continue;
            }
            else if (E_NOTFOUND != hr)
            {
                ExitOnFailure(hr, "Failed to lookup the bundle ID in the ancestors dictionary.");
            }
        }
        else if (fDependent && BOOTSTRAPPER_RELATION_NONE != relationType)
        {
            // Avoid repair loops for older bundles that do not handle ancestors.
            LogId(REPORT_STANDARD, MSG_PLAN_SKIPPED_RELATED_BUNDLE_DEPENDENT, pRelatedBundle->package.sczId, LoggingRelationTypeToString(relationType));
            continue;
        }

        // Pass along any ancestors and ourself to prevent infinite loops.
        pRelatedBundle->package.Bundle.wzAncestors = pRegistration->sczBundlePackageAncestors;
        pRelatedBundle->package.Bundle.wzEngineWorkingDirectory = pPlan->pInternalCommand->sczEngineWorkingDirectory;

        hr = PlanDefaultRelatedBundleRequestState(relationType, pRelatedBundle->planRelationType, pPlan->action, &pRelatedBundle->package.requested);
        ExitOnFailure(hr, "Failed to get default request state for related bundle.");

        pRelatedBundle->package.defaultRequested = pRelatedBundle->package.requested;

        hr = UserExperienceOnPlanRelatedBundle(pUserExperience, pRelatedBundle->package.sczId, &pRelatedBundle->package.requested);
        ExitOnRootFailure(hr, "BA aborted plan related bundle.");

        // If uninstalling and the dependent related bundle may be executed, ignore its provider key to allow for downgrades with ref-counting.
        if (fUninstalling && fDependent && BOOTSTRAPPER_REQUEST_STATE_NONE != pRelatedBundle->package.requested)
        {
            if (0 < pRelatedBundle->package.cDependencyProviders)
            {
                // Bundles only support a single provider key.
                const BURN_DEPENDENCY_PROVIDER* pProvider = pRelatedBundle->package.rgDependencyProviders;

                hr = DepDependencyArrayAlloc(&pPlan->rgPlannedProviders, &pPlan->cPlannedProviders, pProvider->sczKey, pProvider->sczDisplayName);
                ExitOnFailure(hr, "Failed to add the package provider key \"%ls\" to the planned list.", pProvider->sczKey);
            }
        }
    }

LExit:
    ReleaseDict(sdAncestors);
    ReleaseStrArray(rgsczAncestors, cAncestors);

    return hr;
}

extern "C" HRESULT PlanRelatedBundlesComplete(
    __in BURN_USER_EXPERIENCE* pUserExperience,
    __in BURN_REGISTRATION* pRegistration,
    __in BURN_PLAN* pPlan,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables,
    __in DWORD dwExecuteActionEarlyIndex
    )
{
    HRESULT hr = S_OK;
    LPWSTR sczIgnoreDependencies = NULL;
    STRINGDICT_HANDLE sdProviderKeys = NULL;
    BOOL fExecutingAnyPackage = FALSE;
    BOOL fInstallingAnyPackage = FALSE;
    BOOL fUninstalling = BOOTSTRAPPER_ACTION_UNINSTALL == pPlan->action || BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL == pPlan->action;

    // Get the list of dependencies to ignore to pass to related bundles.
    hr = DependencyAllocIgnoreDependencies(pPlan, &sczIgnoreDependencies);
    ExitOnFailure(hr, "Failed to get the list of dependencies to ignore.");

    hr = DictCreateStringList(&sdProviderKeys, pPlan->cExecuteActions, DICT_FLAG_CASEINSENSITIVE);
    ExitOnFailure(hr, "Failed to create dictionary for planned packages.");

    for (DWORD i = 0; i < pPlan->cExecuteActions; ++i)
    {
        BOOTSTRAPPER_ACTION_STATE packageAction = BOOTSTRAPPER_ACTION_STATE_NONE;
        BURN_PACKAGE* pPackage = &pPlan->rgExecuteActions[i].relatedBundle.pRelatedBundle->package;
        BOOL fBundle = FALSE;

        switch (pPlan->rgExecuteActions[i].type)
        {
        case BURN_EXECUTE_ACTION_TYPE_BUNDLE_PACKAGE:
            packageAction = pPlan->rgExecuteActions[i].bundlePackage.action;
            pPackage = pPlan->rgExecuteActions[i].bundlePackage.pPackage;
            fBundle = TRUE;
            break;

        case BURN_EXECUTE_ACTION_TYPE_EXE_PACKAGE:
            packageAction = pPlan->rgExecuteActions[i].exePackage.action;
            pPackage = pPlan->rgExecuteActions[i].exePackage.pPackage;
            fBundle = pPackage->Exe.fBundle;
            break;

        case BURN_EXECUTE_ACTION_TYPE_MSI_PACKAGE:
            packageAction = pPlan->rgExecuteActions[i].msiPackage.action;
            break;

        case BURN_EXECUTE_ACTION_TYPE_MSP_TARGET:
            packageAction = pPlan->rgExecuteActions[i].mspTarget.action;
            break;

        case BURN_EXECUTE_ACTION_TYPE_MSU_PACKAGE:
            packageAction = pPlan->rgExecuteActions[i].msuPackage.action;
            break;
        }

        if (fBundle && BOOTSTRAPPER_ACTION_STATE_NONE != packageAction)
        {
            if (pPackage->cDependencyProviders)
            {
                // Bundles only support a single provider key.
                const BURN_DEPENDENCY_PROVIDER* pProvider = pPackage->rgDependencyProviders;
                DictAddKey(sdProviderKeys, pProvider->sczKey);
            }
        }

        fExecutingAnyPackage |= BOOTSTRAPPER_ACTION_STATE_NONE != packageAction;
        fInstallingAnyPackage |= BOOTSTRAPPER_ACTION_STATE_INSTALL == packageAction || BOOTSTRAPPER_ACTION_STATE_MINOR_UPGRADE == packageAction;
    }

    for (DWORD i = 0; i < pRegistration->relatedBundles.cRelatedBundles; ++i)
    {
        DWORD *pdwInsertIndex = NULL;
        BURN_RELATED_BUNDLE* pRelatedBundle = pRegistration->relatedBundles.rgpPlanSortedRelatedBundles[i];
        BOOL fDependent = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_DEPENDENT_ADDON == pRelatedBundle->planRelationType ||
                          BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_DEPENDENT_PATCH == pRelatedBundle->planRelationType;
        BOOL fAddonOrPatch = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_ADDON == pRelatedBundle->planRelationType ||
                             BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_PATCH == pRelatedBundle->planRelationType;

        if (!pRelatedBundle->fPlannable)
        {
            continue;
        }

        // Do not execute if a major upgrade to the related bundle is an embedded bundle (Provider keys are the same)
        if (0 < pRelatedBundle->package.cDependencyProviders)
        {
            // Bundles only support a single provider key.
            const BURN_DEPENDENCY_PROVIDER* pProvider = pRelatedBundle->package.rgDependencyProviders;
            hr = DictKeyExists(sdProviderKeys, pProvider->sczKey);
            if (E_NOTFOUND != hr)
            {
                ExitOnFailure(hr, "Failed to check the dictionary for a related bundle provider key: \"%ls\".", pProvider->sczKey);
                // Key found, so there is an embedded bundle with the same provider key that will be executed.  So this related bundle should not be added to the plan
                LogId(REPORT_STANDARD, MSG_PLAN_SKIPPED_RELATED_BUNDLE_EMBEDDED_BUNDLE_NEWER, pRelatedBundle->package.sczId, pProvider->sczKey);
                continue;
            }
            else
            {
                hr = S_OK;
            }
        }

        // For an uninstall, there is no need to repair dependent bundles if no packages are executing.
        if (!fExecutingAnyPackage && fDependent && BOOTSTRAPPER_REQUEST_STATE_REPAIR == pRelatedBundle->package.requested && fUninstalling)
        {
            pRelatedBundle->package.requested = BOOTSTRAPPER_REQUEST_STATE_NONE;
            LogId(REPORT_STANDARD, MSG_PLAN_SKIPPED_DEPENDENT_BUNDLE_REPAIR, pRelatedBundle->package.sczId);
        }

        if (fAddonOrPatch)
        {
            // Addon and patch bundles will be passed a list of dependencies to ignore for planning.
            hr = StrAllocString(&pRelatedBundle->package.Bundle.sczIgnoreDependencies, sczIgnoreDependencies, 0);
            ExitOnFailure(hr, "Failed to copy the list of dependencies to ignore.");

            // Uninstall addons and patches early in the chain, before other packages are uninstalled.
            if (fUninstalling)
            {
                pdwInsertIndex = &dwExecuteActionEarlyIndex;
            }
        }

        if (BOOTSTRAPPER_REQUEST_STATE_NONE != pRelatedBundle->package.requested)
        {
            hr = BundlePackageEnginePlanCalculatePackage(&pRelatedBundle->package);
            ExitOnFailure(hr, "Failed to calculate plan for related bundle: %ls", pRelatedBundle->package.sczId);

            // Calculate package states based on reference count for addon and patch related bundles.
            if (fAddonOrPatch)
            {
                hr = DependencyPlanPackageBegin(pRegistration->fPerMachine, &pRelatedBundle->package, pPlan);
                ExitOnFailure(hr, "Failed to begin plan dependency actions to  package: %ls", pRelatedBundle->package.sczId);

                // If uninstalling a related bundle, make sure the bundle is uninstalled after removing registration.
                if (pdwInsertIndex && fUninstalling)
                {
                    ++(*pdwInsertIndex);
                }
            }

            hr = BundlePackageEnginePlanAddRelatedBundle(pdwInsertIndex, pRelatedBundle, pPlan, pLog, pVariables);
            ExitOnFailure(hr, "Failed to add to plan related bundle: %ls", pRelatedBundle->package.sczId);

            // Calculate package states based on reference count for addon and patch related bundles.
            if (fAddonOrPatch)
            {
                hr = DependencyPlanPackageComplete(&pRelatedBundle->package, pPlan);
                ExitOnFailure(hr, "Failed to complete plan dependency actions for related bundle package: %ls", pRelatedBundle->package.sczId);
            }

            // If we are going to take any action on this package, add progress for it.
            if (BOOTSTRAPPER_ACTION_STATE_NONE != pRelatedBundle->package.execute || BOOTSTRAPPER_ACTION_STATE_NONE != pRelatedBundle->package.rollback)
            {
                PlannedExecutePackage(pPlan, &pRelatedBundle->package);
            }
        }
        else if (fAddonOrPatch)
        {
            // Make sure the package is properly ref-counted even if no plan is requested.
            hr = DependencyPlanPackageBegin(pRegistration->fPerMachine, &pRelatedBundle->package, pPlan);
            ExitOnFailure(hr, "Failed to begin plan dependency actions for related bundle package: %ls", pRelatedBundle->package.sczId);

            hr = DependencyPlanPackage(pdwInsertIndex, &pRelatedBundle->package, pPlan);
            ExitOnFailure(hr, "Failed to plan related bundle package provider actions.");

            hr = DependencyPlanPackageComplete(&pRelatedBundle->package, pPlan);
            ExitOnFailure(hr, "Failed to complete plan dependency actions for related bundle package: %ls", pRelatedBundle->package.sczId);
        }

        if (fInstallingAnyPackage && BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_UPGRADE == pRelatedBundle->planRelationType)
        {
            BURN_EXECUTE_ACTION* pAction = NULL;

            pRelatedBundle->defaultRequestedRestore = pRelatedBundle->requestedRestore = BOOTSTRAPPER_REQUEST_STATE_FORCE_PRESENT;

            hr = UserExperienceOnPlanRestoreRelatedBundle(pUserExperience, pRelatedBundle->package.sczId, &pRelatedBundle->requestedRestore);
            ExitOnRootFailure(hr, "BA aborted plan restore related bundle.");

            switch (pRelatedBundle->requestedRestore)
            {
            case BOOTSTRAPPER_REQUEST_STATE_REPAIR:
                pRelatedBundle->restore = BOOTSTRAPPER_ACTION_STATE_REPAIR;
                break;
            case BOOTSTRAPPER_REQUEST_STATE_ABSENT: __fallthrough;
            case BOOTSTRAPPER_REQUEST_STATE_CACHE: __fallthrough;
            case BOOTSTRAPPER_REQUEST_STATE_FORCE_ABSENT:
                pRelatedBundle->restore = BOOTSTRAPPER_ACTION_STATE_UNINSTALL;
                break;
            case BOOTSTRAPPER_REQUEST_STATE_FORCE_PRESENT:
                pRelatedBundle->restore = BOOTSTRAPPER_ACTION_STATE_INSTALL;
                break;
            default:
                pRelatedBundle->restore = BOOTSTRAPPER_ACTION_STATE_NONE;
                break;
            }

            if (BOOTSTRAPPER_ACTION_STATE_NONE != pRelatedBundle->restore)
            {
                hr = AppendRestoreRelatedBundleAction(pPlan, &pAction);
                ExitOnFailure(hr, "Failed to append restore related bundle action to plan.");

                pAction->type = BURN_EXECUTE_ACTION_TYPE_RELATED_BUNDLE;
                pAction->relatedBundle.pRelatedBundle = pRelatedBundle;
                pAction->relatedBundle.action = pRelatedBundle->restore;

                if (pRelatedBundle->package.Bundle.sczIgnoreDependencies)
                {
                    hr = StrAllocString(&pAction->relatedBundle.sczIgnoreDependencies, pRelatedBundle->package.Bundle.sczIgnoreDependencies, 0);
                    ExitOnFailure(hr, "Failed to allocate the list of dependencies to ignore.");
                }

                if (pRelatedBundle->package.Bundle.wzAncestors)
                {
                    hr = StrAllocString(&pAction->relatedBundle.sczAncestors, pRelatedBundle->package.Bundle.wzAncestors, 0);
                    ExitOnFailure(hr, "Failed to allocate the list of ancestors.");
                }

                if (pRelatedBundle->package.Bundle.wzEngineWorkingDirectory)
                {
                    hr = StrAllocString(&pAction->relatedBundle.sczEngineWorkingDirectory, pRelatedBundle->package.Bundle.wzEngineWorkingDirectory, 0);
                    ExitOnFailure(hr, "Failed to allocate the custom working directory.");
                }
            }
        }
    }

LExit:
    ReleaseDict(sdProviderKeys);
    ReleaseStr(sczIgnoreDependencies);

    return hr;
}

extern "C" HRESULT PlanFinalizeActions(
    __in BURN_PLAN* pPlan
    )
{
    HRESULT hr = S_OK;

    FinalizePatchActions(TRUE, pPlan->rgExecuteActions, pPlan->cExecuteActions);

    FinalizePatchActions(FALSE, pPlan->rgRollbackActions, pPlan->cRollbackActions);

    RemoveUnnecessaryActions(TRUE, pPlan->rgExecuteActions, pPlan->cExecuteActions);

    RemoveUnnecessaryActions(FALSE, pPlan->rgRollbackActions, pPlan->cRollbackActions);

    return hr;
}

extern "C" HRESULT PlanCleanPackage(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage
    )
{
    HRESULT hr = S_OK;
    BOOL fPlanCleanPackage = FALSE;
    BURN_CLEAN_ACTION* pCleanAction = NULL;
    BOOL fUninstalling = BOOTSTRAPPER_ACTION_UNINSTALL == pPlan->action || BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL == pPlan->action;

    // The following is a complex set of logic that determines when a package should be cleaned from the cache.
    if (BOOTSTRAPPER_CACHE_TYPE_FORCE > pPackage->cacheType || fUninstalling)
    {
        // The following are all different reasons why the package should be cleaned from the cache.
        // The else-ifs are used to make the conditions easier to see (rather than have them combined
        // in one huge condition).
        if (BOOTSTRAPPER_CACHE_TYPE_KEEP > pPackage->cacheType)  // easy, package is not supposed to stay cached.
        {
            fPlanCleanPackage = TRUE;
        }
        else if ((BOOTSTRAPPER_REQUEST_STATE_FORCE_ABSENT == pPackage->requested ||
                  BOOTSTRAPPER_REQUEST_STATE_ABSENT == pPackage->requested) &&      // requested to be removed and
                 BOOTSTRAPPER_ACTION_STATE_UNINSTALL == pPackage->execute)          // actually being removed.
        {
            fPlanCleanPackage = TRUE;
        }
        else if ((BOOTSTRAPPER_REQUEST_STATE_FORCE_ABSENT == pPackage->requested ||
                  BOOTSTRAPPER_REQUEST_STATE_ABSENT == pPackage->requested) &&      // requested to be removed but
                 BOOTSTRAPPER_ACTION_STATE_NONE == pPackage->execute &&             // execute is do nothing and
                 !pPackage->fDependencyManagerWasHere &&                            // dependency manager didn't change execute and
                 BOOTSTRAPPER_PACKAGE_STATE_PRESENT > pPackage->currentState)       // currently not installed.
        {
            fPlanCleanPackage = TRUE;
        }
        else if (fUninstalling &&                                                   // uninstalling and
                 BOOTSTRAPPER_REQUEST_STATE_NONE == pPackage->requested &&          // requested do nothing (aka: default) and
                 BOOTSTRAPPER_ACTION_STATE_NONE == pPackage->execute &&             // execute is still do nothing and
                 !pPackage->fDependencyManagerWasHere &&                            // dependency manager didn't change execute and
                 BOOTSTRAPPER_PACKAGE_STATE_PRESENT > pPackage->currentState)       // currently not installed.
        {
            fPlanCleanPackage = TRUE;
        }
    }

    if (fPlanCleanPackage)
    {
        hr = AppendCleanAction(pPlan, &pCleanAction);
        ExitOnFailure(hr, "Failed to append clean action to plan.");

        pCleanAction->type = BURN_CLEAN_ACTION_TYPE_PACKAGE;
        pCleanAction->pPackage = pPackage;

        pPackage->fPlannedUncache = TRUE;

        if (pPackage->fCanAffectRegistration)
        {
            pPackage->expectedCacheRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_ABSENT;
        }
    }

    if (pPackage->compatiblePackage.fRemove)
    {
        hr = AppendCleanAction(pPlan, &pCleanAction);
        ExitOnFailure(hr, "Failed to append clean action to plan.");

        pCleanAction->type = BURN_CLEAN_ACTION_TYPE_COMPATIBLE_PACKAGE;
        pCleanAction->pPackage = pPackage;
    }

LExit:
    return hr;
}

extern "C" HRESULT PlanExecuteCacheSyncAndRollback(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage
    )
{
    HRESULT hr = S_OK;
    BURN_EXECUTE_ACTION* pAction = NULL;

    if (pPlan->fPlanPackageCacheRollback)
    {
        hr = PlanAppendRollbackAction(pPlan, &pAction);
        ExitOnFailure(hr, "Failed to append rollback action.");

        pAction->type = BURN_EXECUTE_ACTION_TYPE_UNCACHE_PACKAGE;
        pAction->uncachePackage.pPackage = pPackage;
    }

    hr = PlanExecuteCheckpoint(pPlan);
    ExitOnFailure(hr, "Failed to append execute checkpoint for cache rollback.");

    hr = PlanAppendExecuteAction(pPlan, &pAction);
    ExitOnFailure(hr, "Failed to append wait action for caching.");

    pAction->type = BURN_EXECUTE_ACTION_TYPE_WAIT_CACHE_PACKAGE;
    pAction->waitCachePackage.pPackage = pPackage;

LExit:
    return hr;
}

extern "C" HRESULT PlanExecuteCheckpoint(
    __in BURN_PLAN* pPlan
    )
{
    HRESULT hr = S_OK;
    BURN_EXECUTE_ACTION* pAction = NULL;
    DWORD dwCheckpointId = GetNextCheckpointId(pPlan);

    // execute checkpoint
    hr = PlanAppendExecuteAction(pPlan, &pAction);
    ExitOnFailure(hr, "Failed to append execute action.");

    pAction->type = BURN_EXECUTE_ACTION_TYPE_CHECKPOINT;
    pAction->checkpoint.dwId = dwCheckpointId;
    pAction->checkpoint.pActiveRollbackBoundary = pPlan->pActiveRollbackBoundary;

    // rollback checkpoint
    hr = PlanAppendRollbackAction(pPlan, &pAction);
    ExitOnFailure(hr, "Failed to append rollback action.");

    pAction->type = BURN_EXECUTE_ACTION_TYPE_CHECKPOINT;
    pAction->checkpoint.dwId = dwCheckpointId;
    pAction->checkpoint.pActiveRollbackBoundary = pPlan->pActiveRollbackBoundary;

LExit:
    return hr;
}

extern "C" HRESULT PlanInsertExecuteAction(
    __in DWORD dwIndex,
    __in BURN_PLAN* pPlan,
    __out BURN_EXECUTE_ACTION** ppExecuteAction
    )
{
    HRESULT hr = S_OK;

    hr = MemInsertIntoArray((void**)&pPlan->rgExecuteActions, dwIndex, 1, pPlan->cExecuteActions + 1, sizeof(BURN_EXECUTE_ACTION), 5);
    ExitOnFailure(hr, "Failed to grow plan's array of execute actions.");

    *ppExecuteAction = pPlan->rgExecuteActions + dwIndex;
    ++pPlan->cExecuteActions;

LExit:
    return hr;
}

extern "C" HRESULT PlanInsertRollbackAction(
    __in DWORD dwIndex,
    __in BURN_PLAN* pPlan,
    __out BURN_EXECUTE_ACTION** ppRollbackAction
    )
{
    HRESULT hr = S_OK;

    hr = MemInsertIntoArray((void**)&pPlan->rgRollbackActions, dwIndex, 1, pPlan->cRollbackActions + 1, sizeof(BURN_EXECUTE_ACTION), 5);
    ExitOnFailure(hr, "Failed to grow plan's array of rollback actions.");

    *ppRollbackAction = pPlan->rgRollbackActions + dwIndex;
    ++pPlan->cRollbackActions;

LExit:
    return hr;
}

extern "C" HRESULT PlanAppendExecuteAction(
    __in BURN_PLAN* pPlan,
    __out BURN_EXECUTE_ACTION** ppExecuteAction
    )
{
    HRESULT hr = S_OK;

    hr = MemEnsureArraySize((void**)&pPlan->rgExecuteActions, pPlan->cExecuteActions + 1, sizeof(BURN_EXECUTE_ACTION), 5);
    ExitOnFailure(hr, "Failed to grow plan's array of execute actions.");

    *ppExecuteAction = pPlan->rgExecuteActions + pPlan->cExecuteActions;
    ++pPlan->cExecuteActions;

LExit:
    return hr;
}

extern "C" HRESULT PlanAppendRollbackAction(
    __in BURN_PLAN* pPlan,
    __out BURN_EXECUTE_ACTION** ppRollbackAction
    )
{
    HRESULT hr = S_OK;

    hr = MemEnsureArraySize((void**)&pPlan->rgRollbackActions, pPlan->cRollbackActions + 1, sizeof(BURN_EXECUTE_ACTION), 5);
    ExitOnFailure(hr, "Failed to grow plan's array of rollback actions.");

    *ppRollbackAction = pPlan->rgRollbackActions + pPlan->cRollbackActions;
    ++pPlan->cRollbackActions;

LExit:
    return hr;
}

extern "C" HRESULT PlanRollbackBoundaryBegin(
    __in BURN_PLAN* pPlan,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables,
    __in BURN_ROLLBACK_BOUNDARY* pRollbackBoundary
    )
{
    HRESULT hr = S_OK;
    BURN_EXECUTE_ACTION* pExecuteAction = NULL;

    AssertSz(!pPlan->pActiveRollbackBoundary, "PlanRollbackBoundaryBegin called without completing previous RollbackBoundary");
    pPlan->pActiveRollbackBoundary = pRollbackBoundary;

    // Add begin rollback boundary to execute plan.
    hr = PlanAppendExecuteAction(pPlan, &pExecuteAction);
    ExitOnFailure(hr, "Failed to append rollback boundary begin action.");

    pExecuteAction->type = BURN_EXECUTE_ACTION_TYPE_ROLLBACK_BOUNDARY_START;
    pExecuteAction->rollbackBoundary.pRollbackBoundary = pRollbackBoundary;

    // Add begin rollback boundary to rollback plan.
    hr = PlanAppendRollbackAction(pPlan, &pExecuteAction);
    ExitOnFailure(hr, "Failed to append rollback boundary begin action.");

    pExecuteAction->type = BURN_EXECUTE_ACTION_TYPE_ROLLBACK_BOUNDARY_START;
    pExecuteAction->rollbackBoundary.pRollbackBoundary = pRollbackBoundary;

    hr = UserExperienceOnPlanRollbackBoundary(pUX, pRollbackBoundary->sczId, &pRollbackBoundary->fTransaction);
    ExitOnRootFailure(hr, "BA aborted plan rollback boundary.");

    // Only use MSI transaction if authored and the BA requested it.
    if (!pRollbackBoundary->fTransactionAuthored || !pRollbackBoundary->fTransaction)
    {
        pRollbackBoundary->fTransaction = FALSE;
    }
    else
    {
        LoggingSetTransactionVariable(pRollbackBoundary, NULL, pLog, pVariables); // ignore errors.

        // Add begin MSI transaction to execute plan.
        hr = PlanExecuteCheckpoint(pPlan);
        ExitOnFailure(hr, "Failed to append checkpoint before MSI transaction begin action.");

        hr = PlanAppendExecuteAction(pPlan, &pExecuteAction);
        ExitOnFailure(hr, "Failed to append MSI transaction begin action.");

        pExecuteAction->type = BURN_EXECUTE_ACTION_TYPE_BEGIN_MSI_TRANSACTION;
        pExecuteAction->msiTransaction.pRollbackBoundary = pRollbackBoundary;
    }

LExit:
    return hr;
}

extern "C" HRESULT PlanRollbackBoundaryComplete(
    __in BURN_PLAN* pPlan
    )
{
    HRESULT hr = S_OK;
    BURN_EXECUTE_ACTION* pExecuteAction = NULL;
    BURN_ROLLBACK_BOUNDARY* pRollbackBoundary = pPlan->pActiveRollbackBoundary;

    AssertSz(pRollbackBoundary, "PlanRollbackBoundaryComplete called without an active RollbackBoundary");

    if (pRollbackBoundary && pRollbackBoundary->fTransaction)
    {
        // Add commit MSI transaction to execute plan.
        hr = PlanAppendExecuteAction(pPlan, &pExecuteAction);
        ExitOnFailure(hr, "Failed to append MSI transaction commit action.");

        pExecuteAction->type = BURN_EXECUTE_ACTION_TYPE_COMMIT_MSI_TRANSACTION;
        pExecuteAction->msiTransaction.pRollbackBoundary = pRollbackBoundary;
    }

    pPlan->pActiveRollbackBoundary = NULL;

    // Add checkpoints.
    hr = PlanExecuteCheckpoint(pPlan);

    // Add complete rollback boundary to execute plan.
    hr = PlanAppendExecuteAction(pPlan, &pExecuteAction);
    ExitOnFailure(hr, "Failed to append rollback boundary complete action.");

    pExecuteAction->type = BURN_EXECUTE_ACTION_TYPE_ROLLBACK_BOUNDARY_END;

    // Add begin rollback boundary to rollback plan.
    hr = PlanAppendRollbackAction(pPlan, &pExecuteAction);
    ExitOnFailure(hr, "Failed to append rollback boundary complete action.");

    pExecuteAction->type = BURN_EXECUTE_ACTION_TYPE_ROLLBACK_BOUNDARY_END;

LExit:
    return hr;
}

/*******************************************************************
 PlanSetResumeCommand - Initializes resume command string

*******************************************************************/
extern "C" HRESULT PlanSetResumeCommand(
    __in BURN_PLAN* pPlan,
    __in BURN_REGISTRATION* pRegistration,
    __in BURN_LOGGING* pLog
    )
{
    HRESULT hr = S_OK;

    // build the resume command-line.
    hr = CoreCreateResumeCommandLine(&pRegistration->sczResumeCommandLine, pPlan, pLog);
    ExitOnFailure(hr, "Failed to create resume command-line.");

LExit:
    return hr;
}


// internal function definitions


static void PlannedExecutePackage(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage
    )
{
    LoggingIncrementPackageSequence();

    ++pPlan->cExecutePackagesTotal;
    ++pPlan->cOverallProgressTicksTotal;

    // If package is per-machine and is being executed, flag the plan to be per-machine as well.
    if (pPackage->fPerMachine)
    {
        pPlan->fPerMachine = TRUE;
    }
}

static void UninitializeRegistrationAction(
    __in BURN_DEPENDENT_REGISTRATION_ACTION* pAction
    )
{
    ReleaseStr(pAction->sczDependentProviderKey);
    ReleaseStr(pAction->sczBundleId);
    memset(pAction, 0, sizeof(BURN_DEPENDENT_REGISTRATION_ACTION));
}

static void UninitializeCacheAction(
    __in BURN_CACHE_ACTION* pCacheAction
    )
{
    switch (pCacheAction->type)
    {
    case BURN_CACHE_ACTION_TYPE_LAYOUT_BUNDLE:
        ReleaseStr(pCacheAction->bundleLayout.sczExecutableName);
        ReleaseStr(pCacheAction->bundleLayout.sczUnverifiedPath);
        break;
    }
}

static void ResetPlannedContainerState(
    __in BURN_CONTAINER* pContainer
    )
{
    pContainer->fPlanned = FALSE;
    pContainer->qwExtractSizeTotal = 0;
    pContainer->qwCommittedCacheProgress = 0;
    pContainer->qwCommittedExtractProgress = 0;
    pContainer->fExtracted = FALSE;
    pContainer->fFailedVerificationFromAcquisition = FALSE;
    ReleaseNullStr(pContainer->sczFailedLocalAcquisitionPath);
}

static void ResetPlannedPayloadsState(
    __in BURN_PAYLOADS* pPayloads
    )
{
    for (DWORD i = 0; i < pPayloads->cPayloads; ++i)
    {
        BURN_PAYLOAD* pPayload = pPayloads->rgPayloads + i;

        pPayload->cRemainingInstances = 0;
        pPayload->state = BURN_PAYLOAD_STATE_NONE;
        pPayload->fFailedVerificationFromAcquisition = FALSE;
        ReleaseNullStr(pPayload->sczLocalFilePath);
        ReleaseNullStr(pPayload->sczFailedLocalAcquisitionPath);
    }
}

static void ResetPlannedPayloadGroupState(
    __in BURN_PAYLOAD_GROUP* pPayloadGroup
    )
{
    for (DWORD i = 0; i < pPayloadGroup->cItems; ++i)
    {
        BURN_PAYLOAD_GROUP_ITEM* pItem = pPayloadGroup->rgItems + i;

        pItem->fCached = FALSE;
        pItem->qwCommittedCacheProgress = 0;
    }
}

static void ResetPlannedPackageState(
    __in BURN_PACKAGE* pPackage
    )
{
    // Reset package state that is a result of planning.
    pPackage->cacheType = pPackage->authoredCacheType;
    pPackage->defaultRequested = BOOTSTRAPPER_REQUEST_STATE_NONE;
    pPackage->requested = BOOTSTRAPPER_REQUEST_STATE_NONE;
    pPackage->fCacheVital = FALSE;
    pPackage->fPlannedUncache = FALSE;
    pPackage->execute = BOOTSTRAPPER_ACTION_STATE_NONE;
    pPackage->rollback = BOOTSTRAPPER_ACTION_STATE_NONE;
    pPackage->fProviderExecute = FALSE;
    pPackage->fProviderRollback = FALSE;
    pPackage->dependencyExecute = BURN_DEPENDENCY_ACTION_NONE;
    pPackage->dependencyRollback = BURN_DEPENDENCY_ACTION_NONE;
    pPackage->fDependencyManagerWasHere = FALSE;
    pPackage->expectedCacheRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_UNKNOWN;
    pPackage->expectedInstallRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_UNKNOWN;
    pPackage->executeCacheType = BURN_CACHE_PACKAGE_TYPE_NONE;
    pPackage->rollbackCacheType = BURN_CACHE_PACKAGE_TYPE_NONE;
    ReleaseHandle(pPackage->hCacheEvent);

    ReleaseNullStr(pPackage->sczCacheFolder);

    if (BURN_PACKAGE_TYPE_MSI == pPackage->type)
    {
        for (DWORD i = 0; i < pPackage->Msi.cFeatures; ++i)
        {
            BURN_MSIFEATURE* pFeature = &pPackage->Msi.rgFeatures[i];

            pFeature->expectedState = BOOTSTRAPPER_FEATURE_STATE_UNKNOWN;
            pFeature->defaultRequested = BOOTSTRAPPER_FEATURE_STATE_UNKNOWN;
            pFeature->requested = BOOTSTRAPPER_FEATURE_STATE_UNKNOWN;
            pFeature->execute = BOOTSTRAPPER_FEATURE_ACTION_NONE;
            pFeature->rollback = BOOTSTRAPPER_FEATURE_ACTION_NONE;
        }

        for (DWORD i = 0; i < pPackage->Msi.cSlipstreamMspPackages; ++i)
        {
            BURN_SLIPSTREAM_MSP* pSlipstreamMsp = &pPackage->Msi.rgSlipstreamMsps[i];

            pSlipstreamMsp->execute = BOOTSTRAPPER_ACTION_STATE_NONE;
            pSlipstreamMsp->rollback = BOOTSTRAPPER_ACTION_STATE_NONE;
        }
    }
    else if (BURN_PACKAGE_TYPE_MSP == pPackage->type && pPackage->Msp.rgTargetProducts)
    {
        for (DWORD i = 0; i < pPackage->Msp.cTargetProductCodes; ++i)
        {
            BURN_MSPTARGETPRODUCT* pTargetProduct = &pPackage->Msp.rgTargetProducts[i];

            pTargetProduct->defaultRequested = BOOTSTRAPPER_REQUEST_STATE_NONE;
            pTargetProduct->requested = BOOTSTRAPPER_REQUEST_STATE_NONE;
            pTargetProduct->execute = BOOTSTRAPPER_ACTION_STATE_NONE;
            pTargetProduct->rollback = BOOTSTRAPPER_ACTION_STATE_NONE;
            pTargetProduct->executeSkip = BURN_PATCH_SKIP_STATE_NONE;
            pTargetProduct->rollbackSkip = BURN_PATCH_SKIP_STATE_NONE;
        }
    }

    for (DWORD i = 0; i < pPackage->cDependencyProviders; ++i)
    {
        BURN_DEPENDENCY_PROVIDER* pProvider = &pPackage->rgDependencyProviders[i];

        pProvider->dependentExecute = BURN_DEPENDENCY_ACTION_NONE;
        pProvider->dependentRollback = BURN_DEPENDENCY_ACTION_NONE;
        pProvider->providerExecute = BURN_DEPENDENCY_ACTION_NONE;
        pProvider->providerRollback = BURN_DEPENDENCY_ACTION_NONE;
    }

    ResetPlannedPayloadGroupState(&pPackage->payloads);
}

static void ResetPlannedRollbackBoundaryState(
    __in BURN_ROLLBACK_BOUNDARY* pRollbackBoundary
    )
{
    pRollbackBoundary->fActiveTransaction = FALSE;
    pRollbackBoundary->fTransaction = pRollbackBoundary->fTransactionAuthored;
    ReleaseNullStr(pRollbackBoundary->sczLogPath);
}

static HRESULT GetActionDefaultRequestState(
    __in BOOTSTRAPPER_ACTION action,
    __in BOOTSTRAPPER_PACKAGE_STATE currentState,
    __out BOOTSTRAPPER_REQUEST_STATE* pRequestState
    )
{
    HRESULT hr = S_OK;

    switch (action)
    {
    case BOOTSTRAPPER_ACTION_INSTALL:
        *pRequestState = BOOTSTRAPPER_REQUEST_STATE_PRESENT;
        break;

    case BOOTSTRAPPER_ACTION_REPAIR:
        *pRequestState = BOOTSTRAPPER_REQUEST_STATE_REPAIR;
        break;

    case BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL: __fallthrough;
    case BOOTSTRAPPER_ACTION_UNINSTALL:
        *pRequestState = BOOTSTRAPPER_REQUEST_STATE_ABSENT;
        break;

    case BOOTSTRAPPER_ACTION_MODIFY:
        switch (currentState)
        {
        case BOOTSTRAPPER_PACKAGE_STATE_ABSENT:
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_ABSENT;
            break;

        case BOOTSTRAPPER_PACKAGE_STATE_PRESENT:
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_PRESENT;
            break;

        default:
            *pRequestState = BOOTSTRAPPER_REQUEST_STATE_NONE;
            break;
        }
        break;

    default:
        hr = E_INVALIDARG;
        ExitOnRootFailure(hr, "Invalid action state.");
    }

LExit:
    return hr;
}

static HRESULT AddRegistrationAction(
    __in BURN_PLAN* pPlan,
    __in BURN_DEPENDENT_REGISTRATION_ACTION_TYPE type,
    __in_z LPCWSTR wzDependentProviderKey,
    __in_z LPCWSTR wzOwnerBundleId
    )
{
    HRESULT hr = S_OK;
    BURN_DEPENDENT_REGISTRATION_ACTION_TYPE rollbackType = (BURN_DEPENDENT_REGISTRATION_ACTION_TYPE_REGISTER == type) ? BURN_DEPENDENT_REGISTRATION_ACTION_TYPE_UNREGISTER : BURN_DEPENDENT_REGISTRATION_ACTION_TYPE_REGISTER;
    BURN_DEPENDENT_REGISTRATION_ACTION* pAction = NULL;

    // Create forward registration action.
    hr = MemEnsureArraySize((void**)&pPlan->rgRegistrationActions, pPlan->cRegistrationActions + 1, sizeof(BURN_DEPENDENT_REGISTRATION_ACTION), 5);
    ExitOnFailure(hr, "Failed to grow plan's array of registration actions.");

    pAction = pPlan->rgRegistrationActions + pPlan->cRegistrationActions;
    ++pPlan->cRegistrationActions;

    pAction->type = type;

    hr = StrAllocString(&pAction->sczBundleId, wzOwnerBundleId, 0);
    ExitOnFailure(hr, "Failed to copy owner bundle to registration action.");

    hr = StrAllocString(&pAction->sczDependentProviderKey, wzDependentProviderKey, 0);
    ExitOnFailure(hr, "Failed to copy dependent provider key to registration action.");

    // Create rollback registration action.
    hr = MemEnsureArraySize((void**)&pPlan->rgRollbackRegistrationActions, pPlan->cRollbackRegistrationActions + 1, sizeof(BURN_DEPENDENT_REGISTRATION_ACTION), 5);
    ExitOnFailure(hr, "Failed to grow plan's array of rollback registration actions.");

    pAction = pPlan->rgRollbackRegistrationActions + pPlan->cRollbackRegistrationActions;
    ++pPlan->cRollbackRegistrationActions;

    pAction->type = rollbackType;

    hr = StrAllocString(&pAction->sczBundleId, wzOwnerBundleId, 0);
    ExitOnFailure(hr, "Failed to copy owner bundle to registration action.");

    hr = StrAllocString(&pAction->sczDependentProviderKey, wzDependentProviderKey, 0);
    ExitOnFailure(hr, "Failed to copy dependent provider key to rollback registration action.");

LExit:
    return hr;
}

static HRESULT AddCachePackage(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage,
    __in BOOL fVital
    )
{
    HRESULT hr = S_OK;

    // If this is an MSI package with slipstream MSPs, ensure the MSPs are cached first.
    // TODO: Slipstream packages are not accounted for when caching the MSI package is optional.
    if (BURN_PACKAGE_TYPE_MSI == pPackage->type && 0 < pPackage->Msi.cSlipstreamMspPackages && fVital)
    {
        hr = AddCacheSlipstreamMsps(pPlan, pPackage);
        ExitOnFailure(hr, "Failed to plan slipstream patches for package.");
    }

    hr = AddCachePackageHelper(pPlan, pPackage, fVital);
    ExitOnFailure(hr, "Failed to plan cache package.");

LExit:
    return hr;
}

static HRESULT AddCachePackageHelper(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage,
    __in BOOL fVital
    )
{
    AssertSz(pPackage->sczCacheId && *pPackage->sczCacheId, "AddCachePackageHelper() expects the package to have a cache id.");

    HRESULT hr = S_OK;
    BURN_CACHE_ACTION* pCacheAction = NULL;
    DWORD dwCheckpoint = 0;

    if (pPlan->fEnabledForwardCompatibleBundle) // Passthrough packages must already be cached.
    {
        ExitFunction();
    }

    if (pPackage->hCacheEvent) // Only cache the package once.
    {
        ExitFunction();
    }

    pPackage->hCacheEvent = ::CreateEventW(NULL, TRUE, FALSE, NULL);
    ExitOnNullWithLastError(pPackage->hCacheEvent, hr, "Failed to create syncpoint event.");

    // Cache checkpoints happen before the package is cached because downloading packages'
    // payloads will not roll themselves back the way installation packages rollback on
    // failure automatically.
    dwCheckpoint = GetNextCheckpointId(pPlan);

    hr = AppendCacheAction(pPlan, &pCacheAction);
    ExitOnFailure(hr, "Failed to append checkpoint before package start action.");

    pCacheAction->type = BURN_CACHE_ACTION_TYPE_CHECKPOINT;
    pCacheAction->checkpoint.dwId = dwCheckpoint;

    if (pPlan->fPlanPackageCacheRollback)
    {
        // Create a package cache rollback action *before* the checkpoint.
        hr = AppendRollbackCacheAction(pPlan, &pCacheAction);
        ExitOnFailure(hr, "Failed to append rollback cache action.");

        pCacheAction->type = BURN_CACHE_ACTION_TYPE_ROLLBACK_PACKAGE;
        pCacheAction->rollbackPackage.pPackage = pPackage;

        hr = AppendRollbackCacheAction(pPlan, &pCacheAction);
        ExitOnFailure(hr, "Failed to append rollback cache action.");

        pCacheAction->type = BURN_CACHE_ACTION_TYPE_CHECKPOINT;
        pCacheAction->checkpoint.dwId = dwCheckpoint;
    }

    hr = PlanLayoutPackage(pPlan, pPackage, fVital);
    ExitOnFailure(hr, "Failed to plan cache for package.");

    // Create syncpoint action.
    hr = AppendCacheAction(pPlan, &pCacheAction);
    ExitOnFailure(hr, "Failed to append cache action.");

    pCacheAction->type = BURN_CACHE_ACTION_TYPE_SIGNAL_SYNCPOINT;
    pCacheAction->syncpoint.pPackage = pPackage;

    hr = PlanExecuteCacheSyncAndRollback(pPlan, pPackage);
    ExitOnFailure(hr, "Failed to plan package cache syncpoint");

    if (pPackage->fCanAffectRegistration)
    {
        pPackage->expectedCacheRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_PRESENT;
    }

LExit:
    return hr;
}

static HRESULT AddCacheSlipstreamMsps(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage
    )
{
    HRESULT hr = S_OK;

    AssertSz(BURN_PACKAGE_TYPE_MSI == pPackage->type, "Only MSI packages can have slipstream patches.");

    for (DWORD i = 0; i < pPackage->Msi.cSlipstreamMspPackages; ++i)
    {
        BURN_PACKAGE* pMspPackage = pPackage->Msi.rgSlipstreamMsps[i].pMspPackage;
        AssertSz(BURN_PACKAGE_TYPE_MSP == pMspPackage->type, "Only MSP packages can be slipstream patches.");

        hr = AddCachePackageHelper(pPlan, pMspPackage, TRUE);
        ExitOnFailure(hr, "Failed to plan slipstream MSP: %ls", pMspPackage->sczId);
    }

LExit:
    return hr;
}

static DWORD GetNextCheckpointId(
    __in BURN_PLAN* pPlan
    )
{
    return ++pPlan->dwNextCheckpointId;
}

static HRESULT AppendCacheAction(
    __in BURN_PLAN* pPlan,
    __out BURN_CACHE_ACTION** ppCacheAction
    )
{
    HRESULT hr = S_OK;

    hr = MemEnsureArraySize(reinterpret_cast<LPVOID*>(&pPlan->rgCacheActions), pPlan->cCacheActions + 1, sizeof(BURN_CACHE_ACTION), 5);
    ExitOnFailure(hr, "Failed to grow plan's array of cache actions.");

    *ppCacheAction = pPlan->rgCacheActions + pPlan->cCacheActions;
    ++pPlan->cCacheActions;

LExit:
    return hr;
}

static HRESULT AppendRollbackCacheAction(
    __in BURN_PLAN* pPlan,
    __out BURN_CACHE_ACTION** ppCacheAction
    )
{
    HRESULT hr = S_OK;

    hr = MemEnsureArraySize(reinterpret_cast<LPVOID*>(&pPlan->rgRollbackCacheActions), pPlan->cRollbackCacheActions + 1, sizeof(BURN_CACHE_ACTION), 5);
    ExitOnFailure(hr, "Failed to grow plan's array of rollback cache actions.");

    *ppCacheAction = pPlan->rgRollbackCacheActions + pPlan->cRollbackCacheActions;
    ++pPlan->cRollbackCacheActions;

LExit:
    return hr;
}

static HRESULT AppendCleanAction(
    __in BURN_PLAN* pPlan,
    __out BURN_CLEAN_ACTION** ppCleanAction
    )
{
    HRESULT hr = S_OK;

    hr = MemEnsureArraySizeForNewItems(reinterpret_cast<LPVOID*>(&pPlan->rgCleanActions), pPlan->cCleanActions, 1, sizeof(BURN_CLEAN_ACTION), 5);
    ExitOnFailure(hr, "Failed to grow plan's array of clean actions.");


    *ppCleanAction = pPlan->rgCleanActions + pPlan->cCleanActions;
    ++pPlan->cCleanActions;

LExit:
    return hr;
}

static HRESULT AppendRestoreRelatedBundleAction(
    __in BURN_PLAN* pPlan,
    __out BURN_EXECUTE_ACTION** ppExecuteAction
    )
{
    HRESULT hr = S_OK;

    hr = MemEnsureArraySizeForNewItems(reinterpret_cast<LPVOID*>(&pPlan->rgRestoreRelatedBundleActions), pPlan->cRestoreRelatedBundleActions, 1, sizeof(BURN_EXECUTE_ACTION), 5);
    ExitOnFailure(hr, "Failed to grow plan's array of restore related bundle actions.");

    *ppExecuteAction = pPlan->rgRestoreRelatedBundleActions + pPlan->cRestoreRelatedBundleActions;
    ++pPlan->cRestoreRelatedBundleActions;

LExit:
    return hr;
}

static HRESULT ProcessPayloadGroup(
    __in BURN_PLAN* pPlan,
    __in BURN_PAYLOAD_GROUP* pPayloadGroup
    )
{
    HRESULT hr = S_OK;

    for (DWORD i = 0; i < pPayloadGroup->cItems; ++i)
    {
        BURN_PAYLOAD_GROUP_ITEM* pItem = pPayloadGroup->rgItems + i;
        BURN_PAYLOAD* pPayload = pItem->pPayload;

        pPayload->cRemainingInstances += 1;

        if (pPayload->pContainer && !pPayload->pContainer->fPlanned)
        {
            hr = PlanLayoutContainer(pPlan, pPayload->pContainer);
            ExitOnFailure(hr, "Failed to plan container: %ls", pPayload->pContainer->sczId);
        }

        if (!pPlan->sczLayoutDirectory || !pPayload->pContainer)
        {
            // Acquire + Verify + Finalize
            pPlan->qwCacheSizeTotal += 3 * pPayload->qwFileSize;

            if (!pPlan->sczLayoutDirectory)
            {
                // Staging
                pPlan->qwCacheSizeTotal += pPayload->qwFileSize;
            }
        }

        if (!pPlan->sczLayoutDirectory && pPayload->pContainer && 1 == pPayload->cRemainingInstances)
        {
            // Extract
            pPlan->qwCacheSizeTotal += pPayload->qwFileSize;
            pPayload->pContainer->qwExtractSizeTotal += pPayload->qwFileSize;
        }

        if (!pPayload->sczUnverifiedPath)
        {
            hr = CacheCalculatePayloadWorkingPath(pPlan->pCache, pPayload, &pPayload->sczUnverifiedPath);
            ExitOnFailure(hr, "Failed to calculate unverified path for payload.");
        }
    }

LExit:
    return hr;
}

static void RemoveUnnecessaryActions(
    __in BOOL fExecute,
    __in BURN_EXECUTE_ACTION* rgActions,
    __in DWORD cActions
    )
{
    LPCSTR szExecuteOrRollback = fExecute ? "execute" : "rollback";

    for (DWORD i = 0; i < cActions; ++i)
    {
        BURN_EXECUTE_ACTION* pAction = rgActions + i;

        if (BURN_EXECUTE_ACTION_TYPE_MSP_TARGET == pAction->type && pAction->mspTarget.pChainedTargetPackage)
        {
            BURN_MSPTARGETPRODUCT* pFirstTargetProduct = pAction->mspTarget.rgOrderedPatches->pTargetProduct;
            BURN_PATCH_SKIP_STATE skipState = fExecute ? pFirstTargetProduct->executeSkip : pFirstTargetProduct->rollbackSkip;
            BOOTSTRAPPER_ACTION_STATE chainedTargetPackageAction = fExecute ? pAction->mspTarget.pChainedTargetPackage->execute : pAction->mspTarget.pChainedTargetPackage->rollback;

            switch (skipState)
            {
            case BURN_PATCH_SKIP_STATE_TARGET_UNINSTALL:
                pAction->fDeleted = TRUE;
                LogId(REPORT_STANDARD, MSG_PLAN_SKIP_PATCH_ACTION, pAction->mspTarget.pPackage->sczId, LoggingActionStateToString(pAction->mspTarget.action), pAction->mspTarget.pChainedTargetPackage->sczId, LoggingActionStateToString(chainedTargetPackageAction), szExecuteOrRollback);
                break;
            case BURN_PATCH_SKIP_STATE_SLIPSTREAM:
                pAction->fDeleted = TRUE;
                LogId(REPORT_STANDARD, MSG_PLAN_SKIP_SLIPSTREAM_ACTION, pAction->mspTarget.pPackage->sczId, LoggingActionStateToString(pAction->mspTarget.action), pAction->mspTarget.pChainedTargetPackage->sczId, LoggingActionStateToString(chainedTargetPackageAction), szExecuteOrRollback);
                break;
            }
        }
    }
}

static void FinalizePatchActions(
    __in BOOL fExecute,
    __in BURN_EXECUTE_ACTION* rgActions,
    __in DWORD cActions
    )
{
    for (DWORD i = 0; i < cActions; ++i)
    {
        BURN_EXECUTE_ACTION* pAction = rgActions + i;

        if (BURN_EXECUTE_ACTION_TYPE_MSI_PACKAGE == pAction->type)
        {
            BURN_PACKAGE* pPackage = pAction->msiPackage.pPackage;
            AssertSz(BOOTSTRAPPER_ACTION_STATE_NONE < pAction->msiPackage.action, "Planned execute MSI action to do nothing");

            if (BOOTSTRAPPER_ACTION_STATE_UNINSTALL == pAction->msiPackage.action)
            {
                // If we are uninstalling the MSI, we must skip all the patches.
                for (DWORD j = 0; j < pPackage->Msi.cChainedPatches; ++j)
                {
                    BURN_CHAINED_PATCH* pChainedPatch = pPackage->Msi.rgChainedPatches + j;
                    BURN_MSPTARGETPRODUCT* pTargetProduct = pChainedPatch->pMspPackage->Msp.rgTargetProducts + pChainedPatch->dwMspTargetProductIndex;

                    if (fExecute)
                    {
                        pTargetProduct->execute = BOOTSTRAPPER_ACTION_STATE_UNINSTALL;
                        pTargetProduct->executeSkip = BURN_PATCH_SKIP_STATE_TARGET_UNINSTALL;
                    }
                    else
                    {
                        pTargetProduct->rollback = BOOTSTRAPPER_ACTION_STATE_UNINSTALL;
                        pTargetProduct->rollbackSkip = BURN_PATCH_SKIP_STATE_TARGET_UNINSTALL;
                    }
                }
            }
            else
            {
                // If the slipstream target is being installed or upgraded (not uninstalled or repaired) then we will slipstream so skip
                // the patch's standalone action. Also, if the slipstream target is being repaired and the patch is being
                // repaired, skip this operation since it will be redundant.
                //
                // The primary goal here is to ensure that a slipstream patch that is yet not installed is installed even if the MSI
                // is already on the machine. The slipstream must be installed standalone if the MSI is being repaired.
                for (DWORD j = 0; j < pPackage->Msi.cSlipstreamMspPackages; ++j)
                {
                    BURN_SLIPSTREAM_MSP* pSlipstreamMsp = pPackage->Msi.rgSlipstreamMsps + j;
                    BURN_CHAINED_PATCH* pChainedPatch = pPackage->Msi.rgChainedPatches + pSlipstreamMsp->dwMsiChainedPatchIndex;
                    BURN_MSPTARGETPRODUCT* pTargetProduct = pSlipstreamMsp->pMspPackage->Msp.rgTargetProducts + pChainedPatch->dwMspTargetProductIndex;
                    BOOTSTRAPPER_ACTION_STATE action = fExecute ? pTargetProduct->execute : pTargetProduct->rollback;
                    BOOL fSlipstream = BOOTSTRAPPER_ACTION_STATE_UNINSTALL < action &&
                                       (BOOTSTRAPPER_ACTION_STATE_REPAIR != pAction->msiPackage.action || BOOTSTRAPPER_ACTION_STATE_REPAIR == action);

                    if (fSlipstream)
                    {
                        if (fExecute)
                        {
                            pSlipstreamMsp->execute = action;
                            pTargetProduct->executeSkip = BURN_PATCH_SKIP_STATE_SLIPSTREAM;
                        }
                        else
                        {
                            pSlipstreamMsp->rollback = action;
                            pTargetProduct->rollbackSkip = BURN_PATCH_SKIP_STATE_SLIPSTREAM;
                        }
                    }
                }
            }
        }
    }
}

static void CalculateExpectedRegistrationStates(
    __in BURN_PACKAGE* rgPackages,
    __in DWORD cPackages
    )
{
    for (DWORD i = 0; i < cPackages; ++i)
    {
        BURN_PACKAGE* pPackage = rgPackages + i;

        // MspPackages can have actions throughout the plan, so the plan needed to be finalized before anything could be calculated.
        if (BURN_PACKAGE_TYPE_MSP == pPackage->type && !pPackage->fDependencyManagerWasHere)
        {
            pPackage->execute = BOOTSTRAPPER_ACTION_STATE_NONE;
            pPackage->rollback = BOOTSTRAPPER_ACTION_STATE_NONE;

            for (DWORD j = 0; j < pPackage->Msp.cTargetProductCodes; ++j)
            {
                BURN_MSPTARGETPRODUCT* pTargetProduct = pPackage->Msp.rgTargetProducts + j;

                // The highest aggregate action state found will be used.
                if (pPackage->execute < pTargetProduct->execute)
                {
                    pPackage->execute = pTargetProduct->execute;
                }

                if (pPackage->rollback < pTargetProduct->rollback)
                {
                    pPackage->rollback = pTargetProduct->rollback;
                }
            }
        }

        if (pPackage->fCanAffectRegistration)
        {
            if (BOOTSTRAPPER_ACTION_STATE_UNINSTALL < pPackage->execute)
            {
                pPackage->expectedInstallRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_PRESENT;
            }
            else if (BOOTSTRAPPER_ACTION_STATE_UNINSTALL == pPackage->execute)
            {
                pPackage->expectedInstallRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_ABSENT;
            }

            if (BURN_DEPENDENCY_ACTION_REGISTER == pPackage->dependencyExecute)
            {
                if (BURN_PACKAGE_REGISTRATION_STATE_IGNORED == pPackage->expectedCacheRegistrationState)
                {
                    pPackage->expectedCacheRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_PRESENT;
                }
                if (BURN_PACKAGE_REGISTRATION_STATE_IGNORED == pPackage->expectedInstallRegistrationState)
                {
                    pPackage->expectedInstallRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_PRESENT;
                }
            }
            else if (BURN_DEPENDENCY_ACTION_UNREGISTER == pPackage->dependencyExecute)
            {
                if (BURN_PACKAGE_REGISTRATION_STATE_PRESENT == pPackage->expectedCacheRegistrationState)
                {
                    pPackage->expectedCacheRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_IGNORED;
                }
                if (BURN_PACKAGE_REGISTRATION_STATE_PRESENT == pPackage->expectedInstallRegistrationState)
                {
                    pPackage->expectedInstallRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_IGNORED;
                }
            }
        }
    }
}

static HRESULT PlanDependencyActions(
    __in BOOL fBundlePerMachine,
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage
    )
{
    HRESULT hr = S_OK;

    hr = DependencyPlanPackageBegin(fBundlePerMachine, pPackage, pPlan);
    ExitOnFailure(hr, "Failed to begin plan dependency actions for package: %ls", pPackage->sczId);

    hr = DependencyPlanPackage(NULL, pPackage, pPlan);
    ExitOnFailure(hr, "Failed to plan package dependency actions.");

    hr = DependencyPlanPackageComplete(pPackage, pPlan);
    ExitOnFailure(hr, "Failed to complete plan dependency actions for package: %ls", pPackage->sczId);

LExit:
    return hr;
}

static HRESULT CalculateExecuteActions(
    __in BURN_PACKAGE* pPackage,
    __in_opt BURN_ROLLBACK_BOUNDARY* pActiveRollbackBoundary
    )
{
    HRESULT hr = S_OK;
    BOOL fInsideMsiTransaction = pActiveRollbackBoundary && pActiveRollbackBoundary->fTransaction;

    // Calculate execute actions.
    switch (pPackage->type)
    {
    case BURN_PACKAGE_TYPE_BUNDLE:
        hr = BundlePackageEnginePlanCalculatePackage(pPackage);
        break;

    case BURN_PACKAGE_TYPE_EXE:
        hr = ExeEnginePlanCalculatePackage(pPackage);
        break;

    case BURN_PACKAGE_TYPE_MSI:
        hr = MsiEnginePlanCalculatePackage(pPackage, fInsideMsiTransaction);
        break;

    case BURN_PACKAGE_TYPE_MSP:
        hr = MspEnginePlanCalculatePackage(pPackage, fInsideMsiTransaction);
        break;

    case BURN_PACKAGE_TYPE_MSU:
        hr = MsuEnginePlanCalculatePackage(pPackage);
        break;

    default:
        hr = E_UNEXPECTED;
        ExitOnFailure(hr, "Invalid package type.");
    }

    pPackage->compatiblePackage.fRemove = pPackage->compatiblePackage.fPlannable && pPackage->compatiblePackage.fRequested;

LExit:
    return hr;
}

static BURN_CACHE_PACKAGE_TYPE GetCachePackageType(
    __in BURN_PACKAGE* pPackage,
    __in BOOL fExecute
    )
{
    BURN_CACHE_PACKAGE_TYPE cachePackageType = BURN_CACHE_PACKAGE_TYPE_NONE;

    switch (fExecute ? pPackage->execute : pPackage->rollback)
    {
    case BOOTSTRAPPER_ACTION_STATE_NONE:
        break;
    case BOOTSTRAPPER_ACTION_STATE_UNINSTALL:
        if (BURN_PACKAGE_TYPE_EXE == pPackage->type && BURN_EXE_DETECTION_TYPE_ARP != pPackage->Exe.detectionType)
        {
            // non-ArpEntry Exe packages require the package for all operations (even uninstall).
            cachePackageType = BURN_CACHE_PACKAGE_TYPE_REQUIRED;
        }
        else if (BURN_PACKAGE_TYPE_BUNDLE == pPackage->type)
        {
            // Bundle packages prefer the cache but can fallback to the ARP registration.
            cachePackageType = BURN_CACHE_PACKAGE_TYPE_OPTIONAL;
        }
        else
        {
            // The other package types can uninstall without the original package.
            cachePackageType = BURN_CACHE_PACKAGE_TYPE_NONE;
        }
        break;
    case BOOTSTRAPPER_ACTION_STATE_INSTALL: __fallthrough;
    case BOOTSTRAPPER_ACTION_STATE_MODIFY: __fallthrough;
    case BOOTSTRAPPER_ACTION_STATE_REPAIR: __fallthrough;
    case BOOTSTRAPPER_ACTION_STATE_MINOR_UPGRADE: __fallthrough;
    default:
        // TODO: bundles could theoretically use package cache.
        cachePackageType = BURN_CACHE_PACKAGE_TYPE_REQUIRED;
        break;
    }

    return cachePackageType;
}

static BOOL ForceCache(
    __in BURN_PLAN* pPlan,
    __in BURN_PACKAGE* pPackage
    )
{
    switch (pPackage->cacheType)
    {
    case BOOTSTRAPPER_CACHE_TYPE_KEEP:
        // During actions that are expected to have source media available,
        // all packages that have cacheType set to keep should be cached if the package is going to be present.
        return (BOOTSTRAPPER_ACTION_CACHE == pPlan->action || BOOTSTRAPPER_ACTION_INSTALL == pPlan->action) &&
               BOOTSTRAPPER_REQUEST_STATE_CACHE < pPackage->requested;
    case BOOTSTRAPPER_CACHE_TYPE_FORCE:
        // All packages that have cacheType set to force should be cached if the bundle is going to be present.
        return BOOTSTRAPPER_ACTION_UNINSTALL != pPlan->action && BOOTSTRAPPER_ACTION_UNSAFE_UNINSTALL != pPlan->action;
    default:
        return FALSE;
    }
}

static void DependentRegistrationActionLog(
    __in DWORD iAction,
    __in BURN_DEPENDENT_REGISTRATION_ACTION* pAction,
    __in BOOL fRollback
    )
{
    LPCWSTR wzBase = fRollback ? L"   Rollback dependent registration" : L"   Dependent registration";
    LPCWSTR wzType = NULL;

    switch (pAction->type)
    {
    case BURN_DEPENDENT_REGISTRATION_ACTION_TYPE_REGISTER:
        wzType = L"REGISTER";
        break;

    case BURN_DEPENDENT_REGISTRATION_ACTION_TYPE_UNREGISTER:
        wzType = L"UNREGISTER";
        break;

    default:
        AssertSz(FALSE, "Unknown cache action type.");
        break;
    }

    if (wzType)
    {
        LogStringLine(PlanDumpLevel, "%ls action[%u]: %ls bundle id: %ls, provider key: %ls", wzBase, iAction, wzType, pAction->sczBundleId, pAction->sczDependentProviderKey);
    }
}

static void CacheActionLog(
    __in DWORD iAction,
    __in BURN_CACHE_ACTION* pAction,
    __in BOOL fRollback
    )
{
    LPCWSTR wzBase = fRollback ? L"   Rollback cache" : L"   Cache";
    switch (pAction->type)
    {
    case BURN_CACHE_ACTION_TYPE_CHECKPOINT:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: CHECKPOINT id: %u", wzBase, iAction, pAction->checkpoint.dwId);
        break;

    case BURN_CACHE_ACTION_TYPE_LAYOUT_BUNDLE:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: LAYOUT_BUNDLE working path: %ls, exe name: %ls", wzBase, iAction, pAction->bundleLayout.sczUnverifiedPath, pAction->bundleLayout.sczExecutableName);
        break;

    case BURN_CACHE_ACTION_TYPE_CONTAINER:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: CONTAINER container id: %ls, working path: %ls", wzBase, iAction, pAction->container.pContainer->sczId, pAction->container.pContainer->sczUnverifiedPath);
        break;

    case BURN_CACHE_ACTION_TYPE_PACKAGE:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: PACKAGE id: %ls, vital: %hs, execute cache type: %hs, rollback cache type: %hs", wzBase, iAction, pAction->package.pPackage->sczId, LoggingBoolToString(pAction->package.pPackage->fCacheVital), LoggingCachePackageTypeToString(pAction->package.pPackage->executeCacheType), LoggingCachePackageTypeToString(pAction->package.pPackage->rollbackCacheType));
        break;

    case BURN_CACHE_ACTION_TYPE_ROLLBACK_PACKAGE:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: ROLLBACK_PACKAGE id: %ls", wzBase, iAction, pAction->rollbackPackage.pPackage->sczId);
        break;

    case BURN_CACHE_ACTION_TYPE_SIGNAL_SYNCPOINT:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: SIGNAL_SYNCPOINT package id: %ls, event handle: 0x%p", wzBase, iAction, pAction->syncpoint.pPackage->sczId, pAction->syncpoint.pPackage->hCacheEvent);
        break;

    default:
        AssertSz(FALSE, "Unknown cache action type.");
        break;
    }
}

static void ExecuteActionLog(
    __in DWORD iAction,
    __in BURN_EXECUTE_ACTION* pAction,
    __in BOOL fRollback
    )
{
    LPCWSTR wzBase = fRollback ? L"   Rollback" : L"   Execute";
    switch (pAction->type)
    {
    case BURN_EXECUTE_ACTION_TYPE_CHECKPOINT:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: CHECKPOINT id: %u, msi transaction id: %ls", wzBase, iAction, pAction->checkpoint.dwId, pAction->checkpoint.pActiveRollbackBoundary && pAction->checkpoint.pActiveRollbackBoundary->fTransaction ? pAction->checkpoint.pActiveRollbackBoundary->sczId : L"(none)");
        break;

    case BURN_EXECUTE_ACTION_TYPE_PACKAGE_PROVIDER:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: PACKAGE_PROVIDER package id: %ls", wzBase, iAction, pAction->packageProvider.pPackage->sczId);
        for (DWORD j = 0; j < pAction->packageProvider.pPackage->cDependencyProviders; ++j)
        {
            const BURN_DEPENDENCY_PROVIDER* pProvider = pAction->packageProvider.pPackage->rgDependencyProviders + j;
            LogStringLine(PlanDumpLevel, "      Provider[%u]: key: %ls, action: %hs", j, pProvider->sczKey, LoggingDependencyActionToString(fRollback ? pProvider->providerRollback : pProvider->providerExecute));
        }
        break;

    case BURN_EXECUTE_ACTION_TYPE_PACKAGE_DEPENDENCY:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: PACKAGE_DEPENDENCY package id: %ls, bundle provider key: %ls", wzBase, iAction, pAction->packageDependency.pPackage->sczId, pAction->packageDependency.sczBundleProviderKey);
        for (DWORD j = 0; j < pAction->packageProvider.pPackage->cDependencyProviders; ++j)
        {
            const BURN_DEPENDENCY_PROVIDER* pProvider = pAction->packageProvider.pPackage->rgDependencyProviders + j;
            LogStringLine(PlanDumpLevel, "      Provider[%u]: key: %ls, action: %hs", j, pProvider->sczKey, LoggingDependencyActionToString(fRollback ? pProvider->dependentRollback : pProvider->dependentExecute));
        }
        break;

    case BURN_EXECUTE_ACTION_TYPE_RELATED_BUNDLE:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: RELATED_BUNDLE package id: %ls, action: %hs, ignore dependencies: %ls", wzBase, iAction, pAction->relatedBundle.pRelatedBundle->package.sczId, LoggingActionStateToString(pAction->relatedBundle.action), pAction->relatedBundle.sczIgnoreDependencies);
        break;

    case BURN_EXECUTE_ACTION_TYPE_BUNDLE_PACKAGE:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: BUNDLE_PACKAGE package id: %ls, action: %hs", wzBase, iAction, pAction->bundlePackage.pPackage->sczId, LoggingActionStateToString(pAction->bundlePackage.action));
        break;

    case BURN_EXECUTE_ACTION_TYPE_EXE_PACKAGE:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: EXE_PACKAGE package id: %ls, action: %hs", wzBase, iAction, pAction->exePackage.pPackage->sczId, LoggingActionStateToString(pAction->exePackage.action));
        break;

    case BURN_EXECUTE_ACTION_TYPE_MSI_PACKAGE:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: MSI_PACKAGE package id: %ls, action: %hs, action msi property: %ls, ui level: %u, disable externaluihandler: %hs, file versioning: %hs, log path: %ls, logging attrib: %u", wzBase, iAction, pAction->msiPackage.pPackage->sczId, LoggingActionStateToString(pAction->msiPackage.action), LoggingBurnMsiPropertyToString(pAction->msiPackage.actionMsiProperty), pAction->msiPackage.uiLevel, LoggingBoolToString(pAction->msiPackage.fDisableExternalUiHandler), LoggingMsiFileVersioningToString(pAction->msiPackage.fileVersioning), pAction->msiPackage.sczLogPath, pAction->msiPackage.dwLoggingAttributes);
        for (DWORD j = 0; j < pAction->msiPackage.pPackage->Msi.cSlipstreamMspPackages; ++j)
        {
            const BURN_SLIPSTREAM_MSP* pSlipstreamMsp = pAction->msiPackage.pPackage->Msi.rgSlipstreamMsps + j;
            LogStringLine(PlanDumpLevel, "      Patch[%u]: msp package id: %ls, action: %hs", j, pSlipstreamMsp->pMspPackage->sczId, LoggingActionStateToString(fRollback ? pSlipstreamMsp->rollback : pSlipstreamMsp->execute));
        }
        break;

    case BURN_EXECUTE_ACTION_TYPE_UNINSTALL_MSI_COMPATIBLE_PACKAGE:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: UNINSTALL_MSI_COMPATIBLE_PACKAGE package id: %ls, compatible package id: %ls, cache id: %ls, log path: %ls, logging attrib: %u", wzBase, iAction, pAction->uninstallMsiCompatiblePackage.pParentPackage->sczId, pAction->uninstallMsiCompatiblePackage.pParentPackage->compatiblePackage.compatibleEntry.sczId, pAction->uninstallMsiCompatiblePackage.pParentPackage->compatiblePackage.sczCacheId, pAction->uninstallMsiCompatiblePackage.sczLogPath, pAction->uninstallMsiCompatiblePackage.dwLoggingAttributes);
        break;

    case BURN_EXECUTE_ACTION_TYPE_MSP_TARGET:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: MSP_TARGET package id: %ls, action: %hs, target product code: %ls, target per-machine: %hs, action msi property: %ls, ui level: %u, disable externaluihandler: %hs, file versioning: %hs, log path: %ls", wzBase, iAction, pAction->mspTarget.pPackage->sczId, LoggingActionStateToString(pAction->mspTarget.action), pAction->mspTarget.sczTargetProductCode, LoggingBoolToString(pAction->mspTarget.fPerMachineTarget), LoggingBurnMsiPropertyToString(pAction->mspTarget.actionMsiProperty), pAction->mspTarget.uiLevel, LoggingBoolToString(pAction->mspTarget.fDisableExternalUiHandler), LoggingMsiFileVersioningToString(pAction->mspTarget.fileVersioning), pAction->mspTarget.sczLogPath);
        for (DWORD j = 0; j < pAction->mspTarget.cOrderedPatches; ++j)
        {
            LogStringLine(PlanDumpLevel, "      Patch[%u]: order: %u, msp package id: %ls", j, pAction->mspTarget.rgOrderedPatches[j].pTargetProduct->dwOrder, pAction->mspTarget.rgOrderedPatches[j].pPackage->sczId);
        }
        break;

    case BURN_EXECUTE_ACTION_TYPE_MSU_PACKAGE:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: MSU_PACKAGE package id: %ls, action: %hs, log path: %ls", wzBase, iAction, pAction->msuPackage.pPackage->sczId, LoggingActionStateToString(pAction->msuPackage.action), pAction->msuPackage.sczLogPath);
        break;

    case BURN_EXECUTE_ACTION_TYPE_ROLLBACK_BOUNDARY_START:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: ROLLBACK_BOUNDARY_START id: %ls, vital: %ls", wzBase, iAction, pAction->rollbackBoundary.pRollbackBoundary->sczId, pAction->rollbackBoundary.pRollbackBoundary->fVital ? L"yes" : L"no");
        break;

    case BURN_EXECUTE_ACTION_TYPE_ROLLBACK_BOUNDARY_END:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: ROLLBACK_BOUNDARY_END", wzBase, iAction);
        break;

    case BURN_EXECUTE_ACTION_TYPE_WAIT_CACHE_PACKAGE:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: WAIT_CACHE_PACKAGE id: %ls, event handle: 0x%p", wzBase, iAction, pAction->waitCachePackage.pPackage->sczId, pAction->waitCachePackage.pPackage->hCacheEvent);
        break;

    case BURN_EXECUTE_ACTION_TYPE_UNCACHE_PACKAGE:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: UNCACHE_PACKAGE id: %ls", wzBase, iAction, pAction->uncachePackage.pPackage->sczId);
        break;

    case BURN_EXECUTE_ACTION_TYPE_BEGIN_MSI_TRANSACTION:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: BEGIN_MSI_TRANSACTION id: %ls", wzBase, iAction, pAction->msiTransaction.pRollbackBoundary->sczId);
        break;

    case BURN_EXECUTE_ACTION_TYPE_COMMIT_MSI_TRANSACTION:
        LogStringLine(PlanDumpLevel, "%ls action[%u]: COMMIT_MSI_TRANSACTION id: %ls", wzBase, iAction, pAction->msiTransaction.pRollbackBoundary->sczId);
        break;

    default:
        AssertSz(FALSE, "Unknown execute action type.");
        break;
    }

    if (pAction->fDeleted)
    {
        LogStringLine(PlanDumpLevel, "      (deleted action)");
    }
}

static void RestoreRelatedBundleActionLog(
    __in DWORD iAction,
    __in BURN_EXECUTE_ACTION* pAction
    )
{
    switch (pAction->type)
    {
    case BURN_EXECUTE_ACTION_TYPE_RELATED_BUNDLE:
        LogStringLine(PlanDumpLevel, "Restore action[%u]: RELATED_BUNDLE package id: %ls, action: %hs, ignore dependencies: %ls", iAction, pAction->relatedBundle.pRelatedBundle->package.sczId, LoggingActionStateToString(pAction->relatedBundle.action), pAction->relatedBundle.sczIgnoreDependencies);
        break;

    default:
        AssertSz(FALSE, "Unknown execute action type.");
        break;
    }

    if (pAction->fDeleted)
    {
        LogStringLine(PlanDumpLevel, "      (deleted action)");
    }
}

static void CleanActionLog(
    __in DWORD iAction,
    __in BURN_CLEAN_ACTION* pAction
    )
{
    switch (pAction->type)
    {
    case BURN_CLEAN_ACTION_TYPE_COMPATIBLE_PACKAGE:
        LogStringLine(PlanDumpLevel, "   Clean action[%u]: CLEAN_COMPATIBLE_PACKAGE package id: %ls", iAction, pAction->pPackage->sczId);
        break;

    case BURN_CLEAN_ACTION_TYPE_PACKAGE:
        LogStringLine(PlanDumpLevel, "   Clean action[%u]: CLEAN_PACKAGE package id: %ls", iAction, pAction->pPackage->sczId);
        break;

    default:
        AssertSz(FALSE, "Unknown clean action type.");
        break;
    }
}

extern "C" void PlanDump(
    __in BURN_PLAN* pPlan
    )
{
    LogStringLine(PlanDumpLevel, "--- Begin plan dump ---");

    LogStringLine(PlanDumpLevel, "Plan action: %hs", LoggingBurnActionToString(pPlan->action));
    LogStringLine(PlanDumpLevel, "     bundle id: %ls", pPlan->wzBundleId);
    LogStringLine(PlanDumpLevel, "     bundle provider key: %ls", pPlan->wzBundleProviderKey);
    LogStringLine(PlanDumpLevel, "     use-forward-compatible: %hs", LoggingTrueFalseToString(pPlan->fEnabledForwardCompatibleBundle));
    LogStringLine(PlanDumpLevel, "     per-machine: %hs", LoggingTrueFalseToString(pPlan->fPerMachine));
    LogStringLine(PlanDumpLevel, "     can affect machine state: %hs", LoggingTrueFalseToString(pPlan->fCanAffectMachineState));
    LogStringLine(PlanDumpLevel, "     disable-rollback: %hs", LoggingTrueFalseToString(pPlan->fDisableRollback));
    LogStringLine(PlanDumpLevel, "     disallow-removal: %hs", LoggingTrueFalseToString(pPlan->fDisallowRemoval));
    LogStringLine(PlanDumpLevel, "     downgrade: %hs", LoggingTrueFalseToString(pPlan->fDowngrade));
    LogStringLine(PlanDumpLevel, "     registration options: %hs", LoggingRegistrationOptionsToString(pPlan->dwRegistrationOperations));
    if (pPlan->sczLayoutDirectory)
    {
        LogStringLine(PlanDumpLevel, "     layout directory: %ls", pPlan->sczLayoutDirectory);
    }

    for (DWORD i = 0; i < pPlan->cRegistrationActions; ++i)
    {
        DependentRegistrationActionLog(i, pPlan->rgRegistrationActions + i, FALSE);
    }

    for (DWORD i = 0; i < pPlan->cRollbackRegistrationActions; ++i)
    {
        DependentRegistrationActionLog(i, pPlan->rgRollbackRegistrationActions + i, TRUE);
    }

    LogStringLine(PlanDumpLevel, "Plan cache size: %llu", pPlan->qwCacheSizeTotal);
    for (DWORD i = 0; i < pPlan->cCacheActions; ++i)
    {
        CacheActionLog(i, pPlan->rgCacheActions + i, FALSE);
    }

    for (DWORD i = 0; i < pPlan->cRollbackCacheActions; ++i)
    {
        CacheActionLog(i, pPlan->rgRollbackCacheActions + i, TRUE);
    }

    LogStringLine(PlanDumpLevel, "Plan execute package count: %u", pPlan->cExecutePackagesTotal);
    LogStringLine(PlanDumpLevel, "     overall progress ticks: %u", pPlan->cOverallProgressTicksTotal);
    for (DWORD i = 0; i < pPlan->cExecuteActions; ++i)
    {
        ExecuteActionLog(i, pPlan->rgExecuteActions + i, FALSE);
    }

    for (DWORD i = 0; i < pPlan->cRollbackActions; ++i)
    {
        ExecuteActionLog(i, pPlan->rgRollbackActions + i, TRUE);
    }

    for (DWORD i = 0; i < pPlan->cRestoreRelatedBundleActions; ++i)
    {
        RestoreRelatedBundleActionLog(i, pPlan->rgRestoreRelatedBundleActions + i);
    }

    for (DWORD i = 0; i < pPlan->cCleanActions; ++i)
    {
        CleanActionLog(i, pPlan->rgCleanActions + i);
    }

    for (DWORD i = 0; i < pPlan->cPlannedProviders; ++i)
    {
        LogStringLine(PlanDumpLevel, "   Dependency action[%u]: PLANNED_PROVIDER key: %ls, name: %ls", i, pPlan->rgPlannedProviders[i].sczKey, pPlan->rgPlannedProviders[i].sczName);
    }

    LogStringLine(PlanDumpLevel, "--- End plan dump ---");
}