1 // Copyright 2010 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include "src/base/bits.h"
8 #include "src/base/platform/platform.h"
9 #include "src/bootstrapper.h"
10 #include "src/compiler.h"
11 #include "src/frames-inl.h"
12 #include "src/frames.h"
13 #include "src/gdb-jit.h"
14 #include "src/global-handles.h"
15 #include "src/messages.h"
16 #include "src/objects.h"
17 #include "src/ostreams.h"
18 #include "src/snapshot/natives.h"
22 namespace GDBJITInterface {
24 #ifdef ENABLE_GDB_JIT_INTERFACE
30 typedef MachO DebugObject;
31 typedef MachOSection DebugSection;
36 typedef ELF DebugObject;
37 typedef ELFSection DebugSection;
40 class Writer BASE_EMBEDDED {
42 explicit Writer(DebugObject* debug_object)
43 : debug_object_(debug_object),
46 buffer_(reinterpret_cast<byte*>(malloc(capacity_))) {
53 uintptr_t position() const {
60 Slot(Writer* w, uintptr_t offset) : w_(w), offset_(offset) { }
63 return w_->RawSlotAt<T>(offset_);
66 void set(const T& value) {
67 *w_->RawSlotAt<T>(offset_) = value;
71 return Slot<T>(w_, offset_ + sizeof(T) * i);
80 void Write(const T& val) {
81 Ensure(position_ + sizeof(T));
82 *RawSlotAt<T>(position_) = val;
83 position_ += sizeof(T);
87 Slot<T> SlotAt(uintptr_t offset) {
88 Ensure(offset + sizeof(T));
89 return Slot<T>(this, offset);
93 Slot<T> CreateSlotHere() {
94 return CreateSlotsHere<T>(1);
98 Slot<T> CreateSlotsHere(uint32_t count) {
99 uintptr_t slot_position = position_;
100 position_ += sizeof(T) * count;
102 return SlotAt<T>(slot_position);
105 void Ensure(uintptr_t pos) {
106 if (capacity_ < pos) {
107 while (capacity_ < pos) capacity_ *= 2;
108 buffer_ = reinterpret_cast<byte*>(realloc(buffer_, capacity_));
112 DebugObject* debug_object() { return debug_object_; }
114 byte* buffer() { return buffer_; }
116 void Align(uintptr_t align) {
117 uintptr_t delta = position_ % align;
118 if (delta == 0) return;
119 uintptr_t padding = align - delta;
120 Ensure(position_ += padding);
121 DCHECK((position_ % align) == 0);
124 void WriteULEB128(uintptr_t value) {
126 uint8_t byte = value & 0x7F;
128 if (value != 0) byte |= 0x80;
129 Write<uint8_t>(byte);
130 } while (value != 0);
133 void WriteSLEB128(intptr_t value) {
136 int8_t byte = value & 0x7F;
137 bool byte_sign = byte & 0x40;
140 if ((value == 0 && !byte_sign) || (value == -1 && byte_sign)) {
150 void WriteString(const char* str) {
157 template<typename T> friend class Slot;
160 T* RawSlotAt(uintptr_t offset) {
161 DCHECK(offset < capacity_ && offset + sizeof(T) <= capacity_);
162 return reinterpret_cast<T*>(&buffer_[offset]);
165 DebugObject* debug_object_;
171 class ELFStringTable;
173 template<typename THeader>
174 class DebugSectionBase : public ZoneObject {
176 virtual ~DebugSectionBase() { }
178 virtual void WriteBody(Writer::Slot<THeader> header, Writer* writer) {
179 uintptr_t start = writer->position();
180 if (WriteBodyInternal(writer)) {
181 uintptr_t end = writer->position();
182 header->offset = start;
183 #if defined(__MACH_O)
186 header->size = end - start;
190 virtual bool WriteBodyInternal(Writer* writer) {
194 typedef THeader Header;
198 struct MachOSectionHeader {
201 #if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
218 class MachOSection : public DebugSectionBase<MachOSectionHeader> {
222 S_ATTR_COALESCED = 0xbu,
223 S_ATTR_SOME_INSTRUCTIONS = 0x400u,
224 S_ATTR_DEBUG = 0x02000000u,
225 S_ATTR_PURE_INSTRUCTIONS = 0x80000000u
228 MachOSection(const char* name, const char* segment, uint32_t align,
230 : name_(name), segment_(segment), align_(align), flags_(flags) {
232 DCHECK(base::bits::IsPowerOfTwo32(align));
233 align_ = WhichPowerOf2(align_);
237 virtual ~MachOSection() { }
239 virtual void PopulateHeader(Writer::Slot<Header> header) {
243 header->align = align_;
246 header->flags = flags_;
247 header->reserved1 = 0;
248 header->reserved2 = 0;
249 memset(header->sectname, 0, sizeof(header->sectname));
250 memset(header->segname, 0, sizeof(header->segname));
251 DCHECK(strlen(name_) < sizeof(header->sectname));
252 DCHECK(strlen(segment_) < sizeof(header->segname));
253 strncpy(header->sectname, name_, sizeof(header->sectname));
254 strncpy(header->segname, segment_, sizeof(header->segname));
259 const char* segment_;
265 struct ELFSectionHeader {
275 uintptr_t entry_size;
280 class ELFSection : public DebugSectionBase<ELFSectionHeader> {
295 TYPE_LOPROC = 0x70000000,
296 TYPE_X86_64_UNWIND = 0x70000001,
297 TYPE_HIPROC = 0x7fffffff,
298 TYPE_LOUSER = 0x80000000,
299 TYPE_HIUSER = 0xffffffff
308 enum SpecialIndexes {
309 INDEX_ABSOLUTE = 0xfff1
312 ELFSection(const char* name, Type type, uintptr_t align)
313 : name_(name), type_(type), align_(align) { }
315 virtual ~ELFSection() { }
317 void PopulateHeader(Writer::Slot<Header> header, ELFStringTable* strtab);
319 virtual void WriteBody(Writer::Slot<Header> header, Writer* w) {
320 uintptr_t start = w->position();
321 if (WriteBodyInternal(w)) {
322 uintptr_t end = w->position();
323 header->offset = start;
324 header->size = end - start;
328 virtual bool WriteBodyInternal(Writer* w) {
332 uint16_t index() const { return index_; }
333 void set_index(uint16_t index) { index_ = index; }
336 virtual void PopulateHeader(Writer::Slot<Header> header) {
343 header->entry_size = 0;
352 #endif // defined(__ELF)
355 #if defined(__MACH_O)
356 class MachOTextSection : public MachOSection {
358 MachOTextSection(uintptr_t align,
361 : MachOSection("__text",
364 MachOSection::S_REGULAR |
365 MachOSection::S_ATTR_SOME_INSTRUCTIONS |
366 MachOSection::S_ATTR_PURE_INSTRUCTIONS),
371 virtual void PopulateHeader(Writer::Slot<Header> header) {
372 MachOSection::PopulateHeader(header);
373 header->addr = addr_;
374 header->size = size_;
381 #endif // defined(__MACH_O)
385 class FullHeaderELFSection : public ELFSection {
387 FullHeaderELFSection(const char* name,
394 : ELFSection(name, type, align),
401 virtual void PopulateHeader(Writer::Slot<Header> header) {
402 ELFSection::PopulateHeader(header);
403 header->address = addr_;
404 header->offset = offset_;
405 header->size = size_;
406 header->flags = flags_;
417 class ELFStringTable : public ELFSection {
419 explicit ELFStringTable(const char* name)
420 : ELFSection(name, TYPE_STRTAB, 1), writer_(NULL), offset_(0), size_(0) {
423 uintptr_t Add(const char* str) {
424 if (*str == '\0') return 0;
426 uintptr_t offset = size_;
431 void AttachWriter(Writer* w) {
433 offset_ = writer_->position();
435 // First entry in the string table should be an empty string.
439 void DetachWriter() {
443 virtual void WriteBody(Writer::Slot<Header> header, Writer* w) {
444 DCHECK(writer_ == NULL);
445 header->offset = offset_;
446 header->size = size_;
450 void WriteString(const char* str) {
451 uintptr_t written = 0;
453 writer_->Write(*str);
466 void ELFSection::PopulateHeader(Writer::Slot<ELFSection::Header> header,
467 ELFStringTable* strtab) {
468 header->name = strtab->Add(name_);
469 header->type = type_;
470 header->alignment = align_;
471 PopulateHeader(header);
473 #endif // defined(__ELF)
476 #if defined(__MACH_O)
477 class MachO BASE_EMBEDDED {
479 explicit MachO(Zone* zone) : zone_(zone), sections_(6, zone) { }
481 uint32_t AddSection(MachOSection* section) {
482 sections_.Add(section, zone_);
483 return sections_.length() - 1;
486 void Write(Writer* w, uintptr_t code_start, uintptr_t code_size) {
487 Writer::Slot<MachOHeader> header = WriteHeader(w);
488 uintptr_t load_command_start = w->position();
489 Writer::Slot<MachOSegmentCommand> cmd = WriteSegmentCommand(w,
492 WriteSections(w, cmd, header, load_command_start);
504 #if V8_TARGET_ARCH_X64
509 struct MachOSegmentCommand {
513 #if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
530 enum MachOLoadCommandCmd {
531 LC_SEGMENT_32 = 0x00000001u,
532 LC_SEGMENT_64 = 0x00000019u
536 Writer::Slot<MachOHeader> WriteHeader(Writer* w) {
537 DCHECK(w->position() == 0);
538 Writer::Slot<MachOHeader> header = w->CreateSlotHere<MachOHeader>();
539 #if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
540 header->magic = 0xFEEDFACEu;
541 header->cputype = 7; // i386
542 header->cpusubtype = 3; // CPU_SUBTYPE_I386_ALL
543 #elif V8_TARGET_ARCH_X64
544 header->magic = 0xFEEDFACFu;
545 header->cputype = 7 | 0x01000000; // i386 | 64-bit ABI
546 header->cpusubtype = 3; // CPU_SUBTYPE_I386_ALL
547 header->reserved = 0;
549 #error Unsupported target architecture.
551 header->filetype = 0x1; // MH_OBJECT
553 header->sizeofcmds = 0;
559 Writer::Slot<MachOSegmentCommand> WriteSegmentCommand(Writer* w,
560 uintptr_t code_start,
561 uintptr_t code_size) {
562 Writer::Slot<MachOSegmentCommand> cmd =
563 w->CreateSlotHere<MachOSegmentCommand>();
564 #if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
565 cmd->cmd = LC_SEGMENT_32;
567 cmd->cmd = LC_SEGMENT_64;
569 cmd->vmaddr = code_start;
570 cmd->vmsize = code_size;
576 cmd->nsects = sections_.length();
577 memset(cmd->segname, 0, 16);
578 cmd->cmdsize = sizeof(MachOSegmentCommand) + sizeof(MachOSection::Header) *
584 void WriteSections(Writer* w,
585 Writer::Slot<MachOSegmentCommand> cmd,
586 Writer::Slot<MachOHeader> header,
587 uintptr_t load_command_start) {
588 Writer::Slot<MachOSection::Header> headers =
589 w->CreateSlotsHere<MachOSection::Header>(sections_.length());
590 cmd->fileoff = w->position();
591 header->sizeofcmds = w->position() - load_command_start;
592 for (int section = 0; section < sections_.length(); ++section) {
593 sections_[section]->PopulateHeader(headers.at(section));
594 sections_[section]->WriteBody(headers.at(section), w);
596 cmd->filesize = w->position() - (uintptr_t)cmd->fileoff;
600 ZoneList<MachOSection*> sections_;
602 #endif // defined(__MACH_O)
606 class ELF BASE_EMBEDDED {
608 explicit ELF(Zone* zone) : zone_(zone), sections_(6, zone) {
609 sections_.Add(new(zone) ELFSection("", ELFSection::TYPE_NULL, 0), zone);
610 sections_.Add(new(zone) ELFStringTable(".shstrtab"), zone);
613 void Write(Writer* w) {
615 WriteSectionTable(w);
619 ELFSection* SectionAt(uint32_t index) {
620 return sections_[index];
623 uint32_t AddSection(ELFSection* section) {
624 sections_.Add(section, zone_);
625 section->set_index(sections_.length() - 1);
626 return sections_.length() - 1;
636 uintptr_t pht_offset;
637 uintptr_t sht_offset;
639 uint16_t header_size;
640 uint16_t pht_entry_size;
641 uint16_t pht_entry_num;
642 uint16_t sht_entry_size;
643 uint16_t sht_entry_num;
644 uint16_t sht_strtab_index;
648 void WriteHeader(Writer* w) {
649 DCHECK(w->position() == 0);
650 Writer::Slot<ELFHeader> header = w->CreateSlotHere<ELFHeader>();
651 #if (V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_X87 || \
652 (V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_32_BIT))
653 const uint8_t ident[16] =
654 { 0x7f, 'E', 'L', 'F', 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
655 #elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT
656 const uint8_t ident[16] =
657 { 0x7f, 'E', 'L', 'F', 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
659 #error Unsupported target architecture.
661 memcpy(header->ident, ident, 16);
663 #if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
665 #elif V8_TARGET_ARCH_X64
666 // Processor identification value for x64 is 62 as defined in
667 // System V ABI, AMD64 Supplement
668 // http://www.x86-64.org/documentation/abi.pdf
669 header->machine = 62;
670 #elif V8_TARGET_ARCH_ARM
671 // Set to EM_ARM, defined as 40, in "ARM ELF File Format" at
672 // infocenter.arm.com/help/topic/com.arm.doc.dui0101a/DUI0101A_Elf.pdf
673 header->machine = 40;
675 #error Unsupported target architecture.
679 header->pht_offset = 0;
680 header->sht_offset = sizeof(ELFHeader); // Section table follows header.
682 header->header_size = sizeof(ELFHeader);
683 header->pht_entry_size = 0;
684 header->pht_entry_num = 0;
685 header->sht_entry_size = sizeof(ELFSection::Header);
686 header->sht_entry_num = sections_.length();
687 header->sht_strtab_index = 1;
690 void WriteSectionTable(Writer* w) {
691 // Section headers table immediately follows file header.
692 DCHECK(w->position() == sizeof(ELFHeader));
694 Writer::Slot<ELFSection::Header> headers =
695 w->CreateSlotsHere<ELFSection::Header>(sections_.length());
697 // String table for section table is the first section.
698 ELFStringTable* strtab = static_cast<ELFStringTable*>(SectionAt(1));
699 strtab->AttachWriter(w);
700 for (int i = 0, length = sections_.length();
703 sections_[i]->PopulateHeader(headers.at(i), strtab);
705 strtab->DetachWriter();
708 int SectionHeaderPosition(uint32_t section_index) {
709 return sizeof(ELFHeader) + sizeof(ELFSection::Header) * section_index;
712 void WriteSections(Writer* w) {
713 Writer::Slot<ELFSection::Header> headers =
714 w->SlotAt<ELFSection::Header>(sizeof(ELFHeader));
716 for (int i = 0, length = sections_.length();
719 sections_[i]->WriteBody(headers.at(i), w);
724 ZoneList<ELFSection*> sections_;
728 class ELFSymbol BASE_EMBEDDED {
748 ELFSymbol(const char* name,
757 info((binding << 4) | type),
762 Binding binding() const {
763 return static_cast<Binding>(info >> 4);
765 #if (V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_X87 || \
766 (V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_32_BIT))
767 struct SerializedLayout {
768 SerializedLayout(uint32_t name,
777 info((binding << 4) | type),
789 #elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT
790 struct SerializedLayout {
791 SerializedLayout(uint32_t name,
798 info((binding << 4) | type),
814 void Write(Writer::Slot<SerializedLayout> s, ELFStringTable* t) {
815 // Convert symbol names from strings to indexes in the string table.
816 s->name = t->Add(name);
821 s->section = section;
834 class ELFSymbolTable : public ELFSection {
836 ELFSymbolTable(const char* name, Zone* zone)
837 : ELFSection(name, TYPE_SYMTAB, sizeof(uintptr_t)),
842 virtual void WriteBody(Writer::Slot<Header> header, Writer* w) {
843 w->Align(header->alignment);
844 int total_symbols = locals_.length() + globals_.length() + 1;
845 header->offset = w->position();
847 Writer::Slot<ELFSymbol::SerializedLayout> symbols =
848 w->CreateSlotsHere<ELFSymbol::SerializedLayout>(total_symbols);
850 header->size = w->position() - header->offset;
852 // String table for this symbol table should follow it in the section table.
853 ELFStringTable* strtab =
854 static_cast<ELFStringTable*>(w->debug_object()->SectionAt(index() + 1));
855 strtab->AttachWriter(w);
856 symbols.at(0).set(ELFSymbol::SerializedLayout(0,
859 ELFSymbol::BIND_LOCAL,
860 ELFSymbol::TYPE_NOTYPE,
862 WriteSymbolsList(&locals_, symbols.at(1), strtab);
863 WriteSymbolsList(&globals_, symbols.at(locals_.length() + 1), strtab);
864 strtab->DetachWriter();
867 void Add(const ELFSymbol& symbol, Zone* zone) {
868 if (symbol.binding() == ELFSymbol::BIND_LOCAL) {
869 locals_.Add(symbol, zone);
871 globals_.Add(symbol, zone);
876 virtual void PopulateHeader(Writer::Slot<Header> header) {
877 ELFSection::PopulateHeader(header);
878 // We are assuming that string table will follow symbol table.
879 header->link = index() + 1;
880 header->info = locals_.length() + 1;
881 header->entry_size = sizeof(ELFSymbol::SerializedLayout);
885 void WriteSymbolsList(const ZoneList<ELFSymbol>* src,
886 Writer::Slot<ELFSymbol::SerializedLayout> dst,
887 ELFStringTable* strtab) {
888 for (int i = 0, len = src->length();
891 src->at(i).Write(dst.at(i), strtab);
895 ZoneList<ELFSymbol> locals_;
896 ZoneList<ELFSymbol> globals_;
898 #endif // defined(__ELF)
901 class LineInfo : public Malloced {
903 LineInfo() : pc_info_(10) {}
905 void SetPosition(intptr_t pc, int pos, bool is_statement) {
906 AddPCInfo(PCInfo(pc, pos, is_statement));
910 PCInfo(intptr_t pc, int pos, bool is_statement)
911 : pc_(pc), pos_(pos), is_statement_(is_statement) {}
918 List<PCInfo>* pc_info() { return &pc_info_; }
921 void AddPCInfo(const PCInfo& pc_info) { pc_info_.Add(pc_info); }
923 List<PCInfo> pc_info_;
927 class CodeDescription BASE_EMBEDDED {
929 #if V8_TARGET_ARCH_X64
938 CodeDescription(const char* name, Code* code, SharedFunctionInfo* shared,
940 : name_(name), code_(code), shared_info_(shared), lineinfo_(lineinfo) {}
942 const char* name() const {
946 LineInfo* lineinfo() const { return lineinfo_; }
948 bool is_function() const {
949 Code::Kind kind = code_->kind();
950 return kind == Code::FUNCTION || kind == Code::OPTIMIZED_FUNCTION;
953 bool has_scope_info() const { return shared_info_ != NULL; }
955 ScopeInfo* scope_info() const {
956 DCHECK(has_scope_info());
957 return shared_info_->scope_info();
960 uintptr_t CodeStart() const {
961 return reinterpret_cast<uintptr_t>(code_->instruction_start());
964 uintptr_t CodeEnd() const {
965 return reinterpret_cast<uintptr_t>(code_->instruction_end());
968 uintptr_t CodeSize() const {
969 return CodeEnd() - CodeStart();
973 return shared_info_ != NULL && shared_info_->script()->IsScript();
976 Script* script() { return Script::cast(shared_info_->script()); }
978 bool IsLineInfoAvailable() {
979 return has_script() && script()->source()->IsString() &&
980 script()->HasValidSource() && script()->name()->IsString() &&
984 #if V8_TARGET_ARCH_X64
985 uintptr_t GetStackStateStartAddress(StackState state) const {
986 DCHECK(state < STACK_STATE_MAX);
987 return stack_state_start_addresses_[state];
990 void SetStackStateStartAddress(StackState state, uintptr_t addr) {
991 DCHECK(state < STACK_STATE_MAX);
992 stack_state_start_addresses_[state] = addr;
996 SmartArrayPointer<char> GetFilename() {
997 return String::cast(script()->name())->ToCString();
1000 int GetScriptLineNumber(int pos) { return script()->GetLineNumber(pos) + 1; }
1006 SharedFunctionInfo* shared_info_;
1007 LineInfo* lineinfo_;
1008 #if V8_TARGET_ARCH_X64
1009 uintptr_t stack_state_start_addresses_[STACK_STATE_MAX];
1014 static void CreateSymbolsTable(CodeDescription* desc,
1017 int text_section_index) {
1018 ELFSymbolTable* symtab = new(zone) ELFSymbolTable(".symtab", zone);
1019 ELFStringTable* strtab = new(zone) ELFStringTable(".strtab");
1021 // Symbol table should be followed by the linked string table.
1022 elf->AddSection(symtab);
1023 elf->AddSection(strtab);
1025 symtab->Add(ELFSymbol("V8 Code",
1028 ELFSymbol::BIND_LOCAL,
1029 ELFSymbol::TYPE_FILE,
1030 ELFSection::INDEX_ABSOLUTE),
1033 symtab->Add(ELFSymbol(desc->name(),
1036 ELFSymbol::BIND_GLOBAL,
1037 ELFSymbol::TYPE_FUNC,
1038 text_section_index),
1041 #endif // defined(__ELF)
1044 class DebugInfoSection : public DebugSection {
1046 explicit DebugInfoSection(CodeDescription* desc)
1048 : ELFSection(".debug_info", TYPE_PROGBITS, 1),
1050 : MachOSection("__debug_info",
1053 MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
1058 enum DWARF2LocationOp {
1067 DW_OP_fbreg = 0x91 // 1 param: SLEB128 offset
1070 enum DWARF2Encoding {
1071 DW_ATE_ADDRESS = 0x1,
1075 bool WriteBodyInternal(Writer* w) {
1076 uintptr_t cu_start = w->position();
1077 Writer::Slot<uint32_t> size = w->CreateSlotHere<uint32_t>();
1078 uintptr_t start = w->position();
1079 w->Write<uint16_t>(2); // DWARF version.
1080 w->Write<uint32_t>(0); // Abbreviation table offset.
1081 w->Write<uint8_t>(sizeof(intptr_t));
1083 w->WriteULEB128(1); // Abbreviation code.
1084 w->WriteString(desc_->GetFilename().get());
1085 w->Write<intptr_t>(desc_->CodeStart());
1086 w->Write<intptr_t>(desc_->CodeStart() + desc_->CodeSize());
1087 w->Write<uint32_t>(0);
1089 uint32_t ty_offset = static_cast<uint32_t>(w->position() - cu_start);
1091 w->Write<uint8_t>(kPointerSize);
1092 w->WriteString("v8value");
1094 if (desc_->has_scope_info()) {
1095 ScopeInfo* scope = desc_->scope_info();
1097 w->WriteString(desc_->name());
1098 w->Write<intptr_t>(desc_->CodeStart());
1099 w->Write<intptr_t>(desc_->CodeStart() + desc_->CodeSize());
1100 Writer::Slot<uint32_t> fb_block_size = w->CreateSlotHere<uint32_t>();
1101 uintptr_t fb_block_start = w->position();
1102 #if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
1103 w->Write<uint8_t>(DW_OP_reg5); // The frame pointer's here on ia32
1104 #elif V8_TARGET_ARCH_X64
1105 w->Write<uint8_t>(DW_OP_reg6); // and here on x64.
1106 #elif V8_TARGET_ARCH_ARM
1108 #elif V8_TARGET_ARCH_MIPS
1110 #elif V8_TARGET_ARCH_MIPS64
1113 #error Unsupported target architecture.
1115 fb_block_size.set(static_cast<uint32_t>(w->position() - fb_block_start));
1117 int params = scope->ParameterCount();
1118 int slots = scope->StackLocalCount();
1119 int context_slots = scope->ContextLocalCount();
1120 // The real slot ID is internal_slots + context_slot_id.
1121 int internal_slots = Context::MIN_CONTEXT_SLOTS;
1122 int locals = scope->StackLocalCount();
1123 int current_abbreviation = 4;
1125 for (int param = 0; param < params; ++param) {
1126 w->WriteULEB128(current_abbreviation++);
1128 scope->ParameterName(param)->ToCString(DISALLOW_NULLS).get());
1129 w->Write<uint32_t>(ty_offset);
1130 Writer::Slot<uint32_t> block_size = w->CreateSlotHere<uint32_t>();
1131 uintptr_t block_start = w->position();
1132 w->Write<uint8_t>(DW_OP_fbreg);
1134 JavaScriptFrameConstants::kLastParameterOffset +
1135 kPointerSize * (params - param - 1));
1136 block_size.set(static_cast<uint32_t>(w->position() - block_start));
1139 EmbeddedVector<char, 256> buffer;
1140 StringBuilder builder(buffer.start(), buffer.length());
1142 for (int slot = 0; slot < slots; ++slot) {
1143 w->WriteULEB128(current_abbreviation++);
1145 builder.AddFormatted("slot%d", slot);
1146 w->WriteString(builder.Finalize());
1149 // See contexts.h for more information.
1150 DCHECK(Context::MIN_CONTEXT_SLOTS == 4);
1151 DCHECK(Context::CLOSURE_INDEX == 0);
1152 DCHECK(Context::PREVIOUS_INDEX == 1);
1153 DCHECK(Context::EXTENSION_INDEX == 2);
1154 DCHECK(Context::GLOBAL_OBJECT_INDEX == 3);
1155 w->WriteULEB128(current_abbreviation++);
1156 w->WriteString(".closure");
1157 w->WriteULEB128(current_abbreviation++);
1158 w->WriteString(".previous");
1159 w->WriteULEB128(current_abbreviation++);
1160 w->WriteString(".extension");
1161 w->WriteULEB128(current_abbreviation++);
1162 w->WriteString(".global");
1164 for (int context_slot = 0;
1165 context_slot < context_slots;
1167 w->WriteULEB128(current_abbreviation++);
1169 builder.AddFormatted("context_slot%d", context_slot + internal_slots);
1170 w->WriteString(builder.Finalize());
1173 for (int local = 0; local < locals; ++local) {
1174 w->WriteULEB128(current_abbreviation++);
1176 scope->StackLocalName(local)->ToCString(DISALLOW_NULLS).get());
1177 w->Write<uint32_t>(ty_offset);
1178 Writer::Slot<uint32_t> block_size = w->CreateSlotHere<uint32_t>();
1179 uintptr_t block_start = w->position();
1180 w->Write<uint8_t>(DW_OP_fbreg);
1182 JavaScriptFrameConstants::kLocal0Offset -
1183 kPointerSize * local);
1184 block_size.set(static_cast<uint32_t>(w->position() - block_start));
1188 w->WriteULEB128(current_abbreviation++);
1189 w->WriteString("__function");
1190 w->Write<uint32_t>(ty_offset);
1191 Writer::Slot<uint32_t> block_size = w->CreateSlotHere<uint32_t>();
1192 uintptr_t block_start = w->position();
1193 w->Write<uint8_t>(DW_OP_fbreg);
1194 w->WriteSLEB128(JavaScriptFrameConstants::kFunctionOffset);
1195 block_size.set(static_cast<uint32_t>(w->position() - block_start));
1199 w->WriteULEB128(current_abbreviation++);
1200 w->WriteString("__context");
1201 w->Write<uint32_t>(ty_offset);
1202 Writer::Slot<uint32_t> block_size = w->CreateSlotHere<uint32_t>();
1203 uintptr_t block_start = w->position();
1204 w->Write<uint8_t>(DW_OP_fbreg);
1205 w->WriteSLEB128(StandardFrameConstants::kContextOffset);
1206 block_size.set(static_cast<uint32_t>(w->position() - block_start));
1209 w->WriteULEB128(0); // Terminate the sub program.
1212 w->WriteULEB128(0); // Terminate the compile unit.
1213 size.set(static_cast<uint32_t>(w->position() - start));
1218 CodeDescription* desc_;
1222 class DebugAbbrevSection : public DebugSection {
1224 explicit DebugAbbrevSection(CodeDescription* desc)
1226 : ELFSection(".debug_abbrev", TYPE_PROGBITS, 1),
1228 : MachOSection("__debug_abbrev",
1231 MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
1235 // DWARF2 standard, figure 14.
1237 DW_TAG_FORMAL_PARAMETER = 0x05,
1238 DW_TAG_POINTER_TYPE = 0xf,
1239 DW_TAG_COMPILE_UNIT = 0x11,
1240 DW_TAG_STRUCTURE_TYPE = 0x13,
1241 DW_TAG_BASE_TYPE = 0x24,
1242 DW_TAG_SUBPROGRAM = 0x2e,
1243 DW_TAG_VARIABLE = 0x34
1246 // DWARF2 standard, figure 16.
1247 enum DWARF2ChildrenDetermination {
1252 // DWARF standard, figure 17.
1253 enum DWARF2Attribute {
1254 DW_AT_LOCATION = 0x2,
1256 DW_AT_BYTE_SIZE = 0xb,
1257 DW_AT_STMT_LIST = 0x10,
1258 DW_AT_LOW_PC = 0x11,
1259 DW_AT_HIGH_PC = 0x12,
1260 DW_AT_ENCODING = 0x3e,
1261 DW_AT_FRAME_BASE = 0x40,
1265 // DWARF2 standard, figure 19.
1266 enum DWARF2AttributeForm {
1268 DW_FORM_BLOCK4 = 0x4,
1269 DW_FORM_STRING = 0x8,
1270 DW_FORM_DATA4 = 0x6,
1271 DW_FORM_BLOCK = 0x9,
1272 DW_FORM_DATA1 = 0xb,
1277 void WriteVariableAbbreviation(Writer* w,
1278 int abbreviation_code,
1280 bool is_parameter) {
1281 w->WriteULEB128(abbreviation_code);
1282 w->WriteULEB128(is_parameter ? DW_TAG_FORMAL_PARAMETER : DW_TAG_VARIABLE);
1283 w->Write<uint8_t>(DW_CHILDREN_NO);
1284 w->WriteULEB128(DW_AT_NAME);
1285 w->WriteULEB128(DW_FORM_STRING);
1287 w->WriteULEB128(DW_AT_TYPE);
1288 w->WriteULEB128(DW_FORM_REF4);
1289 w->WriteULEB128(DW_AT_LOCATION);
1290 w->WriteULEB128(DW_FORM_BLOCK4);
1296 bool WriteBodyInternal(Writer* w) {
1297 int current_abbreviation = 1;
1298 bool extra_info = desc_->has_scope_info();
1299 DCHECK(desc_->IsLineInfoAvailable());
1300 w->WriteULEB128(current_abbreviation++);
1301 w->WriteULEB128(DW_TAG_COMPILE_UNIT);
1302 w->Write<uint8_t>(extra_info ? DW_CHILDREN_YES : DW_CHILDREN_NO);
1303 w->WriteULEB128(DW_AT_NAME);
1304 w->WriteULEB128(DW_FORM_STRING);
1305 w->WriteULEB128(DW_AT_LOW_PC);
1306 w->WriteULEB128(DW_FORM_ADDR);
1307 w->WriteULEB128(DW_AT_HIGH_PC);
1308 w->WriteULEB128(DW_FORM_ADDR);
1309 w->WriteULEB128(DW_AT_STMT_LIST);
1310 w->WriteULEB128(DW_FORM_DATA4);
1315 ScopeInfo* scope = desc_->scope_info();
1316 int params = scope->ParameterCount();
1317 int slots = scope->StackLocalCount();
1318 int context_slots = scope->ContextLocalCount();
1319 // The real slot ID is internal_slots + context_slot_id.
1320 int internal_slots = Context::MIN_CONTEXT_SLOTS;
1321 int locals = scope->StackLocalCount();
1322 // Total children is params + slots + context_slots + internal_slots +
1323 // locals + 2 (__function and __context).
1325 // The extra duplication below seems to be necessary to keep
1326 // gdb from getting upset on OSX.
1327 w->WriteULEB128(current_abbreviation++); // Abbreviation code.
1328 w->WriteULEB128(DW_TAG_SUBPROGRAM);
1329 w->Write<uint8_t>(DW_CHILDREN_YES);
1330 w->WriteULEB128(DW_AT_NAME);
1331 w->WriteULEB128(DW_FORM_STRING);
1332 w->WriteULEB128(DW_AT_LOW_PC);
1333 w->WriteULEB128(DW_FORM_ADDR);
1334 w->WriteULEB128(DW_AT_HIGH_PC);
1335 w->WriteULEB128(DW_FORM_ADDR);
1336 w->WriteULEB128(DW_AT_FRAME_BASE);
1337 w->WriteULEB128(DW_FORM_BLOCK4);
1341 w->WriteULEB128(current_abbreviation++);
1342 w->WriteULEB128(DW_TAG_STRUCTURE_TYPE);
1343 w->Write<uint8_t>(DW_CHILDREN_NO);
1344 w->WriteULEB128(DW_AT_BYTE_SIZE);
1345 w->WriteULEB128(DW_FORM_DATA1);
1346 w->WriteULEB128(DW_AT_NAME);
1347 w->WriteULEB128(DW_FORM_STRING);
1351 for (int param = 0; param < params; ++param) {
1352 WriteVariableAbbreviation(w, current_abbreviation++, true, true);
1355 for (int slot = 0; slot < slots; ++slot) {
1356 WriteVariableAbbreviation(w, current_abbreviation++, false, false);
1359 for (int internal_slot = 0;
1360 internal_slot < internal_slots;
1362 WriteVariableAbbreviation(w, current_abbreviation++, false, false);
1365 for (int context_slot = 0;
1366 context_slot < context_slots;
1368 WriteVariableAbbreviation(w, current_abbreviation++, false, false);
1371 for (int local = 0; local < locals; ++local) {
1372 WriteVariableAbbreviation(w, current_abbreviation++, true, false);
1376 WriteVariableAbbreviation(w, current_abbreviation++, true, false);
1379 WriteVariableAbbreviation(w, current_abbreviation++, true, false);
1381 w->WriteULEB128(0); // Terminate the sibling list.
1384 w->WriteULEB128(0); // Terminate the table.
1389 CodeDescription* desc_;
1393 class DebugLineSection : public DebugSection {
1395 explicit DebugLineSection(CodeDescription* desc)
1397 : ELFSection(".debug_line", TYPE_PROGBITS, 1),
1399 : MachOSection("__debug_line",
1402 MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
1406 // DWARF2 standard, figure 34.
1407 enum DWARF2Opcodes {
1409 DW_LNS_ADVANCE_PC = 2,
1410 DW_LNS_ADVANCE_LINE = 3,
1411 DW_LNS_SET_FILE = 4,
1412 DW_LNS_SET_COLUMN = 5,
1413 DW_LNS_NEGATE_STMT = 6
1416 // DWARF2 standard, figure 35.
1417 enum DWARF2ExtendedOpcode {
1418 DW_LNE_END_SEQUENCE = 1,
1419 DW_LNE_SET_ADDRESS = 2,
1420 DW_LNE_DEFINE_FILE = 3
1423 bool WriteBodyInternal(Writer* w) {
1425 Writer::Slot<uint32_t> total_length = w->CreateSlotHere<uint32_t>();
1426 uintptr_t start = w->position();
1428 // Used for special opcodes
1429 const int8_t line_base = 1;
1430 const uint8_t line_range = 7;
1431 const int8_t max_line_incr = (line_base + line_range - 1);
1432 const uint8_t opcode_base = DW_LNS_NEGATE_STMT + 1;
1434 w->Write<uint16_t>(2); // Field version.
1435 Writer::Slot<uint32_t> prologue_length = w->CreateSlotHere<uint32_t>();
1436 uintptr_t prologue_start = w->position();
1437 w->Write<uint8_t>(1); // Field minimum_instruction_length.
1438 w->Write<uint8_t>(1); // Field default_is_stmt.
1439 w->Write<int8_t>(line_base); // Field line_base.
1440 w->Write<uint8_t>(line_range); // Field line_range.
1441 w->Write<uint8_t>(opcode_base); // Field opcode_base.
1442 w->Write<uint8_t>(0); // DW_LNS_COPY operands count.
1443 w->Write<uint8_t>(1); // DW_LNS_ADVANCE_PC operands count.
1444 w->Write<uint8_t>(1); // DW_LNS_ADVANCE_LINE operands count.
1445 w->Write<uint8_t>(1); // DW_LNS_SET_FILE operands count.
1446 w->Write<uint8_t>(1); // DW_LNS_SET_COLUMN operands count.
1447 w->Write<uint8_t>(0); // DW_LNS_NEGATE_STMT operands count.
1448 w->Write<uint8_t>(0); // Empty include_directories sequence.
1449 w->WriteString(desc_->GetFilename().get()); // File name.
1450 w->WriteULEB128(0); // Current directory.
1451 w->WriteULEB128(0); // Unknown modification time.
1452 w->WriteULEB128(0); // Unknown file size.
1453 w->Write<uint8_t>(0);
1454 prologue_length.set(static_cast<uint32_t>(w->position() - prologue_start));
1456 WriteExtendedOpcode(w, DW_LNE_SET_ADDRESS, sizeof(intptr_t));
1457 w->Write<intptr_t>(desc_->CodeStart());
1458 w->Write<uint8_t>(DW_LNS_COPY);
1462 bool is_statement = true;
1464 List<LineInfo::PCInfo>* pc_info = desc_->lineinfo()->pc_info();
1465 pc_info->Sort(&ComparePCInfo);
1467 int pc_info_length = pc_info->length();
1468 for (int i = 0; i < pc_info_length; i++) {
1469 LineInfo::PCInfo* info = &pc_info->at(i);
1470 DCHECK(info->pc_ >= pc);
1472 // Reduce bloating in the debug line table by removing duplicate line
1473 // entries (per DWARF2 standard).
1474 intptr_t new_line = desc_->GetScriptLineNumber(info->pos_);
1475 if (new_line == line) {
1479 // Mark statement boundaries. For a better debugging experience, mark
1480 // the last pc address in the function as a statement (e.g. "}"), so that
1481 // a user can see the result of the last line executed in the function,
1482 // should control reach the end.
1483 if ((i+1) == pc_info_length) {
1484 if (!is_statement) {
1485 w->Write<uint8_t>(DW_LNS_NEGATE_STMT);
1487 } else if (is_statement != info->is_statement_) {
1488 w->Write<uint8_t>(DW_LNS_NEGATE_STMT);
1489 is_statement = !is_statement;
1492 // Generate special opcodes, if possible. This results in more compact
1493 // debug line tables. See the DWARF 2.0 standard to learn more about
1495 uintptr_t pc_diff = info->pc_ - pc;
1496 intptr_t line_diff = new_line - line;
1498 // Compute special opcode (see DWARF 2.0 standard)
1499 intptr_t special_opcode = (line_diff - line_base) +
1500 (line_range * pc_diff) + opcode_base;
1502 // If special_opcode is less than or equal to 255, it can be used as a
1503 // special opcode. If line_diff is larger than the max line increment
1504 // allowed for a special opcode, or if line_diff is less than the minimum
1505 // line that can be added to the line register (i.e. line_base), then
1506 // special_opcode can't be used.
1507 if ((special_opcode >= opcode_base) && (special_opcode <= 255) &&
1508 (line_diff <= max_line_incr) && (line_diff >= line_base)) {
1509 w->Write<uint8_t>(special_opcode);
1511 w->Write<uint8_t>(DW_LNS_ADVANCE_PC);
1512 w->WriteSLEB128(pc_diff);
1513 w->Write<uint8_t>(DW_LNS_ADVANCE_LINE);
1514 w->WriteSLEB128(line_diff);
1515 w->Write<uint8_t>(DW_LNS_COPY);
1518 // Increment the pc and line operands.
1522 // Advance the pc to the end of the routine, since the end sequence opcode
1524 w->Write<uint8_t>(DW_LNS_ADVANCE_PC);
1525 w->WriteSLEB128(desc_->CodeSize() - pc);
1526 WriteExtendedOpcode(w, DW_LNE_END_SEQUENCE, 0);
1527 total_length.set(static_cast<uint32_t>(w->position() - start));
1532 void WriteExtendedOpcode(Writer* w,
1533 DWARF2ExtendedOpcode op,
1534 size_t operands_size) {
1535 w->Write<uint8_t>(0);
1536 w->WriteULEB128(operands_size + 1);
1537 w->Write<uint8_t>(op);
1540 static int ComparePCInfo(const LineInfo::PCInfo* a,
1541 const LineInfo::PCInfo* b) {
1542 if (a->pc_ == b->pc_) {
1543 if (a->is_statement_ != b->is_statement_) {
1544 return b->is_statement_ ? +1 : -1;
1547 } else if (a->pc_ > b->pc_) {
1554 CodeDescription* desc_;
1558 #if V8_TARGET_ARCH_X64
1560 class UnwindInfoSection : public DebugSection {
1562 explicit UnwindInfoSection(CodeDescription* desc);
1563 virtual bool WriteBodyInternal(Writer* w);
1565 int WriteCIE(Writer* w);
1566 void WriteFDE(Writer* w, int);
1568 void WriteFDEStateOnEntry(Writer* w);
1569 void WriteFDEStateAfterRBPPush(Writer* w);
1570 void WriteFDEStateAfterRBPSet(Writer* w);
1571 void WriteFDEStateAfterRBPPop(Writer* w);
1573 void WriteLength(Writer* w,
1574 Writer::Slot<uint32_t>* length_slot,
1575 int initial_position);
1578 CodeDescription* desc_;
1580 // DWARF3 Specification, Table 7.23
1581 enum CFIInstructions {
1582 DW_CFA_ADVANCE_LOC = 0x40,
1583 DW_CFA_OFFSET = 0x80,
1584 DW_CFA_RESTORE = 0xC0,
1586 DW_CFA_SET_LOC = 0x01,
1587 DW_CFA_ADVANCE_LOC1 = 0x02,
1588 DW_CFA_ADVANCE_LOC2 = 0x03,
1589 DW_CFA_ADVANCE_LOC4 = 0x04,
1590 DW_CFA_OFFSET_EXTENDED = 0x05,
1591 DW_CFA_RESTORE_EXTENDED = 0x06,
1592 DW_CFA_UNDEFINED = 0x07,
1593 DW_CFA_SAME_VALUE = 0x08,
1594 DW_CFA_REGISTER = 0x09,
1595 DW_CFA_REMEMBER_STATE = 0x0A,
1596 DW_CFA_RESTORE_STATE = 0x0B,
1597 DW_CFA_DEF_CFA = 0x0C,
1598 DW_CFA_DEF_CFA_REGISTER = 0x0D,
1599 DW_CFA_DEF_CFA_OFFSET = 0x0E,
1601 DW_CFA_DEF_CFA_EXPRESSION = 0x0F,
1602 DW_CFA_EXPRESSION = 0x10,
1603 DW_CFA_OFFSET_EXTENDED_SF = 0x11,
1604 DW_CFA_DEF_CFA_SF = 0x12,
1605 DW_CFA_DEF_CFA_OFFSET_SF = 0x13,
1606 DW_CFA_VAL_OFFSET = 0x14,
1607 DW_CFA_VAL_OFFSET_SF = 0x15,
1608 DW_CFA_VAL_EXPRESSION = 0x16
1611 // System V ABI, AMD64 Supplement, Version 0.99.5, Figure 3.36
1612 enum RegisterMapping {
1613 // Only the relevant ones have been added to reduce clutter.
1622 CODE_ALIGN_FACTOR = 1,
1623 DATA_ALIGN_FACTOR = 1,
1624 RETURN_ADDRESS_REGISTER = AMD64_RA
1629 void UnwindInfoSection::WriteLength(Writer* w,
1630 Writer::Slot<uint32_t>* length_slot,
1631 int initial_position) {
1632 uint32_t align = (w->position() - initial_position) % kPointerSize;
1635 for (uint32_t i = 0; i < (kPointerSize - align); i++) {
1636 w->Write<uint8_t>(DW_CFA_NOP);
1640 DCHECK((w->position() - initial_position) % kPointerSize == 0);
1641 length_slot->set(w->position() - initial_position);
1645 UnwindInfoSection::UnwindInfoSection(CodeDescription* desc)
1647 : ELFSection(".eh_frame", TYPE_X86_64_UNWIND, 1),
1649 : MachOSection("__eh_frame", "__TEXT", sizeof(uintptr_t),
1650 MachOSection::S_REGULAR),
1654 int UnwindInfoSection::WriteCIE(Writer* w) {
1655 Writer::Slot<uint32_t> cie_length_slot = w->CreateSlotHere<uint32_t>();
1656 uint32_t cie_position = w->position();
1658 // Write out the CIE header. Currently no 'common instructions' are
1659 // emitted onto the CIE; every FDE has its own set of instructions.
1661 w->Write<uint32_t>(CIE_ID);
1662 w->Write<uint8_t>(CIE_VERSION);
1663 w->Write<uint8_t>(0); // Null augmentation string.
1664 w->WriteSLEB128(CODE_ALIGN_FACTOR);
1665 w->WriteSLEB128(DATA_ALIGN_FACTOR);
1666 w->Write<uint8_t>(RETURN_ADDRESS_REGISTER);
1668 WriteLength(w, &cie_length_slot, cie_position);
1670 return cie_position;
1674 void UnwindInfoSection::WriteFDE(Writer* w, int cie_position) {
1675 // The only FDE for this function. The CFA is the current RBP.
1676 Writer::Slot<uint32_t> fde_length_slot = w->CreateSlotHere<uint32_t>();
1677 int fde_position = w->position();
1678 w->Write<int32_t>(fde_position - cie_position + 4);
1680 w->Write<uintptr_t>(desc_->CodeStart());
1681 w->Write<uintptr_t>(desc_->CodeSize());
1683 WriteFDEStateOnEntry(w);
1684 WriteFDEStateAfterRBPPush(w);
1685 WriteFDEStateAfterRBPSet(w);
1686 WriteFDEStateAfterRBPPop(w);
1688 WriteLength(w, &fde_length_slot, fde_position);
1692 void UnwindInfoSection::WriteFDEStateOnEntry(Writer* w) {
1693 // The first state, just after the control has been transferred to the the
1696 // RBP for this function will be the value of RSP after pushing the RBP
1697 // for the previous function. The previous RBP has not been pushed yet.
1698 w->Write<uint8_t>(DW_CFA_DEF_CFA_SF);
1699 w->WriteULEB128(AMD64_RSP);
1700 w->WriteSLEB128(-kPointerSize);
1702 // The RA is stored at location CFA + kCallerPCOffset. This is an invariant,
1703 // and hence omitted from the next states.
1704 w->Write<uint8_t>(DW_CFA_OFFSET_EXTENDED);
1705 w->WriteULEB128(AMD64_RA);
1706 w->WriteSLEB128(StandardFrameConstants::kCallerPCOffset);
1708 // The RBP of the previous function is still in RBP.
1709 w->Write<uint8_t>(DW_CFA_SAME_VALUE);
1710 w->WriteULEB128(AMD64_RBP);
1712 // Last location described by this entry.
1713 w->Write<uint8_t>(DW_CFA_SET_LOC);
1715 desc_->GetStackStateStartAddress(CodeDescription::POST_RBP_PUSH));
1719 void UnwindInfoSection::WriteFDEStateAfterRBPPush(Writer* w) {
1720 // The second state, just after RBP has been pushed.
1722 // RBP / CFA for this function is now the current RSP, so just set the
1723 // offset from the previous rule (from -8) to 0.
1724 w->Write<uint8_t>(DW_CFA_DEF_CFA_OFFSET);
1727 // The previous RBP is stored at CFA + kCallerFPOffset. This is an invariant
1728 // in this and the next state, and hence omitted in the next state.
1729 w->Write<uint8_t>(DW_CFA_OFFSET_EXTENDED);
1730 w->WriteULEB128(AMD64_RBP);
1731 w->WriteSLEB128(StandardFrameConstants::kCallerFPOffset);
1733 // Last location described by this entry.
1734 w->Write<uint8_t>(DW_CFA_SET_LOC);
1736 desc_->GetStackStateStartAddress(CodeDescription::POST_RBP_SET));
1740 void UnwindInfoSection::WriteFDEStateAfterRBPSet(Writer* w) {
1741 // The third state, after the RBP has been set.
1743 // The CFA can now directly be set to RBP.
1744 w->Write<uint8_t>(DW_CFA_DEF_CFA);
1745 w->WriteULEB128(AMD64_RBP);
1748 // Last location described by this entry.
1749 w->Write<uint8_t>(DW_CFA_SET_LOC);
1751 desc_->GetStackStateStartAddress(CodeDescription::POST_RBP_POP));
1755 void UnwindInfoSection::WriteFDEStateAfterRBPPop(Writer* w) {
1756 // The fourth (final) state. The RBP has been popped (just before issuing a
1759 // The CFA can is now calculated in the same way as in the first state.
1760 w->Write<uint8_t>(DW_CFA_DEF_CFA_SF);
1761 w->WriteULEB128(AMD64_RSP);
1762 w->WriteSLEB128(-kPointerSize);
1765 w->Write<uint8_t>(DW_CFA_OFFSET_EXTENDED);
1766 w->WriteULEB128(AMD64_RBP);
1767 w->WriteSLEB128(StandardFrameConstants::kCallerFPOffset);
1769 // Last location described by this entry.
1770 w->Write<uint8_t>(DW_CFA_SET_LOC);
1771 w->Write<uint64_t>(desc_->CodeEnd());
1775 bool UnwindInfoSection::WriteBodyInternal(Writer* w) {
1776 uint32_t cie_position = WriteCIE(w);
1777 WriteFDE(w, cie_position);
1782 #endif // V8_TARGET_ARCH_X64
1784 static void CreateDWARFSections(CodeDescription* desc,
1787 if (desc->IsLineInfoAvailable()) {
1788 obj->AddSection(new(zone) DebugInfoSection(desc));
1789 obj->AddSection(new(zone) DebugAbbrevSection(desc));
1790 obj->AddSection(new(zone) DebugLineSection(desc));
1792 #if V8_TARGET_ARCH_X64
1793 obj->AddSection(new(zone) UnwindInfoSection(desc));
1798 // -------------------------------------------------------------------
1799 // Binary GDB JIT Interface as described in
1800 // http://sourceware.org/gdb/onlinedocs/gdb/Declarations.html
1808 struct JITCodeEntry {
1809 JITCodeEntry* next_;
1810 JITCodeEntry* prev_;
1811 Address symfile_addr_;
1812 uint64_t symfile_size_;
1815 struct JITDescriptor {
1817 uint32_t action_flag_;
1818 JITCodeEntry* relevant_entry_;
1819 JITCodeEntry* first_entry_;
1822 // GDB will place breakpoint into this function.
1823 // To prevent GCC from inlining or removing it we place noinline attribute
1824 // and inline assembler statement inside.
1825 void __attribute__((noinline)) __jit_debug_register_code() {
1829 // GDB will inspect contents of this descriptor.
1830 // Static initialization is necessary to prevent GDB from seeing
1831 // uninitialized descriptor.
1832 JITDescriptor __jit_debug_descriptor = { 1, 0, 0, 0 };
1835 void __gdb_print_v8_object(Object* object) {
1836 OFStream os(stdout);
1844 static JITCodeEntry* CreateCodeEntry(Address symfile_addr,
1845 uintptr_t symfile_size) {
1846 JITCodeEntry* entry = static_cast<JITCodeEntry*>(
1847 malloc(sizeof(JITCodeEntry) + symfile_size));
1849 entry->symfile_addr_ = reinterpret_cast<Address>(entry + 1);
1850 entry->symfile_size_ = symfile_size;
1851 MemCopy(entry->symfile_addr_, symfile_addr, symfile_size);
1853 entry->prev_ = entry->next_ = NULL;
1859 static void DestroyCodeEntry(JITCodeEntry* entry) {
1864 static void RegisterCodeEntry(JITCodeEntry* entry) {
1865 entry->next_ = __jit_debug_descriptor.first_entry_;
1866 if (entry->next_ != NULL) entry->next_->prev_ = entry;
1867 __jit_debug_descriptor.first_entry_ =
1868 __jit_debug_descriptor.relevant_entry_ = entry;
1870 __jit_debug_descriptor.action_flag_ = JIT_REGISTER_FN;
1871 __jit_debug_register_code();
1875 static void UnregisterCodeEntry(JITCodeEntry* entry) {
1876 if (entry->prev_ != NULL) {
1877 entry->prev_->next_ = entry->next_;
1879 __jit_debug_descriptor.first_entry_ = entry->next_;
1882 if (entry->next_ != NULL) {
1883 entry->next_->prev_ = entry->prev_;
1886 __jit_debug_descriptor.relevant_entry_ = entry;
1887 __jit_debug_descriptor.action_flag_ = JIT_UNREGISTER_FN;
1888 __jit_debug_register_code();
1892 static JITCodeEntry* CreateELFObject(CodeDescription* desc, Isolate* isolate) {
1895 MachO mach_o(&zone);
1898 mach_o.AddSection(new(&zone) MachOTextSection(kCodeAlignment,
1902 CreateDWARFSections(desc, &zone, &mach_o);
1904 mach_o.Write(&w, desc->CodeStart(), desc->CodeSize());
1910 int text_section_index = elf.AddSection(
1911 new(&zone) FullHeaderELFSection(
1913 ELFSection::TYPE_NOBITS,
1918 ELFSection::FLAG_ALLOC | ELFSection::FLAG_EXEC));
1920 CreateSymbolsTable(desc, &zone, &elf, text_section_index);
1922 CreateDWARFSections(desc, &zone, &elf);
1927 return CreateCodeEntry(w.buffer(), w.position());
1931 struct AddressRange {
1936 struct SplayTreeConfig {
1937 typedef AddressRange Key;
1938 typedef JITCodeEntry* Value;
1939 static const AddressRange kNoKey;
1940 static Value NoValue() { return NULL; }
1941 static int Compare(const AddressRange& a, const AddressRange& b) {
1942 // ptrdiff_t probably doesn't fit in an int.
1943 if (a.start < b.start) return -1;
1944 if (a.start == b.start) return 0;
1949 const AddressRange SplayTreeConfig::kNoKey = {0, 0};
1950 typedef SplayTree<SplayTreeConfig> CodeMap;
1952 static CodeMap* GetCodeMap() {
1953 static CodeMap* code_map = NULL;
1954 if (code_map == NULL) code_map = new CodeMap();
1959 static uint32_t HashCodeAddress(Address addr) {
1960 static const uintptr_t kGoldenRatio = 2654435761u;
1961 uintptr_t offset = OffsetFrom(addr);
1962 return static_cast<uint32_t>((offset >> kCodeAlignmentBits) * kGoldenRatio);
1966 static HashMap* GetLineMap() {
1967 static HashMap* line_map = NULL;
1968 if (line_map == NULL) line_map = new HashMap(&HashMap::PointersMatch);
1973 static void PutLineInfo(Address addr, LineInfo* info) {
1974 HashMap* line_map = GetLineMap();
1975 HashMap::Entry* e = line_map->Lookup(addr, HashCodeAddress(addr), true);
1976 if (e->value != NULL) delete static_cast<LineInfo*>(e->value);
1981 static LineInfo* GetLineInfo(Address addr) {
1982 void* value = GetLineMap()->Remove(addr, HashCodeAddress(addr));
1983 return static_cast<LineInfo*>(value);
1987 static void AddUnwindInfo(CodeDescription* desc) {
1988 #if V8_TARGET_ARCH_X64
1989 if (desc->is_function()) {
1990 // To avoid propagating unwinding information through
1991 // compilation pipeline we use an approximation.
1992 // For most use cases this should not affect usability.
1993 static const int kFramePointerPushOffset = 1;
1994 static const int kFramePointerSetOffset = 4;
1995 static const int kFramePointerPopOffset = -3;
1997 uintptr_t frame_pointer_push_address =
1998 desc->CodeStart() + kFramePointerPushOffset;
2000 uintptr_t frame_pointer_set_address =
2001 desc->CodeStart() + kFramePointerSetOffset;
2003 uintptr_t frame_pointer_pop_address =
2004 desc->CodeEnd() + kFramePointerPopOffset;
2006 desc->SetStackStateStartAddress(CodeDescription::POST_RBP_PUSH,
2007 frame_pointer_push_address);
2008 desc->SetStackStateStartAddress(CodeDescription::POST_RBP_SET,
2009 frame_pointer_set_address);
2010 desc->SetStackStateStartAddress(CodeDescription::POST_RBP_POP,
2011 frame_pointer_pop_address);
2013 desc->SetStackStateStartAddress(CodeDescription::POST_RBP_PUSH,
2015 desc->SetStackStateStartAddress(CodeDescription::POST_RBP_SET,
2017 desc->SetStackStateStartAddress(CodeDescription::POST_RBP_POP,
2020 #endif // V8_TARGET_ARCH_X64
2024 static base::LazyMutex mutex = LAZY_MUTEX_INITIALIZER;
2027 // Remove entries from the splay tree that intersect the given address range,
2028 // and deregister them from GDB.
2029 static void RemoveJITCodeEntries(CodeMap* map, const AddressRange& range) {
2030 DCHECK(range.start < range.end);
2031 CodeMap::Locator cur;
2032 if (map->FindGreatestLessThan(range, &cur) || map->FindLeast(&cur)) {
2033 // Skip entries that are entirely less than the range of interest.
2034 while (cur.key().end <= range.start) {
2035 // CodeMap::FindLeastGreaterThan succeeds for entries whose key is greater
2036 // than _or equal to_ the given key, so we have to advance our key to get
2038 AddressRange new_key;
2039 new_key.start = cur.key().end;
2041 if (!map->FindLeastGreaterThan(new_key, &cur)) return;
2043 // Evict intersecting ranges.
2044 while (cur.key().start < range.end) {
2045 AddressRange old_range = cur.key();
2046 JITCodeEntry* old_entry = cur.value();
2048 UnregisterCodeEntry(old_entry);
2049 DestroyCodeEntry(old_entry);
2051 CHECK(map->Remove(old_range));
2052 if (!map->FindLeastGreaterThan(old_range, &cur)) return;
2058 // Insert the entry into the splay tree and register it with GDB.
2059 static void AddJITCodeEntry(CodeMap* map, const AddressRange& range,
2060 JITCodeEntry* entry, bool dump_if_enabled,
2061 const char* name_hint) {
2062 #if defined(DEBUG) && !V8_OS_WIN
2063 static int file_num = 0;
2064 if (FLAG_gdbjit_dump && dump_if_enabled) {
2065 static const int kMaxFileNameSize = 64;
2068 SNPrintF(Vector<char>(file_name, kMaxFileNameSize), "/tmp/elfdump%s%d.o",
2069 (name_hint != NULL) ? name_hint : "", file_num++);
2070 WriteBytes(file_name, entry->symfile_addr_, entry->symfile_size_);
2074 CodeMap::Locator cur;
2075 CHECK(map->Insert(range, &cur));
2076 cur.set_value(entry);
2078 RegisterCodeEntry(entry);
2082 static void AddCode(const char* name, Code* code, SharedFunctionInfo* shared,
2083 LineInfo* lineinfo) {
2084 DisallowHeapAllocation no_gc;
2086 CodeMap* code_map = GetCodeMap();
2088 range.start = code->address();
2089 range.end = code->address() + code->CodeSize();
2090 RemoveJITCodeEntries(code_map, range);
2092 CodeDescription code_desc(name, code, shared, lineinfo);
2094 if (!FLAG_gdbjit_full && !code_desc.IsLineInfoAvailable()) {
2099 AddUnwindInfo(&code_desc);
2100 Isolate* isolate = code->GetIsolate();
2101 JITCodeEntry* entry = CreateELFObject(&code_desc, isolate);
2105 const char* name_hint = NULL;
2106 bool should_dump = false;
2107 if (FLAG_gdbjit_dump) {
2108 if (strlen(FLAG_gdbjit_dump_filter) == 0) {
2111 } else if (name != NULL) {
2112 name_hint = strstr(name, FLAG_gdbjit_dump_filter);
2113 should_dump = (name_hint != NULL);
2116 AddJITCodeEntry(code_map, range, entry, should_dump, name_hint);
2120 void EventHandler(const v8::JitCodeEvent* event) {
2121 if (!FLAG_gdbjit) return;
2122 base::LockGuard<base::Mutex> lock_guard(mutex.Pointer());
2123 switch (event->type) {
2124 case v8::JitCodeEvent::CODE_ADDED: {
2125 Address addr = reinterpret_cast<Address>(event->code_start);
2126 Code* code = Code::GetCodeFromTargetAddress(addr);
2127 LineInfo* lineinfo = GetLineInfo(addr);
2128 EmbeddedVector<char, 256> buffer;
2129 StringBuilder builder(buffer.start(), buffer.length());
2130 builder.AddSubstring(event->name.str, static_cast<int>(event->name.len));
2131 // It's called UnboundScript in the API but it's a SharedFunctionInfo.
2132 SharedFunctionInfo* shared =
2133 event->script.IsEmpty() ? NULL : *Utils::OpenHandle(*event->script);
2134 AddCode(builder.Finalize(), code, shared, lineinfo);
2137 case v8::JitCodeEvent::CODE_MOVED:
2138 // Enabling the GDB JIT interface should disable code compaction.
2141 case v8::JitCodeEvent::CODE_REMOVED:
2142 // Do nothing. Instead, adding code causes eviction of any entry whose
2143 // address range intersects the address range of the added code.
2145 case v8::JitCodeEvent::CODE_ADD_LINE_POS_INFO: {
2146 LineInfo* line_info = reinterpret_cast<LineInfo*>(event->user_data);
2147 line_info->SetPosition(static_cast<intptr_t>(event->line_info.offset),
2148 static_cast<int>(event->line_info.pos),
2149 event->line_info.position_type ==
2150 v8::JitCodeEvent::STATEMENT_POSITION);
2153 case v8::JitCodeEvent::CODE_START_LINE_INFO_RECORDING: {
2154 v8::JitCodeEvent* mutable_event = const_cast<v8::JitCodeEvent*>(event);
2155 mutable_event->user_data = new LineInfo();
2158 case v8::JitCodeEvent::CODE_END_LINE_INFO_RECORDING: {
2159 LineInfo* line_info = reinterpret_cast<LineInfo*>(event->user_data);
2160 PutLineInfo(reinterpret_cast<Address>(event->code_start), line_info);
2166 } // namespace GDBJITInterface
2167 } // namespace internal