vpd_decode.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * vpd_decode.c
  4. *
  5. * Google VPD decoding routines.
  6. *
  7. * Copyright 2017 Google Inc.
  8. */
  9. #include "vpd_decode.h"
  10. static int vpd_decode_len(const u32 max_len, const u8 *in,
  11. u32 *length, u32 *decoded_len)
  12. {
  13. u8 more;
  14. int i = 0;
  15. if (!length || !decoded_len)
  16. return VPD_FAIL;
  17. *length = 0;
  18. do {
  19. if (i >= max_len)
  20. return VPD_FAIL;
  21. more = in[i] & 0x80;
  22. *length <<= 7;
  23. *length |= in[i] & 0x7f;
  24. ++i;
  25. } while (more);
  26. *decoded_len = i;
  27. return VPD_OK;
  28. }
  29. static int vpd_decode_entry(const u32 max_len, const u8 *input_buf,
  30. u32 *_consumed, const u8 **entry, u32 *entry_len)
  31. {
  32. u32 decoded_len;
  33. u32 consumed = *_consumed;
  34. if (vpd_decode_len(max_len - consumed, &input_buf[consumed],
  35. entry_len, &decoded_len) != VPD_OK)
  36. return VPD_FAIL;
  37. if (max_len - consumed < decoded_len)
  38. return VPD_FAIL;
  39. consumed += decoded_len;
  40. *entry = input_buf + consumed;
  41. /* entry_len is untrusted data and must be checked again. */
  42. if (max_len - consumed < *entry_len)
  43. return VPD_FAIL;
  44. consumed += *entry_len;
  45. *_consumed = consumed;
  46. return VPD_OK;
  47. }
  48. int vpd_decode_string(const u32 max_len, const u8 *input_buf, u32 *consumed,
  49. vpd_decode_callback callback, void *callback_arg)
  50. {
  51. int type;
  52. u32 key_len;
  53. u32 value_len;
  54. const u8 *key;
  55. const u8 *value;
  56. /* type */
  57. if (*consumed >= max_len)
  58. return VPD_FAIL;
  59. type = input_buf[*consumed];
  60. switch (type) {
  61. case VPD_TYPE_INFO:
  62. case VPD_TYPE_STRING:
  63. (*consumed)++;
  64. if (vpd_decode_entry(max_len, input_buf, consumed, &key,
  65. &key_len) != VPD_OK)
  66. return VPD_FAIL;
  67. if (vpd_decode_entry(max_len, input_buf, consumed, &value,
  68. &value_len) != VPD_OK)
  69. return VPD_FAIL;
  70. if (type == VPD_TYPE_STRING)
  71. return callback(key, key_len, value, value_len,
  72. callback_arg);
  73. break;
  74. default:
  75. return VPD_FAIL;
  76. }
  77. return VPD_OK;
  78. }