index.c 35 KB

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