-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpdfdump.c
2466 lines (2060 loc) · 73.7 KB
/
pdfdump.c
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
#include <assert.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdnoreturn.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
/*
Spec:
https://web.archive.org/web/20181118152616/https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
or
https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf
(Or jump through hoops at https://pdfa.org/resource/pdf-specification-index/)
Normally you'd read a PDF using the lookup structures at the end of the file
(trailer and xref), and read only the objects needed for rendering the
currently visible page. This here is for dumping all the data in a PDF, so it
starts at the start and reads all the data. Normally you wouldn't do that.
The file format is conceptually somewhat simple, but made harder by additions:
- Incremental Updates
- Linearization (1.2+)
- Object Streams (1.5+)
- Encryption
All of those aren't implemented yet.
To read a PDF, a regular viewer does:
- read the very first line, check that it's a PDF signature, and extracts
the version number
- go to the end of the file, find `startxref` which has offset to `xref`,
and `trailer`, which has number of objects (/Size),
and id of root object (/Root)
- go to `xref`, which has offsets of all obj IDs
- using the `xref` table, read the root object and objs referenced from
there to deserialize all data needed to render a given page
- if the trailer has an /Encrypt key, all string and stream contents need
to be decrypted using the encryption method described by the object stored
under that key before being processed further
For Incremental Updates (3.4.5 in the 1.7 spec), new data is written at the end
of the existing, unchanged PDF data. That means there's a second startxref (and
then a third, fourth, and so on, one more for each incremental safe) pointing
to a second `xref`, and a second trailer before the startxref. The trailer
stores the offset of the previous xref (? XXX) (/Prev). The xref tables are
read newest-to-oldest, and only offsets for objects that don't already have an
entry in a newer table are used from the older tables.
A linearized file stores a "linearization dictionary" at the top of the file,
right after the header, in the first 1024 bytes, containing only direct
objects. `/Linearized 1.0` marks the dictionary as linearization dictionary,
and that dictionary also stores file length (/L), primary hint stream offset
and length (/H), the id of the first page's page object (/O) and the offset to
the end of the first page (/E), the number of total pages in the document (/N)
and the offset to the first entry in the main xref (/T). After the
linearization dictionary is a first xref for just the first page, followed by a
first trailer that stores an offset to the main xref (/Prev), the total number
of xref entries (/Size), and the id of the root object (/Root). Then an
optional `startxref` with an ignored dummy offset (often `0`), followed by
`%%EOF`. Then comes the document catalog, then in any order both the first page
section (including objects for the first page and the outline hierarchy) and
the primary hint stream. After that, the remaining pages and their referenced
objects follow. Then some optional stuff, and finally the main xref, trailer,
startxref (pointing to the _first_ xref), %%EOF. See Appendix F in
pdf_reference_1-7.pdf for details on linearized PDFs.
Object streams are documented in 3.4.6 Object Streams and
3.4.7 Cross-Reference Streams n the 1.7 spec. A Cross-Reference Stream stores
both `trailer` and `xref` data in an object stream: The `trailer` data in the
stream dict, the `xref` data in the stream's contents. It has `/Type /XRef`.
`startxref` now stores the offset of the cross-reference stream instead of
the `xref`. (Per Appendix H, Acrobat 6+ only supports /FlateDecode for
cross-reference streams.)
It's possible to have a hybrid file that has both traditional `xref` /
`trailer` and a cross-reference stream (for files readable by both 1.4- and
1.5+ readers). Here, startxref points at the traditional `xref` but the trailer
dictionary contains a `/XRefStm` key that points at the cross-reference object.
For reasons, this can only be used in update xref sections (see spec).
ideas:
- crunch
- (re)compress streams
- remove spaces between names
- convert to object streams
- remove remnants of incremental edits (multiple %%EOF, etc)
- gc unused indirect objects
- gc old unref'd generetations of indirect objects
- gc unused direct objects (harder)
- gc objects that have no visual/selection/a11y effect (even harder)
- dedup multiple objects with identical contents (?)
- spy
- show only hidden / unref'd contents
- compile
- (re)compress streams
- fill in binary comment at start (?)
- fill in xref table / startxref offset
- fill in stream lengths
- renumber indirect objects (and refs to them), and update trailer /Size
- check that indirect object ref indices make sense
- linearize / delinearize
- tool
- pretty print (consistent newlines, indent dict contents, etc)
- validate
- everything parses (duh)
- all xref entries point at indirect objs
- xref entries have f / n set consistent with generation number
- all indirect objs are ref'd by an xref table
- startxref points at xref table
- stream /Lengths consistent with contents / offset
- hybrid file has consistent data in `xref` / `trailer` and in
cross-reference stream
- statistics
- number of each object type
- number of empty xref entries
- number of indirect objects obsoleted by newer generation
- extract images
- extract text (by file order and by paint order on page; and from selection
data)
- fill in form data
*/
static noreturn void fatal(const char* msg, ...) {
va_list args;
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
exit(1);
}
static void print_usage(FILE* stream, const char* program_name) {
fprintf(stream, "usage: %s [ options ] filename\n", program_name);
fprintf(stream,
"\n"
"options:\n"
" --dump-tokens dump output of tokenizer\n"
" --no-indent disable auto-indentation of pretty-printer\n"
" --save-iccs save ICC color profiles embedded in the PDF\n"
" --save-images save images embedded in the PDF\n"
" --uncompress uncompress compressed streams\n"
" --update-offsets update offsets to match pretty-printed output\n"
" --quiet print no output\n"
" -h --help print this message\n");
}
///////////////////////////////////////////////////////////////////////////////
// Lexer
struct Span {
uint8_t* data;
size_t size;
};
static void span_advance(struct Span* span, size_t s) {
assert(span->size >= s);
span->data += s;
span->size -= s;
}
static bool is_whitespace(uint8_t c) {
// 3.1.1 Character Set
// TABLE 3.1 White-space characters
return c == 0 || c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == ' ';
}
static bool is_newline(uint8_t c) {
return c == '\n' || c == '\r';
}
static bool is_delimiter(uint8_t c) {
// 3.1.1 Character Set
return c == '(' || c == ')' || c == '<' || c == '>' || c == '[' || c == ']' ||
c == '{' || c == '}' || c == '/' || c == '%';
}
static bool is_digit(uint8_t c) {
return c >= '0' && c <= '9';
}
static bool is_number_start(uint8_t c) {
return c == '+' || c == '-' || c == '.' || is_digit(c);
}
static bool is_number_continuation(uint8_t c) {
return c == '.' || is_digit(c);
}
static bool is_name_continuation(uint8_t c) {
// 3.2.4 Name Objects
// "The name may include any regular characters, but not delimiters or
// white-space characters."
return !is_whitespace(c) && !is_delimiter(c);
}
static bool is_octal_digit(uint8_t c) {
return c >= '0' && c <= '7';
}
enum TokenKind {
kw_obj,
kw_endobj,
kw_stream,
kw_endstream,
kw_R,
kw_f,
kw_n,
kw_xref,
kw_trailer,
kw_startxref,
kw_true,
kw_false,
kw_null,
tok_number,
tok_dict, // <<
tok_enddict, // >>
tok_array, // [
tok_endarray, // ]
tok_name, // /asdf
tok_string, // (hi) or <6869>
tok_comment, // %
tok_eof,
};
struct Token {
enum TokenKind kind;
struct Span payload;
};
static void consume_newline(struct Span* data) {
if (data->size == 0)
fatal("not enough data for newline\n");
if (data->data[0] == '\n') {
span_advance(data, 1);
return;
}
if (data->data[0] != '\r')
fatal("not a newline\n");
if (data->size >= 1 && data->data[1] == '\n')
span_advance(data, 1);
span_advance(data, 1);
}
static void advance_to_next_token(struct Span* data) {
while (data->size && is_whitespace(data->data[0]))
span_advance(data, 1);
}
static bool is_keyword(const struct Span* data, const char* keyword) {
size_t n = strlen(keyword);
if (data->size < n)
return false;
if (strncmp((char*)data->data, keyword, n))
return false;
return data->size == n || is_whitespace(data->data[n]) ||
is_delimiter(data->data[n]);
}
static enum TokenKind classify_current(struct Span* data) {
if (data->size == 0)
return tok_eof;
uint8_t c = data->data[0];
assert(!is_whitespace(c));
if (is_number_start(c))
return tok_number;
if (c == '<') {
if (data->size > 1 && data->data[1] == '<')
return tok_dict;
return tok_string;
}
if (c == '>') {
if (data->size > 1 && data->data[1] == '>')
return tok_enddict;
}
if (c == '[')
return tok_array;
if (c == ']')
return tok_endarray;
if (c == '/')
return tok_name;
if (c == '(')
return tok_string;
if (c == '%')
return tok_comment;
if (is_keyword(data, "obj"))
return kw_obj;
if (is_keyword(data, "endobj"))
return kw_endobj;
if (is_keyword(data, "stream"))
return kw_stream;
if (is_keyword(data, "endstream"))
return kw_endstream;
if (is_keyword(data, "R"))
return kw_R;
if (is_keyword(data, "f"))
return kw_f;
if (is_keyword(data, "n"))
return kw_n;
if (is_keyword(data, "xref"))
return kw_xref;
if (is_keyword(data, "trailer"))
return kw_trailer;
if (is_keyword(data, "startxref"))
return kw_startxref;
if (is_keyword(data, "true"))
return kw_true;
if (is_keyword(data, "false"))
return kw_false;
if (is_keyword(data, "null"))
return kw_null;
fatal("unknown token type %d (%c)\n", c, c);
}
static void advance_to_end_of_token(struct Span* data, struct Token* token) {
switch (token->kind) {
case kw_obj:
span_advance(data, strlen("obj"));
break;
case kw_endobj:
span_advance(data, strlen("endobj"));
break;
case kw_stream:
span_advance(data, strlen("stream"));
break;
case kw_endstream:
span_advance(data, strlen("endstream"));
break;
case kw_xref:
span_advance(data, strlen("xref"));
break;
case kw_trailer:
span_advance(data, strlen("trailer"));
break;
case kw_startxref:
span_advance(data, strlen("startxref"));
break;
case kw_true:
span_advance(data, strlen("true"));
break;
case kw_false:
span_advance(data, strlen("false"));
break;
case kw_null:
span_advance(data, strlen("null"));
break;
case tok_eof:
break;
case kw_R:
case kw_f:
case kw_n:
case tok_array:
case tok_endarray:
span_advance(data, 1);
break;
case tok_name:
span_advance(data, 1); // Skip '/'.
while (data->size && is_name_continuation(data->data[0]))
span_advance(data, 1);
break;
case tok_string:
if (data->data[0] == '(') {
// 3.2.3 String Objects, Literal Strings
span_advance(data, 1); // Skip '('.
int open_parens_count = 1;
while (data->size) {
if (data->data[0] == '\\') {
span_advance(data, 1);
if (!data->size)
break;
if (is_octal_digit(data->data[0])) {
if (data->size < 3)
fatal("incomplete octal escape\n");
if (!is_octal_digit(data->data[1]) ||
!is_octal_digit(data->data[2]))
fatal("invalid octal escape\n");
span_advance(data, 3);
} else {
// Table 3.2 Escape sequences in literal strings
switch(data->data[0]) {
case 'n':
case 'r':
case 't':
case 'b':
case 'f':
case '(':
case ')':
case '\\':
span_advance(data, 1);
}
}
// "If the character following the backslash is not one of those
// shown in the table, the backslash is ignored."
continue;
}
// "Any characters may appear in a string except unbalanced
// parentheses and the backslash, which must be treated specially.
// Balanced pairs of parentheses within a string require no special
// treatment."
if (data->data[0] == '(')
++open_parens_count;
else if (data->data[0] == ')') {
--open_parens_count;
if (open_parens_count == 0)
break;
}
span_advance(data, 1);
}
if (!data->size)
fatal("unterminated () string\n");
span_advance(data, 1); // Skip ')'.
} else {
// 3.2.3 String Objects, Hexadecimal Strings
assert(data->data[0] == '<');
span_advance(data, 1); // Skip '<'.
while (data->size && data->data[0] != '>')
span_advance(data, 1);
if (!data->size)
fatal("unterminated <> string\n");
span_advance(data, 1); // Skip '>'.
}
break;
case tok_dict:
case tok_enddict:
span_advance(data, 2);
break;
case tok_comment:
span_advance(data, 1); // Skip '%'.
while (data->size && !is_newline(data->data[0]))
span_advance(data, 1);
// Make newline after the comment not part of the comment's payload.
break;
case tok_number:
// Accepts `4.`, `-.02`, `0.0`, `1234`.
span_advance(data, 1); // Skip number start.
// FIXME: Accepts multiple periods too. Can that ever happen in valid
// PDF files?
while (data->size && is_number_continuation(data->data[0]))
span_advance(data, 1);
break;
}
}
static void read_token_at_current_position(struct Span* data, struct Token* token) {
token->payload.data = data->data;
token->kind = classify_current(data);
advance_to_end_of_token(data, token);
token->payload.size = data->data - token->payload.data;
}
static void read_token(struct Span* data, struct Token* token) {
advance_to_next_token(data);
read_token_at_current_position(data, token);
}
static void read_non_eof_token(struct Span* data, struct Token* token) {
read_token(data, token);
if (token->kind == tok_eof)
fatal("unexpected eof\n");
}
static void read_non_eof_token_at_current_position(struct Span* data,
struct Token* token) {
read_token_at_current_position(data, token);
if (token->kind == tok_eof)
fatal("unexpected eof\n");
}
static void dump_token(const struct Token* token) {
switch (token->kind) {
case kw_obj:
printf("obj\n");
break;
case kw_endobj:
printf("endobj\n");
break;
case kw_stream:
printf("stream\n");
break;
case kw_endstream:
printf("endstream\n");
break;
case kw_R:
printf("R\n");
break;
case kw_f:
printf("f\n");
break;
case kw_n:
printf("n\n");
break;
case kw_xref:
printf("xref\n");
break;
case kw_trailer:
printf("trailer\n");
break;
case kw_startxref:
printf("startxref\n");
break;
case kw_true:
printf("true\n");
break;
case kw_false:
printf("false\n");
break;
case kw_null:
printf("null\n");
break;
case tok_number:
printf("number '%.*s'\n", (int)token->payload.size, token->payload.data);
break;
case tok_dict:
printf("<<\n");
break;
case tok_enddict:
printf(">>\n");
break;
case tok_array:
printf("[\n");
break;
case tok_endarray:
printf("]\n");
break;
case tok_name:
printf("name '%.*s'\n", (int)token->payload.size, token->payload.data);
break;
case tok_string:
printf("string '%.*s'\n", (int)token->payload.size, token->payload.data);
break;
case tok_comment:
printf("%%\n"); // XXX dump comment text?
break;
case tok_eof:
printf("eof\n");
break;
}
}
static void dump_tokens(struct Span* data) {
while (true) {
struct Token token;
read_token(data, &token);
dump_token(&token);
if (token.kind == tok_eof)
break;
// Ignore everything inside a `stream`.
// FIXME: This is a bit janky. 3.7.1 Content Streams says
// "A content stream, after decoding with any specified filters,
// is interpreted according to the PDF syntax rules described in
// Section 3.1"
// I think this implies we have to make lexing context-sensitive
// for streams.
// FIXME: Can streams contain `endstream` in their data? Do we have to
// use `Length` from the info dict?
if (token.kind == kw_stream) {
// 3.2.7 Stream Objects
const uint8_t* e = memmem(data->data, data->size,
"endstream", strlen("endstream"));
if (!e)
fatal("missing `endstream`\n");
span_advance(data, e - data->data);
}
}
}
///////////////////////////////////////////////////////////////////////////////
// AST
// 3.2 Objects
enum ObjectKind {
Boolean,
Integer,
Real,
String, // (hi) or <6869>
Name, // /hi
Array, // [0 1 2]
Dictionary, // <</Name1 (val1) /Name2 (val2)>>
// 3.2.7 Stream Objects
// "All streams must be indirect objects and the stream dictionary must
// be a direct object."
Stream,
Null,
IndirectObject, // 4 0 obj ... endobj
IndirectObjectRef, // 4 0 R
// FIXME: Having an AST node for comments is a bit weird: where should it go
// for dicts? Where if the comment is between the indirect obj or
// indirect obj ref tokens?
Comment, // For pretty-printing
// In traditional PDFs, the `xref` table is at the end of the file.
// But for incremental updates, and for linearized PDFs, the xref table
// can appear multiple times, sometimes in the middle of the file; or it might
// be hidden away in an object stream, and only `startxref` might be visible.
// So represent `xref`, `startxref`, and `trailer` as normal objects.
XRef,
Trailer,
StartXRef,
};
struct Object {
enum ObjectKind kind;
// Array-of-Structures design; pick array to index into based on `kind`.
size_t index;
};
struct BooleanObject {
bool value;
};
struct IntegerObject {
int32_t value;
};
struct RealObject {
double value;
};
struct StringObject {
struct Span value;
};
struct NameObject {
struct Span value;
};
struct ArrayObject {
size_t count;
struct Object* elements;
};
struct NameObjectPair {
struct NameObject name;
struct Object value;
};
struct DictionaryObject {
size_t count;
struct NameObjectPair* elements;
};
struct Object* dict_get(const struct DictionaryObject* dict, const char* key) {
// FIXME: maybe have a lazily-created hash table on the side?
size_t l = strlen(key);
for (size_t i = 0; i < dict->count; ++i) {
if (dict->elements[i].name.value.size != l ||
strncmp(key, (char*)dict->elements[i].name.value.data, l))
continue;
// 3.2.6 Dictionary Objects
// "A dictionary entry whose value is `null` is equivalent ot an absent entry."
if (dict->elements[i].value.kind == Null)
return NULL;
return &dict->elements[i].value;
}
return NULL;
}
void dict_append(struct DictionaryObject* dict,
struct NameObjectPair new_element) {
// new_element.key must not yet be in the dict.
dict->elements = realloc(dict->elements,
(dict->count + 1) * sizeof(struct NameObjectPair));
dict->elements[dict->count] = new_element;
dict->count++;
}
struct StreamObject {
struct DictionaryObject dict;
struct Span data;
};
struct IndirectObjectObject {
size_t id;
size_t generation;
struct Object value;
};
struct IndirectObjectRefObject {
size_t id;
size_t generation;
};
struct CommentObject {
struct Span value;
};
struct XRefEntry {
size_t offset;
size_t generation;
bool is_free; // true for 'f', false for 'n'
};
struct XRefRange {
size_t start_id;
size_t count;
struct XRefEntry* entries;
};
struct XRefObject {
size_t count;
struct XRefRange* ranges;
};
struct TrailerObject {
struct DictionaryObject dict;
};
struct StartXRefObject {
size_t offset;
};
struct PDFVersion {
uint8_t major;
uint8_t minor;
};
struct PDF {
struct PDFVersion version;
// AST storage.
// Stores all objects of a type, including nested direct objects.
struct BooleanObject* booleans;
size_t booleans_count;
size_t booleans_capacity;
struct IntegerObject* integers;
size_t integers_count;
size_t integers_capacity;
struct RealObject* reals;
size_t reals_count;
size_t reals_capacity;
struct StringObject* strings;
size_t strings_count;
size_t strings_capacity;
struct NameObject* names;
size_t names_count;
size_t names_capacity;
struct ArrayObject* arrays;
size_t arrays_count;
size_t arrays_capacity;
struct DictionaryObject* dicts;
size_t dicts_count;
size_t dicts_capacity;
struct StreamObject* streams;
size_t streams_count;
size_t streams_capacity;
struct IndirectObjectObject* indirect_objects;
size_t indirect_objects_count;
size_t indirect_objects_capacity;
struct IndirectObjectRefObject* indirect_object_refs;
size_t indirect_object_refs_count;
size_t indirect_object_refs_capacity;
struct CommentObject* comments;
size_t comments_count;
size_t comments_capacity;
struct XRefObject* xrefs;
size_t xrefs_count;
size_t xrefs_capacity;
struct TrailerObject* trailers;
size_t trailers_count;
size_t trailers_capacity;
struct StartXRefObject* start_xrefs;
size_t start_xrefs_count;
size_t start_xrefs_capacity;
// Only stores toplevel objects.
// The indices in these Objects refer to the arrays above.
struct Object* toplevel_objects;
size_t toplevel_objects_count;
size_t toplevel_objects_capacity;
// Parsing option.
// FIXME: Should probably be somewhere else.
bool trust_stream_lengths;
};
static void init_pdf(struct PDF* pdf) {
#define N 5
#define INIT(name, type) \
pdf->name = malloc(N * sizeof(struct type)); \
pdf->name##_count = 0; \
pdf->name##_capacity = N
INIT(booleans, BooleanObject);
INIT(integers, IntegerObject);
INIT(reals, RealObject);
INIT(strings, StringObject);
INIT(names, NameObject);
INIT(arrays, ArrayObject);
INIT(dicts, DictionaryObject);
INIT(streams, StreamObject);
INIT(indirect_objects, IndirectObjectObject);
INIT(indirect_object_refs, IndirectObjectRefObject);
INIT(comments, CommentObject);
INIT(xrefs, XRefObject);
INIT(trailers, TrailerObject);
INIT(start_xrefs, StartXRefObject);
INIT(toplevel_objects, Object);
#undef INIT
#undef N
pdf->trust_stream_lengths = true;
}
static void append_boolean(struct PDF* pdf, struct BooleanObject value) {
if (pdf->booleans_count >= pdf->booleans_capacity) {
pdf->booleans_capacity *= 2;
pdf->booleans = realloc(pdf->booleans,
pdf->booleans_capacity * sizeof(struct BooleanObject));
}
pdf->booleans[pdf->booleans_count++] = value;
}
static void append_integer(struct PDF* pdf, struct IntegerObject value) {
if (pdf->integers_count >= pdf->integers_capacity) {
pdf->integers_capacity *= 2;
pdf->integers = realloc(pdf->integers,
pdf->integers_capacity * sizeof(struct IntegerObject));
}
pdf->integers[pdf->integers_count++] = value;
}
static void append_real(struct PDF* pdf, struct RealObject value) {
if (pdf->reals_count >= pdf->reals_capacity) {
pdf->reals_capacity *= 2;
pdf->reals = realloc(pdf->reals,
pdf->reals_capacity * sizeof(struct RealObject));
}
pdf->reals[pdf->reals_count++] = value;
}
static void append_name(struct PDF* pdf, struct NameObject value) {
if (pdf->names_count >= pdf->names_capacity) {
pdf->names_capacity *= 2;
pdf->names = realloc(pdf->names,
pdf->names_capacity * sizeof(struct NameObject));
}
pdf->names[pdf->names_count++] = value;
}
static void append_string(struct PDF* pdf, struct StringObject value) {
if (pdf->strings_count >= pdf->strings_capacity) {
pdf->strings_capacity *= 2;
pdf->strings = realloc(pdf->strings,
pdf->strings_capacity * sizeof(struct StringObject));
}
pdf->strings[pdf->strings_count++] = value;
}
static void append_array(struct PDF* pdf, struct ArrayObject value) {
if (pdf->arrays_count >= pdf->arrays_capacity) {
pdf->arrays_capacity *= 2;
pdf->arrays = realloc(pdf->arrays,
pdf->arrays_capacity * sizeof(struct ArrayObject));
}
pdf->arrays[pdf->arrays_count++] = value;
}
static void append_dict(struct PDF* pdf, struct DictionaryObject value) {
if (pdf->dicts_count >= pdf->dicts_capacity) {
pdf->dicts_capacity *= 2;
pdf->dicts = realloc(pdf->dicts,
pdf->dicts_capacity * sizeof(struct DictionaryObject));
}
pdf->dicts[pdf->dicts_count++] = value;
}
static void append_stream(struct PDF* pdf, struct StreamObject value) {
if (pdf->streams_count >= pdf->streams_capacity) {
pdf->streams_capacity *= 2;
pdf->streams = realloc(pdf->streams,
pdf->streams_capacity * sizeof(struct StreamObject));
}
pdf->streams[pdf->streams_count++] = value;
}
static void append_indirect_object(struct PDF* pdf,
struct IndirectObjectObject value) {
if (pdf->indirect_objects_count >= pdf->indirect_objects_capacity) {
pdf->indirect_objects_capacity *= 2;
pdf->indirect_objects = realloc(
pdf->indirect_objects,
pdf->indirect_objects_capacity * sizeof(struct IndirectObjectObject));
}
pdf->indirect_objects[pdf->indirect_objects_count++] = value;
}
static void append_indirect_object_ref(struct PDF* pdf,
struct IndirectObjectRefObject value) {
if (pdf->indirect_object_refs_count >= pdf->indirect_object_refs_capacity) {
pdf->indirect_object_refs_capacity *= 2;
pdf->indirect_object_refs = realloc(
pdf->indirect_object_refs,
pdf->indirect_object_refs_capacity * sizeof(struct IndirectObjectRefObject));
}
pdf->indirect_object_refs[pdf->indirect_object_refs_count++] = value;
}
static void append_comment(struct PDF* pdf, struct CommentObject value) {
if (pdf->comments_count >= pdf->comments_capacity) {
pdf->comments_capacity *= 2;
pdf->comments = realloc(pdf->comments,
pdf->comments_capacity * sizeof(struct CommentObject));
}
pdf->comments[pdf->comments_count++] = value;
}
static void append_xref(struct PDF* pdf, struct XRefObject value) {
if (pdf->xrefs_count >= pdf->xrefs_capacity) {
pdf->xrefs_capacity *= 2;
pdf->xrefs = realloc(pdf->xrefs,
pdf->xrefs_capacity * sizeof(struct XRefObject));
}
pdf->xrefs[pdf->xrefs_count++] = value;
}
static void append_trailer(struct PDF* pdf, struct TrailerObject value) {