Debian Codegraph @

Utilities/cmliblzma/liblzma/common/index.c

raw symbols SCIP
1 // SPDX-License-Identifier: 0BSD
2
3 ///////////////////////////////////////////////////////////////////////////////
4 //
5 /// \file index.c
6 /// \brief Handling of .xz Indexes and some other Stream information
7 //
8 // Author: Lasse Collin
9 //
10 ///////////////////////////////////////////////////////////////////////////////
11
12 #include "common.h"
13 #include "index.h"
14 #include "stream_flags_common.h"
15
16
17 /// \brief How many Records to allocate at once
18 ///
19 /// This should be big enough to avoid making lots of tiny allocations
20 /// but small enough to avoid too much unused memory at once.
21 #define INDEX_GROUP_SIZE 512
22
23
24 /// \brief How many Records can be allocated at once at maximum
25 #define PREALLOC_MAX ((SIZE_MAX - sizeof(index_group)) / sizeof(index_record))
26
27
28 /// \brief Base structure for index_stream and index_group structures
29 typedef struct index_tree_node_s index_tree_node;
30 struct index_tree_node_s {
31 /// Uncompressed start offset of this Stream (relative to the
32 /// beginning of the file) or Block (relative to the beginning
33 /// of the Stream)
34 lzma_vli uncompressed_base;
35
36 /// Compressed start offset of this Stream or Block
37 lzma_vli compressed_base;
38
39 index_tree_node *parent;
40 index_tree_node *left;
41 index_tree_node *right;
42 };
43
44
45 /// \brief AVL tree to hold index_stream or index_group structures
46 typedef struct {
47 /// Root node
48 index_tree_node *root;
49
50 /// Leftmost node. Since the tree will be filled sequentially,
51 /// this won't change after the first node has been added to
52 /// the tree.
53 index_tree_node *leftmost;
54
55 /// The rightmost node in the tree. Since the tree is filled
56 /// sequentially, this is always the node where to add the new data.
57 index_tree_node *rightmost;
58
59 /// Number of nodes in the tree
60 uint32_t count;
61
62 } index_tree;
63
64
65 typedef struct {
66 lzma_vli uncompressed_sum;
67 lzma_vli unpadded_sum;
68 } index_record;
69
70
71 typedef struct {
72 /// Every Record group is part of index_stream.groups tree.
73 index_tree_node node;
74
75 /// Number of Blocks in this Stream before this group.
76 lzma_vli number_base;
77
78 /// Number of Records that can be put in records[].
79 size_t allocated;
80
81 /// Index of the last Record in use.
82 size_t last;
83
84 /// The sizes in this array are stored as cumulative sums relative
85 /// to the beginning of the Stream. This makes it possible to
86 /// use binary search in lzma_index_locate().
87 ///
88 /// Note that the cumulative summing is done specially for
89 /// unpadded_sum: The previous value is rounded up to the next
90 /// multiple of four before adding the Unpadded Size of the new
91 /// Block. The total encoded size of the Blocks in the Stream
92 /// is records[last].unpadded_sum in the last Record group of
93 /// the Stream.
94 ///
95 /// For example, if the Unpadded Sizes are 39, 57, and 81, the
96 /// stored values are 39, 97 (40 + 57), and 181 (100 + 181).
97 /// The total encoded size of these Blocks is 184.
98 ///
99 /// This is a flexible array, because it makes easy to optimize
100 /// memory usage in case someone concatenates many Streams that
101 /// have only one or few Blocks.
102 index_record records[];
103
104 } index_group;
105
106
107 typedef struct {
108 /// Every index_stream is a node in the tree of Streams.
109 index_tree_node node;
110
111 /// Number of this Stream (first one is 1)
112 uint32_t number;
113
114 /// Total number of Blocks before this Stream
115 lzma_vli block_number_base;
116
117 /// Record groups of this Stream are stored in a tree.
118 /// It's a T-tree with AVL-tree balancing. There are
119 /// INDEX_GROUP_SIZE Records per node by default.
120 /// This keeps the number of memory allocations reasonable
121 /// and finding a Record is fast.
122 index_tree groups;
123
124 /// Number of Records in this Stream
125 lzma_vli record_count;
126
127 /// Size of the List of Records field in this Stream. This is used
128 /// together with record_count to calculate the size of the Index
129 /// field and thus the total size of the Stream.
130 lzma_vli index_list_size;
131
132 /// Stream Flags of this Stream. This is meaningful only if
133 /// the Stream Flags have been told us with lzma_index_stream_flags().
134 /// Initially stream_flags.version is set to UINT32_MAX to indicate
135 /// that the Stream Flags are unknown.
136 lzma_stream_flags stream_flags;
137
138 /// Amount of Stream Padding after this Stream. This defaults to
139 /// zero and can be set with lzma_index_stream_padding().
140 lzma_vli stream_padding;
141
142 } index_stream;
143
144
145 struct lzma_index_s {
146 /// AVL-tree containing the Stream(s). Often there is just one
147 /// Stream, but using a tree keeps lookups fast even when there
148 /// are many concatenated Streams.
149 index_tree streams;
150
151 /// Uncompressed size of all the Blocks in the Stream(s)
152 lzma_vli uncompressed_size;
153
154 /// Total size of all the Blocks in the Stream(s)
155 lzma_vli total_size;
156
157 /// Total number of Records in all Streams in this lzma_index
158 lzma_vli record_count;
159
160 /// Size of the List of Records field if all the Streams in this
161 /// lzma_index were packed into a single Stream (makes it simpler to
162 /// take many .xz files and combine them into a single Stream).
163 ///
164 /// This value together with record_count is needed to calculate
165 /// Backward Size that is stored into Stream Footer.
166 lzma_vli index_list_size;
167
168 /// How many Records to allocate at once in lzma_index_append().
169 /// This defaults to INDEX_GROUP_SIZE but can be overridden with
170 /// lzma_index_prealloc().
171 size_t prealloc;
172
173 /// Bitmask indicating what integrity check types have been used
174 /// as set by lzma_index_stream_flags(). The bit of the last Stream
175 /// is not included here, since it is possible to change it by
176 /// calling lzma_index_stream_flags() again.
177 uint32_t checks;
178 };
179
180
181 static void
182 index_tree_init(index_tree *tree)
183 {
184 tree->root = NULL;
185 tree->leftmost = NULL;
186 tree->rightmost = NULL;
187 tree->count = 0;
188 return;
189 }
190
191
192 /// Helper for index_tree_end()
193 static void
194 index_tree_node_end(index_tree_node *node, const lzma_allocator *allocator,
195 void (*free_func)(void *node, const lzma_allocator *allocator))
196 {
197 // The tree won't ever be very huge, so recursion should be fine.
198 // 20 levels in the tree is likely quite a lot already in practice.
199 if (node->left != NULL)
200 index_tree_node_end(node->left, allocator, free_func);
201
202 if (node->right != NULL)
203 index_tree_node_end(node->right, allocator, free_func);
204
205 free_func(node, allocator);
206 return;
207 }
208
209
210 /// Free the memory allocated for a tree. Each node is freed using the
211 /// given free_func which is either &lzma_free or &index_stream_end.
212 /// The latter is used to free the Record groups from each index_stream
213 /// before freeing the index_stream itself.
214 static void
215 index_tree_end(index_tree *tree, const lzma_allocator *allocator,
216 void (*free_func)(void *node, const lzma_allocator *allocator))
217 {
218 assert(free_func != NULL);
219
220 if (tree->root != NULL)
221 index_tree_node_end(tree->root, allocator, free_func);
222
223 return;
224 }
225
226
227 /// Add a new node to the tree. node->uncompressed_base and
228 /// node->compressed_base must have been set by the caller already.
229 static void
230 index_tree_append(index_tree *tree, index_tree_node *node)
231 {
232 node->parent = tree->rightmost;
233 node->left = NULL;
234 node->right = NULL;
235
236 ++tree->count;
237
238 // Handle the special case of adding the first node.
239 if (tree->root == NULL) {
240 tree->root = node;
241 tree->leftmost = node;
242 tree->rightmost = node;
243 return;
244 }
245
246 // The tree is always filled sequentially.
247 assert(tree->rightmost->uncompressed_base <= node->uncompressed_base);
248 assert(tree->rightmost->compressed_base < node->compressed_base);
249
250 // Add the new node after the rightmost node. It's the correct
251 // place due to the reason above.
252 tree->rightmost->right = node;
253 tree->rightmost = node;
254
255 // Balance the AVL-tree if needed. We don't need to keep the balance
256 // factors in nodes, because we always fill the tree sequentially,
257 // and thus know the state of the tree just by looking at the node
258 // count. From the node count we can calculate how many steps to go
259 // up in the tree to find the rotation root.
260 uint32_t up = tree->count ^ (UINT32_C(1) << bsr32(tree->count));
261 if (up != 0) {
262 // Locate the root node for the rotation.
263 up = ctz32(tree->count) + 2;
264 do {
265 node = node->parent;
266 #ifdef __clang_analyzer__
267 assert(node);
268 #endif
269 } while (--up > 0);
270
271 // Rotate left using node as the rotation root.
272 index_tree_node *pivot = node->right;
273
274 if (node->parent == NULL) {
275 tree->root = pivot;
276 } else {
277 assert(node->parent->right == node);
278 node->parent->right = pivot;
279 }
280
281 pivot->parent = node->parent;
282
283 node->right = pivot->left;
284 if (node->right != NULL)
285 node->right->parent = node;
286
287 pivot->left = node;
288 node->parent = pivot;
289 }
290
291 return;
292 }
293
294
295 /// Get the next node in the tree. Return NULL if there are no more nodes.
296 static void *
297 index_tree_next(const index_tree_node *node)
298 {
299 if (node->right != NULL) {
300 node = node->right;
301 while (node->left != NULL)
302 node = node->left;
303
304 return (void *)(node);
305 }
306
307 while (node->parent != NULL && node->parent->right == node)
308 node = node->parent;
309
310 return (void *)(node->parent);
311 }
312
313
314 /// Locate a node that contains the given uncompressed offset. It is
315 /// caller's job to check that target is not bigger than the uncompressed
316 /// size of the tree (the last node would be returned in that case still).
317 static void *
318 index_tree_locate(const index_tree *tree, lzma_vli target)
319 {
320 const index_tree_node *result = NULL;
321 const index_tree_node *node = tree->root;
322
323 assert(tree->leftmost == NULL
324 || tree->leftmost->uncompressed_base == 0);
325
326 // Consecutive nodes may have the same uncompressed_base.
327 // We must pick the rightmost one.
328 while (node != NULL) {
329 if (node->uncompressed_base > target) {
330 node = node->left;
331 } else {
332 result = node;
333 node = node->right;
334 }
335 }
336
337 return (void *)(result);
338 }
339
340
341 /// Allocate and initialize a new Stream using the given base offsets.
342 static index_stream *
343 index_stream_init(lzma_vli compressed_base, lzma_vli uncompressed_base,
344 uint32_t stream_number, lzma_vli block_number_base,
345 const lzma_allocator *allocator)
346 {
347 index_stream *s = lzma_alloc(sizeof(index_stream), allocator);
348 if (s == NULL)
349 return NULL;
350
351 s->node.uncompressed_base = uncompressed_base;
352 s->node.compressed_base = compressed_base;
353 s->node.parent = NULL;
354 s->node.left = NULL;
355 s->node.right = NULL;
356
357 s->number = stream_number;
358 s->block_number_base = block_number_base;
359
360 index_tree_init(&s->groups);
361
362 s->record_count = 0;
363 s->index_list_size = 0;
364 s->stream_flags.version = UINT32_MAX;
365 s->stream_padding = 0;
366
367 return s;
368 }
369
370
371 /// Free the memory allocated for a Stream and its Record groups.
372 static void
373 index_stream_end(void *node, const lzma_allocator *allocator)
374 {
375 index_stream *s = node;
376 index_tree_end(&s->groups, allocator, &lzma_free);
377 lzma_free(s, allocator);
378 return;
379 }
380
381
382 static lzma_index *
383 index_init_plain(const lzma_allocator *allocator)
384 {
385 lzma_index *i = lzma_alloc(sizeof(lzma_index), allocator);
386 if (i != NULL) {
387 index_tree_init(&i->streams);
388 i->uncompressed_size = 0;
389 i->total_size = 0;
390 i->record_count = 0;
391 i->index_list_size = 0;
392 i->prealloc = INDEX_GROUP_SIZE;
393 i->checks = 0;
394 }
395
396 return i;
397 }
398
399
400 extern LZMA_API(lzma_index *)
401 lzma_index_init(const lzma_allocator *allocator)
402 {
403 lzma_index *i = index_init_plain(allocator);
404 if (i == NULL)
405 return NULL;
406
407 index_stream *s = index_stream_init(0, 0, 1, 0, allocator);
408 if (s == NULL) {
409 lzma_free(i, allocator);
410 return NULL;
411 }
412
413 index_tree_append(&i->streams, &s->node);
414
415 return i;
416 }
417
418
419 extern LZMA_API(void)
420 lzma_index_end(lzma_index *i, const lzma_allocator *allocator)
421 {
422 // NOTE: If you modify this function, check also the bottom
423 // of lzma_index_cat().
424 if (i != NULL) {
425 index_tree_end(&i->streams, allocator, &index_stream_end);
426 lzma_free(i, allocator);
427 }
428
429 return;
430 }
431
432
433 extern void
434 lzma_index_prealloc(lzma_index *i, lzma_vli records)
435 {
436 if (records > PREALLOC_MAX)
437 records = PREALLOC_MAX;
438
439 i->prealloc = (size_t)(records);
440 return;
441 }
442
443
444 extern LZMA_API(uint64_t)
445 lzma_index_memusage(lzma_vli streams, lzma_vli blocks)
446 {
447 // This calculates an upper bound that is only a little bit
448 // bigger than the exact maximum memory usage with the given
449 // parameters.
450
451 // Typical malloc() overhead is 2 * sizeof(void *) but we take
452 // a little bit extra just in case. Using LZMA_MEMUSAGE_BASE
453 // instead would give too inaccurate estimate.
454 const size_t alloc_overhead = 4 * sizeof(void *);
455
456 // Amount of memory needed for each Stream base structures.
457 // We assume that every Stream has at least one Block and
458 // thus at least one group.
459 const size_t stream_base = sizeof(index_stream)
460 + sizeof(index_group) + 2 * alloc_overhead;
461
462 // Amount of memory needed per group.
463 const size_t group_base = sizeof(index_group)
464 + INDEX_GROUP_SIZE * sizeof(index_record)
465 + alloc_overhead;
466
467 // Number of groups. There may actually be more, but that overhead
468 // has been taken into account in stream_base already.
469 const lzma_vli groups
470 = (blocks + INDEX_GROUP_SIZE - 1) / INDEX_GROUP_SIZE;
471
472 // Memory used by index_stream and index_group structures.
473 const uint64_t streams_mem = streams * stream_base;
474 const uint64_t groups_mem = groups * group_base;
475
476 // Memory used by the base structure.
477 const uint64_t index_base = sizeof(lzma_index) + alloc_overhead;
478
479 // Validate the arguments and catch integer overflows.
480 // Maximum number of Streams is "only" UINT32_MAX, because
481 // that limit is used by the tree containing the Streams.
482 const uint64_t limit = UINT64_MAX - index_base;
483 if (streams == 0 || streams > UINT32_MAX || blocks > LZMA_VLI_MAX
484 || streams > limit / stream_base
485 || groups > limit / group_base
486 || limit - streams_mem < groups_mem)
487 return UINT64_MAX;
488
489 return index_base + streams_mem + groups_mem;
490 }
491
492
493 extern LZMA_API(uint64_t)
494 lzma_index_memused(const lzma_index *i)
495 {
496 return lzma_index_memusage(i->streams.count, i->record_count);
497 }
498
499
500 extern LZMA_API(lzma_vli)
501 lzma_index_block_count(const lzma_index *i)
502 {
503 return i->record_count;
504 }
505
506
507 extern LZMA_API(lzma_vli)
508 lzma_index_stream_count(const lzma_index *i)
509 {
510 return i->streams.count;
511 }
512
513
514 extern LZMA_API(lzma_vli)
515 lzma_index_size(const lzma_index *i)
516 {
517 return index_size(i->record_count, i->index_list_size);
518 }
519
520
521 extern LZMA_API(lzma_vli)
522 lzma_index_total_size(const lzma_index *i)
523 {
524 return i->total_size;
525 }
526
527
528 extern LZMA_API(lzma_vli)
529 lzma_index_stream_size(const lzma_index *i)
530 {
531 // Stream Header + Blocks + Index + Stream Footer
532 return LZMA_STREAM_HEADER_SIZE + i->total_size
533 + index_size(i->record_count, i->index_list_size)
534 + LZMA_STREAM_HEADER_SIZE;
535 }
536
537
538 static lzma_vli
539 index_file_size(lzma_vli compressed_base, lzma_vli unpadded_sum,
540 lzma_vli record_count, lzma_vli index_list_size,
541 lzma_vli stream_padding)
542 {
543 // Earlier Streams and Stream Paddings + Stream Header
544 // + Blocks + Index + Stream Footer + Stream Padding
545 //
546 // This might go over LZMA_VLI_MAX due to too big unpadded_sum
547 // when this function is used in lzma_index_append().
548 lzma_vli file_size = compressed_base + 2 * LZMA_STREAM_HEADER_SIZE
549 + stream_padding + vli_ceil4(unpadded_sum);
550 if (file_size > LZMA_VLI_MAX)
551 return LZMA_VLI_UNKNOWN;
552
553 // The same applies here.
554 file_size += index_size(record_count, index_list_size);
555 if (file_size > LZMA_VLI_MAX)
556 return LZMA_VLI_UNKNOWN;
557
558 return file_size;
559 }
560
561
562 extern LZMA_API(lzma_vli)
563 lzma_index_file_size(const lzma_index *i)
564 {
565 const index_stream *s = (const index_stream *)(i->streams.rightmost);
566 const index_group *g = (const index_group *)(s->groups.rightmost);
567 return index_file_size(s->node.compressed_base,
568 g == NULL ? 0 : g->records[g->last].unpadded_sum,
569 s->record_count, s->index_list_size,
570 s->stream_padding);
571 }
572
573
574 extern LZMA_API(lzma_vli)
575 lzma_index_uncompressed_size(const lzma_index *i)
576 {
577 return i->uncompressed_size;
578 }
579
580
581 extern LZMA_API(uint32_t)
582 lzma_index_checks(const lzma_index *i)
583 {
584 uint32_t checks = i->checks;
585
586 // Get the type of the Check of the last Stream too.
587 const index_stream *s = (const index_stream *)(i->streams.rightmost);
588 if (s->stream_flags.version != UINT32_MAX)
589 checks |= UINT32_C(1) << s->stream_flags.check;
590
591 return checks;
592 }
593
594
595 extern uint32_t
596 lzma_index_padding_size(const lzma_index *i)
597 {
598 return (LZMA_VLI_C(4) - index_size_unpadded(
599 i->record_count, i->index_list_size)) & 3;
600 }
601
602
603 extern LZMA_API(lzma_ret)
604 lzma_index_stream_flags(lzma_index *i, const lzma_stream_flags *stream_flags)
605 {
606 if (i == NULL || stream_flags == NULL)
607 return LZMA_PROG_ERROR;
608
609 // Validate the Stream Flags.
610 return_if_error(lzma_stream_flags_compare(
611 stream_flags, stream_flags));
612
613 index_stream *s = (index_stream *)(i->streams.rightmost);
614 s->stream_flags = *stream_flags;
615
616 return LZMA_OK;
617 }
618
619
620 extern LZMA_API(lzma_ret)
621 lzma_index_stream_padding(lzma_index *i, lzma_vli stream_padding)
622 {
623 if (i == NULL || stream_padding > LZMA_VLI_MAX
624 || (stream_padding & 3) != 0)
625 return LZMA_PROG_ERROR;
626
627 index_stream *s = (index_stream *)(i->streams.rightmost);
628
629 // Check that the new value won't make the file grow too big.
630 const lzma_vli old_stream_padding = s->stream_padding;
631 s->stream_padding = 0;
632 if (lzma_index_file_size(i) + stream_padding > LZMA_VLI_MAX) {
633 s->stream_padding = old_stream_padding;
634 return LZMA_DATA_ERROR;
635 }
636
637 s->stream_padding = stream_padding;
638 return LZMA_OK;
639 }
640
641
642 extern LZMA_API(lzma_ret)
643 lzma_index_append(lzma_index *i, const lzma_allocator *allocator,
644 lzma_vli unpadded_size, lzma_vli uncompressed_size)
645 {
646 // Validate.
647 if (i == NULL || unpadded_size < UNPADDED_SIZE_MIN
648 || unpadded_size > UNPADDED_SIZE_MAX
649 || uncompressed_size > LZMA_VLI_MAX)
650 return LZMA_PROG_ERROR;
651
652 index_stream *s = (index_stream *)(i->streams.rightmost);
653 index_group *g = (index_group *)(s->groups.rightmost);
654
655 const lzma_vli compressed_base = g == NULL ? 0
656 : vli_ceil4(g->records[g->last].unpadded_sum);
657 const lzma_vli uncompressed_base = g == NULL ? 0
658 : g->records[g->last].uncompressed_sum;
659 const uint32_t index_list_size_add = lzma_vli_size(unpadded_size)
660 + lzma_vli_size(uncompressed_size);
661
662 // Check that uncompressed size will not overflow.
663 if (uncompressed_base + uncompressed_size > LZMA_VLI_MAX)
664 return LZMA_DATA_ERROR;
665
666 // Check that the new unpadded sum will not overflow. This is
667 // checked again in index_file_size(), but the unpadded sum is
668 // passed to vli_ceil4() which expects a valid lzma_vli value.
669 if (compressed_base + unpadded_size > UNPADDED_SIZE_MAX)
670 return LZMA_DATA_ERROR;
671
672 // Check that the file size will stay within limits.
673 if (index_file_size(s->node.compressed_base,
674 compressed_base + unpadded_size, s->record_count + 1,
675 s->index_list_size + index_list_size_add,
676 s->stream_padding) == LZMA_VLI_UNKNOWN)
677 return LZMA_DATA_ERROR;
678
679 // The size of the Index field must not exceed the maximum value
680 // that can be stored in the Backward Size field.
681 if (index_size(i->record_count + 1,
682 i->index_list_size + index_list_size_add)
683 > LZMA_BACKWARD_SIZE_MAX)
684 return LZMA_DATA_ERROR;
685
686 if (g != NULL && g->last + 1 < g->allocated) {
687 // There is space in the last group at least for one Record.
688 ++g->last;
689 } else {
690 // We need to allocate a new group.
691 g = lzma_alloc(sizeof(index_group)
692 + i->prealloc * sizeof(index_record),
693 allocator);
694 if (g == NULL)
695 return LZMA_MEM_ERROR;
696
697 g->last = 0;
698 g->allocated = i->prealloc;
699
700 // Reset prealloc so that if the application happens to
701 // add new Records, the allocation size will be sane.
702 i->prealloc = INDEX_GROUP_SIZE;
703
704 // Set the start offsets of this group.
705 g->node.uncompressed_base = uncompressed_base;
706 g->node.compressed_base = compressed_base;
707 g->number_base = s->record_count + 1;
708
709 // Add the new group to the Stream.
710 index_tree_append(&s->groups, &g->node);
711 }
712
713 // Add the new Record to the group.
714 g->records[g->last].uncompressed_sum
715 = uncompressed_base + uncompressed_size;
716 g->records[g->last].unpadded_sum
717 = compressed_base + unpadded_size;
718
719 // Update the totals.
720 ++s->record_count;
721 s->index_list_size += index_list_size_add;
722
723 i->total_size += vli_ceil4(unpadded_size);
724 i->uncompressed_size += uncompressed_size;
725 ++i->record_count;
726 i->index_list_size += index_list_size_add;
727
728 return LZMA_OK;
729 }
730
731
732 /// Structure to pass info to index_cat_helper()
733 typedef struct {
734 /// Uncompressed size of the destination
735 lzma_vli uncompressed_size;
736
737 /// Compressed file size of the destination
738 lzma_vli file_size;
739
740 /// Same as above but for Block numbers
741 lzma_vli block_number_add;
742
743 /// Number of Streams that were in the destination index before we
744 /// started appending new Streams from the source index. This is
745 /// used to fix the Stream numbering.
746 uint32_t stream_number_add;
747
748 /// Destination index' Stream tree
749 index_tree *streams;
750
751 } index_cat_info;
752
753
754 /// Add the Stream nodes from the source index to dest using recursion.
755 /// Simplest iterative traversal of the source tree wouldn't work, because
756 /// we update the pointers in nodes when moving them to the destination tree.
757 static void
758 index_cat_helper(const index_cat_info *info, index_stream *this)
759 {
760 index_stream *left = (index_stream *)(this->node.left);
761 index_stream *right = (index_stream *)(this->node.right);
762
763 if (left != NULL)
764 index_cat_helper(info, left);
765
766 this->node.uncompressed_base += info->uncompressed_size;
767 this->node.compressed_base += info->file_size;
768 this->number += info->stream_number_add;
769 this->block_number_base += info->block_number_add;
770 index_tree_append(info->streams, &this->node);
771
772 if (right != NULL)
773 index_cat_helper(info, right);
774
775 return;
776 }
777
778
779 extern LZMA_API(lzma_ret)
780 lzma_index_cat(lzma_index *restrict dest, lzma_index *restrict src,
781 const lzma_allocator *allocator)
782 {
783 if (dest == NULL || src == NULL)
784 return LZMA_PROG_ERROR;
785
786 const lzma_vli dest_file_size = lzma_index_file_size(dest);
787
788 // Check that we don't exceed the file size limits.
789 if (dest_file_size + lzma_index_file_size(src) > LZMA_VLI_MAX
790 || dest->uncompressed_size + src->uncompressed_size
791 > LZMA_VLI_MAX)
792 return LZMA_DATA_ERROR;
793
794 // Check that the encoded size of the combined lzma_indexes stays
795 // within limits. In theory, this should be done only if we know
796 // that the user plans to actually combine the Streams and thus
797 // construct a single Index (probably rare). However, exceeding
798 // this limit is quite theoretical, so we do this check always
799 // to simplify things elsewhere.
800 {
801 const lzma_vli dest_size = index_size_unpadded(
802 dest->record_count, dest->index_list_size);
803 const lzma_vli src_size = index_size_unpadded(
804 src->record_count, src->index_list_size);
805 if (vli_ceil4(dest_size + src_size) > LZMA_BACKWARD_SIZE_MAX)
806 return LZMA_DATA_ERROR;
807 }
808
809 // Optimize the last group to minimize memory usage. Allocation has
810 // to be done before modifying dest or src.
811 {
812 index_stream *s = (index_stream *)(dest->streams.rightmost);
813 index_group *g = (index_group *)(s->groups.rightmost);
814 if (g != NULL && g->last + 1 < g->allocated) {
815 assert(g->node.left == NULL);
816 assert(g->node.right == NULL);
817
818 index_group *newg = lzma_alloc(sizeof(index_group)
819 + (g->last + 1)
820 * sizeof(index_record),
821 allocator);
822 if (newg == NULL)
823 return LZMA_MEM_ERROR;
824
825 newg->node = g->node;
826 newg->allocated = g->last + 1;
827 newg->last = g->last;
828 newg->number_base = g->number_base;
829
830 memcpy(newg->records, g->records, newg->allocated
831 * sizeof(index_record));
832
833 if (g->node.parent != NULL) {
834 assert(g->node.parent->right == &g->node);
835 g->node.parent->right = &newg->node;
836 }
837
838 if (s->groups.leftmost == &g->node) {
839 assert(s->groups.root == &g->node);
840 s->groups.leftmost = &newg->node;
841 s->groups.root = &newg->node;
842 }
843
844 assert(s->groups.rightmost == &g->node);
845 s->groups.rightmost = &newg->node;
846
847 lzma_free(g, allocator);
848
849 // NOTE: newg isn't leaked here because
850 // newg == (void *)&newg->node.
851 }
852 }
853
854 // dest->checks includes the check types of all except the last Stream
855 // in dest. Set the bit for the check type of the last Stream now so
856 // that it won't get lost when Stream(s) from src are appended to dest.
857 dest->checks = lzma_index_checks(dest);
858
859 // Add all the Streams from src to dest. Update the base offsets
860 // of each Stream from src.
861 const index_cat_info info = {
862 .uncompressed_size = dest->uncompressed_size,
863 .file_size = dest_file_size,
864 .stream_number_add = dest->streams.count,
865 .block_number_add = dest->record_count,
866 .streams = &dest->streams,
867 };
868 index_cat_helper(&info, (index_stream *)(src->streams.root));
869
870 // Update info about all the combined Streams.
871 dest->uncompressed_size += src->uncompressed_size;
872 dest->total_size += src->total_size;
873 dest->record_count += src->record_count;
874 dest->index_list_size += src->index_list_size;
875 dest->checks |= src->checks;
876
877 // There's nothing else left in src than the base structure.
878 lzma_free(src, allocator);
879
880 return LZMA_OK;
881 }
882
883
884 /// Duplicate an index_stream.
885 static index_stream *
886 index_dup_stream(const index_stream *src, const lzma_allocator *allocator)
887 {
888 // Catch a somewhat theoretical integer overflow.
889 if (src->record_count > PREALLOC_MAX)
890 return NULL;
891
892 // Allocate and initialize a new Stream.
893 index_stream *dest = index_stream_init(src->node.compressed_base,
894 src->node.uncompressed_base, src->number,
895 src->block_number_base, allocator);
896 if (dest == NULL)
897 return NULL;
898
899 // Copy the overall information.
900 dest->record_count = src->record_count;
901 dest->index_list_size = src->index_list_size;
902 dest->stream_flags = src->stream_flags;
903 dest->stream_padding = src->stream_padding;
904
905 // Return if there are no groups to duplicate.
906 if (src->groups.leftmost == NULL)
907 return dest;
908
909 // Allocate memory for the Records. We put all the Records into
910 // a single group. It's simplest and also tends to make
911 // lzma_index_locate() a little bit faster with very big Indexes.
912 index_group *destg = lzma_alloc(sizeof(index_group)
913 + src->record_count * sizeof(index_record),
914 allocator);
915 if (destg == NULL) {
916 index_stream_end(dest, allocator);
917 return NULL;
918 }
919
920 // Initialize destg.
921 destg->node.uncompressed_base = 0;
922 destg->node.compressed_base = 0;
923 destg->number_base = 1;
924 destg->allocated = src->record_count;
925 destg->last = src->record_count - 1;
926
927 // Go through all the groups in src and copy the Records into destg.
928 const index_group *srcg = (const index_group *)(src->groups.leftmost);
929 size_t i = 0;
930 do {
931 memcpy(destg->records + i, srcg->records,
932 (srcg->last + 1) * sizeof(index_record));
933 i += srcg->last + 1;
934 srcg = index_tree_next(&srcg->node);
935 } while (srcg != NULL);
936
937 assert(i == destg->allocated);
938
939 // Add the group to the new Stream.
940 index_tree_append(&dest->groups, &destg->node);
941
942 return dest;
943 }
944
945
946 extern LZMA_API(lzma_index *)
947 lzma_index_dup(const lzma_index *src, const lzma_allocator *allocator)
948 {
949 // Allocate the base structure (no initial Stream).
950 lzma_index *dest = index_init_plain(allocator);
951 if (dest == NULL)
952 return NULL;
953
954 // Copy the totals.
955 dest->uncompressed_size = src->uncompressed_size;
956 dest->total_size = src->total_size;
957 dest->record_count = src->record_count;
958 dest->index_list_size = src->index_list_size;
959
960 // Copy the Streams and the groups in them.
961 const index_stream *srcstream
962 = (const index_stream *)(src->streams.leftmost);
963 do {
964 index_stream *deststream = index_dup_stream(
965 srcstream, allocator);
966 if (deststream == NULL) {
967 lzma_index_end(dest, allocator);
968 return NULL;
969 }
970
971 index_tree_append(&dest->streams, &deststream->node);
972
973 srcstream = index_tree_next(&srcstream->node);
974 } while (srcstream != NULL);
975
976 return dest;
977 }
978
979
980 /// Indexing for lzma_index_iter.internal[]
981 enum {
982 ITER_INDEX,
983 ITER_STREAM,
984 ITER_GROUP,
985 ITER_RECORD,
986 ITER_METHOD,
987 };
988
989
990 /// Values for lzma_index_iter.internal[ITER_METHOD].s
991 enum {
992 ITER_METHOD_NORMAL,
993 ITER_METHOD_NEXT,
994 ITER_METHOD_LEFTMOST,
995 };
996
997
998 static void
999 iter_set_info(lzma_index_iter *iter)
1000 {
1001 const lzma_index *i = iter->internal[ITER_INDEX].p;
1002 const index_stream *stream = iter->internal[ITER_STREAM].p;
1003 const index_group *group = iter->internal[ITER_GROUP].p;
1004 const size_t record = iter->internal[ITER_RECORD].s;
1005
1006 // lzma_index_iter.internal must not contain a pointer to the last
1007 // group in the index, because that may be reallocated by
1008 // lzma_index_cat().
1009 if (group == NULL) {
1010 // There are no groups.
1011 assert(stream->groups.root == NULL);
1012 iter->internal[ITER_METHOD].s = ITER_METHOD_LEFTMOST;
1013
1014 } else if (i->streams.rightmost != &stream->node
1015 || stream->groups.rightmost != &group->node) {
1016 // The group is not not the last group in the index.
1017 iter->internal[ITER_METHOD].s = ITER_METHOD_NORMAL;
1018
1019 } else if (stream->groups.leftmost != &group->node) {
1020 // The group isn't the only group in the Stream, thus we
1021 // know that it must have a parent group i.e. it's not
1022 // the root node.
1023 assert(stream->groups.root != &group->node);
1024 assert(group->node.parent->right == &group->node);
1025 iter->internal[ITER_METHOD].s = ITER_METHOD_NEXT;
1026 iter->internal[ITER_GROUP].p = group->node.parent;
1027
1028 } else {
1029 // The Stream has only one group.
1030 assert(stream->groups.root == &group->node);
1031 assert(group->node.parent == NULL);
1032 iter->internal[ITER_METHOD].s = ITER_METHOD_LEFTMOST;
1033 iter->internal[ITER_GROUP].p = NULL;
1034 }
1035
1036 // NOTE: lzma_index_iter.stream.number is lzma_vli but we use uint32_t
1037 // internally.
1038 iter->stream.number = stream->number;
1039 iter->stream.block_count = stream->record_count;
1040 iter->stream.compressed_offset = stream->node.compressed_base;
1041 iter->stream.uncompressed_offset = stream->node.uncompressed_base;
1042
1043 // iter->stream.flags will be NULL if the Stream Flags haven't been
1044 // set with lzma_index_stream_flags().
1045 iter->stream.flags = stream->stream_flags.version == UINT32_MAX
1046 ? NULL : &stream->stream_flags;
1047 iter->stream.padding = stream->stream_padding;
1048
1049 if (stream->groups.rightmost == NULL) {
1050 // Stream has no Blocks.
1051 iter->stream.compressed_size = index_size(0, 0)
1052 + 2 * LZMA_STREAM_HEADER_SIZE;
1053 iter->stream.uncompressed_size = 0;
1054 } else {
1055 const index_group *g = (const index_group *)(
1056 stream->groups.rightmost);
1057
1058 // Stream Header + Stream Footer + Index + Blocks
1059 iter->stream.compressed_size = 2 * LZMA_STREAM_HEADER_SIZE
1060 + index_size(stream->record_count,
1061 stream->index_list_size)
1062 + vli_ceil4(g->records[g->last].unpadded_sum);
1063 iter->stream.uncompressed_size
1064 = g->records[g->last].uncompressed_sum;
1065 }
1066
1067 if (group != NULL) {
1068 iter->block.number_in_stream = group->number_base + record;
1069 iter->block.number_in_file = iter->block.number_in_stream
1070 + stream->block_number_base;
1071
1072 iter->block.compressed_stream_offset
1073 = record == 0 ? group->node.compressed_base
1074 : vli_ceil4(group->records[
1075 record - 1].unpadded_sum);
1076 iter->block.uncompressed_stream_offset
1077 = record == 0 ? group->node.uncompressed_base
1078 : group->records[record - 1].uncompressed_sum;
1079
1080 iter->block.uncompressed_size
1081 = group->records[record].uncompressed_sum
1082 - iter->block.uncompressed_stream_offset;
1083 iter->block.unpadded_size
1084 = group->records[record].unpadded_sum
1085 - iter->block.compressed_stream_offset;
1086 iter->block.total_size = vli_ceil4(iter->block.unpadded_size);
1087
1088 iter->block.compressed_stream_offset
1089 += LZMA_STREAM_HEADER_SIZE;
1090
1091 iter->block.compressed_file_offset
1092 = iter->block.compressed_stream_offset
1093 + iter->stream.compressed_offset;
1094 iter->block.uncompressed_file_offset
1095 = iter->block.uncompressed_stream_offset
1096 + iter->stream.uncompressed_offset;
1097 }
1098
1099 return;
1100 }
1101
1102
1103 extern LZMA_API(void)
1104 lzma_index_iter_init(lzma_index_iter *iter, const lzma_index *i)
1105 {
1106 iter->internal[ITER_INDEX].p = i;
1107 lzma_index_iter_rewind(iter);
1108 return;
1109 }
1110
1111
1112 extern LZMA_API(void)
1113 lzma_index_iter_rewind(lzma_index_iter *iter)
1114 {
1115 iter->internal[ITER_STREAM].p = NULL;
1116 iter->internal[ITER_GROUP].p = NULL;
1117 iter->internal[ITER_RECORD].s = 0;
1118 iter->internal[ITER_METHOD].s = ITER_METHOD_NORMAL;
1119 return;
1120 }
1121
1122
1123 extern LZMA_API(lzma_bool)
1124 lzma_index_iter_next(lzma_index_iter *iter, lzma_index_iter_mode mode)
1125 {
1126 // Catch unsupported mode values.
1127 if ((unsigned int)(mode) > LZMA_INDEX_ITER_NONEMPTY_BLOCK)
1128 return true;
1129
1130 const lzma_index *i = iter->internal[ITER_INDEX].p;
1131 const index_stream *stream = iter->internal[ITER_STREAM].p;
1132 const index_group *group = NULL;
1133 size_t record = iter->internal[ITER_RECORD].s;
1134
1135 // If we are being asked for the next Stream, leave group to NULL
1136 // so that the rest of the this function thinks that this Stream
1137 // has no groups and will thus go to the next Stream.
1138 if (mode != LZMA_INDEX_ITER_STREAM) {
1139 // Get the pointer to the current group. See iter_set_inf()
1140 // for explanation.
1141 switch (iter->internal[ITER_METHOD].s) {
1142 case ITER_METHOD_NORMAL:
1143 group = iter->internal[ITER_GROUP].p;
1144 break;
1145
1146 case ITER_METHOD_NEXT:
1147 group = index_tree_next(iter->internal[ITER_GROUP].p);
1148 break;
1149
1150 case ITER_METHOD_LEFTMOST:
1151 group = (const index_group *)(
1152 stream->groups.leftmost);
1153 break;
1154 }
1155 }
1156
1157 again:
1158 if (stream == NULL) {
1159 // We at the beginning of the lzma_index.
1160 // Locate the first Stream.
1161 stream = (const index_stream *)(i->streams.leftmost);
1162 if (mode >= LZMA_INDEX_ITER_BLOCK) {
1163 // Since we are being asked to return information
1164 // about the first a Block, skip Streams that have
1165 // no Blocks.
1166 while (stream->groups.leftmost == NULL) {
1167 stream = index_tree_next(&stream->node);
1168 if (stream == NULL)
1169 return true;
1170 }
1171 }
1172
1173 // Start from the first Record in the Stream.
1174 group = (const index_group *)(stream->groups.leftmost);
1175 record = 0;
1176
1177 } else if (group != NULL && record < group->last) {
1178 // The next Record is in the same group.
1179 ++record;
1180
1181 } else {
1182 // This group has no more Records or this Stream has
1183 // no Blocks at all.
1184 record = 0;
1185
1186 // If group is not NULL, this Stream has at least one Block
1187 // and thus at least one group. Find the next group.
1188 if (group != NULL)
1189 group = index_tree_next(&group->node);
1190
1191 if (group == NULL) {
1192 // This Stream has no more Records. Find the next
1193 // Stream. If we are being asked to return information
1194 // about a Block, we skip empty Streams.
1195 do {
1196 stream = index_tree_next(&stream->node);
1197 if (stream == NULL)
1198 return true;
1199 } while (mode >= LZMA_INDEX_ITER_BLOCK
1200 && stream->groups.leftmost == NULL);
1201
1202 group = (const index_group *)(
1203 stream->groups.leftmost);
1204 }
1205 }
1206
1207 if (mode == LZMA_INDEX_ITER_NONEMPTY_BLOCK) {
1208 // We need to look for the next Block again if this Block
1209 // is empty.
1210 if (record == 0) {
1211 if (group->node.uncompressed_base
1212 == group->records[0].uncompressed_sum)
1213 goto again;
1214 } else if (group->records[record - 1].uncompressed_sum
1215 == group->records[record].uncompressed_sum) {
1216 goto again;
1217 }
1218 }
1219
1220 iter->internal[ITER_STREAM].p = stream;
1221 iter->internal[ITER_GROUP].p = group;
1222 iter->internal[ITER_RECORD].s = record;
1223
1224 iter_set_info(iter);
1225
1226 return false;
1227 }
1228
1229
1230 extern LZMA_API(lzma_bool)
1231 lzma_index_iter_locate(lzma_index_iter *iter, lzma_vli target)
1232 {
1233 const lzma_index *i = iter->internal[ITER_INDEX].p;
1234
1235 // If the target is past the end of the file, return immediately.
1236 if (i->uncompressed_size <= target)
1237 return true;
1238
1239 // Locate the Stream containing the target offset.
1240 const index_stream *stream = index_tree_locate(&i->streams, target);
1241 assert(stream != NULL);
1242 target -= stream->node.uncompressed_base;
1243
1244 // Locate the group containing the target offset.
1245 const index_group *group = index_tree_locate(&stream->groups, target);
1246 assert(group != NULL);
1247
1248 // Use binary search to locate the exact Record. It is the first
1249 // Record whose uncompressed_sum is greater than target.
1250 // This is because we want the rightmost Record that fulfills the
1251 // search criterion. It is possible that there are empty Blocks;
1252 // we don't want to return them.
1253 size_t left = 0;
1254 size_t right = group->last;
1255
1256 while (left < right) {
1257 const size_t pos = left + (right - left) / 2;
1258 if (group->records[pos].uncompressed_sum <= target)
1259 left = pos + 1;
1260 else
1261 right = pos;
1262 }
1263
1264 iter->internal[ITER_STREAM].p = stream;
1265 iter->internal[ITER_GROUP].p = group;
1266 iter->internal[ITER_RECORD].s = left;
1267
1268 iter_set_info(iter);
1269
1270 return false;
1271 }