ResStringPool.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (C) 2018 Hein-Pieter van Braam
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <stdio.h>
  19. #include "ResStringPool.h"
  20. char* to_char_string(const uint8_t* data, uint32_t length) {
  21. char* string = (char*) calloc(length + 1, 1);
  22. for (int i = 0; i < length; ++i) {
  23. string[i] = *(data + (i * 2));
  24. }
  25. return string;
  26. }
  27. ResStringPool::ResStringPool() :
  28. _size(0), _strings(nullptr) {
  29. }
  30. ResStringPool::ResStringPool(const uint8_t* data) {
  31. ResStringPool_header header;
  32. uint32_t* entries;
  33. memcpy(&header, data, sizeof(ResStringPool_header));
  34. if (header.header.type != RES_STRING_POOL_TYPE) {
  35. printf("Not a ResStringPool!\n");
  36. return;
  37. }
  38. _size = header.stringCount;
  39. entries = (uint32_t*) (data + header.header.headerSize);
  40. _strings = (const char**)malloc(_size * sizeof(const char*));
  41. const uint8_t* stringdata = data + header.stringsStart;
  42. for (int i = 0; i < _size; ++i) {
  43. uint32_t offset = entries[i];
  44. size_t size = *((const uint16_t*)(stringdata + offset));
  45. if ((size & 0x8000) != 0) {
  46. offset += 2;
  47. size = ((size & 0x7FFF) << 16) | *((const uint16_t*)(stringdata + offset));
  48. }
  49. offset += 2;
  50. _strings[i] = to_char_string(stringdata + offset, size);
  51. }
  52. }
  53. const char* ResStringPool::get(int32_t index) const {
  54. if (index < 0 || index >= _size) {
  55. return nullptr;
  56. }
  57. return _strings[index];
  58. }
  59. void ResStringPool::dump() {
  60. for (int i = 0; i < _size; ++i) {
  61. printf("String %i: '%s'\n", i, _strings[i]);
  62. }
  63. }
  64. ResStringPool::~ResStringPool() {
  65. for (int i = 0; i < _size; ++i) {
  66. free((void*)_strings[i]);
  67. }
  68. free(_strings);
  69. }