vli_decoder.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // SPDX-License-Identifier: 0BSD
  2. ///////////////////////////////////////////////////////////////////////////////
  3. //
  4. /// \file vli_decoder.c
  5. /// \brief Decodes variable-length integers
  6. //
  7. // Author: Lasse Collin
  8. //
  9. ///////////////////////////////////////////////////////////////////////////////
  10. #include "common.h"
  11. extern LZMA_API(lzma_ret)
  12. lzma_vli_decode(lzma_vli *restrict vli, size_t *vli_pos,
  13. const uint8_t *restrict in, size_t *restrict in_pos,
  14. size_t in_size)
  15. {
  16. // If we haven't been given vli_pos, work in single-call mode.
  17. size_t vli_pos_internal = 0;
  18. if (vli_pos == NULL) {
  19. vli_pos = &vli_pos_internal;
  20. *vli = 0;
  21. // If there's no input, use LZMA_DATA_ERROR. This way it is
  22. // easy to decode VLIs from buffers that have known size,
  23. // and get the correct error code in case the buffer is
  24. // too short.
  25. if (*in_pos >= in_size)
  26. return LZMA_DATA_ERROR;
  27. } else {
  28. // Initialize *vli when starting to decode a new integer.
  29. if (*vli_pos == 0)
  30. *vli = 0;
  31. // Validate the arguments.
  32. if (*vli_pos >= LZMA_VLI_BYTES_MAX
  33. || (*vli >> (*vli_pos * 7)) != 0)
  34. return LZMA_PROG_ERROR;;
  35. if (*in_pos >= in_size)
  36. return LZMA_BUF_ERROR;
  37. }
  38. do {
  39. // Read the next byte. Use a temporary variable so that we
  40. // can update *in_pos immediately.
  41. const uint8_t byte = in[*in_pos];
  42. ++*in_pos;
  43. // Add the newly read byte to *vli.
  44. *vli += (lzma_vli)(byte & 0x7F) << (*vli_pos * 7);
  45. ++*vli_pos;
  46. // Check if this is the last byte of a multibyte integer.
  47. if ((byte & 0x80) == 0) {
  48. // We don't allow using variable-length integers as
  49. // padding i.e. the encoding must use the most the
  50. // compact form.
  51. if (byte == 0x00 && *vli_pos > 1)
  52. return LZMA_DATA_ERROR;
  53. return vli_pos == &vli_pos_internal
  54. ? LZMA_OK : LZMA_STREAM_END;
  55. }
  56. // There is at least one more byte coming. If we have already
  57. // read maximum number of bytes, the integer is considered
  58. // corrupt.
  59. //
  60. // If we need bigger integers in future, old versions liblzma
  61. // will confusingly indicate the file being corrupt instead of
  62. // unsupported. I suppose it's still better this way, because
  63. // in the foreseeable future (writing this in 2008) the only
  64. // reason why files would appear having over 63-bit integers
  65. // is that the files are simply corrupt.
  66. if (*vli_pos == LZMA_VLI_BYTES_MAX)
  67. return LZMA_DATA_ERROR;
  68. } while (*in_pos < in_size);
  69. return vli_pos == &vli_pos_internal ? LZMA_DATA_ERROR : LZMA_OK;
  70. }