process_reader_linux.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. // Copyright 2017 The Crashpad Authors. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "snapshot/linux/process_reader_linux.h"
  15. #include <elf.h>
  16. #include <errno.h>
  17. #include <sched.h>
  18. #include <string.h>
  19. #include <sys/resource.h>
  20. #include <unistd.h>
  21. #include <algorithm>
  22. #include "base/logging.h"
  23. #include "base/strings/stringprintf.h"
  24. #include "build/build_config.h"
  25. #include "snapshot/linux/debug_rendezvous.h"
  26. #include "util/linux/auxiliary_vector.h"
  27. #include "util/linux/proc_stat_reader.h"
  28. #if BUILDFLAG(IS_ANDROID)
  29. #include <android/api-level.h>
  30. #endif
  31. namespace crashpad {
  32. namespace {
  33. bool ShouldMergeStackMappings(const MemoryMap::Mapping& stack_mapping,
  34. const MemoryMap::Mapping& adj_mapping) {
  35. DCHECK(stack_mapping.readable);
  36. return adj_mapping.readable && stack_mapping.device == adj_mapping.device &&
  37. stack_mapping.inode == adj_mapping.inode &&
  38. (stack_mapping.name == adj_mapping.name ||
  39. stack_mapping.name.empty() || adj_mapping.name.empty());
  40. }
  41. } // namespace
  42. ProcessReaderLinux::Thread::Thread()
  43. : thread_info(),
  44. stack_region_address(0),
  45. stack_region_size(0),
  46. name(),
  47. tid(-1),
  48. static_priority(-1),
  49. nice_value(-1) {}
  50. ProcessReaderLinux::Thread::~Thread() {}
  51. bool ProcessReaderLinux::Thread::InitializePtrace(
  52. PtraceConnection* connection) {
  53. if (!connection->GetThreadInfo(tid, &thread_info)) {
  54. return false;
  55. }
  56. // From man proc(5):
  57. //
  58. // /proc/[pid]/comm (since Linux 2.6.33)
  59. //
  60. // Different threads in the same process may have different comm values,
  61. // accessible via /proc/[pid]/task/[tid]/comm.
  62. const std::string path = base::StringPrintf(
  63. "/proc/%d/task/%d/comm", connection->GetProcessID(), tid);
  64. if (connection->ReadFileContents(base::FilePath(path), &name)) {
  65. if (!name.empty() && name.back() == '\n') {
  66. // Remove the final newline character.
  67. name.pop_back();
  68. }
  69. } else {
  70. // Continue on without the thread name.
  71. }
  72. // TODO(jperaza): Collect scheduling priorities via the broker when they can't
  73. // be collected directly.
  74. have_priorities = false;
  75. // TODO(jperaza): Starting with Linux 3.14, scheduling policy, static
  76. // priority, and nice value can be collected all in one call with
  77. // sched_getattr().
  78. int res = sched_getscheduler(tid);
  79. if (res < 0) {
  80. PLOG(WARNING) << "sched_getscheduler";
  81. return true;
  82. }
  83. sched_policy = res;
  84. sched_param param;
  85. if (sched_getparam(tid, &param) != 0) {
  86. PLOG(WARNING) << "sched_getparam";
  87. return true;
  88. }
  89. static_priority = param.sched_priority;
  90. errno = 0;
  91. res = getpriority(PRIO_PROCESS, tid);
  92. if (res == -1 && errno) {
  93. PLOG(WARNING) << "getpriority";
  94. return true;
  95. }
  96. nice_value = res;
  97. have_priorities = true;
  98. return true;
  99. }
  100. void ProcessReaderLinux::Thread::InitializeStack(ProcessReaderLinux* reader) {
  101. LinuxVMAddress stack_pointer;
  102. #if defined(ARCH_CPU_X86_FAMILY)
  103. stack_pointer = reader->Is64Bit() ? thread_info.thread_context.t64.rsp
  104. : thread_info.thread_context.t32.esp;
  105. #elif defined(ARCH_CPU_ARM_FAMILY)
  106. stack_pointer = reader->Is64Bit() ? thread_info.thread_context.t64.sp
  107. : thread_info.thread_context.t32.sp;
  108. #elif defined(ARCH_CPU_MIPS_FAMILY)
  109. stack_pointer = reader->Is64Bit() ? thread_info.thread_context.t64.regs[29]
  110. : thread_info.thread_context.t32.regs[29];
  111. #elif defined(ARCH_CPU_RISCV_FAMILY)
  112. stack_pointer = reader->Is64Bit() ? thread_info.thread_context.t64.sp
  113. : thread_info.thread_context.t32.sp;
  114. #else
  115. #error Port.
  116. #endif
  117. InitializeStackFromSP(reader, stack_pointer);
  118. }
  119. void ProcessReaderLinux::Thread::InitializeStackFromSP(
  120. ProcessReaderLinux* reader,
  121. LinuxVMAddress stack_pointer) {
  122. const MemoryMap* memory_map = reader->GetMemoryMap();
  123. // If we can't find the mapping, it's probably a bad stack pointer
  124. const MemoryMap::Mapping* mapping = memory_map->FindMapping(stack_pointer);
  125. if (!mapping) {
  126. LOG(WARNING) << "no stack mapping";
  127. return;
  128. }
  129. LinuxVMAddress stack_region_start =
  130. reader->Memory()->PointerToAddress(stack_pointer);
  131. // We've hit what looks like a guard page; skip to the end and check for a
  132. // mapped stack region.
  133. if (!mapping->readable) {
  134. stack_region_start = mapping->range.End();
  135. mapping = memory_map->FindMapping(stack_region_start);
  136. if (!mapping) {
  137. LOG(WARNING) << "no stack mapping";
  138. return;
  139. }
  140. } else {
  141. #if defined(ARCH_CPU_X86_FAMILY)
  142. // Adjust start address to include the red zone
  143. if (reader->Is64Bit()) {
  144. constexpr LinuxVMSize kRedZoneSize = 128;
  145. LinuxVMAddress red_zone_base =
  146. stack_region_start - std::min(kRedZoneSize, stack_region_start);
  147. // Only include the red zone if it is part of a valid mapping
  148. if (red_zone_base >= mapping->range.Base()) {
  149. stack_region_start = red_zone_base;
  150. } else {
  151. const MemoryMap::Mapping* rz_mapping =
  152. memory_map->FindMapping(red_zone_base);
  153. if (rz_mapping && ShouldMergeStackMappings(*mapping, *rz_mapping)) {
  154. stack_region_start = red_zone_base;
  155. } else {
  156. stack_region_start = mapping->range.Base();
  157. }
  158. }
  159. }
  160. #endif
  161. }
  162. stack_region_address = stack_region_start;
  163. // If there are more mappings at the end of this one, they may be a
  164. // continuation of the stack.
  165. LinuxVMAddress stack_end = mapping->range.End();
  166. const MemoryMap::Mapping* next_mapping;
  167. while ((next_mapping = memory_map->FindMapping(stack_end)) &&
  168. ShouldMergeStackMappings(*mapping, *next_mapping)) {
  169. stack_end = next_mapping->range.End();
  170. }
  171. // The main thread should have an entry in the maps file just for its stack,
  172. // so we'll assume the base of the stack is at the end of the region. Other
  173. // threads' stacks may not have their own entries in the maps file if they
  174. // were user-allocated within a larger mapping, but pthreads places the TLS
  175. // at the high-address end of the stack so we can try using that to shrink
  176. // the stack region.
  177. stack_region_size = stack_end - stack_region_address;
  178. VMAddress tls_address = reader->Memory()->PointerToAddress(
  179. thread_info.thread_specific_data_address);
  180. if (tid != reader->ProcessID() && tls_address > stack_region_address &&
  181. tls_address < stack_end) {
  182. stack_region_size = tls_address - stack_region_address;
  183. }
  184. }
  185. ProcessReaderLinux::Module::Module()
  186. : name(), elf_reader(nullptr), type(ModuleSnapshot::kModuleTypeUnknown) {}
  187. ProcessReaderLinux::Module::~Module() = default;
  188. ProcessReaderLinux::ProcessReaderLinux()
  189. : connection_(),
  190. process_info_(),
  191. memory_map_(),
  192. threads_(),
  193. modules_(),
  194. elf_readers_(),
  195. is_64_bit_(false),
  196. initialized_threads_(false),
  197. initialized_modules_(false),
  198. initialized_() {}
  199. ProcessReaderLinux::~ProcessReaderLinux() {}
  200. bool ProcessReaderLinux::Initialize(PtraceConnection* connection) {
  201. INITIALIZATION_STATE_SET_INITIALIZING(initialized_);
  202. DCHECK(connection);
  203. connection_ = connection;
  204. if (!process_info_.InitializeWithPtrace(connection_)) {
  205. return false;
  206. }
  207. if (!memory_map_.Initialize(connection_)) {
  208. return false;
  209. }
  210. is_64_bit_ = process_info_.Is64Bit();
  211. INITIALIZATION_STATE_SET_VALID(initialized_);
  212. return true;
  213. }
  214. bool ProcessReaderLinux::StartTime(timeval* start_time) const {
  215. INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  216. return process_info_.StartTime(start_time);
  217. }
  218. bool ProcessReaderLinux::CPUTimes(timeval* user_time,
  219. timeval* system_time) const {
  220. INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  221. timerclear(user_time);
  222. timerclear(system_time);
  223. timeval local_user_time;
  224. timerclear(&local_user_time);
  225. timeval local_system_time;
  226. timerclear(&local_system_time);
  227. for (const Thread& thread : threads_) {
  228. ProcStatReader stat;
  229. if (!stat.Initialize(connection_, thread.tid)) {
  230. return false;
  231. }
  232. timeval thread_user_time;
  233. if (!stat.UserCPUTime(&thread_user_time)) {
  234. return false;
  235. }
  236. timeval thread_system_time;
  237. if (!stat.SystemCPUTime(&thread_system_time)) {
  238. return false;
  239. }
  240. timeradd(&local_user_time, &thread_user_time, &local_user_time);
  241. timeradd(&local_system_time, &thread_system_time, &local_system_time);
  242. }
  243. *user_time = local_user_time;
  244. *system_time = local_system_time;
  245. return true;
  246. }
  247. const std::vector<ProcessReaderLinux::Thread>& ProcessReaderLinux::Threads() {
  248. INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  249. if (!initialized_threads_) {
  250. InitializeThreads();
  251. }
  252. return threads_;
  253. }
  254. const std::vector<ProcessReaderLinux::Module>& ProcessReaderLinux::Modules() {
  255. INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  256. if (!initialized_modules_) {
  257. InitializeModules();
  258. }
  259. return modules_;
  260. }
  261. void ProcessReaderLinux::InitializeAbortMessage() {
  262. #if BUILDFLAG(IS_ANDROID)
  263. const MemoryMap::Mapping* mapping =
  264. memory_map_.FindMappingWithName("[anon:abort message]");
  265. if (!mapping) {
  266. return;
  267. }
  268. if (is_64_bit_) {
  269. ReadAbortMessage<true>(mapping);
  270. } else {
  271. ReadAbortMessage<false>(mapping);
  272. }
  273. #endif
  274. }
  275. #if BUILDFLAG(IS_ANDROID)
  276. // These structure definitions and the magic numbers below were copied from
  277. // bionic/libc/bionic/android_set_abort_message.cpp
  278. template <bool is64Bit>
  279. struct abort_msg_t {
  280. uint32_t size;
  281. char msg[0];
  282. };
  283. template <>
  284. struct abort_msg_t<true> {
  285. uint64_t size;
  286. char msg[0];
  287. };
  288. template <bool is64Bit>
  289. struct magic_abort_msg_t {
  290. uint64_t magic1;
  291. uint64_t magic2;
  292. abort_msg_t<is64Bit> msg;
  293. };
  294. template <bool is64Bit>
  295. void ProcessReaderLinux::ReadAbortMessage(const MemoryMap::Mapping* mapping) {
  296. magic_abort_msg_t<is64Bit> header;
  297. if (!Memory()->Read(
  298. mapping->range.Base(), sizeof(magic_abort_msg_t<is64Bit>), &header)) {
  299. return;
  300. }
  301. size_t size = header.msg.size - sizeof(magic_abort_msg_t<is64Bit>) - 1;
  302. if (header.magic1 != 0xb18e40886ac388f0ULL ||
  303. header.magic2 != 0xc6dfba755a1de0b5ULL ||
  304. mapping->range.Size() <
  305. offsetof(magic_abort_msg_t<is64Bit>, msg.msg) + size) {
  306. return;
  307. }
  308. abort_message_.resize(size);
  309. if (!Memory()->Read(
  310. mapping->range.Base() + offsetof(magic_abort_msg_t<is64Bit>, msg.msg),
  311. size,
  312. &abort_message_[0])) {
  313. abort_message_.clear();
  314. }
  315. }
  316. #endif // BUILDFLAG(IS_ANDROID)
  317. const std::string& ProcessReaderLinux::AbortMessage() {
  318. INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  319. if (abort_message_.empty()) {
  320. InitializeAbortMessage();
  321. }
  322. return abort_message_;
  323. }
  324. void ProcessReaderLinux::InitializeThreads() {
  325. DCHECK(threads_.empty());
  326. initialized_threads_ = true;
  327. pid_t pid = ProcessID();
  328. if (pid == getpid()) {
  329. // TODO(jperaza): ptrace can't be used on threads in the same thread group.
  330. // Using clone to create a new thread in it's own thread group doesn't work
  331. // because glibc doesn't support threads it didn't create via pthreads.
  332. // Fork a new process to snapshot us and copy the data back?
  333. LOG(ERROR) << "not implemented";
  334. return;
  335. }
  336. Thread main_thread;
  337. main_thread.tid = pid;
  338. if (main_thread.InitializePtrace(connection_)) {
  339. main_thread.InitializeStack(this);
  340. threads_.push_back(main_thread);
  341. } else {
  342. LOG(WARNING) << "Couldn't initialize main thread.";
  343. }
  344. bool main_thread_found = false;
  345. std::vector<pid_t> thread_ids;
  346. bool result = connection_->Threads(&thread_ids);
  347. DCHECK(result);
  348. for (pid_t tid : thread_ids) {
  349. if (tid == pid) {
  350. DCHECK(!main_thread_found);
  351. main_thread_found = true;
  352. continue;
  353. }
  354. Thread thread;
  355. thread.tid = tid;
  356. if (connection_->Attach(tid) && thread.InitializePtrace(connection_)) {
  357. thread.InitializeStack(this);
  358. threads_.push_back(thread);
  359. }
  360. }
  361. DCHECK(main_thread_found);
  362. }
  363. void ProcessReaderLinux::InitializeModules() {
  364. INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  365. initialized_modules_ = true;
  366. AuxiliaryVector aux;
  367. if (!aux.Initialize(connection_)) {
  368. return;
  369. }
  370. LinuxVMAddress phdrs;
  371. if (!aux.GetValue(AT_PHDR, &phdrs)) {
  372. return;
  373. }
  374. ProcessMemoryRange range;
  375. if (!range.Initialize(Memory(), is_64_bit_)) {
  376. return;
  377. }
  378. // The strategy used for identifying loaded modules depends on ELF files
  379. // conventionally loading their header and program headers into memory.
  380. // Locating the correct module could fail if the headers aren't mapped, are
  381. // mapped at an unexpected location, or if there are other mappings
  382. // constructed to look like the ELF module being searched for.
  383. const MemoryMap::Mapping* exe_mapping = nullptr;
  384. std::unique_ptr<ElfImageReader> exe_reader;
  385. {
  386. const MemoryMap::Mapping* phdr_mapping = memory_map_.FindMapping(phdrs);
  387. if (!phdr_mapping) {
  388. return;
  389. }
  390. auto possible_mappings =
  391. memory_map_.FindFilePossibleMmapStarts(*phdr_mapping);
  392. const MemoryMap::Mapping* mapping = nullptr;
  393. while ((mapping = possible_mappings->Next())) {
  394. auto parsed_exe = std::make_unique<ElfImageReader>();
  395. if (parsed_exe->Initialize(
  396. range,
  397. mapping->range.Base(),
  398. /* verbose= */ possible_mappings->Count() == 0) &&
  399. parsed_exe->GetProgramHeaderTableAddress() == phdrs) {
  400. exe_mapping = mapping;
  401. exe_reader = std::move(parsed_exe);
  402. break;
  403. }
  404. }
  405. if (!exe_mapping) {
  406. LOG(ERROR) << "no exe mappings 0x" << std::hex
  407. << phdr_mapping->range.Base();
  408. return;
  409. }
  410. }
  411. LinuxVMAddress debug_address;
  412. if (!exe_reader->GetDebugAddress(&debug_address)) {
  413. return;
  414. }
  415. DebugRendezvous debug;
  416. if (!debug.Initialize(range, debug_address)) {
  417. return;
  418. }
  419. Module exe = {};
  420. exe.name = !debug.Executable()->name.empty() ? debug.Executable()->name
  421. : exe_mapping->name;
  422. exe.elf_reader = exe_reader.get();
  423. exe.type = ModuleSnapshot::ModuleType::kModuleTypeExecutable;
  424. modules_.push_back(exe);
  425. elf_readers_.push_back(std::move(exe_reader));
  426. LinuxVMAddress loader_base = 0;
  427. aux.GetValue(AT_BASE, &loader_base);
  428. for (const DebugRendezvous::LinkEntry& entry : debug.Modules()) {
  429. const MemoryMap::Mapping* module_mapping = nullptr;
  430. std::unique_ptr<ElfImageReader> elf_reader;
  431. {
  432. const MemoryMap::Mapping* dyn_mapping =
  433. memory_map_.FindMapping(entry.dynamic_array);
  434. if (!dyn_mapping) {
  435. continue;
  436. }
  437. #if BUILDFLAG(IS_ANDROID)
  438. // Beginning at API 21, Bionic provides android_dlopen_ext() which allows
  439. // passing a file descriptor with an existing relro segment to the loader.
  440. // This means that the mapping attributes of dyn_mapping may be unrelated
  441. // to the attributes of the other mappings for the module. In this case,
  442. // search all mappings in reverse order from dyn_mapping until a module is
  443. // parsed whose dynamic address matches the value in the debug link.
  444. static int api_level = android_get_device_api_level();
  445. auto possible_mappings =
  446. (api_level >= 21 || api_level < 0)
  447. ? memory_map_.ReverseIteratorFrom(*dyn_mapping)
  448. : memory_map_.FindFilePossibleMmapStarts(*dyn_mapping);
  449. #else
  450. auto possible_mappings =
  451. memory_map_.FindFilePossibleMmapStarts(*dyn_mapping);
  452. #endif
  453. const MemoryMap::Mapping* mapping = nullptr;
  454. while ((mapping = possible_mappings->Next())) {
  455. auto parsed_module = std::make_unique<ElfImageReader>();
  456. VMAddress dynamic_address;
  457. if (parsed_module->Initialize(
  458. range,
  459. mapping->range.Base(),
  460. /* verbose= */ possible_mappings->Count() == 0) &&
  461. parsed_module->GetDynamicArrayAddress(&dynamic_address) &&
  462. dynamic_address == entry.dynamic_array) {
  463. module_mapping = mapping;
  464. elf_reader = std::move(parsed_module);
  465. break;
  466. }
  467. }
  468. if (!module_mapping) {
  469. LOG(ERROR) << "no module mappings 0x" << std::hex
  470. << dyn_mapping->range.Base();
  471. continue;
  472. }
  473. }
  474. Module module = {};
  475. std::string soname;
  476. if (elf_reader->SoName(&soname) && !soname.empty()) {
  477. module.name = soname;
  478. } else {
  479. module.name = !entry.name.empty() ? entry.name : module_mapping->name;
  480. }
  481. module.elf_reader = elf_reader.get();
  482. module.type = loader_base && elf_reader->Address() == loader_base
  483. ? ModuleSnapshot::kModuleTypeDynamicLoader
  484. : ModuleSnapshot::kModuleTypeSharedLibrary;
  485. modules_.push_back(module);
  486. elf_readers_.push_back(std::move(elf_reader));
  487. }
  488. }
  489. } // namespace crashpad