xref: /freebsd/contrib/xz/src/liblzma/common/index.c (revision f81c1f4339cd20ea89dad51c0f7d96e0e34313a9)
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
index_tree_init(index_tree * tree)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
index_tree_node_end(index_tree_node * node,const lzma_allocator * allocator,void (* free_func)(void * node,const lzma_allocator * allocator))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
index_tree_end(index_tree * tree,const lzma_allocator * allocator,void (* free_func)(void * node,const lzma_allocator * allocator))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
index_tree_append(index_tree * tree,index_tree_node * node)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 		} while (--up > 0);
267 
268 		// Rotate left using node as the rotation root.
269 		index_tree_node *pivot = node->right;
270 
271 		if (node->parent == NULL) {
272 			tree->root = pivot;
273 		} else {
274 			assert(node->parent->right == node);
275 			node->parent->right = pivot;
276 		}
277 
278 		pivot->parent = node->parent;
279 
280 		node->right = pivot->left;
281 		if (node->right != NULL)
282 			node->right->parent = node;
283 
284 		pivot->left = node;
285 		node->parent = pivot;
286 	}
287 
288 	return;
289 }
290 
291 
292 /// Get the next node in the tree. Return NULL if there are no more nodes.
293 static void *
index_tree_next(const index_tree_node * node)294 index_tree_next(const index_tree_node *node)
295 {
296 	if (node->right != NULL) {
297 		node = node->right;
298 		while (node->left != NULL)
299 			node = node->left;
300 
301 		return (void *)(node);
302 	}
303 
304 	while (node->parent != NULL && node->parent->right == node)
305 		node = node->parent;
306 
307 	return (void *)(node->parent);
308 }
309 
310 
311 /// Locate a node that contains the given uncompressed offset. It is
312 /// caller's job to check that target is not bigger than the uncompressed
313 /// size of the tree (the last node would be returned in that case still).
314 static void *
index_tree_locate(const index_tree * tree,lzma_vli target)315 index_tree_locate(const index_tree *tree, lzma_vli target)
316 {
317 	const index_tree_node *result = NULL;
318 	const index_tree_node *node = tree->root;
319 
320 	assert(tree->leftmost == NULL
321 			|| tree->leftmost->uncompressed_base == 0);
322 
323 	// Consecutive nodes may have the same uncompressed_base.
324 	// We must pick the rightmost one.
325 	while (node != NULL) {
326 		if (node->uncompressed_base > target) {
327 			node = node->left;
328 		} else {
329 			result = node;
330 			node = node->right;
331 		}
332 	}
333 
334 	return (void *)(result);
335 }
336 
337 
338 /// Allocate and initialize a new Stream using the given base offsets.
339 static index_stream *
index_stream_init(lzma_vli compressed_base,lzma_vli uncompressed_base,uint32_t stream_number,lzma_vli block_number_base,const lzma_allocator * allocator)340 index_stream_init(lzma_vli compressed_base, lzma_vli uncompressed_base,
341 		uint32_t stream_number, lzma_vli block_number_base,
342 		const lzma_allocator *allocator)
343 {
344 	index_stream *s = lzma_alloc(sizeof(index_stream), allocator);
345 	if (s == NULL)
346 		return NULL;
347 
348 	s->node.uncompressed_base = uncompressed_base;
349 	s->node.compressed_base = compressed_base;
350 	s->node.parent = NULL;
351 	s->node.left = NULL;
352 	s->node.right = NULL;
353 
354 	s->number = stream_number;
355 	s->block_number_base = block_number_base;
356 
357 	index_tree_init(&s->groups);
358 
359 	s->record_count = 0;
360 	s->index_list_size = 0;
361 	s->stream_flags.version = UINT32_MAX;
362 	s->stream_padding = 0;
363 
364 	return s;
365 }
366 
367 
368 /// Free the memory allocated for a Stream and its Record groups.
369 static void
index_stream_end(void * node,const lzma_allocator * allocator)370 index_stream_end(void *node, const lzma_allocator *allocator)
371 {
372 	index_stream *s = node;
373 	index_tree_end(&s->groups, allocator, &lzma_free);
374 	lzma_free(s, allocator);
375 	return;
376 }
377 
378 
379 static lzma_index *
index_init_plain(const lzma_allocator * allocator)380 index_init_plain(const lzma_allocator *allocator)
381 {
382 	lzma_index *i = lzma_alloc(sizeof(lzma_index), allocator);
383 	if (i != NULL) {
384 		index_tree_init(&i->streams);
385 		i->uncompressed_size = 0;
386 		i->total_size = 0;
387 		i->record_count = 0;
388 		i->index_list_size = 0;
389 		i->prealloc = INDEX_GROUP_SIZE;
390 		i->checks = 0;
391 	}
392 
393 	return i;
394 }
395 
396 
397 extern LZMA_API(lzma_index *)
lzma_index_init(const lzma_allocator * allocator)398 lzma_index_init(const lzma_allocator *allocator)
399 {
400 	lzma_index *i = index_init_plain(allocator);
401 	if (i == NULL)
402 		return NULL;
403 
404 	index_stream *s = index_stream_init(0, 0, 1, 0, allocator);
405 	if (s == NULL) {
406 		lzma_free(i, allocator);
407 		return NULL;
408 	}
409 
410 	index_tree_append(&i->streams, &s->node);
411 
412 	return i;
413 }
414 
415 
416 extern LZMA_API(void)
lzma_index_end(lzma_index * i,const lzma_allocator * allocator)417 lzma_index_end(lzma_index *i, const lzma_allocator *allocator)
418 {
419 	// NOTE: If you modify this function, check also the bottom
420 	// of lzma_index_cat().
421 	if (i != NULL) {
422 		index_tree_end(&i->streams, allocator, &index_stream_end);
423 		lzma_free(i, allocator);
424 	}
425 
426 	return;
427 }
428 
429 
430 extern void
lzma_index_prealloc(lzma_index * i,lzma_vli records)431 lzma_index_prealloc(lzma_index *i, lzma_vli records)
432 {
433 	if (records > PREALLOC_MAX)
434 		records = PREALLOC_MAX;
435 
436 	// If index_decoder.c calls us with records == 0, it's decoding
437 	// an Index that has no Records. In that case the decoder won't call
438 	// lzma_index_append() at all, and i->prealloc isn't used during
439 	// the Index decoding either.
440 	//
441 	// Normally the first lzma_index_append() call from the Index decoder
442 	// would reset i->prealloc to INDEX_GROUP_SIZE. With no Records,
443 	// lzma_index_append() isn't called and the resetting of prealloc
444 	// won't occur either. Thus, if records == 0, use the default value
445 	// INDEX_GROUP_SIZE instead.
446 	//
447 	// NOTE: lzma_index_append() assumes i->prealloc > 0. liblzma <= 5.8.2
448 	// didn't have this check and could set i->prealloc = 0, which would
449 	// result in a buffer overflow if the application called
450 	// lzma_index_append() after decoding an empty Index. Appending
451 	// Records after decoding an Index is a rare thing to do, but
452 	// it is supposed to work.
453 	if (records == 0)
454 		records = INDEX_GROUP_SIZE;
455 
456 	i->prealloc = (size_t)(records);
457 	return;
458 }
459 
460 
461 extern LZMA_API(uint64_t)
lzma_index_memusage(lzma_vli streams,lzma_vli blocks)462 lzma_index_memusage(lzma_vli streams, lzma_vli blocks)
463 {
464 	// This calculates an upper bound that is only a little bit
465 	// bigger than the exact maximum memory usage with the given
466 	// parameters.
467 
468 	// Typical malloc() overhead is 2 * sizeof(void *) but we take
469 	// a little bit extra just in case. Using LZMA_MEMUSAGE_BASE
470 	// instead would give too inaccurate estimate.
471 	const size_t alloc_overhead = 4 * sizeof(void *);
472 
473 	// Amount of memory needed for each Stream base structures.
474 	// We assume that every Stream has at least one Block and
475 	// thus at least one group.
476 	const size_t stream_base = sizeof(index_stream)
477 			+ sizeof(index_group) + 2 * alloc_overhead;
478 
479 	// Amount of memory needed per group.
480 	const size_t group_base = sizeof(index_group)
481 			+ INDEX_GROUP_SIZE * sizeof(index_record)
482 			+ alloc_overhead;
483 
484 	// Number of groups. There may actually be more, but that overhead
485 	// has been taken into account in stream_base already.
486 	const lzma_vli groups
487 			= (blocks + INDEX_GROUP_SIZE - 1) / INDEX_GROUP_SIZE;
488 
489 	// Memory used by index_stream and index_group structures.
490 	const uint64_t streams_mem = streams * stream_base;
491 	const uint64_t groups_mem = groups * group_base;
492 
493 	// Memory used by the base structure.
494 	const uint64_t index_base = sizeof(lzma_index) + alloc_overhead;
495 
496 	// Validate the arguments and catch integer overflows.
497 	// Maximum number of Streams is "only" UINT32_MAX, because
498 	// that limit is used by the tree containing the Streams.
499 	const uint64_t limit = UINT64_MAX - index_base;
500 	if (streams == 0 || streams > UINT32_MAX || blocks > LZMA_VLI_MAX
501 			|| streams > limit / stream_base
502 			|| groups > limit / group_base
503 			|| limit - streams_mem < groups_mem)
504 		return UINT64_MAX;
505 
506 	return index_base + streams_mem + groups_mem;
507 }
508 
509 
510 extern LZMA_API(uint64_t)
lzma_index_memused(const lzma_index * i)511 lzma_index_memused(const lzma_index *i)
512 {
513 	return lzma_index_memusage(i->streams.count, i->record_count);
514 }
515 
516 
517 extern LZMA_API(lzma_vli)
lzma_index_block_count(const lzma_index * i)518 lzma_index_block_count(const lzma_index *i)
519 {
520 	return i->record_count;
521 }
522 
523 
524 extern LZMA_API(lzma_vli)
lzma_index_stream_count(const lzma_index * i)525 lzma_index_stream_count(const lzma_index *i)
526 {
527 	return i->streams.count;
528 }
529 
530 
531 extern LZMA_API(lzma_vli)
lzma_index_size(const lzma_index * i)532 lzma_index_size(const lzma_index *i)
533 {
534 	return index_size(i->record_count, i->index_list_size);
535 }
536 
537 
538 extern LZMA_API(lzma_vli)
lzma_index_total_size(const lzma_index * i)539 lzma_index_total_size(const lzma_index *i)
540 {
541 	return i->total_size;
542 }
543 
544 
545 extern LZMA_API(lzma_vli)
lzma_index_stream_size(const lzma_index * i)546 lzma_index_stream_size(const lzma_index *i)
547 {
548 	// Stream Header + Blocks + Index + Stream Footer
549 	return LZMA_STREAM_HEADER_SIZE + i->total_size
550 			+ index_size(i->record_count, i->index_list_size)
551 			+ LZMA_STREAM_HEADER_SIZE;
552 }
553 
554 
555 static lzma_vli
index_file_size(lzma_vli compressed_base,lzma_vli unpadded_sum,lzma_vli record_count,lzma_vli index_list_size,lzma_vli stream_padding)556 index_file_size(lzma_vli compressed_base, lzma_vli unpadded_sum,
557 		lzma_vli record_count, lzma_vli index_list_size,
558 		lzma_vli stream_padding)
559 {
560 	// Earlier Streams and Stream Paddings + Stream Header
561 	// + Blocks + Index + Stream Footer + Stream Padding
562 	//
563 	// This might go over LZMA_VLI_MAX due to too big unpadded_sum
564 	// when this function is used in lzma_index_append().
565 	lzma_vli file_size = compressed_base + 2 * LZMA_STREAM_HEADER_SIZE
566 			+ stream_padding + vli_ceil4(unpadded_sum);
567 	if (file_size > LZMA_VLI_MAX)
568 		return LZMA_VLI_UNKNOWN;
569 
570 	// The same applies here.
571 	file_size += index_size(record_count, index_list_size);
572 	if (file_size > LZMA_VLI_MAX)
573 		return LZMA_VLI_UNKNOWN;
574 
575 	return file_size;
576 }
577 
578 
579 extern LZMA_API(lzma_vli)
lzma_index_file_size(const lzma_index * i)580 lzma_index_file_size(const lzma_index *i)
581 {
582 	const index_stream *s = (const index_stream *)(i->streams.rightmost);
583 	const index_group *g = (const index_group *)(s->groups.rightmost);
584 	return index_file_size(s->node.compressed_base,
585 			g == NULL ? 0 : g->records[g->last].unpadded_sum,
586 			s->record_count, s->index_list_size,
587 			s->stream_padding);
588 }
589 
590 
591 extern LZMA_API(lzma_vli)
lzma_index_uncompressed_size(const lzma_index * i)592 lzma_index_uncompressed_size(const lzma_index *i)
593 {
594 	return i->uncompressed_size;
595 }
596 
597 
598 extern LZMA_API(uint32_t)
lzma_index_checks(const lzma_index * i)599 lzma_index_checks(const lzma_index *i)
600 {
601 	uint32_t checks = i->checks;
602 
603 	// Get the type of the Check of the last Stream too.
604 	const index_stream *s = (const index_stream *)(i->streams.rightmost);
605 	if (s->stream_flags.version != UINT32_MAX)
606 		checks |= UINT32_C(1) << s->stream_flags.check;
607 
608 	return checks;
609 }
610 
611 
612 extern uint32_t
lzma_index_padding_size(const lzma_index * i)613 lzma_index_padding_size(const lzma_index *i)
614 {
615 	return (LZMA_VLI_C(4) - index_size_unpadded(
616 			i->record_count, i->index_list_size)) & 3;
617 }
618 
619 
620 extern LZMA_API(lzma_ret)
lzma_index_stream_flags(lzma_index * i,const lzma_stream_flags * stream_flags)621 lzma_index_stream_flags(lzma_index *i, const lzma_stream_flags *stream_flags)
622 {
623 	if (i == NULL || stream_flags == NULL)
624 		return LZMA_PROG_ERROR;
625 
626 	// Validate the Stream Flags.
627 	return_if_error(lzma_stream_flags_compare(
628 			stream_flags, stream_flags));
629 
630 	index_stream *s = (index_stream *)(i->streams.rightmost);
631 	s->stream_flags = *stream_flags;
632 
633 	return LZMA_OK;
634 }
635 
636 
637 extern LZMA_API(lzma_ret)
lzma_index_stream_padding(lzma_index * i,lzma_vli stream_padding)638 lzma_index_stream_padding(lzma_index *i, lzma_vli stream_padding)
639 {
640 	if (i == NULL || stream_padding > LZMA_VLI_MAX
641 			|| (stream_padding & 3) != 0)
642 		return LZMA_PROG_ERROR;
643 
644 	index_stream *s = (index_stream *)(i->streams.rightmost);
645 
646 	// Check that the new value won't make the file grow too big.
647 	const lzma_vli old_stream_padding = s->stream_padding;
648 	s->stream_padding = 0;
649 	if (lzma_index_file_size(i) + stream_padding > LZMA_VLI_MAX) {
650 		s->stream_padding = old_stream_padding;
651 		return LZMA_DATA_ERROR;
652 	}
653 
654 	s->stream_padding = stream_padding;
655 	return LZMA_OK;
656 }
657 
658 
659 extern LZMA_API(lzma_ret)
lzma_index_append(lzma_index * i,const lzma_allocator * allocator,lzma_vli unpadded_size,lzma_vli uncompressed_size)660 lzma_index_append(lzma_index *i, const lzma_allocator *allocator,
661 		lzma_vli unpadded_size, lzma_vli uncompressed_size)
662 {
663 	// Validate.
664 	if (i == NULL || unpadded_size < UNPADDED_SIZE_MIN
665 			|| unpadded_size > UNPADDED_SIZE_MAX
666 			|| uncompressed_size > LZMA_VLI_MAX)
667 		return LZMA_PROG_ERROR;
668 
669 	index_stream *s = (index_stream *)(i->streams.rightmost);
670 	index_group *g = (index_group *)(s->groups.rightmost);
671 
672 	const lzma_vli compressed_base = g == NULL ? 0
673 			: vli_ceil4(g->records[g->last].unpadded_sum);
674 	const lzma_vli uncompressed_base = g == NULL ? 0
675 			: g->records[g->last].uncompressed_sum;
676 	const uint32_t index_list_size_add = lzma_vli_size(unpadded_size)
677 			+ lzma_vli_size(uncompressed_size);
678 
679 	// Check that uncompressed size will not overflow.
680 	if (uncompressed_base + uncompressed_size > LZMA_VLI_MAX)
681 		return LZMA_DATA_ERROR;
682 
683 	// Check that the new unpadded sum will not overflow. This is
684 	// checked again in index_file_size(), but the unpadded sum is
685 	// passed to vli_ceil4() which expects a valid lzma_vli value.
686 	if (compressed_base + unpadded_size > UNPADDED_SIZE_MAX)
687 		return LZMA_DATA_ERROR;
688 
689 	// Check that the file size will stay within limits.
690 	if (index_file_size(s->node.compressed_base,
691 			compressed_base + unpadded_size, s->record_count + 1,
692 			s->index_list_size + index_list_size_add,
693 			s->stream_padding) == LZMA_VLI_UNKNOWN)
694 		return LZMA_DATA_ERROR;
695 
696 	// The size of the Index field must not exceed the maximum value
697 	// that can be stored in the Backward Size field.
698 	if (index_size(i->record_count + 1,
699 			i->index_list_size + index_list_size_add)
700 			> LZMA_BACKWARD_SIZE_MAX)
701 		return LZMA_DATA_ERROR;
702 
703 	if (g != NULL && g->last + 1 < g->allocated) {
704 		// There is space in the last group at least for one Record.
705 		++g->last;
706 	} else {
707 		// We need to allocate a new group.
708 		assert(i->prealloc > 0);
709 		g = lzma_alloc(sizeof(index_group)
710 				+ i->prealloc * sizeof(index_record),
711 				allocator);
712 		if (g == NULL)
713 			return LZMA_MEM_ERROR;
714 
715 		g->last = 0;
716 		g->allocated = i->prealloc;
717 
718 		// Reset prealloc so that if the application happens to
719 		// add new Records, the allocation size will be sane.
720 		i->prealloc = INDEX_GROUP_SIZE;
721 
722 		// Set the start offsets of this group.
723 		g->node.uncompressed_base = uncompressed_base;
724 		g->node.compressed_base = compressed_base;
725 		g->number_base = s->record_count + 1;
726 
727 		// Add the new group to the Stream.
728 		index_tree_append(&s->groups, &g->node);
729 	}
730 
731 	// Add the new Record to the group.
732 	g->records[g->last].uncompressed_sum
733 			= uncompressed_base + uncompressed_size;
734 	g->records[g->last].unpadded_sum
735 			= compressed_base + unpadded_size;
736 
737 	// Update the totals.
738 	++s->record_count;
739 	s->index_list_size += index_list_size_add;
740 
741 	i->total_size += vli_ceil4(unpadded_size);
742 	i->uncompressed_size += uncompressed_size;
743 	++i->record_count;
744 	i->index_list_size += index_list_size_add;
745 
746 	return LZMA_OK;
747 }
748 
749 
750 /// Structure to pass info to index_cat_helper()
751 typedef struct {
752 	/// Uncompressed size of the destination
753 	lzma_vli uncompressed_size;
754 
755 	/// Compressed file size of the destination
756 	lzma_vli file_size;
757 
758 	/// Same as above but for Block numbers
759 	lzma_vli block_number_add;
760 
761 	/// Number of Streams that were in the destination index before we
762 	/// started appending new Streams from the source index. This is
763 	/// used to fix the Stream numbering.
764 	uint32_t stream_number_add;
765 
766 	/// Destination index' Stream tree
767 	index_tree *streams;
768 
769 } index_cat_info;
770 
771 
772 /// Add the Stream nodes from the source index to dest using recursion.
773 /// Simplest iterative traversal of the source tree wouldn't work, because
774 /// we update the pointers in nodes when moving them to the destination tree.
775 static void
index_cat_helper(const index_cat_info * info,index_stream * this)776 index_cat_helper(const index_cat_info *info, index_stream *this)
777 {
778 	index_stream *left = (index_stream *)(this->node.left);
779 	index_stream *right = (index_stream *)(this->node.right);
780 
781 	if (left != NULL)
782 		index_cat_helper(info, left);
783 
784 	this->node.uncompressed_base += info->uncompressed_size;
785 	this->node.compressed_base += info->file_size;
786 	this->number += info->stream_number_add;
787 	this->block_number_base += info->block_number_add;
788 	index_tree_append(info->streams, &this->node);
789 
790 	if (right != NULL)
791 		index_cat_helper(info, right);
792 
793 	return;
794 }
795 
796 
797 extern LZMA_API(lzma_ret)
lzma_index_cat(lzma_index * restrict dest,lzma_index * restrict src,const lzma_allocator * allocator)798 lzma_index_cat(lzma_index *restrict dest, lzma_index *restrict src,
799 		const lzma_allocator *allocator)
800 {
801 	if (dest == NULL || src == NULL)
802 		return LZMA_PROG_ERROR;
803 
804 	const lzma_vli dest_file_size = lzma_index_file_size(dest);
805 
806 	// Check that we don't exceed the file size limits.
807 	if (dest_file_size + lzma_index_file_size(src) > LZMA_VLI_MAX
808 			|| dest->uncompressed_size + src->uncompressed_size
809 				> LZMA_VLI_MAX)
810 		return LZMA_DATA_ERROR;
811 
812 	// Check that the encoded size of the combined lzma_indexes stays
813 	// within limits. In theory, this should be done only if we know
814 	// that the user plans to actually combine the Streams and thus
815 	// construct a single Index (probably rare). However, exceeding
816 	// this limit is quite theoretical, so we do this check always
817 	// to simplify things elsewhere.
818 	{
819 		const lzma_vli dest_size = index_size_unpadded(
820 				dest->record_count, dest->index_list_size);
821 		const lzma_vli src_size = index_size_unpadded(
822 				src->record_count, src->index_list_size);
823 		if (vli_ceil4(dest_size + src_size) > LZMA_BACKWARD_SIZE_MAX)
824 			return LZMA_DATA_ERROR;
825 	}
826 
827 	// Optimize the last group to minimize memory usage. Allocation has
828 	// to be done before modifying dest or src.
829 	{
830 		index_stream *s = (index_stream *)(dest->streams.rightmost);
831 		index_group *g = (index_group *)(s->groups.rightmost);
832 		if (g != NULL && g->last + 1 < g->allocated) {
833 			assert(g->node.left == NULL);
834 			assert(g->node.right == NULL);
835 
836 			index_group *newg = lzma_alloc(sizeof(index_group)
837 					+ (g->last + 1)
838 					* sizeof(index_record),
839 					allocator);
840 			if (newg == NULL)
841 				return LZMA_MEM_ERROR;
842 
843 			newg->node = g->node;
844 			newg->allocated = g->last + 1;
845 			newg->last = g->last;
846 			newg->number_base = g->number_base;
847 
848 			memcpy(newg->records, g->records, newg->allocated
849 					* sizeof(index_record));
850 
851 			if (g->node.parent != NULL) {
852 				assert(g->node.parent->right == &g->node);
853 				g->node.parent->right = &newg->node;
854 			}
855 
856 			if (s->groups.leftmost == &g->node) {
857 				assert(s->groups.root == &g->node);
858 				s->groups.leftmost = &newg->node;
859 				s->groups.root = &newg->node;
860 			}
861 
862 			assert(s->groups.rightmost == &g->node);
863 			s->groups.rightmost = &newg->node;
864 
865 			lzma_free(g, allocator);
866 
867 			// NOTE: newg isn't leaked here because
868 			// newg == (void *)&newg->node.
869 		}
870 	}
871 
872 	// dest->checks includes the check types of all except the last Stream
873 	// in dest. Set the bit for the check type of the last Stream now so
874 	// that it won't get lost when Stream(s) from src are appended to dest.
875 	dest->checks = lzma_index_checks(dest);
876 
877 	// Add all the Streams from src to dest. Update the base offsets
878 	// of each Stream from src.
879 	const index_cat_info info = {
880 		.uncompressed_size = dest->uncompressed_size,
881 		.file_size = dest_file_size,
882 		.stream_number_add = dest->streams.count,
883 		.block_number_add = dest->record_count,
884 		.streams = &dest->streams,
885 	};
886 	index_cat_helper(&info, (index_stream *)(src->streams.root));
887 
888 	// Update info about all the combined Streams.
889 	dest->uncompressed_size += src->uncompressed_size;
890 	dest->total_size += src->total_size;
891 	dest->record_count += src->record_count;
892 	dest->index_list_size += src->index_list_size;
893 	dest->checks |= src->checks;
894 
895 	// There's nothing else left in src than the base structure.
896 	lzma_free(src, allocator);
897 
898 	return LZMA_OK;
899 }
900 
901 
902 /// Duplicate an index_stream.
903 static index_stream *
index_dup_stream(const index_stream * src,const lzma_allocator * allocator)904 index_dup_stream(const index_stream *src, const lzma_allocator *allocator)
905 {
906 	// Catch a somewhat theoretical integer overflow.
907 	if (src->record_count > PREALLOC_MAX)
908 		return NULL;
909 
910 	// Allocate and initialize a new Stream.
911 	index_stream *dest = index_stream_init(src->node.compressed_base,
912 			src->node.uncompressed_base, src->number,
913 			src->block_number_base, allocator);
914 	if (dest == NULL)
915 		return NULL;
916 
917 	// Copy the overall information.
918 	dest->record_count = src->record_count;
919 	dest->index_list_size = src->index_list_size;
920 	dest->stream_flags = src->stream_flags;
921 	dest->stream_padding = src->stream_padding;
922 
923 	// Return if there are no groups to duplicate.
924 	if (src->groups.leftmost == NULL)
925 		return dest;
926 
927 	// Allocate memory for the Records. We put all the Records into
928 	// a single group. It's simplest and also tends to make
929 	// lzma_index_locate() a little bit faster with very big Indexes.
930 	index_group *destg = lzma_alloc(sizeof(index_group)
931 			+ src->record_count * sizeof(index_record),
932 			allocator);
933 	if (destg == NULL) {
934 		index_stream_end(dest, allocator);
935 		return NULL;
936 	}
937 
938 	// Initialize destg.
939 	destg->node.uncompressed_base = 0;
940 	destg->node.compressed_base = 0;
941 	destg->number_base = 1;
942 	destg->allocated = src->record_count;
943 	destg->last = src->record_count - 1;
944 
945 	// Go through all the groups in src and copy the Records into destg.
946 	const index_group *srcg = (const index_group *)(src->groups.leftmost);
947 	size_t i = 0;
948 	do {
949 		memcpy(destg->records + i, srcg->records,
950 				(srcg->last + 1) * sizeof(index_record));
951 		i += srcg->last + 1;
952 		srcg = index_tree_next(&srcg->node);
953 	} while (srcg != NULL);
954 
955 	assert(i == destg->allocated);
956 
957 	// Add the group to the new Stream.
958 	index_tree_append(&dest->groups, &destg->node);
959 
960 	return dest;
961 }
962 
963 
964 extern LZMA_API(lzma_index *)
lzma_index_dup(const lzma_index * src,const lzma_allocator * allocator)965 lzma_index_dup(const lzma_index *src, const lzma_allocator *allocator)
966 {
967 	// Allocate the base structure (no initial Stream).
968 	lzma_index *dest = index_init_plain(allocator);
969 	if (dest == NULL)
970 		return NULL;
971 
972 	// Copy the totals.
973 	dest->uncompressed_size = src->uncompressed_size;
974 	dest->total_size = src->total_size;
975 	dest->record_count = src->record_count;
976 	dest->index_list_size = src->index_list_size;
977 
978 	// Copy the Streams and the groups in them.
979 	const index_stream *srcstream
980 			= (const index_stream *)(src->streams.leftmost);
981 	do {
982 		index_stream *deststream = index_dup_stream(
983 				srcstream, allocator);
984 		if (deststream == NULL) {
985 			lzma_index_end(dest, allocator);
986 			return NULL;
987 		}
988 
989 		index_tree_append(&dest->streams, &deststream->node);
990 
991 		srcstream = index_tree_next(&srcstream->node);
992 	} while (srcstream != NULL);
993 
994 	return dest;
995 }
996 
997 
998 /// Indexing for lzma_index_iter.internal[]
999 enum {
1000 	ITER_INDEX,
1001 	ITER_STREAM,
1002 	ITER_GROUP,
1003 	ITER_RECORD,
1004 	ITER_METHOD,
1005 };
1006 
1007 
1008 /// Values for lzma_index_iter.internal[ITER_METHOD].s
1009 enum {
1010 	ITER_METHOD_NORMAL,
1011 	ITER_METHOD_NEXT,
1012 	ITER_METHOD_LEFTMOST,
1013 };
1014 
1015 
1016 static void
iter_set_info(lzma_index_iter * iter)1017 iter_set_info(lzma_index_iter *iter)
1018 {
1019 	const lzma_index *i = iter->internal[ITER_INDEX].p;
1020 	const index_stream *stream = iter->internal[ITER_STREAM].p;
1021 	const index_group *group = iter->internal[ITER_GROUP].p;
1022 	const size_t record = iter->internal[ITER_RECORD].s;
1023 
1024 	// lzma_index_iter.internal must not contain a pointer to the last
1025 	// group in the index, because that may be reallocated by
1026 	// lzma_index_cat().
1027 	if (group == NULL) {
1028 		// There are no groups.
1029 		assert(stream->groups.root == NULL);
1030 		iter->internal[ITER_METHOD].s = ITER_METHOD_LEFTMOST;
1031 
1032 	} else if (i->streams.rightmost != &stream->node
1033 			|| stream->groups.rightmost != &group->node) {
1034 		// The group is not not the last group in the index.
1035 		iter->internal[ITER_METHOD].s = ITER_METHOD_NORMAL;
1036 
1037 	} else if (stream->groups.leftmost != &group->node) {
1038 		// The group isn't the only group in the Stream, thus we
1039 		// know that it must have a parent group i.e. it's not
1040 		// the root node.
1041 		assert(stream->groups.root != &group->node);
1042 		assert(group->node.parent->right == &group->node);
1043 		iter->internal[ITER_METHOD].s = ITER_METHOD_NEXT;
1044 		iter->internal[ITER_GROUP].p = group->node.parent;
1045 
1046 	} else {
1047 		// The Stream has only one group.
1048 		assert(stream->groups.root == &group->node);
1049 		assert(group->node.parent == NULL);
1050 		iter->internal[ITER_METHOD].s = ITER_METHOD_LEFTMOST;
1051 		iter->internal[ITER_GROUP].p = NULL;
1052 	}
1053 
1054 	// NOTE: lzma_index_iter.stream.number is lzma_vli but we use uint32_t
1055 	// internally.
1056 	iter->stream.number = stream->number;
1057 	iter->stream.block_count = stream->record_count;
1058 	iter->stream.compressed_offset = stream->node.compressed_base;
1059 	iter->stream.uncompressed_offset = stream->node.uncompressed_base;
1060 
1061 	// iter->stream.flags will be NULL if the Stream Flags haven't been
1062 	// set with lzma_index_stream_flags().
1063 	iter->stream.flags = stream->stream_flags.version == UINT32_MAX
1064 			? NULL : &stream->stream_flags;
1065 	iter->stream.padding = stream->stream_padding;
1066 
1067 	if (stream->groups.rightmost == NULL) {
1068 		// Stream has no Blocks.
1069 		iter->stream.compressed_size = index_size(0, 0)
1070 				+ 2 * LZMA_STREAM_HEADER_SIZE;
1071 		iter->stream.uncompressed_size = 0;
1072 	} else {
1073 		const index_group *g = (const index_group *)(
1074 				stream->groups.rightmost);
1075 
1076 		// Stream Header + Stream Footer + Index + Blocks
1077 		iter->stream.compressed_size = 2 * LZMA_STREAM_HEADER_SIZE
1078 				+ index_size(stream->record_count,
1079 					stream->index_list_size)
1080 				+ vli_ceil4(g->records[g->last].unpadded_sum);
1081 		iter->stream.uncompressed_size
1082 				= g->records[g->last].uncompressed_sum;
1083 	}
1084 
1085 	if (group != NULL) {
1086 		iter->block.number_in_stream = group->number_base + record;
1087 		iter->block.number_in_file = iter->block.number_in_stream
1088 				+ stream->block_number_base;
1089 
1090 		iter->block.compressed_stream_offset
1091 				= record == 0 ? group->node.compressed_base
1092 				: vli_ceil4(group->records[
1093 					record - 1].unpadded_sum);
1094 		iter->block.uncompressed_stream_offset
1095 				= record == 0 ? group->node.uncompressed_base
1096 				: group->records[record - 1].uncompressed_sum;
1097 
1098 		iter->block.uncompressed_size
1099 				= group->records[record].uncompressed_sum
1100 				- iter->block.uncompressed_stream_offset;
1101 		iter->block.unpadded_size
1102 				= group->records[record].unpadded_sum
1103 				- iter->block.compressed_stream_offset;
1104 		iter->block.total_size = vli_ceil4(iter->block.unpadded_size);
1105 
1106 		iter->block.compressed_stream_offset
1107 				+= LZMA_STREAM_HEADER_SIZE;
1108 
1109 		iter->block.compressed_file_offset
1110 				= iter->block.compressed_stream_offset
1111 				+ iter->stream.compressed_offset;
1112 		iter->block.uncompressed_file_offset
1113 				= iter->block.uncompressed_stream_offset
1114 				+ iter->stream.uncompressed_offset;
1115 	}
1116 
1117 	return;
1118 }
1119 
1120 
1121 extern LZMA_API(void)
lzma_index_iter_init(lzma_index_iter * iter,const lzma_index * i)1122 lzma_index_iter_init(lzma_index_iter *iter, const lzma_index *i)
1123 {
1124 	iter->internal[ITER_INDEX].p = i;
1125 	lzma_index_iter_rewind(iter);
1126 	return;
1127 }
1128 
1129 
1130 extern LZMA_API(void)
lzma_index_iter_rewind(lzma_index_iter * iter)1131 lzma_index_iter_rewind(lzma_index_iter *iter)
1132 {
1133 	iter->internal[ITER_STREAM].p = NULL;
1134 	iter->internal[ITER_GROUP].p = NULL;
1135 	iter->internal[ITER_RECORD].s = 0;
1136 	iter->internal[ITER_METHOD].s = ITER_METHOD_NORMAL;
1137 	return;
1138 }
1139 
1140 
1141 extern LZMA_API(lzma_bool)
lzma_index_iter_next(lzma_index_iter * iter,lzma_index_iter_mode mode)1142 lzma_index_iter_next(lzma_index_iter *iter, lzma_index_iter_mode mode)
1143 {
1144 	// Catch unsupported mode values.
1145 	if ((unsigned int)(mode) > LZMA_INDEX_ITER_NONEMPTY_BLOCK)
1146 		return true;
1147 
1148 	const lzma_index *i = iter->internal[ITER_INDEX].p;
1149 	const index_stream *stream = iter->internal[ITER_STREAM].p;
1150 	const index_group *group = NULL;
1151 	size_t record = iter->internal[ITER_RECORD].s;
1152 
1153 	// If we are being asked for the next Stream, leave group to NULL
1154 	// so that the rest of the this function thinks that this Stream
1155 	// has no groups and will thus go to the next Stream.
1156 	if (mode != LZMA_INDEX_ITER_STREAM) {
1157 		// Get the pointer to the current group. See iter_set_inf()
1158 		// for explanation.
1159 		switch (iter->internal[ITER_METHOD].s) {
1160 		case ITER_METHOD_NORMAL:
1161 			group = iter->internal[ITER_GROUP].p;
1162 			break;
1163 
1164 		case ITER_METHOD_NEXT:
1165 			group = index_tree_next(iter->internal[ITER_GROUP].p);
1166 			break;
1167 
1168 		case ITER_METHOD_LEFTMOST:
1169 			group = (const index_group *)(
1170 					stream->groups.leftmost);
1171 			break;
1172 		}
1173 	}
1174 
1175 again:
1176 	if (stream == NULL) {
1177 		// We at the beginning of the lzma_index.
1178 		// Locate the first Stream.
1179 		stream = (const index_stream *)(i->streams.leftmost);
1180 		if (mode >= LZMA_INDEX_ITER_BLOCK) {
1181 			// Since we are being asked to return information
1182 			// about the first a Block, skip Streams that have
1183 			// no Blocks.
1184 			while (stream->groups.leftmost == NULL) {
1185 				stream = index_tree_next(&stream->node);
1186 				if (stream == NULL)
1187 					return true;
1188 			}
1189 		}
1190 
1191 		// Start from the first Record in the Stream.
1192 		group = (const index_group *)(stream->groups.leftmost);
1193 		record = 0;
1194 
1195 	} else if (group != NULL && record < group->last) {
1196 		// The next Record is in the same group.
1197 		++record;
1198 
1199 	} else {
1200 		// This group has no more Records or this Stream has
1201 		// no Blocks at all.
1202 		record = 0;
1203 
1204 		// If group is not NULL, this Stream has at least one Block
1205 		// and thus at least one group. Find the next group.
1206 		if (group != NULL)
1207 			group = index_tree_next(&group->node);
1208 
1209 		if (group == NULL) {
1210 			// This Stream has no more Records. Find the next
1211 			// Stream. If we are being asked to return information
1212 			// about a Block, we skip empty Streams.
1213 			do {
1214 				stream = index_tree_next(&stream->node);
1215 				if (stream == NULL)
1216 					return true;
1217 			} while (mode >= LZMA_INDEX_ITER_BLOCK
1218 					&& stream->groups.leftmost == NULL);
1219 
1220 			group = (const index_group *)(
1221 					stream->groups.leftmost);
1222 		}
1223 	}
1224 
1225 	if (mode == LZMA_INDEX_ITER_NONEMPTY_BLOCK) {
1226 		// We need to look for the next Block again if this Block
1227 		// is empty.
1228 		if (record == 0) {
1229 			if (group->node.uncompressed_base
1230 					== group->records[0].uncompressed_sum)
1231 				goto again;
1232 		} else if (group->records[record - 1].uncompressed_sum
1233 				== group->records[record].uncompressed_sum) {
1234 			goto again;
1235 		}
1236 	}
1237 
1238 	iter->internal[ITER_STREAM].p = stream;
1239 	iter->internal[ITER_GROUP].p = group;
1240 	iter->internal[ITER_RECORD].s = record;
1241 
1242 	iter_set_info(iter);
1243 
1244 	return false;
1245 }
1246 
1247 
1248 extern LZMA_API(lzma_bool)
lzma_index_iter_locate(lzma_index_iter * iter,lzma_vli target)1249 lzma_index_iter_locate(lzma_index_iter *iter, lzma_vli target)
1250 {
1251 	const lzma_index *i = iter->internal[ITER_INDEX].p;
1252 
1253 	// If the target is past the end of the file, return immediately.
1254 	if (i->uncompressed_size <= target)
1255 		return true;
1256 
1257 	// Locate the Stream containing the target offset.
1258 	const index_stream *stream = index_tree_locate(&i->streams, target);
1259 	assert(stream != NULL);
1260 	target -= stream->node.uncompressed_base;
1261 
1262 	// Locate the group containing the target offset.
1263 	const index_group *group = index_tree_locate(&stream->groups, target);
1264 	assert(group != NULL);
1265 
1266 	// Use binary search to locate the exact Record. It is the first
1267 	// Record whose uncompressed_sum is greater than target.
1268 	// This is because we want the rightmost Record that fulfills the
1269 	// search criterion. It is possible that there are empty Blocks;
1270 	// we don't want to return them.
1271 	size_t left = 0;
1272 	size_t right = group->last;
1273 
1274 	while (left < right) {
1275 		const size_t pos = left + (right - left) / 2;
1276 		if (group->records[pos].uncompressed_sum <= target)
1277 			left = pos + 1;
1278 		else
1279 			right = pos;
1280 	}
1281 
1282 	iter->internal[ITER_STREAM].p = stream;
1283 	iter->internal[ITER_GROUP].p = group;
1284 	iter->internal[ITER_RECORD].s = left;
1285 
1286 	iter_set_info(iter);
1287 
1288 	return false;
1289 }
1290