index.c 35 KB

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