Debian Codegraph @

mozglue/baseprofiler/core/EHABIStackWalk.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /*
8 * This is an implementation of stack unwinding according to a subset
9 * of the ARM Exception Handling ABI, as described in:
10 * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0038a/IHI0038A_ehabi.pdf
11 *
12 * This handles only the ARM-defined "personality routines" (chapter
13 * 9), and don't track the value of FP registers, because profiling
14 * needs only chain of PC/SP values.
15 *
16 * Because the exception handling info may not be accurate for all
17 * possible places where an async signal could occur (e.g., in a
18 * prologue or epilogue), this bounds-checks all stack accesses.
19 *
20 * This file uses "struct" for structures in the exception tables and
21 * "class" otherwise. We should avoid violating the C++11
22 * standard-layout rules in the former.
23 */
24
25 #include "BaseProfiler.h"
26
27 #include "EHABIStackWalk.h"
28
29 #include "SharedLibraries.h"
30 #include "platform.h"
31
32 #include "mozilla/Atomics.h"
33 #include "mozilla/DebugOnly.h"
34 #include "mozilla/EndianUtils.h"
35
36 #include <algorithm>
37 #include <elf.h>
38 #include <stdint.h>
39 #include <vector>
40 #include <string>
41
42 #ifndef PT_ARM_EXIDX
43 # define PT_ARM_EXIDX 0x70000001
44 #endif
45
46 namespace mozilla {
47 namespace baseprofiler {
48
49 struct PRel31 {
50 uint32_t mBits;
51 bool topBit() const { return mBits & 0x80000000; }
52 uint32_t value() const { return mBits & 0x7fffffff; }
53 int32_t offset() const { return (static_cast<int32_t>(mBits) << 1) >> 1; }
54 const void* compute() const {
55 return reinterpret_cast<const char*>(this) + offset();
56 }
57
58 private:
59 PRel31(const PRel31& copied) = delete;
60 PRel31() = delete;
61 };
62
63 struct EHEntry {
64 PRel31 startPC;
65 PRel31 exidx;
66
67 private:
68 EHEntry(const EHEntry& copied) = delete;
69 EHEntry() = delete;
70 };
71
72 class EHState {
73 // Note that any core register can be used as a "frame pointer" to
74 // influence the unwinding process, so this must track all of them.
75 uint32_t mRegs[16];
76
77 public:
78 bool unwind(const EHEntry* aEntry, const void* stackBase);
79 uint32_t& operator[](int i) { return mRegs[i]; }
80 const uint32_t& operator[](int i) const { return mRegs[i]; }
81 explicit EHState(const mcontext_t&);
82 };
83
84 enum { R_SP = 13, R_LR = 14, R_PC = 15 };
85
86 class EHTable {
87 uint32_t mStartPC;
88 uint32_t mEndPC;
89 uint32_t mBaseAddress;
90 const EHEntry* mEntriesBegin;
91 const EHEntry* mEntriesEnd;
92 std::string mName;
93
94 public:
95 EHTable(const void* aELF, size_t aSize, const std::string& aName);
96 const EHEntry* lookup(uint32_t aPC) const;
97 bool isValid() const { return mEntriesEnd != mEntriesBegin; }
98 const std::string& name() const { return mName; }
99 uint32_t startPC() const { return mStartPC; }
100 uint32_t endPC() const { return mEndPC; }
101 uint32_t baseAddress() const { return mBaseAddress; }
102 };
103
104 class EHAddrSpace {
105 std::vector<uint32_t> mStarts;
106 std::vector<EHTable> mTables;
107 static Atomic<const EHAddrSpace*> sCurrent;
108
109 public:
110 explicit EHAddrSpace(const std::vector<EHTable>& aTables);
111 const EHTable* lookup(uint32_t aPC) const;
112 static void Update();
113 static const EHAddrSpace* Get();
114 };
115
116 void EHABIStackWalkInit() { EHAddrSpace::Update(); }
117
118 size_t EHABIStackWalk(const mcontext_t& aContext, void* stackBase, void** aSPs,
119 void** aPCs, const size_t aNumFrames) {
120 const EHAddrSpace* space = EHAddrSpace::Get();
121 EHState state(aContext);
122 size_t count = 0;
123
124 while (count < aNumFrames) {
125 uint32_t pc = state[R_PC], sp = state[R_SP];
126 aPCs[count] = reinterpret_cast<void*>(pc);
127 aSPs[count] = reinterpret_cast<void*>(sp);
128 count++;
129
130 if (!space) break;
131 // TODO: cache these lookups. Binary-searching libxul is
132 // expensive (possibly more expensive than doing the actual
133 // unwind), and even a small cache should help.
134 const EHTable* table = space->lookup(pc);
135 if (!table) break;
136 const EHEntry* entry = table->lookup(pc);
137 if (!entry) break;
138 if (!state.unwind(entry, stackBase)) break;
139 }
140
141 return count;
142 }
143
144 class EHInterp {
145 public:
146 // Note that stackLimit is exclusive and stackBase is inclusive
147 // (i.e, stackLimit < SP <= stackBase), following the convention
148 // set by the AAPCS spec.
149 EHInterp(EHState& aState, const EHEntry* aEntry, uint32_t aStackLimit,
150 uint32_t aStackBase)
151 : mState(aState),
152 mStackLimit(aStackLimit),
153 mStackBase(aStackBase),
154 mNextWord(0),
155 mWordsLeft(0),
156 mFailed(false) {
157 const PRel31& exidx = aEntry->exidx;
158 uint32_t firstWord;
159
160 if (exidx.mBits == 1) { // EXIDX_CANTUNWIND
161 mFailed = true;
162 return;
163 }
164 if (exidx.topBit()) {
165 firstWord = exidx.mBits;
166 } else {
167 mNextWord = reinterpret_cast<const uint32_t*>(exidx.compute());
168 firstWord = *mNextWord++;
169 }
170
171 switch (firstWord >> 24) {
172 case 0x80: // short
173 mWord = firstWord << 8;
174 mBytesLeft = 3;
175 break;
176 case 0x81:
177 case 0x82: // long; catch descriptor size ignored
178 mWord = firstWord << 16;
179 mBytesLeft = 2;
180 mWordsLeft = (firstWord >> 16) & 0xff;
181 break;
182 default:
183 // unknown personality
184 mFailed = true;
185 }
186 }
187
188 bool unwind();
189
190 private:
191 // TODO: GCC has been observed not CSEing repeated reads of
192 // mState[R_SP] with writes to mFailed between them, suggesting that
193 // it hasn't determined that they can't alias and is thus missing
194 // optimization opportunities. So, we may want to flatten EHState
195 // into this class; this may also make the code simpler.
196 EHState& mState;
197 uint32_t mStackLimit;
198 uint32_t mStackBase;
199 const uint32_t* mNextWord;
200 uint32_t mWord;
201 uint8_t mWordsLeft;
202 uint8_t mBytesLeft;
203 bool mFailed;
204
205 enum {
206 I_ADDSP = 0x00, // 0sxxxxxx (subtract if s)
207 M_ADDSP = 0x80,
208 I_POPMASK = 0x80, // 1000iiii iiiiiiii (if any i set)
209 M_POPMASK = 0xf0,
210 I_MOVSP = 0x90, // 1001nnnn
211 M_MOVSP = 0xf0,
212 I_POPN = 0xa0, // 1010lnnn
213 M_POPN = 0xf0,
214 I_FINISH = 0xb0, // 10110000
215 I_POPLO = 0xb1, // 10110001 0000iiii (if any i set)
216 I_ADDSPBIG = 0xb2, // 10110010 uleb128
217 I_POPFDX = 0xb3, // 10110011 sssscccc
218 I_POPFDX8 = 0xb8, // 10111nnn
219 M_POPFDX8 = 0xf8,
220 // "Intel Wireless MMX" extensions omitted.
221 I_POPFDD = 0xc8, // 1100100h sssscccc
222 M_POPFDD = 0xfe,
223 I_POPFDD8 = 0xd0, // 11010nnn
224 M_POPFDD8 = 0xf8
225 };
226
227 uint8_t next() {
228 if (mBytesLeft == 0) {
229 if (mWordsLeft == 0) {
230 return I_FINISH;
231 }
232 mWordsLeft--;
233 mWord = *mNextWord++;
234 mBytesLeft = 4;
235 }
236 mBytesLeft--;
237 mWord = (mWord << 8) | (mWord >> 24); // rotate
238 return mWord;
239 }
240
241 uint32_t& vSP() { return mState[R_SP]; }
242 uint32_t* ptrSP() { return reinterpret_cast<uint32_t*>(vSP()); }
243
244 void checkStackBase() {
245 if (vSP() > mStackBase) mFailed = true;
246 }
247 void checkStackLimit() {
248 if (vSP() <= mStackLimit) mFailed = true;
249 }
250 void checkStackAlign() {
251 if ((vSP() & 3) != 0) mFailed = true;
252 }
253 void checkStack() {
254 checkStackBase();
255 checkStackLimit();
256 checkStackAlign();
257 }
258
259 void popRange(uint8_t first, uint8_t last, uint16_t mask) {
260 bool hasSP = false;
261 uint32_t tmpSP;
262 if (mask == 0) mFailed = true;
263 for (uint8_t r = first; r <= last; ++r) {
264 if (mask & 1) {
265 if (r == R_SP) {
266 hasSP = true;
267 tmpSP = *ptrSP();
268 } else
269 mState[r] = *ptrSP();
270 vSP() += 4;
271 checkStackBase();
272 if (mFailed) return;
273 }
274 mask >>= 1;
275 }
276 if (hasSP) {
277 vSP() = tmpSP;
278 checkStack();
279 }
280 }
281 };
282
283 bool EHState::unwind(const EHEntry* aEntry, const void* stackBasePtr) {
284 // The unwinding program cannot set SP to less than the initial value.
285 uint32_t stackLimit = mRegs[R_SP] - 4;
286 uint32_t stackBase = reinterpret_cast<uint32_t>(stackBasePtr);
287 EHInterp interp(*this, aEntry, stackLimit, stackBase);
288 return interp.unwind();
289 }
290
291 bool EHInterp::unwind() {
292 mState[R_PC] = 0;
293 checkStack();
294 while (!mFailed) {
295 uint8_t insn = next();
296 #if DEBUG_EHABI_UNWIND
297 LOG("unwind insn = %02x", (unsigned)insn);
298 #endif
299 // Try to put the common cases first.
300
301 // 00xxxxxx: vsp = vsp + (xxxxxx << 2) + 4
302 // 01xxxxxx: vsp = vsp - (xxxxxx << 2) - 4
303 if ((insn & M_ADDSP) == I_ADDSP) {
304 uint32_t offset = ((insn & 0x3f) << 2) + 4;
305 if (insn & 0x40) {
306 vSP() -= offset;
307 checkStackLimit();
308 } else {
309 vSP() += offset;
310 checkStackBase();
311 }
312 continue;
313 }
314
315 // 10100nnn: Pop r4-r[4+nnn]
316 // 10101nnn: Pop r4-r[4+nnn], r14
317 if ((insn & M_POPN) == I_POPN) {
318 uint8_t n = (insn & 0x07) + 1;
319 bool lr = insn & 0x08;
320 uint32_t* ptr = ptrSP();
321 vSP() += (n + (lr ? 1 : 0)) * 4;
322 checkStackBase();
323 for (uint8_t r = 4; r < 4 + n; ++r) mState[r] = *ptr++;
324 if (lr) mState[R_LR] = *ptr++;
325 continue;
326 }
327
328 // 1011000: Finish
329 if (insn == I_FINISH) {
330 if (mState[R_PC] == 0) {
331 mState[R_PC] = mState[R_LR];
332 // Non-standard change (bug 916106): Prevent the caller from
333 // re-using LR. Since the caller is by definition not a leaf
334 // routine, it will have to restore LR from somewhere to
335 // return to its own caller, so we can safely zero it here.
336 // This makes a difference only if an error in unwinding
337 // (e.g., caused by starting from within a prologue/epilogue)
338 // causes us to load a pointer to a leaf routine as LR; if we
339 // don't do something, we'll go into an infinite loop of
340 // "returning" to that same function.
341 mState[R_LR] = 0;
342 }
343 return true;
344 }
345
346 // 1001nnnn: Set vsp = r[nnnn]
347 if ((insn & M_MOVSP) == I_MOVSP) {
348 vSP() = mState[insn & 0x0f];
349 checkStack();
350 continue;
351 }
352
353 // 11001000 sssscccc: Pop VFP regs D[16+ssss]-D[16+ssss+cccc] (as FLDMFDD)
354 // 11001001 sssscccc: Pop VFP regs D[ssss]-D[ssss+cccc] (as FLDMFDD)
355 if ((insn & M_POPFDD) == I_POPFDD) {
356 uint8_t n = (next() & 0x0f) + 1;
357 // Note: if the 16+ssss+cccc > 31, the encoding is reserved.
358 // As the space is currently unused, we don't try to check.
359 vSP() += 8 * n;
360 checkStackBase();
361 continue;
362 }
363
364 // 11010nnn: Pop VFP regs D[8]-D[8+nnn] (as FLDMFDD)
365 if ((insn & M_POPFDD8) == I_POPFDD8) {
366 uint8_t n = (insn & 0x07) + 1;
367 vSP() += 8 * n;
368 checkStackBase();
369 continue;
370 }
371
372 // 10110010 uleb128: vsp = vsp + 0x204 + (uleb128 << 2)
373 if (insn == I_ADDSPBIG) {
374 uint32_t acc = 0;
375 uint8_t shift = 0;
376 uint8_t byte;
377 do {
378 if (shift >= 32) return false;
379 byte = next();
380 acc |= (byte & 0x7f) << shift;
381 shift += 7;
382 } while (byte & 0x80);
383 uint32_t offset = 0x204 + (acc << 2);
384 // The calculations above could have overflowed.
385 // But the one we care about is this:
386 if (vSP() + offset < vSP()) mFailed = true;
387 vSP() += offset;
388 // ...so that this is the only other check needed:
389 checkStackBase();
390 continue;
391 }
392
393 // 1000iiii iiiiiiii (i not all 0): Pop under masks {r15-r12}, {r11-r4}
394 if ((insn & M_POPMASK) == I_POPMASK) {
395 popRange(4, 15, ((insn & 0x0f) << 8) | next());
396 continue;
397 }
398
399 // 1011001 0000iiii (i not all 0): Pop under mask {r3-r0}
400 if (insn == I_POPLO) {
401 popRange(0, 3, next() & 0x0f);
402 continue;
403 }
404
405 // 10110011 sssscccc: Pop VFP regs D[ssss]-D[ssss+cccc] (as FLDMFDX)
406 if (insn == I_POPFDX) {
407 uint8_t n = (next() & 0x0f) + 1;
408 vSP() += 8 * n + 4;
409 checkStackBase();
410 continue;
411 }
412
413 // 10111nnn: Pop VFP regs D[8]-D[8+nnn] (as FLDMFDX)
414 if ((insn & M_POPFDX8) == I_POPFDX8) {
415 uint8_t n = (insn & 0x07) + 1;
416 vSP() += 8 * n + 4;
417 checkStackBase();
418 continue;
419 }
420
421 // unhandled instruction
422 #ifdef DEBUG_EHABI_UNWIND
423 LOG("Unhandled EHABI instruction 0x%02x", insn);
424 #endif
425 mFailed = true;
426 }
427 return false;
428 }
429
430 bool operator<(const EHTable& lhs, const EHTable& rhs) {
431 return lhs.startPC() < rhs.startPC();
432 }
433
434 // Async signal unsafe.
435 EHAddrSpace::EHAddrSpace(const std::vector<EHTable>& aTables)
436 : mTables(aTables) {
437 std::sort(mTables.begin(), mTables.end());
438 DebugOnly<uint32_t> lastEnd = 0;
439 for (std::vector<EHTable>::iterator i = mTables.begin(); i != mTables.end();
440 ++i) {
441 MOZ_ASSERT(i->startPC() >= lastEnd);
442 mStarts.push_back(i->startPC());
443 lastEnd = i->endPC();
444 }
445 }
446
447 const EHTable* EHAddrSpace::lookup(uint32_t aPC) const {
448 ptrdiff_t i = (std::upper_bound(mStarts.begin(), mStarts.end(), aPC) -
449 mStarts.begin()) -
450 1;
451
452 if (i < 0 || aPC >= mTables[i].endPC()) return 0;
453 return &mTables[i];
454 }
455
456 const EHEntry* EHTable::lookup(uint32_t aPC) const {
457 MOZ_ASSERT(aPC >= mStartPC);
458 if (aPC >= mEndPC) return nullptr;
459
460 const EHEntry* begin = mEntriesBegin;
461 const EHEntry* end = mEntriesEnd;
462 MOZ_ASSERT(begin < end);
463 if (aPC < reinterpret_cast<uint32_t>(begin->startPC.compute()))
464 return nullptr;
465
466 while (end - begin > 1) {
467 #ifdef EHABI_UNWIND_MORE_ASSERTS
468 if ((end - 1)->startPC.compute() < begin->startPC.compute()) {
469 MOZ_CRASH("unsorted exidx");
470 }
471 #endif
472 const EHEntry* mid = begin + (end - begin) / 2;
473 if (aPC < reinterpret_cast<uint32_t>(mid->startPC.compute()))
474 end = mid;
475 else
476 begin = mid;
477 }
478 return begin;
479 }
480
481 #if MOZ_LITTLE_ENDIAN()
482 static const unsigned char hostEndian = ELFDATA2LSB;
483 #elif MOZ_BIG_ENDIAN()
484 static const unsigned char hostEndian = ELFDATA2MSB;
485 #else
486 # error "No endian?"
487 #endif
488
489 // Async signal unsafe: std::vector::reserve, std::string copy ctor.
490 EHTable::EHTable(const void* aELF, size_t aSize, const std::string& aName)
491 : mStartPC(~0), // largest uint32_t
492 mEndPC(0),
493 mEntriesBegin(nullptr),
494 mEntriesEnd(nullptr),
495 mName(aName) {
496 const uint32_t fileHeaderAddr = reinterpret_cast<uint32_t>(aELF);
497
498 if (aSize < sizeof(Elf32_Ehdr)) return;
499
500 const Elf32_Ehdr& file = *(reinterpret_cast<Elf32_Ehdr*>(fileHeaderAddr));
501 if (memcmp(&file.e_ident[EI_MAG0], ELFMAG, SELFMAG) != 0 ||
502 file.e_ident[EI_CLASS] != ELFCLASS32 ||
503 file.e_ident[EI_DATA] != hostEndian ||
504 file.e_ident[EI_VERSION] != EV_CURRENT || file.e_machine != EM_ARM ||
505 file.e_version != EV_CURRENT)
506 // e_flags?
507 return;
508
509 MOZ_ASSERT(file.e_phoff + file.e_phnum * file.e_phentsize <= aSize);
510 const Elf32_Phdr *exidxHdr = 0, *zeroHdr = 0;
511 for (unsigned i = 0; i < file.e_phnum; ++i) {
512 const Elf32_Phdr& phdr = *(reinterpret_cast<Elf32_Phdr*>(
513 fileHeaderAddr + file.e_phoff + i * file.e_phentsize));
514 if (phdr.p_type == PT_ARM_EXIDX) {
515 exidxHdr = &phdr;
516 } else if (phdr.p_type == PT_LOAD) {
517 if (phdr.p_offset == 0) {
518 zeroHdr = &phdr;
519 }
520 if (phdr.p_flags & PF_X) {
521 mStartPC = std::min(mStartPC, phdr.p_vaddr);
522 mEndPC = std::max(mEndPC, phdr.p_vaddr + phdr.p_memsz);
523 }
524 }
525 }
526 if (!exidxHdr) return;
527 if (!zeroHdr) return;
528 mBaseAddress = fileHeaderAddr - zeroHdr->p_vaddr;
529 mStartPC += mBaseAddress;
530 mEndPC += mBaseAddress;
531 mEntriesBegin =
532 reinterpret_cast<const EHEntry*>(mBaseAddress + exidxHdr->p_vaddr);
533 mEntriesEnd = reinterpret_cast<const EHEntry*>(
534 mBaseAddress + exidxHdr->p_vaddr + exidxHdr->p_memsz);
535 }
536
537 Atomic<const EHAddrSpace*> EHAddrSpace::sCurrent(nullptr);
538
539 // Async signal safe; can fail if Update() hasn't returned yet.
540 const EHAddrSpace* EHAddrSpace::Get() { return sCurrent; }
541
542 // Collect unwinding information from loaded objects. Calls after the
543 // first have no effect. Async signal unsafe.
544 void EHAddrSpace::Update() {
545 const EHAddrSpace* space = sCurrent;
546 if (space) return;
547
548 SharedLibraryInfo info = SharedLibraryInfo::GetInfoForSelf();
549 std::vector<EHTable> tables;
550
551 for (size_t i = 0; i < info.GetSize(); ++i) {
552 const SharedLibrary& lib = info.GetEntry(i);
553 // FIXME: This isn't correct if the start address isn't p_offset 0, because
554 // the start address will not point at the file header. But this is worked
555 // around by magic number checks in the EHTable constructor.
556 EHTable tab(reinterpret_cast<const void*>(lib.GetStart()),
557 lib.GetEnd() - lib.GetStart(), lib.GetDebugPath());
558 if (tab.isValid()) tables.push_back(tab);
559 }
560 space = new EHAddrSpace(tables);
561
562 if (!sCurrent.compareExchange(nullptr, space)) {
563 delete space;
564 space = sCurrent;
565 }
566 }
567
568 EHState::EHState(const mcontext_t& context) {
569 #ifdef linux
570 mRegs[0] = context.arm_r0;
571 mRegs[1] = context.arm_r1;
572 mRegs[2] = context.arm_r2;
573 mRegs[3] = context.arm_r3;
574 mRegs[4] = context.arm_r4;
575 mRegs[5] = context.arm_r5;
576 mRegs[6] = context.arm_r6;
577 mRegs[7] = context.arm_r7;
578 mRegs[8] = context.arm_r8;
579 mRegs[9] = context.arm_r9;
580 mRegs[10] = context.arm_r10;
581 mRegs[11] = context.arm_fp;
582 mRegs[12] = context.arm_ip;
583 mRegs[13] = context.arm_sp;
584 mRegs[14] = context.arm_lr;
585 mRegs[15] = context.arm_pc;
586 #else
587 # error "Unhandled OS for ARM EHABI unwinding"
588 #endif
589 }
590
591 } // namespace baseprofiler
592 } // namespace mozilla