Backed out 2 changesets (bug 1943998) for causing wd failures @ phases.py CLOSED...
[gecko.git] / mozglue / baseprofiler / lul / LulDwarf.cpp
blobc83296fc620de14cda1e54f155f42f1f8acac7d1
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: */
4 // Copyright (c) 2010 Google Inc. All Rights Reserved.
5 //
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
8 // met:
9 //
10 // * Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
12 // * Redistributions in binary form must reproduce the above
13 // copyright notice, this list of conditions and the following disclaimer
14 // in the documentation and/or other materials provided with the
15 // distribution.
16 // * Neither the name of Google Inc. nor the names of its
17 // contributors may be used to endorse or promote products derived from
18 // this software without specific prior written permission.
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 // CFI reader author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>
33 // Original author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>
35 // Implementation of dwarf2reader::LineInfo, dwarf2reader::CompilationUnit,
36 // and dwarf2reader::CallFrameInfo. See dwarf2reader.h for details.
38 // This file is derived from the following files in
39 // toolkit/crashreporter/google-breakpad:
40 // src/common/dwarf/bytereader.cc
41 // src/common/dwarf/dwarf2reader.cc
42 // src/common/dwarf_cfi_to_module.cc
44 #include <stdint.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <stdlib.h>
49 #include <map>
50 #include <stack>
51 #include <string>
53 #include "mozilla/Assertions.h"
54 #include "mozilla/Sprintf.h"
56 #include "LulCommonExt.h"
57 #include "LulDwarfInt.h"
59 // Set this to 1 for verbose logging
60 #define DEBUG_DWARF 0
62 namespace lul {
64 using std::string;
66 ByteReader::ByteReader(enum Endianness endian)
67 : offset_reader_(NULL),
68 address_reader_(NULL),
69 endian_(endian),
70 address_size_(0),
71 offset_size_(0),
72 have_section_base_(),
73 have_text_base_(),
74 have_data_base_(),
75 have_function_base_() {}
77 ByteReader::~ByteReader() {}
79 void ByteReader::SetOffsetSize(uint8 size) {
80 offset_size_ = size;
81 MOZ_ASSERT(size == 4 || size == 8);
82 if (size == 4) {
83 this->offset_reader_ = &ByteReader::ReadFourBytes;
84 } else {
85 this->offset_reader_ = &ByteReader::ReadEightBytes;
89 void ByteReader::SetAddressSize(uint8 size) {
90 address_size_ = size;
91 MOZ_ASSERT(size == 4 || size == 8);
92 if (size == 4) {
93 this->address_reader_ = &ByteReader::ReadFourBytes;
94 } else {
95 this->address_reader_ = &ByteReader::ReadEightBytes;
99 uint64 ByteReader::ReadInitialLength(const char* start, size_t* len) {
100 const uint64 initial_length = ReadFourBytes(start);
101 start += 4;
103 // In DWARF2/3, if the initial length is all 1 bits, then the offset
104 // size is 8 and we need to read the next 8 bytes for the real length.
105 if (initial_length == 0xffffffff) {
106 SetOffsetSize(8);
107 *len = 12;
108 return ReadOffset(start);
109 } else {
110 SetOffsetSize(4);
111 *len = 4;
113 return initial_length;
116 bool ByteReader::ValidEncoding(DwarfPointerEncoding encoding) const {
117 if (encoding == DW_EH_PE_omit) return true;
118 if (encoding == DW_EH_PE_aligned) return true;
119 if ((encoding & 0x7) > DW_EH_PE_udata8) return false;
120 if ((encoding & 0x70) > DW_EH_PE_funcrel) return false;
121 return true;
124 bool ByteReader::UsableEncoding(DwarfPointerEncoding encoding) const {
125 switch (encoding & 0x70) {
126 case DW_EH_PE_absptr:
127 return true;
128 case DW_EH_PE_pcrel:
129 return have_section_base_;
130 case DW_EH_PE_textrel:
131 return have_text_base_;
132 case DW_EH_PE_datarel:
133 return have_data_base_;
134 case DW_EH_PE_funcrel:
135 return have_function_base_;
136 default:
137 return false;
141 uint64 ByteReader::ReadEncodedPointer(const char* buffer,
142 DwarfPointerEncoding encoding,
143 size_t* len) const {
144 // UsableEncoding doesn't approve of DW_EH_PE_omit, so we shouldn't
145 // see it here.
146 MOZ_ASSERT(encoding != DW_EH_PE_omit);
148 // The Linux Standards Base 4.0 does not make this clear, but the
149 // GNU tools (gcc/unwind-pe.h; readelf/dwarf.c; gdb/dwarf2-frame.c)
150 // agree that aligned pointers are always absolute, machine-sized,
151 // machine-signed pointers.
152 if (encoding == DW_EH_PE_aligned) {
153 MOZ_ASSERT(have_section_base_);
155 // We don't need to align BUFFER in *our* address space. Rather, we
156 // need to find the next position in our buffer that would be aligned
157 // when the .eh_frame section the buffer contains is loaded into the
158 // program's memory. So align assuming that buffer_base_ gets loaded at
159 // address section_base_, where section_base_ itself may or may not be
160 // aligned.
162 // First, find the offset to START from the closest prior aligned
163 // address.
164 uint64 skew = section_base_ & (AddressSize() - 1);
165 // Now find the offset from that aligned address to buffer.
166 uint64 offset = skew + (buffer - buffer_base_);
167 // Round up to the next boundary.
168 uint64 aligned = (offset + AddressSize() - 1) & -AddressSize();
169 // Convert back to a pointer.
170 const char* aligned_buffer = buffer_base_ + (aligned - skew);
171 // Finally, store the length and actually fetch the pointer.
172 *len = aligned_buffer - buffer + AddressSize();
173 return ReadAddress(aligned_buffer);
176 // Extract the value first, ignoring whether it's a pointer or an
177 // offset relative to some base.
178 uint64 offset;
179 switch (encoding & 0x0f) {
180 case DW_EH_PE_absptr:
181 // DW_EH_PE_absptr is weird, as it is used as a meaningful value for
182 // both the high and low nybble of encoding bytes. When it appears in
183 // the high nybble, it means that the pointer is absolute, not an
184 // offset from some base address. When it appears in the low nybble,
185 // as here, it means that the pointer is stored as a normal
186 // machine-sized and machine-signed address. A low nybble of
187 // DW_EH_PE_absptr does not imply that the pointer is absolute; it is
188 // correct for us to treat the value as an offset from a base address
189 // if the upper nybble is not DW_EH_PE_absptr.
190 offset = ReadAddress(buffer);
191 *len = AddressSize();
192 break;
194 case DW_EH_PE_uleb128:
195 offset = ReadUnsignedLEB128(buffer, len);
196 break;
198 case DW_EH_PE_udata2:
199 offset = ReadTwoBytes(buffer);
200 *len = 2;
201 break;
203 case DW_EH_PE_udata4:
204 offset = ReadFourBytes(buffer);
205 *len = 4;
206 break;
208 case DW_EH_PE_udata8:
209 offset = ReadEightBytes(buffer);
210 *len = 8;
211 break;
213 case DW_EH_PE_sleb128:
214 offset = ReadSignedLEB128(buffer, len);
215 break;
217 case DW_EH_PE_sdata2:
218 offset = ReadTwoBytes(buffer);
219 // Sign-extend from 16 bits.
220 offset = (offset ^ 0x8000) - 0x8000;
221 *len = 2;
222 break;
224 case DW_EH_PE_sdata4:
225 offset = ReadFourBytes(buffer);
226 // Sign-extend from 32 bits.
227 offset = (offset ^ 0x80000000ULL) - 0x80000000ULL;
228 *len = 4;
229 break;
231 case DW_EH_PE_sdata8:
232 // No need to sign-extend; this is the full width of our type.
233 offset = ReadEightBytes(buffer);
234 *len = 8;
235 break;
237 default:
238 abort();
241 // Find the appropriate base address.
242 uint64 base;
243 switch (encoding & 0x70) {
244 case DW_EH_PE_absptr:
245 base = 0;
246 break;
248 case DW_EH_PE_pcrel:
249 MOZ_ASSERT(have_section_base_);
250 base = section_base_ + (buffer - buffer_base_);
251 break;
253 case DW_EH_PE_textrel:
254 MOZ_ASSERT(have_text_base_);
255 base = text_base_;
256 break;
258 case DW_EH_PE_datarel:
259 MOZ_ASSERT(have_data_base_);
260 base = data_base_;
261 break;
263 case DW_EH_PE_funcrel:
264 MOZ_ASSERT(have_function_base_);
265 base = function_base_;
266 break;
268 default:
269 abort();
272 uint64 pointer = base + offset;
274 // Remove inappropriate upper bits.
275 if (AddressSize() == 4)
276 pointer = pointer & 0xffffffff;
277 else
278 MOZ_ASSERT(AddressSize() == sizeof(uint64));
280 return pointer;
283 // A DWARF rule for recovering the address or value of a register, or
284 // computing the canonical frame address. There is one subclass of this for
285 // each '*Rule' member function in CallFrameInfo::Handler.
287 // It's annoying that we have to handle Rules using pointers (because
288 // the concrete instances can have an arbitrary size). They're small,
289 // so it would be much nicer if we could just handle them by value
290 // instead of fretting about ownership and destruction.
292 // It seems like all these could simply be instances of std::tr1::bind,
293 // except that we need instances to be EqualityComparable, too.
295 // This could logically be nested within State, but then the qualified names
296 // get horrendous.
297 class CallFrameInfo::Rule {
298 public:
299 virtual ~Rule() {}
301 // Tell HANDLER that, at ADDRESS in the program, REG can be
302 // recovered using this rule. If REG is kCFARegister, then this rule
303 // describes how to compute the canonical frame address. Return what the
304 // HANDLER member function returned.
305 virtual bool Handle(Handler* handler, uint64 address, int reg) const = 0;
307 // Equality on rules. We use these to decide which rules we need
308 // to report after a DW_CFA_restore_state instruction.
309 virtual bool operator==(const Rule& rhs) const = 0;
311 bool operator!=(const Rule& rhs) const { return !(*this == rhs); }
313 // Return a pointer to a copy of this rule.
314 virtual Rule* Copy() const = 0;
316 // If this is a base+offset rule, change its base register to REG.
317 // Otherwise, do nothing. (Ugly, but required for DW_CFA_def_cfa_register.)
318 virtual void SetBaseRegister(unsigned reg) {}
320 // If this is a base+offset rule, change its offset to OFFSET. Otherwise,
321 // do nothing. (Ugly, but required for DW_CFA_def_cfa_offset.)
322 virtual void SetOffset(long long offset) {}
324 // A RTTI workaround, to make it possible to implement equality
325 // comparisons on classes derived from this one.
326 enum CFIRTag {
327 CFIR_UNDEFINED_RULE,
328 CFIR_SAME_VALUE_RULE,
329 CFIR_OFFSET_RULE,
330 CFIR_VAL_OFFSET_RULE,
331 CFIR_REGISTER_RULE,
332 CFIR_EXPRESSION_RULE,
333 CFIR_VAL_EXPRESSION_RULE
336 // Produce the tag that identifies the child class of this object.
337 virtual CFIRTag getTag() const = 0;
340 // Rule: the value the register had in the caller cannot be recovered.
341 class CallFrameInfo::UndefinedRule : public CallFrameInfo::Rule {
342 public:
343 UndefinedRule() {}
344 ~UndefinedRule() {}
345 CFIRTag getTag() const override { return CFIR_UNDEFINED_RULE; }
346 bool Handle(Handler* handler, uint64 address, int reg) const override {
347 return handler->UndefinedRule(address, reg);
349 bool operator==(const Rule& rhs) const override {
350 if (rhs.getTag() != CFIR_UNDEFINED_RULE) return false;
351 return true;
353 Rule* Copy() const override { return new UndefinedRule(*this); }
356 // Rule: the register's value is the same as that it had in the caller.
357 class CallFrameInfo::SameValueRule : public CallFrameInfo::Rule {
358 public:
359 SameValueRule() {}
360 ~SameValueRule() {}
361 CFIRTag getTag() const override { return CFIR_SAME_VALUE_RULE; }
362 bool Handle(Handler* handler, uint64 address, int reg) const override {
363 return handler->SameValueRule(address, reg);
365 bool operator==(const Rule& rhs) const override {
366 if (rhs.getTag() != CFIR_SAME_VALUE_RULE) return false;
367 return true;
369 Rule* Copy() const override { return new SameValueRule(*this); }
372 // Rule: the register is saved at OFFSET from BASE_REGISTER. BASE_REGISTER
373 // may be CallFrameInfo::Handler::kCFARegister.
374 class CallFrameInfo::OffsetRule : public CallFrameInfo::Rule {
375 public:
376 OffsetRule(int base_register, long offset)
377 : base_register_(base_register), offset_(offset) {}
378 ~OffsetRule() {}
379 CFIRTag getTag() const override { return CFIR_OFFSET_RULE; }
380 bool Handle(Handler* handler, uint64 address, int reg) const override {
381 return handler->OffsetRule(address, reg, base_register_, offset_);
383 bool operator==(const Rule& rhs) const override {
384 if (rhs.getTag() != CFIR_OFFSET_RULE) return false;
385 const OffsetRule* our_rhs = static_cast<const OffsetRule*>(&rhs);
386 return (base_register_ == our_rhs->base_register_ &&
387 offset_ == our_rhs->offset_);
389 Rule* Copy() const override { return new OffsetRule(*this); }
390 // We don't actually need SetBaseRegister or SetOffset here, since they
391 // are only ever applied to CFA rules, for DW_CFA_def_cfa_offset, and it
392 // doesn't make sense to use OffsetRule for computing the CFA: it
393 // computes the address at which a register is saved, not a value.
394 private:
395 int base_register_;
396 long offset_;
399 // Rule: the value the register had in the caller is the value of
400 // BASE_REGISTER plus offset. BASE_REGISTER may be
401 // CallFrameInfo::Handler::kCFARegister.
402 class CallFrameInfo::ValOffsetRule : public CallFrameInfo::Rule {
403 public:
404 ValOffsetRule(int base_register, long offset)
405 : base_register_(base_register), offset_(offset) {}
406 ~ValOffsetRule() {}
407 CFIRTag getTag() const override { return CFIR_VAL_OFFSET_RULE; }
408 bool Handle(Handler* handler, uint64 address, int reg) const override {
409 return handler->ValOffsetRule(address, reg, base_register_, offset_);
411 bool operator==(const Rule& rhs) const override {
412 if (rhs.getTag() != CFIR_VAL_OFFSET_RULE) return false;
413 const ValOffsetRule* our_rhs = static_cast<const ValOffsetRule*>(&rhs);
414 return (base_register_ == our_rhs->base_register_ &&
415 offset_ == our_rhs->offset_);
417 Rule* Copy() const override { return new ValOffsetRule(*this); }
418 void SetBaseRegister(unsigned reg) override { base_register_ = reg; }
419 void SetOffset(long long offset) override { offset_ = offset; }
421 private:
422 int base_register_;
423 long offset_;
426 // Rule: the register has been saved in another register REGISTER_NUMBER_.
427 class CallFrameInfo::RegisterRule : public CallFrameInfo::Rule {
428 public:
429 explicit RegisterRule(int register_number)
430 : register_number_(register_number) {}
431 ~RegisterRule() {}
432 CFIRTag getTag() const override { return CFIR_REGISTER_RULE; }
433 bool Handle(Handler* handler, uint64 address, int reg) const override {
434 return handler->RegisterRule(address, reg, register_number_);
436 bool operator==(const Rule& rhs) const override {
437 if (rhs.getTag() != CFIR_REGISTER_RULE) return false;
438 const RegisterRule* our_rhs = static_cast<const RegisterRule*>(&rhs);
439 return (register_number_ == our_rhs->register_number_);
441 Rule* Copy() const override { return new RegisterRule(*this); }
443 private:
444 int register_number_;
447 // Rule: EXPRESSION evaluates to the address at which the register is saved.
448 class CallFrameInfo::ExpressionRule : public CallFrameInfo::Rule {
449 public:
450 explicit ExpressionRule(const string& expression) : expression_(expression) {}
451 ~ExpressionRule() {}
452 CFIRTag getTag() const override { return CFIR_EXPRESSION_RULE; }
453 bool Handle(Handler* handler, uint64 address, int reg) const override {
454 return handler->ExpressionRule(address, reg, expression_);
456 bool operator==(const Rule& rhs) const override {
457 if (rhs.getTag() != CFIR_EXPRESSION_RULE) return false;
458 const ExpressionRule* our_rhs = static_cast<const ExpressionRule*>(&rhs);
459 return (expression_ == our_rhs->expression_);
461 Rule* Copy() const override { return new ExpressionRule(*this); }
463 private:
464 string expression_;
467 // Rule: EXPRESSION evaluates to the previous value of the register.
468 class CallFrameInfo::ValExpressionRule : public CallFrameInfo::Rule {
469 public:
470 explicit ValExpressionRule(const string& expression)
471 : expression_(expression) {}
472 ~ValExpressionRule() {}
473 CFIRTag getTag() const override { return CFIR_VAL_EXPRESSION_RULE; }
474 bool Handle(Handler* handler, uint64 address, int reg) const override {
475 return handler->ValExpressionRule(address, reg, expression_);
477 bool operator==(const Rule& rhs) const override {
478 if (rhs.getTag() != CFIR_VAL_EXPRESSION_RULE) return false;
479 const ValExpressionRule* our_rhs =
480 static_cast<const ValExpressionRule*>(&rhs);
481 return (expression_ == our_rhs->expression_);
483 Rule* Copy() const override { return new ValExpressionRule(*this); }
485 private:
486 string expression_;
489 // A map from register numbers to rules.
490 class CallFrameInfo::RuleMap {
491 public:
492 RuleMap() : cfa_rule_(NULL) {}
493 RuleMap(const RuleMap& rhs) : cfa_rule_(NULL) { *this = rhs; }
494 ~RuleMap() { Clear(); }
496 RuleMap& operator=(const RuleMap& rhs);
498 // Set the rule for computing the CFA to RULE. Take ownership of RULE.
499 void SetCFARule(Rule* rule) {
500 delete cfa_rule_;
501 cfa_rule_ = rule;
504 // Return the current CFA rule. Unlike RegisterRule, this RuleMap retains
505 // ownership of the rule. We use this for DW_CFA_def_cfa_offset and
506 // DW_CFA_def_cfa_register, and for detecting references to the CFA before
507 // a rule for it has been established.
508 Rule* CFARule() const { return cfa_rule_; }
510 // Return the rule for REG, or NULL if there is none. The caller takes
511 // ownership of the result.
512 Rule* RegisterRule(int reg) const;
514 // Set the rule for computing REG to RULE. Take ownership of RULE.
515 void SetRegisterRule(int reg, Rule* rule);
517 // Make all the appropriate calls to HANDLER as if we were changing from
518 // this RuleMap to NEW_RULES at ADDRESS. We use this to implement
519 // DW_CFA_restore_state, where lots of rules can change simultaneously.
520 // Return true if all handlers returned true; otherwise, return false.
521 bool HandleTransitionTo(Handler* handler, uint64 address,
522 const RuleMap& new_rules) const;
524 private:
525 // A map from register numbers to Rules.
526 typedef std::map<int, Rule*> RuleByNumber;
528 // Remove all register rules and clear cfa_rule_.
529 void Clear();
531 // The rule for computing the canonical frame address. This RuleMap owns
532 // this rule.
533 Rule* cfa_rule_;
535 // A map from register numbers to postfix expressions to recover
536 // their values. This RuleMap owns the Rules the map refers to.
537 RuleByNumber registers_;
540 CallFrameInfo::RuleMap& CallFrameInfo::RuleMap::operator=(const RuleMap& rhs) {
541 Clear();
542 // Since each map owns the rules it refers to, assignment must copy them.
543 if (rhs.cfa_rule_) cfa_rule_ = rhs.cfa_rule_->Copy();
544 for (RuleByNumber::const_iterator it = rhs.registers_.begin();
545 it != rhs.registers_.end(); it++)
546 registers_[it->first] = it->second->Copy();
547 return *this;
550 CallFrameInfo::Rule* CallFrameInfo::RuleMap::RegisterRule(int reg) const {
551 MOZ_ASSERT(reg != Handler::kCFARegister);
552 RuleByNumber::const_iterator it = registers_.find(reg);
553 if (it != registers_.end())
554 return it->second->Copy();
555 else
556 return NULL;
559 void CallFrameInfo::RuleMap::SetRegisterRule(int reg, Rule* rule) {
560 MOZ_ASSERT(reg != Handler::kCFARegister);
561 MOZ_ASSERT(rule);
562 Rule** slot = &registers_[reg];
563 delete *slot;
564 *slot = rule;
567 bool CallFrameInfo::RuleMap::HandleTransitionTo(
568 Handler* handler, uint64 address, const RuleMap& new_rules) const {
569 // Transition from cfa_rule_ to new_rules.cfa_rule_.
570 if (cfa_rule_ && new_rules.cfa_rule_) {
571 if (*cfa_rule_ != *new_rules.cfa_rule_ &&
572 !new_rules.cfa_rule_->Handle(handler, address, Handler::kCFARegister))
573 return false;
574 } else if (cfa_rule_) {
575 // this RuleMap has a CFA rule but new_rules doesn't.
576 // CallFrameInfo::Handler has no way to handle this --- and shouldn't;
577 // it's garbage input. The instruction interpreter should have
578 // detected this and warned, so take no action here.
579 } else if (new_rules.cfa_rule_) {
580 // This shouldn't be possible: NEW_RULES is some prior state, and
581 // there's no way to remove entries.
582 MOZ_ASSERT(0);
583 } else {
584 // Both CFA rules are empty. No action needed.
587 // Traverse the two maps in order by register number, and report
588 // whatever differences we find.
589 RuleByNumber::const_iterator old_it = registers_.begin();
590 RuleByNumber::const_iterator new_it = new_rules.registers_.begin();
591 while (old_it != registers_.end() && new_it != new_rules.registers_.end()) {
592 if (old_it->first < new_it->first) {
593 // This RuleMap has an entry for old_it->first, but NEW_RULES
594 // doesn't.
596 // This isn't really the right thing to do, but since CFI generally
597 // only mentions callee-saves registers, and GCC's convention for
598 // callee-saves registers is that they are unchanged, it's a good
599 // approximation.
600 if (!handler->SameValueRule(address, old_it->first)) return false;
601 old_it++;
602 } else if (old_it->first > new_it->first) {
603 // NEW_RULES has entry for new_it->first, but this RuleMap
604 // doesn't. This shouldn't be possible: NEW_RULES is some prior
605 // state, and there's no way to remove entries.
606 MOZ_ASSERT(0);
607 } else {
608 // Both maps have an entry for this register. Report the new
609 // rule if it is different.
610 if (*old_it->second != *new_it->second &&
611 !new_it->second->Handle(handler, address, new_it->first))
612 return false;
613 new_it++;
614 old_it++;
617 // Finish off entries from this RuleMap with no counterparts in new_rules.
618 while (old_it != registers_.end()) {
619 if (!handler->SameValueRule(address, old_it->first)) return false;
620 old_it++;
622 // Since we only make transitions from a rule set to some previously
623 // saved rule set, and we can only add rules to the map, NEW_RULES
624 // must have fewer rules than *this.
625 MOZ_ASSERT(new_it == new_rules.registers_.end());
627 return true;
630 // Remove all register rules and clear cfa_rule_.
631 void CallFrameInfo::RuleMap::Clear() {
632 delete cfa_rule_;
633 cfa_rule_ = NULL;
634 for (RuleByNumber::iterator it = registers_.begin(); it != registers_.end();
635 it++)
636 delete it->second;
637 registers_.clear();
640 // The state of the call frame information interpreter as it processes
641 // instructions from a CIE and FDE.
642 class CallFrameInfo::State {
643 public:
644 // Create a call frame information interpreter state with the given
645 // reporter, reader, handler, and initial call frame info address.
646 State(ByteReader* reader, Handler* handler, Reporter* reporter,
647 uint64 address)
648 : reader_(reader),
649 handler_(handler),
650 reporter_(reporter),
651 address_(address),
652 entry_(NULL),
653 cursor_(NULL),
654 saved_rules_(NULL) {}
656 ~State() {
657 if (saved_rules_) delete saved_rules_;
660 // Interpret instructions from CIE, save the resulting rule set for
661 // DW_CFA_restore instructions, and return true. On error, report
662 // the problem to reporter_ and return false.
663 bool InterpretCIE(const CIE& cie);
665 // Interpret instructions from FDE, and return true. On error,
666 // report the problem to reporter_ and return false.
667 bool InterpretFDE(const FDE& fde);
669 private:
670 // The operands of a CFI instruction, for ParseOperands.
671 struct Operands {
672 unsigned register_number; // A register number.
673 uint64 offset; // An offset or address.
674 long signed_offset; // A signed offset.
675 string expression; // A DWARF expression.
678 // Parse CFI instruction operands from STATE's instruction stream as
679 // described by FORMAT. On success, populate OPERANDS with the
680 // results, and return true. On failure, report the problem and
681 // return false.
683 // Each character of FORMAT should be one of the following:
685 // 'r' unsigned LEB128 register number (OPERANDS->register_number)
686 // 'o' unsigned LEB128 offset (OPERANDS->offset)
687 // 's' signed LEB128 offset (OPERANDS->signed_offset)
688 // 'a' machine-size address (OPERANDS->offset)
689 // (If the CIE has a 'z' augmentation string, 'a' uses the
690 // encoding specified by the 'R' argument.)
691 // '1' a one-byte offset (OPERANDS->offset)
692 // '2' a two-byte offset (OPERANDS->offset)
693 // '4' a four-byte offset (OPERANDS->offset)
694 // '8' an eight-byte offset (OPERANDS->offset)
695 // 'e' a DW_FORM_block holding a (OPERANDS->expression)
696 // DWARF expression
697 bool ParseOperands(const char* format, Operands* operands);
699 // Interpret one CFI instruction from STATE's instruction stream, update
700 // STATE, report any rule changes to handler_, and return true. On
701 // failure, report the problem and return false.
702 bool DoInstruction();
704 // The following Do* member functions are subroutines of DoInstruction,
705 // factoring out the actual work of operations that have several
706 // different encodings.
708 // Set the CFA rule to be the value of BASE_REGISTER plus OFFSET, and
709 // return true. On failure, report and return false. (Used for
710 // DW_CFA_def_cfa and DW_CFA_def_cfa_sf.)
711 bool DoDefCFA(unsigned base_register, long offset);
713 // Change the offset of the CFA rule to OFFSET, and return true. On
714 // failure, report and return false. (Subroutine for
715 // DW_CFA_def_cfa_offset and DW_CFA_def_cfa_offset_sf.)
716 bool DoDefCFAOffset(long offset);
718 // Specify that REG can be recovered using RULE, and return true. On
719 // failure, report and return false.
720 bool DoRule(unsigned reg, Rule* rule);
722 // Specify that REG can be found at OFFSET from the CFA, and return true.
723 // On failure, report and return false. (Subroutine for DW_CFA_offset,
724 // DW_CFA_offset_extended, and DW_CFA_offset_extended_sf.)
725 bool DoOffset(unsigned reg, long offset);
727 // Specify that the caller's value for REG is the CFA plus OFFSET,
728 // and return true. On failure, report and return false. (Subroutine
729 // for DW_CFA_val_offset and DW_CFA_val_offset_sf.)
730 bool DoValOffset(unsigned reg, long offset);
732 // Restore REG to the rule established in the CIE, and return true. On
733 // failure, report and return false. (Subroutine for DW_CFA_restore and
734 // DW_CFA_restore_extended.)
735 bool DoRestore(unsigned reg);
737 // Return the section offset of the instruction at cursor. For use
738 // in error messages.
739 uint64 CursorOffset() { return entry_->offset + (cursor_ - entry_->start); }
741 // Report that entry_ is incomplete, and return false. For brevity.
742 bool ReportIncomplete() {
743 reporter_->Incomplete(entry_->offset, entry_->kind);
744 return false;
747 // For reading multi-byte values with the appropriate endianness.
748 ByteReader* reader_;
750 // The handler to which we should report the data we find.
751 Handler* handler_;
753 // For reporting problems in the info we're parsing.
754 Reporter* reporter_;
756 // The code address to which the next instruction in the stream applies.
757 uint64 address_;
759 // The entry whose instructions we are currently processing. This is
760 // first a CIE, and then an FDE.
761 const Entry* entry_;
763 // The next instruction to process.
764 const char* cursor_;
766 // The current set of rules.
767 RuleMap rules_;
769 // The set of rules established by the CIE, used by DW_CFA_restore
770 // and DW_CFA_restore_extended. We set this after interpreting the
771 // CIE's instructions.
772 RuleMap cie_rules_;
774 // A stack of saved states, for DW_CFA_remember_state and
775 // DW_CFA_restore_state.
776 std::stack<RuleMap>* saved_rules_;
779 bool CallFrameInfo::State::InterpretCIE(const CIE& cie) {
780 entry_ = &cie;
781 cursor_ = entry_->instructions;
782 while (cursor_ < entry_->end)
783 if (!DoInstruction()) return false;
784 // Note the rules established by the CIE, for use by DW_CFA_restore
785 // and DW_CFA_restore_extended.
786 cie_rules_ = rules_;
787 return true;
790 bool CallFrameInfo::State::InterpretFDE(const FDE& fde) {
791 entry_ = &fde;
792 cursor_ = entry_->instructions;
793 while (cursor_ < entry_->end)
794 if (!DoInstruction()) return false;
795 return true;
798 bool CallFrameInfo::State::ParseOperands(const char* format,
799 Operands* operands) {
800 size_t len;
801 const char* operand;
803 for (operand = format; *operand; operand++) {
804 size_t bytes_left = entry_->end - cursor_;
805 switch (*operand) {
806 case 'r':
807 operands->register_number = reader_->ReadUnsignedLEB128(cursor_, &len);
808 if (len > bytes_left) return ReportIncomplete();
809 cursor_ += len;
810 break;
812 case 'o':
813 operands->offset = reader_->ReadUnsignedLEB128(cursor_, &len);
814 if (len > bytes_left) return ReportIncomplete();
815 cursor_ += len;
816 break;
818 case 's':
819 operands->signed_offset = reader_->ReadSignedLEB128(cursor_, &len);
820 if (len > bytes_left) return ReportIncomplete();
821 cursor_ += len;
822 break;
824 case 'a':
825 operands->offset = reader_->ReadEncodedPointer(
826 cursor_, entry_->cie->pointer_encoding, &len);
827 if (len > bytes_left) return ReportIncomplete();
828 cursor_ += len;
829 break;
831 case '1':
832 if (1 > bytes_left) return ReportIncomplete();
833 operands->offset = static_cast<unsigned char>(*cursor_++);
834 break;
836 case '2':
837 if (2 > bytes_left) return ReportIncomplete();
838 operands->offset = reader_->ReadTwoBytes(cursor_);
839 cursor_ += 2;
840 break;
842 case '4':
843 if (4 > bytes_left) return ReportIncomplete();
844 operands->offset = reader_->ReadFourBytes(cursor_);
845 cursor_ += 4;
846 break;
848 case '8':
849 if (8 > bytes_left) return ReportIncomplete();
850 operands->offset = reader_->ReadEightBytes(cursor_);
851 cursor_ += 8;
852 break;
854 case 'e': {
855 size_t expression_length = reader_->ReadUnsignedLEB128(cursor_, &len);
856 if (len > bytes_left || expression_length > bytes_left - len)
857 return ReportIncomplete();
858 cursor_ += len;
859 operands->expression = string(cursor_, expression_length);
860 cursor_ += expression_length;
861 break;
864 default:
865 MOZ_ASSERT(0);
869 return true;
872 bool CallFrameInfo::State::DoInstruction() {
873 CIE* cie = entry_->cie;
874 Operands ops;
876 // Our entry's kind should have been set by now.
877 MOZ_ASSERT(entry_->kind != kUnknown);
879 // We shouldn't have been invoked unless there were more
880 // instructions to parse.
881 MOZ_ASSERT(cursor_ < entry_->end);
883 unsigned opcode = *cursor_++;
884 if ((opcode & 0xc0) != 0) {
885 switch (opcode & 0xc0) {
886 // Advance the address.
887 case DW_CFA_advance_loc: {
888 size_t code_offset = opcode & 0x3f;
889 address_ += code_offset * cie->code_alignment_factor;
890 break;
893 // Find a register at an offset from the CFA.
894 case DW_CFA_offset:
895 if (!ParseOperands("o", &ops) ||
896 !DoOffset(opcode & 0x3f, ops.offset * cie->data_alignment_factor))
897 return false;
898 break;
900 // Restore the rule established for a register by the CIE.
901 case DW_CFA_restore:
902 if (!DoRestore(opcode & 0x3f)) return false;
903 break;
905 // The 'if' above should have excluded this possibility.
906 default:
907 MOZ_ASSERT(0);
910 // Return here, so the big switch below won't be indented.
911 return true;
914 switch (opcode) {
915 // Set the address.
916 case DW_CFA_set_loc:
917 if (!ParseOperands("a", &ops)) return false;
918 address_ = ops.offset;
919 break;
921 // Advance the address.
922 case DW_CFA_advance_loc1:
923 if (!ParseOperands("1", &ops)) return false;
924 address_ += ops.offset * cie->code_alignment_factor;
925 break;
927 // Advance the address.
928 case DW_CFA_advance_loc2:
929 if (!ParseOperands("2", &ops)) return false;
930 address_ += ops.offset * cie->code_alignment_factor;
931 break;
933 // Advance the address.
934 case DW_CFA_advance_loc4:
935 if (!ParseOperands("4", &ops)) return false;
936 address_ += ops.offset * cie->code_alignment_factor;
937 break;
939 // Advance the address.
940 case DW_CFA_MIPS_advance_loc8:
941 if (!ParseOperands("8", &ops)) return false;
942 address_ += ops.offset * cie->code_alignment_factor;
943 break;
945 // Compute the CFA by adding an offset to a register.
946 case DW_CFA_def_cfa:
947 if (!ParseOperands("ro", &ops) ||
948 !DoDefCFA(ops.register_number, ops.offset))
949 return false;
950 break;
952 // Compute the CFA by adding an offset to a register.
953 case DW_CFA_def_cfa_sf:
954 if (!ParseOperands("rs", &ops) ||
955 !DoDefCFA(ops.register_number,
956 ops.signed_offset * cie->data_alignment_factor))
957 return false;
958 break;
960 // Change the base register used to compute the CFA.
961 case DW_CFA_def_cfa_register: {
962 Rule* cfa_rule = rules_.CFARule();
963 if (!cfa_rule) {
964 reporter_->NoCFARule(entry_->offset, entry_->kind, CursorOffset());
965 return false;
967 if (!ParseOperands("r", &ops)) return false;
968 cfa_rule->SetBaseRegister(ops.register_number);
969 if (!cfa_rule->Handle(handler_, address_, Handler::kCFARegister))
970 return false;
971 break;
974 // Change the offset used to compute the CFA.
975 case DW_CFA_def_cfa_offset:
976 if (!ParseOperands("o", &ops) || !DoDefCFAOffset(ops.offset))
977 return false;
978 break;
980 // Change the offset used to compute the CFA.
981 case DW_CFA_def_cfa_offset_sf:
982 if (!ParseOperands("s", &ops) ||
983 !DoDefCFAOffset(ops.signed_offset * cie->data_alignment_factor))
984 return false;
985 break;
987 // Specify an expression whose value is the CFA.
988 case DW_CFA_def_cfa_expression: {
989 if (!ParseOperands("e", &ops)) return false;
990 Rule* rule = new ValExpressionRule(ops.expression);
991 rules_.SetCFARule(rule);
992 if (!rule->Handle(handler_, address_, Handler::kCFARegister))
993 return false;
994 break;
997 // The register's value cannot be recovered.
998 case DW_CFA_undefined: {
999 if (!ParseOperands("r", &ops) ||
1000 !DoRule(ops.register_number, new UndefinedRule()))
1001 return false;
1002 break;
1005 // The register's value is unchanged from its value in the caller.
1006 case DW_CFA_same_value: {
1007 if (!ParseOperands("r", &ops) ||
1008 !DoRule(ops.register_number, new SameValueRule()))
1009 return false;
1010 break;
1013 // Find a register at an offset from the CFA.
1014 case DW_CFA_offset_extended:
1015 if (!ParseOperands("ro", &ops) ||
1016 !DoOffset(ops.register_number,
1017 ops.offset * cie->data_alignment_factor))
1018 return false;
1019 break;
1021 // The register is saved at an offset from the CFA.
1022 case DW_CFA_offset_extended_sf:
1023 if (!ParseOperands("rs", &ops) ||
1024 !DoOffset(ops.register_number,
1025 ops.signed_offset * cie->data_alignment_factor))
1026 return false;
1027 break;
1029 // The register is saved at an offset from the CFA.
1030 case DW_CFA_GNU_negative_offset_extended:
1031 if (!ParseOperands("ro", &ops) ||
1032 !DoOffset(ops.register_number,
1033 -ops.offset * cie->data_alignment_factor))
1034 return false;
1035 break;
1037 // The register's value is the sum of the CFA plus an offset.
1038 case DW_CFA_val_offset:
1039 if (!ParseOperands("ro", &ops) ||
1040 !DoValOffset(ops.register_number,
1041 ops.offset * cie->data_alignment_factor))
1042 return false;
1043 break;
1045 // The register's value is the sum of the CFA plus an offset.
1046 case DW_CFA_val_offset_sf:
1047 if (!ParseOperands("rs", &ops) ||
1048 !DoValOffset(ops.register_number,
1049 ops.signed_offset * cie->data_alignment_factor))
1050 return false;
1051 break;
1053 // The register has been saved in another register.
1054 case DW_CFA_register: {
1055 if (!ParseOperands("ro", &ops) ||
1056 !DoRule(ops.register_number, new RegisterRule(ops.offset)))
1057 return false;
1058 break;
1061 // An expression yields the address at which the register is saved.
1062 case DW_CFA_expression: {
1063 if (!ParseOperands("re", &ops) ||
1064 !DoRule(ops.register_number, new ExpressionRule(ops.expression)))
1065 return false;
1066 break;
1069 // An expression yields the caller's value for the register.
1070 case DW_CFA_val_expression: {
1071 if (!ParseOperands("re", &ops) ||
1072 !DoRule(ops.register_number, new ValExpressionRule(ops.expression)))
1073 return false;
1074 break;
1077 // Restore the rule established for a register by the CIE.
1078 case DW_CFA_restore_extended:
1079 if (!ParseOperands("r", &ops) || !DoRestore(ops.register_number))
1080 return false;
1081 break;
1083 // Save the current set of rules on a stack.
1084 case DW_CFA_remember_state:
1085 if (!saved_rules_) {
1086 saved_rules_ = new std::stack<RuleMap>();
1088 saved_rules_->push(rules_);
1089 break;
1091 // Pop the current set of rules off the stack.
1092 case DW_CFA_restore_state: {
1093 if (!saved_rules_ || saved_rules_->empty()) {
1094 reporter_->EmptyStateStack(entry_->offset, entry_->kind,
1095 CursorOffset());
1096 return false;
1098 const RuleMap& new_rules = saved_rules_->top();
1099 if (rules_.CFARule() && !new_rules.CFARule()) {
1100 reporter_->ClearingCFARule(entry_->offset, entry_->kind,
1101 CursorOffset());
1102 return false;
1104 rules_.HandleTransitionTo(handler_, address_, new_rules);
1105 rules_ = new_rules;
1106 saved_rules_->pop();
1107 break;
1110 // No operation. (Padding instruction.)
1111 case DW_CFA_nop:
1112 break;
1114 // A SPARC register window save: Registers 8 through 15 (%o0-%o7)
1115 // are saved in registers 24 through 31 (%i0-%i7), and registers
1116 // 16 through 31 (%l0-%l7 and %i0-%i7) are saved at CFA offsets
1117 // (0-15 * the register size). The register numbers must be
1118 // hard-coded. A GNU extension, and not a pretty one.
1119 case DW_CFA_GNU_window_save: {
1120 // Save %o0-%o7 in %i0-%i7.
1121 for (int i = 8; i < 16; i++)
1122 if (!DoRule(i, new RegisterRule(i + 16))) return false;
1123 // Save %l0-%l7 and %i0-%i7 at the CFA.
1124 for (int i = 16; i < 32; i++)
1125 // Assume that the byte reader's address size is the same as
1126 // the architecture's register size. !@#%*^ hilarious.
1127 if (!DoRule(i, new OffsetRule(Handler::kCFARegister,
1128 (i - 16) * reader_->AddressSize())))
1129 return false;
1130 break;
1133 // I'm not sure what this is. GDB doesn't use it for unwinding.
1134 case DW_CFA_GNU_args_size:
1135 if (!ParseOperands("o", &ops)) return false;
1136 break;
1138 // An opcode we don't recognize.
1139 default: {
1140 reporter_->BadInstruction(entry_->offset, entry_->kind, CursorOffset());
1141 return false;
1145 return true;
1148 bool CallFrameInfo::State::DoDefCFA(unsigned base_register, long offset) {
1149 Rule* rule = new ValOffsetRule(base_register, offset);
1150 rules_.SetCFARule(rule);
1151 return rule->Handle(handler_, address_, Handler::kCFARegister);
1154 bool CallFrameInfo::State::DoDefCFAOffset(long offset) {
1155 Rule* cfa_rule = rules_.CFARule();
1156 if (!cfa_rule) {
1157 reporter_->NoCFARule(entry_->offset, entry_->kind, CursorOffset());
1158 return false;
1160 cfa_rule->SetOffset(offset);
1161 return cfa_rule->Handle(handler_, address_, Handler::kCFARegister);
1164 bool CallFrameInfo::State::DoRule(unsigned reg, Rule* rule) {
1165 rules_.SetRegisterRule(reg, rule);
1166 return rule->Handle(handler_, address_, reg);
1169 bool CallFrameInfo::State::DoOffset(unsigned reg, long offset) {
1170 if (!rules_.CFARule()) {
1171 reporter_->NoCFARule(entry_->offset, entry_->kind, CursorOffset());
1172 return false;
1174 return DoRule(reg, new OffsetRule(Handler::kCFARegister, offset));
1177 bool CallFrameInfo::State::DoValOffset(unsigned reg, long offset) {
1178 if (!rules_.CFARule()) {
1179 reporter_->NoCFARule(entry_->offset, entry_->kind, CursorOffset());
1180 return false;
1182 return DoRule(reg, new ValOffsetRule(Handler::kCFARegister, offset));
1185 bool CallFrameInfo::State::DoRestore(unsigned reg) {
1186 // DW_CFA_restore and DW_CFA_restore_extended don't make sense in a CIE.
1187 if (entry_->kind == kCIE) {
1188 reporter_->RestoreInCIE(entry_->offset, CursorOffset());
1189 return false;
1191 Rule* rule = cie_rules_.RegisterRule(reg);
1192 if (!rule) {
1193 // This isn't really the right thing to do, but since CFI generally
1194 // only mentions callee-saves registers, and GCC's convention for
1195 // callee-saves registers is that they are unchanged, it's a good
1196 // approximation.
1197 rule = new SameValueRule();
1199 return DoRule(reg, rule);
1202 bool CallFrameInfo::ReadEntryPrologue(const char* cursor, Entry* entry) {
1203 const char* buffer_end = buffer_ + buffer_length_;
1205 // Initialize enough of ENTRY for use in error reporting.
1206 entry->offset = cursor - buffer_;
1207 entry->start = cursor;
1208 entry->kind = kUnknown;
1209 entry->end = NULL;
1211 // Read the initial length. This sets reader_'s offset size.
1212 size_t length_size;
1213 uint64 length = reader_->ReadInitialLength(cursor, &length_size);
1214 if (length_size > size_t(buffer_end - cursor)) return ReportIncomplete(entry);
1215 cursor += length_size;
1217 // In a .eh_frame section, a length of zero marks the end of the series
1218 // of entries.
1219 if (length == 0 && eh_frame_) {
1220 entry->kind = kTerminator;
1221 entry->end = cursor;
1222 return true;
1225 // Validate the length.
1226 if (length > size_t(buffer_end - cursor)) return ReportIncomplete(entry);
1228 // The length is the number of bytes after the initial length field;
1229 // we have that position handy at this point, so compute the end
1230 // now. (If we're parsing 64-bit-offset DWARF on a 32-bit machine,
1231 // and the length didn't fit in a size_t, we would have rejected it
1232 // above.)
1233 entry->end = cursor + length;
1235 // Parse the next field: either the offset of a CIE or a CIE id.
1236 size_t offset_size = reader_->OffsetSize();
1237 if (offset_size > size_t(entry->end - cursor)) return ReportIncomplete(entry);
1238 entry->id = reader_->ReadOffset(cursor);
1240 // Don't advance cursor past id field yet; in .eh_frame data we need
1241 // the id's position to compute the section offset of an FDE's CIE.
1243 // Now we can decide what kind of entry this is.
1244 if (eh_frame_) {
1245 // In .eh_frame data, an ID of zero marks the entry as a CIE, and
1246 // anything else is an offset from the id field of the FDE to the start
1247 // of the CIE.
1248 if (entry->id == 0) {
1249 entry->kind = kCIE;
1250 } else {
1251 entry->kind = kFDE;
1252 // Turn the offset from the id into an offset from the buffer's start.
1253 entry->id = (cursor - buffer_) - entry->id;
1255 } else {
1256 // In DWARF CFI data, an ID of ~0 (of the appropriate width, given the
1257 // offset size for the entry) marks the entry as a CIE, and anything
1258 // else is the offset of the CIE from the beginning of the section.
1259 if (offset_size == 4)
1260 entry->kind = (entry->id == 0xffffffff) ? kCIE : kFDE;
1261 else {
1262 MOZ_ASSERT(offset_size == 8);
1263 entry->kind = (entry->id == 0xffffffffffffffffULL) ? kCIE : kFDE;
1267 // Now advance cursor past the id.
1268 cursor += offset_size;
1270 // The fields specific to this kind of entry start here.
1271 entry->fields = cursor;
1273 entry->cie = NULL;
1275 return true;
1278 bool CallFrameInfo::ReadCIEFields(CIE* cie) {
1279 const char* cursor = cie->fields;
1280 size_t len;
1282 MOZ_ASSERT(cie->kind == kCIE);
1284 // Prepare for early exit.
1285 cie->version = 0;
1286 cie->augmentation.clear();
1287 cie->code_alignment_factor = 0;
1288 cie->data_alignment_factor = 0;
1289 cie->return_address_register = 0;
1290 cie->has_z_augmentation = false;
1291 cie->pointer_encoding = DW_EH_PE_absptr;
1292 cie->instructions = 0;
1294 // Parse the version number.
1295 if (cie->end - cursor < 1) return ReportIncomplete(cie);
1296 cie->version = reader_->ReadOneByte(cursor);
1297 cursor++;
1299 // If we don't recognize the version, we can't parse any more fields of the
1300 // CIE. For DWARF CFI, we handle versions 1 through 4 (there was never a
1301 // version 2 of CFI data). For .eh_frame, we handle versions 1 and 4 as well;
1302 // the difference between those versions seems to be the same as for
1303 // .debug_frame.
1304 if (cie->version < 1 || cie->version > 4) {
1305 reporter_->UnrecognizedVersion(cie->offset, cie->version);
1306 return false;
1309 const char* augmentation_start = cursor;
1310 const void* augmentation_end =
1311 memchr(augmentation_start, '\0', cie->end - augmentation_start);
1312 if (!augmentation_end) return ReportIncomplete(cie);
1313 cursor = static_cast<const char*>(augmentation_end);
1314 cie->augmentation = string(augmentation_start, cursor - augmentation_start);
1315 // Skip the terminating '\0'.
1316 cursor++;
1318 // Is this CFI augmented?
1319 if (!cie->augmentation.empty()) {
1320 // Is it an augmentation we recognize?
1321 if (cie->augmentation[0] == DW_Z_augmentation_start) {
1322 // Linux C++ ABI 'z' augmentation, used for exception handling data.
1323 cie->has_z_augmentation = true;
1324 } else {
1325 // Not an augmentation we recognize. Augmentations can have arbitrary
1326 // effects on the form of rest of the content, so we have to give up.
1327 reporter_->UnrecognizedAugmentation(cie->offset, cie->augmentation);
1328 return false;
1332 if (cie->version >= 4) {
1333 // Check that the address_size and segment_size fields are plausible.
1334 if (cie->end - cursor < 2) {
1335 return ReportIncomplete(cie);
1337 uint8_t address_size = reader_->ReadOneByte(cursor);
1338 cursor++;
1339 if (address_size != sizeof(void*)) {
1340 // This is not per-se invalid CFI. But we can reasonably expect to
1341 // be running on a target of the same word size as the CFI is for,
1342 // so we reject this case.
1343 reporter_->InvalidDwarf4Artefact(cie->offset, "Invalid address_size");
1344 return false;
1346 uint8_t segment_size = reader_->ReadOneByte(cursor);
1347 cursor++;
1348 if (segment_size != 0) {
1349 // This is also not per-se invalid CFI, but we don't currently handle
1350 // the case of non-zero |segment_size|.
1351 reporter_->InvalidDwarf4Artefact(cie->offset, "Invalid segment_size");
1352 return false;
1354 // We only continue parsing if |segment_size| is zero. If this routine
1355 // is ever changed to allow non-zero |segment_size|, then
1356 // ReadFDEFields() below will have to be changed to match, per comments
1357 // there.
1360 // Parse the code alignment factor.
1361 cie->code_alignment_factor = reader_->ReadUnsignedLEB128(cursor, &len);
1362 if (size_t(cie->end - cursor) < len) return ReportIncomplete(cie);
1363 cursor += len;
1365 // Parse the data alignment factor.
1366 cie->data_alignment_factor = reader_->ReadSignedLEB128(cursor, &len);
1367 if (size_t(cie->end - cursor) < len) return ReportIncomplete(cie);
1368 cursor += len;
1370 // Parse the return address register. This is a ubyte in version 1, and
1371 // a ULEB128 in version 3.
1372 if (cie->version == 1) {
1373 if (cursor >= cie->end) return ReportIncomplete(cie);
1374 cie->return_address_register = uint8(*cursor++);
1375 } else {
1376 cie->return_address_register = reader_->ReadUnsignedLEB128(cursor, &len);
1377 if (size_t(cie->end - cursor) < len) return ReportIncomplete(cie);
1378 cursor += len;
1381 // If we have a 'z' augmentation string, find the augmentation data and
1382 // use the augmentation string to parse it.
1383 if (cie->has_z_augmentation) {
1384 uint64_t data_size = reader_->ReadUnsignedLEB128(cursor, &len);
1385 if (size_t(cie->end - cursor) < len + data_size)
1386 return ReportIncomplete(cie);
1387 cursor += len;
1388 const char* data = cursor;
1389 cursor += data_size;
1390 const char* data_end = cursor;
1392 cie->has_z_lsda = false;
1393 cie->has_z_personality = false;
1394 cie->has_z_signal_frame = false;
1396 // Walk the augmentation string, and extract values from the
1397 // augmentation data as the string directs.
1398 for (size_t i = 1; i < cie->augmentation.size(); i++) {
1399 switch (cie->augmentation[i]) {
1400 case DW_Z_has_LSDA:
1401 // The CIE's augmentation data holds the language-specific data
1402 // area pointer's encoding, and the FDE's augmentation data holds
1403 // the pointer itself.
1404 cie->has_z_lsda = true;
1405 // Fetch the LSDA encoding from the augmentation data.
1406 if (data >= data_end) return ReportIncomplete(cie);
1407 cie->lsda_encoding = DwarfPointerEncoding(*data++);
1408 if (!reader_->ValidEncoding(cie->lsda_encoding)) {
1409 reporter_->InvalidPointerEncoding(cie->offset, cie->lsda_encoding);
1410 return false;
1412 // Don't check if the encoding is usable here --- we haven't
1413 // read the FDE's fields yet, so we're not prepared for
1414 // DW_EH_PE_funcrel, although that's a fine encoding for the
1415 // LSDA to use, since it appears in the FDE.
1416 break;
1418 case DW_Z_has_personality_routine:
1419 // The CIE's augmentation data holds the personality routine
1420 // pointer's encoding, followed by the pointer itself.
1421 cie->has_z_personality = true;
1422 // Fetch the personality routine pointer's encoding from the
1423 // augmentation data.
1424 if (data >= data_end) return ReportIncomplete(cie);
1425 cie->personality_encoding = DwarfPointerEncoding(*data++);
1426 if (!reader_->ValidEncoding(cie->personality_encoding)) {
1427 reporter_->InvalidPointerEncoding(cie->offset,
1428 cie->personality_encoding);
1429 return false;
1431 if (!reader_->UsableEncoding(cie->personality_encoding)) {
1432 reporter_->UnusablePointerEncoding(cie->offset,
1433 cie->personality_encoding);
1434 return false;
1436 // Fetch the personality routine's pointer itself from the data.
1437 cie->personality_address = reader_->ReadEncodedPointer(
1438 data, cie->personality_encoding, &len);
1439 if (len > size_t(data_end - data)) return ReportIncomplete(cie);
1440 data += len;
1441 break;
1443 case DW_Z_has_FDE_address_encoding:
1444 // The CIE's augmentation data holds the pointer encoding to use
1445 // for addresses in the FDE.
1446 if (data >= data_end) return ReportIncomplete(cie);
1447 cie->pointer_encoding = DwarfPointerEncoding(*data++);
1448 if (!reader_->ValidEncoding(cie->pointer_encoding)) {
1449 reporter_->InvalidPointerEncoding(cie->offset,
1450 cie->pointer_encoding);
1451 return false;
1453 if (!reader_->UsableEncoding(cie->pointer_encoding)) {
1454 reporter_->UnusablePointerEncoding(cie->offset,
1455 cie->pointer_encoding);
1456 return false;
1458 break;
1460 case DW_Z_is_signal_trampoline:
1461 // Frames using this CIE are signal delivery frames.
1462 cie->has_z_signal_frame = true;
1463 break;
1465 default:
1466 // An augmentation we don't recognize.
1467 reporter_->UnrecognizedAugmentation(cie->offset, cie->augmentation);
1468 return false;
1473 // The CIE's instructions start here.
1474 cie->instructions = cursor;
1476 return true;
1479 bool CallFrameInfo::ReadFDEFields(FDE* fde) {
1480 const char* cursor = fde->fields;
1481 size_t size;
1483 // At this point, for Dwarf 4 and above, we are assuming that the
1484 // associated CIE has its |segment_size| field equal to zero. This is
1485 // checked for in ReadCIEFields() above. If ReadCIEFields() is ever
1486 // changed to allow non-zero |segment_size| CIEs then we will have to read
1487 // the segment_selector value at this point.
1489 fde->address =
1490 reader_->ReadEncodedPointer(cursor, fde->cie->pointer_encoding, &size);
1491 if (size > size_t(fde->end - cursor)) return ReportIncomplete(fde);
1492 cursor += size;
1493 reader_->SetFunctionBase(fde->address);
1495 // For the length, we strip off the upper nybble of the encoding used for
1496 // the starting address.
1497 DwarfPointerEncoding length_encoding =
1498 DwarfPointerEncoding(fde->cie->pointer_encoding & 0x0f);
1499 fde->size = reader_->ReadEncodedPointer(cursor, length_encoding, &size);
1500 if (size > size_t(fde->end - cursor)) return ReportIncomplete(fde);
1501 cursor += size;
1503 // If the CIE has a 'z' augmentation string, then augmentation data
1504 // appears here.
1505 if (fde->cie->has_z_augmentation) {
1506 uint64_t data_size = reader_->ReadUnsignedLEB128(cursor, &size);
1507 if (size_t(fde->end - cursor) < size + data_size)
1508 return ReportIncomplete(fde);
1509 cursor += size;
1511 // In the abstract, we should walk the augmentation string, and extract
1512 // items from the FDE's augmentation data as we encounter augmentation
1513 // string characters that specify their presence: the ordering of items
1514 // in the augmentation string determines the arrangement of values in
1515 // the augmentation data.
1517 // In practice, there's only ever one value in FDE augmentation data
1518 // that we support --- the LSDA pointer --- and we have to bail if we
1519 // see any unrecognized augmentation string characters. So if there is
1520 // anything here at all, we know what it is, and where it starts.
1521 if (fde->cie->has_z_lsda) {
1522 // Check whether the LSDA's pointer encoding is usable now: only once
1523 // we've parsed the FDE's starting address do we call reader_->
1524 // SetFunctionBase, so that the DW_EH_PE_funcrel encoding becomes
1525 // usable.
1526 if (!reader_->UsableEncoding(fde->cie->lsda_encoding)) {
1527 reporter_->UnusablePointerEncoding(fde->cie->offset,
1528 fde->cie->lsda_encoding);
1529 return false;
1532 fde->lsda_address =
1533 reader_->ReadEncodedPointer(cursor, fde->cie->lsda_encoding, &size);
1534 if (size > data_size) return ReportIncomplete(fde);
1535 // Ideally, we would also complain here if there were unconsumed
1536 // augmentation data.
1539 cursor += data_size;
1542 // The FDE's instructions start after those.
1543 fde->instructions = cursor;
1545 return true;
1548 bool CallFrameInfo::Start() {
1549 const char* buffer_end = buffer_ + buffer_length_;
1550 const char* cursor;
1551 bool all_ok = true;
1552 const char* entry_end;
1553 bool ok;
1555 // Traverse all the entries in buffer_, skipping CIEs and offering
1556 // FDEs to the handler.
1557 for (cursor = buffer_; cursor < buffer_end;
1558 cursor = entry_end, all_ok = all_ok && ok) {
1559 FDE fde;
1561 // Make it easy to skip this entry with 'continue': assume that
1562 // things are not okay until we've checked all the data, and
1563 // prepare the address of the next entry.
1564 ok = false;
1566 // Read the entry's prologue.
1567 if (!ReadEntryPrologue(cursor, &fde)) {
1568 if (!fde.end) {
1569 // If we couldn't even figure out this entry's extent, then we
1570 // must stop processing entries altogether.
1571 all_ok = false;
1572 break;
1574 entry_end = fde.end;
1575 continue;
1578 // The next iteration picks up after this entry.
1579 entry_end = fde.end;
1581 // Did we see an .eh_frame terminating mark?
1582 if (fde.kind == kTerminator) {
1583 // If there appears to be more data left in the section after the
1584 // terminating mark, warn the user. But this is just a warning;
1585 // we leave all_ok true.
1586 if (fde.end < buffer_end) reporter_->EarlyEHTerminator(fde.offset);
1587 break;
1590 // In this loop, we skip CIEs. We only parse them fully when we
1591 // parse an FDE that refers to them. This limits our memory
1592 // consumption (beyond the buffer itself) to that needed to
1593 // process the largest single entry.
1594 if (fde.kind != kFDE) {
1595 ok = true;
1596 continue;
1599 // Validate the CIE pointer.
1600 if (fde.id > buffer_length_) {
1601 reporter_->CIEPointerOutOfRange(fde.offset, fde.id);
1602 continue;
1605 CIE cie;
1607 // Parse this FDE's CIE header.
1608 if (!ReadEntryPrologue(buffer_ + fde.id, &cie)) continue;
1609 // This had better be an actual CIE.
1610 if (cie.kind != kCIE) {
1611 reporter_->BadCIEId(fde.offset, fde.id);
1612 continue;
1614 if (!ReadCIEFields(&cie)) continue;
1616 // We now have the values that govern both the CIE and the FDE.
1617 cie.cie = &cie;
1618 fde.cie = &cie;
1620 // Parse the FDE's header.
1621 if (!ReadFDEFields(&fde)) continue;
1623 // Call Entry to ask the consumer if they're interested.
1624 if (!handler_->Entry(fde.offset, fde.address, fde.size, cie.version,
1625 cie.augmentation, cie.return_address_register)) {
1626 // The handler isn't interested in this entry. That's not an error.
1627 ok = true;
1628 continue;
1631 if (cie.has_z_augmentation) {
1632 // Report the personality routine address, if we have one.
1633 if (cie.has_z_personality) {
1634 if (!handler_->PersonalityRoutine(
1635 cie.personality_address,
1636 IsIndirectEncoding(cie.personality_encoding)))
1637 continue;
1640 // Report the language-specific data area address, if we have one.
1641 if (cie.has_z_lsda) {
1642 if (!handler_->LanguageSpecificDataArea(
1643 fde.lsda_address, IsIndirectEncoding(cie.lsda_encoding)))
1644 continue;
1647 // If this is a signal-handling frame, report that.
1648 if (cie.has_z_signal_frame) {
1649 if (!handler_->SignalHandler()) continue;
1653 // Interpret the CIE's instructions, and then the FDE's instructions.
1654 State state(reader_, handler_, reporter_, fde.address);
1655 ok = state.InterpretCIE(cie) && state.InterpretFDE(fde);
1657 // Tell the ByteReader that the function start address from the
1658 // FDE header is no longer valid.
1659 reader_->ClearFunctionBase();
1661 // Report the end of the entry.
1662 handler_->End();
1665 return all_ok;
1668 const char* CallFrameInfo::KindName(EntryKind kind) {
1669 if (kind == CallFrameInfo::kUnknown)
1670 return "entry";
1671 else if (kind == CallFrameInfo::kCIE)
1672 return "common information entry";
1673 else if (kind == CallFrameInfo::kFDE)
1674 return "frame description entry";
1675 else {
1676 MOZ_ASSERT(kind == CallFrameInfo::kTerminator);
1677 return ".eh_frame sequence terminator";
1681 bool CallFrameInfo::ReportIncomplete(Entry* entry) {
1682 reporter_->Incomplete(entry->offset, entry->kind);
1683 return false;
1686 void CallFrameInfo::Reporter::Incomplete(uint64 offset,
1687 CallFrameInfo::EntryKind kind) {
1688 char buf[300];
1689 SprintfLiteral(buf, "%s: CFI %s at offset 0x%llx in '%s': entry ends early\n",
1690 filename_.c_str(), CallFrameInfo::KindName(kind), offset,
1691 section_.c_str());
1692 log_(buf);
1695 void CallFrameInfo::Reporter::EarlyEHTerminator(uint64 offset) {
1696 char buf[300];
1697 SprintfLiteral(buf,
1698 "%s: CFI at offset 0x%llx in '%s': saw end-of-data marker"
1699 " before end of section contents\n",
1700 filename_.c_str(), offset, section_.c_str());
1701 log_(buf);
1704 void CallFrameInfo::Reporter::CIEPointerOutOfRange(uint64 offset,
1705 uint64 cie_offset) {
1706 char buf[300];
1707 SprintfLiteral(buf,
1708 "%s: CFI frame description entry at offset 0x%llx in '%s':"
1709 " CIE pointer is out of range: 0x%llx\n",
1710 filename_.c_str(), offset, section_.c_str(), cie_offset);
1711 log_(buf);
1714 void CallFrameInfo::Reporter::BadCIEId(uint64 offset, uint64 cie_offset) {
1715 char buf[300];
1716 SprintfLiteral(buf,
1717 "%s: CFI frame description entry at offset 0x%llx in '%s':"
1718 " CIE pointer does not point to a CIE: 0x%llx\n",
1719 filename_.c_str(), offset, section_.c_str(), cie_offset);
1720 log_(buf);
1723 void CallFrameInfo::Reporter::UnrecognizedVersion(uint64 offset, int version) {
1724 char buf[300];
1725 SprintfLiteral(buf,
1726 "%s: CFI frame description entry at offset 0x%llx in '%s':"
1727 " CIE specifies unrecognized version: %d\n",
1728 filename_.c_str(), offset, section_.c_str(), version);
1729 log_(buf);
1732 void CallFrameInfo::Reporter::UnrecognizedAugmentation(uint64 offset,
1733 const string& aug) {
1734 char buf[300];
1735 SprintfLiteral(buf,
1736 "%s: CFI frame description entry at offset 0x%llx in '%s':"
1737 " CIE specifies unrecognized augmentation: '%s'\n",
1738 filename_.c_str(), offset, section_.c_str(), aug.c_str());
1739 log_(buf);
1742 void CallFrameInfo::Reporter::InvalidDwarf4Artefact(uint64 offset,
1743 const char* what) {
1744 char* what_safe = strndup(what, 100);
1745 char buf[300];
1746 SprintfLiteral(buf,
1747 "%s: CFI frame description entry at offset 0x%llx in '%s':"
1748 " CIE specifies invalid Dwarf4 artefact: %s\n",
1749 filename_.c_str(), offset, section_.c_str(), what_safe);
1750 log_(buf);
1751 free(what_safe);
1754 void CallFrameInfo::Reporter::InvalidPointerEncoding(uint64 offset,
1755 uint8 encoding) {
1756 char buf[300];
1757 SprintfLiteral(buf,
1758 "%s: CFI common information entry at offset 0x%llx in '%s':"
1759 " 'z' augmentation specifies invalid pointer encoding: "
1760 "0x%02x\n",
1761 filename_.c_str(), offset, section_.c_str(), encoding);
1762 log_(buf);
1765 void CallFrameInfo::Reporter::UnusablePointerEncoding(uint64 offset,
1766 uint8 encoding) {
1767 char buf[300];
1768 SprintfLiteral(buf,
1769 "%s: CFI common information entry at offset 0x%llx in '%s':"
1770 " 'z' augmentation specifies a pointer encoding for which"
1771 " we have no base address: 0x%02x\n",
1772 filename_.c_str(), offset, section_.c_str(), encoding);
1773 log_(buf);
1776 void CallFrameInfo::Reporter::RestoreInCIE(uint64 offset, uint64 insn_offset) {
1777 char buf[300];
1778 SprintfLiteral(buf,
1779 "%s: CFI common information entry at offset 0x%llx in '%s':"
1780 " the DW_CFA_restore instruction at offset 0x%llx"
1781 " cannot be used in a common information entry\n",
1782 filename_.c_str(), offset, section_.c_str(), insn_offset);
1783 log_(buf);
1786 void CallFrameInfo::Reporter::BadInstruction(uint64 offset,
1787 CallFrameInfo::EntryKind kind,
1788 uint64 insn_offset) {
1789 char buf[300];
1790 SprintfLiteral(buf,
1791 "%s: CFI %s at offset 0x%llx in section '%s':"
1792 " the instruction at offset 0x%llx is unrecognized\n",
1793 filename_.c_str(), CallFrameInfo::KindName(kind), offset,
1794 section_.c_str(), insn_offset);
1795 log_(buf);
1798 void CallFrameInfo::Reporter::NoCFARule(uint64 offset,
1799 CallFrameInfo::EntryKind kind,
1800 uint64 insn_offset) {
1801 char buf[300];
1802 SprintfLiteral(buf,
1803 "%s: CFI %s at offset 0x%llx in section '%s':"
1804 " the instruction at offset 0x%llx assumes that a CFA rule "
1805 "has been set, but none has been set\n",
1806 filename_.c_str(), CallFrameInfo::KindName(kind), offset,
1807 section_.c_str(), insn_offset);
1808 log_(buf);
1811 void CallFrameInfo::Reporter::EmptyStateStack(uint64 offset,
1812 CallFrameInfo::EntryKind kind,
1813 uint64 insn_offset) {
1814 char buf[300];
1815 SprintfLiteral(buf,
1816 "%s: CFI %s at offset 0x%llx in section '%s':"
1817 " the DW_CFA_restore_state instruction at offset 0x%llx"
1818 " should pop a saved state from the stack, but the stack "
1819 "is empty\n",
1820 filename_.c_str(), CallFrameInfo::KindName(kind), offset,
1821 section_.c_str(), insn_offset);
1822 log_(buf);
1825 void CallFrameInfo::Reporter::ClearingCFARule(uint64 offset,
1826 CallFrameInfo::EntryKind kind,
1827 uint64 insn_offset) {
1828 char buf[300];
1829 SprintfLiteral(buf,
1830 "%s: CFI %s at offset 0x%llx in section '%s':"
1831 " the DW_CFA_restore_state instruction at offset 0x%llx"
1832 " would clear the CFA rule in effect\n",
1833 filename_.c_str(), CallFrameInfo::KindName(kind), offset,
1834 section_.c_str(), insn_offset);
1835 log_(buf);
1838 unsigned int DwarfCFIToModule::RegisterNames::I386() {
1840 8 "$eax", "$ecx", "$edx", "$ebx", "$esp", "$ebp", "$esi", "$edi",
1841 3 "$eip", "$eflags", "$unused1",
1842 8 "$st0", "$st1", "$st2", "$st3", "$st4", "$st5", "$st6", "$st7",
1843 2 "$unused2", "$unused3",
1844 8 "$xmm0", "$xmm1", "$xmm2", "$xmm3", "$xmm4", "$xmm5", "$xmm6", "$xmm7",
1845 8 "$mm0", "$mm1", "$mm2", "$mm3", "$mm4", "$mm5", "$mm6", "$mm7",
1846 3 "$fcw", "$fsw", "$mxcsr",
1847 8 "$es", "$cs", "$ss", "$ds", "$fs", "$gs", "$unused4", "$unused5",
1848 2 "$tr", "$ldtr"
1850 return 8 + 3 + 8 + 2 + 8 + 8 + 3 + 8 + 2;
1853 unsigned int DwarfCFIToModule::RegisterNames::X86_64() {
1855 8 "$rax", "$rdx", "$rcx", "$rbx", "$rsi", "$rdi", "$rbp", "$rsp",
1856 8 "$r8", "$r9", "$r10", "$r11", "$r12", "$r13", "$r14", "$r15",
1857 1 "$rip",
1858 8 "$xmm0","$xmm1","$xmm2", "$xmm3", "$xmm4", "$xmm5", "$xmm6", "$xmm7",
1859 8 "$xmm8","$xmm9","$xmm10","$xmm11","$xmm12","$xmm13","$xmm14","$xmm15",
1860 8 "$st0", "$st1", "$st2", "$st3", "$st4", "$st5", "$st6", "$st7",
1861 8 "$mm0", "$mm1", "$mm2", "$mm3", "$mm4", "$mm5", "$mm6", "$mm7",
1862 1 "$rflags",
1863 8 "$es", "$cs", "$ss", "$ds", "$fs", "$gs", "$unused1", "$unused2",
1864 4 "$fs.base", "$gs.base", "$unused3", "$unused4",
1865 2 "$tr", "$ldtr",
1866 3 "$mxcsr", "$fcw", "$fsw"
1868 return 8 + 8 + 1 + 8 + 8 + 8 + 8 + 1 + 8 + 4 + 2 + 3;
1871 // Per ARM IHI 0040A, section 3.1
1872 unsigned int DwarfCFIToModule::RegisterNames::ARM() {
1874 8 "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
1875 8 "r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc",
1876 8 "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
1877 8 "fps", "cpsr", "", "", "", "", "", "",
1878 8 "", "", "", "", "", "", "", "",
1879 8 "", "", "", "", "", "", "", "",
1880 8 "", "", "", "", "", "", "", "",
1881 8 "", "", "", "", "", "", "", "",
1882 8 "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
1883 8 "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15",
1884 8 "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23",
1885 8 "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31",
1886 8 "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7"
1888 return 13 * 8;
1891 // Per ARM IHI 0057A, section 3.1
1892 unsigned int DwarfCFIToModule::RegisterNames::ARM64() {
1894 8 "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7",
1895 8 "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15",
1896 8 "x16" "x17", "x18", "x19", "x20", "x21", "x22", "x23",
1897 8 "x24", "x25", "x26", "x27", "x28", "x29", "x30","sp",
1898 8 "", "", "", "", "", "", "", "",
1899 8 "", "", "", "", "", "", "", "",
1900 8 "", "", "", "", "", "", "", "",
1901 8 "", "", "", "", "", "", "", "",
1902 8 "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7",
1903 8 "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
1904 8 "v16", "v17", "v18", "v19", "v20", "v21", "v22, "v23",
1905 8 "v24", "x25", "x26, "x27", "v28", "v29", "v30", "v31",
1907 return 12 * 8;
1910 unsigned int DwarfCFIToModule::RegisterNames::MIPS() {
1912 8 "$zero", "$at", "$v0", "$v1", "$a0", "$a1", "$a2", "$a3",
1913 8 "$t0", "$t1", "$t2", "$t3", "$t4", "$t5", "$t6", "$t7",
1914 8 "$s0", "$s1", "$s2", "$s3", "$s4", "$s5", "$s6", "$s7",
1915 8 "$t8", "$t9", "$k0", "$k1", "$gp", "$sp", "$fp", "$ra",
1916 9 "$lo", "$hi", "$pc", "$f0", "$f1", "$f2", "$f3", "$f4", "$f5",
1917 8 "$f6", "$f7", "$f8", "$f9", "$f10", "$f11", "$f12", "$f13",
1918 7 "$f14", "$f15", "$f16", "$f17", "$f18", "$f19", "$f20",
1919 7 "$f21", "$f22", "$f23", "$f24", "$f25", "$f26", "$f27",
1920 6 "$f28", "$f29", "$f30", "$f31", "$fcsr", "$fir"
1922 return 8 + 8 + 8 + 8 + 9 + 8 + 7 + 7 + 6;
1925 // See prototype for comments.
1926 int32_t parseDwarfExpr(Summariser* summ, const ByteReader* reader, string expr,
1927 bool debug, bool pushCfaAtStart, bool derefAtEnd) {
1928 const char* cursor = expr.c_str();
1929 const char* end1 = cursor + expr.length();
1931 char buf[100];
1932 if (debug) {
1933 SprintfLiteral(buf, "LUL.DW << DwarfExpr, len is %d\n",
1934 (int)(end1 - cursor));
1935 summ->Log(buf);
1938 // Add a marker for the start of this expression. In it, indicate
1939 // whether or not the CFA should be pushed onto the stack prior to
1940 // evaluation.
1941 int32_t start_ix =
1942 summ->AddPfxInstr(PfxInstr(PX_Start, pushCfaAtStart ? 1 : 0));
1943 MOZ_ASSERT(start_ix >= 0);
1945 while (cursor < end1) {
1946 uint8 opc = reader->ReadOneByte(cursor);
1947 cursor++;
1949 const char* nm = nullptr;
1950 PfxExprOp pxop = PX_End;
1952 switch (opc) {
1953 case DW_OP_lit0 ... DW_OP_lit31: {
1954 int32_t simm32 = (int32_t)(opc - DW_OP_lit0);
1955 if (debug) {
1956 SprintfLiteral(buf, "LUL.DW DW_OP_lit%d\n", (int)simm32);
1957 summ->Log(buf);
1959 (void)summ->AddPfxInstr(PfxInstr(PX_SImm32, simm32));
1960 break;
1963 case DW_OP_breg0 ... DW_OP_breg31: {
1964 size_t len;
1965 int64_t n = reader->ReadSignedLEB128(cursor, &len);
1966 cursor += len;
1967 DW_REG_NUMBER reg = (DW_REG_NUMBER)(opc - DW_OP_breg0);
1968 if (debug) {
1969 SprintfLiteral(buf, "LUL.DW DW_OP_breg%d %lld\n", (int)reg,
1970 (long long int)n);
1971 summ->Log(buf);
1973 // PfxInstr only allows a 32 bit signed offset. So we
1974 // must fail if the immediate is out of range.
1975 if (n < INT32_MIN || INT32_MAX < n) goto fail;
1976 (void)summ->AddPfxInstr(PfxInstr(PX_DwReg, reg));
1977 (void)summ->AddPfxInstr(PfxInstr(PX_SImm32, (int32_t)n));
1978 (void)summ->AddPfxInstr(PfxInstr(PX_Add));
1979 break;
1982 case DW_OP_const4s: {
1983 uint64_t u64 = reader->ReadFourBytes(cursor);
1984 cursor += 4;
1985 // u64 is guaranteed by |ReadFourBytes| to be in the
1986 // range 0 .. FFFFFFFF inclusive. But to be safe:
1987 uint32_t u32 = (uint32_t)(u64 & 0xFFFFFFFF);
1988 int32_t s32 = (int32_t)u32;
1989 if (debug) {
1990 SprintfLiteral(buf, "LUL.DW DW_OP_const4s %d\n", (int)s32);
1991 summ->Log(buf);
1993 (void)summ->AddPfxInstr(PfxInstr(PX_SImm32, s32));
1994 break;
1997 case DW_OP_deref:
1998 nm = "deref";
1999 pxop = PX_Deref;
2000 goto no_operands;
2001 case DW_OP_and:
2002 nm = "and";
2003 pxop = PX_And;
2004 goto no_operands;
2005 case DW_OP_plus:
2006 nm = "plus";
2007 pxop = PX_Add;
2008 goto no_operands;
2009 case DW_OP_minus:
2010 nm = "minus";
2011 pxop = PX_Sub;
2012 goto no_operands;
2013 case DW_OP_shl:
2014 nm = "shl";
2015 pxop = PX_Shl;
2016 goto no_operands;
2017 case DW_OP_ge:
2018 nm = "ge";
2019 pxop = PX_CmpGES;
2020 goto no_operands;
2021 no_operands:
2022 MOZ_ASSERT(nm && pxop != PX_End);
2023 if (debug) {
2024 SprintfLiteral(buf, "LUL.DW DW_OP_%s\n", nm);
2025 summ->Log(buf);
2027 (void)summ->AddPfxInstr(PfxInstr(pxop));
2028 break;
2030 default:
2031 if (debug) {
2032 SprintfLiteral(buf, "LUL.DW unknown opc %d\n", (int)opc);
2033 summ->Log(buf);
2035 goto fail;
2037 } // switch (opc)
2039 } // while (cursor < end1)
2041 MOZ_ASSERT(cursor >= end1);
2043 if (cursor > end1) {
2044 // We overran the Dwarf expression. Give up.
2045 goto fail;
2048 // For DW_CFA_expression, what the expression denotes is the address
2049 // of where the previous value is located. The caller of this routine
2050 // may therefore request one last dereference before the end marker is
2051 // inserted.
2052 if (derefAtEnd) {
2053 (void)summ->AddPfxInstr(PfxInstr(PX_Deref));
2056 // Insert an end marker, and declare success.
2057 (void)summ->AddPfxInstr(PfxInstr(PX_End));
2058 if (debug) {
2059 SprintfLiteral(buf,
2060 "LUL.DW conversion of dwarf expression succeeded, "
2061 "ix = %d\n",
2062 (int)start_ix);
2063 summ->Log(buf);
2064 summ->Log("LUL.DW >>\n");
2066 return start_ix;
2068 fail:
2069 if (debug) {
2070 summ->Log("LUL.DW conversion of dwarf expression failed\n");
2071 summ->Log("LUL.DW >>\n");
2073 return -1;
2076 bool DwarfCFIToModule::Entry(size_t offset, uint64 address, uint64 length,
2077 uint8 version, const string& augmentation,
2078 unsigned return_address) {
2079 if (DEBUG_DWARF) {
2080 char buf[100];
2081 SprintfLiteral(buf, "LUL.DW DwarfCFIToModule::Entry 0x%llx,+%lld\n",
2082 address, length);
2083 summ_->Log(buf);
2086 summ_->Entry(address, length);
2088 // If dwarf2reader::CallFrameInfo can handle this version and
2089 // augmentation, then we should be okay with that, so there's no
2090 // need to check them here.
2092 // Get ready to collect entries.
2093 return_address_ = return_address;
2095 // Breakpad STACK CFI records must provide a .ra rule, but DWARF CFI
2096 // may not establish any rule for .ra if the return address column
2097 // is an ordinary register, and that register holds the return
2098 // address on entry to the function. So establish an initial .ra
2099 // rule citing the return address register.
2100 if (return_address_ < num_dw_regs_) {
2101 summ_->Rule(address, return_address_, NODEREF, return_address, 0);
2104 return true;
2107 const UniqueString* DwarfCFIToModule::RegisterName(int i) {
2108 if (i < 0) {
2109 MOZ_ASSERT(i == kCFARegister);
2110 return usu_->ToUniqueString(".cfa");
2112 unsigned reg = i;
2113 if (reg == return_address_) return usu_->ToUniqueString(".ra");
2115 char buf[30];
2116 SprintfLiteral(buf, "dwarf_reg_%u", reg);
2117 return usu_->ToUniqueString(buf);
2120 bool DwarfCFIToModule::UndefinedRule(uint64 address, int reg) {
2121 reporter_->UndefinedNotSupported(entry_offset_, RegisterName(reg));
2122 // Treat this as a non-fatal error.
2123 return true;
2126 bool DwarfCFIToModule::SameValueRule(uint64 address, int reg) {
2127 if (DEBUG_DWARF) {
2128 char buf[100];
2129 SprintfLiteral(buf, "LUL.DW 0x%llx: old r%d = Same\n", address, reg);
2130 summ_->Log(buf);
2132 // reg + 0
2133 summ_->Rule(address, reg, NODEREF, reg, 0);
2134 return true;
2137 bool DwarfCFIToModule::OffsetRule(uint64 address, int reg, int base_register,
2138 long offset) {
2139 if (DEBUG_DWARF) {
2140 char buf[100];
2141 SprintfLiteral(buf, "LUL.DW 0x%llx: old r%d = *(r%d + %ld)\n", address,
2142 reg, base_register, offset);
2143 summ_->Log(buf);
2145 // *(base_register + offset)
2146 summ_->Rule(address, reg, DEREF, base_register, offset);
2147 return true;
2150 bool DwarfCFIToModule::ValOffsetRule(uint64 address, int reg, int base_register,
2151 long offset) {
2152 if (DEBUG_DWARF) {
2153 char buf[100];
2154 SprintfLiteral(buf, "LUL.DW 0x%llx: old r%d = r%d + %ld\n", address, reg,
2155 base_register, offset);
2156 summ_->Log(buf);
2158 // base_register + offset
2159 summ_->Rule(address, reg, NODEREF, base_register, offset);
2160 return true;
2163 bool DwarfCFIToModule::RegisterRule(uint64 address, int reg,
2164 int base_register) {
2165 if (DEBUG_DWARF) {
2166 char buf[100];
2167 SprintfLiteral(buf, "LUL.DW 0x%llx: old r%d = r%d\n", address, reg,
2168 base_register);
2169 summ_->Log(buf);
2171 // base_register + 0
2172 summ_->Rule(address, reg, NODEREF, base_register, 0);
2173 return true;
2176 bool DwarfCFIToModule::ExpressionRule(uint64 address, int reg,
2177 const string& expression) {
2178 bool debug = !!DEBUG_DWARF;
2179 int32_t start_ix =
2180 parseDwarfExpr(summ_, reader_, expression, debug, true /*pushCfaAtStart*/,
2181 true /*derefAtEnd*/);
2182 if (start_ix >= 0) {
2183 summ_->Rule(address, reg, PFXEXPR, 0, start_ix);
2184 } else {
2185 // Parsing of the Dwarf expression failed. Treat this as a
2186 // non-fatal error, hence return |true| even on this path.
2187 reporter_->ExpressionCouldNotBeSummarised(entry_offset_, RegisterName(reg));
2189 return true;
2192 bool DwarfCFIToModule::ValExpressionRule(uint64 address, int reg,
2193 const string& expression) {
2194 bool debug = !!DEBUG_DWARF;
2195 int32_t start_ix =
2196 parseDwarfExpr(summ_, reader_, expression, debug, true /*pushCfaAtStart*/,
2197 false /*!derefAtEnd*/);
2198 if (start_ix >= 0) {
2199 summ_->Rule(address, reg, PFXEXPR, 0, start_ix);
2200 } else {
2201 // Parsing of the Dwarf expression failed. Treat this as a
2202 // non-fatal error, hence return |true| even on this path.
2203 reporter_->ExpressionCouldNotBeSummarised(entry_offset_, RegisterName(reg));
2205 return true;
2208 bool DwarfCFIToModule::End() {
2209 // module_->AddStackFrameEntry(entry_);
2210 if (DEBUG_DWARF) {
2211 summ_->Log("LUL.DW DwarfCFIToModule::End()\n");
2213 summ_->End();
2214 return true;
2217 void DwarfCFIToModule::Reporter::UndefinedNotSupported(
2218 size_t offset, const UniqueString* reg) {
2219 char buf[300];
2220 SprintfLiteral(buf, "DwarfCFIToModule::Reporter::UndefinedNotSupported()\n");
2221 log_(buf);
2222 // BPLOG(INFO) << file_ << ", section '" << section_
2223 // << "': the call frame entry at offset 0x"
2224 // << std::setbase(16) << offset << std::setbase(10)
2225 // << " sets the rule for register '" << FromUniqueString(reg)
2226 // << "' to 'undefined', but the Breakpad symbol file format cannot "
2227 // << " express this";
2230 // FIXME: move this somewhere sensible
2231 static bool is_power_of_2(uint64_t n) {
2232 int i, nSetBits = 0;
2233 for (i = 0; i < 8 * (int)sizeof(n); i++) {
2234 if ((n & ((uint64_t)1) << i) != 0) nSetBits++;
2236 return nSetBits <= 1;
2239 void DwarfCFIToModule::Reporter::ExpressionCouldNotBeSummarised(
2240 size_t offset, const UniqueString* reg) {
2241 static uint64_t n_complaints = 0; // This isn't threadsafe
2242 n_complaints++;
2243 if (!is_power_of_2(n_complaints)) return;
2244 char buf[300];
2245 SprintfLiteral(buf,
2246 "DwarfCFIToModule::Reporter::"
2247 "ExpressionCouldNotBeSummarised(shown %llu times)\n",
2248 (unsigned long long int)n_complaints);
2249 log_(buf);
2252 } // namespace lul