Symbolication.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Checked.h>
  7. #include <AK/JsonArray.h>
  8. #include <AK/JsonObject.h>
  9. #include <AK/JsonValue.h>
  10. #include <AK/MappedFile.h>
  11. #include <LibCore/File.h>
  12. #include <LibDebug/DebugInfo.h>
  13. #include <LibSymbolication/Symbolication.h>
  14. namespace Symbolication {
  15. struct CachedELF {
  16. NonnullRefPtr<MappedFile> mapped_file;
  17. NonnullOwnPtr<Debug::DebugInfo> debug_info;
  18. NonnullOwnPtr<ELF::Image> image;
  19. };
  20. static HashMap<String, OwnPtr<CachedELF>> s_cache;
  21. enum class KernelBaseState {
  22. Uninitialized,
  23. Valid,
  24. Invalid,
  25. };
  26. static FlatPtr s_kernel_base;
  27. static KernelBaseState s_kernel_base_state = KernelBaseState::Uninitialized;
  28. Optional<FlatPtr> kernel_base()
  29. {
  30. if (s_kernel_base_state == KernelBaseState::Uninitialized) {
  31. auto file = Core::File::open("/proc/kernel_base", Core::OpenMode::ReadOnly);
  32. if (file.is_error()) {
  33. s_kernel_base_state = KernelBaseState::Invalid;
  34. return {};
  35. }
  36. auto kernel_base_str = String { file.value()->read_all(), NoChomp };
  37. #if ARCH(I386)
  38. using AddressType = u32;
  39. #else
  40. using AddressType = u64;
  41. #endif
  42. auto maybe_kernel_base = kernel_base_str.to_uint<AddressType>();
  43. if (!maybe_kernel_base.has_value()) {
  44. s_kernel_base_state = KernelBaseState::Invalid;
  45. return {};
  46. }
  47. s_kernel_base = maybe_kernel_base.value();
  48. s_kernel_base_state = KernelBaseState::Valid;
  49. }
  50. if (s_kernel_base_state == KernelBaseState::Invalid)
  51. return {};
  52. return s_kernel_base;
  53. }
  54. Optional<Symbol> symbolicate(String const& path, FlatPtr address)
  55. {
  56. if (!s_cache.contains(path)) {
  57. auto mapped_file = MappedFile::map(path);
  58. if (mapped_file.is_error()) {
  59. dbgln("Failed to map {}: {}", path, mapped_file.error().string());
  60. s_cache.set(path, {});
  61. return {};
  62. }
  63. auto elf = make<ELF::Image>(mapped_file.value()->bytes());
  64. if (!elf->is_valid()) {
  65. dbgln("ELF not valid: {}", path);
  66. s_cache.set(path, {});
  67. {};
  68. }
  69. auto cached_elf = make<CachedELF>(mapped_file.release_value(), make<Debug::DebugInfo>(*elf), move(elf));
  70. s_cache.set(path, move(cached_elf));
  71. }
  72. auto it = s_cache.find(path);
  73. VERIFY(it != s_cache.end());
  74. auto& cached_elf = it->value;
  75. if (!cached_elf)
  76. return {};
  77. u32 offset = 0;
  78. auto symbol = cached_elf->debug_info->elf().symbolicate(address, &offset);
  79. auto source_position_with_inlines = cached_elf->debug_info->get_source_position_with_inlines(address);
  80. Vector<Debug::DebugInfo::SourcePosition> positions;
  81. for (auto& position : source_position_with_inlines.inline_chain) {
  82. if (!positions.contains_slow(position))
  83. positions.append(position);
  84. }
  85. if (source_position_with_inlines.source_position.has_value() && !positions.contains_slow(source_position_with_inlines.source_position.value())) {
  86. positions.insert(0, source_position_with_inlines.source_position.value());
  87. }
  88. return Symbol {
  89. .address = address,
  90. .name = move(symbol),
  91. .offset = offset,
  92. .source_positions = move(positions),
  93. };
  94. }
  95. Vector<Symbol> symbolicate_thread(pid_t pid, pid_t tid)
  96. {
  97. struct RegionWithSymbols {
  98. FlatPtr base { 0 };
  99. size_t size { 0 };
  100. String path;
  101. };
  102. Vector<FlatPtr> stack;
  103. Vector<RegionWithSymbols> regions;
  104. if (auto maybe_kernel_base = kernel_base(); maybe_kernel_base.has_value()) {
  105. regions.append(RegionWithSymbols {
  106. .base = maybe_kernel_base.value(),
  107. .size = 0x3fffffff,
  108. .path = "/boot/Kernel.debug",
  109. });
  110. }
  111. {
  112. auto stack_path = String::formatted("/proc/{}/stacks/{}", pid, tid);
  113. auto file_or_error = Core::File::open(stack_path, Core::OpenMode::ReadOnly);
  114. if (file_or_error.is_error()) {
  115. warnln("Could not open {}: {}", stack_path, file_or_error.error());
  116. return {};
  117. }
  118. auto json = JsonValue::from_string(file_or_error.value()->read_all());
  119. if (!json.has_value() || !json.value().is_array()) {
  120. warnln("Invalid contents in {}", stack_path);
  121. return {};
  122. }
  123. stack.ensure_capacity(json.value().as_array().size());
  124. for (auto& value : json.value().as_array().values()) {
  125. stack.append(value.to_addr());
  126. }
  127. }
  128. {
  129. auto vm_path = String::formatted("/proc/{}/vm", pid);
  130. auto file_or_error = Core::File::open(vm_path, Core::OpenMode::ReadOnly);
  131. if (file_or_error.is_error()) {
  132. warnln("Could not open {}: {}", vm_path, file_or_error.error());
  133. return {};
  134. }
  135. auto json = JsonValue::from_string(file_or_error.value()->read_all());
  136. if (!json.has_value() || !json.value().is_array()) {
  137. warnln("Invalid contents in {}", vm_path);
  138. return {};
  139. }
  140. for (auto& region_value : json.value().as_array().values()) {
  141. auto& region = region_value.as_object();
  142. auto name = region.get("name").to_string();
  143. auto address = region.get("address").to_addr();
  144. auto size = region.get("size").to_addr();
  145. String path;
  146. if (name == "/usr/lib/Loader.so") {
  147. path = name;
  148. } else if (name.ends_with(": .text")) {
  149. auto parts = name.split_view(':');
  150. path = parts[0];
  151. if (!path.starts_with('/'))
  152. path = String::formatted("/usr/lib/{}", path);
  153. } else {
  154. continue;
  155. }
  156. RegionWithSymbols r;
  157. r.base = address;
  158. r.size = size;
  159. r.path = path;
  160. regions.append(move(r));
  161. }
  162. }
  163. Vector<Symbol> symbols;
  164. bool first_frame = true;
  165. for (auto address : stack) {
  166. const RegionWithSymbols* found_region = nullptr;
  167. for (auto& region : regions) {
  168. FlatPtr region_end;
  169. if (Checked<FlatPtr>::addition_would_overflow(region.base, region.size))
  170. region_end = NumericLimits<FlatPtr>::max();
  171. else
  172. region_end = region.base + region.size;
  173. if (address >= region.base && address < region_end) {
  174. found_region = &region;
  175. break;
  176. }
  177. }
  178. if (!found_region) {
  179. outln("{:p} ??", address);
  180. continue;
  181. }
  182. FlatPtr adjusted_address = address - found_region->base;
  183. // We're subtracting 1 from the address because this is the return address,
  184. // i.e. it is one instruction past the call instruction.
  185. // However, because the first frame represents the current
  186. // instruction pointer rather than the return address we don't
  187. // subtract 1 for that.
  188. auto result = symbolicate(found_region->path, adjusted_address - (first_frame ? 0 : 1));
  189. first_frame = false;
  190. if (!result.has_value()) {
  191. symbols.append(Symbol {
  192. .address = address,
  193. .source_positions = {},
  194. });
  195. continue;
  196. }
  197. symbols.append(result.value());
  198. }
  199. return symbols;
  200. }
  201. }