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