Symbolication.cpp 8.9 KB

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