-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQPDF_linearization.cc
1789 lines (1562 loc) · 68.5 KB
/
QPDF_linearization.cc
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
// See doc/linearization.
#include <qpdf/QPDF.hh>
#include <qpdf/BitStream.hh>
#include <qpdf/BitWriter.hh>
#include <qpdf/Pl_Buffer.hh>
#include <qpdf/Pl_Count.hh>
#include <qpdf/Pl_Flate.hh>
#include <qpdf/QPDFExc.hh>
#include <qpdf/QPDFLogger.hh>
#include <qpdf/QTC.hh>
#include <qpdf/QUtil.hh>
#include <algorithm>
#include <cmath>
#include <cstring>
template <class T, class int_type>
static void
load_vector_int(
BitStream& bit_stream, int nitems, std::vector<T>& vec, int bits_wanted, int_type T::*field)
{
bool append = vec.empty();
// nitems times, read bits_wanted from the given bit stream, storing results in the ith vector
// entry.
for (size_t i = 0; i < QIntC::to_size(nitems); ++i) {
if (append) {
vec.push_back(T());
}
vec.at(i).*field = bit_stream.getBitsInt(QIntC::to_size(bits_wanted));
}
if (QIntC::to_int(vec.size()) != nitems) {
throw std::logic_error("vector has wrong size in load_vector_int");
}
// The PDF spec says that each hint table starts at a byte boundary. Each "row" actually must
// start on a byte boundary.
bit_stream.skipToNextByte();
}
template <class T>
static void
load_vector_vector(
BitStream& bit_stream,
int nitems1,
std::vector<T>& vec1,
int T::*nitems2,
int bits_wanted,
std::vector<int> T::*vec2)
{
// nitems1 times, read nitems2 (from the ith element of vec1) items into the vec2 vector field
// of the ith item of vec1.
for (size_t i1 = 0; i1 < QIntC::to_size(nitems1); ++i1) {
for (int i2 = 0; i2 < vec1.at(i1).*nitems2; ++i2) {
(vec1.at(i1).*vec2).push_back(bit_stream.getBitsInt(QIntC::to_size(bits_wanted)));
}
}
bit_stream.skipToNextByte();
}
void
QPDF::linearizationWarning(std::string_view msg)
{
m->linearization_warnings = true;
warn(qpdf_e_linearization, "", 0, std::string(msg));
}
bool
QPDF::checkLinearization()
{
bool result = false;
try {
readLinearizationData();
result = checkLinearizationInternal();
} catch (std::runtime_error& e) {
linearizationWarning(
"error encountered while checking linearization data: " + std::string(e.what()));
}
return result;
}
bool
QPDF::isLinearized()
{
// If the first object in the file is a dictionary with a suitable /Linearized key and has an /L
// key that accurately indicates the file size, initialize m->lindict and return true.
// A linearized PDF spec's first object will be contained within the first 1024 bytes of the
// file and will be a dictionary with a valid /Linearized key. This routine looks for that and
// does no additional validation.
// The PDF spec says the linearization dictionary must be completely contained within the first
// 1024 bytes of the file. Add a byte for a null terminator.
static int const tbuf_size = 1025;
auto b = std::make_unique<char[]>(tbuf_size);
char* buf = b.get();
m->file->seek(0, SEEK_SET);
memset(buf, '\0', tbuf_size);
m->file->read(buf, tbuf_size - 1);
int lindict_obj = -1;
char* p = buf;
while (lindict_obj == -1) {
// Find a digit or end of buffer
while (((p - buf) < tbuf_size) && (!QUtil::is_digit(*p))) {
++p;
}
if (p - buf == tbuf_size) {
break;
}
// Seek to the digit. Then skip over digits for a potential
// next iteration.
m->file->seek(p - buf, SEEK_SET);
while (((p - buf) < tbuf_size) && QUtil::is_digit(*p)) {
++p;
}
QPDFTokenizer::Token t1 = readToken(m->file);
if (t1.isInteger() && readToken(m->file).isInteger() && readToken(m->file).isWord("obj") &&
(readToken(m->file).getType() == QPDFTokenizer::tt_dict_open)) {
lindict_obj = toI(QUtil::string_to_ll(t1.getValue().c_str()));
}
}
if (lindict_obj <= 0) {
return false;
}
auto candidate = getObjectByID(lindict_obj, 0);
if (!candidate.isDictionary()) {
return false;
}
QPDFObjectHandle linkey = candidate.getKey("/Linearized");
if (!(linkey.isNumber() && (toI(floor(linkey.getNumericValue())) == 1))) {
return false;
}
QPDFObjectHandle L = candidate.getKey("/L");
if (L.isInteger()) {
qpdf_offset_t Li = L.getIntValue();
m->file->seek(0, SEEK_END);
if (Li != m->file->tell()) {
QTC::TC("qpdf", "QPDF /L mismatch");
return false;
} else {
m->linp.file_size = Li;
}
}
m->lindict = candidate;
return true;
}
void
QPDF::readLinearizationData()
{
// This function throws an exception (which is trapped by checkLinearization()) for any errors
// that prevent loading.
if (!isLinearized()) {
throw std::logic_error("called readLinearizationData for file"
" that is not linearized");
}
// /L is read and stored in linp by isLinearized()
QPDFObjectHandle H = m->lindict.getKey("/H");
QPDFObjectHandle O = m->lindict.getKey("/O");
QPDFObjectHandle E = m->lindict.getKey("/E");
QPDFObjectHandle N = m->lindict.getKey("/N");
QPDFObjectHandle T = m->lindict.getKey("/T");
QPDFObjectHandle P = m->lindict.getKey("/P");
if (!(H.isArray() && O.isInteger() && E.isInteger() && N.isInteger() && T.isInteger() &&
(P.isInteger() || P.isNull()))) {
throw damagedPDF(
"linearization dictionary",
"some keys in linearization dictionary are of the wrong type");
}
// Hint table array: offset length [ offset length ]
size_t n_H_items = toS(H.getArrayNItems());
if (!((n_H_items == 2) || (n_H_items == 4))) {
throw damagedPDF("linearization dictionary", "H has the wrong number of items");
}
std::vector<int> H_items;
for (size_t i = 0; i < n_H_items; ++i) {
QPDFObjectHandle oh(H.getArrayItem(toI(i)));
if (oh.isInteger()) {
H_items.push_back(oh.getIntValueAsInt());
} else {
throw damagedPDF("linearization dictionary", "some H items are of the wrong type");
}
}
// H: hint table offset/length for primary and overflow hint tables
int H0_offset = H_items.at(0);
int H0_length = H_items.at(1);
int H1_offset = 0;
int H1_length = 0;
if (H_items.size() == 4) {
// Acrobat doesn't read or write these (as PDF 1.4), so we don't have a way to generate a
// test case.
// QTC::TC("qpdf", "QPDF overflow hint table");
H1_offset = H_items.at(2);
H1_length = H_items.at(3);
}
// P: first page number
int first_page = 0;
if (P.isInteger()) {
QTC::TC("qpdf", "QPDF P present in lindict");
first_page = P.getIntValueAsInt();
} else {
QTC::TC("qpdf", "QPDF P absent in lindict");
}
// Store linearization parameter data
// Various places in the code use linp.npages, which is initialized from N, to pre-allocate
// memory, so make sure it's accurate and bail right now if it's not.
if (N.getIntValue() != static_cast<long long>(getAllPages().size())) {
throw damagedPDF("linearization hint table", "/N does not match number of pages");
}
// file_size initialized by isLinearized()
m->linp.first_page_object = O.getIntValueAsInt();
m->linp.first_page_end = E.getIntValue();
m->linp.npages = N.getIntValueAsInt();
m->linp.xref_zero_offset = T.getIntValue();
m->linp.first_page = first_page;
m->linp.H_offset = H0_offset;
m->linp.H_length = H0_length;
// Read hint streams
Pl_Buffer pb("hint buffer");
QPDFObjectHandle H0 = readHintStream(pb, H0_offset, toS(H0_length));
if (H1_offset) {
(void)readHintStream(pb, H1_offset, toS(H1_length));
}
// PDF 1.4 hint tables that we ignore:
// /T thumbnail
// /A thread information
// /E named destination
// /V interactive form
// /I information dictionary
// /C logical structure
// /L page label
// Individual hint table offsets
QPDFObjectHandle HS = H0.getKey("/S"); // shared object
QPDFObjectHandle HO = H0.getKey("/O"); // outline
auto hbp = pb.getBufferSharedPointer();
Buffer* hb = hbp.get();
unsigned char const* h_buf = hb->getBuffer();
size_t h_size = hb->getSize();
readHPageOffset(BitStream(h_buf, h_size));
int HSi = HS.getIntValueAsInt();
if ((HSi < 0) || (toS(HSi) >= h_size)) {
throw damagedPDF("linearization hint table", "/S (shared object) offset is out of bounds");
}
readHSharedObject(BitStream(h_buf + HSi, h_size - toS(HSi)));
if (HO.isInteger()) {
int HOi = HO.getIntValueAsInt();
if ((HOi < 0) || (toS(HOi) >= h_size)) {
throw damagedPDF("linearization hint table", "/O (outline) offset is out of bounds");
}
readHGeneric(BitStream(h_buf + HOi, h_size - toS(HOi)), m->outline_hints);
}
}
QPDFObjectHandle
QPDF::readHintStream(Pipeline& pl, qpdf_offset_t offset, size_t length)
{
QPDFObjGen og;
QPDFObjectHandle H =
readObjectAtOffset(false, offset, "linearization hint stream", QPDFObjGen(0, 0), og, false);
ObjCache& oc = m->obj_cache[og];
qpdf_offset_t min_end_offset = oc.end_before_space;
qpdf_offset_t max_end_offset = oc.end_after_space;
if (!H.isStream()) {
throw damagedPDF("linearization dictionary", "hint table is not a stream");
}
QPDFObjectHandle Hdict = H.getDict();
// Some versions of Acrobat make /Length indirect and place it immediately after the stream,
// increasing length to cover it, even though the specification says all objects in the
// linearization parameter dictionary must be direct. We have to get the file position of the
// end of length in this case.
QPDFObjectHandle length_obj = Hdict.getKey("/Length");
if (length_obj.isIndirect()) {
QTC::TC("qpdf", "QPDF hint table length indirect");
// Force resolution
(void)length_obj.getIntValue();
ObjCache& oc2 = m->obj_cache[length_obj.getObjGen()];
min_end_offset = oc2.end_before_space;
max_end_offset = oc2.end_after_space;
} else {
QTC::TC("qpdf", "QPDF hint table length direct");
}
qpdf_offset_t computed_end = offset + toO(length);
if ((computed_end < min_end_offset) || (computed_end > max_end_offset)) {
linearizationWarning(
"expected = " + std::to_string(computed_end) +
"; actual = " + std::to_string(min_end_offset) + ".." + std::to_string(max_end_offset));
throw damagedPDF("linearization dictionary", "hint table length mismatch");
}
H.pipeStreamData(&pl, 0, qpdf_dl_specialized);
return Hdict;
}
void
QPDF::readHPageOffset(BitStream h)
{
// All comments referring to the PDF spec refer to the spec for version 1.4.
HPageOffset& t = m->page_offset_hints;
t.min_nobjects = h.getBitsInt(32); // 1
t.first_page_offset = h.getBitsInt(32); // 2
t.nbits_delta_nobjects = h.getBitsInt(16); // 3
t.min_page_length = h.getBitsInt(32); // 4
t.nbits_delta_page_length = h.getBitsInt(16); // 5
t.min_content_offset = h.getBitsInt(32); // 6
t.nbits_delta_content_offset = h.getBitsInt(16); // 7
t.min_content_length = h.getBitsInt(32); // 8
t.nbits_delta_content_length = h.getBitsInt(16); // 9
t.nbits_nshared_objects = h.getBitsInt(16); // 10
t.nbits_shared_identifier = h.getBitsInt(16); // 11
t.nbits_shared_numerator = h.getBitsInt(16); // 12
t.shared_denominator = h.getBitsInt(16); // 13
std::vector<HPageOffsetEntry>& entries = t.entries;
entries.clear();
int nitems = m->linp.npages;
load_vector_int(h, nitems, entries, t.nbits_delta_nobjects, &HPageOffsetEntry::delta_nobjects);
load_vector_int(
h, nitems, entries, t.nbits_delta_page_length, &HPageOffsetEntry::delta_page_length);
load_vector_int(
h, nitems, entries, t.nbits_nshared_objects, &HPageOffsetEntry::nshared_objects);
load_vector_vector(
h,
nitems,
entries,
&HPageOffsetEntry::nshared_objects,
t.nbits_shared_identifier,
&HPageOffsetEntry::shared_identifiers);
load_vector_vector(
h,
nitems,
entries,
&HPageOffsetEntry::nshared_objects,
t.nbits_shared_numerator,
&HPageOffsetEntry::shared_numerators);
load_vector_int(
h, nitems, entries, t.nbits_delta_content_offset, &HPageOffsetEntry::delta_content_offset);
load_vector_int(
h, nitems, entries, t.nbits_delta_content_length, &HPageOffsetEntry::delta_content_length);
}
void
QPDF::readHSharedObject(BitStream h)
{
HSharedObject& t = m->shared_object_hints;
t.first_shared_obj = h.getBitsInt(32); // 1
t.first_shared_offset = h.getBitsInt(32); // 2
t.nshared_first_page = h.getBitsInt(32); // 3
t.nshared_total = h.getBitsInt(32); // 4
t.nbits_nobjects = h.getBitsInt(16); // 5
t.min_group_length = h.getBitsInt(32); // 6
t.nbits_delta_group_length = h.getBitsInt(16); // 7
QTC::TC(
"qpdf",
"QPDF lin nshared_total > nshared_first_page",
(t.nshared_total > t.nshared_first_page) ? 1 : 0);
std::vector<HSharedObjectEntry>& entries = t.entries;
entries.clear();
int nitems = t.nshared_total;
load_vector_int(
h, nitems, entries, t.nbits_delta_group_length, &HSharedObjectEntry::delta_group_length);
load_vector_int(h, nitems, entries, 1, &HSharedObjectEntry::signature_present);
for (size_t i = 0; i < toS(nitems); ++i) {
if (entries.at(i).signature_present) {
// Skip 128-bit MD5 hash. These are not supported by acrobat, so they should probably
// never be there. We have no test case for this.
for (int j = 0; j < 4; ++j) {
(void)h.getBits(32);
}
}
}
load_vector_int(h, nitems, entries, t.nbits_nobjects, &HSharedObjectEntry::nobjects_minus_one);
}
void
QPDF::readHGeneric(BitStream h, HGeneric& t)
{
t.first_object = h.getBitsInt(32); // 1
t.first_object_offset = h.getBitsInt(32); // 2
t.nobjects = h.getBitsInt(32); // 3
t.group_length = h.getBitsInt(32); // 4
}
bool
QPDF::checkLinearizationInternal()
{
// All comments referring to the PDF spec refer to the spec for version 1.4.
// Check all values in linearization parameter dictionary
LinParameters& p = m->linp;
// L: file size in bytes -- checked by isLinearized
// O: object number of first page
std::vector<QPDFObjectHandle> const& pages = getAllPages();
if (p.first_page_object != pages.at(0).getObjectID()) {
QTC::TC("qpdf", "QPDF err /O mismatch");
linearizationWarning("first page object (/O) mismatch");
}
// N: number of pages
int npages = toI(pages.size());
if (p.npages != npages) {
// Not tested in the test suite
linearizationWarning("page count (/N) mismatch");
}
for (size_t i = 0; i < toS(npages); ++i) {
QPDFObjectHandle const& page = pages.at(i);
QPDFObjGen og(page.getObjGen());
if (m->xref_table[og].getType() == 2) {
linearizationWarning(
"page dictionary for page " + std::to_string(i) + " is compressed");
}
}
// T: offset of whitespace character preceding xref entry for object 0
m->file->seek(p.xref_zero_offset, SEEK_SET);
while (true) {
char ch;
m->file->read(&ch, 1);
if (!((ch == ' ') || (ch == '\r') || (ch == '\n'))) {
m->file->seek(-1, SEEK_CUR);
break;
}
}
if (m->file->tell() != m->first_xref_item_offset) {
QTC::TC("qpdf", "QPDF err /T mismatch");
linearizationWarning(
"space before first xref item (/T) mismatch "
"(computed = " +
std::to_string(m->first_xref_item_offset) +
"; file = " + std::to_string(m->file->tell()));
}
// P: first page number -- Implementation note 124 says Acrobat ignores this value, so we will
// too.
// Check numbering of compressed objects in each xref section. For linearized files, all
// compressed objects are supposed to be at the end of the containing xref section if any object
// streams are in use.
if (m->uncompressed_after_compressed) {
linearizationWarning("linearized file contains an uncompressed object after a compressed "
"one in a cross-reference stream");
}
// Further checking requires optimization and order calculation. Don't allow optimization to
// make changes. If it has to, then the file is not properly linearized. We use the xref table
// to figure out which objects are compressed and which are uncompressed.
{ // local scope
std::map<int, int> object_stream_data;
for (auto const& iter: m->xref_table) {
QPDFObjGen const& og = iter.first;
QPDFXRefEntry const& entry = iter.second;
if (entry.getType() == 2) {
object_stream_data[og.getObj()] = entry.getObjStreamNumber();
}
}
optimize(object_stream_data, false);
calculateLinearizationData(object_stream_data);
}
// E: offset of end of first page -- Implementation note 123 says Acrobat includes on extra
// object here by mistake. pdlin fails to place thumbnail images in section 9, so when
// thumbnails are present, it also gets the wrong value for /E. It also doesn't count outlines
// here when it should even though it places them in part 6. This code fails to put thread
// information dictionaries in part 9, so it actually gets the wrong value for E when threads
// are present. In that case, it would probably agree with pdlin. As of this writing, the test
// suite doesn't contain any files with threads.
if (m->part6.empty()) {
stopOnError("linearization part 6 unexpectedly empty");
}
qpdf_offset_t min_E = -1;
qpdf_offset_t max_E = -1;
for (auto const& oh: m->part6) {
QPDFObjGen og(oh.getObjGen());
if (m->obj_cache.count(og) == 0) {
// All objects have to have been dereferenced to be classified.
throw std::logic_error("linearization part6 object not in cache");
}
ObjCache const& oc = m->obj_cache[og];
min_E = std::max(min_E, oc.end_before_space);
max_E = std::max(max_E, oc.end_after_space);
}
if ((p.first_page_end < min_E) || (p.first_page_end > max_E)) {
QTC::TC("qpdf", "QPDF warn /E mismatch");
linearizationWarning(
"end of first page section (/E) mismatch: /E = " + std::to_string(p.first_page_end) +
"; computed = " + std::to_string(min_E) + ".." + std::to_string(max_E));
}
// Check hint tables
std::map<int, int> shared_idx_to_obj;
checkHSharedObject(pages, shared_idx_to_obj);
checkHPageOffset(pages, shared_idx_to_obj);
checkHOutlines();
return !m->linearization_warnings;
}
qpdf_offset_t
QPDF::maxEnd(ObjUser const& ou)
{
if (m->obj_user_to_objects.count(ou) == 0) {
stopOnError("no entry in object user table for requested object user");
}
qpdf_offset_t end = 0;
for (auto const& og: m->obj_user_to_objects[ou]) {
if (m->obj_cache.count(og) == 0) {
stopOnError("unknown object referenced in object user table");
}
end = std::max(end, m->obj_cache[og].end_after_space);
}
return end;
}
qpdf_offset_t
QPDF::getLinearizationOffset(QPDFObjGen const& og)
{
QPDFXRefEntry entry = m->xref_table[og];
qpdf_offset_t result = 0;
switch (entry.getType()) {
case 1:
result = entry.getOffset();
break;
case 2:
// For compressed objects, return the offset of the object stream that contains them.
result = getLinearizationOffset(QPDFObjGen(entry.getObjStreamNumber(), 0));
break;
default:
stopOnError("getLinearizationOffset called for xref entry not of type 1 or 2");
break;
}
return result;
}
QPDFObjectHandle
QPDF::getUncompressedObject(QPDFObjectHandle& obj, std::map<int, int> const& object_stream_data)
{
if (obj.isNull() || (object_stream_data.count(obj.getObjectID()) == 0)) {
return obj;
} else {
int repl = (*(object_stream_data.find(obj.getObjectID()))).second;
return getObject(repl, 0);
}
}
int
QPDF::lengthNextN(int first_object, int n)
{
int length = 0;
for (int i = 0; i < n; ++i) {
QPDFObjGen og(first_object + i, 0);
if (m->xref_table.count(og) == 0) {
linearizationWarning(
"no xref table entry for " + std::to_string(first_object + i) + " 0");
} else {
if (m->obj_cache.count(og) == 0) {
stopOnError("found unknown object while calculating length for linearization data");
}
length += toI(m->obj_cache[og].end_after_space - getLinearizationOffset(og));
}
}
return length;
}
void
QPDF::checkHPageOffset(
std::vector<QPDFObjectHandle> const& pages, std::map<int, int>& shared_idx_to_obj)
{
// Implementation note 126 says Acrobat always sets delta_content_offset and
// delta_content_length in the page offset header dictionary to 0. It also states that
// min_content_offset in the per-page information is always 0, which is an incorrect value.
// Implementation note 127 explains that Acrobat always sets item 8 (min_content_length) to
// zero, item 9 (nbits_delta_content_length) to the value of item 5 (nbits_delta_page_length),
// and item 7 of each per-page hint table (delta_content_length) to item 2 (delta_page_length)
// of that entry. Acrobat ignores these values when reading files.
// Empirically, it also seems that Acrobat sometimes puts items under a page's /Resources
// dictionary in with shared objects even when they are private.
int npages = toI(pages.size());
qpdf_offset_t table_offset = adjusted_offset(m->page_offset_hints.first_page_offset);
QPDFObjGen first_page_og(pages.at(0).getObjGen());
if (m->xref_table.count(first_page_og) == 0) {
stopOnError("supposed first page object is not known");
}
qpdf_offset_t offset = getLinearizationOffset(first_page_og);
if (table_offset != offset) {
linearizationWarning("first page object offset mismatch");
}
for (int pageno = 0; pageno < npages; ++pageno) {
QPDFObjGen page_og(pages.at(toS(pageno)).getObjGen());
int first_object = page_og.getObj();
if (m->xref_table.count(page_og) == 0) {
stopOnError("unknown object in page offset hint table");
}
offset = getLinearizationOffset(page_og);
HPageOffsetEntry& he = m->page_offset_hints.entries.at(toS(pageno));
CHPageOffsetEntry& ce = m->c_page_offset_data.entries.at(toS(pageno));
int h_nobjects = he.delta_nobjects + m->page_offset_hints.min_nobjects;
if (h_nobjects != ce.nobjects) {
// This happens with pdlin when there are thumbnails.
linearizationWarning(
"object count mismatch for page " + std::to_string(pageno) + ": hint table = " +
std::to_string(h_nobjects) + "; computed = " + std::to_string(ce.nobjects));
}
// Use value for number of objects in hint table rather than computed value if there is a
// discrepancy.
int length = lengthNextN(first_object, h_nobjects);
int h_length = toI(he.delta_page_length + m->page_offset_hints.min_page_length);
if (length != h_length) {
// This condition almost certainly indicates a bad hint table or a bug in this code.
linearizationWarning(
"page length mismatch for page " + std::to_string(pageno) + ": hint table = " +
std::to_string(h_length) + "; computed length = " + std::to_string(length) +
" (offset = " + std::to_string(offset) + ")");
}
offset += h_length;
// Translate shared object indexes to object numbers.
std::set<int> hint_shared;
std::set<int> computed_shared;
if ((pageno == 0) && (he.nshared_objects > 0)) {
// pdlin and Acrobat both do this even though the spec states clearly and unambiguously
// that they should not.
linearizationWarning("page 0 has shared identifier entries");
}
for (size_t i = 0; i < toS(he.nshared_objects); ++i) {
int idx = he.shared_identifiers.at(i);
if (shared_idx_to_obj.count(idx) == 0) {
stopOnError("unable to get object for item in"
" shared objects hint table");
}
hint_shared.insert(shared_idx_to_obj[idx]);
}
for (size_t i = 0; i < toS(ce.nshared_objects); ++i) {
int idx = ce.shared_identifiers.at(i);
if (idx >= m->c_shared_object_data.nshared_total) {
stopOnError("index out of bounds for shared object hint table");
}
int obj = m->c_shared_object_data.entries.at(toS(idx)).object;
computed_shared.insert(obj);
}
for (int iter: hint_shared) {
if (!computed_shared.count(iter)) {
// pdlin puts thumbnails here even though it shouldn't
linearizationWarning(
"page " + std::to_string(pageno) + ": shared object " + std::to_string(iter) +
": in hint table but not computed list");
}
}
for (int iter: computed_shared) {
if (!hint_shared.count(iter)) {
// Acrobat does not put some things including at least built-in fonts and procsets
// here, at least in some cases.
linearizationWarning(
("page " + std::to_string(pageno) + ": shared object " + std::to_string(iter) +
": in computed list but not hint table"));
}
}
}
}
void
QPDF::checkHSharedObject(std::vector<QPDFObjectHandle> const& pages, std::map<int, int>& idx_to_obj)
{
// Implementation note 125 says shared object groups always contain only one object.
// Implementation note 128 says that Acrobat always nbits_nobjects to zero. Implementation note
// 130 says that Acrobat does not support more than one shared object per group. These are all
// consistent.
// Implementation note 129 states that MD5 signatures are not implemented in Acrobat, so
// signature_present must always be zero.
// Implementation note 131 states that first_shared_obj and first_shared_offset have meaningless
// values for single-page files.
// Empirically, Acrobat and pdlin generate incorrect values for these whenever there are no
// shared objects not referenced by the first page (i.e., nshared_total == nshared_first_page).
HSharedObject& so = m->shared_object_hints;
if (so.nshared_total < so.nshared_first_page) {
linearizationWarning("shared object hint table: ntotal < nfirst_page");
} else {
// The first nshared_first_page objects are consecutive objects starting with the first page
// object. The rest are consecutive starting from the first_shared_obj object.
int cur_object = pages.at(0).getObjectID();
for (int i = 0; i < so.nshared_total; ++i) {
if (i == so.nshared_first_page) {
QTC::TC("qpdf", "QPDF lin check shared past first page");
if (m->part8.empty()) {
linearizationWarning("part 8 is empty but nshared_total > "
"nshared_first_page");
} else {
int obj = m->part8.at(0).getObjectID();
if (obj != so.first_shared_obj) {
linearizationWarning(
"first shared object number mismatch: "
"hint table = " +
std::to_string(so.first_shared_obj) +
"; computed = " + std::to_string(obj));
}
}
cur_object = so.first_shared_obj;
QPDFObjGen og(cur_object, 0);
if (m->xref_table.count(og) == 0) {
stopOnError("unknown object in shared object hint table");
}
qpdf_offset_t offset = getLinearizationOffset(og);
qpdf_offset_t h_offset = adjusted_offset(so.first_shared_offset);
if (offset != h_offset) {
linearizationWarning(
"first shared object offset mismatch: hint table = " +
std::to_string(h_offset) + "; computed = " + std::to_string(offset));
}
}
idx_to_obj[i] = cur_object;
HSharedObjectEntry& se = so.entries.at(toS(i));
int nobjects = se.nobjects_minus_one + 1;
int length = lengthNextN(cur_object, nobjects);
int h_length = so.min_group_length + se.delta_group_length;
if (length != h_length) {
linearizationWarning(
"shared object " + std::to_string(i) + " length mismatch: hint table = " +
std::to_string(h_length) + "; computed = " + std::to_string(length));
}
cur_object += nobjects;
}
}
}
void
QPDF::checkHOutlines()
{
// Empirically, Acrobat generates the correct value for the object number but incorrectly stores
// the next object number's offset as the offset, at least when outlines appear in part 6. It
// also generates an incorrect value for length (specifically, the length that would cover the
// correct number of objects from the wrong starting place). pdlin appears to generate correct
// values in those cases.
if (m->c_outline_data.nobjects == m->outline_hints.nobjects) {
if (m->c_outline_data.nobjects == 0) {
return;
}
if (m->c_outline_data.first_object == m->outline_hints.first_object) {
// Check length and offset. Acrobat gets these wrong.
QPDFObjectHandle outlines = getRoot().getKey("/Outlines");
if (!outlines.isIndirect()) {
// This case is not exercised in test suite since not permitted by the spec, but if
// this does occur, the code below would fail.
linearizationWarning("/Outlines key of root dictionary is not indirect");
return;
}
QPDFObjGen og(outlines.getObjGen());
if (m->xref_table.count(og) == 0) {
stopOnError("unknown object in outlines hint table");
}
qpdf_offset_t offset = getLinearizationOffset(og);
ObjUser ou(ObjUser::ou_root_key, "/Outlines");
int length = toI(maxEnd(ou) - offset);
qpdf_offset_t table_offset = adjusted_offset(m->outline_hints.first_object_offset);
if (offset != table_offset) {
linearizationWarning(
"incorrect offset in outlines table: hint table = " +
std::to_string(table_offset) + "; computed = " + std::to_string(offset));
}
int table_length = m->outline_hints.group_length;
if (length != table_length) {
linearizationWarning(
"incorrect length in outlines table: hint table = " +
std::to_string(table_length) + "; computed = " + std::to_string(length));
}
} else {
linearizationWarning("incorrect first object number in outline "
"hints table.");
}
} else {
linearizationWarning("incorrect object count in outline hint table");
}
}
void
QPDF::showLinearizationData()
{
try {
readLinearizationData();
checkLinearizationInternal();
dumpLinearizationDataInternal();
} catch (QPDFExc& e) {
linearizationWarning(e.what());
}
}
void
QPDF::dumpLinearizationDataInternal()
{
*m->log->getInfo() << m->file->getName() << ": linearization data:\n\n";
*m->log->getInfo() << "file_size: " << m->linp.file_size << "\n"
<< "first_page_object: " << m->linp.first_page_object << "\n"
<< "first_page_end: " << m->linp.first_page_end << "\n"
<< "npages: " << m->linp.npages << "\n"
<< "xref_zero_offset: " << m->linp.xref_zero_offset << "\n"
<< "first_page: " << m->linp.first_page << "\n"
<< "H_offset: " << m->linp.H_offset << "\n"
<< "H_length: " << m->linp.H_length << "\n"
<< "\n";
*m->log->getInfo() << "Page Offsets Hint Table\n\n";
dumpHPageOffset();
*m->log->getInfo() << "\nShared Objects Hint Table\n\n";
dumpHSharedObject();
if (m->outline_hints.nobjects > 0) {
*m->log->getInfo() << "\nOutlines Hint Table\n\n";
dumpHGeneric(m->outline_hints);
}
}
qpdf_offset_t
QPDF::adjusted_offset(qpdf_offset_t offset)
{
// All offsets >= H_offset have to be increased by H_length since all hint table location values
// disregard the hint table itself.
if (offset >= m->linp.H_offset) {
return offset + m->linp.H_length;
}
return offset;
}
void
QPDF::dumpHPageOffset()
{
HPageOffset& t = m->page_offset_hints;
*m->log->getInfo() << "min_nobjects: " << t.min_nobjects << "\n"
<< "first_page_offset: " << adjusted_offset(t.first_page_offset) << "\n"
<< "nbits_delta_nobjects: " << t.nbits_delta_nobjects << "\n"
<< "min_page_length: " << t.min_page_length << "\n"
<< "nbits_delta_page_length: " << t.nbits_delta_page_length << "\n"
<< "min_content_offset: " << t.min_content_offset << "\n"
<< "nbits_delta_content_offset: " << t.nbits_delta_content_offset << "\n"
<< "min_content_length: " << t.min_content_length << "\n"
<< "nbits_delta_content_length: " << t.nbits_delta_content_length << "\n"
<< "nbits_nshared_objects: " << t.nbits_nshared_objects << "\n"
<< "nbits_shared_identifier: " << t.nbits_shared_identifier << "\n"
<< "nbits_shared_numerator: " << t.nbits_shared_numerator << "\n"
<< "shared_denominator: " << t.shared_denominator << "\n";
for (size_t i1 = 0; i1 < toS(m->linp.npages); ++i1) {
HPageOffsetEntry& pe = t.entries.at(i1);
*m->log->getInfo() << "Page " << i1 << ":\n"
<< " nobjects: " << pe.delta_nobjects + t.min_nobjects << "\n"
<< " length: " << pe.delta_page_length + t.min_page_length
<< "\n"
// content offset is relative to page, not file
<< " content_offset: " << pe.delta_content_offset + t.min_content_offset
<< "\n"
<< " content_length: " << pe.delta_content_length + t.min_content_length
<< "\n"
<< " nshared_objects: " << pe.nshared_objects << "\n";
for (size_t i2 = 0; i2 < toS(pe.nshared_objects); ++i2) {
*m->log->getInfo() << " identifier " << i2 << ": " << pe.shared_identifiers.at(i2)
<< "\n";
*m->log->getInfo() << " numerator " << i2 << ": " << pe.shared_numerators.at(i2)
<< "\n";
}
}
}
void
QPDF::dumpHSharedObject()
{
HSharedObject& t = m->shared_object_hints;
*m->log->getInfo() << "first_shared_obj: " << t.first_shared_obj << "\n"
<< "first_shared_offset: " << adjusted_offset(t.first_shared_offset) << "\n"
<< "nshared_first_page: " << t.nshared_first_page << "\n"
<< "nshared_total: " << t.nshared_total << "\n"
<< "nbits_nobjects: " << t.nbits_nobjects << "\n"
<< "min_group_length: " << t.min_group_length << "\n"
<< "nbits_delta_group_length: " << t.nbits_delta_group_length << "\n";
for (size_t i = 0; i < toS(t.nshared_total); ++i) {
HSharedObjectEntry& se = t.entries.at(i);
*m->log->getInfo() << "Shared Object " << i << ":\n"
<< " group length: " << se.delta_group_length + t.min_group_length
<< "\n";
// PDF spec says signature present nobjects_minus_one are always 0, so print them only if
// they have a non-zero value.
if (se.signature_present) {
*m->log->getInfo() << " signature present\n";
}
if (se.nobjects_minus_one != 0) {
*m->log->getInfo() << " nobjects: " << se.nobjects_minus_one + 1 << "\n";
}
}
}
void
QPDF::dumpHGeneric(HGeneric& t)
{
*m->log->getInfo() << "first_object: " << t.first_object << "\n"
<< "first_object_offset: " << adjusted_offset(t.first_object_offset) << "\n"
<< "nobjects: " << t.nobjects << "\n"
<< "group_length: " << t.group_length << "\n";
}
void
QPDF::calculateLinearizationData(std::map<int, int> const& object_stream_data)
{
// This function calculates the ordering of objects, divides them into the appropriate parts,
// and computes some values for the linearization parameter dictionary and hint tables. The
// file must be optimized (via calling optimize()) prior to calling this function. Note that
// actual offsets and lengths are not computed here, but anything related to object ordering is.
if (m->object_to_obj_users.empty()) {
// Note that we can't call optimize here because we don't know whether it should be called
// with or without allow changes.
throw std::logic_error(
"INTERNAL ERROR: QPDF::calculateLinearizationData called before optimize()");
}
// Separate objects into the categories sufficient for us to determine which part of the
// linearized file should contain the object. This categorization is useful for other purposes
// as well. Part numbers refer to version 1.4 of the PDF spec.
// Parts 1, 3, 5, 10, and 11 don't contain any objects from the original file (except the
// trailer dictionary in part 11).
// Part 4 is the document catalog (root) and the following root keys: /ViewerPreferences,
// /PageMode, /Threads, /OpenAction, /AcroForm, /Encrypt. Note that Thread information
// dictionaries are supposed to appear in part 9, but we are disregarding that recommendation
// for now.
// Part 6 is the first page section. It includes all remaining objects referenced by the first
// page including shared objects but not including thumbnails. Additionally, if /PageMode is
// /Outlines, then information from /Outlines also appears here.
// Part 7 contains remaining objects private to pages other than the first page.
// Part 8 contains all remaining shared objects except those that are shared only within
// thumbnails.
// Part 9 contains all remaining objects.
// We sort objects into the following categories: