Coverage Report

Created: 2026-02-09 06:05

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