toolkit/crashreporter/google-breakpad/src/common/dwarf/dwarf2reader.cc

Sat, 03 Jan 2015 20:18:00 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Sat, 03 Jan 2015 20:18:00 +0100
branch
TOR_BUG_3246
changeset 7
129ffea94266
permissions
-rw-r--r--

Conditionally enable double key logic according to:
private browsing mode or privacy.thirdparty.isolate preference and
implement in GetCookieStringCommon and FindCookie where it counts...
With some reservations of how to convince FindCookie users to test
condition and pass a nullptr when disabling double key logic.

     1 // Copyright (c) 2010 Google Inc. All Rights Reserved.
     2 //
     3 // Redistribution and use in source and binary forms, with or without
     4 // modification, are permitted provided that the following conditions are
     5 // met:
     6 //
     7 //     * Redistributions of source code must retain the above copyright
     8 // notice, this list of conditions and the following disclaimer.
     9 //     * Redistributions in binary form must reproduce the above
    10 // copyright notice, this list of conditions and the following disclaimer
    11 // in the documentation and/or other materials provided with the
    12 // distribution.
    13 //     * Neither the name of Google Inc. nor the names of its
    14 // contributors may be used to endorse or promote products derived from
    15 // this software without specific prior written permission.
    16 //
    17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    29 // CFI reader author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>
    31 // Implementation of dwarf2reader::LineInfo, dwarf2reader::CompilationUnit,
    32 // and dwarf2reader::CallFrameInfo. See dwarf2reader.h for details.
    34 #include "common/dwarf/dwarf2reader.h"
    36 #include <assert.h>
    37 #include <stdint.h>
    38 #include <stdio.h>
    39 #include <string.h>
    41 #include <map>
    42 #include <memory>
    43 #include <stack>
    44 #include <string>
    45 #include <utility>
    47 #include "common/dwarf/bytereader-inl.h"
    48 #include "common/dwarf/bytereader.h"
    49 #include "common/dwarf/line_state_machine.h"
    50 #include "common/using_std_string.h"
    52 namespace dwarf2reader {
    54 CompilationUnit::CompilationUnit(const SectionMap& sections, uint64 offset,
    55                                  ByteReader* reader, Dwarf2Handler* handler)
    56     : offset_from_section_start_(offset), reader_(reader),
    57       sections_(sections), handler_(handler), abbrevs_(NULL),
    58       string_buffer_(NULL), string_buffer_length_(0) {}
    60 // Read a DWARF2/3 abbreviation section.
    61 // Each abbrev consists of a abbreviation number, a tag, a byte
    62 // specifying whether the tag has children, and a list of
    63 // attribute/form pairs.
    64 // The list of forms is terminated by a 0 for the attribute, and a
    65 // zero for the form.  The entire abbreviation section is terminated
    66 // by a zero for the code.
    68 void CompilationUnit::ReadAbbrevs() {
    69   if (abbrevs_)
    70     return;
    72   // First get the debug_abbrev section.  ".debug_abbrev" is the name
    73   // recommended in the DWARF spec, and used on Linux;
    74   // "__debug_abbrev" is the name used in Mac OS X Mach-O files.
    75   SectionMap::const_iterator iter = sections_.find(".debug_abbrev");
    76   if (iter == sections_.end())
    77     iter = sections_.find("__debug_abbrev");
    78   assert(iter != sections_.end());
    80   abbrevs_ = new std::vector<Abbrev>;
    81   abbrevs_->resize(1);
    83   // The only way to check whether we are reading over the end of the
    84   // buffer would be to first compute the size of the leb128 data by
    85   // reading it, then go back and read it again.
    86   const char* abbrev_start = iter->second.first +
    87                                       header_.abbrev_offset;
    88   const char* abbrevptr = abbrev_start;
    89 #ifndef NDEBUG
    90   const uint64 abbrev_length = iter->second.second - header_.abbrev_offset;
    91 #endif
    93   while (1) {
    94     CompilationUnit::Abbrev abbrev;
    95     size_t len;
    96     const uint64 number = reader_->ReadUnsignedLEB128(abbrevptr, &len);
    98     if (number == 0)
    99       break;
   100     abbrev.number = number;
   101     abbrevptr += len;
   103     assert(abbrevptr < abbrev_start + abbrev_length);
   104     const uint64 tag = reader_->ReadUnsignedLEB128(abbrevptr, &len);
   105     abbrevptr += len;
   106     abbrev.tag = static_cast<enum DwarfTag>(tag);
   108     assert(abbrevptr < abbrev_start + abbrev_length);
   109     abbrev.has_children = reader_->ReadOneByte(abbrevptr);
   110     abbrevptr += 1;
   112     assert(abbrevptr < abbrev_start + abbrev_length);
   114     while (1) {
   115       const uint64 nametemp = reader_->ReadUnsignedLEB128(abbrevptr, &len);
   116       abbrevptr += len;
   118       assert(abbrevptr < abbrev_start + abbrev_length);
   119       const uint64 formtemp = reader_->ReadUnsignedLEB128(abbrevptr, &len);
   120       abbrevptr += len;
   121       if (nametemp == 0 && formtemp == 0)
   122         break;
   124       const enum DwarfAttribute name =
   125         static_cast<enum DwarfAttribute>(nametemp);
   126       const enum DwarfForm form = static_cast<enum DwarfForm>(formtemp);
   127       abbrev.attributes.push_back(std::make_pair(name, form));
   128     }
   129     assert(abbrev.number == abbrevs_->size());
   130     abbrevs_->push_back(abbrev);
   131   }
   132 }
   134 // Skips a single DIE's attributes.
   135 const char* CompilationUnit::SkipDIE(const char* start,
   136                                               const Abbrev& abbrev) {
   137   for (AttributeList::const_iterator i = abbrev.attributes.begin();
   138        i != abbrev.attributes.end();
   139        i++)  {
   140     start = SkipAttribute(start, i->second);
   141   }
   142   return start;
   143 }
   145 // Skips a single attribute form's data.
   146 const char* CompilationUnit::SkipAttribute(const char* start,
   147                                                     enum DwarfForm form) {
   148   size_t len;
   150   switch (form) {
   151     case DW_FORM_indirect:
   152       form = static_cast<enum DwarfForm>(reader_->ReadUnsignedLEB128(start,
   153                                                                      &len));
   154       start += len;
   155       return SkipAttribute(start, form);
   157     case DW_FORM_flag_present:
   158       return start;
   159     case DW_FORM_data1:
   160     case DW_FORM_flag:
   161     case DW_FORM_ref1:
   162       return start + 1;
   163     case DW_FORM_ref2:
   164     case DW_FORM_data2:
   165       return start + 2;
   166     case DW_FORM_ref4:
   167     case DW_FORM_data4:
   168       return start + 4;
   169     case DW_FORM_ref8:
   170     case DW_FORM_data8:
   171     case DW_FORM_ref_sig8:
   172       return start + 8;
   173     case DW_FORM_string:
   174       return start + strlen(start) + 1;
   175     case DW_FORM_udata:
   176     case DW_FORM_ref_udata:
   177       reader_->ReadUnsignedLEB128(start, &len);
   178       return start + len;
   180     case DW_FORM_sdata:
   181       reader_->ReadSignedLEB128(start, &len);
   182       return start + len;
   183     case DW_FORM_addr:
   184       return start + reader_->AddressSize();
   185     case DW_FORM_ref_addr:
   186       // DWARF2 and 3 differ on whether ref_addr is address size or
   187       // offset size.
   188       assert(header_.version == 2 || header_.version == 3);
   189       if (header_.version == 2) {
   190         return start + reader_->AddressSize();
   191       } else if (header_.version == 3) {
   192         return start + reader_->OffsetSize();
   193       }
   195     case DW_FORM_block1:
   196       return start + 1 + reader_->ReadOneByte(start);
   197     case DW_FORM_block2:
   198       return start + 2 + reader_->ReadTwoBytes(start);
   199     case DW_FORM_block4:
   200       return start + 4 + reader_->ReadFourBytes(start);
   201     case DW_FORM_block:
   202     case DW_FORM_exprloc: {
   203       uint64 size = reader_->ReadUnsignedLEB128(start, &len);
   204       return start + size + len;
   205     }
   206     case DW_FORM_strp:
   207     case DW_FORM_sec_offset:
   208       return start + reader_->OffsetSize();
   209   }
   210   fprintf(stderr,"Unhandled form type");
   211   return NULL;
   212 }
   214 // Read a DWARF2/3 header.
   215 // The header is variable length in DWARF3 (and DWARF2 as extended by
   216 // most compilers), and consists of an length field, a version number,
   217 // the offset in the .debug_abbrev section for our abbrevs, and an
   218 // address size.
   219 void CompilationUnit::ReadHeader() {
   220   const char* headerptr = buffer_;
   221   size_t initial_length_size;
   223   assert(headerptr + 4 < buffer_ + buffer_length_);
   224   const uint64 initial_length
   225     = reader_->ReadInitialLength(headerptr, &initial_length_size);
   226   headerptr += initial_length_size;
   227   header_.length = initial_length;
   229   assert(headerptr + 2 < buffer_ + buffer_length_);
   230   header_.version = reader_->ReadTwoBytes(headerptr);
   231   headerptr += 2;
   233   assert(headerptr + reader_->OffsetSize() < buffer_ + buffer_length_);
   234   header_.abbrev_offset = reader_->ReadOffset(headerptr);
   235   headerptr += reader_->OffsetSize();
   237   assert(headerptr + 1 < buffer_ + buffer_length_);
   238   header_.address_size = reader_->ReadOneByte(headerptr);
   239   reader_->SetAddressSize(header_.address_size);
   240   headerptr += 1;
   242   after_header_ = headerptr;
   244   // This check ensures that we don't have to do checking during the
   245   // reading of DIEs. header_.length does not include the size of the
   246   // initial length.
   247   assert(buffer_ + initial_length_size + header_.length <=
   248         buffer_ + buffer_length_);
   249 }
   251 uint64 CompilationUnit::Start() {
   252   // First get the debug_info section.  ".debug_info" is the name
   253   // recommended in the DWARF spec, and used on Linux; "__debug_info"
   254   // is the name used in Mac OS X Mach-O files.
   255   SectionMap::const_iterator iter = sections_.find(".debug_info");
   256   if (iter == sections_.end())
   257     iter = sections_.find("__debug_info");
   258   assert(iter != sections_.end());
   260   // Set up our buffer
   261   buffer_ = iter->second.first + offset_from_section_start_;
   262   buffer_length_ = iter->second.second - offset_from_section_start_;
   264   // Read the header
   265   ReadHeader();
   267   // Figure out the real length from the end of the initial length to
   268   // the end of the compilation unit, since that is the value we
   269   // return.
   270   uint64 ourlength = header_.length;
   271   if (reader_->OffsetSize() == 8)
   272     ourlength += 12;
   273   else
   274     ourlength += 4;
   276   // See if the user wants this compilation unit, and if not, just return.
   277   if (!handler_->StartCompilationUnit(offset_from_section_start_,
   278                                       reader_->AddressSize(),
   279                                       reader_->OffsetSize(),
   280                                       header_.length,
   281                                       header_.version))
   282     return ourlength;
   284   // Otherwise, continue by reading our abbreviation entries.
   285   ReadAbbrevs();
   287   // Set the string section if we have one.  ".debug_str" is the name
   288   // recommended in the DWARF spec, and used on Linux; "__debug_str"
   289   // is the name used in Mac OS X Mach-O files.
   290   iter = sections_.find(".debug_str");
   291   if (iter == sections_.end())
   292     iter = sections_.find("__debug_str");
   293   if (iter != sections_.end()) {
   294     string_buffer_ = iter->second.first;
   295     string_buffer_length_ = iter->second.second;
   296   }
   298   // Now that we have our abbreviations, start processing DIE's.
   299   ProcessDIEs();
   301   return ourlength;
   302 }
   304 // If one really wanted, you could merge SkipAttribute and
   305 // ProcessAttribute
   306 // This is all boring data manipulation and calling of the handler.
   307 const char* CompilationUnit::ProcessAttribute(
   308     uint64 dieoffset, const char* start, enum DwarfAttribute attr,
   309     enum DwarfForm form) {
   310   size_t len;
   312   switch (form) {
   313     // DW_FORM_indirect is never used because it is such a space
   314     // waster.
   315     case DW_FORM_indirect:
   316       form = static_cast<enum DwarfForm>(reader_->ReadUnsignedLEB128(start,
   317                                                                      &len));
   318       start += len;
   319       return ProcessAttribute(dieoffset, start, attr, form);
   321     case DW_FORM_flag_present:
   322       handler_->ProcessAttributeUnsigned(dieoffset, attr, form, 1);
   323       return start;
   324     case DW_FORM_data1:
   325     case DW_FORM_flag:
   326       handler_->ProcessAttributeUnsigned(dieoffset, attr, form,
   327                                          reader_->ReadOneByte(start));
   328       return start + 1;
   329     case DW_FORM_data2:
   330       handler_->ProcessAttributeUnsigned(dieoffset, attr, form,
   331                                          reader_->ReadTwoBytes(start));
   332       return start + 2;
   333     case DW_FORM_data4:
   334       handler_->ProcessAttributeUnsigned(dieoffset, attr, form,
   335                                          reader_->ReadFourBytes(start));
   336       return start + 4;
   337     case DW_FORM_data8:
   338       handler_->ProcessAttributeUnsigned(dieoffset, attr, form,
   339                                          reader_->ReadEightBytes(start));
   340       return start + 8;
   341     case DW_FORM_string: {
   342       const char* str = start;
   343       handler_->ProcessAttributeString(dieoffset, attr, form,
   344                                        str);
   345       return start + strlen(str) + 1;
   346     }
   347     case DW_FORM_udata:
   348       handler_->ProcessAttributeUnsigned(dieoffset, attr, form,
   349                                          reader_->ReadUnsignedLEB128(start,
   350                                                                      &len));
   351       return start + len;
   353     case DW_FORM_sdata:
   354       handler_->ProcessAttributeSigned(dieoffset, attr, form,
   355                                       reader_->ReadSignedLEB128(start, &len));
   356       return start + len;
   357     case DW_FORM_addr:
   358       handler_->ProcessAttributeUnsigned(dieoffset, attr, form,
   359                                          reader_->ReadAddress(start));
   360       return start + reader_->AddressSize();
   361     case DW_FORM_sec_offset:
   362       handler_->ProcessAttributeUnsigned(dieoffset, attr, form,
   363                                          reader_->ReadOffset(start));
   364       return start + reader_->OffsetSize();
   366     case DW_FORM_ref1:
   367       handler_->ProcessAttributeReference(dieoffset, attr, form,
   368                                           reader_->ReadOneByte(start)
   369                                           + offset_from_section_start_);
   370       return start + 1;
   371     case DW_FORM_ref2:
   372       handler_->ProcessAttributeReference(dieoffset, attr, form,
   373                                           reader_->ReadTwoBytes(start)
   374                                           + offset_from_section_start_);
   375       return start + 2;
   376     case DW_FORM_ref4:
   377       handler_->ProcessAttributeReference(dieoffset, attr, form,
   378                                           reader_->ReadFourBytes(start)
   379                                           + offset_from_section_start_);
   380       return start + 4;
   381     case DW_FORM_ref8:
   382       handler_->ProcessAttributeReference(dieoffset, attr, form,
   383                                           reader_->ReadEightBytes(start)
   384                                           + offset_from_section_start_);
   385       return start + 8;
   386     case DW_FORM_ref_udata:
   387       handler_->ProcessAttributeReference(dieoffset, attr, form,
   388                                           reader_->ReadUnsignedLEB128(start,
   389                                                                       &len)
   390                                           + offset_from_section_start_);
   391       return start + len;
   392     case DW_FORM_ref_addr:
   393       // DWARF2 and 3 differ on whether ref_addr is address size or
   394       // offset size.
   395       assert(header_.version == 2 || header_.version == 3);
   396       if (header_.version == 2) {
   397         handler_->ProcessAttributeReference(dieoffset, attr, form,
   398                                             reader_->ReadAddress(start));
   399         return start + reader_->AddressSize();
   400       } else if (header_.version == 3) {
   401         handler_->ProcessAttributeReference(dieoffset, attr, form,
   402                                             reader_->ReadOffset(start));
   403         return start + reader_->OffsetSize();
   404       }
   405       break;
   406     case DW_FORM_ref_sig8:
   407       handler_->ProcessAttributeSignature(dieoffset, attr, form,
   408                                           reader_->ReadEightBytes(start));
   409       return start + 8;
   411     case DW_FORM_block1: {
   412       uint64 datalen = reader_->ReadOneByte(start);
   413       handler_->ProcessAttributeBuffer(dieoffset, attr, form, start + 1,
   414                                        datalen);
   415       return start + 1 + datalen;
   416     }
   417     case DW_FORM_block2: {
   418       uint64 datalen = reader_->ReadTwoBytes(start);
   419       handler_->ProcessAttributeBuffer(dieoffset, attr, form, start + 2,
   420                                        datalen);
   421       return start + 2 + datalen;
   422     }
   423     case DW_FORM_block4: {
   424       uint64 datalen = reader_->ReadFourBytes(start);
   425       handler_->ProcessAttributeBuffer(dieoffset, attr, form, start + 4,
   426                                        datalen);
   427       return start + 4 + datalen;
   428     }
   429     case DW_FORM_block:
   430     case DW_FORM_exprloc: {
   431       uint64 datalen = reader_->ReadUnsignedLEB128(start, &len);
   432       handler_->ProcessAttributeBuffer(dieoffset, attr, form, start + len,
   433                                        datalen);
   434       return start + datalen + len;
   435     }
   436     case DW_FORM_strp: {
   437       assert(string_buffer_ != NULL);
   439       const uint64 offset = reader_->ReadOffset(start);
   440       assert(string_buffer_ + offset < string_buffer_ + string_buffer_length_);
   442       const char* str = string_buffer_ + offset;
   443       handler_->ProcessAttributeString(dieoffset, attr, form,
   444                                        str);
   445       return start + reader_->OffsetSize();
   446     }
   447   }
   448   fprintf(stderr, "Unhandled form type\n");
   449   return NULL;
   450 }
   452 const char* CompilationUnit::ProcessDIE(uint64 dieoffset,
   453                                                  const char* start,
   454                                                  const Abbrev& abbrev) {
   455   for (AttributeList::const_iterator i = abbrev.attributes.begin();
   456        i != abbrev.attributes.end();
   457        i++)  {
   458     start = ProcessAttribute(dieoffset, start, i->first, i->second);
   459   }
   460   return start;
   461 }
   463 void CompilationUnit::ProcessDIEs() {
   464   const char* dieptr = after_header_;
   465   size_t len;
   467   // lengthstart is the place the length field is based on.
   468   // It is the point in the header after the initial length field
   469   const char* lengthstart = buffer_;
   471   // In 64 bit dwarf, the initial length is 12 bytes, because of the
   472   // 0xffffffff at the start.
   473   if (reader_->OffsetSize() == 8)
   474     lengthstart += 12;
   475   else
   476     lengthstart += 4;
   478   std::stack<uint64> die_stack;
   480   while (dieptr < (lengthstart + header_.length)) {
   481     // We give the user the absolute offset from the beginning of
   482     // debug_info, since they need it to deal with ref_addr forms.
   483     uint64 absolute_offset = (dieptr - buffer_) + offset_from_section_start_;
   485     uint64 abbrev_num = reader_->ReadUnsignedLEB128(dieptr, &len);
   487     dieptr += len;
   489     // Abbrev == 0 represents the end of a list of children, or padding
   490     // at the end of the compilation unit.
   491     if (abbrev_num == 0) {
   492       if (die_stack.size() == 0)
   493         // If it is padding, then we are done with the compilation unit's DIEs.
   494         return;
   495       const uint64 offset = die_stack.top();
   496       die_stack.pop();
   497       handler_->EndDIE(offset);
   498       continue;
   499     }
   501     const Abbrev& abbrev = abbrevs_->at(static_cast<size_t>(abbrev_num));
   502     const enum DwarfTag tag = abbrev.tag;
   503     if (!handler_->StartDIE(absolute_offset, tag)) {
   504       dieptr = SkipDIE(dieptr, abbrev);
   505     } else {
   506       dieptr = ProcessDIE(absolute_offset, dieptr, abbrev);
   507     }
   509     if (abbrev.has_children) {
   510       die_stack.push(absolute_offset);
   511     } else {
   512       handler_->EndDIE(absolute_offset);
   513     }
   514   }
   515 }
   517 LineInfo::LineInfo(const char* buffer, uint64 buffer_length,
   518                    ByteReader* reader, LineInfoHandler* handler):
   519     handler_(handler), reader_(reader), buffer_(buffer),
   520     buffer_length_(buffer_length) {
   521   header_.std_opcode_lengths = NULL;
   522 }
   524 uint64 LineInfo::Start() {
   525   ReadHeader();
   526   ReadLines();
   527   return after_header_ - buffer_;
   528 }
   530 // The header for a debug_line section is mildly complicated, because
   531 // the line info is very tightly encoded.
   532 void LineInfo::ReadHeader() {
   533   const char* lineptr = buffer_;
   534   size_t initial_length_size;
   536   const uint64 initial_length
   537     = reader_->ReadInitialLength(lineptr, &initial_length_size);
   539   lineptr += initial_length_size;
   540   header_.total_length = initial_length;
   541   assert(buffer_ + initial_length_size + header_.total_length <=
   542         buffer_ + buffer_length_);
   544   // Address size *must* be set by CU ahead of time.
   545   assert(reader_->AddressSize() != 0);
   547   header_.version = reader_->ReadTwoBytes(lineptr);
   548   lineptr += 2;
   550   header_.prologue_length = reader_->ReadOffset(lineptr);
   551   lineptr += reader_->OffsetSize();
   553   header_.min_insn_length = reader_->ReadOneByte(lineptr);
   554   lineptr += 1;
   556   header_.default_is_stmt = reader_->ReadOneByte(lineptr);
   557   lineptr += 1;
   559   header_.line_base = *reinterpret_cast<const int8*>(lineptr);
   560   lineptr += 1;
   562   header_.line_range = reader_->ReadOneByte(lineptr);
   563   lineptr += 1;
   565   header_.opcode_base = reader_->ReadOneByte(lineptr);
   566   lineptr += 1;
   568   header_.std_opcode_lengths = new std::vector<unsigned char>;
   569   header_.std_opcode_lengths->resize(header_.opcode_base + 1);
   570   (*header_.std_opcode_lengths)[0] = 0;
   571   for (int i = 1; i < header_.opcode_base; i++) {
   572     (*header_.std_opcode_lengths)[i] = reader_->ReadOneByte(lineptr);
   573     lineptr += 1;
   574   }
   576   // It is legal for the directory entry table to be empty.
   577   if (*lineptr) {
   578     uint32 dirindex = 1;
   579     while (*lineptr) {
   580       const char* dirname = lineptr;
   581       handler_->DefineDir(dirname, dirindex);
   582       lineptr += strlen(dirname) + 1;
   583       dirindex++;
   584     }
   585   }
   586   lineptr++;
   588   // It is also legal for the file entry table to be empty.
   589   if (*lineptr) {
   590     uint32 fileindex = 1;
   591     size_t len;
   592     while (*lineptr) {
   593       const char* filename = lineptr;
   594       lineptr += strlen(filename) + 1;
   596       uint64 dirindex = reader_->ReadUnsignedLEB128(lineptr, &len);
   597       lineptr += len;
   599       uint64 mod_time = reader_->ReadUnsignedLEB128(lineptr, &len);
   600       lineptr += len;
   602       uint64 filelength = reader_->ReadUnsignedLEB128(lineptr, &len);
   603       lineptr += len;
   604       handler_->DefineFile(filename, fileindex, static_cast<uint32>(dirindex), 
   605                            mod_time, filelength);
   606       fileindex++;
   607     }
   608   }
   609   lineptr++;
   611   after_header_ = lineptr;
   612 }
   614 /* static */
   615 bool LineInfo::ProcessOneOpcode(ByteReader* reader,
   616                                 LineInfoHandler* handler,
   617                                 const struct LineInfoHeader &header,
   618                                 const char* start,
   619                                 struct LineStateMachine* lsm,
   620                                 size_t* len,
   621                                 uintptr pc,
   622                                 bool *lsm_passes_pc) {
   623   size_t oplen = 0;
   624   size_t templen;
   625   uint8 opcode = reader->ReadOneByte(start);
   626   oplen++;
   627   start++;
   629   // If the opcode is great than the opcode_base, it is a special
   630   // opcode. Most line programs consist mainly of special opcodes.
   631   if (opcode >= header.opcode_base) {
   632     opcode -= header.opcode_base;
   633     const int64 advance_address = (opcode / header.line_range)
   634                                   * header.min_insn_length;
   635     const int32 advance_line = (opcode % header.line_range)
   636                                + header.line_base;
   638     // Check if the lsm passes "pc". If so, mark it as passed.
   639     if (lsm_passes_pc &&
   640         lsm->address <= pc && pc < lsm->address + advance_address) {
   641       *lsm_passes_pc = true;
   642     }
   644     lsm->address += advance_address;
   645     lsm->line_num += advance_line;
   646     lsm->basic_block = true;
   647     *len = oplen;
   648     return true;
   649   }
   651   // Otherwise, we have the regular opcodes
   652   switch (opcode) {
   653     case DW_LNS_copy: {
   654       lsm->basic_block = false;
   655       *len = oplen;
   656       return true;
   657     }
   659     case DW_LNS_advance_pc: {
   660       uint64 advance_address = reader->ReadUnsignedLEB128(start, &templen);
   661       oplen += templen;
   663       // Check if the lsm passes "pc". If so, mark it as passed.
   664       if (lsm_passes_pc && lsm->address <= pc &&
   665           pc < lsm->address + header.min_insn_length * advance_address) {
   666         *lsm_passes_pc = true;
   667       }
   669       lsm->address += header.min_insn_length * advance_address;
   670     }
   671       break;
   672     case DW_LNS_advance_line: {
   673       const int64 advance_line = reader->ReadSignedLEB128(start, &templen);
   674       oplen += templen;
   675       lsm->line_num += static_cast<int32>(advance_line);
   677       // With gcc 4.2.1, we can get the line_no here for the first time
   678       // since DW_LNS_advance_line is called after DW_LNE_set_address is
   679       // called. So we check if the lsm passes "pc" here, not in
   680       // DW_LNE_set_address.
   681       if (lsm_passes_pc && lsm->address == pc) {
   682         *lsm_passes_pc = true;
   683       }
   684     }
   685       break;
   686     case DW_LNS_set_file: {
   687       const uint64 fileno = reader->ReadUnsignedLEB128(start, &templen);
   688       oplen += templen;
   689       lsm->file_num = static_cast<uint32>(fileno);
   690     }
   691       break;
   692     case DW_LNS_set_column: {
   693       const uint64 colno = reader->ReadUnsignedLEB128(start, &templen);
   694       oplen += templen;
   695       lsm->column_num = static_cast<uint32>(colno);
   696     }
   697       break;
   698     case DW_LNS_negate_stmt: {
   699       lsm->is_stmt = !lsm->is_stmt;
   700     }
   701       break;
   702     case DW_LNS_set_basic_block: {
   703       lsm->basic_block = true;
   704     }
   705       break;
   706     case DW_LNS_fixed_advance_pc: {
   707       const uint16 advance_address = reader->ReadTwoBytes(start);
   708       oplen += 2;
   710       // Check if the lsm passes "pc". If so, mark it as passed.
   711       if (lsm_passes_pc &&
   712           lsm->address <= pc && pc < lsm->address + advance_address) {
   713         *lsm_passes_pc = true;
   714       }
   716       lsm->address += advance_address;
   717     }
   718       break;
   719     case DW_LNS_const_add_pc: {
   720       const int64 advance_address = header.min_insn_length
   721                                     * ((255 - header.opcode_base)
   722                                        / header.line_range);
   724       // Check if the lsm passes "pc". If so, mark it as passed.
   725       if (lsm_passes_pc &&
   726           lsm->address <= pc && pc < lsm->address + advance_address) {
   727         *lsm_passes_pc = true;
   728       }
   730       lsm->address += advance_address;
   731     }
   732       break;
   733     case DW_LNS_extended_op: {
   734       const uint64 extended_op_len = reader->ReadUnsignedLEB128(start,
   735                                                                 &templen);
   736       start += templen;
   737       oplen += templen + extended_op_len;
   739       const uint64 extended_op = reader->ReadOneByte(start);
   740       start++;
   742       switch (extended_op) {
   743         case DW_LNE_end_sequence: {
   744           lsm->end_sequence = true;
   745           *len = oplen;
   746           return true;
   747         }
   748           break;
   749         case DW_LNE_set_address: {
   750           // With gcc 4.2.1, we cannot tell the line_no here since
   751           // DW_LNE_set_address is called before DW_LNS_advance_line is
   752           // called.  So we do not check if the lsm passes "pc" here.  See
   753           // also the comment in DW_LNS_advance_line.
   754           uint64 address = reader->ReadAddress(start);
   755           lsm->address = address;
   756         }
   757           break;
   758         case DW_LNE_define_file: {
   759           const char* filename  = start;
   761           templen = strlen(filename) + 1;
   762           start += templen;
   764           uint64 dirindex = reader->ReadUnsignedLEB128(start, &templen);
   765           oplen += templen;
   767           const uint64 mod_time = reader->ReadUnsignedLEB128(start,
   768                                                              &templen);
   769           oplen += templen;
   771           const uint64 filelength = reader->ReadUnsignedLEB128(start,
   772                                                                &templen);
   773           oplen += templen;
   775           if (handler) {
   776             handler->DefineFile(filename, -1, static_cast<uint32>(dirindex), 
   777                                 mod_time, filelength);
   778           }
   779         }
   780           break;
   781       }
   782     }
   783       break;
   785     default: {
   786       // Ignore unknown opcode  silently
   787       if (header.std_opcode_lengths) {
   788         for (int i = 0; i < (*header.std_opcode_lengths)[opcode]; i++) {
   789           reader->ReadUnsignedLEB128(start, &templen);
   790           start += templen;
   791           oplen += templen;
   792         }
   793       }
   794     }
   795       break;
   796   }
   797   *len = oplen;
   798   return false;
   799 }
   801 void LineInfo::ReadLines() {
   802   struct LineStateMachine lsm;
   804   // lengthstart is the place the length field is based on.
   805   // It is the point in the header after the initial length field
   806   const char* lengthstart = buffer_;
   808   // In 64 bit dwarf, the initial length is 12 bytes, because of the
   809   // 0xffffffff at the start.
   810   if (reader_->OffsetSize() == 8)
   811     lengthstart += 12;
   812   else
   813     lengthstart += 4;
   815   const char* lineptr = after_header_;
   816   lsm.Reset(header_.default_is_stmt);
   818   // The LineInfoHandler interface expects each line's length along
   819   // with its address, but DWARF only provides addresses (sans
   820   // length), and an end-of-sequence address; one infers the length
   821   // from the next address. So we report a line only when we get the
   822   // next line's address, or the end-of-sequence address.
   823   bool have_pending_line = false;
   824   uint64 pending_address = 0;
   825   uint32 pending_file_num = 0, pending_line_num = 0, pending_column_num = 0;
   827   while (lineptr < lengthstart + header_.total_length) {
   828     size_t oplength;
   829     bool add_row = ProcessOneOpcode(reader_, handler_, header_,
   830                                     lineptr, &lsm, &oplength, (uintptr)-1,
   831                                     NULL);
   832     if (add_row) {
   833       if (have_pending_line)
   834         handler_->AddLine(pending_address, lsm.address - pending_address,
   835                           pending_file_num, pending_line_num,
   836                           pending_column_num);
   837       if (lsm.end_sequence) {
   838         lsm.Reset(header_.default_is_stmt);      
   839         have_pending_line = false;
   840       } else {
   841         pending_address = lsm.address;
   842         pending_file_num = lsm.file_num;
   843         pending_line_num = lsm.line_num;
   844         pending_column_num = lsm.column_num;
   845         have_pending_line = true;
   846       }
   847     }
   848     lineptr += oplength;
   849   }
   851   after_header_ = lengthstart + header_.total_length;
   852 }
   854 // A DWARF rule for recovering the address or value of a register, or
   855 // computing the canonical frame address. There is one subclass of this for
   856 // each '*Rule' member function in CallFrameInfo::Handler.
   857 //
   858 // It's annoying that we have to handle Rules using pointers (because
   859 // the concrete instances can have an arbitrary size). They're small,
   860 // so it would be much nicer if we could just handle them by value
   861 // instead of fretting about ownership and destruction.
   862 //
   863 // It seems like all these could simply be instances of std::tr1::bind,
   864 // except that we need instances to be EqualityComparable, too.
   865 //
   866 // This could logically be nested within State, but then the qualified names
   867 // get horrendous.
   868 class CallFrameInfo::Rule {
   869  public:
   870   virtual ~Rule() { }
   872   // Tell HANDLER that, at ADDRESS in the program, REGISTER can be
   873   // recovered using this rule. If REGISTER is kCFARegister, then this rule
   874   // describes how to compute the canonical frame address. Return what the
   875   // HANDLER member function returned.
   876   virtual bool Handle(Handler *handler,
   877                       uint64 address, int register) const = 0;
   879   // Equality on rules. We use these to decide which rules we need
   880   // to report after a DW_CFA_restore_state instruction.
   881   virtual bool operator==(const Rule &rhs) const = 0;
   883   bool operator!=(const Rule &rhs) const { return ! (*this == rhs); }
   885   // Return a pointer to a copy of this rule.
   886   virtual Rule *Copy() const = 0;
   888   // If this is a base+offset rule, change its base register to REG.
   889   // Otherwise, do nothing. (Ugly, but required for DW_CFA_def_cfa_register.)
   890   virtual void SetBaseRegister(unsigned reg) { }
   892   // If this is a base+offset rule, change its offset to OFFSET. Otherwise,
   893   // do nothing. (Ugly, but required for DW_CFA_def_cfa_offset.)
   894   virtual void SetOffset(long long offset) { }
   896   // A RTTI workaround, to make it possible to implement equality
   897   // comparisons on classes derived from this one.
   898   enum CFIRTag {
   899     CFIR_UNDEFINED_RULE,
   900     CFIR_SAME_VALUE_RULE,
   901     CFIR_OFFSET_RULE,
   902     CFIR_VAL_OFFSET_RULE,
   903     CFIR_REGISTER_RULE,
   904     CFIR_EXPRESSION_RULE,
   905     CFIR_VAL_EXPRESSION_RULE
   906   };
   908   // Produce the tag that identifies the child class of this object.
   909   virtual CFIRTag getTag() const = 0;
   910 };
   912 // Rule: the value the register had in the caller cannot be recovered.
   913 class CallFrameInfo::UndefinedRule: public CallFrameInfo::Rule {
   914  public:
   915   UndefinedRule() { }
   916   ~UndefinedRule() { }
   917   CFIRTag getTag() const { return CFIR_UNDEFINED_RULE; }
   918   bool Handle(Handler *handler, uint64 address, int reg) const {
   919     return handler->UndefinedRule(address, reg);
   920   }
   921   bool operator==(const Rule &rhs) const {
   922     if (rhs.getTag() != CFIR_UNDEFINED_RULE) return false;
   923     return true;
   924   }
   925   Rule *Copy() const { return new UndefinedRule(*this); }
   926 };
   928 // Rule: the register's value is the same as that it had in the caller.
   929 class CallFrameInfo::SameValueRule: public CallFrameInfo::Rule {
   930  public:
   931   SameValueRule() { }
   932   ~SameValueRule() { }
   933   CFIRTag getTag() const { return CFIR_SAME_VALUE_RULE; }
   934   bool Handle(Handler *handler, uint64 address, int reg) const {
   935     return handler->SameValueRule(address, reg);
   936   }
   937   bool operator==(const Rule &rhs) const {
   938     if (rhs.getTag() != CFIR_SAME_VALUE_RULE) return false;
   939     return true;
   940   }
   941   Rule *Copy() const { return new SameValueRule(*this); }
   942 };
   944 // Rule: the register is saved at OFFSET from BASE_REGISTER.  BASE_REGISTER
   945 // may be CallFrameInfo::Handler::kCFARegister.
   946 class CallFrameInfo::OffsetRule: public CallFrameInfo::Rule {
   947  public:
   948   OffsetRule(int base_register, long offset)
   949       : base_register_(base_register), offset_(offset) { }
   950   ~OffsetRule() { }
   951   CFIRTag getTag() const { return CFIR_OFFSET_RULE; }
   952   bool Handle(Handler *handler, uint64 address, int reg) const {
   953     return handler->OffsetRule(address, reg, base_register_, offset_);
   954   }
   955   bool operator==(const Rule &rhs) const {
   956     if (rhs.getTag() != CFIR_OFFSET_RULE) return false;
   957     const OffsetRule *our_rhs = static_cast<const OffsetRule *>(&rhs);
   958     return (base_register_ == our_rhs->base_register_ &&
   959             offset_ == our_rhs->offset_);
   960   }
   961   Rule *Copy() const { return new OffsetRule(*this); }
   962   // We don't actually need SetBaseRegister or SetOffset here, since they
   963   // are only ever applied to CFA rules, for DW_CFA_def_cfa_offset, and it
   964   // doesn't make sense to use OffsetRule for computing the CFA: it
   965   // computes the address at which a register is saved, not a value.
   966  private:
   967   int base_register_;
   968   long offset_;
   969 };
   971 // Rule: the value the register had in the caller is the value of
   972 // BASE_REGISTER plus offset. BASE_REGISTER may be
   973 // CallFrameInfo::Handler::kCFARegister.
   974 class CallFrameInfo::ValOffsetRule: public CallFrameInfo::Rule {
   975  public:
   976   ValOffsetRule(int base_register, long offset)
   977       : base_register_(base_register), offset_(offset) { }
   978   ~ValOffsetRule() { }
   979   CFIRTag getTag() const { return CFIR_VAL_OFFSET_RULE; }
   980   bool Handle(Handler *handler, uint64 address, int reg) const {
   981     return handler->ValOffsetRule(address, reg, base_register_, offset_);
   982   }
   983   bool operator==(const Rule &rhs) const {
   984     if (rhs.getTag() != CFIR_VAL_OFFSET_RULE) return false;
   985     const ValOffsetRule *our_rhs = static_cast<const ValOffsetRule *>(&rhs);
   986     return (base_register_ == our_rhs->base_register_ &&
   987             offset_ == our_rhs->offset_);
   988   }
   989   Rule *Copy() const { return new ValOffsetRule(*this); }
   990   void SetBaseRegister(unsigned reg) { base_register_ = reg; }
   991   void SetOffset(long long offset) { offset_ = offset; }
   992  private:
   993   int base_register_;
   994   long offset_;
   995 };
   997 // Rule: the register has been saved in another register REGISTER_NUMBER_.
   998 class CallFrameInfo::RegisterRule: public CallFrameInfo::Rule {
   999  public:
  1000   explicit RegisterRule(int register_number)
  1001       : register_number_(register_number) { }
  1002   ~RegisterRule() { }
  1003   CFIRTag getTag() const { return CFIR_REGISTER_RULE; }
  1004   bool Handle(Handler *handler, uint64 address, int reg) const {
  1005     return handler->RegisterRule(address, reg, register_number_);
  1007   bool operator==(const Rule &rhs) const {
  1008     if (rhs.getTag() != CFIR_REGISTER_RULE) return false;
  1009     const RegisterRule *our_rhs = static_cast<const RegisterRule *>(&rhs);
  1010     return (register_number_ == our_rhs->register_number_);
  1012   Rule *Copy() const { return new RegisterRule(*this); }
  1013  private:
  1014   int register_number_;
  1015 };
  1017 // Rule: EXPRESSION evaluates to the address at which the register is saved.
  1018 class CallFrameInfo::ExpressionRule: public CallFrameInfo::Rule {
  1019  public:
  1020   explicit ExpressionRule(const string &expression)
  1021       : expression_(expression) { }
  1022   ~ExpressionRule() { }
  1023   CFIRTag getTag() const { return CFIR_EXPRESSION_RULE; }
  1024   bool Handle(Handler *handler, uint64 address, int reg) const {
  1025     return handler->ExpressionRule(address, reg, expression_);
  1027   bool operator==(const Rule &rhs) const {
  1028     if (rhs.getTag() != CFIR_EXPRESSION_RULE) return false;
  1029     const ExpressionRule *our_rhs = static_cast<const ExpressionRule *>(&rhs);
  1030     return (expression_ == our_rhs->expression_);
  1032   Rule *Copy() const { return new ExpressionRule(*this); }
  1033  private:
  1034   string expression_;
  1035 };
  1037 // Rule: EXPRESSION evaluates to the address at which the register is saved.
  1038 class CallFrameInfo::ValExpressionRule: public CallFrameInfo::Rule {
  1039  public:
  1040   explicit ValExpressionRule(const string &expression)
  1041       : expression_(expression) { }
  1042   ~ValExpressionRule() { }
  1043   CFIRTag getTag() const { return CFIR_VAL_EXPRESSION_RULE; }
  1044   bool Handle(Handler *handler, uint64 address, int reg) const {
  1045     return handler->ValExpressionRule(address, reg, expression_);
  1047   bool operator==(const Rule &rhs) const {
  1048     if (rhs.getTag() != CFIR_VAL_EXPRESSION_RULE) return false;
  1049     const ValExpressionRule *our_rhs =
  1050         static_cast<const ValExpressionRule *>(&rhs);
  1051     return (expression_ == our_rhs->expression_);
  1053   Rule *Copy() const { return new ValExpressionRule(*this); }
  1054  private:
  1055   string expression_;
  1056 };
  1058 // A map from register numbers to rules.
  1059 class CallFrameInfo::RuleMap {
  1060  public:
  1061   RuleMap() : cfa_rule_(NULL) { }
  1062   RuleMap(const RuleMap &rhs) : cfa_rule_(NULL) { *this = rhs; }
  1063   ~RuleMap() { Clear(); }
  1065   RuleMap &operator=(const RuleMap &rhs);
  1067   // Set the rule for computing the CFA to RULE. Take ownership of RULE.
  1068   void SetCFARule(Rule *rule) { delete cfa_rule_; cfa_rule_ = rule; }
  1070   // Return the current CFA rule. Unlike RegisterRule, this RuleMap retains
  1071   // ownership of the rule. We use this for DW_CFA_def_cfa_offset and
  1072   // DW_CFA_def_cfa_register, and for detecting references to the CFA before
  1073   // a rule for it has been established.
  1074   Rule *CFARule() const { return cfa_rule_; }
  1076   // Return the rule for REG, or NULL if there is none. The caller takes
  1077   // ownership of the result.
  1078   Rule *RegisterRule(int reg) const;
  1080   // Set the rule for computing REG to RULE. Take ownership of RULE.
  1081   void SetRegisterRule(int reg, Rule *rule);
  1083   // Make all the appropriate calls to HANDLER as if we were changing from
  1084   // this RuleMap to NEW_RULES at ADDRESS. We use this to implement
  1085   // DW_CFA_restore_state, where lots of rules can change simultaneously.
  1086   // Return true if all handlers returned true; otherwise, return false.
  1087   bool HandleTransitionTo(Handler *handler, uint64 address,
  1088                           const RuleMap &new_rules) const;
  1090  private:
  1091   // A map from register numbers to Rules.
  1092   typedef std::map<int, Rule *> RuleByNumber;
  1094   // Remove all register rules and clear cfa_rule_.
  1095   void Clear();
  1097   // The rule for computing the canonical frame address. This RuleMap owns
  1098   // this rule.
  1099   Rule *cfa_rule_;
  1101   // A map from register numbers to postfix expressions to recover
  1102   // their values. This RuleMap owns the Rules the map refers to.
  1103   RuleByNumber registers_;
  1104 };
  1106 CallFrameInfo::RuleMap &CallFrameInfo::RuleMap::operator=(const RuleMap &rhs) {
  1107   Clear();
  1108   // Since each map owns the rules it refers to, assignment must copy them.
  1109   if (rhs.cfa_rule_) cfa_rule_ = rhs.cfa_rule_->Copy();
  1110   for (RuleByNumber::const_iterator it = rhs.registers_.begin();
  1111        it != rhs.registers_.end(); it++)
  1112     registers_[it->first] = it->second->Copy();
  1113   return *this;
  1116 CallFrameInfo::Rule *CallFrameInfo::RuleMap::RegisterRule(int reg) const {
  1117   assert(reg != Handler::kCFARegister);
  1118   RuleByNumber::const_iterator it = registers_.find(reg);
  1119   if (it != registers_.end())
  1120     return it->second->Copy();
  1121   else
  1122     return NULL;
  1125 void CallFrameInfo::RuleMap::SetRegisterRule(int reg, Rule *rule) {
  1126   assert(reg != Handler::kCFARegister);
  1127   assert(rule);
  1128   Rule **slot = &registers_[reg];
  1129   delete *slot;
  1130   *slot = rule;
  1133 bool CallFrameInfo::RuleMap::HandleTransitionTo(
  1134     Handler *handler,
  1135     uint64 address,
  1136     const RuleMap &new_rules) const {
  1137   // Transition from cfa_rule_ to new_rules.cfa_rule_.
  1138   if (cfa_rule_ && new_rules.cfa_rule_) {
  1139     if (*cfa_rule_ != *new_rules.cfa_rule_ &&
  1140         !new_rules.cfa_rule_->Handle(handler, address,
  1141                                      Handler::kCFARegister))
  1142       return false;
  1143   } else if (cfa_rule_) {
  1144     // this RuleMap has a CFA rule but new_rules doesn't.
  1145     // CallFrameInfo::Handler has no way to handle this --- and shouldn't;
  1146     // it's garbage input. The instruction interpreter should have
  1147     // detected this and warned, so take no action here.
  1148   } else if (new_rules.cfa_rule_) {
  1149     // This shouldn't be possible: NEW_RULES is some prior state, and
  1150     // there's no way to remove entries.
  1151     assert(0);
  1152   } else {
  1153     // Both CFA rules are empty.  No action needed.
  1156   // Traverse the two maps in order by register number, and report
  1157   // whatever differences we find.
  1158   RuleByNumber::const_iterator old_it = registers_.begin();
  1159   RuleByNumber::const_iterator new_it = new_rules.registers_.begin();
  1160   while (old_it != registers_.end() && new_it != new_rules.registers_.end()) {
  1161     if (old_it->first < new_it->first) {
  1162       // This RuleMap has an entry for old_it->first, but NEW_RULES
  1163       // doesn't.
  1164       //
  1165       // This isn't really the right thing to do, but since CFI generally
  1166       // only mentions callee-saves registers, and GCC's convention for
  1167       // callee-saves registers is that they are unchanged, it's a good
  1168       // approximation.
  1169       if (!handler->SameValueRule(address, old_it->first))
  1170         return false;
  1171       old_it++;
  1172     } else if (old_it->first > new_it->first) {
  1173       // NEW_RULES has entry for new_it->first, but this RuleMap
  1174       // doesn't. This shouldn't be possible: NEW_RULES is some prior
  1175       // state, and there's no way to remove entries.
  1176       assert(0);
  1177     } else {
  1178       // Both maps have an entry for this register. Report the new
  1179       // rule if it is different.
  1180       if (*old_it->second != *new_it->second &&
  1181           !new_it->second->Handle(handler, address, new_it->first))
  1182         return false;
  1183       new_it++, old_it++;
  1186   // Finish off entries from this RuleMap with no counterparts in new_rules.
  1187   while (old_it != registers_.end()) {
  1188     if (!handler->SameValueRule(address, old_it->first))
  1189       return false;
  1190     old_it++;
  1192   // Since we only make transitions from a rule set to some previously
  1193   // saved rule set, and we can only add rules to the map, NEW_RULES
  1194   // must have fewer rules than *this.
  1195   assert(new_it == new_rules.registers_.end());
  1197   return true;
  1200 // Remove all register rules and clear cfa_rule_.
  1201 void CallFrameInfo::RuleMap::Clear() {
  1202   delete cfa_rule_;
  1203   cfa_rule_ = NULL;
  1204   for (RuleByNumber::iterator it = registers_.begin();
  1205        it != registers_.end(); it++)
  1206     delete it->second;
  1207   registers_.clear();
  1210 // The state of the call frame information interpreter as it processes
  1211 // instructions from a CIE and FDE.
  1212 class CallFrameInfo::State {
  1213  public:
  1214   // Create a call frame information interpreter state with the given
  1215   // reporter, reader, handler, and initial call frame info address.
  1216   State(ByteReader *reader, Handler *handler, Reporter *reporter,
  1217         uint64 address)
  1218       : reader_(reader), handler_(handler), reporter_(reporter),
  1219         address_(address), entry_(NULL), cursor_(NULL) { }
  1221   // Interpret instructions from CIE, save the resulting rule set for
  1222   // DW_CFA_restore instructions, and return true. On error, report
  1223   // the problem to reporter_ and return false.
  1224   bool InterpretCIE(const CIE &cie);
  1226   // Interpret instructions from FDE, and return true. On error,
  1227   // report the problem to reporter_ and return false.
  1228   bool InterpretFDE(const FDE &fde);
  1230  private:  
  1231   // The operands of a CFI instruction, for ParseOperands.
  1232   struct Operands {
  1233     unsigned register_number;  // A register number.
  1234     uint64 offset;             // An offset or address.
  1235     long signed_offset;        // A signed offset.
  1236     string expression;         // A DWARF expression.
  1237   };
  1239   // Parse CFI instruction operands from STATE's instruction stream as
  1240   // described by FORMAT. On success, populate OPERANDS with the
  1241   // results, and return true. On failure, report the problem and
  1242   // return false.
  1243   //
  1244   // Each character of FORMAT should be one of the following:
  1245   //
  1246   //   'r'  unsigned LEB128 register number (OPERANDS->register_number)
  1247   //   'o'  unsigned LEB128 offset          (OPERANDS->offset)
  1248   //   's'  signed LEB128 offset            (OPERANDS->signed_offset)
  1249   //   'a'  machine-size address            (OPERANDS->offset)
  1250   //        (If the CIE has a 'z' augmentation string, 'a' uses the
  1251   //        encoding specified by the 'R' argument.)
  1252   //   '1'  a one-byte offset               (OPERANDS->offset)
  1253   //   '2'  a two-byte offset               (OPERANDS->offset)
  1254   //   '4'  a four-byte offset              (OPERANDS->offset)
  1255   //   '8'  an eight-byte offset            (OPERANDS->offset)
  1256   //   'e'  a DW_FORM_block holding a       (OPERANDS->expression)
  1257   //        DWARF expression
  1258   bool ParseOperands(const char *format, Operands *operands);
  1260   // Interpret one CFI instruction from STATE's instruction stream, update
  1261   // STATE, report any rule changes to handler_, and return true. On
  1262   // failure, report the problem and return false.
  1263   bool DoInstruction();
  1265   // The following Do* member functions are subroutines of DoInstruction,
  1266   // factoring out the actual work of operations that have several
  1267   // different encodings.
  1269   // Set the CFA rule to be the value of BASE_REGISTER plus OFFSET, and
  1270   // return true. On failure, report and return false. (Used for
  1271   // DW_CFA_def_cfa and DW_CFA_def_cfa_sf.)
  1272   bool DoDefCFA(unsigned base_register, long offset);
  1274   // Change the offset of the CFA rule to OFFSET, and return true. On
  1275   // failure, report and return false. (Subroutine for
  1276   // DW_CFA_def_cfa_offset and DW_CFA_def_cfa_offset_sf.)
  1277   bool DoDefCFAOffset(long offset);
  1279   // Specify that REG can be recovered using RULE, and return true. On
  1280   // failure, report and return false.
  1281   bool DoRule(unsigned reg, Rule *rule);
  1283   // Specify that REG can be found at OFFSET from the CFA, and return true.
  1284   // On failure, report and return false. (Subroutine for DW_CFA_offset,
  1285   // DW_CFA_offset_extended, and DW_CFA_offset_extended_sf.)
  1286   bool DoOffset(unsigned reg, long offset);
  1288   // Specify that the caller's value for REG is the CFA plus OFFSET,
  1289   // and return true. On failure, report and return false. (Subroutine
  1290   // for DW_CFA_val_offset and DW_CFA_val_offset_sf.)
  1291   bool DoValOffset(unsigned reg, long offset);
  1293   // Restore REG to the rule established in the CIE, and return true. On
  1294   // failure, report and return false. (Subroutine for DW_CFA_restore and
  1295   // DW_CFA_restore_extended.)
  1296   bool DoRestore(unsigned reg);
  1298   // Return the section offset of the instruction at cursor. For use
  1299   // in error messages.
  1300   uint64 CursorOffset() { return entry_->offset + (cursor_ - entry_->start); }
  1302   // Report that entry_ is incomplete, and return false. For brevity.
  1303   bool ReportIncomplete() {
  1304     reporter_->Incomplete(entry_->offset, entry_->kind);
  1305     return false;
  1308   // For reading multi-byte values with the appropriate endianness.
  1309   ByteReader *reader_;
  1311   // The handler to which we should report the data we find.
  1312   Handler *handler_;
  1314   // For reporting problems in the info we're parsing.
  1315   Reporter *reporter_;
  1317   // The code address to which the next instruction in the stream applies.
  1318   uint64 address_;
  1320   // The entry whose instructions we are currently processing. This is
  1321   // first a CIE, and then an FDE.
  1322   const Entry *entry_;
  1324   // The next instruction to process.
  1325   const char *cursor_;
  1327   // The current set of rules.
  1328   RuleMap rules_;
  1330   // The set of rules established by the CIE, used by DW_CFA_restore
  1331   // and DW_CFA_restore_extended. We set this after interpreting the
  1332   // CIE's instructions.
  1333   RuleMap cie_rules_;
  1335   // A stack of saved states, for DW_CFA_remember_state and
  1336   // DW_CFA_restore_state.
  1337   std::stack<RuleMap> saved_rules_;
  1338 };
  1340 bool CallFrameInfo::State::InterpretCIE(const CIE &cie) {
  1341   entry_ = &cie;
  1342   cursor_ = entry_->instructions;
  1343   while (cursor_ < entry_->end)
  1344     if (!DoInstruction())
  1345       return false;
  1346   // Note the rules established by the CIE, for use by DW_CFA_restore
  1347   // and DW_CFA_restore_extended.
  1348   cie_rules_ = rules_;
  1349   return true;
  1352 bool CallFrameInfo::State::InterpretFDE(const FDE &fde) {
  1353   entry_ = &fde;
  1354   cursor_ = entry_->instructions;
  1355   while (cursor_ < entry_->end)
  1356     if (!DoInstruction())
  1357       return false;
  1358   return true;
  1361 bool CallFrameInfo::State::ParseOperands(const char *format,
  1362                                          Operands *operands) {
  1363   size_t len;
  1364   const char *operand;
  1366   for (operand = format; *operand; operand++) {
  1367     size_t bytes_left = entry_->end - cursor_;
  1368     switch (*operand) {
  1369       case 'r':
  1370         operands->register_number = reader_->ReadUnsignedLEB128(cursor_, &len);
  1371         if (len > bytes_left) return ReportIncomplete();
  1372         cursor_ += len;
  1373         break;
  1375       case 'o':
  1376         operands->offset = reader_->ReadUnsignedLEB128(cursor_, &len);
  1377         if (len > bytes_left) return ReportIncomplete();
  1378         cursor_ += len;
  1379         break;
  1381       case 's':
  1382         operands->signed_offset = reader_->ReadSignedLEB128(cursor_, &len);
  1383         if (len > bytes_left) return ReportIncomplete();
  1384         cursor_ += len;
  1385         break;
  1387       case 'a':
  1388         operands->offset =
  1389           reader_->ReadEncodedPointer(cursor_, entry_->cie->pointer_encoding,
  1390                                       &len);
  1391         if (len > bytes_left) return ReportIncomplete();
  1392         cursor_ += len;
  1393         break;
  1395       case '1':
  1396         if (1 > bytes_left) return ReportIncomplete();
  1397         operands->offset = static_cast<unsigned char>(*cursor_++);
  1398         break;
  1400       case '2':
  1401         if (2 > bytes_left) return ReportIncomplete();
  1402         operands->offset = reader_->ReadTwoBytes(cursor_);
  1403         cursor_ += 2;
  1404         break;
  1406       case '4':
  1407         if (4 > bytes_left) return ReportIncomplete();
  1408         operands->offset = reader_->ReadFourBytes(cursor_);
  1409         cursor_ += 4;
  1410         break;
  1412       case '8':
  1413         if (8 > bytes_left) return ReportIncomplete();
  1414         operands->offset = reader_->ReadEightBytes(cursor_);
  1415         cursor_ += 8;
  1416         break;
  1418       case 'e': {
  1419         size_t expression_length = reader_->ReadUnsignedLEB128(cursor_, &len);
  1420         if (len > bytes_left || expression_length > bytes_left - len)
  1421           return ReportIncomplete();
  1422         cursor_ += len;
  1423         operands->expression = string(cursor_, expression_length);
  1424         cursor_ += expression_length;
  1425         break;
  1428       default:
  1429           assert(0);
  1433   return true;
  1436 bool CallFrameInfo::State::DoInstruction() {
  1437   CIE *cie = entry_->cie;
  1438   Operands ops;
  1440   // Our entry's kind should have been set by now.
  1441   assert(entry_->kind != kUnknown);
  1443   // We shouldn't have been invoked unless there were more
  1444   // instructions to parse.
  1445   assert(cursor_ < entry_->end);
  1447   unsigned opcode = *cursor_++;
  1448   if ((opcode & 0xc0) != 0) {
  1449     switch (opcode & 0xc0) {
  1450       // Advance the address.
  1451       case DW_CFA_advance_loc: {
  1452         size_t code_offset = opcode & 0x3f;
  1453         address_ += code_offset * cie->code_alignment_factor;
  1454         break;
  1457       // Find a register at an offset from the CFA.
  1458       case DW_CFA_offset:
  1459         if (!ParseOperands("o", &ops) ||
  1460             !DoOffset(opcode & 0x3f, ops.offset * cie->data_alignment_factor))
  1461           return false;
  1462         break;
  1464       // Restore the rule established for a register by the CIE.
  1465       case DW_CFA_restore:
  1466         if (!DoRestore(opcode & 0x3f)) return false;
  1467         break;
  1469       // The 'if' above should have excluded this possibility.
  1470       default:
  1471         assert(0);
  1474     // Return here, so the big switch below won't be indented.
  1475     return true;
  1478   switch (opcode) {
  1479     // Set the address.
  1480     case DW_CFA_set_loc:
  1481       if (!ParseOperands("a", &ops)) return false;
  1482       address_ = ops.offset;
  1483       break;
  1485     // Advance the address.
  1486     case DW_CFA_advance_loc1:
  1487       if (!ParseOperands("1", &ops)) return false;
  1488       address_ += ops.offset * cie->code_alignment_factor;
  1489       break;
  1491     // Advance the address.
  1492     case DW_CFA_advance_loc2:
  1493       if (!ParseOperands("2", &ops)) return false;
  1494       address_ += ops.offset * cie->code_alignment_factor;
  1495       break;
  1497     // Advance the address.
  1498     case DW_CFA_advance_loc4:
  1499       if (!ParseOperands("4", &ops)) return false;
  1500       address_ += ops.offset * cie->code_alignment_factor;
  1501       break;
  1503     // Advance the address.
  1504     case DW_CFA_MIPS_advance_loc8:
  1505       if (!ParseOperands("8", &ops)) return false;
  1506       address_ += ops.offset * cie->code_alignment_factor;
  1507       break;
  1509     // Compute the CFA by adding an offset to a register.
  1510     case DW_CFA_def_cfa:
  1511       if (!ParseOperands("ro", &ops) ||
  1512           !DoDefCFA(ops.register_number, ops.offset))
  1513         return false;
  1514       break;
  1516     // Compute the CFA by adding an offset to a register.
  1517     case DW_CFA_def_cfa_sf:
  1518       if (!ParseOperands("rs", &ops) ||
  1519           !DoDefCFA(ops.register_number,
  1520                     ops.signed_offset * cie->data_alignment_factor))
  1521         return false;
  1522       break;
  1524     // Change the base register used to compute the CFA.
  1525     case DW_CFA_def_cfa_register: {
  1526       Rule *cfa_rule = rules_.CFARule();
  1527       if (!cfa_rule) {
  1528         reporter_->NoCFARule(entry_->offset, entry_->kind, CursorOffset());
  1529         return false;
  1531       if (!ParseOperands("r", &ops)) return false;
  1532       cfa_rule->SetBaseRegister(ops.register_number);
  1533       if (!cfa_rule->Handle(handler_, address_,
  1534                             Handler::kCFARegister))
  1535         return false;
  1536       break;
  1539     // Change the offset used to compute the CFA.
  1540     case DW_CFA_def_cfa_offset:
  1541       if (!ParseOperands("o", &ops) ||
  1542           !DoDefCFAOffset(ops.offset))
  1543         return false;
  1544       break;
  1546     // Change the offset used to compute the CFA.
  1547     case DW_CFA_def_cfa_offset_sf:
  1548       if (!ParseOperands("s", &ops) ||
  1549           !DoDefCFAOffset(ops.signed_offset * cie->data_alignment_factor))
  1550         return false;
  1551       break;
  1553     // Specify an expression whose value is the CFA.
  1554     case DW_CFA_def_cfa_expression: {
  1555       if (!ParseOperands("e", &ops))
  1556         return false;
  1557       Rule *rule = new ValExpressionRule(ops.expression);
  1558       rules_.SetCFARule(rule);
  1559       if (!rule->Handle(handler_, address_,
  1560                         Handler::kCFARegister))
  1561         return false;
  1562       break;
  1565     // The register's value cannot be recovered.
  1566     case DW_CFA_undefined: {
  1567       if (!ParseOperands("r", &ops) ||
  1568           !DoRule(ops.register_number, new UndefinedRule()))
  1569         return false;
  1570       break;
  1573     // The register's value is unchanged from its value in the caller.
  1574     case DW_CFA_same_value: {
  1575       if (!ParseOperands("r", &ops) ||
  1576           !DoRule(ops.register_number, new SameValueRule()))
  1577         return false;
  1578       break;
  1581     // Find a register at an offset from the CFA.
  1582     case DW_CFA_offset_extended:
  1583       if (!ParseOperands("ro", &ops) ||
  1584           !DoOffset(ops.register_number,
  1585                     ops.offset * cie->data_alignment_factor))
  1586         return false;
  1587       break;
  1589     // The register is saved at an offset from the CFA.
  1590     case DW_CFA_offset_extended_sf:
  1591       if (!ParseOperands("rs", &ops) ||
  1592           !DoOffset(ops.register_number,
  1593                     ops.signed_offset * cie->data_alignment_factor))
  1594         return false;
  1595       break;
  1597     // The register is saved at an offset from the CFA.
  1598     case DW_CFA_GNU_negative_offset_extended:
  1599       if (!ParseOperands("ro", &ops) ||
  1600           !DoOffset(ops.register_number,
  1601                     -ops.offset * cie->data_alignment_factor))
  1602         return false;
  1603       break;
  1605     // The register's value is the sum of the CFA plus an offset.
  1606     case DW_CFA_val_offset:
  1607       if (!ParseOperands("ro", &ops) ||
  1608           !DoValOffset(ops.register_number,
  1609                        ops.offset * cie->data_alignment_factor))
  1610         return false;
  1611       break;
  1613     // The register's value is the sum of the CFA plus an offset.
  1614     case DW_CFA_val_offset_sf:
  1615       if (!ParseOperands("rs", &ops) ||
  1616           !DoValOffset(ops.register_number,
  1617                        ops.signed_offset * cie->data_alignment_factor))
  1618         return false;
  1619       break;
  1621     // The register has been saved in another register.
  1622     case DW_CFA_register: {
  1623       if (!ParseOperands("ro", &ops) ||
  1624           !DoRule(ops.register_number, new RegisterRule(ops.offset)))
  1625         return false;
  1626       break;
  1629     // An expression yields the address at which the register is saved.
  1630     case DW_CFA_expression: {
  1631       if (!ParseOperands("re", &ops) ||
  1632           !DoRule(ops.register_number, new ExpressionRule(ops.expression)))
  1633         return false;
  1634       break;
  1637     // An expression yields the caller's value for the register.
  1638     case DW_CFA_val_expression: {
  1639       if (!ParseOperands("re", &ops) ||
  1640           !DoRule(ops.register_number, new ValExpressionRule(ops.expression)))
  1641         return false;
  1642       break;
  1645     // Restore the rule established for a register by the CIE.
  1646     case DW_CFA_restore_extended:
  1647       if (!ParseOperands("r", &ops) ||
  1648           !DoRestore( ops.register_number))
  1649         return false;
  1650       break;
  1652     // Save the current set of rules on a stack.
  1653     case DW_CFA_remember_state:
  1654       saved_rules_.push(rules_);
  1655       break;
  1657     // Pop the current set of rules off the stack.
  1658     case DW_CFA_restore_state: {
  1659       if (saved_rules_.empty()) {
  1660         reporter_->EmptyStateStack(entry_->offset, entry_->kind,
  1661                                    CursorOffset());
  1662         return false;
  1664       const RuleMap &new_rules = saved_rules_.top();
  1665       if (rules_.CFARule() && !new_rules.CFARule()) {
  1666         reporter_->ClearingCFARule(entry_->offset, entry_->kind,
  1667                                    CursorOffset());
  1668         return false;
  1670       rules_.HandleTransitionTo(handler_, address_, new_rules);
  1671       rules_ = new_rules;
  1672       saved_rules_.pop();
  1673       break;
  1676     // No operation.  (Padding instruction.)
  1677     case DW_CFA_nop:
  1678       break;
  1680     // A SPARC register window save: Registers 8 through 15 (%o0-%o7)
  1681     // are saved in registers 24 through 31 (%i0-%i7), and registers
  1682     // 16 through 31 (%l0-%l7 and %i0-%i7) are saved at CFA offsets
  1683     // (0-15 * the register size). The register numbers must be
  1684     // hard-coded. A GNU extension, and not a pretty one.
  1685     case DW_CFA_GNU_window_save: {
  1686       // Save %o0-%o7 in %i0-%i7.
  1687       for (int i = 8; i < 16; i++)
  1688         if (!DoRule(i, new RegisterRule(i + 16)))
  1689           return false;
  1690       // Save %l0-%l7 and %i0-%i7 at the CFA.
  1691       for (int i = 16; i < 32; i++)
  1692         // Assume that the byte reader's address size is the same as
  1693         // the architecture's register size. !@#%*^ hilarious.
  1694         if (!DoRule(i, new OffsetRule(Handler::kCFARegister,
  1695                                       (i - 16) * reader_->AddressSize())))
  1696           return false;
  1697       break;
  1700     // I'm not sure what this is. GDB doesn't use it for unwinding.
  1701     case DW_CFA_GNU_args_size:
  1702       if (!ParseOperands("o", &ops)) return false;
  1703       break;
  1705     // An opcode we don't recognize.
  1706     default: {
  1707       reporter_->BadInstruction(entry_->offset, entry_->kind, CursorOffset());
  1708       return false;
  1712   return true;
  1715 bool CallFrameInfo::State::DoDefCFA(unsigned base_register, long offset) {
  1716   Rule *rule = new ValOffsetRule(base_register, offset);
  1717   rules_.SetCFARule(rule);
  1718   return rule->Handle(handler_, address_,
  1719                       Handler::kCFARegister);
  1722 bool CallFrameInfo::State::DoDefCFAOffset(long offset) {
  1723   Rule *cfa_rule = rules_.CFARule();
  1724   if (!cfa_rule) {
  1725     reporter_->NoCFARule(entry_->offset, entry_->kind, CursorOffset());
  1726     return false;
  1728   cfa_rule->SetOffset(offset);
  1729   return cfa_rule->Handle(handler_, address_,
  1730                           Handler::kCFARegister);
  1733 bool CallFrameInfo::State::DoRule(unsigned reg, Rule *rule) {
  1734   rules_.SetRegisterRule(reg, rule);
  1735   return rule->Handle(handler_, address_, reg);
  1738 bool CallFrameInfo::State::DoOffset(unsigned reg, long offset) {
  1739   if (!rules_.CFARule()) {
  1740     reporter_->NoCFARule(entry_->offset, entry_->kind, CursorOffset());
  1741     return false;
  1743   return DoRule(reg,
  1744                 new OffsetRule(Handler::kCFARegister, offset));
  1747 bool CallFrameInfo::State::DoValOffset(unsigned reg, long offset) {
  1748   if (!rules_.CFARule()) {
  1749     reporter_->NoCFARule(entry_->offset, entry_->kind, CursorOffset());
  1750     return false;
  1752   return DoRule(reg,
  1753                 new ValOffsetRule(Handler::kCFARegister, offset));
  1756 bool CallFrameInfo::State::DoRestore(unsigned reg) {
  1757   // DW_CFA_restore and DW_CFA_restore_extended don't make sense in a CIE.
  1758   if (entry_->kind == kCIE) {
  1759     reporter_->RestoreInCIE(entry_->offset, CursorOffset());
  1760     return false;
  1762   Rule *rule = cie_rules_.RegisterRule(reg);
  1763   if (!rule) {
  1764     // This isn't really the right thing to do, but since CFI generally
  1765     // only mentions callee-saves registers, and GCC's convention for
  1766     // callee-saves registers is that they are unchanged, it's a good
  1767     // approximation.
  1768     rule = new SameValueRule();
  1770   return DoRule(reg, rule);
  1773 bool CallFrameInfo::ReadEntryPrologue(const char *cursor, Entry *entry) {
  1774   const char *buffer_end = buffer_ + buffer_length_;
  1776   // Initialize enough of ENTRY for use in error reporting.
  1777   entry->offset = cursor - buffer_;
  1778   entry->start = cursor;
  1779   entry->kind = kUnknown;
  1780   entry->end = NULL;
  1782   // Read the initial length. This sets reader_'s offset size.
  1783   size_t length_size;
  1784   uint64 length = reader_->ReadInitialLength(cursor, &length_size);
  1785   if (length_size > size_t(buffer_end - cursor))
  1786     return ReportIncomplete(entry);
  1787   cursor += length_size;
  1789   // In a .eh_frame section, a length of zero marks the end of the series
  1790   // of entries.
  1791   if (length == 0 && eh_frame_) {
  1792     entry->kind = kTerminator;
  1793     entry->end = cursor;
  1794     return true;
  1797   // Validate the length.
  1798   if (length > size_t(buffer_end - cursor))
  1799     return ReportIncomplete(entry);
  1801   // The length is the number of bytes after the initial length field;
  1802   // we have that position handy at this point, so compute the end
  1803   // now. (If we're parsing 64-bit-offset DWARF on a 32-bit machine,
  1804   // and the length didn't fit in a size_t, we would have rejected it
  1805   // above.)
  1806   entry->end = cursor + length;
  1808   // Parse the next field: either the offset of a CIE or a CIE id.
  1809   size_t offset_size = reader_->OffsetSize();
  1810   if (offset_size > size_t(entry->end - cursor)) return ReportIncomplete(entry);
  1811   entry->id = reader_->ReadOffset(cursor);
  1813   // Don't advance cursor past id field yet; in .eh_frame data we need
  1814   // the id's position to compute the section offset of an FDE's CIE.
  1816   // Now we can decide what kind of entry this is.
  1817   if (eh_frame_) {
  1818     // In .eh_frame data, an ID of zero marks the entry as a CIE, and
  1819     // anything else is an offset from the id field of the FDE to the start
  1820     // of the CIE.
  1821     if (entry->id == 0) {
  1822       entry->kind = kCIE;
  1823     } else {
  1824       entry->kind = kFDE;
  1825       // Turn the offset from the id into an offset from the buffer's start.
  1826       entry->id = (cursor - buffer_) - entry->id;
  1828   } else {
  1829     // In DWARF CFI data, an ID of ~0 (of the appropriate width, given the
  1830     // offset size for the entry) marks the entry as a CIE, and anything
  1831     // else is the offset of the CIE from the beginning of the section.
  1832     if (offset_size == 4)
  1833       entry->kind = (entry->id == 0xffffffff) ? kCIE : kFDE;
  1834     else {
  1835       assert(offset_size == 8);
  1836       entry->kind = (entry->id == 0xffffffffffffffffULL) ? kCIE : kFDE;
  1840   // Now advance cursor past the id.
  1841    cursor += offset_size;
  1843   // The fields specific to this kind of entry start here.
  1844   entry->fields = cursor;
  1846   entry->cie = NULL;
  1848   return true;
  1851 bool CallFrameInfo::ReadCIEFields(CIE *cie) {
  1852   const char *cursor = cie->fields;
  1853   size_t len;
  1855   assert(cie->kind == kCIE);
  1857   // Prepare for early exit.
  1858   cie->version = 0;
  1859   cie->augmentation.clear();
  1860   cie->code_alignment_factor = 0;
  1861   cie->data_alignment_factor = 0;
  1862   cie->return_address_register = 0;
  1863   cie->has_z_augmentation = false;
  1864   cie->pointer_encoding = DW_EH_PE_absptr;
  1865   cie->instructions = 0;
  1867   // Parse the version number.
  1868   if (cie->end - cursor < 1)
  1869     return ReportIncomplete(cie);
  1870   cie->version = reader_->ReadOneByte(cursor);
  1871   cursor++;
  1873   // If we don't recognize the version, we can't parse any more fields of the
  1874   // CIE. For DWARF CFI, we handle versions 1 through 3 (there was never a
  1875   // version 2 of CFI data). For .eh_frame, we handle versions 1 and 3 as well;
  1876   // the difference between those versions seems to be the same as for
  1877   // .debug_frame.
  1878   if (cie->version < 1 || cie->version > 3) {
  1879     reporter_->UnrecognizedVersion(cie->offset, cie->version);
  1880     return false;
  1883   const char *augmentation_start = cursor;
  1884   const void *augmentation_end =
  1885       memchr(augmentation_start, '\0', cie->end - augmentation_start);
  1886   if (! augmentation_end) return ReportIncomplete(cie);
  1887   cursor = static_cast<const char *>(augmentation_end);
  1888   cie->augmentation = string(augmentation_start,
  1889                                   cursor - augmentation_start);
  1890   // Skip the terminating '\0'.
  1891   cursor++;
  1893   // Is this CFI augmented?
  1894   if (!cie->augmentation.empty()) {
  1895     // Is it an augmentation we recognize?
  1896     if (cie->augmentation[0] == DW_Z_augmentation_start) {
  1897       // Linux C++ ABI 'z' augmentation, used for exception handling data.
  1898       cie->has_z_augmentation = true;
  1899     } else {
  1900       // Not an augmentation we recognize. Augmentations can have arbitrary
  1901       // effects on the form of rest of the content, so we have to give up.
  1902       reporter_->UnrecognizedAugmentation(cie->offset, cie->augmentation);
  1903       return false;
  1907   // Parse the code alignment factor.
  1908   cie->code_alignment_factor = reader_->ReadUnsignedLEB128(cursor, &len);
  1909   if (size_t(cie->end - cursor) < len) return ReportIncomplete(cie);
  1910   cursor += len;
  1912   // Parse the data alignment factor.
  1913   cie->data_alignment_factor = reader_->ReadSignedLEB128(cursor, &len);
  1914   if (size_t(cie->end - cursor) < len) return ReportIncomplete(cie);
  1915   cursor += len;
  1917   // Parse the return address register. This is a ubyte in version 1, and
  1918   // a ULEB128 in version 3.
  1919   if (cie->version == 1) {
  1920     if (cursor >= cie->end) return ReportIncomplete(cie);
  1921     cie->return_address_register = uint8(*cursor++);
  1922   } else {
  1923     cie->return_address_register = reader_->ReadUnsignedLEB128(cursor, &len);
  1924     if (size_t(cie->end - cursor) < len) return ReportIncomplete(cie);
  1925     cursor += len;
  1928   // If we have a 'z' augmentation string, find the augmentation data and
  1929   // use the augmentation string to parse it.
  1930   if (cie->has_z_augmentation) {
  1931     uint64_t data_size = reader_->ReadUnsignedLEB128(cursor, &len);
  1932     if (size_t(cie->end - cursor) < len + data_size)
  1933       return ReportIncomplete(cie);
  1934     cursor += len;
  1935     const char *data = cursor;
  1936     cursor += data_size;
  1937     const char *data_end = cursor;
  1939     cie->has_z_lsda = false;
  1940     cie->has_z_personality = false;
  1941     cie->has_z_signal_frame = false;
  1943     // Walk the augmentation string, and extract values from the
  1944     // augmentation data as the string directs.
  1945     for (size_t i = 1; i < cie->augmentation.size(); i++) {
  1946       switch (cie->augmentation[i]) {
  1947         case DW_Z_has_LSDA:
  1948           // The CIE's augmentation data holds the language-specific data
  1949           // area pointer's encoding, and the FDE's augmentation data holds
  1950           // the pointer itself.
  1951           cie->has_z_lsda = true;
  1952           // Fetch the LSDA encoding from the augmentation data.
  1953           if (data >= data_end) return ReportIncomplete(cie);
  1954           cie->lsda_encoding = DwarfPointerEncoding(*data++);
  1955           if (!reader_->ValidEncoding(cie->lsda_encoding)) {
  1956             reporter_->InvalidPointerEncoding(cie->offset, cie->lsda_encoding);
  1957             return false;
  1959           // Don't check if the encoding is usable here --- we haven't
  1960           // read the FDE's fields yet, so we're not prepared for
  1961           // DW_EH_PE_funcrel, although that's a fine encoding for the
  1962           // LSDA to use, since it appears in the FDE.
  1963           break;
  1965         case DW_Z_has_personality_routine:
  1966           // The CIE's augmentation data holds the personality routine
  1967           // pointer's encoding, followed by the pointer itself.
  1968           cie->has_z_personality = true;
  1969           // Fetch the personality routine pointer's encoding from the
  1970           // augmentation data.
  1971           if (data >= data_end) return ReportIncomplete(cie);
  1972           cie->personality_encoding = DwarfPointerEncoding(*data++);
  1973           if (!reader_->ValidEncoding(cie->personality_encoding)) {
  1974             reporter_->InvalidPointerEncoding(cie->offset,
  1975                                               cie->personality_encoding);
  1976             return false;
  1978           if (!reader_->UsableEncoding(cie->personality_encoding)) {
  1979             reporter_->UnusablePointerEncoding(cie->offset,
  1980                                                cie->personality_encoding);
  1981             return false;
  1983           // Fetch the personality routine's pointer itself from the data.
  1984           cie->personality_address =
  1985             reader_->ReadEncodedPointer(data, cie->personality_encoding,
  1986                                         &len);
  1987           if (len > size_t(data_end - data))
  1988             return ReportIncomplete(cie);
  1989           data += len;
  1990           break;
  1992         case DW_Z_has_FDE_address_encoding:
  1993           // The CIE's augmentation data holds the pointer encoding to use
  1994           // for addresses in the FDE.
  1995           if (data >= data_end) return ReportIncomplete(cie);
  1996           cie->pointer_encoding = DwarfPointerEncoding(*data++);
  1997           if (!reader_->ValidEncoding(cie->pointer_encoding)) {
  1998             reporter_->InvalidPointerEncoding(cie->offset,
  1999                                               cie->pointer_encoding);
  2000             return false;
  2002           if (!reader_->UsableEncoding(cie->pointer_encoding)) {
  2003             reporter_->UnusablePointerEncoding(cie->offset,
  2004                                                cie->pointer_encoding);
  2005             return false;
  2007           break;
  2009         case DW_Z_is_signal_trampoline:
  2010           // Frames using this CIE are signal delivery frames.
  2011           cie->has_z_signal_frame = true;
  2012           break;
  2014         default:
  2015           // An augmentation we don't recognize.
  2016           reporter_->UnrecognizedAugmentation(cie->offset, cie->augmentation);
  2017           return false;
  2022   // The CIE's instructions start here.
  2023   cie->instructions = cursor;
  2025   return true;
  2028 bool CallFrameInfo::ReadFDEFields(FDE *fde) {
  2029   const char *cursor = fde->fields;
  2030   size_t size;
  2032   fde->address = reader_->ReadEncodedPointer(cursor, fde->cie->pointer_encoding,
  2033                                              &size);
  2034   if (size > size_t(fde->end - cursor))
  2035     return ReportIncomplete(fde);
  2036   cursor += size;
  2037   reader_->SetFunctionBase(fde->address);
  2039   // For the length, we strip off the upper nybble of the encoding used for
  2040   // the starting address.
  2041   DwarfPointerEncoding length_encoding =
  2042     DwarfPointerEncoding(fde->cie->pointer_encoding & 0x0f);
  2043   fde->size = reader_->ReadEncodedPointer(cursor, length_encoding, &size);
  2044   if (size > size_t(fde->end - cursor))
  2045     return ReportIncomplete(fde);
  2046   cursor += size;
  2048   // If the CIE has a 'z' augmentation string, then augmentation data
  2049   // appears here.
  2050   if (fde->cie->has_z_augmentation) {
  2051     uint64_t data_size = reader_->ReadUnsignedLEB128(cursor, &size);
  2052     if (size_t(fde->end - cursor) < size + data_size)
  2053       return ReportIncomplete(fde);
  2054     cursor += size;
  2056     // In the abstract, we should walk the augmentation string, and extract
  2057     // items from the FDE's augmentation data as we encounter augmentation
  2058     // string characters that specify their presence: the ordering of items
  2059     // in the augmentation string determines the arrangement of values in
  2060     // the augmentation data.
  2061     //
  2062     // In practice, there's only ever one value in FDE augmentation data
  2063     // that we support --- the LSDA pointer --- and we have to bail if we
  2064     // see any unrecognized augmentation string characters. So if there is
  2065     // anything here at all, we know what it is, and where it starts.
  2066     if (fde->cie->has_z_lsda) {
  2067       // Check whether the LSDA's pointer encoding is usable now: only once
  2068       // we've parsed the FDE's starting address do we call reader_->
  2069       // SetFunctionBase, so that the DW_EH_PE_funcrel encoding becomes
  2070       // usable.
  2071       if (!reader_->UsableEncoding(fde->cie->lsda_encoding)) {
  2072         reporter_->UnusablePointerEncoding(fde->cie->offset,
  2073                                            fde->cie->lsda_encoding);
  2074         return false;
  2077       fde->lsda_address =
  2078         reader_->ReadEncodedPointer(cursor, fde->cie->lsda_encoding, &size);
  2079       if (size > data_size)
  2080         return ReportIncomplete(fde);
  2081       // Ideally, we would also complain here if there were unconsumed
  2082       // augmentation data.
  2085     cursor += data_size;
  2088   // The FDE's instructions start after those.
  2089   fde->instructions = cursor;
  2091   return true;
  2094 bool CallFrameInfo::Start() {
  2095   const char *buffer_end = buffer_ + buffer_length_;
  2096   const char *cursor;
  2097   bool all_ok = true;
  2098   const char *entry_end;
  2099   bool ok;
  2101   // Traverse all the entries in buffer_, skipping CIEs and offering
  2102   // FDEs to the handler.
  2103   for (cursor = buffer_; cursor < buffer_end;
  2104        cursor = entry_end, all_ok = all_ok && ok) {
  2105     FDE fde;
  2107     // Make it easy to skip this entry with 'continue': assume that
  2108     // things are not okay until we've checked all the data, and
  2109     // prepare the address of the next entry.
  2110     ok = false;
  2112     // Read the entry's prologue.
  2113     if (!ReadEntryPrologue(cursor, &fde)) {
  2114       if (!fde.end) {
  2115         // If we couldn't even figure out this entry's extent, then we
  2116         // must stop processing entries altogether.
  2117         all_ok = false;
  2118         break;
  2120       entry_end = fde.end;
  2121       continue;
  2124     // The next iteration picks up after this entry.
  2125     entry_end = fde.end;
  2127     // Did we see an .eh_frame terminating mark?
  2128     if (fde.kind == kTerminator) {
  2129       // If there appears to be more data left in the section after the
  2130       // terminating mark, warn the user. But this is just a warning;
  2131       // we leave all_ok true.
  2132       if (fde.end < buffer_end) reporter_->EarlyEHTerminator(fde.offset);
  2133       break;
  2136     // In this loop, we skip CIEs. We only parse them fully when we
  2137     // parse an FDE that refers to them. This limits our memory
  2138     // consumption (beyond the buffer itself) to that needed to
  2139     // process the largest single entry.
  2140     if (fde.kind != kFDE) {
  2141       ok = true;
  2142       continue;
  2145     // Validate the CIE pointer.
  2146     if (fde.id > buffer_length_) {
  2147       reporter_->CIEPointerOutOfRange(fde.offset, fde.id);
  2148       continue;
  2151     CIE cie;
  2153     // Parse this FDE's CIE header.
  2154     if (!ReadEntryPrologue(buffer_ + fde.id, &cie))
  2155       continue;
  2156     // This had better be an actual CIE.
  2157     if (cie.kind != kCIE) {
  2158       reporter_->BadCIEId(fde.offset, fde.id);
  2159       continue;
  2161     if (!ReadCIEFields(&cie))
  2162       continue;
  2164     // We now have the values that govern both the CIE and the FDE.
  2165     cie.cie = &cie;
  2166     fde.cie = &cie;
  2168     // Parse the FDE's header.
  2169     if (!ReadFDEFields(&fde))
  2170       continue;
  2172     // Call Entry to ask the consumer if they're interested.
  2173     if (!handler_->Entry(fde.offset, fde.address, fde.size,
  2174                          cie.version, cie.augmentation,
  2175                          cie.return_address_register)) {
  2176       // The handler isn't interested in this entry. That's not an error.
  2177       ok = true;
  2178       continue;
  2181     if (cie.has_z_augmentation) {
  2182       // Report the personality routine address, if we have one.
  2183       if (cie.has_z_personality) {
  2184         if (!handler_
  2185             ->PersonalityRoutine(cie.personality_address,
  2186                                  IsIndirectEncoding(cie.personality_encoding)))
  2187           continue;
  2190       // Report the language-specific data area address, if we have one.
  2191       if (cie.has_z_lsda) {
  2192         if (!handler_
  2193             ->LanguageSpecificDataArea(fde.lsda_address,
  2194                                        IsIndirectEncoding(cie.lsda_encoding)))
  2195           continue;
  2198       // If this is a signal-handling frame, report that.
  2199       if (cie.has_z_signal_frame) {
  2200         if (!handler_->SignalHandler())
  2201           continue;
  2205     // Interpret the CIE's instructions, and then the FDE's instructions.
  2206     State state(reader_, handler_, reporter_, fde.address);
  2207     ok = state.InterpretCIE(cie) && state.InterpretFDE(fde);
  2209     // Tell the ByteReader that the function start address from the
  2210     // FDE header is no longer valid.
  2211     reader_->ClearFunctionBase();
  2213     // Report the end of the entry.
  2214     handler_->End();
  2217   return all_ok;
  2220 const char *CallFrameInfo::KindName(EntryKind kind) {
  2221   if (kind == CallFrameInfo::kUnknown)
  2222     return "entry";
  2223   else if (kind == CallFrameInfo::kCIE)
  2224     return "common information entry";
  2225   else if (kind == CallFrameInfo::kFDE)
  2226     return "frame description entry";
  2227   else {
  2228     assert (kind == CallFrameInfo::kTerminator);
  2229     return ".eh_frame sequence terminator";
  2233 bool CallFrameInfo::ReportIncomplete(Entry *entry) {
  2234   reporter_->Incomplete(entry->offset, entry->kind);
  2235   return false;
  2238 void CallFrameInfo::Reporter::Incomplete(uint64 offset,
  2239                                          CallFrameInfo::EntryKind kind) {
  2240   fprintf(stderr,
  2241           "%s: CFI %s at offset 0x%llx in '%s': entry ends early\n",
  2242           filename_.c_str(), CallFrameInfo::KindName(kind), offset,
  2243           section_.c_str());
  2246 void CallFrameInfo::Reporter::EarlyEHTerminator(uint64 offset) {
  2247   fprintf(stderr,
  2248           "%s: CFI at offset 0x%llx in '%s': saw end-of-data marker"
  2249           " before end of section contents\n",
  2250           filename_.c_str(), offset, section_.c_str());
  2253 void CallFrameInfo::Reporter::CIEPointerOutOfRange(uint64 offset,
  2254                                                    uint64 cie_offset) {
  2255   fprintf(stderr,
  2256           "%s: CFI frame description entry at offset 0x%llx in '%s':"
  2257           " CIE pointer is out of range: 0x%llx\n",
  2258           filename_.c_str(), offset, section_.c_str(), cie_offset);
  2261 void CallFrameInfo::Reporter::BadCIEId(uint64 offset, uint64 cie_offset) {
  2262   fprintf(stderr,
  2263           "%s: CFI frame description entry at offset 0x%llx in '%s':"
  2264           " CIE pointer does not point to a CIE: 0x%llx\n",
  2265           filename_.c_str(), offset, section_.c_str(), cie_offset);
  2268 void CallFrameInfo::Reporter::UnrecognizedVersion(uint64 offset, int version) {
  2269   fprintf(stderr,
  2270           "%s: CFI frame description entry at offset 0x%llx in '%s':"
  2271           " CIE specifies unrecognized version: %d\n",
  2272           filename_.c_str(), offset, section_.c_str(), version);
  2275 void CallFrameInfo::Reporter::UnrecognizedAugmentation(uint64 offset,
  2276                                                        const string &aug) {
  2277   fprintf(stderr,
  2278           "%s: CFI frame description entry at offset 0x%llx in '%s':"
  2279           " CIE specifies unrecognized augmentation: '%s'\n",
  2280           filename_.c_str(), offset, section_.c_str(), aug.c_str());
  2283 void CallFrameInfo::Reporter::InvalidPointerEncoding(uint64 offset,
  2284                                                      uint8 encoding) {
  2285   fprintf(stderr,
  2286           "%s: CFI common information entry at offset 0x%llx in '%s':"
  2287           " 'z' augmentation specifies invalid pointer encoding: 0x%02x\n",
  2288           filename_.c_str(), offset, section_.c_str(), encoding);
  2291 void CallFrameInfo::Reporter::UnusablePointerEncoding(uint64 offset,
  2292                                                       uint8 encoding) {
  2293   fprintf(stderr,
  2294           "%s: CFI common information entry at offset 0x%llx in '%s':"
  2295           " 'z' augmentation specifies a pointer encoding for which"
  2296           " we have no base address: 0x%02x\n",
  2297           filename_.c_str(), offset, section_.c_str(), encoding);
  2300 void CallFrameInfo::Reporter::RestoreInCIE(uint64 offset, uint64 insn_offset) {
  2301   fprintf(stderr,
  2302           "%s: CFI common information entry at offset 0x%llx in '%s':"
  2303           " the DW_CFA_restore instruction at offset 0x%llx"
  2304           " cannot be used in a common information entry\n",
  2305           filename_.c_str(), offset, section_.c_str(), insn_offset);
  2308 void CallFrameInfo::Reporter::BadInstruction(uint64 offset,
  2309                                              CallFrameInfo::EntryKind kind,
  2310                                              uint64 insn_offset) {
  2311   fprintf(stderr,
  2312           "%s: CFI %s at offset 0x%llx in section '%s':"
  2313           " the instruction at offset 0x%llx is unrecognized\n",
  2314           filename_.c_str(), CallFrameInfo::KindName(kind),
  2315           offset, section_.c_str(), insn_offset);
  2318 void CallFrameInfo::Reporter::NoCFARule(uint64 offset,
  2319                                         CallFrameInfo::EntryKind kind,
  2320                                         uint64 insn_offset) {
  2321   fprintf(stderr,
  2322           "%s: CFI %s at offset 0x%llx in section '%s':"
  2323           " the instruction at offset 0x%llx assumes that a CFA rule has"
  2324           " been set, but none has been set\n",
  2325           filename_.c_str(), CallFrameInfo::KindName(kind), offset,
  2326           section_.c_str(), insn_offset);
  2329 void CallFrameInfo::Reporter::EmptyStateStack(uint64 offset,
  2330                                               CallFrameInfo::EntryKind kind,
  2331                                               uint64 insn_offset) {
  2332   fprintf(stderr,
  2333           "%s: CFI %s at offset 0x%llx in section '%s':"
  2334           " the DW_CFA_restore_state instruction at offset 0x%llx"
  2335           " should pop a saved state from the stack, but the stack is empty\n",
  2336           filename_.c_str(), CallFrameInfo::KindName(kind), offset,
  2337           section_.c_str(), insn_offset);
  2340 void CallFrameInfo::Reporter::ClearingCFARule(uint64 offset,
  2341                                               CallFrameInfo::EntryKind kind,
  2342                                               uint64 insn_offset) {
  2343   fprintf(stderr,
  2344           "%s: CFI %s at offset 0x%llx in section '%s':"
  2345           " the DW_CFA_restore_state instruction at offset 0x%llx"
  2346           " would clear the CFA rule in effect\n",
  2347           filename_.c_str(), CallFrameInfo::KindName(kind), offset,
  2348           section_.c_str(), insn_offset);
  2351 }  // namespace dwarf2reader

mercurial