disassembler.cc 13.3 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.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
      PrintF(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
  Code* code() const { return code_; }
 private:
  Code* code_;
68 69

  EmbeddedVector<char, 128> v8_buffer_;
70 71 72 73
};


const char* V8NameConverter::NameOfAddress(byte* pc) const {
74
  const char* name = code_->GetIsolate()->builtins()->Lookup(pc);
75
  if (name != NULL) {
76 77
    OS::SNPrintF(v8_buffer_, "%s  (%p)", name, pc);
    return v8_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(v8_buffer_, "%d  (%p)", offs, pc);
      return v8_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, StringBuilder* out) {
101
  if (f == NULL) {
102
    PrintF("%s\n", out->Finalize());
103
  } else {
104
    PrintF(f, "%s\n", out->Finalize());
105
  }
106
  out->Reset();
107 108
}

109

110
static const int kOutBufferSize = 2048 + String::kMaxShortPrintLength;
111 112
static const int kRelocInfoPosition = 57;

113 114
static int DecodeIt(Isolate* isolate,
                    FILE* f,
115 116 117
                    const V8NameConverter& converter,
                    byte* begin,
                    byte* end) {
118 119
  SealHandleScope shs(isolate);
  DisallowHeapAllocation no_alloc;
120
  ExternalReferenceEncoder ref_encoder(isolate);
121
  Heap* heap = isolate->heap();
122

123 124
  v8::internal::EmbeddedVector<char, 128> decode_buffer;
  v8::internal::EmbeddedVector<char, kOutBufferSize> out_buffer;
125
  StringBuilder out(out_buffer.start(), out_buffer.length());
126 127 128 129 130 131 132 133
  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.
  }
134
  int constants = -1;  // no constants being decoded at the start
135 136 137 138

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

    // Collect RelocInfo for this instruction (prev_pc .. pc-1)
    List<const char*> comments(4);
    List<byte*> pcs(1);
171
    List<RelocInfo::Mode> rmodes(1);
172 173 174
    List<intptr_t> datas(1);
    if (it != NULL) {
      while (!it->done() && it->rinfo()->pc() < pc) {
175
        if (RelocInfo::IsComment(it->rinfo()->rmode())) {
176 177 178 179 180 181 182 183 184 185 186 187 188 189
          // 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();
      }
    }

    // Comments.
    for (int i = 0; i < comments.length(); i++) {
190 191
      out.AddFormatted("                  %s", comments[i]);
      DumpBuffer(f, &out);
192 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

    // 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
203
      RelocInfo relocinfo(pcs[i], rmodes[i], datas[i], NULL);
204 205 206 207

      // 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
        DumpBuffer(f, &out);
212
        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
        SmartArrayPointer<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
          if (ic_state == MONOMORPHIC) {
247 248
            Code::StubType type = code->type();
            out.AddFormatted(", %s", Code::StubType2String(type));
249
          }
250
          if (kind == Code::CALL_IC || kind == Code::KEYED_CALL_IC) {
251 252 253 254 255
            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.
256 257
          Object* obj = heap->code_stubs()->SlowReverseLookup(code);
          if (obj != heap->undefined_value()) {
258 259 260 261
            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);
262 263
            CodeStub::Major major_key = CodeStub::GetMajorKey(code);
            ASSERT(major_key == CodeStub::MajorKeyFromKey(key));
264 265
            out.AddFormatted(" %s, %s, ",
                             Code::Kind2String(kind),
266 267
                             CodeStub::MajorName(major_key, false));
            switch (major_key) {
268 269 270 271
              case CodeStub::CallFunction: {
                int argc =
                    CallFunctionStub::ExtractArgcFromMinorKey(minor_key);
                out.AddFormatted("argc = %d", argc);
272
                break;
273 274
              }
              default:
275
                out.AddFormatted("minor: %d", minor_key);
276 277
            }
          }
278 279
        } else {
          out.AddFormatted(" %s", Code::Kind2String(kind));
280
        }
281 282 283
        if (rmode == RelocInfo::CODE_TARGET_WITH_ID) {
          out.AddFormatted(" (id = %d)", static_cast<int>(relocinfo.data()));
        }
284
      } else if (RelocInfo::IsRuntimeEntry(rmode) &&
285
                 isolate->deoptimizer_data() != NULL) {
286 287
        // A runtime entry reloinfo might be a deoptimization bailout.
        Address addr = relocinfo.target_address();
288 289 290
        int id = Deoptimizer::GetDeoptimizationId(isolate,
                                                  addr,
                                                  Deoptimizer::EAGER);
291
        if (id == Deoptimizer::kNotDeoptimizationEntry) {
292 293 294
          id = Deoptimizer::GetDeoptimizationId(isolate,
                                                addr,
                                                Deoptimizer::LAZY);
295
          if (id == Deoptimizer::kNotDeoptimizationEntry) {
296 297 298 299 300 301 302 303
            id = Deoptimizer::GetDeoptimizationId(isolate,
                                                  addr,
                                                  Deoptimizer::SOFT);
            if (id == Deoptimizer::kNotDeoptimizationEntry) {
              out.AddFormatted("    ;; %s", RelocInfo::RelocModeName(rmode));
            } else {
              out.AddFormatted("    ;; soft deoptimization bailout %d", id);
            }
304 305 306
          } else {
            out.AddFormatted("    ;; lazy deoptimization bailout %d", id);
          }
307 308 309
        } else {
          out.AddFormatted("    ;; deoptimization bailout %d", id);
        }
310 311
      } else {
        out.AddFormatted("    ;; %s", RelocInfo::RelocModeName(rmode));
312 313
      }
    }
314
    DumpBuffer(f, &out);
315 316
  }

317 318 319 320 321 322 323 324 325 326 327
  // Emit comments following the last instruction (if any).
  if (it != NULL) {
    for ( ; !it->done(); it->next()) {
      if (RelocInfo::IsComment(it->rinfo()->rmode())) {
        out.AddFormatted("                  %s",
                         reinterpret_cast<const char*>(it->rinfo()->data()));
        DumpBuffer(f, &out);
      }
    }
  }

328
  delete it;
329
  return static_cast<int>(pc - begin);
330 331 332
}


333
int Disassembler::Decode(Isolate* isolate, FILE* f, byte* begin, byte* end) {
334
  V8NameConverter defaultConverter(NULL);
335
  return DecodeIt(isolate, f, defaultConverter, begin, end);
336 337 338
}


339
// Called by Code::CodePrint.
340
void Disassembler::Decode(FILE* f, Code* code) {
341
  Isolate* isolate = code->GetIsolate();
342
  int decode_size = code->is_crankshafted()
343
      ? static_cast<int>(code->safepoint_table_offset())
344
      : code->instruction_size();
345
  // If there might be a back edge table, stop before reaching it.
346 347
  if (code->kind() == Code::FUNCTION) {
    decode_size =
348
        Min(decode_size, static_cast<int>(code->back_edge_table_offset()));
349 350 351 352
  }

  byte* begin = code->instruction_start();
  byte* end = begin + decode_size;
353
  V8NameConverter v8NameConverter(code);
354
  DecodeIt(isolate, f, v8NameConverter, begin, end);
355
}
356

357 358 359
#else  // ENABLE_DISASSEMBLER

void Disassembler::Dump(FILE* f, byte* begin, byte* end) {}
360 361 362
int Disassembler::Decode(Isolate* isolate, FILE* f, byte* begin, byte* end) {
  return 0;
}
363 364


365 366 367 368 369
void Disassembler::Decode(FILE* f, Code* code) {}

#endif  // ENABLE_DISASSEMBLER

} }  // namespace v8::internal