index.c 35 KB

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