aboutsummaryrefslogtreecommitdiffstats
path: root/libqpdf/QPDF.cc
blob: 565c73f635b4bcd3cad4aeb94ee46169558185ed (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
#include <qpdf/qpdf-config.h>  // include first for large file support

#include <qpdf/QPDF.hh>

#include <atomic>
#include <vector>
#include <map>
#include <algorithm>
#include <limits>
#include <sstream>
#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include <qpdf/QTC.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/Pipeline.hh>
#include <qpdf/Pl_Discard.hh>
#include <qpdf/FileInputSource.hh>
#include <qpdf/BufferInputSource.hh>
#include <qpdf/OffsetInputSource.hh>

#include <qpdf/QPDFExc.hh>
#include <qpdf/QPDF_Null.hh>
#include <qpdf/QPDF_Dictionary.hh>
#include <qpdf/QPDF_Stream.hh>
#include <qpdf/QPDF_Array.hh>

// This must be a fixed value. This API returns a const reference to
// it, and the C API relies on its being static as well.
std::string const QPDF::qpdf_version(QPDF_VERSION);

static char const* EMPTY_PDF =
    "%PDF-1.3\n"
    "1 0 obj\n"
    "<< /Type /Catalog /Pages 2 0 R >>\n"
    "endobj\n"
    "2 0 obj\n"
    "<< /Type /Pages /Kids [] /Count 0 >>\n"
    "endobj\n"
    "xref\n"
    "0 3\n"
    "0000000000 65535 f \n"
    "0000000009 00000 n \n"
    "0000000058 00000 n \n"
    "trailer << /Size 3 /Root 1 0 R >>\n"
    "startxref\n"
    "110\n"
    "%%EOF\n";

class InvalidInputSource: public InputSource
{
  public:
    virtual ~InvalidInputSource() = default;
    virtual qpdf_offset_t findAndSkipNextEOL() override
    {
        throwException();
        return 0;
    }
    virtual std::string const& getName() const override
    {
        static std::string name("closed input source");
        return name;
    }
    virtual qpdf_offset_t tell() override
    {
        throwException();
        return 0;
    }
    virtual void seek(qpdf_offset_t offset, int whence) override
    {
        throwException();
    }
    virtual void rewind() override
    {
        throwException();
    }
    virtual size_t read(char* buffer, size_t length) override
    {
        throwException();
        return 0;
    }
    virtual void unreadCh(char ch) override
    {
        throwException();
    }

  private:
    void throwException()
    {
        throw std::logic_error(
            "QPDF operation attempted on a QPDF object with no input source."
            " QPDF operations are invalid before processFile (or another"
            " process method) or after closeInputSource");
    }
};

QPDF::ForeignStreamData::ForeignStreamData(
    PointerHolder<EncryptionParameters> encp,
    PointerHolder<InputSource> file,
    int foreign_objid,
    int foreign_generation,
    qpdf_offset_t offset,
    size_t length,
    QPDFObjectHandle local_dict)
    :
    encp(encp),
    file(file),
    foreign_objid(foreign_objid),
    foreign_generation(foreign_generation),
    offset(offset),
    length(length),
    local_dict(local_dict)
{
}

QPDF::CopiedStreamDataProvider::CopiedStreamDataProvider(
    QPDF& destination_qpdf) :
    QPDFObjectHandle::StreamDataProvider(true),
    destination_qpdf(destination_qpdf)
{
}

bool
QPDF::CopiedStreamDataProvider::provideStreamData(
    int objid, int generation, Pipeline* pipeline,
    bool suppress_warnings, bool will_retry)
{
    PointerHolder<ForeignStreamData> foreign_data =
        this->foreign_stream_data[QPDFObjGen(objid, generation)];
    bool result = false;
    if (foreign_data.get())
    {
        result = destination_qpdf.pipeForeignStreamData(
            foreign_data, pipeline, suppress_warnings, will_retry);
        QTC::TC("qpdf", "QPDF copy foreign with data",
                result ? 0 : 1);
    }
    else
    {
        QPDFObjectHandle foreign_stream =
            this->foreign_streams[QPDFObjGen(objid, generation)];
        result = foreign_stream.pipeStreamData(
            pipeline, nullptr, 0, qpdf_dl_none,
            suppress_warnings, will_retry);
        QTC::TC("qpdf", "QPDF copy foreign with foreign_stream",
                result ? 0 : 1);
    }
    return result;
}

void
QPDF::CopiedStreamDataProvider::registerForeignStream(
    QPDFObjGen const& local_og, QPDFObjectHandle foreign_stream)
{
    this->foreign_streams[local_og] = foreign_stream;
}

void
QPDF::CopiedStreamDataProvider::registerForeignStream(
    QPDFObjGen const& local_og,
    PointerHolder<ForeignStreamData> foreign_stream)
{
    this->foreign_stream_data[local_og] = foreign_stream;
}

QPDF::StringDecrypter::StringDecrypter(QPDF* qpdf, int objid, int gen) :
    qpdf(qpdf),
    objid(objid),
    gen(gen)
{
}

void
QPDF::StringDecrypter::decryptString(std::string& val)
{
    qpdf->decryptString(val, objid, gen);
}

std::string const&
QPDF::QPDFVersion()
{
    // The C API relies on this being a static value.
    return QPDF::qpdf_version;
}

QPDF::EncryptionParameters::EncryptionParameters() :
    encrypted(false),
    encryption_initialized(false),
    encryption_V(0),
    encryption_R(0),
    encrypt_metadata(true),
    cf_stream(e_none),
    cf_string(e_none),
    cf_file(e_none),
    cached_key_objid(0),
    cached_key_generation(0),
    user_password_matched(false),
    owner_password_matched(false)
{
}

QPDF::Members::Members() :
    unique_id(0),
    file(new InvalidInputSource()),
    provided_password_is_hex_key(false),
    ignore_xref_streams(false),
    suppress_warnings(false),
    out_stream(&std::cout),
    err_stream(&std::cerr),
    attempt_recovery(true),
    encp(new EncryptionParameters),
    pushed_inherited_attributes_to_pages(false),
    copied_stream_data_provider(0),
    reconstructed_xref(false),
    fixed_dangling_refs(false),
    immediate_copy_from(false),
    in_parse(false),
    parsed(false),
    ever_replaced_objects(false),
    first_xref_item_offset(0),
    uncompressed_after_compressed(false)
{
}

QPDF::Members::~Members()
{
}

QPDF::QPDF() :
    m(new Members())
{
    m->tokenizer.allowEOF();
    // Generate a unique ID. It just has to be unique among all QPDF
    // objects allocated throughout the lifetime of this running
    // application.
    static std::atomic<unsigned long long> unique_id{0};
    m->unique_id = unique_id.fetch_add(1ULL);
}

QPDF::~QPDF()
{
    // If two objects are mutually referential (through each object
    // having an array or dictionary that contains an indirect
    // reference to the other), the circular references in the
    // PointerHolder objects will prevent the objects from being
    // deleted.  Walk through all objects in the object cache, which
    // is those objects that we read from the file, and break all
    // resolved references.  At this point, obviously no one is still
    // using the QPDF object, but we'll explicitly clear the xref
    // table anyway just to prevent any possibility of resolve()
    // succeeding.  Note that we can't break references like this at
    // any time when the QPDF object is active.  If we do, the next
    // reference will reread the object from the file, which would
    // have the effect of undoing any modifications that may have been
    // made to any of the objects.
    this->m->xref_table.clear();
    for (std::map<QPDFObjGen, ObjCache>::iterator iter =
             this->m->obj_cache.begin();
	 iter != this->m->obj_cache.end(); ++iter)
    {
	QPDFObject::ObjAccessor::releaseResolved(
	    (*iter).second.object.get());
    }
}

void
QPDF::processFile(char const* filename, char const* password)
{
    FileInputSource* fi = new FileInputSource();
    fi->setFilename(filename);
    processInputSource(fi, password);
}

void
QPDF::processFile(char const* description, FILE* filep,
                  bool close_file, char const* password)
{
    FileInputSource* fi = new FileInputSource();
    fi->setFile(description, filep, close_file);
    processInputSource(fi, password);
}

void
QPDF::processMemoryFile(char const* description,
			char const* buf, size_t length,
			char const* password)
{
    processInputSource(
	new BufferInputSource(
            description,
            new Buffer(QUtil::unsigned_char_pointer(buf), length),
            true),
        password);
}

void
QPDF::processInputSource(PointerHolder<InputSource> source,
                         char const* password)
{
    this->m->file = source;
    parse(password);
}

void
QPDF::closeInputSource()
{
    this->m->file = new InvalidInputSource();
}

void
QPDF::setPasswordIsHexKey(bool val)
{
    this->m->provided_password_is_hex_key = val;
}

void
QPDF::emptyPDF()
{
    processMemoryFile("empty PDF", EMPTY_PDF, strlen(EMPTY_PDF));
}

void
QPDF::registerStreamFilter(
    std::string const& filter_name,
    std::function<std::shared_ptr<QPDFStreamFilter> ()> factory)
{
    QPDF_Stream::registerStreamFilter(filter_name, factory);
}

void
QPDF::setIgnoreXRefStreams(bool val)
{
    this->m->ignore_xref_streams = val;
}

void
QPDF::setOutputStreams(std::ostream* out, std::ostream* err)
{
    this->m->out_stream = out ? out : &std::cout;
    this->m->err_stream = err ? err : &std::cerr;
}

void
QPDF::setSuppressWarnings(bool val)
{
    this->m->suppress_warnings = val;
}

void
QPDF::setAttemptRecovery(bool val)
{
    this->m->attempt_recovery = val;
}

void
QPDF::setImmediateCopyFrom(bool val)
{
    this->m->immediate_copy_from = val;
}

std::vector<QPDFExc>
QPDF::getWarnings()
{
    std::vector<QPDFExc> result = this->m->warnings;
    this->m->warnings.clear();
    return result;
}

bool
QPDF::anyWarnings() const
{
    return ! this->m->warnings.empty();
}

size_t
QPDF::numWarnings() const
{
    return this->m->warnings.size();
}

bool
QPDF::findHeader()
{
    qpdf_offset_t global_offset = this->m->file->tell();
    std::string line = this->m->file->readLine(1024);
    char const* p = line.c_str();
    if (strncmp(p, "%PDF-", 5) != 0)
    {
        throw std::logic_error("findHeader is not looking at %PDF-");
    }
    p += 5;
    std::string version;
    // Note: The string returned by line.c_str() is always
    // null-terminated. The code below never overruns the buffer
    // because a null character always short-circuits further
    // advancement.
    bool valid = QUtil::is_digit(*p);
    if (valid)
    {
        while (QUtil::is_digit(*p))
        {
            version.append(1, *p++);
        }
        if ((*p == '.') && QUtil::is_digit(*(p+1)))
        {
            version.append(1, *p++);
            while (QUtil::is_digit(*p))
            {
                version.append(1, *p++);
            }
        }
        else
        {
            valid = false;
        }
    }
    if (valid)
    {
        this->m->pdf_version = version;
        if (global_offset != 0)
        {
            // Empirical evidence strongly suggests that when there is
            // leading material prior to the PDF header, all explicit
            // offsets in the file are such that 0 points to the
            // beginning of the header.
            QTC::TC("qpdf", "QPDF global offset");
            this->m->file = new OffsetInputSource(this->m->file, global_offset);
        }
    }
    return valid;
}

bool
QPDF::findStartxref()
{
    QPDFTokenizer::Token t = readToken(this->m->file);
    if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "startxref"))
    {
        t = readToken(this->m->file);
        if (t.getType() == QPDFTokenizer::tt_integer)
        {
            // Position in front of offset token
            this->m->file->seek(this->m->file->getLastOffset(), SEEK_SET);
            return true;
        }
    }
    return false;
}

void
QPDF::parse(char const* password)
{
    if (password)
    {
	this->m->encp->provided_password = password;
    }

    // Find the header anywhere in the first 1024 bytes of the file.
    PatternFinder hf(*this, &QPDF::findHeader);
    if (! this->m->file->findFirst("%PDF-", 0, 1024, hf))
    {
	QTC::TC("qpdf", "QPDF not a pdf file");
	warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
                     "", 0, "can't find PDF header"));
        // QPDFWriter writes files that usually require at least
        // version 1.2 for /FlateDecode
        this->m->pdf_version = "1.2";
    }

    // PDF spec says %%EOF must be found within the last 1024 bytes of
    // the file.  We add an extra 30 characters to leave room for the
    // startxref stuff.
    this->m->file->seek(0, SEEK_END);
    qpdf_offset_t end_offset = this->m->file->tell();
    qpdf_offset_t start_offset = (end_offset > 1054 ? end_offset - 1054 : 0);
    PatternFinder sf(*this, &QPDF::findStartxref);
    qpdf_offset_t xref_offset = 0;
    if (this->m->file->findLast("startxref", start_offset, 0, sf))
    {
        xref_offset = QUtil::string_to_ll(
            readToken(this->m->file).getValue().c_str());
    }

    try
    {
	if (xref_offset == 0)
	{
	    QTC::TC("qpdf", "QPDF can't find startxref");
	    throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
			  "can't find startxref");
	}
        try
        {
            read_xref(xref_offset);
        }
        catch (QPDFExc&)
        {
            throw;
        }
        catch (std::exception& e)
        {
	    throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
			  std::string("error reading xref: ") + e.what());

        }
    }
    catch (QPDFExc& e)
    {
	if (this->m->attempt_recovery)
	{
	    reconstruct_xref(e);
	    QTC::TC("qpdf", "QPDF reconstructed xref table");
	}
	else
	{
	    throw e;
	}
    }

    initializeEncryption();
    this->m->parsed = true;
}

void
QPDF::inParse(bool v)
{
    if (this->m->in_parse == v)
    {
        // This happens of QPDFObjectHandle::parseInternal tries to
        // resolve an indirect object while it is parsing.
        throw std::logic_error(
            "QPDF: re-entrant parsing detected. This is a qpdf bug."
            " Please report at https://github.com/qpdf/qpdf/issues.");
    }
    this->m->in_parse = v;
}

void
QPDF::warn(QPDFExc const& e)
{
    this->m->warnings.push_back(e);
    if (! this->m->suppress_warnings)
    {
	*this->m->err_stream
            << "WARNING: "
            << this->m->warnings.back().what() << std::endl;
    }
}

void
QPDF::setTrailer(QPDFObjectHandle obj)
{
    if (this->m->trailer.isInitialized())
    {
	return;
    }
    this->m->trailer = obj;
}

void
QPDF::reconstruct_xref(QPDFExc& e)
{
    if (this->m->reconstructed_xref)
    {
        // Avoid xref reconstruction infinite loops. This is getting
        // very hard to reproduce because qpdf is throwing many fewer
        // exceptions while parsing. Most situations are warnings now.
        throw e;
    }

    this->m->reconstructed_xref = true;

    warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
		 "file is damaged"));
    warn(e);
    warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
		 "Attempting to reconstruct cross-reference table"));

    // Delete all references to type 1 (uncompressed) objects
    std::set<QPDFObjGen> to_delete;
    for (std::map<QPDFObjGen, QPDFXRefEntry>::iterator iter =
	     this->m->xref_table.begin();
	 iter != this->m->xref_table.end(); ++iter)
    {
	if (((*iter).second).getType() == 1)
	{
	    to_delete.insert((*iter).first);
	}
    }
    for (std::set<QPDFObjGen>::iterator iter = to_delete.begin();
	 iter != to_delete.end(); ++iter)
    {
	this->m->xref_table.erase(*iter);
    }

    this->m->file->seek(0, SEEK_END);
    qpdf_offset_t eof = this->m->file->tell();
    this->m->file->seek(0, SEEK_SET);
    qpdf_offset_t line_start = 0;
    // Don't allow very long tokens here during recovery.
    static size_t const MAX_LEN = 100;
    while (this->m->file->tell() < eof)
    {
        this->m->file->findAndSkipNextEOL();
        qpdf_offset_t next_line_start = this->m->file->tell();
        this->m->file->seek(line_start, SEEK_SET);
        QPDFTokenizer::Token t1 = readToken(this->m->file, MAX_LEN);
        qpdf_offset_t token_start =
            this->m->file->tell() - toO(t1.getValue().length());
        if (token_start >= next_line_start)
        {
            // don't process yet -- wait until we get to the line
            // containing this token
        }
	else if (t1.getType() == QPDFTokenizer::tt_integer)
        {
            QPDFTokenizer::Token t2 =
                readToken(this->m->file, MAX_LEN);
            QPDFTokenizer::Token t3 =
                readToken(this->m->file, MAX_LEN);
            if ((t2.getType() == QPDFTokenizer::tt_integer) &&
                (t3 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj")))
            {
                int obj = QUtil::string_to_int(t1.getValue().c_str());
                int gen = QUtil::string_to_int(t2.getValue().c_str());
                insertXrefEntry(obj, 1, token_start, gen, true);
            }
        }
        else if ((! this->m->trailer.isInitialized()) &&
                 (t1 == QPDFTokenizer::Token(
                     QPDFTokenizer::tt_word, "trailer")))
        {
            QPDFObjectHandle t =
                    readObject(this->m->file, "trailer", 0, 0, false);
            if (! t.isDictionary())
            {
                // Oh well.  It was worth a try.
            }
            else
            {
                setTrailer(t);
            }
	}
        this->m->file->seek(next_line_start, SEEK_SET);
        line_start = next_line_start;
    }

    if (! this->m->trailer.isInitialized())
    {
	// We could check the last encountered object to see if it was
	// an xref stream.  If so, we could try to get the trailer
	// from there.  This may make it possible to recover files
	// with bad startxref pointers even when they have object
	// streams.

	throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
		      "unable to find trailer "
		      "dictionary while recovering damaged file");
    }

    // We could iterate through the objects looking for streams and
    // try to find objects inside of them, but it's probably not worth
    // the trouble.  Acrobat can't recover files with any errors in an
    // xref stream, and this would be a real long shot anyway.  If we
    // wanted to do anything that involved looking at stream contents,
    // we'd also have to call initializeEncryption() here.  It's safe
    // to call it more than once.
}

void
QPDF::read_xref(qpdf_offset_t xref_offset)
{
    std::map<int, int> free_table;
    std::set<qpdf_offset_t> visited;
    while (xref_offset)
    {
        visited.insert(xref_offset);
        char buf[7];
        memset(buf, 0, sizeof(buf));
	this->m->file->seek(xref_offset, SEEK_SET);
        // Some files miss the mark a little with startxref. We could
        // do a better job of searching in the neighborhood for
        // something that looks like either an xref table or stream,
        // but the simple heuristic of skipping whitespace can help
        // with the xref table case and is harmless with the stream
        // case.
        bool done = false;
        bool skipped_space = false;
        while (! done)
        {
            char ch;
            if (1 == this->m->file->read(&ch, 1))
            {
                if (QUtil::is_space(ch))
                {
                    skipped_space = true;
                }
                else
                {
                    this->m->file->unreadCh(ch);
                    done = true;
                }
            }
            else
            {
                QTC::TC("qpdf", "QPDF eof skipping spaces before xref",
                        skipped_space ? 0 : 1);
                done = true;
            }
        }

	this->m->file->read(buf, sizeof(buf) - 1);
        // The PDF spec says xref must be followed by a line
        // terminator, but files exist in the wild where it is
        // terminated by arbitrary whitespace.
        if ((strncmp(buf, "xref", 4) == 0) &&
            QUtil::is_space(buf[4]))
	{
            if (skipped_space)
            {
                QTC::TC("qpdf", "QPDF xref skipped space");
                warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
                             "", 0,
                             "extraneous whitespace seen before xref"));
            }
            QTC::TC("qpdf", "QPDF xref space",
                    ((buf[4] == '\n') ? 0 :
                     (buf[4] == '\r') ? 1 :
                     (buf[4] == ' ') ? 2 : 9999));
            int skip = 4;
            // buf is null-terminated, and QUtil::is_space('\0') is
            // false, so this won't overrun.
            while (QUtil::is_space(buf[skip]))
            {
                ++skip;
            }
            xref_offset = read_xrefTable(xref_offset + skip);
	}
	else
	{
	    xref_offset = read_xrefStream(xref_offset);
	}
        if (visited.count(xref_offset) != 0)
        {
            QTC::TC("qpdf", "QPDF xref loop");
            throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
                          "loop detected following xref tables");
        }
    }

    if (! this->m->trailer.isInitialized())
    {
        throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
                      "unable to find trailer while reading xref");
    }
    int size = this->m->trailer.getKey("/Size").getIntValueAsInt();
    int max_obj = 0;
    if (! this->m->xref_table.empty())
    {
	max_obj = (*(this->m->xref_table.rbegin())).first.getObj();
    }
    if (! this->m->deleted_objects.empty())
    {
	max_obj = std::max(max_obj, *(this->m->deleted_objects.rbegin()));
    }
    if ((size < 1) || (size - 1 != max_obj))
    {
	QTC::TC("qpdf", "QPDF xref size mismatch");
	warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
		     std::string("reported number of objects (") +
		     QUtil::int_to_string(size) +
		     ") is not one plus the highest object number (" +
		     QUtil::int_to_string(max_obj) + ")"));
    }

    // We no longer need the deleted_objects table, so go ahead and
    // clear it out to make sure we never depend on its being set.
    this->m->deleted_objects.clear();
}

bool
QPDF::parse_xrefFirst(std::string const& line,
                      int& obj, int& num, int& bytes)
{
    // is_space and is_digit both return false on '\0', so this will
    // not overrun the null-terminated buffer.
    char const* p = line.c_str();
    char const* start = line.c_str();

    // Skip zero or more spaces
    while (QUtil::is_space(*p))
    {
        ++p;
    }
    // Require digit
    if (! QUtil::is_digit(*p))
    {
        return false;
    }
    // Gather digits
    std::string obj_str;
    while (QUtil::is_digit(*p))
    {
        obj_str.append(1, *p++);
    }
    // Require space
    if (! QUtil::is_space(*p))
    {
        return false;
    }
    // Skip spaces
    while (QUtil::is_space(*p))
    {
        ++p;
    }
    // Require digit
    if (! QUtil::is_digit(*p))
    {
        return false;
    }
    // Gather digits
    std::string num_str;
    while (QUtil::is_digit(*p))
    {
        num_str.append(1, *p++);
    }
    // Skip any space including line terminators
    while (QUtil::is_space(*p))
    {
        ++p;
    }
    bytes = toI(p - start);
    obj = QUtil::string_to_int(obj_str.c_str());
    num = QUtil::string_to_int(num_str.c_str());
    return true;
}

bool
QPDF::parse_xrefEntry(std::string const& line,
                      qpdf_offset_t& f1, int& f2, char& type)
{
    // is_space and is_digit both return false on '\0', so this will
    // not overrun the null-terminated buffer.
    char const* p = line.c_str();

    // Skip zero or more spaces. There aren't supposed to be any.
    bool invalid = false;
    while (QUtil::is_space(*p))
    {
        ++p;
        QTC::TC("qpdf", "QPDF ignore first space in xref entry");
        invalid = true;
    }
    // Require digit
    if (! QUtil::is_digit(*p))
    {
        return false;
    }
    // Gather digits
    std::string f1_str;
    while (QUtil::is_digit(*p))
    {
        f1_str.append(1, *p++);
    }
    // Require space
    if (! QUtil::is_space(*p))
    {
        return false;
    }
    if (QUtil::is_space(*(p+1)))
    {
        QTC::TC("qpdf", "QPDF ignore first extra space in xref entry");
        invalid = true;
    }
    // Skip spaces
    while (QUtil::is_space(*p))
    {
        ++p;
    }
    // Require digit
    if (! QUtil::is_digit(*p))
    {
        return false;
    }
    // Gather digits
    std::string f2_str;
    while (QUtil::is_digit(*p))
    {
        f2_str.append(1, *p++);
    }
    // Require space
    if (! QUtil::is_space(*p))
    {
        return false;
    }
    if (QUtil::is_space(*(p+1)))
    {
        QTC::TC("qpdf", "QPDF ignore second extra space in xref entry");
        invalid = true;
    }
    // Skip spaces
    while (QUtil::is_space(*p))
    {
        ++p;
    }
    if ((*p == 'f') || (*p == 'n'))
    {
        type = *p;
    }
    else
    {
        return false;
    }
    if ((f1_str.length() != 10) || (f2_str.length() != 5))
    {
        QTC::TC("qpdf", "QPDF ignore length error xref entry");
        invalid = true;
    }

    if (invalid)
    {
        warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
                     "xref table",
                     this->m->file->getLastOffset(),
                     "accepting invalid xref table entry"));
    }

    f1 = QUtil::string_to_ll(f1_str.c_str());
    f2 = QUtil::string_to_int(f2_str.c_str());

    return true;
}

qpdf_offset_t
QPDF::read_xrefTable(qpdf_offset_t xref_offset)
{
    std::vector<QPDFObjGen> deleted_items;

    this->m->file->seek(xref_offset, SEEK_SET);
    bool done = false;
    while (! done)
    {
        char linebuf[51];
        memset(linebuf, 0, sizeof(linebuf));
        this->m->file->read(linebuf, sizeof(linebuf) - 1);
	std::string line = linebuf;
        int obj = 0;
        int num = 0;
        int bytes = 0;
        if (! parse_xrefFirst(line, obj, num, bytes))
	{
	    QTC::TC("qpdf", "QPDF invalid xref");
	    throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			  "xref table", this->m->file->getLastOffset(),
			  "xref syntax invalid");
	}
        this->m->file->seek(this->m->file->getLastOffset() + bytes, SEEK_SET);
	for (qpdf_offset_t i = obj; i - num < obj; ++i)
	{
	    if (i == 0)
	    {
		// This is needed by checkLinearization()
		this->m->first_xref_item_offset = this->m->file->tell();
	    }
	    std::string xref_entry = this->m->file->readLine(30);
            // For xref_table, these will always be small enough to be ints
	    qpdf_offset_t f1 = 0;
	    int f2 = 0;
	    char type = '\0';
            if (! parse_xrefEntry(xref_entry, f1, f2, type))
	    {
		QTC::TC("qpdf", "QPDF invalid xref entry");
		throw QPDFExc(
		    qpdf_e_damaged_pdf, this->m->file->getName(),
		    "xref table", this->m->file->getLastOffset(),
		    "invalid xref entry (obj=" +
		    QUtil::int_to_string(i) + ")");
	    }
	    if (type == 'f')
	    {
		// Save deleted items until after we've checked the
		// XRefStm, if any.
		deleted_items.push_back(QPDFObjGen(toI(i), f2));
	    }
	    else
	    {
		insertXrefEntry(toI(i), 1, f1, f2);
	    }
	}
	qpdf_offset_t pos = this->m->file->tell();
	QPDFTokenizer::Token t = readToken(this->m->file);
	if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "trailer"))
	{
	    done = true;
	}
	else
	{
	    this->m->file->seek(pos, SEEK_SET);
	}
    }

    // Set offset to previous xref table if any
    QPDFObjectHandle cur_trailer =
	readObject(this->m->file, "trailer", 0, 0, false);
    if (! cur_trailer.isDictionary())
    {
	QTC::TC("qpdf", "QPDF missing trailer");
	throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
		      "", this->m->file->getLastOffset(),
		      "expected trailer dictionary");
    }

    if (! this->m->trailer.isInitialized())
    {
	setTrailer(cur_trailer);

	if (! this->m->trailer.hasKey("/Size"))
	{
	    QTC::TC("qpdf", "QPDF trailer lacks size");
	    throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			  "trailer", this->m->file->getLastOffset(),
			  "trailer dictionary lacks /Size key");
	}
	if (! this->m->trailer.getKey("/Size").isInteger())
	{
	    QTC::TC("qpdf", "QPDF trailer size not integer");
	    throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			  "trailer", this->m->file->getLastOffset(),
			  "/Size key in trailer dictionary is not "
			  "an integer");
	}
    }

    if (cur_trailer.hasKey("/XRefStm"))
    {
	if (this->m->ignore_xref_streams)
	{
	    QTC::TC("qpdf", "QPDF ignoring XRefStm in trailer");
	}
	else
	{
	    if (cur_trailer.getKey("/XRefStm").isInteger())
	    {
		// Read the xref stream but disregard any return value
		// -- we'll use our trailer's /Prev key instead of the
		// xref stream's.
		(void) read_xrefStream(
		    cur_trailer.getKey("/XRefStm").getIntValue());
	    }
	    else
	    {
		throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			      "xref stream", xref_offset,
			      "invalid /XRefStm");
	    }
	}
    }

    // Handle any deleted items now that we've read the /XRefStm.
    for (std::vector<QPDFObjGen>::iterator iter = deleted_items.begin();
	 iter != deleted_items.end(); ++iter)
    {
	QPDFObjGen& og = *iter;
	insertXrefEntry(og.getObj(), 0, 0, og.getGen());
    }

    if (cur_trailer.hasKey("/Prev"))
    {
	if (! cur_trailer.getKey("/Prev").isInteger())
	{
	    QTC::TC("qpdf", "QPDF trailer prev not integer");
	    throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			  "trailer", this->m->file->getLastOffset(),
			  "/Prev key in trailer dictionary is not "
			  "an integer");
	}
	QTC::TC("qpdf", "QPDF prev key in trailer dictionary");
	xref_offset = cur_trailer.getKey("/Prev").getIntValue();
    }
    else
    {
	xref_offset = 0;
    }

    return xref_offset;
}

qpdf_offset_t
QPDF::read_xrefStream(qpdf_offset_t xref_offset)
{
    bool found = false;
    if (! this->m->ignore_xref_streams)
    {
	int xobj;
	int xgen;
	QPDFObjectHandle xref_obj;
	try
	{
	    xref_obj = readObjectAtOffset(
		false, xref_offset, "xref stream", -1, 0, xobj, xgen);
	}
	catch (QPDFExc&)
	{
	    // ignore -- report error below
	}
        if (xref_obj.isStreamOfType("/XRef"))
	{
	    QTC::TC("qpdf", "QPDF found xref stream");
	    found = true;
	    xref_offset = processXRefStream(xref_offset, xref_obj);
	}
    }

    if (! found)
    {
	QTC::TC("qpdf", "QPDF can't find xref");
	throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
		      "", xref_offset, "xref not found");
    }

    return xref_offset;
}

qpdf_offset_t
QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj)
{
    QPDFObjectHandle dict = xref_obj.getDict();
    QPDFObjectHandle W_obj = dict.getKey("/W");
    QPDFObjectHandle Index_obj = dict.getKey("/Index");
    if (! (W_obj.isArray() &&
	   (W_obj.getArrayNItems() >= 3) &&
	   W_obj.getArrayItem(0).isInteger() &&
	   W_obj.getArrayItem(1).isInteger() &&
	   W_obj.getArrayItem(2).isInteger() &&
	   dict.getKey("/Size").isInteger() &&
	   (Index_obj.isArray() || Index_obj.isNull())))
    {
	throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
		      "xref stream", xref_offset,
		      "Cross-reference stream does not have"
		      " proper /W and /Index keys");
    }

    int W[3];
    size_t entry_size = 0;
    int max_bytes = sizeof(qpdf_offset_t);
    for (int i = 0; i < 3; ++i)
    {
	W[i] = W_obj.getArrayItem(i).getIntValueAsInt();
        if (W[i] > max_bytes)
        {
            throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
                          "xref stream", xref_offset,
                          "Cross-reference stream's /W contains"
                          " impossibly large values");
        }
	entry_size += toS(W[i]);
    }
    if (entry_size == 0)
    {
        throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
                      "xref stream", xref_offset,
                      "Cross-reference stream's /W indicates"
                      " entry size of 0");
    }
    unsigned long long max_num_entries =
        static_cast<unsigned long long>(-1) / entry_size;

    std::vector<long long> indx;
    if (Index_obj.isArray())
    {
	int n_index = Index_obj.getArrayNItems();
	if ((n_index % 2) || (n_index < 2))
	{
	    throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			  "xref stream", xref_offset,
			  "Cross-reference stream's /Index has an"
			  " invalid number of values");
	}
	for (int i = 0; i < n_index; ++i)
	{
	    if (Index_obj.getArrayItem(i).isInteger())
	    {
		indx.push_back(Index_obj.getArrayItem(i).getIntValue());
	    }
	    else
	    {
		throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			      "xref stream", xref_offset,
			      "Cross-reference stream's /Index's item " +
			      QUtil::int_to_string(i) +
			      " is not an integer");
	    }
	}
	QTC::TC("qpdf", "QPDF xref /Index is array",
		n_index == 2 ? 0 : 1);
    }
    else
    {
	QTC::TC("qpdf", "QPDF xref /Index is null");
	long long size = dict.getKey("/Size").getIntValue();
	indx.push_back(0);
	indx.push_back(size);
    }

    size_t num_entries = 0;
    for (size_t i = 1; i < indx.size(); i += 2)
    {
        if (indx.at(i) > QIntC::to_longlong(max_num_entries - num_entries))
        {
            throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
                          "xref stream", xref_offset,
                          "Cross-reference stream claims to contain"
                          " too many entries: " +
                          QUtil::int_to_string(indx.at(i)) + " " +
                          QUtil::uint_to_string(max_num_entries) + " " +
                          QUtil::uint_to_string(num_entries));
        }
	num_entries += toS(indx.at(i));
    }

    // entry_size and num_entries have both been validated to ensure
    // that this multiplication does not cause an overflow.
    size_t expected_size = entry_size * num_entries;

    PointerHolder<Buffer> bp = xref_obj.getStreamData(qpdf_dl_specialized);
    size_t actual_size = bp->getSize();

    if (expected_size != actual_size)
    {
	QPDFExc x(qpdf_e_damaged_pdf, this->m->file->getName(),
		  "xref stream", xref_offset,
		  "Cross-reference stream data has the wrong size;"
		  " expected = " + QUtil::uint_to_string(expected_size) +
		  "; actual = " + QUtil::uint_to_string(actual_size));
	if (expected_size > actual_size)
	{
	    throw x;
	}
	else
	{
	    warn(x);
	}
    }

    size_t cur_chunk = 0;
    int chunk_count = 0;

    bool saw_first_compressed_object = false;

    // Actual size vs. expected size check above ensures that we will
    // not overflow any buffers here.  We know that entry_size *
    // num_entries is equal to the size of the buffer.
    unsigned char const* data = bp->getBuffer();
    for (size_t i = 0; i < num_entries; ++i)
    {
	// Read this entry
	unsigned char const* entry = data + (entry_size * i);
	qpdf_offset_t fields[3];
	unsigned char const* p = entry;
	for (int j = 0; j < 3; ++j)
	{
	    fields[j] = 0;
	    if ((j == 0) && (W[0] == 0))
	    {
		QTC::TC("qpdf", "QPDF default for xref stream field 0");
		fields[0] = 1;
	    }
	    for (int k = 0; k < W[j]; ++k)
	    {
		fields[j] <<= 8;
		fields[j] += toI(*p++);
	    }
	}

	// Get the object and generation number.  The object number is
	// based on /Index.  The generation number is 0 unless this is
	// an uncompressed object record, in which case the generation
	// number appears as the third field.
	int obj = toI(indx.at(cur_chunk));
        if ((obj < 0) ||
            ((std::numeric_limits<int>::max() - obj) < chunk_count))
        {
            std::ostringstream msg;
            msg.imbue(std::locale::classic());
            msg << "adding " << chunk_count << " to " << obj
                << " while computing index in xref stream would cause"
                << " an integer overflow";
            throw std::range_error(msg.str());
        }
        obj += chunk_count;
	++chunk_count;
	if (chunk_count >= indx.at(cur_chunk + 1))
	{
	    cur_chunk += 2;
	    chunk_count = 0;
	}

	if (saw_first_compressed_object)
	{
	    if (fields[0] != 2)
	    {
		this->m->uncompressed_after_compressed = true;
	    }
	}
	else if (fields[0] == 2)
	{
	    saw_first_compressed_object = true;
	}
	if (obj == 0)
	{
	    // This is needed by checkLinearization()
	    this->m->first_xref_item_offset = xref_offset;
	}
        if (fields[0] == 0)
        {
            // Ignore fields[2], which we don't care about in this
            // case. This works around the issue of some PDF files
            // that put invalid values, like -1, here for deleted
            // objects.
            fields[2] = 0;
        }
	insertXrefEntry(obj, toI(fields[0]),
                        fields[1], toI(fields[2]));
    }

    if (! this->m->trailer.isInitialized())
    {
	setTrailer(dict);
    }

    if (dict.hasKey("/Prev"))
    {
	if (! dict.getKey("/Prev").isInteger())
	{
	    throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			  "xref stream", this->m->file->getLastOffset(),
			  "/Prev key in xref stream dictionary is not "
			  "an integer");
	}
	QTC::TC("qpdf", "QPDF prev key in xref stream dictionary");
	xref_offset = dict.getKey("/Prev").getIntValue();
    }
    else
    {
	xref_offset = 0;
    }

    return xref_offset;
}

void
QPDF::insertXrefEntry(int obj, int f0, qpdf_offset_t f1, int f2, bool overwrite)
{
    // Populate the xref table in such a way that the first reference
    // to an object that we see, which is the one in the latest xref
    // table in which it appears, is the one that gets stored.  This
    // works because we are reading more recent appends before older
    // ones.  Exception: if overwrite is true, then replace any
    // existing object.  This is used in xref recovery mode, which
    // reads the file from beginning to end.

    // If there is already an entry for this object and generation in
    // the table, it means that a later xref table has registered this
    // object.  Disregard this one.
    { // private scope
	int gen = (f0 == 2 ? 0 : f2);
	QPDFObjGen og(obj, gen);
	if (this->m->xref_table.count(og))
	{
	    if (overwrite)
	    {
		QTC::TC("qpdf", "QPDF xref overwrite object");
		this->m->xref_table.erase(og);
	    }
	    else
	    {
		QTC::TC("qpdf", "QPDF xref reused object");
		return;
	    }
	}
	if (this->m->deleted_objects.count(obj))
	{
	    QTC::TC("qpdf", "QPDF xref deleted object");
	    return;
	}
    }

    switch (f0)
    {
      case 0:
	this->m->deleted_objects.insert(obj);
	break;

      case 1:
	// f2 is generation
	QTC::TC("qpdf", "QPDF xref gen > 0", ((f2 > 0) ? 1 : 0));
	this->m->xref_table[QPDFObjGen(obj, f2)] = QPDFXRefEntry(f0, f1, f2);
	break;

      case 2:
	this->m->xref_table[QPDFObjGen(obj, 0)] = QPDFXRefEntry(f0, f1, f2);
	break;

      default:
	throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
		      "xref stream", this->m->file->getLastOffset(),
		      "unknown xref stream entry type " +
		      QUtil::int_to_string(f0));
	break;
    }
}

void
QPDF::showXRefTable()
{
    for (std::map<QPDFObjGen, QPDFXRefEntry>::iterator iter =
	     this->m->xref_table.begin();
	 iter != this->m->xref_table.end(); ++iter)
    {
	QPDFObjGen const& og = (*iter).first;
	QPDFXRefEntry const& entry = (*iter).second;
	*this->m->out_stream << og.getObj() << "/" << og.getGen() << ": ";
	switch (entry.getType())
	{
	  case 1:
	    *this->m->out_stream
                << "uncompressed; offset = " << entry.getOffset();
	    break;

	  case 2:
	    *this->m->out_stream
                << "compressed; stream = "
                << entry.getObjStreamNumber()
                << ", index = " << entry.getObjStreamIndex();
	    break;

	  default:
	    throw std::logic_error("unknown cross-reference table type while"
				   " showing xref_table");
	    break;
	}
	*this->m->out_stream << std::endl;
    }
}

void
QPDF::fixDanglingReferences(bool force)
{
    if (this->m->fixed_dangling_refs && (! force))
    {
        return;
    }
    this->m->fixed_dangling_refs = true;

    // Create a set of all known indirect objects including those
    // we've previously resolved and those that we have created.
    std::set<QPDFObjGen> to_process;
    for (std::map<QPDFObjGen, ObjCache>::iterator iter =
	     this->m->obj_cache.begin();
	 iter != this->m->obj_cache.end(); ++iter)
    {
	to_process.insert((*iter).first);
    }
    for (std::map<QPDFObjGen, QPDFXRefEntry>::iterator iter =
	     this->m->xref_table.begin();
	 iter != this->m->xref_table.end(); ++iter)
    {
	to_process.insert((*iter).first);
    }

    // For each non-scalar item to process, put it in the queue.
    std::list<QPDFObjectHandle> queue;
    queue.push_back(this->m->trailer);
    for (std::set<QPDFObjGen>::iterator iter = to_process.begin();
         iter != to_process.end(); ++iter)
    {
        QPDFObjectHandle obj = QPDFObjectHandle::Factory::newIndirect(
            this, (*iter).getObj(), (*iter).getGen());
        if (obj.isDictionary() || obj.isArray())
        {
            queue.push_back(obj);
        }
        else if (obj.isStream())
        {
            queue.push_back(obj.getDict());
        }
    }

    // Process the queue by recursively resolving all object
    // references. We don't need to do loop detection because we don't
    // traverse known indirect objects when processing the queue.
    while (! queue.empty())
    {
        QPDFObjectHandle obj = queue.front();
        queue.pop_front();
        std::list<QPDFObjectHandle> to_check;
        if (obj.isDictionary())
        {
            std::map<std::string, QPDFObjectHandle> members =
                obj.getDictAsMap();
            for (std::map<std::string, QPDFObjectHandle>::iterator iter =
                     members.begin();
                 iter != members.end(); ++iter)
            {
                to_check.push_back((*iter).second);
            }
        }
        else if (obj.isArray())
        {
            QPDF_Array* arr =
                dynamic_cast<QPDF_Array*>(
                    QPDFObjectHandle::ObjAccessor::getObject(obj).get());
            arr->addExplicitElementsToList(to_check);
        }
        for (std::list<QPDFObjectHandle>::iterator iter = to_check.begin();
             iter != to_check.end(); ++iter)
        {
            QPDFObjectHandle sub = *iter;
            if (sub.isIndirect())
            {
                if (sub.getOwningQPDF() == this)
                {
                    QPDFObjGen og(sub.getObjGen());
                    if (this->m->obj_cache.count(og) == 0)
                    {
                        QTC::TC("qpdf", "QPDF detected dangling ref");
                        queue.push_back(sub);
                    }
                }
            }
            else
            {
                queue.push_back(sub);
            }
        }
    }
}

size_t
QPDF::getObjectCount()
{
    // This method returns the next available indirect object number.
    // makeIndirectObject uses it for this purpose. After
    // fixDanglingReferences is called, all objects in the xref table
    // will also be in obj_cache.
    fixDanglingReferences();
    QPDFObjGen og(0, 0);
    if (! this->m->obj_cache.empty())
    {
	og = (*(this->m->obj_cache.rbegin())).first;
    }
    return toS(og.getObj());
}

std::vector<QPDFObjectHandle>
QPDF::getAllObjects()
{
    // After fixDanglingReferences is called, all objects are in the
    // object cache.
    fixDanglingReferences(true);
    std::vector<QPDFObjectHandle> result;
    for (std::map<QPDFObjGen, ObjCache>::iterator iter =
	     this->m->obj_cache.begin();
	 iter != this->m->obj_cache.end(); ++iter)
    {

	QPDFObjGen const& og = (*iter).first;
        result.push_back(QPDFObjectHandle::Factory::newIndirect(
                             this, og.getObj(), og.getGen()));
    }
    return result;
}

void
QPDF::setLastObjectDescription(std::string const& description,
			       int objid, int generation)
{
    this->m->last_object_description.clear();
    if (! description.empty())
    {
	this->m->last_object_description += description;
	if (objid > 0)
	{
	    this->m->last_object_description += ": ";
	}
    }
    if (objid > 0)
    {
	this->m->last_object_description += "object " +
	    QUtil::int_to_string(objid) + " " +
	    QUtil::int_to_string(generation);
    }
}

QPDFObjectHandle
QPDF::readObject(PointerHolder<InputSource> input,
		 std::string const& description,
		 int objid, int generation, bool in_object_stream)
{
    setLastObjectDescription(description, objid, generation);
    qpdf_offset_t offset = input->tell();

    bool empty = false;
    PointerHolder<StringDecrypter> decrypter_ph;
    StringDecrypter* decrypter = 0;
    if (this->m->encp->encrypted && (! in_object_stream))
    {
        decrypter_ph = new StringDecrypter(this, objid, generation);
        decrypter = decrypter_ph.get();
    }
    QPDFObjectHandle object = QPDFObjectHandle::parse(
        input, this->m->last_object_description,
        this->m->tokenizer, empty, decrypter, this);
    if (empty)
    {
        // Nothing in the PDF spec appears to allow empty objects, but
        // they have been encountered in actual PDF files and Adobe
        // Reader appears to ignore them.
        warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(),
                     this->m->last_object_description,
                     input->getLastOffset(),
                     "empty object treated as null"));
    }
    else if (object.isDictionary() && (! in_object_stream))
    {
        // check for stream
        qpdf_offset_t cur_offset = input->tell();
        if (readToken(input) ==
            QPDFTokenizer::Token(QPDFTokenizer::tt_word, "stream"))
        {
            // The PDF specification states that the word "stream"
            // should be followed by either a carriage return and
            // a newline or by a newline alone.  It specifically
            // disallowed following it by a carriage return alone
            // since, in that case, there would be no way to tell
            // whether the NL in a CR NL sequence was part of the
            // stream data.  However, some readers, including
            // Adobe reader, accept a carriage return by itself
            // when followed by a non-newline character, so that's
            // what we do here. We have also seen files that have
            // extraneous whitespace between the stream keyword and
            // the newline.
            bool done = false;
            while (! done)
            {
                done = true;
                char ch;
                if (input->read(&ch, 1) == 0)
                {
                    // A premature EOF here will result in some
                    // other problem that will get reported at
                    // another time.
                }
                else if (ch == '\n')
                {
                    // ready to read stream data
                    QTC::TC("qpdf", "QPDF stream with NL only");
                }
                else if (ch == '\r')
                {
                    // Read another character
                    if (input->read(&ch, 1) != 0)
                    {
                        if (ch == '\n')
                        {
                            // Ready to read stream data
                            QTC::TC("qpdf", "QPDF stream with CRNL");
                        }
                        else
                        {
                            // Treat the \r by itself as the
                            // whitespace after endstream and
                            // start reading stream data in spite
                            // of not having seen a newline.
                            QTC::TC("qpdf", "QPDF stream with CR only");
                            input->unreadCh(ch);
                            warn(QPDFExc(
                                     qpdf_e_damaged_pdf,
                                     input->getName(),
                                     this->m->last_object_description,
                                     input->tell(),
                                     "stream keyword followed"
                                     " by carriage return only"));
                        }
                    }
                }
                else if (QUtil::is_space(ch))
                {
                    warn(QPDFExc(
                             qpdf_e_damaged_pdf,
                             input->getName(),
                             this->m->last_object_description,
                             input->tell(),
                             "stream keyword followed by"
                             " extraneous whitespace"));
                    done = false;
                }
                else
                {
                    QTC::TC("qpdf", "QPDF stream without newline");
                    input->unreadCh(ch);
                    warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(),
                                 this->m->last_object_description,
                                 input->tell(),
                                 "stream keyword not followed"
                                 " by proper line terminator"));
                }
            }

            // Must get offset before accessing any additional
            // objects since resolving a previously unresolved
            // indirect object will change file position.
            qpdf_offset_t stream_offset = input->tell();
            size_t length = 0;

            try
            {
                std::map<std::string, QPDFObjectHandle> dict =
                    object.getDictAsMap();

                if (dict.count("/Length") == 0)
                {
                    QTC::TC("qpdf", "QPDF stream without length");
                    throw QPDFExc(qpdf_e_damaged_pdf, input->getName(),
                                  this->m->last_object_description, offset,
                                  "stream dictionary lacks /Length key");
                }

                QPDFObjectHandle length_obj = dict["/Length"];
                if (! length_obj.isInteger())
                {
                    QTC::TC("qpdf", "QPDF stream length not integer");
                    throw QPDFExc(qpdf_e_damaged_pdf, input->getName(),
                                  this->m->last_object_description, offset,
                                  "/Length key in stream dictionary is not "
                                  "an integer");
                }

                length = toS(length_obj.getUIntValue());
                // Seek in two steps to avoid potential integer overflow
                input->seek(stream_offset, SEEK_SET);
                input->seek(toO(length), SEEK_CUR);
                if (! (readToken(input) ==
                       QPDFTokenizer::Token(
                           QPDFTokenizer::tt_word, "endstream")))
                {
                    QTC::TC("qpdf", "QPDF missing endstream");
                    throw QPDFExc(qpdf_e_damaged_pdf, input->getName(),
                                  this->m->last_object_description,
                                  input->getLastOffset(),
                                  "expected endstream");
                }
            }
            catch (QPDFExc& e)
            {
                if (this->m->attempt_recovery)
                {
                    warn(e);
                    length = recoverStreamLength(
                        input, objid, generation, stream_offset);
                }
                else
                {
                    throw e;
                }
            }
            object = QPDFObjectHandle::Factory::newStream(
                this, objid, generation, object, stream_offset, length);
        }
        else
        {
            input->seek(cur_offset, SEEK_SET);
        }
    }

    // Override last_offset so that it points to the beginning of the
    // object we just read
    input->setLastOffset(offset);
    return object;
}

bool
QPDF::findEndstream()
{
    // Find endstream or endobj. Position the input at that token.
    QPDFTokenizer::Token t = readToken(this->m->file, 20);
    if ((t.getType() == QPDFTokenizer::tt_word) &&
        ((t.getValue() == "endobj") ||
         (t.getValue() == "endstream")))
    {
        this->m->file->seek(this->m->file->getLastOffset(), SEEK_SET);
        return true;
    }
    return false;
}

size_t
QPDF::recoverStreamLength(PointerHolder<InputSource> input,
			  int objid, int generation,
                          qpdf_offset_t stream_offset)
{
    // Try to reconstruct stream length by looking for
    // endstream or endobj
    warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(),
		 this->m->last_object_description, stream_offset,
		 "attempting to recover stream length"));

    PatternFinder ef(*this, &QPDF::findEndstream);
    size_t length = 0;
    if (this->m->file->findFirst("end", stream_offset, 0, ef))
    {
        length = toS(this->m->file->tell() - stream_offset);
        // Reread endstream but, if it was endobj, don't skip that.
        QPDFTokenizer::Token t = readToken(this->m->file);
        if (t.getValue() == "endobj")
        {
            this->m->file->seek(this->m->file->getLastOffset(), SEEK_SET);
        }
    }

    if (length)
    {
	qpdf_offset_t this_obj_offset = 0;
	QPDFObjGen this_obj(0, 0);

	// Make sure this is inside this object
	for (std::map<QPDFObjGen, QPDFXRefEntry>::iterator iter =
		 this->m->xref_table.begin();
	     iter != this->m->xref_table.end(); ++iter)
	{
	    QPDFObjGen const& og = (*iter).first;
	    QPDFXRefEntry const& entry = (*iter).second;
	    if (entry.getType() == 1)
	    {
		qpdf_offset_t obj_offset = entry.getOffset();
		if ((obj_offset > stream_offset) &&
		    ((this_obj_offset == 0) ||
		     (this_obj_offset > obj_offset)))
		{
		    this_obj_offset = obj_offset;
		    this_obj = og;
		}
	    }
	}
	if (this_obj_offset &&
	    (this_obj.getObj() == objid) &&
	    (this_obj.getGen() == generation))
	{
	    // Well, we found endstream\nendobj within the space
	    // allowed for this object, so we're probably in good
	    // shape.
	}
	else
	{
	    QTC::TC("qpdf", "QPDF found wrong endstream in recovery");
	}
    }

    if (length == 0)
    {
        warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(),
                     this->m->last_object_description, stream_offset,
                     "unable to recover stream data;"
                     " treating stream as empty"));
    }
    else
    {
        warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(),
                     this->m->last_object_description, stream_offset,
                     "recovered stream length: " +
                     QUtil::uint_to_string(length)));
    }

    QTC::TC("qpdf", "QPDF recovered stream length");
    return length;
}

QPDFTokenizer::Token
QPDF::readToken(PointerHolder<InputSource> input, size_t max_len)
{
    return this->m->tokenizer.readToken(
        input, this->m->last_object_description, true, max_len);
}

QPDFObjectHandle
QPDF::readObjectAtOffset(bool try_recovery,
			 qpdf_offset_t offset, std::string const& description,
			 int exp_objid, int exp_generation,
			 int& objid, int& generation)
{
    if (! this->m->attempt_recovery)
    {
        try_recovery = false;
    }
    setLastObjectDescription(description, exp_objid, exp_generation);

    // Special case: if offset is 0, just return null.  Some PDF
    // writers, in particular "Mac OS X 10.7.5 Quartz PDFContext", may
    // store deleted objects in the xref table as "0000000000 00000
    // n", which is not correct, but it won't hurt anything for to
    // ignore these.
    if (offset == 0)
    {
        QTC::TC("qpdf", "QPDF bogus 0 offset", 0);
	warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
		     this->m->last_object_description, 0,
		     "object has offset 0"));
        return QPDFObjectHandle::newNull();
    }

    this->m->file->seek(offset, SEEK_SET);

    QPDFTokenizer::Token tobjid = readToken(this->m->file);
    QPDFTokenizer::Token tgen = readToken(this->m->file);
    QPDFTokenizer::Token tobj = readToken(this->m->file);

    bool objidok = (tobjid.getType() == QPDFTokenizer::tt_integer);
    int genok = (tgen.getType() == QPDFTokenizer::tt_integer);
    int objok = (tobj == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj"));

    QTC::TC("qpdf", "QPDF check objid", objidok ? 1 : 0);
    QTC::TC("qpdf", "QPDF check generation", genok ? 1 : 0);
    QTC::TC("qpdf", "QPDF check obj", objok ? 1 : 0);

    try
    {
	if (! (objidok && genok && objok))
	{
	    QTC::TC("qpdf", "QPDF expected n n obj");
	    throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			  this->m->last_object_description, offset,
			  "expected n n obj");
	}
	objid = QUtil::string_to_int(tobjid.getValue().c_str());
	generation = QUtil::string_to_int(tgen.getValue().c_str());

        if (objid == 0)
        {
            QTC::TC("qpdf", "QPDF object id 0");
            throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
                          this->m->last_object_description, offset,
                          "object with ID 0");
        }

	if ((exp_objid >= 0) &&
	    (! ((objid == exp_objid) && (generation == exp_generation))))
	{
	    QTC::TC("qpdf", "QPDF err wrong objid/generation");
	    QPDFExc e(qpdf_e_damaged_pdf, this->m->file->getName(),
                      this->m->last_object_description, offset,
                      std::string("expected ") +
                      QUtil::int_to_string(exp_objid) + " " +
                      QUtil::int_to_string(exp_generation) + " obj");
            if (try_recovery)
            {
                // Will be retried below
                throw e;
            }
            else
            {
                // We can try reading the object anyway even if the ID
                // doesn't match.
                warn(e);
            }
	}
    }
    catch (QPDFExc& e)
    {
	if ((exp_objid >= 0) && try_recovery)
	{
	    // Try again after reconstructing xref table
	    reconstruct_xref(e);
	    QPDFObjGen og(exp_objid, exp_generation);
	    if (this->m->xref_table.count(og) &&
		(this->m->xref_table[og].getType() == 1))
	    {
		qpdf_offset_t new_offset = this->m->xref_table[og].getOffset();
		QPDFObjectHandle result = readObjectAtOffset(
		    false, new_offset, description,
		    exp_objid, exp_generation, objid, generation);
		QTC::TC("qpdf", "QPDF recovered in readObjectAtOffset");
		return result;
	    }
	    else
	    {
		QTC::TC("qpdf", "QPDF object gone after xref reconstruction");
		warn(QPDFExc(
			 qpdf_e_damaged_pdf, this->m->file->getName(),
			 "", 0,
			 std::string(
			     "object " +
			     QUtil::int_to_string(exp_objid) +
			     " " +
			     QUtil::int_to_string(exp_generation) +
			     " not found in file after regenerating"
			     " cross reference table")));
		return QPDFObjectHandle::newNull();
	    }
	}
	else
	{
	    throw e;
	}
    }

    QPDFObjectHandle oh = readObject(
	this->m->file, description, objid, generation, false);

    if (! (readToken(this->m->file) ==
	   QPDFTokenizer::Token(QPDFTokenizer::tt_word, "endobj")))
    {
	QTC::TC("qpdf", "QPDF err expected endobj");
	warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
		     this->m->last_object_description,
                     this->m->file->getLastOffset(),
		     "expected endobj"));
    }

    QPDFObjGen og(objid, generation);
    if (! this->m->obj_cache.count(og))
    {
	// Store the object in the cache here so it gets cached
	// whether we first know the offset or whether we first know
	// the object ID and generation (in which we case we would get
	// here through resolve).

	// Determine the end offset of this object before and after
	// white space.  We use these numbers to validate
	// linearization hint tables.  Offsets and lengths of objects
	// may imply the end of an object to be anywhere between these
	// values.
	qpdf_offset_t end_before_space = this->m->file->tell();

	// skip over spaces
	while (true)
	{
	    char ch;
	    if (this->m->file->read(&ch, 1))
	    {
		if (! isspace(static_cast<unsigned char>(ch)))
		{
		    this->m->file->seek(-1, SEEK_CUR);
		    break;
		}
	    }
	    else
	    {
		throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			      this->m->last_object_description,
                              this->m->file->tell(),
			      "EOF after endobj");
	    }
	}
	qpdf_offset_t end_after_space = this->m->file->tell();

	this->m->obj_cache[og] =
	    ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh),
		     end_before_space, end_after_space);
    }

    return oh;
}

bool
QPDF::objectChanged(QPDFObjGen const& og, PointerHolder<QPDFObject>& oph)
{
    // See if the object cached at og, if any, is the one passed in.
    // QPDFObjectHandle uses this to detect outdated handles to
    // replaced or swapped objects. This is a somewhat expensive check
    // because it happens with every dereference of a
    // QPDFObjectHandle. To reduce the hit somewhat, short-circuit the
    // check if we never called a function that replaces an object
    // already in cache. It is important for functions that do this to
    // set ever_replaced_objects = true.

    if (! this->m->ever_replaced_objects)
    {
        return false;
    }
    auto c = this->m->obj_cache.find(og);
    if (c == this->m->obj_cache.end())
    {
        return true;
    }
    return (c->second.object.get() != oph.get());
}

PointerHolder<QPDFObject>
QPDF::resolve(int objid, int generation)
{
    // Check object cache before checking xref table.  This allows us
    // to insert things into the object cache that don't actually
    // exist in the file.
    QPDFObjGen og(objid, generation);
    if (this->m->resolving.count(og))
    {
        // This can happen if an object references itself directly or
        // indirectly in some key that has to be resolved during
        // object parsing, such as stream length.
	QTC::TC("qpdf", "QPDF recursion loop in resolve");
	warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
		     "", this->m->file->getLastOffset(),
		     "loop detected resolving object " +
		     QUtil::int_to_string(objid) + " " +
		     QUtil::int_to_string(generation)));
        return new QPDF_Null;
    }
    ResolveRecorder rr(this, og);

    if ((! this->m->obj_cache.count(og)) && this->m->xref_table.count(og))
    {
	QPDFXRefEntry const& entry = this->m->xref_table[og];
        try
        {
            switch (entry.getType())
            {
              case 1:
                {
                    qpdf_offset_t offset = entry.getOffset();
                    // Object stored in cache by readObjectAtOffset
                    int aobjid;
                    int ageneration;
                    QPDFObjectHandle oh =
                        readObjectAtOffset(true, offset, "", objid, generation,
                                           aobjid, ageneration);
                }
                break;

              case 2:
                resolveObjectsInStream(entry.getObjStreamNumber());
                break;

              default:
                throw QPDFExc(qpdf_e_damaged_pdf,
                              this->m->file->getName(), "", 0,
                              "object " +
                              QUtil::int_to_string(objid) + "/" +
                              QUtil::int_to_string(generation) +
                              " has unexpected xref entry type");
            }
        }
        catch (QPDFExc& e)
        {
            warn(e);
        }
        catch (std::exception& e)
        {
            warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
                         "object " +
                         QUtil::int_to_string(objid) + "/" +
                         QUtil::int_to_string(generation) +
                         ": error reading object: " + e.what()));
        }
    }
    if (this->m->obj_cache.count(og) == 0)
    {
        // PDF spec says unknown objects resolve to the null object.
        QTC::TC("qpdf", "QPDF resolve failure to null");
        QPDFObjectHandle oh = QPDFObjectHandle::newNull();
        this->m->obj_cache[og] =
            ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), -1, -1);
    }

    PointerHolder<QPDFObject> result(this->m->obj_cache[og].object);
    if (! result->hasDescription())
    {
        result->setDescription(
            this,
            "object " + QUtil::int_to_string(objid) + " " +
            QUtil::int_to_string(generation));
    }
    return result;
}

void
QPDF::resolveObjectsInStream(int obj_stream_number)
{
    if (this->m->resolved_object_streams.count(obj_stream_number))
    {
        return;
    }
    this->m->resolved_object_streams.insert(obj_stream_number);
    // Force resolution of object stream
    QPDFObjectHandle obj_stream = getObjectByID(obj_stream_number, 0);
    if (! obj_stream.isStream())
    {
	throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
		      this->m->last_object_description,
		      this->m->file->getLastOffset(),
		      "supposed object stream " +
		      QUtil::int_to_string(obj_stream_number) +
		      " is not a stream");
    }

    // For linearization data in the object, use the data from the
    // object stream for the objects in the stream.
    QPDFObjGen stream_og(obj_stream_number, 0);
    qpdf_offset_t end_before_space =
        this->m->obj_cache[stream_og].end_before_space;
    qpdf_offset_t end_after_space =
        this->m->obj_cache[stream_og].end_after_space;

    QPDFObjectHandle dict = obj_stream.getDict();
    if (! dict.isDictionaryOfType("/ObjStm"))
    {
	QTC::TC("qpdf", "QPDF ERR object stream with wrong type");
	warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
                     this->m->last_object_description,
                     this->m->file->getLastOffset(),
                     "supposed object stream " +
                     QUtil::int_to_string(obj_stream_number) +
                     " has wrong type"));
    }

    if (! (dict.getKey("/N").isInteger() &&
	   dict.getKey("/First").isInteger()))
    {
	throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
		      this->m->last_object_description,
		      this->m->file->getLastOffset(),
		      "object stream " +
		      QUtil::int_to_string(obj_stream_number) +
		      " has incorrect keys");
    }

    int n = dict.getKey("/N").getIntValueAsInt();
    int first = dict.getKey("/First").getIntValueAsInt();

    std::map<int, int> offsets;

    PointerHolder<Buffer> bp = obj_stream.getStreamData(qpdf_dl_specialized);
    PointerHolder<InputSource> input = new BufferInputSource(
        this->m->file->getName() +
        " object stream " + QUtil::int_to_string(obj_stream_number),
	bp.get());

    for (int i = 0; i < n; ++i)
    {
	QPDFTokenizer::Token tnum = readToken(input);
	QPDFTokenizer::Token toffset = readToken(input);
	if (! ((tnum.getType() == QPDFTokenizer::tt_integer) &&
	       (toffset.getType() == QPDFTokenizer::tt_integer)))
	{
	    throw QPDFExc(qpdf_e_damaged_pdf, input->getName(),
			  this->m->last_object_description,
                          input->getLastOffset(),
			  "expected integer in object stream header");
	}

	int num = QUtil::string_to_int(tnum.getValue().c_str());
	long long offset = QUtil::string_to_int(toffset.getValue().c_str());
	offsets[num] = QIntC::to_int(offset + first);
    }

    // To avoid having to read the object stream multiple times, store
    // all objects that would be found here in the cache.  Remember
    // that some objects stored here might have been overridden by new
    // objects appended to the file, so it is necessary to recheck the
    // xref table and only cache what would actually be resolved here.
    for (std::map<int, int>::iterator iter = offsets.begin();
	 iter != offsets.end(); ++iter)
    {
	int obj = (*iter).first;
	QPDFObjGen og(obj, 0);
        QPDFXRefEntry const& entry = this->m->xref_table[og];
        if ((entry.getType() == 2) &&
            (entry.getObjStreamNumber() == obj_stream_number))
        {
            int offset = (*iter).second;
            input->seek(offset, SEEK_SET);
            QPDFObjectHandle oh = readObject(input, "", obj, 0, true);
            this->m->obj_cache[og] =
                ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh),
                         end_before_space, end_after_space);
        }
        else
        {
            QTC::TC("qpdf", "QPDF not caching overridden objstm object");
        }
    }
}

QPDFObjectHandle
QPDF::makeIndirectObject(QPDFObjectHandle oh)
{
    int max_objid = toI(getObjectCount());
    if (max_objid == std::numeric_limits<int>::max())
    {
        throw std::range_error(
            "max object id is too high to create new objects");
    }
    QPDFObjGen next(max_objid + 1, 0);
    this->m->obj_cache[next] =
	ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), -1, -1);
    return QPDFObjectHandle::Factory::newIndirect(
        this, next.getObj(), next.getGen());
}

QPDFObjectHandle
QPDF::getObjectByObjGen(QPDFObjGen const& og)
{
    return getObjectByID(og.getObj(), og.getGen());
}

QPDFObjectHandle
QPDF::getObjectByID(int objid, int generation)
{
    return QPDFObjectHandle::Factory::newIndirect(this, objid, generation);
}

void
QPDF::replaceObject(QPDFObjGen const& og, QPDFObjectHandle oh)
{
    replaceObject(og.getObj(), og.getGen(), oh);
}

void
QPDF::replaceObject(int objid, int generation, QPDFObjectHandle oh)
{
    if (oh.isIndirect())
    {
	QTC::TC("qpdf", "QPDF replaceObject called with indirect object");
	throw std::logic_error(
	    "QPDF::replaceObject called with indirect object handle");
    }

    // Force new object to appear in the cache
    resolve(objid, generation);

    // Replace the object in the object cache
    QPDFObjGen og(objid, generation);
    this->m->ever_replaced_objects = true;
    this->m->obj_cache[og] =
	ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), -1, -1);
}

void
QPDF::replaceReserved(QPDFObjectHandle reserved,
                      QPDFObjectHandle replacement)
{
    QTC::TC("qpdf", "QPDF replaceReserved");
    reserved.assertReserved();
    replaceObject(reserved.getObjGen(), replacement);
}

QPDFObjectHandle
QPDF::copyForeignObject(QPDFObjectHandle foreign)
{
    // Here's an explanation of what's going on here.
    //
    // A QPDFObjectHandle that is an indirect object has an owning
    // QPDF. The object ID and generation refers to an object in the
    // owning QPDF. When we copy the QPDFObjectHandle from a foreign
    // QPDF into the local QPDF, we have to replace all indirect
    // object references with references to the corresponding object
    // in the local file.
    //
    // To do this, we maintain mappings from foreign object IDs to
    // local object IDs for each foreign QPDF that we are copying
    // from. The mapping is stored in an ObjCopier, which contains a
    // mapping from the foreign ObjGen to the local QPDFObjectHandle.
    //
    // To copy, we do a deep traversal of the foreign object with loop
    // detection to discover all indirect objects that are
    // encountered, stopping at page boundaries. Whenever we encounter
    // an indirect object, we check to see if we have already created
    // a local copy of it. If not, we allocate a "reserved" object
    // (or, for a stream, just a new stream) and store in the map the
    // mapping from the foreign object ID to the new object. While we
    // do this, we keep a list of objects to copy.
    //
    // Once we are done with the traversal, we copy all the objects
    // that we need to copy. However, the copies will contain indirect
    // object IDs that refer to objects in the foreign file. We need
    // to replace them with references to objects in the local file.
    // This is what replaceForeignIndirectObjects does. Once we have
    // created a copy of the foreign object with all the indirect
    // references replaced with new ones in the local context, we can
    // replace the local reserved object with the copy. This mechanism
    // allows us to copy objects with circular references in any
    // order.

    // For streams, rather than copying the objects, we set up the
    // stream data to pull from the original stream by using a stream
    // data provider. This is done in a manner that doesn't require
    // the original QPDF object but may require the original source of
    // the stream data with special handling for immediate_copy_from.
    // This logic is also in replaceForeignIndirectObjects.

    // Note that we explicitly allow use of copyForeignObject on page
    // objects. It is a documented use case to copy pages this way if
    // the intention is to not update the pages tree.
    if (! foreign.isIndirect())
    {
        QTC::TC("qpdf", "QPDF copyForeign direct");
	throw std::logic_error(
	    "QPDF::copyForeign called with direct object handle");
    }
    QPDF* other = foreign.getOwningQPDF();
    if (other == this)
    {
        QTC::TC("qpdf", "QPDF copyForeign not foreign");
        throw std::logic_error(
            "QPDF::copyForeign called with object from this QPDF");
    }

    ObjCopier& obj_copier = this->m->object_copiers[other->m->unique_id];
    if (! obj_copier.visiting.empty())
    {
        throw std::logic_error("obj_copier.visiting is not empty"
                               " at the beginning of copyForeignObject");
    }

    // Make sure we have an object in this file for every referenced
    // object in the old file.  obj_copier.object_map maps foreign
    // QPDFObjGen to local objects.  For everything new that we have
    // to copy, the local object will be a reservation, unless it is a
    // stream, in which case the local object will already be a
    // stream.
    reserveObjects(foreign, obj_copier, true);

    if (! obj_copier.visiting.empty())
    {
        throw std::logic_error("obj_copier.visiting is not empty"
                               " after reserving objects");
    }

    // Copy any new objects and replace the reservations.
    for (std::vector<QPDFObjectHandle>::iterator iter =
             obj_copier.to_copy.begin();
         iter != obj_copier.to_copy.end(); ++iter)
    {
        QPDFObjectHandle& to_copy = *iter;
        QPDFObjectHandle copy =
            replaceForeignIndirectObjects(to_copy, obj_copier, true);
        if (! to_copy.isStream())
        {
            QPDFObjGen og(to_copy.getObjGen());
            replaceReserved(obj_copier.object_map[og], copy);
        }
    }
    obj_copier.to_copy.clear();

    return obj_copier.object_map[foreign.getObjGen()];
}

void
QPDF::reserveObjects(QPDFObjectHandle foreign, ObjCopier& obj_copier,
                     bool top)
{
    if (foreign.isReserved())
    {
        throw std::logic_error(
            "QPDF: attempting to copy a foreign reserved object");
    }

    if (foreign.isPagesObject())
    {
        QTC::TC("qpdf", "QPDF not copying pages object");
        return;
    }

    if ((! top) && foreign.isPageObject())
    {
        QTC::TC("qpdf", "QPDF not crossing page boundary");
        return;
    }

    if (foreign.isIndirect())
    {
        QPDFObjGen foreign_og(foreign.getObjGen());
        if (obj_copier.visiting.find(foreign_og) != obj_copier.visiting.end())
        {
            QTC::TC("qpdf", "QPDF loop reserving objects");
            return;
        }
        if (obj_copier.object_map.find(foreign_og) !=
            obj_copier.object_map.end())
        {
            QTC::TC("qpdf", "QPDF already reserved object");
            return;
        }
        QTC::TC("qpdf", "QPDF copy indirect");
        obj_copier.visiting.insert(foreign_og);
        std::map<QPDFObjGen, QPDFObjectHandle>::iterator mapping =
            obj_copier.object_map.find(foreign_og);
        if (mapping == obj_copier.object_map.end())
        {
            obj_copier.to_copy.push_back(foreign);
            QPDFObjectHandle reservation;
            if (foreign.isStream())
            {
                reservation = QPDFObjectHandle::newStream(this);
            }
            else
            {
                reservation = QPDFObjectHandle::newReserved(this);
            }
            obj_copier.object_map[foreign_og] = reservation;
        }
    }

    if (foreign.isArray())
    {
        QTC::TC("qpdf", "QPDF reserve array");
	int n = foreign.getArrayNItems();
	for (int i = 0; i < n; ++i)
	{
            reserveObjects(foreign.getArrayItem(i), obj_copier, false);
	}
    }
    else if (foreign.isDictionary())
    {
        QTC::TC("qpdf", "QPDF reserve dictionary");
	std::set<std::string> keys = foreign.getKeys();
	for (std::set<std::string>::iterator iter = keys.begin();
	     iter != keys.end(); ++iter)
	{
            reserveObjects(foreign.getKey(*iter), obj_copier, false);
	}
    }
    else if (foreign.isStream())
    {
        QTC::TC("qpdf", "QPDF reserve stream");
        reserveObjects(foreign.getDict(), obj_copier, false);
    }

    if (foreign.isIndirect())
    {
        QPDFObjGen foreign_og(foreign.getObjGen());
        obj_copier.visiting.erase(foreign_og);
    }
}

QPDFObjectHandle
QPDF::replaceForeignIndirectObjects(
    QPDFObjectHandle foreign, ObjCopier& obj_copier, bool top)
{
    QPDFObjectHandle result;
    if ((! top) && foreign.isIndirect())
    {
        QTC::TC("qpdf", "QPDF replace indirect");
        QPDFObjGen foreign_og(foreign.getObjGen());
        std::map<QPDFObjGen, QPDFObjectHandle>::iterator mapping =
            obj_copier.object_map.find(foreign_og);
        if (mapping == obj_copier.object_map.end())
        {
            // This case would occur if this is a reference to a Page
            // or Pages object that we didn't traverse into.
            QTC::TC("qpdf", "QPDF replace foreign indirect with null");
            result = QPDFObjectHandle::newNull();
        }
        else
        {
            result = obj_copier.object_map[foreign_og];
        }
    }
    else if (foreign.isArray())
    {
        QTC::TC("qpdf", "QPDF replace array");
        result = QPDFObjectHandle::newArray();
	int n = foreign.getArrayNItems();
	for (int i = 0; i < n; ++i)
	{
            result.appendItem(
                replaceForeignIndirectObjects(
                    foreign.getArrayItem(i), obj_copier, false));
	}
    }
    else if (foreign.isDictionary())
    {
        QTC::TC("qpdf", "QPDF replace dictionary");
        result = QPDFObjectHandle::newDictionary();
	std::set<std::string> keys = foreign.getKeys();
	for (std::set<std::string>::iterator iter = keys.begin();
	     iter != keys.end(); ++iter)
	{
            result.replaceKey(
                *iter,
                replaceForeignIndirectObjects(
                    foreign.getKey(*iter), obj_copier, false));
	}
    }
    else if (foreign.isStream())
    {
        QTC::TC("qpdf", "QPDF replace stream");
        QPDFObjGen foreign_og(foreign.getObjGen());
        result = obj_copier.object_map[foreign_og];
        result.assertStream();
        QPDFObjectHandle dict = result.getDict();
        QPDFObjectHandle old_dict = foreign.getDict();
        std::set<std::string> keys = old_dict.getKeys();
        for (std::set<std::string>::iterator iter = keys.begin();
             iter != keys.end(); ++iter)
        {
            dict.replaceKey(
                *iter,
                replaceForeignIndirectObjects(
                    old_dict.getKey(*iter), obj_copier, false));
        }
        copyStreamData(result, foreign);
    }
    else
    {
        foreign.assertScalar();
        result = foreign;
        result.makeDirect();
    }

    if (top && (! result.isStream()) && result.isIndirect())
    {
        throw std::logic_error("replacement for foreign object is indirect");
    }

    return result;
}

void
QPDF::copyStreamData(QPDFObjectHandle result, QPDFObjectHandle foreign)
{
    // This method was originally written for copying foreign streams,
    // but it is used by QPDFObjectHandle to copy streams from the
    // same QPDF object as well.

    QPDFObjectHandle dict = result.getDict();
    QPDFObjectHandle old_dict = foreign.getDict();
    if (this->m->copied_stream_data_provider == 0)
    {
        this->m->copied_stream_data_provider =
            new CopiedStreamDataProvider(*this);
        this->m->copied_streams = this->m->copied_stream_data_provider;
    }
    QPDFObjGen local_og(result.getObjGen());
    // Copy information from the foreign stream so we can pipe its
    // data later without keeping the original QPDF object around.
    QPDF* foreign_stream_qpdf = foreign.getOwningQPDF();
    if (! foreign_stream_qpdf)
    {
        throw std::logic_error("unable to retrieve owning qpdf"
                               " from foreign stream");
    }
    QPDF_Stream* stream =
        dynamic_cast<QPDF_Stream*>(
            QPDFObjectHandle::ObjAccessor::getObject(
                foreign).get());
    if (! stream)
    {
        throw std::logic_error("unable to retrieve underlying"
                               " stream object from foreign stream");
    }
    PointerHolder<Buffer> stream_buffer =
        stream->getStreamDataBuffer();
    if ((foreign_stream_qpdf->m->immediate_copy_from) &&
        (stream_buffer.get() == 0))
    {
        // Pull the stream data into a buffer before attempting
        // the copy operation. Do it on the source stream so that
        // if the source stream is copied multiple times, we don't
        // have to keep duplicating the memory.
        QTC::TC("qpdf", "QPDF immediate copy stream data");
        foreign.replaceStreamData(foreign.getRawStreamData(),
                                  old_dict.getKey("/Filter"),
                                  old_dict.getKey("/DecodeParms"));
        stream_buffer = stream->getStreamDataBuffer();
    }
    PointerHolder<QPDFObjectHandle::StreamDataProvider> stream_provider =
        stream->getStreamDataProvider();
    if (stream_buffer.get())
    {
        QTC::TC("qpdf", "QPDF copy foreign stream with buffer");
        result.replaceStreamData(stream_buffer,
                                 dict.getKey("/Filter"),
                                 dict.getKey("/DecodeParms"));
    }
    else if (stream_provider.get())
    {
        // In this case, the remote stream's QPDF must stay in scope.
        QTC::TC("qpdf", "QPDF copy foreign stream with provider");
        this->m->copied_stream_data_provider->registerForeignStream(
            local_og, foreign);
        result.replaceStreamData(this->m->copied_streams,
                                 dict.getKey("/Filter"),
                                 dict.getKey("/DecodeParms"));
    }
    else
    {
        PointerHolder<ForeignStreamData> foreign_stream_data =
            new ForeignStreamData(
                foreign_stream_qpdf->m->encp,
                foreign_stream_qpdf->m->file,
                foreign.getObjectID(),
                foreign.getGeneration(),
                stream->getOffset(),
                stream->getLength(),
                dict);
        this->m->copied_stream_data_provider->registerForeignStream(
            local_og, foreign_stream_data);
        result.replaceStreamData(this->m->copied_streams,
                                 dict.getKey("/Filter"),
                                 dict.getKey("/DecodeParms"));
    }
}

void
QPDF::swapObjects(QPDFObjGen const& og1, QPDFObjGen const& og2)
{
    swapObjects(og1.getObj(), og1.getGen(), og2.getObj(), og2.getGen());
}

void
QPDF::swapObjects(int objid1, int generation1, int objid2, int generation2)
{
    // Force objects to be loaded into cache; then swap them in the
    // cache.
    resolve(objid1, generation1);
    resolve(objid2, generation2);
    QPDFObjGen og1(objid1, generation1);
    QPDFObjGen og2(objid2, generation2);
    ObjCache t = this->m->obj_cache[og1];
    this->m->ever_replaced_objects = true;
    this->m->obj_cache[og1] = this->m->obj_cache[og2];
    this->m->obj_cache[og2] = t;
}

unsigned long long
QPDF::getUniqueId() const
{
    return this->m->unique_id;
}

std::string
QPDF::getFilename() const
{
    return this->m->file->getName();
}

std::string
QPDF::getPDFVersion() const
{
    return this->m->pdf_version;
}

int
QPDF::getExtensionLevel()
{
    int result = 0;
    QPDFObjectHandle obj = getRoot();
    if (obj.hasKey("/Extensions"))
    {
        obj = obj.getKey("/Extensions");
        if (obj.isDictionary() && obj.hasKey("/ADBE"))
        {
            obj = obj.getKey("/ADBE");
            if (obj.isDictionary() && obj.hasKey("/ExtensionLevel"))
            {
                obj = obj.getKey("/ExtensionLevel");
                if (obj.isInteger())
                {
                    result = obj.getIntValueAsInt();
                }
            }
        }
    }
    return result;
}

QPDFObjectHandle
QPDF::getTrailer()
{
    return this->m->trailer;
}

QPDFObjectHandle
QPDF::getRoot()
{
    QPDFObjectHandle root = this->m->trailer.getKey("/Root");
    if (! root.isDictionary())
    {
        throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
                      "", this->m->file->getLastOffset(),
                      "unable to find /Root dictionary");
    }
    return root;
}

std::map<QPDFObjGen, QPDFXRefEntry>
QPDF::getXRefTable()
{
    if (! this->m->parsed)
    {
        throw std::logic_error("QPDF::getXRefTable called before parsing.");
    }

    return this->m->xref_table;
}

void
QPDF::getObjectStreamData(std::map<int, int>& omap)
{
    for (std::map<QPDFObjGen, QPDFXRefEntry>::iterator iter =
	     this->m->xref_table.begin();
	 iter != this->m->xref_table.end(); ++iter)
    {
	QPDFObjGen const& og = (*iter).first;
	QPDFXRefEntry const& entry = (*iter).second;
	if (entry.getType() == 2)
	{
	    omap[og.getObj()] = entry.getObjStreamNumber();
	}
    }
}

std::vector<QPDFObjGen>
QPDF::getCompressibleObjGens()
{
    // Return a list of objects that are allowed to be in object
    // streams.  Walk through the objects by traversing the document
    // from the root, including a traversal of the pages tree.  This
    // makes that objects that are on the same page are more likely to
    // be in the same object stream, which is slightly more efficient,
    // particularly with linearized files.  This is better than
    // iterating through the xref table since it avoids preserving
    // orphaned items.

    // Exclude encryption dictionary, if any
    QPDFObjectHandle encryption_dict =
        this->m->trailer.getKey("/Encrypt");
    QPDFObjGen encryption_dict_og = encryption_dict.getObjGen();

    std::set<QPDFObjGen> visited;
    std::list<QPDFObjectHandle> queue;
    queue.push_front(this->m->trailer);
    std::vector<QPDFObjGen> result;
    while (! queue.empty())
    {
	QPDFObjectHandle obj = queue.front();
	queue.pop_front();
	if (obj.isIndirect())
	{
	    QPDFObjGen og = obj.getObjGen();
	    if (visited.count(og))
	    {
		QTC::TC("qpdf", "QPDF loop detected traversing objects");
		continue;
	    }
	    if (og == encryption_dict_og)
	    {
		QTC::TC("qpdf", "QPDF exclude encryption dictionary");
	    }
            else if (! (obj.isStream() ||
                        (obj.isDictionaryOfType("/Sig") &&
                         obj.hasKey("/ByteRange") &&
                         obj.hasKey("/Contents"))))
	    {
		result.push_back(og);
	    }
	    visited.insert(og);
	}
	if (obj.isStream())
	{
	    QPDFObjectHandle dict = obj.getDict();
	    std::set<std::string> keys = dict.getKeys();
	    for (std::set<std::string>::reverse_iterator iter = keys.rbegin();
		 iter != keys.rend(); ++iter)
	    {
		std::string const& key = *iter;
		QPDFObjectHandle value = dict.getKey(key);
		if (key == "/Length")
		{
		    // omit stream lengths
		    if (value.isIndirect())
		    {
			QTC::TC("qpdf", "QPDF exclude indirect length");
		    }
		}
		else
		{
		    queue.push_front(value);
		}
	    }
	}
	else if (obj.isDictionary())
	{
	    std::set<std::string> keys = obj.getKeys();
	    for (std::set<std::string>::reverse_iterator iter = keys.rbegin();
		 iter != keys.rend(); ++iter)
	    {
		queue.push_front(obj.getKey(*iter));
	    }
	}
	else if (obj.isArray())
	{
	    int n = obj.getArrayNItems();
	    for (int i = 1; i <= n; ++i)
	    {
		queue.push_front(obj.getArrayItem(n - i));
	    }
	}
    }

    return result;
}

bool
QPDF::pipeStreamData(PointerHolder<EncryptionParameters> encp,
                     PointerHolder<InputSource> file,
                     QPDF& qpdf_for_warning,
                     int objid, int generation,
		     qpdf_offset_t offset, size_t length,
		     QPDFObjectHandle stream_dict,
		     Pipeline* pipeline,
                     bool suppress_warnings,
                     bool will_retry)
{
    std::vector<std::shared_ptr<Pipeline>> to_delete;
    if (encp->encrypted)
    {
	decryptStream(encp, file, qpdf_for_warning,
                      pipeline, objid, generation,
                      stream_dict, to_delete);
    }

    bool success = false;
    try
    {
	file->seek(offset, SEEK_SET);
	char buf[10240];
	while (length > 0)
	{
	    size_t to_read = (sizeof(buf) < length ? sizeof(buf) : length);
	    size_t len = file->read(buf, to_read);
	    if (len == 0)
	    {
		throw QPDFExc(qpdf_e_damaged_pdf,
			      file->getName(),
			      "",
			      file->getLastOffset(),
			      "unexpected EOF reading stream data");
	    }
	    length -= len;
	    pipeline->write(QUtil::unsigned_char_pointer(buf), len);
	}
        pipeline->finish();
        success = true;
    }
    catch (QPDFExc& e)
    {
        if (! suppress_warnings)
        {
            qpdf_for_warning.warn(e);
        }
    }
    catch (std::exception& e)
    {
        if (! suppress_warnings)
        {
            QTC::TC("qpdf", "QPDF decoding error warning");
            qpdf_for_warning.warn(
                QPDFExc(qpdf_e_damaged_pdf, file->getName(),
                        "", file->getLastOffset(),
                        "error decoding stream data for object " +
                        QUtil::int_to_string(objid) + " " +
                        QUtil::int_to_string(generation) + ": " + e.what()));
            if (will_retry)
            {
                qpdf_for_warning.warn(
                    QPDFExc(qpdf_e_damaged_pdf, file->getName(),
                            "", file->getLastOffset(),
                            "stream will be re-processed without"
                            " filtering to avoid data loss"));
            }
        }
    }
    if (! success)
    {
        try
        {
            pipeline->finish();
        }
        catch (std::exception&)
        {
            // ignore
        }
    }
    return success;
}

bool
QPDF::pipeStreamData(int objid, int generation,
		     qpdf_offset_t offset, size_t length,
		     QPDFObjectHandle stream_dict,
		     Pipeline* pipeline,
                     bool suppress_warnings,
                     bool will_retry)
{
    return pipeStreamData(
        this->m->encp, this->m->file, *this,
        objid, generation, offset, length,
        stream_dict, pipeline,
        suppress_warnings, will_retry);
}

bool
QPDF::pipeForeignStreamData(
    PointerHolder<ForeignStreamData> foreign,
    Pipeline* pipeline,
    bool suppress_warnings, bool will_retry)
{
    if (foreign->encp->encrypted)
    {
        QTC::TC("qpdf", "QPDF pipe foreign encrypted stream");
    }
    return pipeStreamData(
        foreign->encp, foreign->file, *this,
        foreign->foreign_objid, foreign->foreign_generation,
        foreign->offset, foreign->length,
        foreign->local_dict, pipeline,
        suppress_warnings, will_retry);
}

void
QPDF::stopOnError(std::string const& message)
{
    // Throw a generic exception when we lack context for something
    // more specific. New code should not use this. This method exists
    // to improve somewhat from calling assert in very old code.
    throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
                  "", this->m->file->getLastOffset(), message);
}