vpd_decode.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*
  2. * vpd_decode.c
  3. *
  4. * Google VPD decoding routines.
  5. *
  6. * Copyright 2017 Google Inc.
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License v2.0 as published by
  10. * the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. */
  17. #include <linux/export.h>
  18. #include "vpd_decode.h"
  19. static int vpd_decode_len(const u32 max_len, const u8 *in,
  20. u32 *length, u32 *decoded_len)
  21. {
  22. u8 more;
  23. int i = 0;
  24. if (!length || !decoded_len)
  25. return VPD_FAIL;
  26. *length = 0;
  27. do {
  28. if (i >= max_len)
  29. return VPD_FAIL;
  30. more = in[i] & 0x80;
  31. *length <<= 7;
  32. *length |= in[i] & 0x7f;
  33. ++i;
  34. } while (more);
  35. *decoded_len = i;
  36. return VPD_OK;
  37. }
  38. static int vpd_decode_entry(const u32 max_len, const u8 *input_buf,
  39. u32 *_consumed, const u8 **entry, u32 *entry_len)
  40. {
  41. u32 decoded_len;
  42. u32 consumed = *_consumed;
  43. if (vpd_decode_len(max_len - consumed, &input_buf[consumed],
  44. entry_len, &decoded_len) != VPD_OK)
  45. return VPD_FAIL;
  46. if (max_len - consumed < decoded_len)
  47. return VPD_FAIL;
  48. consumed += decoded_len;
  49. *entry = input_buf + consumed;
  50. /* entry_len is untrusted data and must be checked again. */
  51. if (max_len - consumed < *entry_len)
  52. return VPD_FAIL;
  53. consumed += *entry_len;
  54. *_consumed = consumed;
  55. return VPD_OK;
  56. }
  57. int vpd_decode_string(const u32 max_len, const u8 *input_buf, u32 *consumed,
  58. vpd_decode_callback callback, void *callback_arg)
  59. {
  60. int type;
  61. u32 key_len;
  62. u32 value_len;
  63. const u8 *key;
  64. const u8 *value;
  65. /* type */
  66. if (*consumed >= max_len)
  67. return VPD_FAIL;
  68. type = input_buf[*consumed];
  69. switch (type) {
  70. case VPD_TYPE_INFO:
  71. case VPD_TYPE_STRING:
  72. (*consumed)++;
  73. if (vpd_decode_entry(max_len, input_buf, consumed, &key,
  74. &key_len) != VPD_OK)
  75. return VPD_FAIL;
  76. if (vpd_decode_entry(max_len, input_buf, consumed, &value,
  77. &value_len) != VPD_OK)
  78. return VPD_FAIL;
  79. if (type == VPD_TYPE_STRING)
  80. return callback(key, key_len, value, value_len,
  81. callback_arg);
  82. break;
  83. default:
  84. return VPD_FAIL;
  85. }
  86. return VPD_OK;
  87. }