aboutsummaryrefslogtreecommitdiff
path: root/libbuild2/install/rule.cxx
blob: 1aa21d01d4934b4214390b5dc9e6ba3004cccb39 (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
// file      : libbuild2/install/rule.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <libbuild2/install/rule.hxx>
#include <libbuild2/install/utility.hxx> // resolve_dir() declaration

#include <libbutl/filesystem.hxx> // dir_exists(), file_exists()

#include <libbuild2/scope.hxx>
#include <libbuild2/target.hxx>
#include <libbuild2/context.hxx>
#include <libbuild2/algorithm.hxx>
#include <libbuild2/filesystem.hxx>
#include <libbuild2/diagnostics.hxx>

#include <libbuild2/install/operation.hxx>

using namespace std;
using namespace butl;

namespace build2
{
  namespace install
  {
    // Lookup the install or install.* variable. Return NULL if not found or
    // if the value is the special 'false' name (which means do not install;
    // so the result can be used as bool). T is either scope or target.
    //
    template <typename P, typename T>
    static const P*
    lookup_install (T& t, const string& var)
    {
      auto l (t[var]);

      if (!l)
        return nullptr;

      const P& r (cast<P> (l));
      return r.simple () && r.string () == "false" ? nullptr : &r;
    }

    // Note that the below rules are called for both install and
    // update-for-install.
    //
    // @@ TODO: we clearly need a module class.
    //
    static inline const variable&
    var_install (const scope& rs)
    {
      context& ctx (rs.ctx);

      return *rs.root_extra->operations[
        (ctx.current_outer_oif != nullptr
         ? ctx.current_outer_oif
         : ctx.current_inner_oif)->id].ovar;
    }

    // alias_rule
    //
    const alias_rule alias_rule::instance;

    bool alias_rule::
    match (action, target&) const
    {
      // We always match.
      //
      // Note that we are called both as the outer part during the update-for-
      // un/install pre-operation and as the inner part during the un/install
      // operation itself.
      //
      return true;
    }

    pair<const target*, uint64_t> alias_rule::
    filter (const scope* is,
            action a, const target& t, prerequisite_iterator& i,
            match_extra& me) const
    {
      assert (i->member == nullptr);
      return filter (is, a, t, i->prerequisite, me);
    }

    pair<const target*, uint64_t> alias_rule::
    filter (const scope* is,
            action, const target& t, const prerequisite& p,
            match_extra&) const
    {
      const target& pt (search (t, p));
      const uint64_t options (match_extra::all_options); // No definition.
      return make_pair (is == nullptr || pt.in (*is) ? &pt : nullptr, options);
    }

    recipe alias_rule::
    apply (action a, target& t, match_extra& me) const
    {
      return apply_impl (a, t, me);
    }

    recipe alias_rule::
    apply (action, target&) const
    {
      assert (false); // Never called.
      return nullptr;
    }

    recipe alias_rule::
    apply_impl (action a, target& t, match_extra& me, bool reapply) const
    {
      tracer trace ("install::alias_rule::apply");

      assert (!reapply || a.operation () != update_id);

      // Pass-through to our installable prerequisites.
      //
      // @@ Shouldn't we do match in parallel (here and below)?
      //
      optional<const scope*> is; // Installation scope (resolve lazily).

      auto& pts (t.prerequisite_targets[a]);
      auto pms (group_prerequisite_members (a, t, members_mode::never));
      for (auto i (pms.begin ()), e (pms.end ()); i != e; ++i)
      {
        // NOTE: see essentially the same logic in reapply_impl() below.
        //
        const prerequisite& p (i->prerequisite);

        // Ignore excluded.
        //
        include_type pi (include (a, t, p));

        if (!pi)
          continue;

        // Ignore unresolved targets that are imported from other projects.
        // We are definitely not installing those.
        //
        if (p.proj)
          continue;

        // Let a customized rule have its say.
        //
        // Note: we assume that if the filter enters the group, then it
        // iterates over all its members.
        //
        if (!is)
          is = a.operation () != update_id ? install_scope (t) : nullptr;

        pair<const target*, uint64_t> fr (filter (*is, a, t, i, me));

        const target* pt (fr.first);
        uint64_t options (fr.second);

        lookup l;

        if (pt == nullptr)
        {
          l5 ([&]{trace << "ignoring " << p << " (filtered out)";});
        }
        // Check if this prerequisite is explicitly "not installable", that
        // is, there is the 'install' variable and its value is false.
        //
        // At first, this might seem redundand since we could have let the
        // file_rule below take care of it. The nuance is this: this
        // prerequsite can be in a different subproject that hasn't loaded the
        // install module (and therefore has no file_rule registered). The
        // typical example would be the 'tests' subproject.
        //
        // Note: not the same as lookup_install() above.
        //
        else if ((l = (*pt)[var_install (*p.scope.root_scope ())]) &&
                 cast<path> (l).string () == "false")
        {
          l5 ([&]{trace << "ignoring " << *pt << " (not installable)";});
          pt = nullptr;
        }
        // If this is not a file-based target (e.g., a target group such as
        // libu{}) then ignore it if there is no rule to install.
        //
        else if (pt->is_a<file> ())
        {
          match_sync (a, *pt, options);
        }
        else if (!try_match_sync (a, *pt, options).first)
        {
          l5 ([&]{trace << "ignoring " << *pt << " (no rule)";});
          pt = nullptr;
        }

        if (pt != nullptr || reapply)
        {
          // Use auxiliary data for a NULL entry to distinguish between
          // filtered out (1) and ignored for other reasons (0).
          //
          pts.push_back (
            prerequisite_target (pt, pi, fr.first == nullptr ? 1 : 0));
        }
      }

      return default_recipe;
    }

    void alias_rule::
    reapply_impl (action a, target& t, match_extra& me) const
    {
      tracer trace ("install::alias_rule::reapply");

      assert (a.operation () != update_id);

      optional<const scope*> is;

      // Iterate over prerequisites and prerequisite targets in parallel.
      //
      auto& pts (t.prerequisite_targets[a]);
      size_t j (0), n (pts.size ()), en (0);

      auto pms (group_prerequisite_members (a, t, members_mode::never));
      for (auto i (pms.begin ()), e (pms.end ());
           i != e && j != n;
           ++i, ++j, ++en)
      {
        // The same logic as in apply() above except that we skip
        // prerequisites that were not filtered out.
        //
        const prerequisite& p (i->prerequisite);

        include_type pi (include (a, t, p));
        if (!pi)
          continue;

        if (p.proj)
          continue;

        prerequisite_target& pto (pts[j]);

        if (pto.target != nullptr || pto.data == 0)
          continue;

        if (!is)
          is = a.operation () != update_id ? install_scope (t) : nullptr;

        pair<const target*, uint64_t> fr (filter (*is, a, t, i, me));

        const target* pt (fr.first);
        uint64_t options (fr.second);

        lookup l;

        if (pt == nullptr)
        {
          l5 ([&]{trace << "ignoring " << p << " (filtered out)";});
        }
        else if ((l = (*pt)[var_install (*p.scope.root_scope ())]) &&
                 cast<path> (l).string () == "false")
        {
          l5 ([&]{trace << "ignoring " << *pt << " (not installable)";});
          pt = nullptr;
        }
        else if (pt->is_a<file> ())
        {
          match_sync (a, *pt, options);
        }
        else if (!try_match_sync (a, *pt, options).first)
        {
          l5 ([&]{trace << "ignoring " << *pt << " (no rule)";});
          pt = nullptr;
        }

        pto = prerequisite_target (pt, pi, fr.first == nullptr ? 1 : 0);
      }

      assert (en == n); // Did not call apply() with true for reapply?
    }

    // group_rule
    //
    const group_rule group_rule::instance (false /* see_through_only */);

    bool group_rule::
    match (action a, target& t) const
    {
      return (!see_through_only || t.type ().see_through ()) &&
        alias_rule::match (a, t);
    }

    bool group_rule::
    filter (action, const target&, const target&) const
    {
      return true;
    }

    pair<const target*, uint64_t> group_rule::
    filter (const scope* is,
            action, const target& t, const prerequisite& p,
            match_extra&) const
    {
      const uint64_t options (match_extra::all_options); // No definition.
      pair<const target*, uint64_t> r (nullptr, options);

      // The same logic as in file_rule::filter() below.
      //
      if (p.is_a<exe> ())
      {
        const scope& rs (*p.scope.root_scope ());

        if (p.vars.empty () ||
            cast_empty<path> (p.vars[var_install (rs)]).string () != "true")
          return r;
      }

      const target& pt (search (t, p));
      if (is == nullptr || pt.in (*is))
        r.first = &pt;

      return r;
    }

    recipe group_rule::
    apply (action a, target& t, match_extra& me) const
    {
      tracer trace ("install::group_rule::apply");

      // Resolve group members.
      //
      // Remember that we are called twice: first during update for install
      // (pre-operation) and then during install. During the former, we rely
      // on the normal update rule to resolve the group members. During the
      // latter, there will be no rule to do this but the group will already
      // have been resolved by the pre-operation.
      //
      // If the rule could not resolve the group, then we ignore it.
      //
      group_view gv (a.outer ()
                     ? resolve_members (a, t)
                     : t.group_members (a));

      if (gv.members != nullptr && gv.count != 0)
      {
        const scope& rs (t.root_scope ());

        auto& pts (t.prerequisite_targets[a]);
        for (size_t i (0); i != gv.count; ++i)
        {
          const target* mt (gv.members[i]);

          if (mt == nullptr)
            continue;

          // Let a customized rule have its say.
          //
          if (!filter (a, t, *mt))
          {
            l5 ([&]{trace << "ignoring " << *mt << " (filtered out)";});
            continue;
          }

          // See if we were explicitly instructed not to touch this target
          // (the same semantics as in the prerequisites match).
          //
          // Note: not the same as lookup_install() above.
          //
          auto l ((*mt)[var_install (rs)]);
          if (l && cast<path> (l).string () == "false")
          {
            l5 ([&]{trace << "ignoring " << *mt << " (not installable)";});
            continue;
          }

          match_sync (a, *mt);
          pts.push_back (mt); // Never ad hoc.
        }
      }

      // Delegate to the base rule.
      //
      return alias_rule::apply (a, t, me);
    }


    // file_rule
    //
    const file_rule file_rule::instance;

    bool file_rule::
    match (action, target&) const
    {
      // We always match, even if this target is not installable (so that we
      // can ignore it; see apply()).
      //
      return true;
    }

    bool file_rule::
    filter (action, const target&, const target&) const
    {
      return true;
    }

    pair<const target*, uint64_t> file_rule::
    filter (const scope* is,
            action a, const target& t, prerequisite_iterator& i,
            match_extra& me) const
    {
      assert (i->member == nullptr);
      return filter (is, a, t, i->prerequisite, me);
    }

    pair<const target*, uint64_t> file_rule::
    filter (const scope* is,
            action, const target& t, const prerequisite& p,
            match_extra&) const
    {
      const uint64_t options (match_extra::all_options); // No definition.
      pair<const target*, uint64_t> r (nullptr, options);

      // See also group_rule::filter() with identical semantics.
      //
      if (p.is_a<exe> ())
      {
        const scope& rs (*p.scope.root_scope ());

        // Note that while include() checks for install=false, here we need to
        // check for explicit install=true. We could have re-used the lookup
        // performed by include(), but then we would have had to drag it
        // through and also diagnose any invalid values.
        //
        if (p.vars.empty () ||
            cast_empty<path> (p.vars[var_install (rs)]).string () != "true")
          return r;
      }

      const target& pt (search (t, p));
      if (is == nullptr || pt.in (*is))
        r.first = &pt;

      return r;
    }

    recipe file_rule::
    apply (action a, target& t, match_extra& me) const
    {
      recipe r (apply_impl (a, t, me));
      return r != nullptr ? move (r) : noop_recipe;
    }

    recipe file_rule::
    apply (action, target&) const
    {
      assert (false); // Never called.
      return nullptr;
    }

    recipe file_rule::
    apply_impl (action a, target& t, match_extra& me, bool reapply) const
    {
      tracer trace ("install::file_rule::apply");

      assert (!reapply || a.operation () != update_id);

      // Note that we are called both as the outer part during the update-for-
      // un/install pre-operation and as the inner part during the un/install
      // operation itself.
      //
      // In both cases we first determine if the target is installable and
      // return noop if it's not. Otherwise, in the first case (update-for-
      // un/install) we delegate to the normal update and in the second
      // (un/install) -- perform the install.
      //
      if (!lookup_install<path> (t, "install"))
        return empty_recipe;

      // In both cases, the next step is to search, match, and collect all the
      // installable prerequisites.
      //
      // But first, in case of the update pre-operation, match the inner rule
      // (actual update). We used to do this after matching the prerequisites
      // but the inner rule may provide some rule-specific information (like
      // the target extension for exe{}) that may be required during the
      // prerequisite search (like the base name for in{}; this no longer
      // reproduces likely due to the changes to exe{} extension derivation
      // but a contrived arrangement can still be made to trigger this).
      //
      // But then we discovered that doing this before the prerequisites messes
      // up with the for-install signaling. Specifically, matching the
      // prerequisites may signal that they are being updated for install,
      // for example, for a library via a metadata library used in a moc
      // recipe. While matching the inner rule may trigger updating during
      // match of such prerequisites, for example, a source file generated by
      // that moc recipe that depends on this metadata library. If we match
      // prerequisites before, then the library that is pulled by the metadata
      // library will be updated before we had a chance to signal that it
      // should be updated for install.
      //
      // To try to accommodate both cases (as best as we can) we now split the
      // inner rule match into two steps: we do the match before and apply
      // after. This allows rules that deal with tricky prerequisites like
      // in{} to assign the target path in match() instead of apply() (see
      // in::rule, for example).
      //
#if 0
      optional<bool> unchanged;
      if (a.operation () == update_id)
        unchanged = match_inner (a, t, unmatch::unchanged).first;
#else
      action ia (a.inner_action ());
      if (a.operation () == update_id)
        match_only_sync (ia, t);
#endif

      optional<const scope*> is; // Installation scope (resolve lazily).

      auto& pts (t.prerequisite_targets[a]);
      auto pms (group_prerequisite_members (a, t, members_mode::never));
      for (auto i (pms.begin ()), e (pms.end ()); i != e; ++i)
      {
        // NOTE: see essentially the same logic in reapply_impl() below.
        //
        const prerequisite& p (i->prerequisite);

        // Ignore excluded.
        //
        include_type pi (include (a, t, p));

        if (!pi)
          continue;

        // Ignore unresolved targets that are imported from other projects.
        // We are definitely not installing those.
        //
        if (p.proj)
          continue;

        // Let a customized rule have its say.
        //
        // Note: we assume that if the filter enters the group, then it
        // iterates over all its members.
        //
        if (!is)
          is = a.operation () != update_id ? install_scope (t) : nullptr;

        pair<const target*, uint64_t> fr (filter (*is, a, t, i, me));

        const target* pt (fr.first);
        uint64_t options (fr.second);

        lookup l;

        if (pt == nullptr)
        {
          l5 ([&]{trace << "ignoring " << p << " (filtered out)";});
        }
        //
        // See if we were explicitly instructed not to touch this target (the
        // same semantics as in alias_rule).
        //
        // Note: not the same as lookup_install() above.
        //
        else if ((l = (*pt)[var_install (*p.scope.root_scope ())]) &&
                 cast<path> (l).string () == "false")
        {
          l5 ([&]{trace << "ignoring " << *pt << " (not installable)";});
          pt = nullptr;
        }
        else if (pt->is_a<file> ())
        {
          // If the matched rule returned noop_recipe, then the target state
          // is set to unchanged as an optimization. Use this knowledge to
          // optimize things on our side as well since this will help a lot
          // when updating static installable content (headers, documentation,
          // etc).
          //
          // Regarding options, the expectation here is that they are not used
          // for the update operation. And for install/uninstall, if they are
          // used, then they don't effect whether the target is unchanged. All
          // feels reasonable.
          //
          if (match_sync (a, *pt, unmatch::unchanged, options).first)
            pt = nullptr;
        }
        else if (!try_match_sync (a, *pt, options).first)
        {
          l5 ([&]{trace << "ignoring " << *pt << " (no rule)";});
          pt = nullptr;
        }

        if (pt != nullptr || reapply)
        {
          // Use auxiliary data for a NULL entry to distinguish between
          // filtered out (1) and ignored for other reasons (0).
          //
          pts.push_back (
            prerequisite_target (pt, pi, fr.first == nullptr ? 1 : 0));
        }
      }

#if 1
      optional<bool> unchanged;
      if (a.operation () == update_id)
        unchanged = match_sync (ia, t, unmatch::unchanged).first;
#endif

      if (a.operation () == update_id)
      {
        return *unchanged
          ? (pts.empty () ? noop_recipe : default_recipe)
          : &perform_update;
      }
      else
      {
        return [this] (action a, const target& t)
        {
          return a.operation () == install_id
            ? perform_install   (a, t)
            : perform_uninstall (a, t);
        };
      }
    }

    void file_rule::
    reapply_impl (action a, target& t, match_extra& me) const
    {
      tracer trace ("install::file_rule::reapply");

      assert (a.operation () != update_id);

      optional<const scope*> is;

      // Iterate over prerequisites and prerequisite targets in parallel.
      //
      auto& pts (t.prerequisite_targets[a]);
      size_t j (0), n (pts.size ()), en (0);

      auto pms (group_prerequisite_members (a, t, members_mode::never));
      for (auto i (pms.begin ()), e (pms.end ());
           i != e && j != n;
           ++i, ++j, ++en)
      {
        // The same logic as in apply() above except that we skip
        // prerequisites that were not filtered out.
        //
        const prerequisite& p (i->prerequisite);

        include_type pi (include (a, t, p));
        if (!pi)
          continue;

        if (p.proj)
          continue;

        prerequisite_target& pto (pts[j]);

        if (pto.target != nullptr || pto.data == 0)
          continue;

        if (!is)
          is = a.operation () != update_id ? install_scope (t) : nullptr;

        pair<const target*, uint64_t> fr (filter (*is, a, t, i, me));

        const target* pt (fr.first);
        uint64_t options (fr.second);

        lookup l;

        if (pt == nullptr)
        {
          l5 ([&]{trace << "ignoring " << p << " (filtered out)";});
        }
        else if ((l = (*pt)[var_install (*p.scope.root_scope ())]) &&
                 cast<path> (l).string () == "false")
        {
          l5 ([&]{trace << "ignoring " << *pt << " (not installable)";});
          pt = nullptr;
        }
        else if (pt->is_a<file> ())
        {
          if (match_sync (a, *pt, unmatch::unchanged, options).first)
            pt = nullptr;
        }
        else if (!try_match_sync (a, *pt, options).first)
        {
          l5 ([&]{trace << "ignoring " << *pt << " (no rule)";});
          pt = nullptr;
        }

        pto = prerequisite_target (pt, pi, fr.first == nullptr ? 1 : 0);
      }

      assert (en == n); // Did not call apply() with true for reapply?
    }

    target_state file_rule::
    perform_update (action a, const target& t)
    {
      // First execute the inner recipe then prerequisites.
      //
      target_state ts (execute_inner (a, t));

      if (t.prerequisite_targets[a].size () != 0)
        ts |= straight_execute_prerequisites (a, t);

      return ts;
    }

    bool file_rule::
    install_extra (const file&, const install_dir&) const
    {
      return false;
    }

    bool file_rule::
    uninstall_extra (const file&, const install_dir&) const
    {
      return false;
    }

    auto_rmfile file_rule::
    install_pre (const file& t, const install_dir&) const
    {
      return auto_rmfile (t.path (), false /* active */);
    }

    bool file_rule::
    install_post (const file& t, const install_dir& id, auto_rmfile&&) const
    {
      return install_extra (t, id);
    }

    struct install_dir
    {
      dir_path dir;

      // If not NULL, then point to the corresponding install.* value.
      //
      const string*  sudo     = nullptr;
      const path*    cmd      = nullptr;
      const strings* options  = nullptr;
      const string*  mode     = nullptr;
      const string*  dir_mode = nullptr;

      explicit
      install_dir (dir_path d = dir_path ()): dir (move (d)) {}

      install_dir (dir_path d, const install_dir& b)
          : dir (move (d)),
            sudo (b.sudo),
            cmd (b.cmd),
            options (b.options),
            mode (b.mode),
            dir_mode (b.dir_mode) {}
    };

    using install_dirs = vector<install_dir>;

    // Calculate a subdirectory based on l's location (*.subdirs) and if not
    // empty add it to install_dirs. Return the new last element.
    //
    static install_dir&
    resolve_subdir (install_dirs& rs,
                    const target& t,
                    const scope& s,
                    const lookup& l)
    {
      // Find the scope from which this value came and use as a base
      // to calculate the subdirectory.
      //
      for (const scope* p (&s); p != nullptr; p = p->parent_scope ())
      {
        if (l.belongs (*p, true)) // Include target type/pattern-specific.
        {
          // The target can be in out or src.
          //
          const dir_path& d (t.out_dir ().leaf (p->out_path ()));

          // Add it as another leading directory rather than modifying
          // the last one directly; somehow, it feels right. Note: the
          // result is normalized.
          //
          if (!d.empty ())
            rs.emplace_back (rs.back ().dir / d, rs.back ());
          break;
        }
      }

      return rs.back ();
    }

    // Resolve installation directory name to absolute and normalized
    // directory path. Return all the super-directories leading up to the
    // destination (last).
    //
    // If target is not NULL, then also handle the subdirs logic.
    //
    // @@ TODO: detect cycles (maybe by keeping a stack-based linked list).
    //
    static install_dirs
    resolve (const scope& s,
             const target* t,
             dir_path d,
             bool fail_unknown = true,
             const string* var = nullptr)
    {
      install_dirs rs;

      if (d.absolute ())
        rs.emplace_back (move (d.normalize ()));
      else
      {
        // If it is relative, then the first component is treated as the
        // installation directory name, e.g., bin, sbin, lib, etc. Look it
        // up and recurse.
        //
        if (d.empty ())
          fail << "empty installation directory name";

        const string& sn (*d.begin ());
        const string var ("install." + sn);
        if (const dir_path* dn = lookup_install<dir_path> (s, var))
        {
          if (dn->empty ())
            fail << "empty installation directory for name " << sn <<
              info << "did you specified empty config." << var << "?";

          rs = resolve (s, t, *dn, fail_unknown, &var);

          if (rs.empty ())
          {
            assert (!fail_unknown);
            return rs; // Empty.
          }

          d = rs.back ().dir / dir_path (++d.begin (), d.end ());
          rs.emplace_back (move (d.normalize ()), rs.back ());
        }
        else
        {
          if (fail_unknown)
            fail << "unknown installation directory name '" << sn << "'" <<
              info << "did you forget to specify config." << var << "?" <<
              info << "specify !config." << var << "=... if installing "
                   << "from multiple projects";

          return rs; // Empty.
        }
      }

      install_dir* r (&rs.back ());

      // Override components in install_dir if we have our own.
      //
      if (var != nullptr)
      {
        if (auto l = s[*var + ".sudo"])     r->sudo     = &cast<string> (l);
        if (auto l = s[*var + ".cmd"])      r->cmd      = &cast<path> (l);
        if (auto l = s[*var + ".mode"])     r->mode     = &cast<string> (l);
        if (auto l = s[*var + ".dir_mode"]) r->dir_mode = &cast<string> (l);
        if (auto l = s[*var + ".options"])  r->options  = &cast<strings> (l);

        if (t != nullptr)
        {
          if (auto l = s[*var + ".subdirs"])
          {
            if (cast<bool> (l))
              r = &resolve_subdir (rs, *t, s, l);
          }
        }
      }

      // Set globals for unspecified components.
      //
      if (r->sudo == nullptr)
        r->sudo = cast_null<string> (s["config.install.sudo"]);

      if (r->cmd == nullptr)
        r->cmd = cast_null<path> (s["config.install.cmd"]);

      if (r->options == nullptr)
        r->options = cast_null<strings> (s["config.install.options"]);

      if (r->mode == nullptr)
        r->mode = cast_null<string> (s["config.install.mode"]);

      if (r->dir_mode == nullptr)
        r->dir_mode = cast_null<string> (s["config.install.dir_mode"]);

      return rs;
    }

    static dir_path
    resolve_dir (const scope& s, const target* t,
                 dir_path d, dir_path rb,
                 bool fail_unknown)
    {
      install_dirs rs (resolve (s, t, move (d), fail_unknown));

      if (rs.empty ())
        return dir_path ();

      dir_path r (move (rs.back ().dir));

      if (!rb.empty ())
      {
        dir_path b (resolve (s, t, move (rb), false).back ().dir);

        try
        {
          r = r.relative (b);
        }
        catch (const invalid_path&)
        {
          fail << "unable to make installation directory " << r
               << " relative to " << b;
        }
      }

      return r;
    }

    dir_path
    resolve_dir (const target& t, dir_path d, dir_path rb, bool fail_unknown)
    {
      return resolve_dir (t.base_scope (), &t, move (d), move (rb), fail_unknown);
    }

    dir_path
    resolve_dir (const scope& s, dir_path d, dir_path rb, bool fail_unknown)
    {
      return resolve_dir (s, nullptr, move (d), move (rb), fail_unknown);
    }

    static inline install_dirs
    resolve (const target& t, dir_path d, bool fail_unknown = true)
    {
      return resolve (t.base_scope (), &t, move (d), fail_unknown);
    }

    path
    resolve_file (const file& f)
    {
      // Note: similar logic to perform_install().
      //
      const path* p (lookup_install<path> (f, "install"));

      if (p == nullptr) // Not installable.
        return path ();

      bool n (!p->to_directory ());
      dir_path d (n ? p->directory () : path_cast<dir_path> (*p));

      if (n && d.empty ())
        fail << "relative installation file path '" << p
             << "' has no directory component";

      install_dirs ids (resolve (f, d));

      if (!n)
      {
        if (auto l = f["install.subdirs"])
        {
          if (cast<bool> (l))
            resolve_subdir (ids, f, f.base_scope (), l);
        }
      }

      return ids.back ().dir / (n ? p->leaf () : f.path ().leaf ());
    }

    // On Windows we use MSYS2 install.exe and MSYS2 by default ignores
    // filesystem permissions (noacl mount option). And this means, for
    // example, that .exe that we install won't be runnable by Windows (MSYS2
    // itself will still run them since it recognizes the file extension).
    //
    // NOTE: this is no longer the case and we now use noacl (and acl causes
    // other problems; see baseutils fstab for details).
    //
    // The way we work around this (at least in our distribution of the MSYS2
    // tools) is by changing the mount option for cygdrives (/c, /d, etc) to
    // acl. But that's not all: we also have to install via a path that "hits"
    // one of those mount points, c:\foo won't work, we have to use /c/foo.
    // So this function translates an absolute Windows path to its MSYS
    // representation.
    //
    // Note that we return the result as a string, not dir_path since path
    // starting with / are illegal on Windows. Also note that the result
    // doesn't have the trailing slash.
    //
    static string
    msys_path (const dir_path& d)
    {
      assert (d.absolute ());
      string s (d.representation ());

      // First replace ':' with the drive letter (so the path is no longer
      // absolute) but postpone setting the first character to / until we are
      // a string.
      //
      s[1] = lcase (s[0]);
      s = dir_path (move (s)).posix_string ();
      s[0] = '/';

      return s;
    }

    void file_rule::
    install_d (const scope& rs,
               const install_dir& base,
               const dir_path& d,
               const file& t,
               uint16_t verbosity)
    {
      assert (d.absolute ());

      context& ctx (rs.ctx);

      // Here is the problem: if this is a dry-run, then we will keep showing
      // the same directory creation commands over and over again (because we
      // don't actually create them). There are two alternative ways to solve
      // this: actually create the directories or simply don't show anything.
      // While we use the former approach during update (see mkdir() in
      // filesystem), here it feels like we really shouldn't be touching the
      // destination filesystem. Plus, not showing anything will be symmetric
      // with uninstall since the directories won't be empty (because we don't
      // actually uninstall any files).
      //
      // Note that this also means we won't have the directory entries in the
      // manifest created with dry-run. Probably not a big deal.
      //
      if (ctx.dry_run || !filter_entry (rs, d, path (), entry_type::directory))
        return;

      dir_path chd (chroot_path (rs, d));

      try
      {
        if (dir_exists (chd)) // May throw (e.g., EACCES).
          return;
      }
      catch (const system_error& e)
      {
        fail << "invalid installation directory " << chd << ": " << e;
      }

      // While install -d will create all the intermediate components between
      // base and dir, we do it explicitly, one at a time. This way the output
      // is symmetrical to uninstall() below.
      //
      // Note that if the chroot directory does not exist, then install -d
      // will create it and we don't bother removing it.
      //
      if (d != base.dir)
      {
        dir_path pd (d.directory ());

        if (pd != base.dir)
          install_d (rs, base, pd, t, verbosity);
      }

      cstrings args;

      string reld (
        ctx.build_host->class_ == "windows"
        ? msys_path (chd)
        : relative (chd).string ());

      if (base.sudo != nullptr)
        args.push_back (base.sudo->c_str ());

      // Wouldn't be here otherwise.
      //
      assert (base.cmd != nullptr && base.dir_mode != nullptr);

      args.push_back (base.cmd->string ().c_str ());
      args.push_back ("-d");

      if (base.options != nullptr)
        append_options (args, *base.options);

      args.push_back ("-m");
      args.push_back (base.dir_mode->c_str ());
      args.push_back (reld.c_str ());
      args.push_back (nullptr);

      process_path pp (run_search (args[0]));

      if (verb >= verbosity)
      {
        if (verb >= 2)
          print_process (args);
        else if (verb)
          print_diag ("install -d", chd); // See also `install -l` below.
      }

      run (ctx,
           pp, args,
           verb >= verbosity ? 1 : verb_never /* finish_verbosity */);

      context_data::manifest_install_d (ctx, t, d, *base.dir_mode);
    }

    void file_rule::
    install_f (const scope& rs,
               const install_dir& base,
               const path& name,
               const file& t,
               const path& f,
               uint16_t verbosity)
    {
      assert (name.empty () || name.simple ());

      context& ctx (rs.ctx);

      const path& leaf (name.empty () ? f.leaf () : name);

      if (!filter_entry (rs, base.dir, leaf, entry_type::regular))
        return;

      path relf (relative (f));

      dir_path chd (chroot_path (rs, base.dir));

      string reld (
        ctx.build_host->class_ == "windows"
        ? msys_path (chd)
        : relative (chd).string ());

      if (!name.empty ())
      {
        reld += path::traits_type::directory_separator;
        reld += name.string ();
      }

      cstrings args;

      if (base.sudo != nullptr)
        args.push_back (base.sudo->c_str ());

      // Wouldn't be here otherwise.
      //
      assert (base.cmd != nullptr && base.mode != nullptr);

      args.push_back (base.cmd->string ().c_str ());

      if (base.options != nullptr)
        append_options (args, *base.options);

      args.push_back ("-m");
      args.push_back (base.mode->c_str ());
      args.push_back (relf.string ().c_str ());
      args.push_back (reld.c_str ());
      args.push_back (nullptr);

      process_path pp (run_search (args[0]));

      if (verb >= verbosity)
      {
        if (verb >= 2)
          print_process (args);
        else if (verb)
        {
          if (name.empty ())
            print_diag ("install", t, chd);
          else
            print_diag ("install", t, chd / name);
        }
      }

      if (!ctx.dry_run)
        run (ctx,
             pp, args,
             verb >= verbosity ? 1 : verb_never /* finish_verbosity */);

      context_data::manifest_install_f (ctx, t, base.dir, leaf, *base.mode);
    }

    void file_rule::
    install_l (const scope& rs,
               const install_dir& base,
               const path& link,
               const file& target,
               const path& link_target,
               uint16_t verbosity)
    {
      assert (link.simple () && !link.empty ());

      context& ctx (rs.ctx);

      if (!filter_entry (rs, base.dir, link, entry_type::symlink))
        return;

      if (link_target.absolute () &&
          cast_false<bool> (rs["install.relocatable"]))
      {
        fail << "absolute symlink target " << link_target.string ()
             << " in relocatable installation";
      }

      dir_path chd (chroot_path (rs, base.dir));

      path rell (relative (chd));
      rell /= link;

      // We can create a symlink directly without calling ln. This, however,
      // won't work if we have sudo. Also, we would have to deal with existing
      // destinations (ln's -f takes care of that). So we are just going to
      // always (sudo or not) use ln unless we are on Windows, where we will
      // use mkanylink().
      //
#ifndef _WIN32
      const char* args_a[] = {
        base.sudo != nullptr ? base.sudo->c_str () : nullptr,
        "ln",
        "-sf",
        link_target.string ().c_str (),
        rell.string ().c_str (),
        nullptr};

      const char** args (&args_a[base.sudo == nullptr ? 1 : 0]);

      process_path pp (run_search (args[0]));

      if (verb >= verbosity)
      {
        if (verb >= 2)
          print_process (args);
        else if (verb)
        {
          // Without a flag it's unclear (unlike with ln) that we are creating
          // a link. FreeBSD install(1) has the -l flag with the appropriate
          // semantics. For consistency, we also pass -d above.
          //
          print_diag ("install -l", link_target, chd / link);
        }
      }

      if (!ctx.dry_run)
        run (ctx,
             pp, args,
             verb >= verbosity ? 1 : verb_never /* finish_verbosity */);
#else
      // The -f part.
      //
      // We use uninstall_f() since reliably removing stuff on Windows is no
      // easy feat (see uninstall_f() for details).
      //
      uninstall_f (rs, base, nullptr /* target */, link, 3 /* verbosity */);

      if (verb >= verbosity)
      {
        if (verb >= 2)
          text << "ln -sf " << link_target.string () << ' ' << rell.string ();
        else if (verb)
          print_diag ("install -l", link_target, chd / link);
      }

      if (!ctx.dry_run)
      try
      {
        mkanylink (link_target, rell, true /* copy */);
      }
      catch (const pair<entry_type, system_error>& e)
      {
        const char* w (e.first == entry_type::regular ? "copy"     :
                       e.first == entry_type::symlink ? "symlink"  :
                       e.first == entry_type::other   ? "hardlink" :
                       nullptr);

        fail << "unable to make " << w << ' ' << rell << ": " << e.second;
      }
#endif

      context_data::manifest_install_l (ctx,
                                        target,
                                        link_target,
                                        base.dir,
                                        link);
    }

    target_state file_rule::
    perform_install (action a, const target& xt) const
    {
      const file& t (xt.as<file> ());
      const path& tp (t.path ());

      // Path should have been assigned by update unless it is unreal.
      //
      assert (!tp.empty () || t.mtime () == timestamp_unreal);

      const scope& rs (t.root_scope ());

      auto install_target = [&rs, this] (const file& t,
                                         const path& p,
                                         uint16_t verbosity)
      {
        // Note: similar logic to resolve_file().
        //
        bool n (!p.to_directory ());
        dir_path d (n ? p.directory () : path_cast<dir_path> (p));

        if (n && d.empty ())
          fail << "relative installation file path '" << p
               << "' has no directory component";

        // Resolve target directory.
        //
        install_dirs ids (resolve (t, d));

        // Handle install.subdirs if one was specified. Unless the target path
        // includes the file name in which case we assume it's a "final" path.
        //
        if (!n)
        {
          if (auto l = t["install.subdirs"])
          {
            if (cast<bool> (l))
              resolve_subdir (ids, t, t.base_scope (), l);
          }
        }

        // Create leading directories. Note that we are using the leading
        // directory (if there is one) for the creation information (mode,
        // sudo, etc).
        //
        for (auto i (ids.begin ()), j (i); i != ids.end (); j = i++)
          install_d (rs, *j, i->dir, t, verbosity); // install -d

        install_dir& id (ids.back ());

        // Override mode if one was specified.
        //
        if (auto l = t["install.mode"])
          id.mode = &cast<string> (l);

        // Install the target.
        //
        auto_rmfile f (install_pre (t, id));

        // If install_pre() returned a different file name, make sure we
        // install it as the original.
        //
        const path& tp (t.path ());
        const path& fp (f.path);

        install_f (
          rs,
          id,
          n ? p.leaf () : fp.leaf () != tp.leaf () ? tp.leaf () : path (),
          t,
          f.path,
          verbosity);

        install_post (t, id, move (f));
      };

      // First handle installable prerequisites.
      //
      target_state r (straight_execute_prerequisites (a, t));

      bool fr (filter (a, t, t));

      // Then installable ad hoc group members, if any.
      //
      for (const target* m (t.adhoc_member);
           m != nullptr;
           m = m->adhoc_member)
      {
        if (const file* mf = m->is_a<file> ())
        {
          if (!mf->path ().empty () && mf->mtime () != timestamp_nonexistent)
          {
            if (filter (a, t, *mf))
            {
              if (const path* p = lookup_install<path> (*mf, "install"))
              {
                install_target (*mf, *p, !fr || tp.empty () ? 1 : 2);
                r |= target_state::changed;
              }
            }
          }
        }
      }

      // Finally install the target itself (since we got here we know the
      // install variable is there).
      //
      if (fr && !tp.empty ())
      {
        install_target (t, cast<path> (t[var_install (rs)]), 1);
        r |= target_state::changed;
      }

      return r;
    }

    bool file_rule::
    uninstall_d (const scope& rs,
                 const install_dir& base,
                 const dir_path& d,
                 uint16_t verbosity)
    {
      assert (d.absolute ());

      context& ctx (rs.ctx);

      // See install_d() for the rationale.
      //
      if (ctx.dry_run || !filter_entry (rs, d, path (), entry_type::directory))
        return false;

      dir_path chd (chroot_path (rs, d));

      // Figure out if we should try to remove this directory. Note that if
      // it doesn't exist, then we may still need to remove outer ones.
      //
      bool r (false);
      try
      {
        if ((r = dir_exists (chd))) // May throw (e.g., EACCES).
        {
          if (!dir_empty (chd)) // May also throw.
            return false; // Won't be able to remove any outer directories.
        }
      }
      catch (const system_error& e)
      {
        fail << "invalid installation directory " << chd << ": " << e;
      }

      if (r)
      {
        dir_path reld (relative (chd));

        // Normally when we need to remove a file or directory we do it
        // directly without calling rm/rmdir. This however, won't work if we
        // have sudo. So we are going to do it both ways.
        //
        // While there is no sudo on Windows, deleting things that are being
        // used can get complicated. So we will always use rm/rmdir from
        // MSYS2/Cygwin which go above and beyond to accomplish the mission.
        //
        // Note also that it's possible we didn't create the directory and
        // won't be able to remove it due to permissions (for example, on Mac
        // OS we cannot remove empty /usr/local even with sudo). So instead of
        // failing we issue a warning and skip the directory.
        //
#ifndef _WIN32
        if (base.sudo == nullptr)
        {
          if (verb >= verbosity)
          {
            if (verb >= 2)
              text << "rmdir " << reld;
            else if (verb)
              print_diag ("uninstall -d", chd);
          }

          try
          {
            try_rmdir (chd);
          }
          catch (const system_error&)
          {
            r = false;
          }
        }
        else
#endif
        {
          const char* args_a[] = {
            base.sudo != nullptr ? base.sudo->c_str () : nullptr,
            "rmdir",
            reld.string ().c_str (),
            nullptr};

          const char** args (&args_a[base.sudo == nullptr ? 1 : 0]);

          process_path pp (run_search (args[0]));

          if (verb >= verbosity)
          {
            if (verb >= 2)
              print_process (args);
            else if (verb)
              print_diag ("uninstall -d", chd);
          }

          process pr (run_start (pp, args,
                                 0                       /* stdin */,
                                 1                       /* stdout */,
                                 diag_buffer::pipe (ctx) /* stderr */));
          diag_buffer dbuf (ctx, args[0], pr);
          dbuf.read ();
          r = run_finish_code (
            dbuf,
            args, pr,
            verb >= verbosity ? 1 : verb_never /* verbosity */);
        }

        if (!r)
        {
          warn << "unable to remove empty directory " << chd << ", ignoring";
          return false;
        }
      }

      // If we have more empty directories between base and dir, then try
      // to clean them up as well.
      //
      if (d != base.dir)
      {
        dir_path pd (d.directory ());

        if (pd != base.dir)
          r = uninstall_d (rs, base, pd, verbosity) || r;
      }

      return r;
    }

    static void
    uninstall_f_impl (const scope& rs,
                      const install_dir& base,
                      const path& f,
                      uint16_t verbosity)
    {
      context& ctx (rs.ctx);

      path relf (relative (f));

      // The same story as with uninstall -d (on Windows rm is also from
      // MSYS2/Cygwin).
      //
#ifndef _WIN32
      if (base.sudo == nullptr)
      {
        if (verb >= verbosity && verb >= 2)
          text << "rm " << relf;

        if (!ctx.dry_run)
        {
          try
          {
            try_rmfile (f);
          }
          catch (const system_error& e)
          {
            fail << "unable to remove file " << f << ": " << e;
          }
        }
      }
      else
#endif
      {
        const char* args_a[] = {
          base.sudo != nullptr ? base.sudo->c_str () : nullptr,
          "rm",
          "-f",
          relf.string ().c_str (),
          nullptr};

        const char** args (&args_a[base.sudo == nullptr ? 1 : 0]);

        process_path pp (run_search (args[0]));

        if (verb >= verbosity)
        {
          if (verb >= 2)
            print_process (args);
        }

        if (!ctx.dry_run)
          run (ctx,
               pp, args,
               verb >= verbosity ? 1 : verb_never /* finish_verbosity */);
      }
    }

    bool file_rule::
    uninstall_f (const scope& rs,
                 const install_dir& base,
                 const file* t,
                 const path& name,
                 uint16_t verbosity)
    {
      assert (name.empty () ? t != nullptr : name.simple ());

      const path& leaf (name.empty () ? t->path ().leaf () : name);

      if (!filter_entry (rs, base.dir, leaf, entry_type::regular))
        return false;

      dir_path chd (chroot_path (rs, base.dir));
      path f (chd / leaf);

      try
      {
        // Note: don't follow symlinks so if the target is a dangling symlinks
        // we will proceed to removing it.
        //
        if (!file_exists (f, false)) // May throw (e.g., EACCES).
          return false;
      }
      catch (const system_error& e)
      {
        fail << "invalid installation path " << f << ": " << e;
      }

      if (verb >= verbosity && verb == 1)
      {
        if (t != nullptr)
        {
          if (name.empty ())
            print_diag ("uninstall", *t, chd, "<-");
          else
            print_diag ("uninstall", *t, f, "<-");
        }
        else
          print_diag ("uninstall", f);
      }

      uninstall_f_impl (rs, base, f, verbosity);
      return true;
    }

    bool file_rule::
    uninstall_l (const scope& rs,
                 const install_dir& base,
                 const path& link,
                 const path& /*link_target*/,
                 uint16_t verbosity)
    {
      assert (link.simple () && !link.empty ());

      if (!filter_entry (rs, base.dir, link, entry_type::symlink))
        return false;

      dir_path chd (chroot_path (rs, base.dir));
      path f (chd / link);

      try
      {
        // Note: don't follow symlinks so if the target is a dangling symlinks
        // we will proceed to removing it.
        //
        if (!file_exists (f, false)) // May throw (e.g., EACCES).
          return false;
      }
      catch (const system_error& e)
      {
        fail << "invalid installation path " << f << ": " << e;
      }

      if (verb >= verbosity && verb == 1)
      {
        // It's dubious showing the link target path adds anything useful
        // here.
        //
#if 0
        print_diag ("uninstall -l", target, f, "<-");
#else
        print_diag ("uninstall -l", f);
#endif
      }

      uninstall_f_impl (rs, base, f, verbosity);
      return true;
    }

    target_state file_rule::
    perform_uninstall (action a, const target& xt) const
    {
      const file& t (xt.as<file> ());
      const path& tp (t.path ());

      // Path should have been assigned by update unless it is unreal.
      //
      assert (!tp.empty () || t.mtime () == timestamp_unreal);

      const scope& rs (t.root_scope ());

      auto uninstall_target = [&rs, this] (const file& t,
                                           const path& p,
                                           uint16_t verbosity) -> target_state
      {
        bool n (!p.to_directory ());
        dir_path d (n ? p.directory () : path_cast<dir_path> (p));

        if (n && d.empty ())
          fail << "relative installation file path '" << p
               << "' has no directory component";

        // Resolve target directory.
        //
        install_dirs ids (resolve (t, d));

        // Handle install.subdirs if one was specified.
        //
        if (!n)
        {
          if (auto l = t["install.subdirs"])
          {
            if (cast<bool> (l))
              resolve_subdir (ids, t, t.base_scope (), l);
          }
        }

        // Remove extras and the target itself.
        //
        const install_dir& id (ids.back ());

        target_state r (uninstall_extra (t, id)
                        ? target_state::changed
                        : target_state::unchanged);

        if (uninstall_f (rs, id, &t, n ? p.leaf () : path (), verbosity))
          r |= target_state::changed;

        // Clean up empty leading directories (in reverse).
        //
        // Note that we are using the leading directory (if there is one) for
        // the clean up information (sudo, etc). We may also try to uninstall
        // the same directory via different bases (e.g., root and exec_bin).
        //
        for (auto i (ids.rbegin ()), j (i), e (ids.rend ()); i != e; j = ++i)
        {
          if (uninstall_d (rs, ++j != e ? *j : *i, i->dir, verbosity))
            r |= target_state::changed;
        }

        return r;
      };

      // Reverse order of installation: first the target itself (since we got
      // here we know the install variable is there).
      //
      target_state r (target_state::unchanged);

      bool fr (filter (a, t, t));

      if (fr && !tp.empty ())
        r |= uninstall_target (t, cast<path> (t[var_install (rs)]), 1);

      // Then installable ad hoc group members, if any. To be anally precise,
      // we would have to do it in reverse, but that's not easy (it's a
      // single-linked list).
      //
      for (const target* m (t.adhoc_member);
           m != nullptr;
           m = m->adhoc_member)
      {
        if (const file* mf = m->is_a<file> ())
        {
          if (!mf->path ().empty () && mf->mtime () != timestamp_nonexistent)
          {
            if (filter (a, t, *mf))
            {
              if (const path* p = lookup_install<path> (*m, "install"))
              {
                r |= uninstall_target (
                  *mf,
                  *p,
                  !fr || tp.empty () || r != target_state::changed ? 1 : 2);
              }
            }
          }
        }
      }

      // Finally handle installable prerequisites.
      //
      r |= reverse_execute_prerequisites (a, t);

      return r;
    }

    // fsdir_rule
    //
    const fsdir_rule fsdir_rule::instance;

    bool fsdir_rule::
    match (action, target&) const
    {
      // We always match.
      //
      // Note that we are called both as the outer part during the update-for-
      // un/install pre-operation and as the inner part during the un/install
      // operation itself.
      //
      return true;
    }

    recipe fsdir_rule::
    apply (action a, target& t) const
    {
      // If this is outer part of the update-for-un/install, delegate to the
      // default fsdir rule. Otherwise, this is a noop (we don't install
      // fsdir{}).
      //
      // For now we also assume we don't need to do anything for prerequisites
      // (the only sensible prerequisite of fsdir{} is another fsdir{}).
      //
      if (a.operation () == update_id)
      {
        match_inner (a, t);
        return inner_recipe;
      }
      else
        return noop_recipe;
    }
  }
}