summaryrefslogtreecommitdiff
path: root/src/generic/apt/aptcache.cc
blob: 36d8f63a3a57b8d4647ef694545271ecb4e9d4ad (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
// aptcache.cc
//
//  Copyright 1999-2009, 2011 Daniel Burrows
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; see the file COPYING.  If not, write to
//  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
//  Boston, MA 02111-1307, USA.

#include "aptcache.h"

#include <aptitude.h>
#include <loggers.h>

#include "apt.h"
#include "aptitude_resolver_universe.h"
#include "aptitudepolicy.h"
#include "config_signal.h"
#include <generic/apt/matching/match.h>
#include <generic/apt/matching/parse.h>
#include <generic/apt/matching/pattern.h>
#include <generic/problemresolver/solution.h>
#include <generic/util/undo.h>

#include <apt-pkg/error.h>
#include <apt-pkg/sourcelist.h>
#include <apt-pkg/pkgcachegen.h>
#include <apt-pkg/configuration.h>
#include <apt-pkg/tagfile.h>
#include <apt-pkg/fileutl.h>
#include <apt-pkg/algorithms.h>
#include <apt-pkg/pkgsystem.h>
#include <apt-pkg/policy.h>
#include <apt-pkg/version.h>

#include <vector>

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>

#include <cwidget/generic/util/eassert.h>
#include <cwidget/generic/util/ssprintf.h>

#include <sigc++/adaptors/bind.h>
#include <sigc++/functors/mem_fun.h>

namespace cw = cwidget;

using namespace std;
using aptitude::Loggers;

class aptitudeDepCache::apt_undoer:public undoable
// Allows an action performed on the package cache to be undone.  My first
// thought was to just snapshot the package cache before the action and then
// copy over the state, but this works better (IMO :) ) -- the other method
// had the drawback of not telling what was actually happening, and potentially
// leaving bits of the cache in weird states.
//
// Of course, there's always the danger that this won't properly restore the
// cache state, so I'll have to revert to the original method..
{
  PkgIterator pkg;
  int prev_mode;  // One of Delete,Keep,Install
  int prev_iflags, prev_flags;
  changed_reason prev_removereason;
  pkgCache::State::PkgSelectedState prev_selection_state;

  string prev_forbidver;

  aptitudeDepCache *owner;
public:
  apt_undoer(PkgIterator _pkg, int _prev_mode, int _prev_flags, int _prev_iflags,
	     changed_reason _prev_removereason,
	     pkgCache::State::PkgSelectedState _prev_selection_state,
	     string _prev_forbidver,
	     aptitudeDepCache *_owner)
    :pkg(_pkg), prev_mode(_prev_mode), prev_iflags(_prev_iflags), prev_flags(_prev_flags),
     prev_removereason(_prev_removereason),
     prev_selection_state(_prev_selection_state),
     prev_forbidver(_prev_forbidver),
     owner(_owner)
  {
  }

  void undo()
  {
    aptitudeDepCache::action_group group(*owner);

    owner->pre_package_state_changed();

    if(prev_iflags&ReInstall)
      owner->internal_mark_install(pkg, false, true);
    else switch(prev_mode)
      {
      case ModeDelete:
	owner->internal_mark_delete(pkg, prev_iflags & Purge, prev_removereason == unused);
	break;
      case ModeKeep:
	owner->internal_mark_keep(pkg, prev_iflags & AutoKept, prev_selection_state == pkgCache::State::Hold);
	break;
      case ModeInstall:
	owner->internal_mark_install(pkg, false, false);
	break;
      }

    // make sure that everything is really set.
    owner->MarkAuto(pkg, (prev_flags & Flag::Auto));
    owner->get_ext_state(pkg).remove_reason=prev_removereason;
    owner->get_ext_state(pkg).forbidver=prev_forbidver;
  }
};

extern sigc::signal0<void> cache_reloaded;

class aptitudeDepCache::forget_undoer:public undoable
// Undoes a "forget_new" command
{
  vector<pkgCache::PkgIterator> packages;

  aptitudeDepCache *owner;
public:
  forget_undoer(aptitudeDepCache *_owner):owner(_owner) {}

  void add_item(pkgCache::PkgIterator item)
  {
    packages.push_back(item);
  }

  bool empty()
  {
    return packages.empty();
  }

  void undo()
  {
    for(vector<pkgCache::PkgIterator>::iterator i=packages.begin(); i!=packages.end(); i++)
      owner->set_new_flag(*i, true);

    // Hack to make all the trees rebuild themselves.
    cache_reloaded();
  }
};

class aptitudeDepCache::candver_undoer:public undoable
// Undoes a "set candidate version" command.
{
  pkgCache::VerIterator oldver;

  aptitudeDepCache *owner;
public:
  candver_undoer(pkgCache::VerIterator _oldver,
		 aptitudeDepCache *_owner)
    :oldver(_oldver), owner(_owner)
  {
  }

  void undo()
  {
    owner->pre_package_state_changed();
    owner->set_candidate_version(oldver, NULL);
    owner->package_state_changed();
  }
};

aptitudeDepCache::action_group::action_group(aptitudeDepCache &cache,
					     undo_group *group)
  : parent_group(new pkgDepCache::ActionGroup(cache)),
    cache(cache), group(group)
{
  cache.begin_action_group();
}

aptitudeDepCache::action_group::~action_group()
{
  // Force the parent to mark-and-sweep first.
  delete parent_group;

  cache.end_action_group(group);
}

aptitudeDepCache::aptitudeDepCache(pkgCache *Cache, Policy *Plcy)
  :pkgDepCache(Cache, Plcy), dirty(false), read_only(true),
   package_states(NULL), lock(-1), group_level(0),
   new_package_count(0), records(NULL)
{
  // When the "install recommended packages" flag changes, collect garbage.
#if 0
  aptcfg->connect("Apt::Install-Recommends",
		  sigc::bind(sigc::mem_fun(*this,
					   &pkgDepCache::MarkAndSweep),
			     (undo_group *) NULL));

  aptcfg->connect(PACKAGE "::Keep-Recommends",
		  sigc::bind(sigc::mem_fun(*this,
					   &pkgDepCache::MarkAndSweep),
			     (undo_group *) NULL));

  // sim.
  aptcfg->connect(PACKAGE "::Keep-Suggests",
		  sigc::bind(sigc::mem_fun(*this,
					   &pkgDepCache::MarkAndSweep),
			     (undo_group *) NULL));
#endif
}

bool aptitudeDepCache::Init(OpProgress *Prog, bool WithLock, bool do_initselections, const char *status_fname)
{
  return build_selection_list(*Prog, WithLock, do_initselections, status_fname);
}

aptitudeDepCache::~aptitudeDepCache()
{
  delete records;
  delete[] package_states;

  if(lock!=-1)
    close(lock);
}

void aptitudeDepCache::set_read_only(bool new_read_only)
{
  read_only = new_read_only;
}

namespace
{
  // User tag syntax:
  // 
  // Tag-List ::= Tag+
  // Tag      ::= regexp([^[:space:]]) | regexp("([^\\"]|\\.)")
  bool parse_user_tag(std::string &out,
		      const char *&start, const char *end,
		      const std::string &package_name)
  {
    const char * const initial_start = start;
    while(start != end && isspace(*start))
      ++start;

    if(start == end)
      return false;
    else if(*start != '"')
      {
	while(start != end && !isspace(*start))
	  {
	    out += *start;
	    ++start;
	  }
	return true;
      }
    else
      {
	++start;
	while(start != end && *start != '"')
	  {
	    if(*start == '\\')
	      {
		++start;
		if(start == end)
		  return _error->Error(_("Error parsing a user-tag for the package %s: unexpected end-of-line following %s."),
				       package_name.c_str(),
				       (std::string("\"") + std::string(initial_start, start)).c_str());
		else
		  {
		    out += *start;
		    ++start;
		  }
	      }
	    else
	      {
		out += *start;
		++start;
	      }
	  }

	if(start == end)
	  return _error->Error(_("Unterminated '\"' in the user-tags list of the package %s."),
			       package_name.c_str());
	else
	  {
	    ++start;
	    return true;
	  }
      }
  }
}

void aptitudeDepCache::parse_user_tags(std::set<user_tag> &tags,
				       const char *&start, const char *end,
				       const std::string &package_name)
{
  while(start != end)
    {
      while(start != end && isspace(*start))
	++start;

      std::string tag;
      parse_user_tag(tag, start, end, package_name);

      typedef std::map<std::string, user_tag_reference>::const_iterator
	user_tags_index_iterator;
      user_tags_index_iterator found = user_tags_index.find(tag);
      if(found == user_tags_index.end())
	{
	  user_tag_reference loc(user_tags.size());
	  user_tags.push_back(tag);
	  std::pair<user_tags_index_iterator, bool> tmp(user_tags_index.insert(std::make_pair(tag, loc)));
	  found = tmp.first;
	}
      tags.insert(user_tag(found->second));
    }
}

bool aptitudeDepCache::build_selection_list(OpProgress &Prog, bool WithLock,
					    bool do_initselections,
					    const char *status_fname)
{
  action_group group(*this);

  bool initial_open=false;
  // This will be set to true if the state file does not exist.

  if(!pkgDepCache::Init(&Prog))
    return false;

  records = new pkgRecords(*this);

  // This is necessary so that the Garbage flags are initialized.
  // Some of the Mark* methods perturb the Auto flag in largely
  // uncontrollable ways, and one defense against this is to get
  // Garbage set up (they behave more the way they ought to then).
  MarkAndSweep();

  string statedir=aptcfg->FindDir("Dir::Aptitude::state", STATEDIR);
  // Should this not go under Dir:: ?  I'm not sure..
  delete package_states;
  package_states=new aptitude_state[Head().PackageCount];
  user_tags.clear();
  for(unsigned int i=0; i<Head().PackageCount; i++)
    {
      package_states[i].new_package=true;
      package_states[i].reinstall=false;
      package_states[i].user_tags.clear();
      package_states[i].remove_reason=manual;
      package_states[i].selection_state = pkgCache::State::Unknown;
      package_states[i].previously_auto_package = false;
    }

  if(WithLock && lock==-1)
    {
      lock = GetLock(aptcfg->Find("Aptitude::LockFile", LOCKFILE));

      if(_error->PendingError())
	{
	  if(lock!=-1)
	    close(lock);
	  lock=-1;
	  read_only = true;
	  return false;
	}
    }
  // Errrrr, I think we need to do this first in case the stuff below
  // manages to trigger a mark operation.
  duplicate_cache(&backup_state);

  FileFd state_file;

  // Read in the states that we saved
  if(status_fname==NULL)
    state_file.Open(statedir+"pkgstates", FileFd::ReadOnly);
  else
    state_file.Open(status_fname, FileFd::ReadOnly);

  // Have to make the file NOT read-only to set up the initial state.
  read_only = false;

  if(!state_file.IsOpen())
    {
      _error->Discard();
      if(errno!=ENOENT)
	_error->Warning(_("Can't open Aptitude extended state file"));
      else
	{
	  initial_open=true;
	  // Mark the cache as dirty so that we'll create the
	  // pkgstates file later.  We need to do this even if the
	  // user doesn't change anything because otherwise we won't
	  // know which packages are new until we save the cache (#429732).
	  dirty = true;
	}
    }
  else
    {
      int file_size=state_file.Size();
      Prog.OverallProgress(0, file_size, 1, _("Reading extended state information"));

      pkgTagFile tagfile(&state_file);
      pkgTagSection section;
      int amt=0;
      bool do_dselect=aptcfg->FindB(PACKAGE "::Track-Dselect-State", true);
      while(tagfile.Step(section))
	{
	  std::string package_name(section.FindS("Package"));
          std::string arch(section.FindS("Architecture"));
	  PkgIterator pkg;
          // TODO: Wheezy+n can assume that all sections will have the
          // Architecture tag (probably ;-).
          if(arch.empty())
            pkg=FindPkg(package_name);
          else
            pkg=FindPkg(package_name, arch);
	  if(!pkg.end() && !pkg.VersionList().end())
	    // Silently ignore unknown packages and packages with no actual
	    // version.
	    {
	      unsigned long tmp=0;
	      string candver;

	      aptitude_state &pkg_state=get_ext_state(pkg);

	      section.FindFlag("Unseen", tmp, 1);

	      pkg_state.new_package=(tmp==1);

	      tmp=0;
	      section.FindFlag("Upgrade", tmp, 1);
	      pkg_state.upgrade=(tmp==1);

	      unsigned long auto_new_install = 0;
	      section.FindFlag("Auto-New-Install", auto_new_install, 1);
	      if(auto_new_install)
		pkg_state.previously_auto_package = true;

	      // The install reason is much more important to preserve
	      // from previous versions, so support the outdated name
	      // for it.
	      changed_reason install_reason=(changed_reason)
		section.FindI("Install-Reason",
			      section.FindI("Last-Change", manual));

	      if(install_reason != manual)
		pkg_state.previously_auto_package = true;

	      pkg_state.remove_reason=(changed_reason)
		section.FindI("Remove-Reason", manual);

	      candver=section.FindS("Version");

	      pkg_state.selection_state=(pkgCache::State::PkgSelectedState) section.FindI("State", pkgCache::State::Unknown);
	      pkgCache::State::PkgSelectedState last_dselect_state
		= (pkgCache::State::PkgSelectedState)
		    section.FindI("Dselect-State", pkg->SelectedState);
	      pkg_state.candver=candver;
	      pkg_state.forbidver=section.FindS("ForbidVer");

	      {
		const char *start, *end;
		if(section.Find("User-Tags", start, end))
		  parse_user_tags(pkg_state.user_tags, start, end,
				  package_name);
	      }

	      if(do_dselect && pkg->SelectedState != last_dselect_state)
		{
		  MarkFromDselect(pkg);
		  // dirty should be set to "true" so that we update
		  // the on-disk dselect state ASAP, even if no
		  // package states change as a result.
		  dirty=true;

		  // We need to update the package state from the
		  // dselect state regardless of whether we're doing
		  // initselections.  This is so that, e.g., if the
		  // user installed a package outside aptitude (so the
		  // dselect state says to install it), our internal
		  // state isn't left at "remove".  But if we aren't
		  // supposed to set up stored installs/removals, we
		  // should cancel this at the apt-get level (so the
		  // package doesn't get changed if dselect said to
		  // install it, but this isn't stored in our database
		  // for future runs).
		  //
		  // In the past, we skipped doing MarkFromDselect in
		  // this case.  BAD.
		  if(!do_initselections)
		    MarkKeep(pkg, false);
		}
	    }
	  amt+=section.size();
	  Prog.OverallProgress(amt, file_size, 1, _("Reading extended state information"));
	}
      Prog.OverallProgress(file_size, file_size, 1, _("Reading extended state information"));
      Prog.Done();
    }

  int num=0;

  Prog.OverallProgress(0, Head().PackageCount, 1, _("Initializing package states"));

  new_package_count=0;

  pre_package_state_changed();

  // Act on them
  for(pkgCache::PkgIterator i=PkgBegin(); !i.end(); i++)
    {
      StateCache &state=(*this)[i];
      aptitude_state &estate=get_ext_state(i);

      if(initial_open) // Don't make everything "new".
	estate.new_package=false;
      else if(!i.VersionList().end() && estate.new_package)
	++new_package_count;

      switch(estate.selection_state)
	{
	case pkgCache::State::Unknown:
	  if(i.CurrentVer().end())
	    estate.selection_state=pkgCache::State::DeInstall;
	  else
	    estate.selection_state=pkgCache::State::Install;
	  break;
	case pkgCache::State::Install:
	  if(!do_initselections)
	    break;

	  // FIXME: should I check this for "unknown" packages as well?
	  // Does that even make sense??
	  if(!estate.candver.empty())
	    {
	      for(pkgCache::VerIterator ver=i.VersionList(); !ver.end(); ++ver)
		if(ver.VerStr()==estate.candver &&
		   (ver.Downloadable() ||
		    (ver == ver.ParentPkg().CurrentVer() &&
		     ver.ParentPkg()->CurrentState != pkgCache::State::ConfigFiles)))
		  SetCandidateVersion(ver);

	      MarkInstall(i, false);
	    }
	  else
	    if(i.CurrentVer().end())
	      MarkInstall(i, false);
	    else
	      {
		SetReInstall(i, estate.reinstall);

		if(estate.upgrade && state.Upgradable())
		  MarkInstall(i, false);
	      }
	  break;
	case pkgCache::State::Hold:
	  if(!do_initselections)
	    break;

	  MarkKeep(i, false);
	  break;
	case pkgCache::State::DeInstall:
	  if(!do_initselections)
	    break;

	  if(!i.CurrentVer().end())
	    MarkDelete(i, false);
	  break;
	case pkgCache::State::Purge:
	  if(!do_initselections)
	    break;

	  if(!i.CurrentVer().end())
	    MarkDelete(i, true);
	  break;
	}

      if(estate.previously_auto_package)
	{
	  MarkAuto(i, true);
	  dirty = true;
	}

      ++num;
      Prog.OverallProgress(num, Head().PackageCount, 1, _("Initializing package states"));
    }

  Prog.OverallProgress(Head().PackageCount, Head().PackageCount, 1, _("Initializing package states"));

  duplicate_cache(&backup_state);

  if(aptcfg->FindB(PACKAGE "::Auto-Upgrade", false) && do_initselections)
    mark_all_upgradable(aptcfg->FindB(PACKAGE "::Auto-Install", true),
			true, NULL);
  Prog.Done();

  read_only = (lock == -1);

  return true;
}

void aptitudeDepCache::mark_all_upgradable(bool with_autoinst,
					   bool ignore_removed,
					   undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  pre_package_state_changed();

  action_group group(*this, undo);

  for(int iter=0; iter==0 || (iter==1 && with_autoinst); ++iter)
    {
      // Do this twice, only turning auto-install on the second time.
      // A reason for this is the following scenario:
      //
      // Packages A and B are installed at 1.0.  Package C is not installed.
      // Version 2.0 of each package is available.
      //
      // Version 2.0 of A depends on "C (= 2.0) | B (= 2.0)".
      //
      // Upgrading A if B is not upgraded will cause this dependency to
      // break.  Auto-install will then cheerfully fulfill it by installing
      // C.
      //
      // A real-life example of this is xemacs21, xemacs21-mule, and
      // xemacs21-nomule; aptitude would keep trying to install the mule
      // version on upgrades.
      bool do_autoinstall=(iter==1);

      std::set<pkgCache::PkgIterator> to_upgrade;
      get_upgradable(ignore_removed, to_upgrade);
      for(std::set<pkgCache::PkgIterator>::const_iterator it =
	    to_upgrade.begin(); it != to_upgrade.end(); ++it)
	{
	  pre_package_state_changed();
	  dirty = true;

	  internal_mark_install(*it, do_autoinstall, false);
	}
    }
}

void aptitudeDepCache::get_upgradable(bool ignore_removed,
				      std::set<pkgCache::PkgIterator> &upgradable)
{
  logging::LoggerPtr logger(Loggers::getAptitudeAptCache());

  LOG_TRACE(logger, "Fetching the list of upgradable packages.");

  for(pkgCache::PkgIterator p = PkgBegin(); !p.end(); ++p)
    {
      StateCache &state = (*this)[p];
      aptitude_state &estate = get_ext_state(p);

      if(p.CurrentVer().end())
	{
	  LOG_TRACE(logger, p.FullName(false) << " is not upgradable: it is not currently installed.");
	  continue;
	}

      bool do_upgrade = false;

      if(!ignore_removed)
	{
	  do_upgrade = state.Status > 0 && !is_held(p);
	  if(do_upgrade)
	    LOG_DEBUG(logger, p.FullName(false) << " is upgradable.");
	  else
	    LOG_TRACE(logger, p.FullName(false) << " is not upgradable: no newer version is available, or it is held back.");
	}
      else
	{
	  switch(estate.selection_state)
	    {
	      // This case shouldn't really happen:
	    case pkgCache::State::Unknown:
	      estate.selection_state = pkgCache::State::Install;
	      LOG_WARN(logger, p.FullName(false) << " has not been seen before, but it should have been initialized on startup.");

	      // Fall through
	    case pkgCache::State::Install:
	      if(state.Status > 0 && !is_held(p))
		{
		  do_upgrade = true;
		  LOG_TRACE(logger, p.FullName(false) << " is upgradable.");
		}
	      else
		LOG_TRACE(logger, p.FullName(false) << " is not upgradable: no newer version is available, or it is held back.");
	      break;
	    default:
	      LOG_TRACE(logger, p.FullName(false) << " is not upgradable: its state is " << estate.selection_state << " instead of " << pkgCache::State::Install << ".");
	      break;
	    }
	}

      if(do_upgrade)
	upgradable.insert(p);
    }
}

// If fd is -1, just write unconditionally to the given fd.
//
//  FIXME: clean up the logic by having an internal "write to this fd"
// routine and an exported "ok, set up for the write and then clean up"
// routine.
bool aptitudeDepCache::save_selection_list(OpProgress &prog,
					   const char *status_fname)
{
  // Refuse to write to disk if nothing changed and we aren't writing
  // to an unusual file
  if(!dirty && !status_fname)
    return true;

  if(lock==-1 && !status_fname)
    return true;

  // Don't write the global apt state file if we're not writing our
  // own global state.  TODO: this means that su-to-root will lose
  // automatic states! (but we couldn't do anything about it anyway
  // because we're not root and so can't write the global state file)
  // Ow, that sucks.  The solution will be to write the apt states to
  // a separate file.
  if(status_fname == NULL)
    writeStateFile(&prog);

  string statefile=_config->FindDir("Dir::Aptitude::state", STATEDIR)+"pkgstates";

  FileFd newstate;

  if(!status_fname)
    newstate.Open(statefile+".new", FileFd::WriteEmpty, 0644);
  else
    newstate.Open(status_fname, FileFd::WriteEmpty, 0644);

  // The user might have a restrictive umask -- make sure we get a
  // mode 644 file.
  fchmod(newstate.Fd(), 0644);

  if(!newstate.IsOpen())
    _error->Error(_("Cannot open Aptitude state file"));
  else
    {
      int num=0;
      prog.OverallProgress(0, Head().PackageCount, 1, _("Writing extended state information"));

      for(PkgIterator i=PkgBegin(); !i.end(); i++)
	if(!i.VersionList().end())
	  {
	    StateCache &state=(*this)[i];
	    aptitude_state &estate=get_ext_state(i);

	    string forbidstr=!estate.forbidver.empty()
	      ? "ForbidVer: "+estate.forbidver+"\n":"";

	    bool upgrade=(!i.CurrentVer().end()) && state.Install();
	    string upgradestr=upgrade ? "Upgrade: yes\n" : "";

	    bool auto_new_install = (i.CurrentVer().end() &&
				     state.Install() &&
				     ((state.Flags & Flag::Auto) != 0));
	    string autostr = auto_new_install ? "Auto-New-Install: yes\n" : "";

	    string tailstr;

	    if(state.Install() &&
	       !estate.candver.empty() &&
	       (GetCandidateVer(i).end() ||
		GetCandidateVer(i).VerStr() != estate.candver))
	      tailstr = "Version: " + estate.candver + "\n";

	    // Build the list of usertags for this package.
	    std::string user_tags;
	    if(!estate.user_tags.empty())
	      {
		user_tags = "User-Tags: ";

		// Put the usertags in sorted order so we get
		// predictable outputs.
		std::vector<std::string> tmp;
		tmp.reserve(estate.user_tags.size());

		for(std::set<user_tag>::const_iterator it
		      = estate.user_tags.begin(); it != estate.user_tags.end(); ++it)
		  tmp.push_back(deref_user_tag(*it));

		std::sort(tmp.begin(), tmp.end());

		bool first = true;
		// Append user tags to the field, using double-quotes
		// if the tag contains spaces or double-quotes.
		for(std::vector<std::string>::const_iterator it = tmp.begin();
		    it != tmp.end(); ++it)
		  {
		    if(first)
		      first = false;
		    else
		      user_tags.push_back(' ');

		    if(it->find_first_of(" \"\\") != std::string::npos)
		      {
			user_tags.push_back('"');
			for(std::string::const_iterator tag_it = it->begin();
			    tag_it != it->end(); ++tag_it)
			  {
			    switch(*tag_it)
			      {
			      case '"':
			      case '\\':
				user_tags.push_back('\\');
				user_tags.push_back(*tag_it);
				break;
			      default:
				user_tags.push_back(*tag_it);
				break;
			      }
			  }
			user_tags.push_back('"');
		      }
		    else
		      user_tags.insert(user_tags.size(), *it);
		  }

		user_tags.push_back('\n');
	      }

	    using cw::util::ssprintf;
	    std::string line(ssprintf("Package: %s\nArchitecture: %s\nUnseen: %s\nState: %i\nDselect-State: %i\nRemove-Reason: %i\n%s%s%s%s%s\n",
				      i.Name(),
                                      i.Arch(),
				      estate.new_package?"yes":"no",
				      estate.selection_state,
				      i->SelectedState,
				      estate.remove_reason,
				      upgradestr.c_str(),
				      autostr.c_str(),
				      forbidstr.c_str(),
				      user_tags.c_str(),
				      tailstr.c_str()));

	    if(newstate.Failed() || !newstate.Write(line.c_str(), line.size()))
	      {
		_error->Error(_("Couldn't write state file"));
		newstate.Close();

		if(!status_fname)
		  unlink((statefile+".new").c_str());
		return false;
	      }

	    num++;
	    prog.OverallProgress(num, Head().PackageCount, 1, _("Writing extended state information"));
	  }

      prog.OverallProgress(Head().PackageCount, Head().PackageCount, 1, _("Writing extended state information"));

      if(newstate.Failed())
	// This is /probably/ redundant, but paranoia never hurts.
	{
	  _error->Error(_("Error writing state file"));
	  newstate.Close();

	  if(!status_fname)
	    unlink((statefile+".new").c_str());

	  prog.Done();
	  return false;
	}
      newstate.Close();
      // FIXME!  This potentially breaks badly on NFS.. (?) -- actually, it
      //       wouldn't be harmful; you'd just get gratuitous errors..
      if(!status_fname)
	{
	  string oldstr(statefile + ".old"), newstr(statefile + ".new");

	  if(unlink(oldstr.c_str()) != 0 && errno != ENOENT)
	    {
	      _error->Errno("save_selection_list", _("failed to remove %s"), oldstr.c_str());
	      prog.Done();
	      return false;
	    }

	  if(link(statefile.c_str(), oldstr.c_str()) != 0 && errno != ENOENT)
	    {
	      _error->Errno("save_selection_list", _("failed to rename %s to %s"),
			    statefile.c_str(), (statefile + ".old").c_str());
	      prog.Done();
	      return false;
	    }

	  if(rename(newstr.c_str(), statefile.c_str()) != 0)
	    {
	      _error->Errno("save_selection_list", _("couldn't replace %s with %s"), statefile.c_str(), newstr.c_str());
	      prog.Done();
	      return false;
	    }
	}
    }

  prog.Done();
  return true;
}

void aptitudeDepCache::set_new_flag(const pkgCache::PkgIterator &pkg,
				    bool is_new)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  aptitude_state &estate=get_ext_state(pkg);

  if(estate.new_package && !is_new)
    {
      --new_package_count;
      estate.new_package=is_new;
    }
  else if(!estate.new_package && is_new)
    {
      ++new_package_count;
      estate.new_package=is_new;
    }
}

void aptitudeDepCache::forget_new(undoable **undoer)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  forget_undoer *undo=undoer?new forget_undoer(this):NULL;

  for(pkgCache::PkgIterator i=PkgBegin(); !i.end(); i++)
    if(package_states[i->ID].new_package)
      {
	dirty=true;
	package_states[i->ID].new_package=false;
	if(undo)
	  undo->add_item(i);
      }

  new_package_count=0;

  if(undoer && undo && !undo->empty())
    *undoer=undo;
  else
    delete undo;

  duplicate_cache(&backup_state);

  // Umm, is this a hack? dunno.
  cache_reloaded();
}

undoable *aptitudeDepCache::state_restorer(PkgIterator pkg, StateCache &state, aptitude_state &ext_state)
{
  return new apt_undoer(pkg, state.Mode, state.Flags, state.iFlags,
			ext_state.remove_reason,
			ext_state.selection_state,
			ext_state.forbidver, this);
}

void aptitudeDepCache::cleanup_after_change(undo_group *undo,
					    std::set<pkgCache::PkgIterator> *changed_packages,
					    bool alter_stickies)
  // Finds any packages whose states have changed and: (a) updates the
  // selected_state if it's not already updated; (b) adds an item to the
  // undo group.
{
  // We get here with NULL backup_state in certain very early failures
  // (e.g., when someone else is holding a lock).  In this case we
  // don't know what the previous state was, so we can't possibly
  // build a collection of undoers to return to it or find out which
  // packages changed relative to it.
  if(backup_state.PkgState == NULL ||
     backup_state.DepState == NULL ||
     backup_state.AptitudeState == NULL)
    return;

  for(pkgCache::PkgIterator pkg=PkgBegin(); !pkg.end(); pkg++)
    {
      // Set to true if we should signal that this package's visible
      // state changed.
      bool visibly_changed = false;

      if(PkgState[pkg->ID].Mode!=backup_state.PkgState[pkg->ID].Mode ||
	 (PkgState[pkg->ID].Flags & pkgCache::Flag::Auto) != (backup_state.PkgState[pkg->ID].Flags & pkgCache::Flag::Auto) ||
	 package_states[pkg->ID].selection_state!=backup_state.AptitudeState[pkg->ID].selection_state ||
	 package_states[pkg->ID].reinstall!=backup_state.AptitudeState[pkg->ID].reinstall ||
	 package_states[pkg->ID].remove_reason!=backup_state.AptitudeState[pkg->ID].remove_reason ||
	 package_states[pkg->ID].forbidver!=backup_state.AptitudeState[pkg->ID].forbidver)
	{
	  // Technically this could be invoked only when we're really
	  // about to change a package's state, but placing it here
	  // should avoid signalling changes unnecessarily while still
	  // signalling a change whenever something changed.
	  //
	  // You could argue that this invocation of
	  // pre_package_state_changed makes all other unnecessary,
	  // but I think they should be left in for safety's sake.
	  // Forgetting to call pre_package_state_changed can lead to
	  // hard to track down bugs like #432411.
	  pre_package_state_changed();

	  int n=pkg->ID;
	  n=n;
	  char curM=PkgState[pkg->ID].Mode;
	  curM=curM;
	  char oldM=backup_state.PkgState[pkg->ID].Mode;
	  oldM=oldM;

	  if(alter_stickies &&
	     PkgState[pkg->ID].Mode!=backup_state.PkgState[pkg->ID].Mode &&
	     package_states[pkg->ID].selection_state==backup_state.AptitudeState[pkg->ID].selection_state)
	    // Catch packages which switched without altering their Aptitude
	    // selection mode
	    {
	      switch(PkgState[pkg->ID].Mode)
		{
		case ModeDelete:
		  if(package_states[pkg->ID].selection_state!=pkgCache::State::DeInstall)
		    {
		      if(!pkg.CurrentVer().end())
			package_states[pkg->ID].remove_reason=libapt;

		      package_states[pkg->ID].selection_state=pkgCache::State::DeInstall;
		    }
		  break;
		case ModeKeep:
		  if(!pkg.CurrentVer().end())
		    package_states[pkg->ID].selection_state=pkgCache::State::Install;
		  else if(pkg->CurrentState==pkgCache::State::NotInstalled)
		    package_states[pkg->ID].selection_state=pkgCache::State::Purge;
		  else
		    package_states[pkg->ID].selection_state=pkgCache::State::DeInstall;
		  break;
		case ModeInstall:
		  if(package_states[pkg->ID].selection_state!=pkgCache::State::Install)
		    package_states[pkg->ID].selection_state=pkgCache::State::Install;
		  break;
		}
	    }

	  visibly_changed = true;

	  if(undo)
	    undo->add_item(state_restorer(pkg,
					  backup_state.PkgState[pkg->ID],
					  backup_state.AptitudeState[pkg->ID]));
	}
      // Detect things like broken-ness and other changes that
      // shouldn't trigger undo but might trigger updating the
      // package's display.
      else if(PkgState[pkg->ID].Flags != backup_state.PkgState[pkg->ID].Flags ||
	      PkgState[pkg->ID].DepState != backup_state.PkgState[pkg->ID].DepState ||
	      PkgState[pkg->ID].CandidateVer != backup_state.PkgState[pkg->ID].CandidateVer ||
	      PkgState[pkg->ID].Marked != backup_state.PkgState[pkg->ID].Marked ||
	      PkgState[pkg->ID].Garbage != backup_state.PkgState[pkg->ID].Garbage ||
	      package_states[pkg->ID].user_tags != backup_state.AptitudeState[pkg->ID].user_tags ||
	      package_states[pkg->ID].new_package != backup_state.AptitudeState[pkg->ID].new_package)
	visibly_changed = true;

      if(visibly_changed && changed_packages != NULL)
	changed_packages->insert(pkg);
    }
}

void aptitudeDepCache::mark_install(const PkgIterator &Pkg,
				    bool AutoInst,
				    bool ReInstall,
				    undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  action_group group(*this, undo);

  pre_package_state_changed();

  internal_mark_install(Pkg, AutoInst, ReInstall);
}

void aptitudeDepCache::internal_mark_install(const PkgIterator &Pkg,
					     bool AutoInst,
					     bool ReInstall)
{
  dirty=true;

  bool set_to_manual =
    ((Pkg.CurrentVer().end()  && !(*this)[Pkg].Install()) ||
     (!Pkg.CurrentVer().end() && (*this)[Pkg].Delete() && get_ext_state(Pkg).remove_reason == unused));

  // MarkInstall and friends like to modify the auto flag, so save it
  // here and restore it afterwards:
  bool previously_auto = ((*this)[Pkg].Flags & Flag::Auto) != 0;

  if(!ReInstall)
    {
      pkgDepCache::MarkInstall(Pkg, AutoInst);
    }
  else
    pkgDepCache::MarkKeep(Pkg, AutoInst);

  pkgDepCache::SetReInstall(Pkg, ReInstall);

  MarkAuto(Pkg, previously_auto);

  if(set_to_manual)
    MarkAuto(Pkg, false);

  get_ext_state(Pkg).selection_state=pkgCache::State::Install;
  get_ext_state(Pkg).reinstall=ReInstall;
  get_ext_state(Pkg).forbidver="";
}

void aptitudeDepCache::mark_delete(const PkgIterator &Pkg,
				   bool Purge,
				   bool unused_delete,
				   undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  action_group group(*this, undo);

  pre_package_state_changed();

  internal_mark_delete(Pkg, Purge, unused_delete);
}

void aptitudeDepCache::internal_mark_delete(const PkgIterator &Pkg,
					    bool Purge,
					    bool unused_delete)
{
  dirty=true;

  bool previously_to_delete=(*this)[Pkg].Delete();

  pkgDepCache::MarkDelete(Pkg, Purge);
  pkgDepCache::SetReInstall(Pkg, false);

  get_ext_state(Pkg).selection_state=(Purge?pkgCache::State::Purge:pkgCache::State::DeInstall);
  get_ext_state(Pkg).reinstall=false;

  if(!previously_to_delete)
    {
      if(unused_delete)
	get_ext_state(Pkg).remove_reason=unused;
      else
	get_ext_state(Pkg).remove_reason=manual;
    }
}

void aptitudeDepCache::mark_keep(const PkgIterator &Pkg, bool Automatic, bool SetHold, undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  action_group group(*this, undo);

  pre_package_state_changed();

  internal_mark_keep(Pkg, Automatic, SetHold);
}

void aptitudeDepCache::internal_mark_keep(const PkgIterator &Pkg, bool Automatic, bool SetHold)
{
  dirty=true;


  // If the package is currently installed and is being garbage
  // collected, switch it to manual mode.  We check
  // pkg.CurrentVer().end() to avoid fiddling with packages that are
  // in the ConfigFiles state and are being purged.
  bool was_garbage_removed =
    (*this)[Pkg].Delete() &&
    !Pkg.CurrentVer().end() &&
    get_ext_state(Pkg).remove_reason == unused;

  if(was_garbage_removed)
    MarkAuto(Pkg, false);


  pkgDepCache::MarkKeep(Pkg, false, !Automatic);
  pkgDepCache::SetReInstall(Pkg, false);
  get_ext_state(Pkg).reinstall=false;

  if(Pkg.CurrentVer().end())
    {
      if((*this)[Pkg].iFlags&Purge)
	get_ext_state(Pkg).selection_state=pkgCache::State::Purge;
      else
	get_ext_state(Pkg).selection_state=pkgCache::State::DeInstall;
    }
  else if(SetHold)
    get_ext_state(Pkg).selection_state=pkgCache::State::Hold;
  else
    get_ext_state(Pkg).selection_state=pkgCache::State::Install;
}

void aptitudeDepCache::set_candidate_version(const VerIterator &ver,
					     undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  dirty=true;

  if(!ver.end() &&
     (ver.Downloadable() ||
      (ver == ver.ParentPkg().CurrentVer() &&
       ver.ParentPkg()->CurrentState != pkgCache::State::ConfigFiles)))
    {
      pre_package_state_changed();


      // Make the package manually installed if it was being
      // garbage-collected.
      bool set_to_manual =
	(ver.ParentPkg().CurrentVer().end() && !(*this)[ver.ParentPkg()].Install()) ||
	(!ver.ParentPkg().CurrentVer().end() &&
	 (*this)[ver.ParentPkg()].Delete() &&
	 get_ext_state(ver.ParentPkg()).remove_reason == unused);

      if(set_to_manual)
	MarkAuto(ver.ParentPkg(), false);



      // Use the InstVerIter instead of GetCandidateVersion, since
      // that seems to store the currently to-be-installed version.
      VerIterator prev=(*this)[(ver.ParentPkg())].InstVerIter(GetCache());

      aptitude_state &estate = get_ext_state(ver.ParentPkg());

      if(ver!=GetCandidateVer(ver.ParentPkg()))
	estate.candver=ver.VerStr();
      else
	estate.candver="";

      estate.selection_state = pkgCache::State::Install;

      SetCandidateVersion(ver);

      if(group_level == 0)
	{
	  if(undo)
	    undo->add_item(new candver_undoer(prev, this));

	  MarkAndSweep();

	  //if(BrokenCount()>0)
	  //create_resolver();
	  //
	  // EW - rely on the fact that mark_and_sweep implicitly calls
	  // begin/end_action_group(), which in turn does just this.

	  package_state_changed();
	}
    }
}

void aptitudeDepCache::forbid_upgrade(const PkgIterator &pkg,
				      string verstr, undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  aptitude_state &estate=get_ext_state(pkg);

  if(verstr!=estate.forbidver)
    {
      action_group group(*this, undo);

      pre_package_state_changed();

      pkgCache::VerIterator candver=(*this)[pkg].CandidateVerIter(*this);

      dirty=true;

      estate.forbidver=verstr;
      if(!candver.end() && candver.VerStr()==verstr && (*this)[pkg].Install())
	MarkKeep(pkg, false);
    }
}

void aptitudeDepCache::mark_single_install(const PkgIterator &Pkg, undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  action_group group(*this, undo);

  pre_package_state_changed();
  dirty=true;

  for(PkgIterator i=PkgBegin(); !i.end(); i++)
    pkgDepCache::MarkKeep(i, true);


  bool set_to_manual =
    ((Pkg.CurrentVer().end()  && !(*this)[Pkg].Install()) ||
     (!Pkg.CurrentVer().end() && (*this)[Pkg].Delete() && get_ext_state(Pkg).remove_reason == unused));

  if(set_to_manual)
    MarkAuto(Pkg, false);

  internal_mark_install(Pkg, true, false);
}

void aptitudeDepCache::mark_auto_installed(const PkgIterator &Pkg,
					   bool set_auto,
					   undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  action_group group(*this, undo);

  pre_package_state_changed();
  dirty=true;

  MarkAuto(Pkg, set_auto);
}

// Undoers for the tag manipulators below.
namespace
{
  class attach_user_tag_undoer : public undoable
  {
    aptitudeDepCache *parent;
    pkgCache::PkgIterator pkg;
    std::string tag;

  public:
    attach_user_tag_undoer(aptitudeDepCache *_parent,
		      const pkgCache::PkgIterator &_pkg,
		      const std::string &_tag)
      : parent(_parent), pkg(_pkg), tag(_tag)
    {
    }

    void undo()
    {
      parent->detach_user_tag(pkg, tag, NULL);
    }
  };

  class detach_user_tag_undoer : public undoable
  {
    aptitudeDepCache *parent;
    pkgCache::PkgIterator pkg;
    std::string tag;

  public:
    detach_user_tag_undoer(aptitudeDepCache *_parent,
			   const pkgCache::PkgIterator &_pkg,
			   const std::string &_tag)
      : parent(_parent), pkg(_pkg), tag(_tag)
    {
    }

    void undo()
    {
      parent->attach_user_tag(pkg, tag, NULL);
    }
  };
}

void aptitudeDepCache::attach_user_tag(const PkgIterator &pkg,
				       const std::string &tag,
				       undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  // Find the tag in our cache or add it.
  typedef std::map<std::string, user_tag_reference>::const_iterator index_ref;
  index_ref found = user_tags_index.find(tag);

  if(found == user_tags_index.end())
    {
      user_tag_reference loc = user_tags.size();
      user_tags.push_back(tag);
      std::pair<index_ref, bool> tmp(user_tags_index.insert(std::make_pair(tag, loc)));
      found = tmp.first;
    }

  std::pair<std::set<user_tag>::const_iterator, bool> insert_result =
    get_ext_state(pkg).user_tags.insert(user_tag(found->second));

  if(insert_result.second)
    {
      dirty = true;
      if(undo != NULL)
	undo->add_item(new attach_user_tag_undoer(this, pkg, tag));
    }
}

void aptitudeDepCache::detach_user_tag(const PkgIterator &pkg,
				       const std::string &tag,
				       undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  std::map<std::string, user_tag_reference>::const_iterator found =
    user_tags_index.find(tag);

  if(found == user_tags_index.end())
    return;

  std::set<user_tag>::size_type num_erased =
    get_ext_state(pkg).user_tags.erase(user_tag(found->second));

  if(num_erased > 0)
    {
      dirty = true;
      if(undo != NULL)
	undo->add_item(new detach_user_tag_undoer(this, pkg, tag));
    }
}

bool aptitudeDepCache::all_upgrade(bool with_autoinst, undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return false;
    }

  action_group group(*this, undo);

  pre_package_state_changed();

  pkgProblemResolver fixer(this);

  if(BrokenCount()!=0)
    return false;

  for(pkgCache::PkgIterator pkg=PkgBegin(); !pkg.end(); ++pkg)
    {
      if((*this)[pkg].Install())
	fixer.Protect(pkg);

      if(!is_held(pkg) &&
	 !pkg.CurrentVer().end() && !(*this)[pkg].Install())
	MarkInstall(pkg, with_autoinst);
    }

  bool rval=fixer.ResolveByKeep();

  return rval;
}

bool aptitudeDepCache::try_fix_broken(pkgProblemResolver &fixer, undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return false;
    }

  action_group group(*this, undo);

  pre_package_state_changed();
  dirty=true;
  bool founderr=false;
  if(!fixer.Resolve(true))
    founderr=true;

  if(founderr)
    _error->Error(_("Unable to correct dependencies, some packages cannot be installed"));

  return !founderr;
}

bool aptitudeDepCache::try_fix_broken(undo_group *undo)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return false;
    }

  pkgProblemResolver fixer(this);
  pre_package_state_changed();
  for(pkgCache::PkgIterator i=PkgBegin(); !i.end(); i++)
    {
      fixer.Clear(i);
      if(!i.CurrentVer().end() &&
	 get_ext_state(i).selection_state==pkgCache::pkgCache::State::Hold)
	fixer.Protect(i);
      else
	{
	  pkgDepCache::StateCache &state=(*this)[i];
	  if(state.InstBroken() || state.NowBroken())
            internal_mark_install(i, true, false);
	  else if(state.Delete())
	    fixer.Remove(i);
	}
    }

  return try_fix_broken(fixer, undo);
}

/** Update the given package's aptitude state based on its state
 *  according to dpkg/dselect.
 *
 *  \param Pkg the package to modify.
 */
void aptitudeDepCache::MarkFromDselect(const PkgIterator &Pkg)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  aptitude_state &state=get_ext_state(Pkg);

  if(Pkg->SelectedState!=state.selection_state)
    {
      switch(Pkg->SelectedState)
	{
	case pkgCache::State::Unknown:
	  break;
	case pkgCache::State::Purge:
	  if( (!Pkg.CurrentVer().end()) || !((*this)[Pkg].iFlags&Purge) )
	    mark_delete(Pkg, true, false, NULL);
	  else
	    mark_keep(Pkg, false, false, NULL);
	  break;
	case pkgCache::State::DeInstall:
	  if(!Pkg.CurrentVer().end())
	    mark_delete(Pkg, false, false, NULL);
	  else
	    mark_keep(Pkg, false, false, NULL);
	  break;
	case pkgCache::State::Hold:
	  if(!Pkg.CurrentVer().end())
	    mark_keep(Pkg, false, true, NULL);
	  break;
	case pkgCache::State::Install:
	  if(Pkg.CurrentVer().end())
	    mark_install(Pkg, false, false, NULL);
	  else
	    mark_keep(Pkg, false, false, NULL);
	  break;
	}
    }
}

void aptitudeDepCache::duplicate_cache(apt_state_snapshot *target)
  // Remember: the tables in the target have to be correctly sized!
{
  if(!target->PkgState)
    target->PkgState=new StateCache[Head().PackageCount];
  if(!target->DepState)
    target->DepState=new unsigned char[Head().DependsCount];
  if(!target->AptitudeState)
    target->AptitudeState=new aptitude_state[Head().PackageCount];

  memcpy(target->PkgState, PkgState, sizeof(StateCache)*Head().PackageCount);
  memcpy(target->DepState, DepState, sizeof(char)*Head().DependsCount);
  // memcpy doesn't work here because the aptitude_state structure
  // contains a std::string.  (would it be worthwhile/possible to
  // change things so that it doesn't?)
  for(unsigned int i=0; i<Head().PackageCount; ++i)
    target->AptitudeState[i]=package_states[i];

  target->iUsrSize=iUsrSize;
  target->iDownloadSize=iDownloadSize;
  target->iInstCount=iInstCount;
  target->iDelCount=iDelCount;
  target->iKeepCount=iKeepCount;
  target->iBrokenCount=iBrokenCount;
  target->iBadCount=iBadCount;
}

// Helpers for aptitudeDepCache::sweep().
namespace
{
  // Remove reverse dependencies of the given version from the set of
  // reinstated packages.  All the packages in the set are assumed to
  // be installed at their current version when checking dependencies.
  void remove_reverse_current_versions(std::set<pkgCache::PkgIterator> &reinstated,
				       pkgCache::VerIterator bad_ver)
  {
    logging::LoggerPtr logger(Loggers::getAptitudeAptCache());
    LOG_TRACE(logger, "Removing reverse dependencies of "
	      << bad_ver.ParentPkg().FullName(false) << " "
	      << bad_ver.VerStr() << " from the reinstate set.");
    // Follow direct revdeps.
    for(pkgCache::DepIterator dep = bad_ver.ParentPkg().RevDependsList();
	!dep.end(); ++dep)
      {
	// Skip self-deps.
	if(dep.ParentPkg() == bad_ver.ParentPkg())
	  continue;

	// Skip packages that aren't in the reinstate set.
	if(reinstated.find(dep.ParentPkg()) == reinstated.end())
	  continue;

	if((dep->Type == pkgCache::Dep::Depends ||
	    dep->Type == pkgCache::Dep::PreDepends) &&
	   dep.ParentVer() == dep.ParentPkg().CurrentVer() &&
	   _system->VS->CheckDep(bad_ver.VerStr(),
				 dep->CompareOp,
				 dep.TargetVer()))
	  {
	    LOG_DEBUG(logger,
		      "Not reinstating " << dep.ParentPkg().FullName(false)
		      << " due to its dependency on "
		      << bad_ver.ParentPkg().FullName(false)
		      << " " << bad_ver.VerStr());
	    reinstated.erase(dep.ParentPkg());
	    remove_reverse_current_versions(reinstated, dep.ParentVer());
	  }
      }

    // Follow indirect revdeps.
    for(pkgCache::PrvIterator prv = bad_ver.ProvidesList();
	!prv.end(); ++prv)
      for(pkgCache::DepIterator dep = prv.ParentPkg().RevDependsList();
	  !dep.end(); ++dep)
	{
	  // Skip self-deps.
	  if(dep.ParentPkg() == bad_ver.ParentPkg())
	    continue;

	  // Skip packages that aren't in the reinstate set.
	  if(reinstated.find(dep.ParentPkg()) == reinstated.end())
	    continue;

	  if((dep->Type == pkgCache::Dep::Depends ||
	      dep->Type == pkgCache::Dep::PreDepends) &&
	     dep.ParentVer() == dep.ParentPkg().CurrentVer() &&
	     _system->VS->CheckDep(prv.ProvideVersion(),
				   dep->CompareOp,
				   dep.TargetVer()))
	    {
	      LOG_DEBUG(logger,
			"Not reinstating " << dep.ParentPkg().FullName(false)
			<< " due to its dependency on "
			<< bad_ver.ParentPkg().FullName(false)
			<< " " << bad_ver.VerStr()
			<< " via the virtual package "
			<< prv.ParentPkg().Name());
	      reinstated.erase(dep.ParentPkg());
	      remove_reverse_current_versions(reinstated, dep.ParentVer());
	    }
	}
  }

  // Given a package that we know is not orphaned, add all the
  // transitive dependencies of its current version that are in
  // "reinstated" to the not-orphaned set.  (the condition on
  // reinstated is so we don't pick the wrong branch of an OR)
  void trace_not_orphaned(const pkgCache::PkgIterator &notOrphan,
			  const std::set<pkgCache::PkgIterator> &reinstated,
			  pkgDepCache &cache,
			  std::set<pkgCache::PkgIterator> &not_orphaned)
  {
    logging::LoggerPtr logger(Loggers::getAptitudeAptCache());

    if(not_orphaned.find(notOrphan) != not_orphaned.end())
      {
	LOG_TRACE(logger, "Ignoring " << notOrphan.FullName(false)
		  << ": it was already visited.");
	return;
      }

    // Sanity-check.
    if(notOrphan->CurrentState == pkgCache::State::NotInstalled ||
       notOrphan->CurrentState == pkgCache::State::ConfigFiles ||
       notOrphan.CurrentVer().end())
      {
	LOG_WARN(logger, "Sanity-check failed: assuming the package "
		 << notOrphan.FullName(false)
		 << " is orphaned, since it is not currently installed.");
	return;
      }

    if(reinstated.find(notOrphan) == reinstated.end())
      {
	LOG_DEBUG(logger, "Treating the package "
		  << notOrphan.FullName(false)
		  << " as an orphan, since it is not in the reinstatement set.");
	return;
      }

    LOG_DEBUG(logger, "The package " << notOrphan.FullName(false)
	      << " is not an orphan.");

    not_orphaned.insert(notOrphan);
    for(pkgCache::DepIterator dep = notOrphan.CurrentVer().DependsList();
	!dep.end(); ++dep)
      {
	if(!cache.IsImportantDep(dep))
	  continue;

	// If the target is installed, check if it matches the dep and
	// is reinstated.
	pkgCache::PkgIterator targetPkg(dep.TargetPkg());
	if(!(targetPkg->CurrentState == pkgCache::State::NotInstalled ||
	     targetPkg->CurrentState == pkgCache::State::ConfigFiles))
	  {
	    if(_system->VS->CheckDep(targetPkg.CurrentVer().VerStr(),
				     dep->CompareOp,
				     dep.TargetVer()))
	      trace_not_orphaned(targetPkg,
				 reinstated,
				 cache,
				 not_orphaned);
	  }

	for(pkgCache::PrvIterator prv = targetPkg.ProvidesList();
	    !prv.end(); ++prv)
	  {
	    if(_system->VS->CheckDep(prv.ProvideVersion(),
				     dep->CompareOp,
				     dep.TargetVer()))
	      trace_not_orphaned(prv.OwnerPkg(),
				 reinstated,
				 cache,
				 not_orphaned);
	  }
      }
  }

  // If the given package is a direct
  // dependency/pre-dependency/recommendation of a manually installed
  // package, find the set of its transitive dependencies that's
  // closed under reinstatement.  NB: we can assume here that the
  // reinstated set is consistent (all dependencies will be met)
  // because any strong dependencies on stuff that was thrown out
  // would also have been thrown out.
  void find_not_orphaned(const pkgCache::PkgIterator &maybeOrphan,
			 const std::set<pkgCache::PkgIterator> &reinstated,
			 pkgDepCache &cache,
			 std::set<pkgCache::PkgIterator> &not_orphaned)
  {
    logging::LoggerPtr logger(Loggers::getAptitudeAptCache());

    // Sanity-check.
    if(maybeOrphan->CurrentState == pkgCache::State::NotInstalled ||
       maybeOrphan->CurrentState == pkgCache::State::ConfigFiles ||
       maybeOrphan.CurrentVer().end())
      {
	LOG_WARN(logger, "Sanity-check failed: assuming the package "
		 << maybeOrphan.FullName(false)
		 << " is orphaned, since it is not currently installed.");
	return;
      }

    pkgCache::VerIterator maybeOrphanCurrentVer(maybeOrphan.CurrentVer());
    for(pkgCache::DepIterator dep = maybeOrphan.RevDependsList();
	!dep.end(); ++dep)
      {
	if(dep.ParentPkg() != maybeOrphan &&
	   (dep->Type == pkgCache::Dep::Depends ||
	    dep->Type == pkgCache::Dep::PreDepends))
	  {
	    if(_system->VS->CheckDep(maybeOrphanCurrentVer.VerStr(),
				     dep->CompareOp,
				     dep.TargetVer()))
	      trace_not_orphaned(maybeOrphan, reinstated, cache, not_orphaned);
	  }
      }


    for(pkgCache::PrvIterator prv = maybeOrphanCurrentVer.ProvidesList();
	!prv.end(); ++prv)
      for(pkgCache::DepIterator dep = prv.ParentPkg().RevDependsList();
	  !dep.end(); ++dep)
	{
	  if(dep.ParentPkg() != maybeOrphan &&
	     (dep->Type == pkgCache::Dep::Depends ||
	      dep->Type == pkgCache::Dep::PreDepends))
	    {
	      if(_system->VS->CheckDep(prv.ProvideVersion(),
				       dep->CompareOp,
				       dep.TargetVer()))
		trace_not_orphaned(maybeOrphan, reinstated, cache, not_orphaned);
	    }
	}
  }
}

void aptitudeDepCache::sweep()
{
  if(!aptcfg->FindB(PACKAGE "::Delete-Unused", true))
    return;

  logging::LoggerPtr logger(Loggers::getAptitudeAptCache());
  // "reinstated" holds packages that should be reinstated, and
  // "reinstated_bad" holds packages that *shouldn't* be reinstated
  // because they conflict with an installed package.
  //
  // We have to be careful because reinstating packages could lead to
  // situations where a valid resolver solution led to broken
  // dependencies.  For instance, the package that's being brought
  // back onto the system might conflict with another package that's
  // being installed by this solution!
  //
  // See Debian bugs #522881 and #524667.
  std::set<pkgCache::PkgIterator> reinstated, reinstated_bad;

  // Suppress intermediate removals.
  //
  // \todo this may cause problems if we do undo tracking via ActionGroups.
  pkgDepCache::ActionGroup group(*this);

  bool purge_unused = aptcfg->FindB(PACKAGE "::Purge-Unused", false);

  for(pkgCache::PkgIterator pkg = PkgBegin(); !pkg.end(); ++pkg)
    {
      if(PkgState[pkg->ID].Garbage)
	{
	  if(pkg.CurrentVer() != 0 && pkg->CurrentState != pkgCache::State::ConfigFiles)
	    {
	      // NB: apt sets the Garbage flag on packages that are
	      // being deleted and are automatic (this is due to some
	      // internal details of the mark&sweep algorithm and its
	      // aptitude heritage).  To compensate for this, we
	      // *only* set the unused-delete flag if the package was
	      // not previously being deleted.
	      if(!PkgState[pkg->ID].Delete())
		{
		  LOG_DEBUG(logger, "aptitudeDepCache::sweep(): Removing " << pkg.FullName(false) << ": it is unused.");

		  pre_package_state_changed();
		  MarkDelete(pkg, purge_unused);
		  package_states[pkg->ID].selection_state =
		    (purge_unused ? pkgCache::State::Purge : pkgCache::State::DeInstall);
		  package_states[pkg->ID].remove_reason = unused;
		}
	    }
	  else
	    {
	      if(pkg.CurrentVer().end())
		{
		  if((*this)[pkg].iFlags & Purge)
		    package_states[pkg->ID].selection_state = pkgCache::State::Purge;
		  else
		    package_states[pkg->ID].selection_state = pkgCache::State::DeInstall;
		}
	      else
		package_states[pkg->ID].selection_state = pkgCache::State::Install;
	      pre_package_state_changed();

	      if(!PkgState[pkg->ID].Keep())
		LOG_DEBUG(logger, "aptitudeDepCache::sweep(): Cancelling the installation of " << pkg.FullName(false) << ": it is unused.");

	      MarkKeep(pkg, false, false);
	    }
	}
      else if(PkgState[pkg->ID].Delete() && package_states[pkg->ID].remove_reason == unused)
	{
	  pkgCache::DepIterator conflict = is_conflicted(pkg.CurrentVer(), *this);
	  if(!conflict.end())
	    {
	      LOG_DEBUG(logger, "aptitudeDepCache::sweep(): not scheduling "
			<< pkg.FullName(false) << " for reinstatement due to the conflict between "
			<< conflict.ParentPkg().FullName(false)
			<< " and " << conflict.TargetPkg().FullName(false));

	      reinstated_bad.insert(pkg);
	    }
	  else
	    {
	      LOG_DEBUG(logger, "aptitudeDepCache::sweep(): provisionally scheduling "
			<< pkg.FullName(false) << " for reinstatement.");


	      reinstated.insert(pkg);
	    }
	}
    }

  // Remove packages that transitively depend on a package in
  // reinstated_bad from reinstated.
  for(std::set<pkgCache::PkgIterator>::const_iterator it =
	reinstated_bad.begin(); it != reinstated_bad.end(); ++it)
    remove_reverse_current_versions(reinstated, it->CurrentVer());

  // Figure out which reinstated packages aren't orphaned.
  std::set<pkgCache::PkgIterator> not_orphaned;
  for(std::set<pkgCache::PkgIterator>::const_iterator it =
	reinstated.begin(); it != reinstated.end(); ++it)
    find_not_orphaned(*it,
		      reinstated,
		      *this,
		      not_orphaned);

  // The ones that survived should be reinstated:
  for(std::set<pkgCache::PkgIterator>::const_iterator it =
	not_orphaned.begin(); it != not_orphaned.end(); ++it)
    {
      pkgCache::PkgIterator pkg(*it);
      LOG_INFO(logger, "aptitudeDepCache::sweep(): reinstating "
	       << pkg.FullName(false));
      MarkKeep(pkg, false, false);
    }
}

void aptitudeDepCache::begin_action_group()
{
  group_level++;
}

void aptitudeDepCache::end_action_group(undo_group *undo)
{
  std::set<pkgCache::PkgIterator> changed_packages;

  eassert(group_level>0);

  if(group_level==1)
    {
      if(read_only && !read_only_permission())
	{
	  if(group_level == 0)
	    read_only_fail();

	  group_level--;
	  return;
	}

      sweep();

      cleanup_after_change(undo, &changed_packages);

      duplicate_cache(&backup_state);

      package_state_changed();
      package_states_changed(&changed_packages);
    }

  group_level--;
}

const aptitudeDepCache::apt_state_snapshot *aptitudeDepCache::snapshot_apt_state()
{
  apt_state_snapshot *rval=new apt_state_snapshot;
  duplicate_cache(rval);

  return rval;
}

void aptitudeDepCache::restore_apt_state(const apt_state_snapshot *snapshot)
{
  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      return;
    }

  memcpy(PkgState, snapshot->PkgState, sizeof(StateCache)*Head().PackageCount);
  memcpy(DepState, snapshot->DepState, sizeof(char)*Head().DependsCount);
  // memcpy doesn't work here because the aptitude_state structure
  // contains a std::string.  (would it be worthwhile/possible to
  // change things so that it doesn't?)
  for(unsigned int i=0; i<Head().PackageCount; ++i)
    package_states[i]=snapshot->AptitudeState[i];

  iUsrSize=snapshot->iUsrSize;
  iDownloadSize=snapshot->iDownloadSize;
  iInstCount=snapshot->iInstCount;
  iDelCount=snapshot->iDelCount;
  iKeepCount=snapshot->iKeepCount;
  iBrokenCount=snapshot->iBrokenCount;
  iBadCount=snapshot->iBadCount;
}

void aptitudeDepCache::apply_solution(const generic_solution<aptitude_universe> &realSol,
				      undo_group *undo)
{
  logging::LoggerPtr logger(Loggers::getAptitudeAptCache());

  // Make a local copy so we don't crash when applying the solution:
  // applying the solution might trigger a callback that causes
  // something else to throw away its reference to the solution =>
  // BOOM.
  const generic_solution<aptitude_universe> sol(realSol);

  LOG_DEBUG(logger, "Applying solution: " << sol);

  if(read_only && !read_only_permission())
    {
      if(group_level == 0)
	read_only_fail();
      LOG_DEBUG(logger, "Not applying solution: the cache is read-only.");
      return;
    }

  action_group group(*this, undo);

  pre_package_state_changed();

  // Build a list of all the resolver versions that are to be
  // installed: versions selected in the solution as well as the
  // versions that were initially installed.  The boolean values that
  // tag along indicate whether each version was automatically
  // installed (true if it was, false if it wasn't).
  std::vector<std::pair<aptitude_resolver_version, bool> > versions;

  LOG_TRACE(logger, "Collecting initial versions from the solution:");

  std::set<aptitude_resolver_version> initial_versions;
  sol.get_initial_state().get_initial_versions(initial_versions);
  for(std::set<aptitude_resolver_version>::const_iterator it =
	initial_versions.begin(); it != initial_versions.end(); ++it)
    {
      aptitude_resolver_version ver(*it);

      LOG_TRACE(logger, "Adding initial version: " << ver);
      versions.push_back(std::make_pair(*it, false));
    }

  for(generic_choice_set<aptitude_universe>::const_iterator
	i = sol.get_choices().begin();
      i != sol.get_choices().end(); ++i)
    {
      if(i->get_type() == generic_choice<aptitude_universe>::install_version)
	{
	  aptitude_resolver_version ver(i->get_ver());
	  LOG_TRACE(logger, "Adding version chosen by the resolver: " << ver);
	  versions.push_back(std::make_pair(ver, true));
	}
      else
	LOG_TRACE(logger, "Skipping " << *i << ": it is not a version install.");
    }

  for(std::vector<std::pair<aptitude_resolver_version, bool> >::const_iterator it =
	versions.begin(); it != versions.end(); ++it)
    {
      const bool is_auto = it->second;

      LOG_TRACE(logger, "Selecting " << it->first << " "
		<< (is_auto ? "automatically" : "manually"));

      pkgCache::PkgIterator pkg = it->first.get_pkg();
      pkgCache::VerIterator curver=pkg.CurrentVer();
      pkgCache::VerIterator instver = (*apt_cache_file)[pkg].InstVerIter(*apt_cache_file);
      pkgCache::VerIterator actionver = it->first.get_ver();

      // Check what type of action it is.
      if(actionver.end())
	{
	  LOG_TRACE(logger, "Removing " << pkg.FullName(false));

	  // removal.
	  internal_mark_delete(pkg, false, false);
	  if(is_auto && !curver.end())
	    get_ext_state(pkg).remove_reason = from_resolver;
	}
      else if(actionver == curver)
	{
	  LOG_TRACE(logger, "Keeping " << pkg.FullName(false)
		    << " at its current version ("
		    << curver.VerStr() << ")");

	  internal_mark_keep(pkg, is_auto, false);
	}
      else
	// install a particular version that's not the current one.
	{
	  LOG_TRACE(logger, "Installing " << pkg.FullName(false) << " " << actionver.VerStr());

	  set_candidate_version(actionver, NULL);
	  internal_mark_install(pkg, false, false);
	  // Mark the package as automatic iff it isn't currently
	  // going to be installed.  Thus packages that are currently
	  // manually installed don't get marked as auto, packages
	  // that are going to be manually installed don't get marked
	  // as auto, but packages that are being removed *do* get
	  // marked as auto.
	  if(is_auto && instver.end())
	    MarkAuto(pkg, true);
	}
    }
}

aptitudeCacheFile::aptitudeCacheFile()
  :Map(NULL), Cache(NULL), DCache(NULL), have_system_lock(false), Policy(NULL)
{
}

aptitudeCacheFile::~aptitudeCacheFile()
{
  delete Cache;
  delete Map;
  ReleaseLock();

  delete DCache;
  delete Policy;
}

bool aptitudeCacheFile::Open(OpProgress &Progress, bool do_initselections,
			     bool WithLock, const char *status_fname)
{
  if(WithLock)
    {
      if(!_system->Lock())
	return false;

      have_system_lock=true;
    }

  if(_error->PendingError())
    return false;

  pkgSourceList List;
  if(!List.ReadMainList())
    return _error->Error(_("The list of sources could not be read."));

  // Read the caches:
  bool Res=pkgMakeStatusCache(List, Progress, &Map, !WithLock);
  Progress.Done();

  if(!Res)
    return _error->Error(_("The package lists or status file could not be parsed or opened."));

  if(!_error->empty())
    _error->Warning(_("You may want to update the package lists to correct these missing files"));

  Cache=new pkgCache(Map);
  if(_error->PendingError())
    return false;

  Policy=new aptitudePolicy(Cache);
  if(_error->PendingError())
    return false;
  if(ReadPinFile(*Policy) == false || ReadPinDir(*Policy) == false)
    return false;

  DCache=new aptitudeDepCache(Cache, Policy);
  if(_error->PendingError())
    return false;

  DCache->Init(&Progress, WithLock, do_initselections, status_fname);
  Progress.Done();

  if(_error->PendingError())
    return false;

  return true;
}

void aptitudeCacheFile::ReleaseLock()
{
  if(have_system_lock)
    {
      _system->UnLock();
      have_system_lock=false;
    }
}

bool aptitudeCacheFile::GainLock()
{
  if(have_system_lock)
    return true;

  if(!_system->Lock())
    return false;

  have_system_lock=true;
  return true;
}

bool aptitudeDepCache::is_held(const PkgIterator &pkg)
{
  aptitude_state state=get_ext_state(pkg);

  pkgCache::VerIterator candver=(*this)[pkg].CandidateVerIter(*this);

  return !pkg.CurrentVer().end() &&
    (state.selection_state == pkgCache::State::Hold ||
     (!candver.end() && candver.VerStr() == state.forbidver));
}

bool aptitudeDepCache::MarkFollowsRecommends()
{
  return pkgDepCache::MarkFollowsRecommends() ||
    aptcfg->FindB("Apt::Install-Recommends", true) ||
    aptcfg->FindB(PACKAGE "::Keep-Recommends", false);
}

bool aptitudeDepCache::MarkFollowsSuggests()
{
  return pkgDepCache::MarkFollowsSuggests() ||
    aptcfg->FindB(PACKAGE "::Keep-Suggests", false) ||
    aptcfg->FindB(PACKAGE "::Suggests-Important", false);
}

class AptitudeInRootSetFunc : public pkgDepCache::InRootSetFunc
{
  /** \brief A pointer to the cache in which we're matching. */
  aptitudeDepCache &cache;

  /** A pattern if one could be created; otherwise NULL. */
  cwidget::util::ref_ptr<aptitude::matching::pattern> p;

  /** \brief The search cache to use in applying this function. */
  cwidget::util::ref_ptr<aptitude::matching::search_cache> search_info;

  /** \b true if the package was successfully constructed. */
  bool constructedSuccessfully;

  /** The secondary test to apply.  Only set if creating the match
   *  succeeds.
   */
  pkgDepCache::InRootSetFunc *chain;
public:
  AptitudeInRootSetFunc(pkgDepCache::InRootSetFunc *_chain,
			aptitudeDepCache &_cache)
    : cache(_cache), p(NULL),
      search_info(aptitude::matching::search_cache::create()),
      constructedSuccessfully(false), chain(NULL)
  {
    std::string matchterm = aptcfg->Find(PACKAGE "::Keep-Unused-Pattern", "~nlinux-image-.*");
    if(matchterm.empty()) // Bug-compatibility with old versions.
      matchterm = aptcfg->Find(PACKAGE "::Delete-Unused-Pattern");

    if(matchterm.empty())
      constructedSuccessfully = true;
    else
      {
	p = aptitude::matching::parse(matchterm);
	if(p.valid())
	  constructedSuccessfully = true;
      }

    if(constructedSuccessfully)
      chain = _chain;
  }

  bool wasConstructedSuccessfully() const
  {
    return constructedSuccessfully;
  }

  bool InRootSet(const pkgCache::PkgIterator &pkg)
  {
    pkgRecords &records(cache.get_records());
    if(p.valid() && aptitude::matching::get_match(p, pkg, search_info, cache, records).valid())
      return true;
    else
      return chain != NULL && chain->InRootSet(pkg);
  }

  ~AptitudeInRootSetFunc()
  {
    delete chain;
  }
};

pkgDepCache::InRootSetFunc *aptitudeDepCache::GetRootSetFunc()
{
  InRootSetFunc *superFunc = pkgDepCache::GetRootSetFunc();

  AptitudeInRootSetFunc *f = new AptitudeInRootSetFunc(superFunc, *this);

  if(f->wasConstructedSuccessfully())
    return f;
  else
    {
      delete f;
      return superFunc;
    }
}

bool aptitudeDepCache::IsInstallOk(const pkgCache::PkgIterator &pkg,
				   bool AutoInst,
				   unsigned long Depth,
				   bool FromUser)
{
  if(Depth == 0)
    // This is a straight-up MarkInstall() call, not a dependency
    // resolution; allow it.
    return true;

  pkgCache::VerIterator candver((*this)[pkg].CandidateVerIter(*this));
  const aptitude_state &estate = get_ext_state(pkg);

  if(candver.end())
    {
      LOG_WARN(Loggers::getAptitudeAptCache(), "The package " << pkg.FullName(false) << " has no candidate version, unsure whether it should be installed.");
      return true;
    }

  if(estate.selection_state == pkgCache::State::Hold &&
     candver != pkg.CurrentVer())
    {
      LOG_INFO(Loggers::getAptitudeAptCache(), "Refusing to install version "
	       << candver.VerStr() << " of the held package "
	       << pkg.FullName(false));
      return false;
    }

  if(estate.forbidver == candver.VerStr())
    {
      LOG_INFO(Loggers::getAptitudeAptCache(),
	       "Refusing to install the forbidden version "
	       << candver.VerStr() << " of the package " << pkg.FullName(false));
      return false;
    }

  return true;
}

bool aptitudeDepCache::IsDeleteOk(const pkgCache::PkgIterator &pkg,
				  bool Purge,
				  unsigned long Depth,
				  bool FromUser)
{
  if(Depth == 0)
    // This is a straight-up MarkDelete() call, not a dependency
    // resolution; allow it.
    return true;

  if(!aptcfg->FindB(PACKAGE "::Auto-Install-Remove-Ok", false))
    return false;
  else
    {
      const aptitude_state &estate = get_ext_state(pkg);

      if(estate.selection_state == pkgCache::State::Hold)
	{
	  LOG_INFO(Loggers::getAptitudeAptCache(),
		   "Refusing to remove the held package "
		   << pkg.FullName(false));
	  return false;
	}

      return true;
    }
}