| 6 |
| 7 | #include <mach-o/compact_unwind_encoding.h> |
| 8 | #include <mach/mach.h> |
| 9 | #include <mach/vm_map.h> |
| 10 | #include <sys/ptrace.h> |
| 11 |
| 12 | #include "base/logging.h" |
| 13 | #include "base/profiler/module_cache.h" |
| 14 | #include "base/profiler/native_unwinder.h" |
| 15 | #include "base/profiler/profile_builder.h" |
| 16 |
| 17 | extern "C" { |
| 18 | void _sigtramp(int, int, struct sigset*); |
| 19 | } |
| 20 |
| 21 | namespace base { |
| 22 |
| 23 | namespace { |
| 24 |
| 25 | // Extracts the "frame offset" for a given frame from the compact unwind info. |
| 26 | // A frame offset indicates the location of saved non-volatile registers in |
| 27 | // relation to the frame pointer. See |mach-o/compact_unwind_encoding.h| for |
| 28 | // details. |
| 29 | uint32_t GetFrameOffset(int compact_unwind_info) { |
| 30 | // The frame offset lives in bytes 16-23. This shifts it down by the number of |
| 31 | // leading zeroes in the mask, then masks with (1 << number of one bits in the |
| 32 | // mask) - 1, turning 0x00FF0000 into 0x000000FF. Adapted from |EXTRACT_BITS| |
| 33 | // in libunwind's CompactUnwinder.hpp. |
| 34 | return ( |
| 35 | (compact_unwind_info >> __builtin_ctz(UNWIND_X86_64_RBP_FRAME_OFFSET)) & |
| 36 | (((1 << __builtin_popcount(UNWIND_X86_64_RBP_FRAME_OFFSET))) - 1)); |
| 37 | } |
| 38 |
| 39 | // True if the unwind from |leaf_frame_module| may trigger a crash bug in |
| 40 | // unw_init_local. If so, the stack walk should be aborted at the leaf frame. |
| 41 | bool MayTriggerUnwInitLocalCrash(const ModuleCache::Module* leaf_frame_module) { |
| 42 | // The issue here is a bug in unw_init_local that, in some unwinds, results in |
| 43 | // attempts to access memory at the address immediately following the address |
| 44 | // range of the library. When the library is the last of the mapped libraries |
| 45 | // that address is in a different memory region. Starting with 10.13.4 beta |
| 46 | // releases it appears that this region is sometimes either unmapped or mapped |
| 47 | // without read access, resulting in crashes on the attempted access. It's not |
| 48 | // clear what circumstances result in this situation; attempts to reproduce on |
| 49 | // a 10.13.4 beta did not trigger the issue. |
| 50 | // |
| 51 | // The workaround is to check if the memory address that would be accessed is |
| 52 | // readable, and if not, abort the stack walk before calling unw_init_local. |
| 53 | // As of 2018/03/19 about 0.1% of non-idle stacks on the UI and GPU main |
| 54 | // threads have a leaf frame in the last library. Since the issue appears to |
| 55 | // only occur some of the time it's expected that the quantity of lost samples |
| 56 | // will be lower than 0.1%, possibly significantly lower. |
| 57 | // |
| 58 | // TODO(lgrey): Add references above to LLVM/Radar bugs on unw_init_local once |
| 59 | // filed. |
| 60 | uint64_t unused; |
| 61 | vm_size_t size = sizeof(unused); |
| 62 | return vm_read_overwrite( |
| 63 | current_task(), |
| 64 | leaf_frame_module->GetBaseAddress() + leaf_frame_module->GetSize(), |
| 65 | sizeof(unused), reinterpret_cast<vm_address_t>(&unused), |
| 66 | &size) != 0; |
| 67 | } |
| 68 |
| 69 | // Check if the cursor contains a valid-looking frame pointer for frame pointer |
| 70 | // unwinds. If the stack frame has a frame pointer, stepping the cursor will |
| 71 | // involve indexing memory access off of that pointer. In that case, |
| 72 | // sanity-check the frame pointer register to ensure it's within bounds. |
| 73 | // |
| 74 | // Additionally, the stack frame might be in a prologue or epilogue, which can |
| 75 | // cause a crash when the unwinder attempts to access non-volatile registers |
| 76 | // that have not yet been pushed, or have already been popped from the |
| 77 | // stack. libwunwind will try to restore those registers using an offset from |
| 78 | // the frame pointer. However, since we copy the stack from RSP up, any |
| 79 | // locations below the stack pointer are before the beginning of the stack |
| 80 | // buffer. Account for this by checking that the expected location is above the |
| 81 | // stack pointer, and rejecting the sample if it isn't. |
| 82 | bool HasValidRbp(unw_cursor_t* unwind_cursor, uintptr_t stack_top) { |
| 83 | unw_proc_info_t proc_info; |
| 84 | unw_get_proc_info(unwind_cursor, &proc_info); |
| 85 | if ((proc_info.format & UNWIND_X86_64_MODE_MASK) == |
| 86 | UNWIND_X86_64_MODE_RBP_FRAME) { |
| 87 | unw_word_t rsp, rbp; |
| 88 | unw_get_reg(unwind_cursor, UNW_X86_64_RSP, &rsp); |
| 89 | unw_get_reg(unwind_cursor, UNW_X86_64_RBP, &rbp); |
| 90 | uint32_t offset = GetFrameOffset(proc_info.format) * sizeof(unw_word_t); |
| 91 | if (rbp < offset || (rbp - offset) < rsp || rbp > stack_top) |
| 92 | return false; |
| 93 | } |
| 94 | return true; |
| 95 | } |
| 96 |
| 97 | const ModuleCache::Module* GetLibSystemKernelModule(ModuleCache* module_cache) { |
| 98 | const ModuleCache::Module* module = |
| 99 | module_cache->GetModuleForAddress(reinterpret_cast<uintptr_t>(ptrace)); |
| 100 | DCHECK(module); |
| 101 | DCHECK_EQ(FilePath("libsystem_kernel.dylib"), module->GetDebugBasename()); |
| 102 | return module; |
| 103 | } |
| 104 |
| 105 | void GetSigtrampRange(uintptr_t* start, uintptr_t* end) { |
| 106 | auto address = reinterpret_cast<uintptr_t>(&_sigtramp); |
| 107 | DCHECK(address != 0); |
| 108 |
| 109 | *start = address; |
| 110 |
| 111 | unw_context_t context; |
| 112 | unw_cursor_t cursor; |
| 113 | unw_proc_info_t info; |
| 114 |
| 115 | unw_getcontext(&context); |
| 116 | // Set the context's RIP to the beginning of sigtramp, |
| 117 | // +1 byte to work around a bug in 10.11 (crbug.com/764468). |
| 118 | context.data[16] = address + 1; |
| 119 | unw_init_local(&cursor, &context); |
| 120 | unw_get_proc_info(&cursor, &info); |
| 121 |
| 122 | DCHECK_EQ(info.start_ip, address); |
| 123 | *end = info.end_ip; |
| 124 | } |
| 125 |
| 126 | } // namespace |
| 127 |
| 128 | NativeUnwinderMac::NativeUnwinderMac(ModuleCache* module_cache) |
| 129 | : libsystem_kernel_module_(GetLibSystemKernelModule(module_cache)) { |
| 130 | GetSigtrampRange(&sigtramp_start_, &sigtramp_end_); |
| 131 | } |
| 132 |
| 133 | bool NativeUnwinderMac::CanUnwindFrom(const Frame& current_frame) const { |
| 134 | return current_frame.module && current_frame.module->IsNative(); |
| 135 | } |
| 136 |
| 137 | UnwindResult NativeUnwinderMac::TryUnwind(x86_thread_state64_t* thread_context, |
| 138 | uintptr_t stack_top, |
| 139 | ModuleCache* module_cache, |
| 140 | std::vector<Frame>* stack) const { |
| 141 | // We expect the frame correponding to the |thread_context| register state to |
| 142 | // exist within |stack|. |
| 143 | DCHECK_GT(stack->size(), 0u); |
| 144 |
| 145 | // There isn't an official way to create a unw_context other than to create it |
| 146 | // from the current state of the current thread's stack. Since we're walking a |
| 147 | // different thread's stack we must forge a context. The unw_context is just a |
| 148 | // copy of the 16 main registers followed by the instruction pointer, nothing |
| 149 | // more. Coincidentally, the first 17 items of the x86_thread_state64_t type |
| 150 | // are exactly those registers in exactly the same order, so just bulk copy |
| 151 | // them over. |
| 152 | unw_context_t unwind_context; |
| 153 | memcpy(&unwind_context, thread_context, sizeof(uintptr_t) * 17); |
| 154 |
| 155 | // Avoid an out-of-bounds read bug in libunwind that can crash us in some |
| 156 | // circumstances. If we're subject to that case, just record the first frame |
| 157 | // and bail. See MayTriggerUnwInitLocalCrash for details. |
| 158 | if (stack->back().module && MayTriggerUnwInitLocalCrash(stack->back().module)) |
| 159 | return UnwindResult::ABORTED; |
| 160 |
| 161 | unw_cursor_t unwind_cursor; |
| 162 | unw_init_local(&unwind_cursor, &unwind_context); |
| 163 |
| 164 | for (;;) { |
| 165 | Optional<UnwindResult> result = |
| 166 | CheckPreconditions(&stack->back(), &unwind_cursor, stack_top); |
| 167 | if (result.has_value()) |
| 168 | return *result; |
| 169 |
| 170 | unw_word_t prev_rsp; |
| 171 | unw_get_reg(&unwind_cursor, UNW_REG_SP, &prev_rsp); |
| 172 |
| 173 | int step_result = UnwindStep(&unwind_context, &unwind_cursor, |
| 174 | stack->size() == 1, module_cache); |
| 175 |
| 176 | unw_word_t rip; |
| 177 | unw_get_reg(&unwind_cursor, UNW_REG_IP, &rip); |
| 178 | unw_word_t rsp; |
| 179 | unw_get_reg(&unwind_cursor, UNW_REG_SP, &rsp); |
| 180 |
| 181 | bool successfully_unwound; |
| 182 | result = CheckPostconditions(step_result, prev_rsp, rsp, stack_top, |
| 183 | &successfully_unwound); |
| 184 |
| 185 | if (successfully_unwound) { |
| 186 | stack->emplace_back(rip, module_cache->GetModuleForAddress(rip)); |
| 187 |
| 188 | // Save the relevant register state back into the thread context. |
| 189 | unw_word_t rbp; |
| 190 | unw_get_reg(&unwind_cursor, UNW_X86_64_RBP, &rbp); |
| 191 | thread_context->__rip = rip; |
| 192 | thread_context->__rsp = rsp; |
| 193 | thread_context->__rbp = rbp; |
| 194 | } |
| 195 |
| 196 | if (result.has_value()) |
| 197 | return *result; |
| 198 | } |
| 199 |
| 200 | NOTREACHED(); |
| 201 | return UnwindResult::COMPLETED; |
| 202 | } |
| 203 |
| 204 | // Checks preconditions for attempting an unwind. If any conditions fail, |
| 205 | // returns corresponding UnwindResult. Otherwise returns nullopt. |
| 206 | Optional<UnwindResult> NativeUnwinderMac::CheckPreconditions( |
| 207 | const Frame* current_frame, |
| 208 | unw_cursor_t* unwind_cursor, |
| 209 | uintptr_t stack_top) const { |
| 210 | if (!current_frame->module) { |
| 211 | // There's no loaded module containing the instruction pointer. This is |
| 212 | // due to either executing code that is not in a module (e.g. V8 |
| 213 | // runtime-generated code), or to a previous bad unwind. |
| 214 | // |
| 215 | // The bad unwind scenario can occur in frameless (non-DWARF) unwinding, |
| 216 | // which works by fetching the function's stack size from the unwind |
| 217 | // encoding or stack, and adding it to the stack pointer to determine the |
| 218 | // function's return address. |
| 219 | // |
| 220 | // If we're in a function prologue or epilogue, the actual stack size may |
| 221 | // be smaller than it will be during the normal course of execution. When |
| 222 | // libunwind adds the expected stack size, it will look for the return |
| 223 | // address in the wrong place. This check ensures we don't continue trying |
| 224 | // to unwind using the resulting bad IP value. |
| 225 | return UnwindResult::ABORTED; |
| 226 | } |
| 227 |
| 228 | if (!current_frame->module->IsNative()) { |
| 229 | // This is a non-native module associated with the auxiliary unwinder |
| 230 | // (e.g. corresponding to a frame in V8 generated code). Report as |
| 231 | // UNRECOGNIZED_FRAME to allow that unwinder to unwind the frame. |
| 232 | return UnwindResult::UNRECOGNIZED_FRAME; |
| 233 | } |
| 234 |
| 235 | // Don't continue if we're in sigtramp. Unwinding this from another thread |
| 236 | // is very fragile. It's a complex DWARF unwind that needs to restore the |
| 237 | // entire thread context which was saved by the kernel when the interrupt |
| 238 | // occurred. |
| 239 | if (current_frame->instruction_pointer >= sigtramp_start_ && |
| 240 | current_frame->instruction_pointer < sigtramp_end_) { |
| 241 | return UnwindResult::ABORTED; |
| 242 | } |
| 243 |
| 244 | // Don't continue if rbp appears to be invalid (due to a previous bad |
| 245 | // unwind). |
| 246 | if (!HasValidRbp(unwind_cursor, stack_top)) |
| 247 | return UnwindResult::ABORTED; |
| 248 |
| 249 | return nullopt; |
| 250 | } |
| 251 |
| 252 | // Attempts to unwind the current frame using unw_step, and returns its return |
| 253 | // value. |
| 254 | int NativeUnwinderMac::UnwindStep(unw_context_t* unwind_context, |
| 255 | unw_cursor_t* unwind_cursor, |
| 256 | bool at_first_frame, |
| 257 | ModuleCache* module_cache) const { |
| 258 | int step_result = unw_step(unwind_cursor); |
| 259 |
| 260 | if (step_result == 0 && at_first_frame) { |
| 261 | // libunwind is designed to be triggered by user code on their own thread, |
| 262 | // if it hits a library that has no unwind info for the function that is |
| 263 | // being executed, it just stops. This isn't a problem in the normal case, |
| 264 | // but in the case where this is the first frame unwind, it's quite |
| 265 | // possible that the stack being walked is stopped in a function that |
| 266 | // bridges to the kernel and thus is missing the unwind info. |
| 267 |
| 268 | // For now, just unwind the single case where the thread is stopped in a |
| 269 | // function in libsystem_kernel. |
| 270 | uint64_t& rsp = unwind_context->data[7]; |
| 271 | uint64_t& rip = unwind_context->data[16]; |
| 272 | if (module_cache->GetModuleForAddress(rip) == libsystem_kernel_module_) { |
| 273 | rip = *reinterpret_cast<uint64_t*>(rsp); |
| 274 | rsp += 8; |
| 275 | // Reset the cursor. |
| 276 | unw_init_local(unwind_cursor, unwind_context); |
| 277 | // Mock a successful step_result. |
| 278 | return 1; |
| 279 | } |
| 280 | } |
| 281 |
| 282 | return step_result; |
| 283 | } |
| 284 |
| 285 | // Checks postconditions after attempting an unwind. If any conditions fail, |
| 286 | // returns corresponding UnwindResult. Otherwise returns nullopt. Sets |
| 287 | // *|successfully_unwound| if the unwind succeeded (and hence the frame should |
| 288 | // be recorded). |
| 289 | Optional<UnwindResult> NativeUnwinderMac::CheckPostconditions( |
| 290 | int step_result, |
| 291 | unw_word_t prev_rsp, |
| 292 | unw_word_t rsp, |
| 293 | uintptr_t stack_top, |
| 294 | bool* successfully_unwound) const { |
| 295 | const bool stack_pointer_was_moved_and_is_valid = |
| 296 | rsp > prev_rsp && rsp < stack_top; |
| 297 |
| 298 | *successfully_unwound = |
| 299 | step_result > 0 || |
| 300 | // libunwind considers the unwind complete and returns 0 if no unwind |
| 301 | // info was found for the current instruction pointer. It performs this |
| 302 | // check both before *and* after stepping the cursor. In the former case |
| 303 | // no action is taken, but in the latter case an unwind was successfully |
| 304 | // performed prior to the check. Distinguish these cases by checking |
| 305 | // whether the stack pointer was moved by unw_step. If so, record the |
| 306 | // new frame to enable non-native unwinders to continue the unwinding. |
| 307 | (step_result == 0 && stack_pointer_was_moved_and_is_valid); |
| 308 |
| 309 | if (step_result < 0) |
| 310 | return UnwindResult::ABORTED; |
| 311 |
| 312 | // libunwind returns 0 if it can't continue because no unwind info was found |
| 313 | // for the current instruction pointer. This could be due to unwinding past |
| 314 | // the entry point, in which case the unwind would be complete. It could |
| 315 | // also be due to unwinding to a function that simply doesn't have unwind |
| 316 | // info, in which case the unwind should be aborted. Or it could be due to |
| 317 | // unwinding to code not in a module, in which case the unwind might be |
| 318 | // continuable by a non-native unwinder. We don't have a good way to |
| 319 | // distinguish these cases, so return UNRECOGNIZED_FRAME to at least |
| 320 | // signify that we couldn't unwind further. |
| 321 | if (step_result == 0) |
| 322 | return UnwindResult::UNRECOGNIZED_FRAME; |
| 323 |
| 324 | // If we succeeded but didn't advance the stack pointer, or got an invalid |
| 325 | // new stack pointer, abort. |
| 326 | if (!stack_pointer_was_moved_and_is_valid) |
| 327 | return UnwindResult::ABORTED; |
| 328 |
| 329 | return nullopt; |
| 330 | } |
| 331 |
| 332 | std::unique_ptr<Unwinder> CreateNativeUnwinder(ModuleCache* module_cache) { |
| 333 | return std::make_unique<NativeUnwinderMac>(module_cache); |
| 334 | } |
| 335 |
| 336 | } // namespace base |
| 337 |