index.c 35 KB

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