disassembler.cc 12 KB
Newer Older
1
// Copyright 2011 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#include "code-stubs.h"
31
#include "codegen-inl.h"
32
#include "debug.h"
33
#include "deoptimizer.h"
34 35 36 37 38 39
#include "disasm.h"
#include "disassembler.h"
#include "macro-assembler.h"
#include "serialize.h"
#include "string-stream.h"

40 41
namespace v8 {
namespace internal {
42 43 44 45 46 47

#ifdef ENABLE_DISASSEMBLER

void Disassembler::Dump(FILE* f, byte* begin, byte* end) {
  for (byte* pc = begin; pc < end; pc++) {
    if (f == NULL) {
48 49 50 51
      PrintF("%" V8PRIxPTR "  %4" V8PRIdPTR "  %02x\n",
             reinterpret_cast<intptr_t>(pc),
             pc - begin,
             *pc);
52
    } else {
53 54
      fprintf(f, "%" V8PRIxPTR "  %4" V8PRIdPTR "  %02x\n",
              reinterpret_cast<uintptr_t>(pc), pc - begin, *pc);
55 56 57 58 59 60 61 62 63
    }
  }
}


class V8NameConverter: public disasm::NameConverter {
 public:
  explicit V8NameConverter(Code* code) : code_(code) {}
  virtual const char* NameOfAddress(byte* pc) const;
64
  virtual const char* NameInCode(byte* addr) const;
65 66 67 68 69 70 71
  Code* code() const { return code_; }
 private:
  Code* code_;
};


const char* V8NameConverter::NameOfAddress(byte* pc) const {
72
  static v8::internal::EmbeddedVector<char, 128> buffer;
73 74 75

  const char* name = Builtins::Lookup(pc);
  if (name != NULL) {
76 77
    OS::SNPrintF(buffer, "%s  (%p)", name, pc);
    return buffer.start();
78 79 80
  }

  if (code_ != NULL) {
81
    int offs = static_cast<int>(pc - code_->instruction_start());
82 83
    // print as code offset, if it seems reasonable
    if (0 <= offs && offs < code_->instruction_size()) {
84 85
      OS::SNPrintF(buffer, "%d  (%p)", offs, pc);
      return buffer.start();
86 87 88 89 90 91 92
    }
  }

  return disasm::NameConverter::NameOfAddress(pc);
}


93 94 95 96 97 98 99
const char* V8NameConverter::NameInCode(byte* addr) const {
  // The V8NameConverter is used for well known code, so we can "safely"
  // dereference pointers in generated code.
  return (code_ != NULL) ? reinterpret_cast<const char*>(addr) : "";
}


100
static void DumpBuffer(FILE* f, char* buff) {
101 102 103 104 105
  if (f == NULL) {
    PrintF("%s", buff);
  } else {
    fprintf(f, "%s", buff);
  }
106 107
}

108
static const int kOutBufferSize = 2048 + String::kMaxShortPrintLength;
109 110 111 112 113 114 115 116 117 118
static const int kRelocInfoPosition = 57;

static int DecodeIt(FILE* f,
                    const V8NameConverter& converter,
                    byte* begin,
                    byte* end) {
  NoHandleAllocation ha;
  AssertNoAllocation no_alloc;
  ExternalReferenceEncoder ref_encoder;

119 120
  v8::internal::EmbeddedVector<char, 128> decode_buffer;
  v8::internal::EmbeddedVector<char, kOutBufferSize> out_buffer;
121 122 123 124 125 126 127 128
  byte* pc = begin;
  disasm::Disassembler d(converter);
  RelocIterator* it = NULL;
  if (converter.code() != NULL) {
    it = new RelocIterator(converter.code());
  } else {
    // No relocation information when printing code stubs.
  }
129
  int constants = -1;  // no constants being decoded at the start
130 131 132 133

  while (pc < end) {
    // First decode instruction so that we know its length.
    byte* prev_pc = pc;
134 135 136 137 138 139 140 141 142 143 144 145 146 147
    if (constants > 0) {
      OS::SNPrintF(decode_buffer,
                   "%08x       constant",
                   *reinterpret_cast<int32_t*>(pc));
      constants--;
      pc += 4;
    } else {
      int num_const = d.ConstantPoolSizeAt(pc);
      if (num_const >= 0) {
        OS::SNPrintF(decode_buffer,
                     "%08x       constant pool begin",
                     *reinterpret_cast<int32_t*>(pc));
        constants = num_const;
        pc += 4;
148
      } else if (it != NULL && !it->done() && it->rinfo()->pc() == pc &&
149
          it->rinfo()->rmode() == RelocInfo::INTERNAL_REFERENCE) {
150 151 152
        // raw pointer embedded in code stream, e.g., jump table
        byte* ptr = *reinterpret_cast<byte**>(pc);
        OS::SNPrintF(decode_buffer,
153 154
                     "%08" V8PRIxPTR "      jump table entry %4" V8PRIdPTR,
                     ptr,
155 156
                     ptr - begin);
        pc += 4;
157 158
      } else {
        decode_buffer[0] = '\0';
159
        pc += d.InstructionDecode(decode_buffer, pc);
160 161
      }
    }
162 163 164 165

    // Collect RelocInfo for this instruction (prev_pc .. pc-1)
    List<const char*> comments(4);
    List<byte*> pcs(1);
166
    List<RelocInfo::Mode> rmodes(1);
167 168 169
    List<intptr_t> datas(1);
    if (it != NULL) {
      while (!it->done() && it->rinfo()->pc() < pc) {
170
        if (RelocInfo::IsComment(it->rinfo()->rmode())) {
171 172 173 174 175 176 177 178 179 180 181 182
          // For comments just collect the text.
          comments.Add(reinterpret_cast<const char*>(it->rinfo()->data()));
        } else {
          // For other reloc info collect all data.
          pcs.Add(it->rinfo()->pc());
          rmodes.Add(it->rinfo()->rmode());
          datas.Add(it->rinfo()->data());
        }
        it->next();
      }
    }

183
    StringBuilder out(out_buffer.start(), out_buffer.length());
184 185 186

    // Comments.
    for (int i = 0; i < comments.length(); i++) {
187
      out.AddFormatted("                  %s\n", comments[i]);
188 189 190
    }

    // Write out comments, resets outp so that we can format the next line.
191 192
    DumpBuffer(f, out.Finalize());
    out.Reset();
193 194

    // Instruction address and instruction offset.
195
    out.AddFormatted("%p  %4d  ", prev_pc, prev_pc - begin);
196

197
    // Instruction.
198
    out.AddFormatted("%s", decode_buffer.start());
199 200 201 202 203 204 205 206 207

    // Print all the reloc info for this instruction which are not comments.
    for (int i = 0; i < pcs.length(); i++) {
      // Put together the reloc info
      RelocInfo relocinfo(pcs[i], rmodes[i], datas[i]);

      // Indent the printing of the reloc info.
      if (i == 0) {
        // The first reloc info is printed after the disassembled instruction.
208
        out.AddPadding(' ', kRelocInfoPosition - out.position());
209 210
      } else {
        // Additional reloc infos are printed on separate lines.
211 212
        out.AddFormatted("\n");
        out.AddPadding(' ', kRelocInfoPosition);
213 214
      }

215 216 217
      RelocInfo::Mode rmode = relocinfo.rmode();
      if (RelocInfo::IsPosition(rmode)) {
        if (RelocInfo::IsStatementPosition(rmode)) {
218 219 220 221
          out.AddFormatted("    ;; debug: statement %d", relocinfo.data());
        } else {
          out.AddFormatted("    ;; debug: position %d", relocinfo.data());
        }
222
      } else if (rmode == RelocInfo::EMBEDDED_OBJECT) {
223 224 225
        HeapStringAllocator allocator;
        StringStream accumulator(&allocator);
        relocinfo.target_object()->ShortPrint(&accumulator);
226
        SmartPointer<const char> obj_name = accumulator.ToCString();
227
        out.AddFormatted("    ;; object: %s", *obj_name);
228
      } else if (rmode == RelocInfo::EXTERNAL_REFERENCE) {
229 230
        const char* reference_name =
            ref_encoder.NameOfAddress(*relocinfo.target_reference_address());
231
        out.AddFormatted("    ;; external reference (%s)", reference_name);
232
      } else if (RelocInfo::IsCodeTarget(rmode)) {
233
        out.AddFormatted("    ;; code:");
234
        if (rmode == RelocInfo::CONSTRUCT_CALL) {
235 236
          out.AddFormatted(" constructor,");
        }
237
        Code* code = Code::GetCodeFromTargetAddress(relocinfo.target_address());
238 239
        Code::Kind kind = code->kind();
        if (code->is_inline_cache_stub()) {
240
          if (rmode == RelocInfo::CODE_TARGET_CONTEXT) {
241 242 243 244 245
            out.AddFormatted(" contextual,");
          }
          InlineCacheState ic_state = code->ic_state();
          out.AddFormatted(" %s, %s", Code::Kind2String(kind),
              Code::ICState2String(ic_state));
246 247 248 249
          if (ic_state == MONOMORPHIC) {
            PropertyType type = code->type();
            out.AddFormatted(", %s", Code::PropertyType2String(type));
          }
250 251 252
          if (code->ic_in_loop() == IN_LOOP) {
            out.AddFormatted(", in_loop");
          }
253
          if (kind == Code::CALL_IC || kind == Code::KEYED_CALL_IC) {
254 255 256 257 258 259 260 261 262 263 264
            out.AddFormatted(", argc = %d", code->arguments_count());
          }
        } else if (kind == Code::STUB) {
          // Reverse lookup required as the minor key cannot be retrieved
          // from the code object.
          Object* obj = Heap::code_stubs()->SlowReverseLookup(code);
          if (obj != Heap::undefined_value()) {
            ASSERT(obj->IsSmi());
            // Get the STUB key and extract major and minor key.
            uint32_t key = Smi::cast(obj)->value();
            uint32_t minor_key = CodeStub::MinorKeyFromKey(key);
265 266
            CodeStub::Major major_key = CodeStub::GetMajorKey(code);
            ASSERT(major_key == CodeStub::MajorKeyFromKey(key));
267 268
            out.AddFormatted(" %s, %s, ",
                             Code::Kind2String(kind),
269 270
                             CodeStub::MajorName(major_key, false));
            switch (major_key) {
271 272 273 274
              case CodeStub::CallFunction: {
                int argc =
                    CallFunctionStub::ExtractArgcFromMinorKey(minor_key);
                out.AddFormatted("argc = %d", argc);
275
                break;
276 277
              }
              default:
278
                out.AddFormatted("minor: %d", minor_key);
279 280
            }
          }
281 282
        } else {
          out.AddFormatted(" %s", Code::Kind2String(kind));
283
        }
284 285 286 287 288 289 290 291 292
      } else if (rmode == RelocInfo::RUNTIME_ENTRY) {
        // A runtime entry reloinfo might be a deoptimization bailout.
        Address addr = relocinfo.target_address();
        int id = Deoptimizer::GetDeoptimizationId(addr, Deoptimizer::EAGER);
        if (id == Deoptimizer::kNotDeoptimizationEntry) {
          out.AddFormatted("    ;; %s", RelocInfo::RelocModeName(rmode));
        } else {
          out.AddFormatted("    ;; deoptimization bailout %d", id);
        }
293 294
      } else {
        out.AddFormatted("    ;; %s", RelocInfo::RelocModeName(rmode));
295 296
      }
    }
297 298 299
    out.AddString("\n");
    DumpBuffer(f, out.Finalize());
    out.Reset();
300 301 302
  }

  delete it;
303
  return static_cast<int>(pc - begin);
304 305 306 307 308 309 310 311 312
}


int Disassembler::Decode(FILE* f, byte* begin, byte* end) {
  V8NameConverter defaultConverter(NULL);
  return DecodeIt(f, defaultConverter, begin, end);
}


313
// Called by Code::CodePrint.
314
void Disassembler::Decode(FILE* f, Code* code) {
315
  int decode_size = (code->kind() == Code::OPTIMIZED_FUNCTION)
316
      ? static_cast<int>(code->safepoint_table_offset())
317 318 319 320
      : code->instruction_size();
  // If there might be a stack check table, stop before reaching it.
  if (code->kind() == Code::FUNCTION) {
    decode_size =
321
        Min(decode_size, static_cast<int>(code->stack_check_table_offset()));
322 323 324 325
  }

  byte* begin = code->instruction_start();
  byte* end = begin + decode_size;
326 327 328
  V8NameConverter v8NameConverter(code);
  DecodeIt(f, v8NameConverter, begin, end);
}
329

330 331 332 333 334 335 336 337 338
#else  // ENABLE_DISASSEMBLER

void Disassembler::Dump(FILE* f, byte* begin, byte* end) {}
int Disassembler::Decode(FILE* f, byte* begin, byte* end) { return 0; }
void Disassembler::Decode(FILE* f, Code* code) {}

#endif  // ENABLE_DISASSEMBLER

} }  // namespace v8::internal