index.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  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 Streams.
  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 overridden 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 uncompressed size will not overflow.
  511. if (uncompressed_base + uncompressed_size > LZMA_VLI_MAX)
  512. return LZMA_DATA_ERROR;
  513. // Check that the file size will stay within limits.
  514. if (index_file_size(s->node.compressed_base,
  515. compressed_base + unpadded_size, s->record_count + 1,
  516. s->index_list_size + index_list_size_add,
  517. s->stream_padding) == LZMA_VLI_UNKNOWN)
  518. return LZMA_DATA_ERROR;
  519. // The size of the Index field must not exceed the maximum value
  520. // that can be stored in the Backward Size field.
  521. if (index_size(i->record_count + 1,
  522. i->index_list_size + index_list_size_add)
  523. > LZMA_BACKWARD_SIZE_MAX)
  524. return LZMA_DATA_ERROR;
  525. if (g != NULL && g->last + 1 < g->allocated) {
  526. // There is space in the last group at least for one Record.
  527. ++g->last;
  528. } else {
  529. // We need to allocate a new group.
  530. g = lzma_alloc(sizeof(index_group)
  531. + i->prealloc * sizeof(index_record),
  532. allocator);
  533. if (g == NULL)
  534. return LZMA_MEM_ERROR;
  535. g->last = 0;
  536. g->allocated = i->prealloc;
  537. // Reset prealloc so that if the application happens to
  538. // add new Records, the allocation size will be sane.
  539. i->prealloc = INDEX_GROUP_SIZE;
  540. // Set the start offsets of this group.
  541. g->node.uncompressed_base = uncompressed_base;
  542. g->node.compressed_base = compressed_base;
  543. g->number_base = s->record_count + 1;
  544. // Add the new group to the Stream.
  545. index_tree_append(&s->groups, &g->node);
  546. }
  547. // Add the new Record to the group.
  548. g->records[g->last].uncompressed_sum
  549. = uncompressed_base + uncompressed_size;
  550. g->records[g->last].unpadded_sum
  551. = compressed_base + unpadded_size;
  552. // Update the totals.
  553. ++s->record_count;
  554. s->index_list_size += index_list_size_add;
  555. i->total_size += vli_ceil4(unpadded_size);
  556. i->uncompressed_size += uncompressed_size;
  557. ++i->record_count;
  558. i->index_list_size += index_list_size_add;
  559. return LZMA_OK;
  560. }
  561. /// Structure to pass info to index_cat_helper()
  562. typedef struct {
  563. /// Uncompressed size of the destination
  564. lzma_vli uncompressed_size;
  565. /// Compressed file size of the destination
  566. lzma_vli file_size;
  567. /// Same as above but for Block numbers
  568. lzma_vli block_number_add;
  569. /// Number of Streams that were in the destination index before we
  570. /// started appending new Streams from the source index. This is
  571. /// used to fix the Stream numbering.
  572. uint32_t stream_number_add;
  573. /// Destination index' Stream tree
  574. index_tree *streams;
  575. } index_cat_info;
  576. /// Add the Stream nodes from the source index to dest using recursion.
  577. /// Simplest iterative traversal of the source tree wouldn't work, because
  578. /// we update the pointers in nodes when moving them to the destination tree.
  579. static void
  580. index_cat_helper(const index_cat_info *info, index_stream *this)
  581. {
  582. index_stream *left = (index_stream *)(this->node.left);
  583. index_stream *right = (index_stream *)(this->node.right);
  584. if (left != NULL)
  585. index_cat_helper(info, left);
  586. this->node.uncompressed_base += info->uncompressed_size;
  587. this->node.compressed_base += info->file_size;
  588. this->number += info->stream_number_add;
  589. this->block_number_base += info->block_number_add;
  590. index_tree_append(info->streams, &this->node);
  591. if (right != NULL)
  592. index_cat_helper(info, right);
  593. return;
  594. }
  595. extern LZMA_API(lzma_ret)
  596. lzma_index_cat(lzma_index *restrict dest, lzma_index *restrict src,
  597. const lzma_allocator *allocator)
  598. {
  599. if (dest == NULL || src == NULL)
  600. return LZMA_PROG_ERROR;
  601. const lzma_vli dest_file_size = lzma_index_file_size(dest);
  602. // Check that we don't exceed the file size limits.
  603. if (dest_file_size + lzma_index_file_size(src) > LZMA_VLI_MAX
  604. || dest->uncompressed_size + src->uncompressed_size
  605. > LZMA_VLI_MAX)
  606. return LZMA_DATA_ERROR;
  607. // Check that the encoded size of the combined lzma_indexes stays
  608. // within limits. In theory, this should be done only if we know
  609. // that the user plans to actually combine the Streams and thus
  610. // construct a single Index (probably rare). However, exceeding
  611. // this limit is quite theoretical, so we do this check always
  612. // to simplify things elsewhere.
  613. {
  614. const lzma_vli dest_size = index_size_unpadded(
  615. dest->record_count, dest->index_list_size);
  616. const lzma_vli src_size = index_size_unpadded(
  617. src->record_count, src->index_list_size);
  618. if (vli_ceil4(dest_size + src_size) > LZMA_BACKWARD_SIZE_MAX)
  619. return LZMA_DATA_ERROR;
  620. }
  621. // Optimize the last group to minimize memory usage. Allocation has
  622. // to be done before modifying dest or src.
  623. {
  624. index_stream *s = (index_stream *)(dest->streams.rightmost);
  625. index_group *g = (index_group *)(s->groups.rightmost);
  626. if (g != NULL && g->last + 1 < g->allocated) {
  627. assert(g->node.left == NULL);
  628. assert(g->node.right == NULL);
  629. index_group *newg = lzma_alloc(sizeof(index_group)
  630. + (g->last + 1)
  631. * sizeof(index_record),
  632. allocator);
  633. if (newg == NULL)
  634. return LZMA_MEM_ERROR;
  635. newg->node = g->node;
  636. newg->allocated = g->last + 1;
  637. newg->last = g->last;
  638. newg->number_base = g->number_base;
  639. memcpy(newg->records, g->records, newg->allocated
  640. * sizeof(index_record));
  641. if (g->node.parent != NULL) {
  642. assert(g->node.parent->right == &g->node);
  643. g->node.parent->right = &newg->node;
  644. }
  645. if (s->groups.leftmost == &g->node) {
  646. assert(s->groups.root == &g->node);
  647. s->groups.leftmost = &newg->node;
  648. s->groups.root = &newg->node;
  649. }
  650. assert(s->groups.rightmost == &g->node);
  651. s->groups.rightmost = &newg->node;
  652. lzma_free(g, allocator);
  653. // NOTE: newg isn't leaked here because
  654. // newg == (void *)&newg->node.
  655. }
  656. }
  657. // dest->checks includes the check types of all except the last Stream
  658. // in dest. Set the bit for the check type of the last Stream now so
  659. // that it won't get lost when Stream(s) from src are appended to dest.
  660. dest->checks = lzma_index_checks(dest);
  661. // Add all the Streams from src to dest. Update the base offsets
  662. // of each Stream from src.
  663. const index_cat_info info = {
  664. .uncompressed_size = dest->uncompressed_size,
  665. .file_size = dest_file_size,
  666. .stream_number_add = dest->streams.count,
  667. .block_number_add = dest->record_count,
  668. .streams = &dest->streams,
  669. };
  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 |= 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, const lzma_allocator *allocator)
  684. {
  685. // Catch a somewhat theoretical integer overflow.
  686. if (src->record_count > PREALLOC_MAX)
  687. return NULL;
  688. // Allocate and initialize a new Stream.
  689. index_stream *dest = index_stream_init(src->node.compressed_base,
  690. src->node.uncompressed_base, src->number,
  691. src->block_number_base, allocator);
  692. if (dest == NULL)
  693. return NULL;
  694. // Copy the overall information.
  695. dest->record_count = src->record_count;
  696. dest->index_list_size = src->index_list_size;
  697. dest->stream_flags = src->stream_flags;
  698. dest->stream_padding = src->stream_padding;
  699. // Return if there are no groups to duplicate.
  700. if (src->groups.leftmost == NULL)
  701. return dest;
  702. // Allocate memory for the Records. We put all the Records into
  703. // a single group. It's simplest and also tends to make
  704. // lzma_index_locate() a little bit faster with very big Indexes.
  705. index_group *destg = lzma_alloc(sizeof(index_group)
  706. + src->record_count * sizeof(index_record),
  707. allocator);
  708. if (destg == NULL) {
  709. index_stream_end(dest, allocator);
  710. return NULL;
  711. }
  712. // Initialize destg.
  713. destg->node.uncompressed_base = 0;
  714. destg->node.compressed_base = 0;
  715. destg->number_base = 1;
  716. destg->allocated = src->record_count;
  717. destg->last = src->record_count - 1;
  718. // Go through all the groups in src and copy the Records into destg.
  719. const index_group *srcg = (const index_group *)(src->groups.leftmost);
  720. size_t i = 0;
  721. do {
  722. memcpy(destg->records + i, srcg->records,
  723. (srcg->last + 1) * sizeof(index_record));
  724. i += srcg->last + 1;
  725. srcg = index_tree_next(&srcg->node);
  726. } while (srcg != NULL);
  727. assert(i == destg->allocated);
  728. // Add the group to the new Stream.
  729. index_tree_append(&dest->groups, &destg->node);
  730. return dest;
  731. }
  732. extern LZMA_API(lzma_index *)
  733. lzma_index_dup(const lzma_index *src, const lzma_allocator *allocator)
  734. {
  735. // Allocate the base structure (no initial Stream).
  736. lzma_index *dest = index_init_plain(allocator);
  737. if (dest == NULL)
  738. return NULL;
  739. // Copy the totals.
  740. dest->uncompressed_size = src->uncompressed_size;
  741. dest->total_size = src->total_size;
  742. dest->record_count = src->record_count;
  743. dest->index_list_size = src->index_list_size;
  744. // Copy the Streams and the groups in them.
  745. const index_stream *srcstream
  746. = (const index_stream *)(src->streams.leftmost);
  747. do {
  748. index_stream *deststream = index_dup_stream(
  749. srcstream, allocator);
  750. if (deststream == NULL) {
  751. lzma_index_end(dest, allocator);
  752. return NULL;
  753. }
  754. index_tree_append(&dest->streams, &deststream->node);
  755. srcstream = index_tree_next(&srcstream->node);
  756. } while (srcstream != NULL);
  757. return dest;
  758. }
  759. /// Indexing for lzma_index_iter.internal[]
  760. enum {
  761. ITER_INDEX,
  762. ITER_STREAM,
  763. ITER_GROUP,
  764. ITER_RECORD,
  765. ITER_METHOD,
  766. };
  767. /// Values for lzma_index_iter.internal[ITER_METHOD].s
  768. enum {
  769. ITER_METHOD_NORMAL,
  770. ITER_METHOD_NEXT,
  771. ITER_METHOD_LEFTMOST,
  772. };
  773. static void
  774. iter_set_info(lzma_index_iter *iter)
  775. {
  776. const lzma_index *i = iter->internal[ITER_INDEX].p;
  777. const index_stream *stream = iter->internal[ITER_STREAM].p;
  778. const index_group *group = iter->internal[ITER_GROUP].p;
  779. const size_t record = iter->internal[ITER_RECORD].s;
  780. // lzma_index_iter.internal must not contain a pointer to the last
  781. // group in the index, because that may be reallocated by
  782. // lzma_index_cat().
  783. if (group == NULL) {
  784. // There are no groups.
  785. assert(stream->groups.root == NULL);
  786. iter->internal[ITER_METHOD].s = ITER_METHOD_LEFTMOST;
  787. } else if (i->streams.rightmost != &stream->node
  788. || stream->groups.rightmost != &group->node) {
  789. // The group is not not the last group in the index.
  790. iter->internal[ITER_METHOD].s = ITER_METHOD_NORMAL;
  791. } else if (stream->groups.leftmost != &group->node) {
  792. // The group isn't the only group in the Stream, thus we
  793. // know that it must have a parent group i.e. it's not
  794. // the root node.
  795. assert(stream->groups.root != &group->node);
  796. assert(group->node.parent->right == &group->node);
  797. iter->internal[ITER_METHOD].s = ITER_METHOD_NEXT;
  798. iter->internal[ITER_GROUP].p = group->node.parent;
  799. } else {
  800. // The Stream has only one group.
  801. assert(stream->groups.root == &group->node);
  802. assert(group->node.parent == NULL);
  803. iter->internal[ITER_METHOD].s = ITER_METHOD_LEFTMOST;
  804. iter->internal[ITER_GROUP].p = NULL;
  805. }
  806. // NOTE: lzma_index_iter.stream.number is lzma_vli but we use uint32_t
  807. // internally.
  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. // Catch unsupported mode values.
  882. if ((unsigned int)(mode) > LZMA_INDEX_ITER_NONEMPTY_BLOCK)
  883. return true;
  884. const lzma_index *i = iter->internal[ITER_INDEX].p;
  885. const index_stream *stream = iter->internal[ITER_STREAM].p;
  886. const index_group *group = NULL;
  887. size_t record = iter->internal[ITER_RECORD].s;
  888. // If we are being asked for the next Stream, leave group to NULL
  889. // so that the rest of the this function thinks that this Stream
  890. // has no groups and will thus go to the next Stream.
  891. if (mode != LZMA_INDEX_ITER_STREAM) {
  892. // Get the pointer to the current group. See iter_set_inf()
  893. // for explanation.
  894. switch (iter->internal[ITER_METHOD].s) {
  895. case ITER_METHOD_NORMAL:
  896. group = iter->internal[ITER_GROUP].p;
  897. break;
  898. case ITER_METHOD_NEXT:
  899. group = index_tree_next(iter->internal[ITER_GROUP].p);
  900. break;
  901. case ITER_METHOD_LEFTMOST:
  902. group = (const index_group *)(
  903. stream->groups.leftmost);
  904. break;
  905. }
  906. }
  907. again:
  908. if (stream == NULL) {
  909. // We at the beginning of the lzma_index.
  910. // Locate the first Stream.
  911. stream = (const index_stream *)(i->streams.leftmost);
  912. if (mode >= LZMA_INDEX_ITER_BLOCK) {
  913. // Since we are being asked to return information
  914. // about the first a Block, skip Streams that have
  915. // no Blocks.
  916. while (stream->groups.leftmost == NULL) {
  917. stream = index_tree_next(&stream->node);
  918. if (stream == NULL)
  919. return true;
  920. }
  921. }
  922. // Start from the first Record in the Stream.
  923. group = (const index_group *)(stream->groups.leftmost);
  924. record = 0;
  925. } else if (group != NULL && record < group->last) {
  926. // The next Record is in the same group.
  927. ++record;
  928. } else {
  929. // This group has no more Records or this Stream has
  930. // no Blocks at all.
  931. record = 0;
  932. // If group is not NULL, this Stream has at least one Block
  933. // and thus at least one group. Find the next group.
  934. if (group != NULL)
  935. group = index_tree_next(&group->node);
  936. if (group == NULL) {
  937. // This Stream has no more Records. Find the next
  938. // Stream. If we are being asked to return information
  939. // about a Block, we skip empty Streams.
  940. do {
  941. stream = index_tree_next(&stream->node);
  942. if (stream == NULL)
  943. return true;
  944. } while (mode >= LZMA_INDEX_ITER_BLOCK
  945. && stream->groups.leftmost == NULL);
  946. group = (const index_group *)(
  947. stream->groups.leftmost);
  948. }
  949. }
  950. if (mode == LZMA_INDEX_ITER_NONEMPTY_BLOCK) {
  951. // We need to look for the next Block again if this Block
  952. // is empty.
  953. if (record == 0) {
  954. if (group->node.uncompressed_base
  955. == group->records[0].uncompressed_sum)
  956. goto again;
  957. } else if (group->records[record - 1].uncompressed_sum
  958. == group->records[record].uncompressed_sum) {
  959. goto again;
  960. }
  961. }
  962. iter->internal[ITER_STREAM].p = stream;
  963. iter->internal[ITER_GROUP].p = group;
  964. iter->internal[ITER_RECORD].s = record;
  965. iter_set_info(iter);
  966. return false;
  967. }
  968. extern LZMA_API(lzma_bool)
  969. lzma_index_iter_locate(lzma_index_iter *iter, lzma_vli target)
  970. {
  971. const lzma_index *i = iter->internal[ITER_INDEX].p;
  972. // If the target is past the end of the file, return immediately.
  973. if (i->uncompressed_size <= target)
  974. return true;
  975. // Locate the Stream containing the target offset.
  976. const index_stream *stream = index_tree_locate(&i->streams, target);
  977. assert(stream != NULL);
  978. target -= stream->node.uncompressed_base;
  979. // Locate the group containing the target offset.
  980. const index_group *group = index_tree_locate(&stream->groups, target);
  981. assert(group != NULL);
  982. // Use binary search to locate the exact Record. It is the first
  983. // Record whose uncompressed_sum is greater than target.
  984. // This is because we want the rightmost Record that fulfills the
  985. // search criterion. It is possible that there are empty Blocks;
  986. // we don't want to return them.
  987. size_t left = 0;
  988. size_t right = group->last;
  989. while (left < right) {
  990. const size_t pos = left + (right - left) / 2;
  991. if (group->records[pos].uncompressed_sum <= target)
  992. left = pos + 1;
  993. else
  994. right = pos;
  995. }
  996. iter->internal[ITER_STREAM].p = stream;
  997. iter->internal[ITER_GROUP].p = group;
  998. iter->internal[ITER_RECORD].s = left;
  999. iter_set_info(iter);
  1000. return false;
  1001. }