inflate_stream.ipp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. // This is a derivative work based on Zlib, copyright below:
  10. /*
  11. Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler
  12. This software is provided 'as-is', without any express or implied
  13. warranty. In no event will the authors be held liable for any damages
  14. arising from the use of this software.
  15. Permission is granted to anyone to use this software for any purpose,
  16. including commercial applications, and to alter it and redistribute it
  17. freely, subject to the following restrictions:
  18. 1. The origin of this software must not be misrepresented; you must not
  19. claim that you wrote the original software. If you use this software
  20. in a product, an acknowledgment in the product documentation would be
  21. appreciated but is not required.
  22. 2. Altered source versions must be plainly marked as such, and must not be
  23. misrepresented as being the original software.
  24. 3. This notice may not be removed or altered from any source distribution.
  25. Jean-loup Gailly Mark Adler
  26. jloup@gzip.org madler@alumni.caltech.edu
  27. The data format used by the zlib library is described by RFCs (Request for
  28. Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
  29. (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
  30. */
  31. #ifndef BOOST_BEAST_ZLIB_DETAIL_INFLATE_STREAM_IPP
  32. #define BOOST_BEAST_ZLIB_DETAIL_INFLATE_STREAM_IPP
  33. #include <boost/beast/zlib/detail/inflate_stream.hpp>
  34. #include <boost/throw_exception.hpp>
  35. #include <array>
  36. namespace boost {
  37. namespace beast {
  38. namespace zlib {
  39. namespace detail {
  40. void
  41. inflate_stream::
  42. doClear()
  43. {
  44. }
  45. void
  46. inflate_stream::
  47. doReset(int windowBits)
  48. {
  49. if(windowBits < 8 || windowBits > 15)
  50. BOOST_THROW_EXCEPTION(std::domain_error{
  51. "windowBits out of range"});
  52. w_.reset(windowBits);
  53. bi_.flush();
  54. mode_ = HEAD;
  55. last_ = 0;
  56. dmax_ = 32768U;
  57. lencode_ = codes_;
  58. distcode_ = codes_;
  59. next_ = codes_;
  60. back_ = -1;
  61. }
  62. void
  63. inflate_stream::
  64. doWrite(z_params& zs, Flush flush, error_code& ec)
  65. {
  66. ranges r;
  67. r.in.first = static_cast<
  68. std::uint8_t const*>(zs.next_in);
  69. r.in.last = r.in.first + zs.avail_in;
  70. r.in.next = r.in.first;
  71. r.out.first = static_cast<
  72. std::uint8_t*>(zs.next_out);
  73. r.out.last = r.out.first + zs.avail_out;
  74. r.out.next = r.out.first;
  75. auto const done =
  76. [&]
  77. {
  78. /*
  79. Return from inflate(), updating the total counts and the check value.
  80. If there was no progress during the inflate() call, return a buffer
  81. error. Call updatewindow() to create and/or update the window state.
  82. Note: a memory error from inflate() is non-recoverable.
  83. */
  84. // VFALCO TODO Don't allocate update the window unless necessary
  85. if(/*wsize_ ||*/ (r.out.used() && mode_ < BAD &&
  86. (mode_ < CHECK || flush != Flush::finish)))
  87. w_.write(r.out.first, r.out.used());
  88. zs.next_in = r.in.next;
  89. zs.avail_in = r.in.avail();
  90. zs.next_out = r.out.next;
  91. zs.avail_out = r.out.avail();
  92. zs.total_in += r.in.used();
  93. zs.total_out += r.out.used();
  94. zs.data_type = bi_.size() + (last_ ? 64 : 0) +
  95. (mode_ == TYPE ? 128 : 0) +
  96. (mode_ == LEN_ || mode_ == COPY_ ? 256 : 0);
  97. if(((! r.in.used() && ! r.out.used()) ||
  98. flush == Flush::finish) && ! ec)
  99. ec = error::need_buffers;
  100. };
  101. auto const err =
  102. [&](error e)
  103. {
  104. ec = e;
  105. mode_ = BAD;
  106. };
  107. if(mode_ == TYPE)
  108. mode_ = TYPEDO;
  109. for(;;)
  110. {
  111. switch(mode_)
  112. {
  113. case HEAD:
  114. mode_ = TYPEDO;
  115. break;
  116. case TYPE:
  117. if(flush == Flush::block || flush == Flush::trees)
  118. return done();
  119. // fall through
  120. case TYPEDO:
  121. {
  122. if(last_)
  123. {
  124. bi_.flush_byte();
  125. mode_ = CHECK;
  126. break;
  127. }
  128. if(! bi_.fill(3, r.in.next, r.in.last))
  129. return done();
  130. std::uint8_t v;
  131. bi_.read(v, 1);
  132. last_ = v != 0;
  133. bi_.read(v, 2);
  134. switch(v)
  135. {
  136. case 0:
  137. // uncompressed block
  138. mode_ = STORED;
  139. break;
  140. case 1:
  141. // fixed Huffman table
  142. fixedTables();
  143. mode_ = LEN_; /* decode codes */
  144. if(flush == Flush::trees)
  145. return done();
  146. break;
  147. case 2:
  148. // dynamic Huffman table
  149. mode_ = TABLE;
  150. break;
  151. default:
  152. return err(error::invalid_block_type);
  153. }
  154. break;
  155. }
  156. case STORED:
  157. {
  158. bi_.flush_byte();
  159. std::uint32_t v;
  160. if(! bi_.fill(32, r.in.next, r.in.last))
  161. return done();
  162. bi_.peek(v, 32);
  163. length_ = v & 0xffff;
  164. if(length_ != ((v >> 16) ^ 0xffff))
  165. return err(error::invalid_stored_length);
  166. // flush instead of read, otherwise
  167. // undefined right shift behavior.
  168. bi_.flush();
  169. mode_ = COPY_;
  170. if(flush == Flush::trees)
  171. return done();
  172. BOOST_FALLTHROUGH;
  173. }
  174. case COPY_:
  175. mode_ = COPY;
  176. BOOST_FALLTHROUGH;
  177. case COPY:
  178. {
  179. auto copy = length_;
  180. if(copy == 0)
  181. {
  182. mode_ = TYPE;
  183. break;
  184. }
  185. copy = clamp(copy, r.in.avail());
  186. copy = clamp(copy, r.out.avail());
  187. if(copy == 0)
  188. return done();
  189. std::memcpy(r.out.next, r.in.next, copy);
  190. r.in.next += copy;
  191. r.out.next += copy;
  192. length_ -= copy;
  193. break;
  194. }
  195. case TABLE:
  196. if(! bi_.fill(5 + 5 + 4, r.in.next, r.in.last))
  197. return done();
  198. bi_.read(nlen_, 5);
  199. nlen_ += 257;
  200. bi_.read(ndist_, 5);
  201. ndist_ += 1;
  202. bi_.read(ncode_, 4);
  203. ncode_ += 4;
  204. if(nlen_ > 286 || ndist_ > 30)
  205. return err(error::too_many_symbols);
  206. have_ = 0;
  207. mode_ = LENLENS;
  208. BOOST_FALLTHROUGH;
  209. case LENLENS:
  210. {
  211. static std::array<std::uint8_t, 19> constexpr order = {{
  212. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}};
  213. while(have_ < ncode_)
  214. {
  215. if(! bi_.fill(3, r.in.next, r.in.last))
  216. return done();
  217. bi_.read(lens_[order[have_]], 3);
  218. ++have_;
  219. }
  220. while(have_ < order.size())
  221. lens_[order[have_++]] = 0;
  222. next_ = &codes_[0];
  223. lencode_ = next_;
  224. lenbits_ = 7;
  225. inflate_table(build::codes, &lens_[0],
  226. order.size(), &next_, &lenbits_, work_, ec);
  227. if(ec)
  228. {
  229. mode_ = BAD;
  230. break;
  231. }
  232. have_ = 0;
  233. mode_ = CODELENS;
  234. BOOST_FALLTHROUGH;
  235. }
  236. case CODELENS:
  237. {
  238. while(have_ < nlen_ + ndist_)
  239. {
  240. std::uint16_t v;
  241. if(! bi_.fill(lenbits_, r.in.next, r.in.last))
  242. return done();
  243. bi_.peek(v, lenbits_);
  244. auto cp = &lencode_[v];
  245. if(cp->val < 16)
  246. {
  247. bi_.drop(cp->bits);
  248. lens_[have_++] = cp->val;
  249. }
  250. else
  251. {
  252. std::uint16_t len;
  253. std::uint16_t copy;
  254. if(cp->val == 16)
  255. {
  256. if(! bi_.fill(cp->bits + 2, r.in.next, r.in.last))
  257. return done();
  258. bi_.drop(cp->bits);
  259. if(have_ == 0)
  260. return err(error::invalid_bit_length_repeat);
  261. bi_.read(copy, 2);
  262. len = lens_[have_ - 1];
  263. copy += 3;
  264. }
  265. else if(cp->val == 17)
  266. {
  267. if(! bi_.fill(cp->bits + 3, r.in.next, r.in.last))
  268. return done();
  269. bi_.drop(cp->bits);
  270. bi_.read(copy, 3);
  271. len = 0;
  272. copy += 3;
  273. }
  274. else
  275. {
  276. if(! bi_.fill(cp->bits + 7, r.in.next, r.in.last))
  277. return done();
  278. bi_.drop(cp->bits);
  279. bi_.read(copy, 7);
  280. len = 0;
  281. copy += 11;
  282. }
  283. if(have_ + copy > nlen_ + ndist_)
  284. return err(error::invalid_bit_length_repeat);
  285. std::fill(&lens_[have_], &lens_[have_ + copy], len);
  286. have_ += copy;
  287. copy = 0;
  288. }
  289. }
  290. // handle error breaks in while
  291. if(mode_ == BAD)
  292. break;
  293. // check for end-of-block code (better have one)
  294. if(lens_[256] == 0)
  295. return err(error::missing_eob);
  296. /* build code tables -- note: do not change the lenbits or distbits
  297. values here (9 and 6) without reading the comments in inftrees.hpp
  298. concerning the kEnough constants, which depend on those values */
  299. next_ = &codes_[0];
  300. lencode_ = next_;
  301. lenbits_ = 9;
  302. inflate_table(build::lens, &lens_[0],
  303. nlen_, &next_, &lenbits_, work_, ec);
  304. if(ec)
  305. {
  306. mode_ = BAD;
  307. return;
  308. }
  309. distcode_ = next_;
  310. distbits_ = 6;
  311. inflate_table(build::dists, lens_ + nlen_,
  312. ndist_, &next_, &distbits_, work_, ec);
  313. if(ec)
  314. {
  315. mode_ = BAD;
  316. return;
  317. }
  318. mode_ = LEN_;
  319. if(flush == Flush::trees)
  320. return done();
  321. BOOST_FALLTHROUGH;
  322. }
  323. case LEN_:
  324. mode_ = LEN;
  325. BOOST_FALLTHROUGH;
  326. case LEN:
  327. {
  328. if(r.in.avail() >= 6 && r.out.avail() >= 258)
  329. {
  330. inflate_fast(r, ec);
  331. if(ec)
  332. {
  333. mode_ = BAD;
  334. return;
  335. }
  336. if(mode_ == TYPE)
  337. back_ = -1;
  338. break;
  339. }
  340. if(! bi_.fill(lenbits_, r.in.next, r.in.last))
  341. return done();
  342. std::uint16_t v;
  343. back_ = 0;
  344. bi_.peek(v, lenbits_);
  345. auto cp = &lencode_[v];
  346. if(cp->op && (cp->op & 0xf0) == 0)
  347. {
  348. auto prev = cp;
  349. if(! bi_.fill(prev->bits + prev->op, r.in.next, r.in.last))
  350. return done();
  351. bi_.peek(v, prev->bits + prev->op);
  352. cp = &lencode_[prev->val + (v >> prev->bits)];
  353. bi_.drop(prev->bits + cp->bits);
  354. back_ += prev->bits + cp->bits;
  355. }
  356. else
  357. {
  358. bi_.drop(cp->bits);
  359. back_ += cp->bits;
  360. }
  361. length_ = cp->val;
  362. if(cp->op == 0)
  363. {
  364. mode_ = LIT;
  365. break;
  366. }
  367. if(cp->op & 32)
  368. {
  369. back_ = -1;
  370. mode_ = TYPE;
  371. break;
  372. }
  373. if(cp->op & 64)
  374. return err(error::invalid_literal_length);
  375. extra_ = cp->op & 15;
  376. mode_ = LENEXT;
  377. BOOST_FALLTHROUGH;
  378. }
  379. case LENEXT:
  380. if(extra_)
  381. {
  382. if(! bi_.fill(extra_, r.in.next, r.in.last))
  383. return done();
  384. std::uint16_t v;
  385. bi_.read(v, extra_);
  386. length_ += v;
  387. back_ += extra_;
  388. }
  389. was_ = length_;
  390. mode_ = DIST;
  391. BOOST_FALLTHROUGH;
  392. case DIST:
  393. {
  394. if(! bi_.fill(distbits_, r.in.next, r.in.last))
  395. return done();
  396. std::uint16_t v;
  397. bi_.peek(v, distbits_);
  398. auto cp = &distcode_[v];
  399. if((cp->op & 0xf0) == 0)
  400. {
  401. auto prev = cp;
  402. if(! bi_.fill(prev->bits + prev->op, r.in.next, r.in.last))
  403. return done();
  404. bi_.peek(v, prev->bits + prev->op);
  405. cp = &distcode_[prev->val + (v >> prev->bits)];
  406. bi_.drop(prev->bits + cp->bits);
  407. back_ += prev->bits + cp->bits;
  408. }
  409. else
  410. {
  411. bi_.drop(cp->bits);
  412. back_ += cp->bits;
  413. }
  414. if(cp->op & 64)
  415. return err(error::invalid_distance_code);
  416. offset_ = cp->val;
  417. extra_ = cp->op & 15;
  418. mode_ = DISTEXT;
  419. BOOST_FALLTHROUGH;
  420. }
  421. case DISTEXT:
  422. if(extra_)
  423. {
  424. std::uint16_t v;
  425. if(! bi_.fill(extra_, r.in.next, r.in.last))
  426. return done();
  427. bi_.read(v, extra_);
  428. offset_ += v;
  429. back_ += extra_;
  430. }
  431. #ifdef INFLATE_STRICT
  432. if(offset_ > dmax_)
  433. return err(error::invalid_distance);
  434. #endif
  435. mode_ = MATCH;
  436. BOOST_FALLTHROUGH;
  437. case MATCH:
  438. {
  439. if(! r.out.avail())
  440. return done();
  441. if(offset_ > r.out.used())
  442. {
  443. // copy from window
  444. auto offset = static_cast<std::uint16_t>(
  445. offset_ - r.out.used());
  446. if(offset > w_.size())
  447. return err(error::invalid_distance);
  448. auto const n = clamp(clamp(
  449. length_, offset), r.out.avail());
  450. w_.read(r.out.next, offset, n);
  451. r.out.next += n;
  452. length_ -= n;
  453. }
  454. else
  455. {
  456. // copy from output
  457. auto in = r.out.next - offset_;
  458. auto n = clamp(length_, r.out.avail());
  459. length_ -= n;
  460. while(n--)
  461. *r.out.next++ = *in++;
  462. }
  463. if(length_ == 0)
  464. mode_ = LEN;
  465. break;
  466. }
  467. case LIT:
  468. {
  469. if(! r.out.avail())
  470. return done();
  471. auto const v = static_cast<std::uint8_t>(length_);
  472. *r.out.next++ = v;
  473. mode_ = LEN;
  474. break;
  475. }
  476. case CHECK:
  477. mode_ = DONE;
  478. BOOST_FALLTHROUGH;
  479. case DONE:
  480. ec = error::end_of_stream;
  481. return done();
  482. case BAD:
  483. return done();
  484. case SYNC:
  485. default:
  486. BOOST_THROW_EXCEPTION(std::logic_error{
  487. "stream error"});
  488. }
  489. }
  490. }
  491. //------------------------------------------------------------------------------
  492. /* Build a set of tables to decode the provided canonical Huffman code.
  493. The code lengths are lens[0..codes-1]. The result starts at *table,
  494. whose indices are 0..2^bits-1. work is a writable array of at least
  495. lens shorts, which is used as a work area. type is the type of code
  496. to be generated, build::codes, build::lens, or build::dists. On
  497. return, zero is success, -1 is an invalid code, and +1 means that
  498. kEnough isn't enough. table on return points to the next available
  499. entry's address. bits is the requested root table index bits, and
  500. on return it is the actual root table index bits. It will differ if
  501. the request is greater than the longest code or if it is less than
  502. the shortest code.
  503. */
  504. void
  505. inflate_stream::
  506. inflate_table(
  507. build type,
  508. std::uint16_t* lens,
  509. std::size_t codes,
  510. code** table,
  511. unsigned *bits,
  512. std::uint16_t* work,
  513. error_code& ec)
  514. {
  515. unsigned len; // a code's length in bits
  516. unsigned sym; // index of code symbols
  517. unsigned min, max; // minimum and maximum code lengths
  518. unsigned root; // number of index bits for root table
  519. unsigned curr; // number of index bits for current table
  520. unsigned drop; // code bits to drop for sub-table
  521. int left; // number of prefix codes available
  522. unsigned used; // code entries in table used
  523. unsigned huff; // Huffman code
  524. unsigned incr; // for incrementing code, index
  525. unsigned fill; // index for replicating entries
  526. unsigned low; // low bits for current root entry
  527. unsigned mask; // mask for low root bits
  528. code here; // table entry for duplication
  529. code *next; // next available space in table
  530. std::uint16_t const* base; // base value table to use
  531. std::uint16_t const* extra; // extra bits table to use
  532. int end; // use base and extra for symbol > end
  533. std::uint16_t count[15+1]; // number of codes of each length
  534. std::uint16_t offs[15+1]; // offsets in table for each length
  535. // Length codes 257..285 base
  536. static std::uint16_t constexpr lbase[31] = {
  537. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  538. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  539. // Length codes 257..285 extra
  540. static std::uint16_t constexpr lext[31] = {
  541. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  542. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78};
  543. // Distance codes 0..29 base
  544. static std::uint16_t constexpr dbase[32] = {
  545. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  546. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  547. 8193, 12289, 16385, 24577, 0, 0};
  548. // Distance codes 0..29 extra
  549. static std::uint16_t constexpr dext[32] = {
  550. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  551. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  552. 28, 28, 29, 29, 64, 64};
  553. /*
  554. Process a set of code lengths to create a canonical Huffman code. The
  555. code lengths are lens[0..codes-1]. Each length corresponds to the
  556. symbols 0..codes-1. The Huffman code is generated by first sorting the
  557. symbols by length from short to long, and retaining the symbol order
  558. for codes with equal lengths. Then the code starts with all zero bits
  559. for the first code of the shortest length, and the codes are integer
  560. increments for the same length, and zeros are appended as the length
  561. increases. For the deflate format, these bits are stored backwards
  562. from their more natural integer increment ordering, and so when the
  563. decoding tables are built in the large loop below, the integer codes
  564. are incremented backwards.
  565. This routine assumes, but does not check, that all of the entries in
  566. lens[] are in the range 0..15. The caller must assure this.
  567. 1..15 is interpreted as that code length. zero means that that
  568. symbol does not occur in this code.
  569. The codes are sorted by computing a count of codes for each length,
  570. creating from that a table of starting indices for each length in the
  571. sorted table, and then entering the symbols in order in the sorted
  572. table. The sorted table is work[], with that space being provided by
  573. the caller.
  574. The length counts are used for other purposes as well, i.e. finding
  575. the minimum and maximum length codes, determining if there are any
  576. codes at all, checking for a valid set of lengths, and looking ahead
  577. at length counts to determine sub-table sizes when building the
  578. decoding tables.
  579. */
  580. /* accumulate lengths for codes (assumes lens[] all in 0..15) */
  581. for (len = 0; len <= 15; len++)
  582. count[len] = 0;
  583. for (sym = 0; sym < codes; sym++)
  584. count[lens[sym]]++;
  585. /* bound code lengths, force root to be within code lengths */
  586. root = *bits;
  587. for (max = 15; max >= 1; max--)
  588. if (count[max] != 0)
  589. break;
  590. if (root > max)
  591. root = max;
  592. if (max == 0)
  593. { /* no symbols to code at all */
  594. here.op = (std::uint8_t)64; /* invalid code marker */
  595. here.bits = (std::uint8_t)1;
  596. here.val = (std::uint16_t)0;
  597. *(*table)++ = here; /* make a table to force an error */
  598. *(*table)++ = here;
  599. *bits = 1;
  600. return; /* no symbols, but wait for decoding to report error */
  601. }
  602. for (min = 1; min < max; min++)
  603. if (count[min] != 0)
  604. break;
  605. if (root < min)
  606. root = min;
  607. /* check for an over-subscribed or incomplete set of lengths */
  608. left = 1;
  609. for (len = 1; len <= 15; len++)
  610. {
  611. left <<= 1;
  612. left -= count[len];
  613. if (left < 0)
  614. {
  615. ec = error::over_subscribed_length;
  616. return;
  617. }
  618. }
  619. if (left > 0 && (type == build::codes || max != 1))
  620. {
  621. ec = error::incomplete_length_set;
  622. return;
  623. }
  624. /* generate offsets into symbol table for each length for sorting */
  625. offs[1] = 0;
  626. for (len = 1; len < 15; len++)
  627. offs[len + 1] = offs[len] + count[len];
  628. /* sort symbols by length, by symbol order within each length */
  629. for (sym = 0; sym < codes; sym++)
  630. if (lens[sym] != 0)
  631. work[offs[lens[sym]]++] = (std::uint16_t)sym;
  632. /*
  633. Create and fill in decoding tables. In this loop, the table being
  634. filled is at next and has curr index bits. The code being used is huff
  635. with length len. That code is converted to an index by dropping drop
  636. bits off of the bottom. For codes where len is less than drop + curr,
  637. those top drop + curr - len bits are incremented through all values to
  638. fill the table with replicated entries.
  639. root is the number of index bits for the root table. When len exceeds
  640. root, sub-tables are created pointed to by the root entry with an index
  641. of the low root bits of huff. This is saved in low to check for when a
  642. new sub-table should be started. drop is zero when the root table is
  643. being filled, and drop is root when sub-tables are being filled.
  644. When a new sub-table is needed, it is necessary to look ahead in the
  645. code lengths to determine what size sub-table is needed. The length
  646. counts are used for this, and so count[] is decremented as codes are
  647. entered in the tables.
  648. used keeps track of how many table entries have been allocated from the
  649. provided *table space. It is checked for build::lens and DIST tables against
  650. the constants kEnoughLens and kEnoughDists to guard against changes in
  651. the initial root table size constants. See the comments in inftrees.hpp
  652. for more information.
  653. sym increments through all symbols, and the loop terminates when
  654. all codes of length max, i.e. all codes, have been processed. This
  655. routine permits incomplete codes, so another loop after this one fills
  656. in the rest of the decoding tables with invalid code markers.
  657. */
  658. /* set up for code type */
  659. switch (type)
  660. {
  661. case build::codes:
  662. base = extra = work; /* dummy value--not used */
  663. end = 19;
  664. break;
  665. case build::lens:
  666. base = lbase;
  667. base -= 257;
  668. extra = lext;
  669. extra -= 257;
  670. end = 256;
  671. break;
  672. default: /* build::dists */
  673. base = dbase;
  674. extra = dext;
  675. end = -1;
  676. }
  677. /* initialize state for loop */
  678. huff = 0; /* starting code */
  679. sym = 0; /* starting code symbol */
  680. len = min; /* starting code length */
  681. next = *table; /* current table to fill in */
  682. curr = root; /* current table index bits */
  683. drop = 0; /* current bits to drop from code for index */
  684. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  685. used = 1U << root; /* use root table entries */
  686. mask = used - 1; /* mask for comparing low */
  687. auto const not_enough = []
  688. {
  689. BOOST_THROW_EXCEPTION(std::logic_error{
  690. "insufficient output size when inflating tables"});
  691. };
  692. // check available table space
  693. if ((type == build::lens && used > kEnoughLens) ||
  694. (type == build::dists && used > kEnoughDists))
  695. return not_enough();
  696. /* process all codes and make table entries */
  697. for (;;)
  698. {
  699. /* create table entry */
  700. here.bits = (std::uint8_t)(len - drop);
  701. if ((int)(work[sym]) < end)
  702. {
  703. here.op = (std::uint8_t)0;
  704. here.val = work[sym];
  705. }
  706. else if ((int)(work[sym]) > end)
  707. {
  708. here.op = (std::uint8_t)(extra[work[sym]]);
  709. here.val = base[work[sym]];
  710. }
  711. else
  712. {
  713. here.op = (std::uint8_t)(32 + 64); /* end of block */
  714. here.val = 0;
  715. }
  716. /* replicate for those indices with low len bits equal to huff */
  717. incr = 1U << (len - drop);
  718. fill = 1U << curr;
  719. min = fill; /* save offset to next table */
  720. do
  721. {
  722. fill -= incr;
  723. next[(huff >> drop) + fill] = here;
  724. } while (fill != 0);
  725. /* backwards increment the len-bit code huff */
  726. incr = 1U << (len - 1);
  727. while (huff & incr)
  728. incr >>= 1;
  729. if (incr != 0)
  730. {
  731. huff &= incr - 1;
  732. huff += incr;
  733. }
  734. else
  735. huff = 0;
  736. /* go to next symbol, update count, len */
  737. sym++;
  738. if (--(count[len]) == 0)
  739. {
  740. if (len == max) break;
  741. len = lens[work[sym]];
  742. }
  743. /* create new sub-table if needed */
  744. if (len > root && (huff & mask) != low)
  745. {
  746. /* if first time, transition to sub-tables */
  747. if (drop == 0)
  748. drop = root;
  749. /* increment past last table */
  750. next += min; /* here min is 1 << curr */
  751. /* determine length of next table */
  752. curr = len - drop;
  753. left = (int)(1 << curr);
  754. while (curr + drop < max)
  755. {
  756. left -= count[curr + drop];
  757. if (left <= 0) break;
  758. curr++;
  759. left <<= 1;
  760. }
  761. /* check for enough space */
  762. used += 1U << curr;
  763. if ((type == build::lens && used > kEnoughLens) ||
  764. (type == build::dists && used > kEnoughDists))
  765. return not_enough();
  766. /* point entry in root table to sub-table */
  767. low = huff & mask;
  768. (*table)[low].op = (std::uint8_t)curr;
  769. (*table)[low].bits = (std::uint8_t)root;
  770. (*table)[low].val = (std::uint16_t)(next - *table);
  771. }
  772. }
  773. /* fill in remaining table entry if code is incomplete (guaranteed to have
  774. at most one remaining entry, since if the code is incomplete, the
  775. maximum code length that was allowed to get this far is one bit) */
  776. if (huff != 0)
  777. {
  778. here.op = 64; // invalid code marker
  779. here.bits = (std::uint8_t)(len - drop);
  780. here.val = 0;
  781. next[huff] = here;
  782. }
  783. *table += used;
  784. *bits = root;
  785. }
  786. auto
  787. inflate_stream::
  788. get_fixed_tables() ->
  789. codes const&
  790. {
  791. struct fixed_codes : codes
  792. {
  793. code len_[512];
  794. code dist_[32];
  795. fixed_codes()
  796. {
  797. lencode = len_;
  798. lenbits = 9;
  799. distcode = dist_;
  800. distbits = 5;
  801. std::uint16_t lens[320];
  802. std::uint16_t work[288];
  803. std::fill(&lens[ 0], &lens[144], std::uint16_t{8});
  804. std::fill(&lens[144], &lens[256], std::uint16_t{9});
  805. std::fill(&lens[256], &lens[280], std::uint16_t{7});
  806. std::fill(&lens[280], &lens[288], std::uint16_t{8});
  807. {
  808. error_code ec;
  809. auto next = &len_[0];
  810. inflate_table(build::lens,
  811. lens, 288, &next, &lenbits, work, ec);
  812. if(ec)
  813. BOOST_THROW_EXCEPTION(std::logic_error{ec.message()});
  814. }
  815. // VFALCO These fixups are from ZLib
  816. len_[ 99].op = 64;
  817. len_[227].op = 64;
  818. len_[355].op = 64;
  819. len_[483].op = 64;
  820. {
  821. error_code ec;
  822. auto next = &dist_[0];
  823. std::fill(&lens[0], &lens[32], std::uint16_t{5});
  824. inflate_table(build::dists,
  825. lens, 32, &next, &distbits, work, ec);
  826. if(ec)
  827. BOOST_THROW_EXCEPTION(std::logic_error{ec.message()});
  828. }
  829. }
  830. };
  831. static fixed_codes const fc;
  832. return fc;
  833. }
  834. void
  835. inflate_stream::
  836. fixedTables()
  837. {
  838. auto const fc = get_fixed_tables();
  839. lencode_ = fc.lencode;
  840. lenbits_ = fc.lenbits;
  841. distcode_ = fc.distcode;
  842. distbits_ = fc.distbits;
  843. }
  844. /*
  845. Decode literal, length, and distance codes and write out the resulting
  846. literal and match bytes until either not enough input or output is
  847. available, an end-of-block is encountered, or a data error is encountered.
  848. When large enough input and output buffers are supplied to inflate(), for
  849. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  850. inflate execution time is spent in this routine.
  851. Entry assumptions:
  852. state->mode_ == LEN
  853. zs.avail_in >= 6
  854. zs.avail_out >= 258
  855. start >= zs.avail_out
  856. state->bits_ < 8
  857. On return, state->mode_ is one of:
  858. LEN -- ran out of enough output space or enough available input
  859. TYPE -- reached end of block code, inflate() to interpret next block
  860. BAD -- error in block data
  861. Notes:
  862. - The maximum input bits used by a length/distance pair is 15 bits for the
  863. length code, 5 bits for the length extra, 15 bits for the distance code,
  864. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  865. Therefore if zs.avail_in >= 6, then there is enough input to avoid
  866. checking for available input while decoding.
  867. - The maximum bytes that a single length/distance pair can output is 258
  868. bytes, which is the maximum length that can be coded. inflate_fast()
  869. requires zs.avail_out >= 258 for each loop to avoid checking for
  870. output space.
  871. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  872. - Using bit fields for code structure
  873. - Different op definition to avoid & for extra bits (do & for table bits)
  874. - Three separate decoding do-loops for direct, window, and wnext == 0
  875. - Special case for distance > 1 copies to do overlapped load and store copy
  876. - Explicit branch predictions (based on measured branch probabilities)
  877. - Deferring match copy and interspersed it with decoding subsequent codes
  878. - Swapping literal/length else
  879. - Swapping window/direct else
  880. - Larger unrolled copy loops (three is about right)
  881. - Moving len -= 3 statement into middle of loop
  882. */
  883. void
  884. inflate_stream::
  885. inflate_fast(ranges& r, error_code& ec)
  886. {
  887. unsigned char const* last; // have enough input while in < last
  888. unsigned char *end; // while out < end, enough space available
  889. std::size_t op; // code bits, operation, extra bits, or window position, window bytes to copy
  890. unsigned len; // match length, unused bytes
  891. unsigned dist; // match distance
  892. unsigned const lmask =
  893. (1U << lenbits_) - 1; // mask for first level of length codes
  894. unsigned const dmask =
  895. (1U << distbits_) - 1; // mask for first level of distance codes
  896. last = r.in.next + (r.in.avail() - 5);
  897. end = r.out.next + (r.out.avail() - 257);
  898. /* decode literals and length/distances until end-of-block or not enough
  899. input data or output space */
  900. do
  901. {
  902. if(bi_.size() < 15)
  903. bi_.fill_16(r.in.next);
  904. auto cp = &lencode_[bi_.peek_fast() & lmask];
  905. dolen:
  906. bi_.drop(cp->bits);
  907. op = (unsigned)(cp->op);
  908. if(op == 0)
  909. {
  910. // literal
  911. *r.out.next++ = (unsigned char)(cp->val);
  912. }
  913. else if(op & 16)
  914. {
  915. // length base
  916. len = (unsigned)(cp->val);
  917. op &= 15; // number of extra bits
  918. if(op)
  919. {
  920. if(bi_.size() < op)
  921. bi_.fill_8(r.in.next);
  922. len += (unsigned)bi_.peek_fast() & ((1U << op) - 1);
  923. bi_.drop(op);
  924. }
  925. if(bi_.size() < 15)
  926. bi_.fill_16(r.in.next);
  927. cp = &distcode_[bi_.peek_fast() & dmask];
  928. dodist:
  929. bi_.drop(cp->bits);
  930. op = (unsigned)(cp->op);
  931. if(op & 16)
  932. {
  933. // distance base
  934. dist = (unsigned)(cp->val);
  935. op &= 15; // number of extra bits
  936. if(bi_.size() < op)
  937. {
  938. bi_.fill_8(r.in.next);
  939. if(bi_.size() < op)
  940. bi_.fill_8(r.in.next);
  941. }
  942. dist += (unsigned)bi_.peek_fast() & ((1U << op) - 1);
  943. #ifdef INFLATE_STRICT
  944. if(dist > dmax_)
  945. {
  946. ec = error::invalid_distance;
  947. mode_ = BAD;
  948. break;
  949. }
  950. #endif
  951. bi_.drop(op);
  952. op = r.out.used();
  953. if(dist > op)
  954. {
  955. // copy from window
  956. op = dist - op; // distance back in window
  957. if(op > w_.size())
  958. {
  959. ec = error::invalid_distance;
  960. mode_ = BAD;
  961. break;
  962. }
  963. auto const n = clamp(len, op);
  964. w_.read(r.out.next, op, n);
  965. r.out.next += n;
  966. len -= n;
  967. }
  968. if(len > 0)
  969. {
  970. // copy from output
  971. auto in = r.out.next - dist;
  972. auto n = clamp(len, r.out.avail());
  973. len -= n;
  974. while(n--)
  975. *r.out.next++ = *in++;
  976. }
  977. }
  978. else if((op & 64) == 0)
  979. {
  980. // 2nd level distance code
  981. cp = &distcode_[cp->val + (bi_.peek_fast() & ((1U << op) - 1))];
  982. goto dodist;
  983. }
  984. else
  985. {
  986. ec = error::invalid_distance_code;
  987. mode_ = BAD;
  988. break;
  989. }
  990. }
  991. else if((op & 64) == 0)
  992. {
  993. // 2nd level length code
  994. cp = &lencode_[cp->val + (bi_.peek_fast() & ((1U << op) - 1))];
  995. goto dolen;
  996. }
  997. else if(op & 32)
  998. {
  999. // end-of-block
  1000. mode_ = TYPE;
  1001. break;
  1002. }
  1003. else
  1004. {
  1005. ec = error::invalid_literal_length;
  1006. mode_ = BAD;
  1007. break;
  1008. }
  1009. }
  1010. while(r.in.next < last && r.out.next < end);
  1011. // return unused bytes (on entry, bits < 8, so in won't go too far back)
  1012. bi_.rewind(r.in.next);
  1013. }
  1014. } // detail
  1015. } // zlib
  1016. } // beast
  1017. } // boost
  1018. #endif