inflate_stream.ipp 37 KB

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