gdb-jit.cc 61.8 KB
Newer Older
1
// Copyright 2010 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4 5

#ifdef ENABLE_GDB_JIT_INTERFACE
6
#include "src/v8.h"
7

8
#include "src/base/bits.h"
9
#include "src/base/platform/platform.h"
10 11 12
#include "src/bootstrapper.h"
#include "src/compiler.h"
#include "src/frames-inl.h"
13 14
#include "src/frames.h"
#include "src/gdb-jit.h"
15 16 17
#include "src/global-handles.h"
#include "src/messages.h"
#include "src/natives.h"
18
#include "src/ostreams.h"
19
#include "src/scopes.h"
20 21 22 23

namespace v8 {
namespace internal {

24
#ifdef __APPLE__
25 26 27 28 29 30 31
#define __MACH_O
class MachO;
class MachOSection;
typedef MachO DebugObject;
typedef MachOSection DebugSection;
#else
#define __ELF
32
class ELF;
33 34 35 36
class ELFSection;
typedef ELF DebugObject;
typedef ELFSection DebugSection;
#endif
37 38 39

class Writer BASE_EMBEDDED {
 public:
40 41
  explicit Writer(DebugObject* debug_object)
      : debug_object_(debug_object),
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
        position_(0),
        capacity_(1024),
        buffer_(reinterpret_cast<byte*>(malloc(capacity_))) {
  }

  ~Writer() {
    free(buffer_);
  }

  uintptr_t position() const {
    return position_;
  }

  template<typename T>
  class Slot {
   public:
    Slot(Writer* w, uintptr_t offset) : w_(w), offset_(offset) { }

    T* operator-> () {
      return w_->RawSlotAt<T>(offset_);
    }

    void set(const T& value) {
      *w_->RawSlotAt<T>(offset_) = value;
    }

    Slot<T> at(int i) {
      return Slot<T>(w_, offset_ + sizeof(T) * i);
    }

   private:
    Writer* w_;
    uintptr_t offset_;
  };

  template<typename T>
  void Write(const T& val) {
    Ensure(position_ + sizeof(T));
    *RawSlotAt<T>(position_) = val;
    position_ += sizeof(T);
  }

  template<typename T>
  Slot<T> SlotAt(uintptr_t offset) {
    Ensure(offset + sizeof(T));
    return Slot<T>(this, offset);
  }

  template<typename T>
  Slot<T> CreateSlotHere() {
    return CreateSlotsHere<T>(1);
  }

  template<typename T>
  Slot<T> CreateSlotsHere(uint32_t count) {
    uintptr_t slot_position = position_;
    position_ += sizeof(T) * count;
    Ensure(position_);
    return SlotAt<T>(slot_position);
  }

  void Ensure(uintptr_t pos) {
    if (capacity_ < pos) {
      while (capacity_ < pos) capacity_ *= 2;
      buffer_ = reinterpret_cast<byte*>(realloc(buffer_, capacity_));
    }
  }

110
  DebugObject* debug_object() { return debug_object_; }
111 112 113 114 115 116 117 118

  byte* buffer() { return buffer_; }

  void Align(uintptr_t align) {
    uintptr_t delta = position_ % align;
    if (delta == 0) return;
    uintptr_t padding = align - delta;
    Ensure(position_ += padding);
119
    DCHECK((position_ % align) == 0);
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
  }

  void WriteULEB128(uintptr_t value) {
    do {
      uint8_t byte = value & 0x7F;
      value >>= 7;
      if (value != 0) byte |= 0x80;
      Write<uint8_t>(byte);
    } while (value != 0);
  }

  void WriteSLEB128(intptr_t value) {
    bool more = true;
    while (more) {
      int8_t byte = value & 0x7F;
      bool byte_sign = byte & 0x40;
      value >>= 7;

      if ((value == 0 && !byte_sign) || (value == -1 && byte_sign)) {
        more = false;
      } else {
        byte |= 0x80;
      }

      Write<int8_t>(byte);
    }
  }

  void WriteString(const char* str) {
    do {
      Write<char>(*str);
    } while (*str++);
  }

 private:
  template<typename T> friend class Slot;

  template<typename T>
  T* RawSlotAt(uintptr_t offset) {
159
    DCHECK(offset < capacity_ && offset + sizeof(T) <= capacity_);
160 161 162
    return reinterpret_cast<T*>(&buffer_[offset]);
  }

163
  DebugObject* debug_object_;
164 165 166 167 168
  uintptr_t position_;
  uintptr_t capacity_;
  byte* buffer_;
};

169
class ELFStringTable;
170

171 172
template<typename THeader>
class DebugSectionBase : public ZoneObject {
173
 public:
174 175 176 177
  virtual ~DebugSectionBase() { }

  virtual void WriteBody(Writer::Slot<THeader> header, Writer* writer) {
    uintptr_t start = writer->position();
178
    if (WriteBodyInternal(writer)) {
179 180 181 182 183 184 185 186 187
      uintptr_t end = writer->position();
      header->offset = start;
#if defined(__MACH_O)
      header->addr = 0;
#endif
      header->size = end - start;
    }
  }

188
  virtual bool WriteBodyInternal(Writer* writer) {
189 190 191 192 193 194 195 196 197 198
    return false;
  }

  typedef THeader Header;
};


struct MachOSectionHeader {
  char sectname[16];
  char segname[16];
danno@chromium.org's avatar
danno@chromium.org committed
199
#if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
  uint32_t addr;
  uint32_t size;
#else
  uint64_t addr;
  uint64_t size;
#endif
  uint32_t offset;
  uint32_t align;
  uint32_t reloff;
  uint32_t nreloc;
  uint32_t flags;
  uint32_t reserved1;
  uint32_t reserved2;
};


class MachOSection : public DebugSectionBase<MachOSectionHeader> {
 public:
  enum Type {
    S_REGULAR = 0x0u,
    S_ATTR_COALESCED = 0xbu,
    S_ATTR_SOME_INSTRUCTIONS = 0x400u,
    S_ATTR_DEBUG = 0x02000000u,
    S_ATTR_PURE_INSTRUCTIONS = 0x80000000u
224 225
  };

226
  MachOSection(const char* name, const char* segment, uint32_t align,
227
               uint32_t flags)
228
      : name_(name), segment_(segment), align_(align), flags_(flags) {
229
    if (align_ != 0) {
230
      DCHECK(base::bits::IsPowerOfTwo32(align));
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
      align_ = WhichPowerOf2(align_);
    }
  }

  virtual ~MachOSection() { }

  virtual void PopulateHeader(Writer::Slot<Header> header) {
    header->addr = 0;
    header->size = 0;
    header->offset = 0;
    header->align = align_;
    header->reloff = 0;
    header->nreloc = 0;
    header->flags = flags_;
    header->reserved1 = 0;
    header->reserved2 = 0;
247 248
    memset(header->sectname, 0, sizeof(header->sectname));
    memset(header->segname, 0, sizeof(header->segname));
249 250
    DCHECK(strlen(name_) < sizeof(header->sectname));
    DCHECK(strlen(segment_) < sizeof(header->segname));
251 252
    strncpy(header->sectname, name_, sizeof(header->sectname));
    strncpy(header->segname, segment_, sizeof(header->segname));
253 254 255 256 257
  }

 private:
  const char* name_;
  const char* segment_;
258
  uint32_t align_;
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
  uint32_t flags_;
};


struct ELFSectionHeader {
  uint32_t name;
  uint32_t type;
  uintptr_t flags;
  uintptr_t address;
  uintptr_t offset;
  uintptr_t size;
  uint32_t link;
  uint32_t info;
  uintptr_t alignment;
  uintptr_t entry_size;
};
275

276 277 278 279

#if defined(__ELF)
class ELFSection : public DebugSectionBase<ELFSectionHeader> {
 public:
280 281 282 283 284 285 286 287 288 289 290 291 292 293
  enum Type {
    TYPE_NULL = 0,
    TYPE_PROGBITS = 1,
    TYPE_SYMTAB = 2,
    TYPE_STRTAB = 3,
    TYPE_RELA = 4,
    TYPE_HASH = 5,
    TYPE_DYNAMIC = 6,
    TYPE_NOTE = 7,
    TYPE_NOBITS = 8,
    TYPE_REL = 9,
    TYPE_SHLIB = 10,
    TYPE_DYNSYM = 11,
    TYPE_LOPROC = 0x70000000,
294
    TYPE_X86_64_UNWIND = 0x70000001,
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
    TYPE_HIPROC = 0x7fffffff,
    TYPE_LOUSER = 0x80000000,
    TYPE_HIUSER = 0xffffffff
  };

  enum Flags {
    FLAG_WRITE = 1,
    FLAG_ALLOC = 2,
    FLAG_EXEC = 4
  };

  enum SpecialIndexes {
    INDEX_ABSOLUTE = 0xfff1
  };

  ELFSection(const char* name, Type type, uintptr_t align)
      : name_(name), type_(type), align_(align) { }

  virtual ~ELFSection() { }

315
  void PopulateHeader(Writer::Slot<Header> header, ELFStringTable* strtab);
316 317 318

  virtual void WriteBody(Writer::Slot<Header> header, Writer* w) {
    uintptr_t start = w->position();
319
    if (WriteBodyInternal(w)) {
320 321 322 323 324 325
      uintptr_t end = w->position();
      header->offset = start;
      header->size = end - start;
    }
  }

326
  virtual bool WriteBodyInternal(Writer* w) {
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    return false;
  }

  uint16_t index() const { return index_; }
  void set_index(uint16_t index) { index_ = index; }

 protected:
  virtual void PopulateHeader(Writer::Slot<Header> header) {
    header->flags = 0;
    header->address = 0;
    header->offset = 0;
    header->size = 0;
    header->link = 0;
    header->info = 0;
    header->entry_size = 0;
  }

 private:
  const char* name_;
  Type type_;
  uintptr_t align_;
  uint16_t index_;
};
350
#endif  // defined(__ELF)
351 352


353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
#if defined(__MACH_O)
class MachOTextSection : public MachOSection {
 public:
  MachOTextSection(uintptr_t align,
                   uintptr_t addr,
                   uintptr_t size)
      : MachOSection("__text",
                     "__TEXT",
                     align,
                     MachOSection::S_REGULAR |
                         MachOSection::S_ATTR_SOME_INSTRUCTIONS |
                         MachOSection::S_ATTR_PURE_INSTRUCTIONS),
        addr_(addr),
        size_(size) { }

 protected:
  virtual void PopulateHeader(Writer::Slot<Header> header) {
    MachOSection::PopulateHeader(header);
    header->addr = addr_;
    header->size = size_;
  }

 private:
  uintptr_t addr_;
  uintptr_t size_;
};
#endif  // defined(__MACH_O)


#if defined(__ELF)
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
class FullHeaderELFSection : public ELFSection {
 public:
  FullHeaderELFSection(const char* name,
                       Type type,
                       uintptr_t align,
                       uintptr_t addr,
                       uintptr_t offset,
                       uintptr_t size,
                       uintptr_t flags)
      : ELFSection(name, type, align),
        addr_(addr),
        offset_(offset),
        size_(size),
        flags_(flags) { }

 protected:
  virtual void PopulateHeader(Writer::Slot<Header> header) {
    ELFSection::PopulateHeader(header);
    header->address = addr_;
    header->offset = offset_;
    header->size = size_;
    header->flags = flags_;
  }

 private:
  uintptr_t addr_;
  uintptr_t offset_;
  uintptr_t size_;
  uintptr_t flags_;
};


415
class ELFStringTable : public ELFSection {
416
 public:
417
  explicit ELFStringTable(const char* name)
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
      : ELFSection(name, TYPE_STRTAB, 1), writer_(NULL), offset_(0), size_(0) {
  }

  uintptr_t Add(const char* str) {
    if (*str == '\0') return 0;

    uintptr_t offset = size_;
    WriteString(str);
    return offset;
  }

  void AttachWriter(Writer* w) {
    writer_ = w;
    offset_ = writer_->position();

    // First entry in the string table should be an empty string.
    WriteString("");
  }

  void DetachWriter() {
    writer_ = NULL;
  }

  virtual void WriteBody(Writer::Slot<Header> header, Writer* w) {
442
    DCHECK(writer_ == NULL);
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    header->offset = offset_;
    header->size = size_;
  }

 private:
  void WriteString(const char* str) {
    uintptr_t written = 0;
    do {
      writer_->Write(*str);
      written++;
    } while (*str++);
    size_ += written;
  }

  Writer* writer_;

  uintptr_t offset_;
  uintptr_t size_;
};


void ELFSection::PopulateHeader(Writer::Slot<ELFSection::Header> header,
465
                                ELFStringTable* strtab) {
466 467 468 469 470
  header->name = strtab->Add(name_);
  header->type = type_;
  header->alignment = align_;
  PopulateHeader(header);
}
471 472 473 474 475 476
#endif  // defined(__ELF)


#if defined(__MACH_O)
class MachO BASE_EMBEDDED {
 public:
477
  explicit MachO(Zone* zone) : zone_(zone), sections_(6, zone) { }
478 479

  uint32_t AddSection(MachOSection* section) {
480
    sections_.Add(section, zone_);
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
    return sections_.length() - 1;
  }

  void Write(Writer* w, uintptr_t code_start, uintptr_t code_size) {
    Writer::Slot<MachOHeader> header = WriteHeader(w);
    uintptr_t load_command_start = w->position();
    Writer::Slot<MachOSegmentCommand> cmd = WriteSegmentCommand(w,
                                                                code_start,
                                                                code_size);
    WriteSections(w, cmd, header, load_command_start);
  }

 private:
  struct MachOHeader {
    uint32_t magic;
    uint32_t cputype;
    uint32_t cpusubtype;
    uint32_t filetype;
    uint32_t ncmds;
    uint32_t sizeofcmds;
    uint32_t flags;
502
#if V8_TARGET_ARCH_X64
503 504 505 506 507 508 509 510
    uint32_t reserved;
#endif
  };

  struct MachOSegmentCommand {
    uint32_t cmd;
    uint32_t cmdsize;
    char segname[16];
danno@chromium.org's avatar
danno@chromium.org committed
511
#if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    uint32_t vmaddr;
    uint32_t vmsize;
    uint32_t fileoff;
    uint32_t filesize;
#else
    uint64_t vmaddr;
    uint64_t vmsize;
    uint64_t fileoff;
    uint64_t filesize;
#endif
    uint32_t maxprot;
    uint32_t initprot;
    uint32_t nsects;
    uint32_t flags;
  };

  enum MachOLoadCommandCmd {
    LC_SEGMENT_32 = 0x00000001u,
    LC_SEGMENT_64 = 0x00000019u
  };


  Writer::Slot<MachOHeader> WriteHeader(Writer* w) {
535
    DCHECK(w->position() == 0);
536
    Writer::Slot<MachOHeader> header = w->CreateSlotHere<MachOHeader>();
danno@chromium.org's avatar
danno@chromium.org committed
537
#if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
538 539 540
    header->magic = 0xFEEDFACEu;
    header->cputype = 7;  // i386
    header->cpusubtype = 3;  // CPU_SUBTYPE_I386_ALL
541
#elif V8_TARGET_ARCH_X64
542 543 544 545 546 547 548 549 550 551 552 553 554
    header->magic = 0xFEEDFACFu;
    header->cputype = 7 | 0x01000000;  // i386 | 64-bit ABI
    header->cpusubtype = 3;  // CPU_SUBTYPE_I386_ALL
    header->reserved = 0;
#else
#error Unsupported target architecture.
#endif
    header->filetype = 0x1;  // MH_OBJECT
    header->ncmds = 1;
    header->sizeofcmds = 0;
    header->flags = 0;
    return header;
  }
555 556


557 558 559 560 561
  Writer::Slot<MachOSegmentCommand> WriteSegmentCommand(Writer* w,
                                                        uintptr_t code_start,
                                                        uintptr_t code_size) {
    Writer::Slot<MachOSegmentCommand> cmd =
        w->CreateSlotHere<MachOSegmentCommand>();
danno@chromium.org's avatar
danno@chromium.org committed
562
#if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    cmd->cmd = LC_SEGMENT_32;
#else
    cmd->cmd = LC_SEGMENT_64;
#endif
    cmd->vmaddr = code_start;
    cmd->vmsize = code_size;
    cmd->fileoff = 0;
    cmd->filesize = 0;
    cmd->maxprot = 7;
    cmd->initprot = 7;
    cmd->flags = 0;
    cmd->nsects = sections_.length();
    memset(cmd->segname, 0, 16);
    cmd->cmdsize = sizeof(MachOSegmentCommand) + sizeof(MachOSection::Header) *
        cmd->nsects;
    return cmd;
  }


  void WriteSections(Writer* w,
                     Writer::Slot<MachOSegmentCommand> cmd,
                     Writer::Slot<MachOHeader> header,
                     uintptr_t load_command_start) {
    Writer::Slot<MachOSection::Header> headers =
        w->CreateSlotsHere<MachOSection::Header>(sections_.length());
    cmd->fileoff = w->position();
    header->sizeofcmds = w->position() - load_command_start;
    for (int section = 0; section < sections_.length(); ++section) {
      sections_[section]->PopulateHeader(headers.at(section));
      sections_[section]->WriteBody(headers.at(section), w);
    }
    cmd->filesize = w->position() - (uintptr_t)cmd->fileoff;
  }

597
  Zone* zone_;
598 599 600 601 602 603
  ZoneList<MachOSection*> sections_;
};
#endif  // defined(__MACH_O)


#if defined(__ELF)
604 605
class ELF BASE_EMBEDDED {
 public:
606
  explicit ELF(Zone* zone) : zone_(zone), sections_(6, zone) {
607
    sections_.Add(new(zone) ELFSection("", ELFSection::TYPE_NULL, 0), zone);
608
    sections_.Add(new(zone) ELFStringTable(".shstrtab"), zone);
609 610 611 612 613 614 615 616 617 618 619 620
  }

  void Write(Writer* w) {
    WriteHeader(w);
    WriteSectionTable(w);
    WriteSections(w);
  }

  ELFSection* SectionAt(uint32_t index) {
    return sections_[index];
  }

621 622
  uint32_t AddSection(ELFSection* section) {
    sections_.Add(section, zone_);
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
    section->set_index(sections_.length() - 1);
    return sections_.length() - 1;
  }

 private:
  struct ELFHeader {
    uint8_t ident[16];
    uint16_t type;
    uint16_t machine;
    uint32_t version;
    uintptr_t entry;
    uintptr_t pht_offset;
    uintptr_t sht_offset;
    uint32_t flags;
    uint16_t header_size;
    uint16_t pht_entry_size;
    uint16_t pht_entry_num;
    uint16_t sht_entry_size;
    uint16_t sht_entry_num;
    uint16_t sht_strtab_index;
  };


  void WriteHeader(Writer* w) {
647
    DCHECK(w->position() == 0);
648
    Writer::Slot<ELFHeader> header = w->CreateSlotHere<ELFHeader>();
649 650
#if (V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_X87 || \
     (V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_32_BIT))
651 652
    const uint8_t ident[16] =
        { 0x7f, 'E', 'L', 'F', 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
653
#elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT
654
    const uint8_t ident[16] =
655
        { 0x7f, 'E', 'L', 'F', 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
656 657 658
#else
#error Unsupported target architecture.
#endif
659
    memcpy(header->ident, ident, 16);
660
    header->type = 1;
danno@chromium.org's avatar
danno@chromium.org committed
661
#if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
662
    header->machine = 3;
663
#elif V8_TARGET_ARCH_X64
664 665 666 667
    // Processor identification value for x64 is 62 as defined in
    //    System V ABI, AMD64 Supplement
    //    http://www.x86-64.org/documentation/abi.pdf
    header->machine = 62;
668
#elif V8_TARGET_ARCH_ARM
669 670 671
    // Set to EM_ARM, defined as 40, in "ARM ELF File Format" at
    // infocenter.arm.com/help/topic/com.arm.doc.dui0101a/DUI0101A_Elf.pdf
    header->machine = 40;
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
#else
#error Unsupported target architecture.
#endif
    header->version = 1;
    header->entry = 0;
    header->pht_offset = 0;
    header->sht_offset = sizeof(ELFHeader);  // Section table follows header.
    header->flags = 0;
    header->header_size = sizeof(ELFHeader);
    header->pht_entry_size = 0;
    header->pht_entry_num = 0;
    header->sht_entry_size = sizeof(ELFSection::Header);
    header->sht_entry_num = sections_.length();
    header->sht_strtab_index = 1;
  }

  void WriteSectionTable(Writer* w) {
    // Section headers table immediately follows file header.
690
    DCHECK(w->position() == sizeof(ELFHeader));
691 692 693 694 695

    Writer::Slot<ELFSection::Header> headers =
        w->CreateSlotsHere<ELFSection::Header>(sections_.length());

    // String table for section table is the first section.
696
    ELFStringTable* strtab = static_cast<ELFStringTable*>(SectionAt(1));
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
    strtab->AttachWriter(w);
    for (int i = 0, length = sections_.length();
         i < length;
         i++) {
      sections_[i]->PopulateHeader(headers.at(i), strtab);
    }
    strtab->DetachWriter();
  }

  int SectionHeaderPosition(uint32_t section_index) {
    return sizeof(ELFHeader) + sizeof(ELFSection::Header) * section_index;
  }

  void WriteSections(Writer* w) {
    Writer::Slot<ELFSection::Header> headers =
        w->SlotAt<ELFSection::Header>(sizeof(ELFHeader));

    for (int i = 0, length = sections_.length();
         i < length;
         i++) {
      sections_[i]->WriteBody(headers.at(i), w);
    }
  }

721
  Zone* zone_;
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
  ZoneList<ELFSection*> sections_;
};


class ELFSymbol BASE_EMBEDDED {
 public:
  enum Type {
    TYPE_NOTYPE = 0,
    TYPE_OBJECT = 1,
    TYPE_FUNC = 2,
    TYPE_SECTION = 3,
    TYPE_FILE = 4,
    TYPE_LOPROC = 13,
    TYPE_HIPROC = 15
  };

  enum Binding {
    BIND_LOCAL = 0,
    BIND_GLOBAL = 1,
    BIND_WEAK = 2,
    BIND_LOPROC = 13,
    BIND_HIPROC = 15
  };

  ELFSymbol(const char* name,
            uintptr_t value,
            uintptr_t size,
            Binding binding,
            Type type,
            uint16_t section)
      : name(name),
        value(value),
        size(size),
        info((binding << 4) | type),
        other(0),
        section(section) {
  }

  Binding binding() const {
    return static_cast<Binding>(info >> 4);
  }
763 764
#if (V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_X87 || \
     (V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_32_BIT))
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
  struct SerializedLayout {
    SerializedLayout(uint32_t name,
                     uintptr_t value,
                     uintptr_t size,
                     Binding binding,
                     Type type,
                     uint16_t section)
        : name(name),
          value(value),
          size(size),
          info((binding << 4) | type),
          other(0),
          section(section) {
    }

    uint32_t name;
    uintptr_t value;
    uintptr_t size;
    uint8_t info;
    uint8_t other;
    uint16_t section;
  };
787
#elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
  struct SerializedLayout {
    SerializedLayout(uint32_t name,
                     uintptr_t value,
                     uintptr_t size,
                     Binding binding,
                     Type type,
                     uint16_t section)
        : name(name),
          info((binding << 4) | type),
          other(0),
          section(section),
          value(value),
          size(size) {
    }

    uint32_t name;
    uint8_t info;
    uint8_t other;
    uint16_t section;
    uintptr_t value;
    uintptr_t size;
  };
#endif

812
  void Write(Writer::Slot<SerializedLayout> s, ELFStringTable* t) {
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
    // Convert symbol names from strings to indexes in the string table.
    s->name = t->Add(name);
    s->value = value;
    s->size = size;
    s->info = info;
    s->other = other;
    s->section = section;
  }

 private:
  const char* name;
  uintptr_t value;
  uintptr_t size;
  uint8_t info;
  uint8_t other;
  uint16_t section;
};


class ELFSymbolTable : public ELFSection {
 public:
834
  ELFSymbolTable(const char* name, Zone* zone)
835
      : ELFSection(name, TYPE_SYMTAB, sizeof(uintptr_t)),
836 837
        locals_(1, zone),
        globals_(1, zone) {
838 839 840 841 842 843 844 845 846 847 848 849 850
  }

  virtual void WriteBody(Writer::Slot<Header> header, Writer* w) {
    w->Align(header->alignment);
    int total_symbols = locals_.length() + globals_.length() + 1;
    header->offset = w->position();

    Writer::Slot<ELFSymbol::SerializedLayout> symbols =
        w->CreateSlotsHere<ELFSymbol::SerializedLayout>(total_symbols);

    header->size = w->position() - header->offset;

    // String table for this symbol table should follow it in the section table.
851 852
    ELFStringTable* strtab =
        static_cast<ELFStringTable*>(w->debug_object()->SectionAt(index() + 1));
853 854 855 856 857 858 859 860 861 862 863 864
    strtab->AttachWriter(w);
    symbols.at(0).set(ELFSymbol::SerializedLayout(0,
                                                  0,
                                                  0,
                                                  ELFSymbol::BIND_LOCAL,
                                                  ELFSymbol::TYPE_NOTYPE,
                                                  0));
    WriteSymbolsList(&locals_, symbols.at(1), strtab);
    WriteSymbolsList(&globals_, symbols.at(locals_.length() + 1), strtab);
    strtab->DetachWriter();
  }

865
  void Add(const ELFSymbol& symbol, Zone* zone) {
866
    if (symbol.binding() == ELFSymbol::BIND_LOCAL) {
867
      locals_.Add(symbol, zone);
868
    } else {
869
      globals_.Add(symbol, zone);
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
    }
  }

 protected:
  virtual void PopulateHeader(Writer::Slot<Header> header) {
    ELFSection::PopulateHeader(header);
    // We are assuming that string table will follow symbol table.
    header->link = index() + 1;
    header->info = locals_.length() + 1;
    header->entry_size = sizeof(ELFSymbol::SerializedLayout);
  }

 private:
  void WriteSymbolsList(const ZoneList<ELFSymbol>* src,
                        Writer::Slot<ELFSymbol::SerializedLayout> dst,
885
                        ELFStringTable* strtab) {
886 887 888 889 890 891 892 893 894 895
    for (int i = 0, len = src->length();
         i < len;
         i++) {
      src->at(i).Write(dst.at(i), strtab);
    }
  }

  ZoneList<ELFSymbol> locals_;
  ZoneList<ELFSymbol> globals_;
};
896
#endif  // defined(__ELF)
897 898


899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
class LineInfo : public Malloced {
 public:
  LineInfo() : pc_info_(10) {}

  void SetPosition(intptr_t pc, int pos, bool is_statement) {
    AddPCInfo(PCInfo(pc, pos, is_statement));
  }

  struct PCInfo {
    PCInfo(intptr_t pc, int pos, bool is_statement)
        : pc_(pc), pos_(pos), is_statement_(is_statement) {}

    intptr_t pc_;
    int pos_;
    bool is_statement_;
  };

  List<PCInfo>* pc_info() { return &pc_info_; }

 private:
  void AddPCInfo(const PCInfo& pc_info) { pc_info_.Add(pc_info); }

  List<PCInfo> pc_info_;
};


925 926
class CodeDescription BASE_EMBEDDED {
 public:
927
#if V8_TARGET_ARCH_X64
928 929 930 931 932 933 934 935
  enum StackState {
    POST_RBP_PUSH,
    POST_RBP_SET,
    POST_RBP_POP,
    STACK_STATE_MAX
  };
#endif

936 937
  CodeDescription(const char* name, Code* code, Handle<Script> script,
                  LineInfo* lineinfo, GDBJITInterface::CodeTag tag,
938
                  CompilationInfo* info)
939 940 941 942
      : name_(name),
        code_(code),
        script_(script),
        lineinfo_(lineinfo),
943
        tag_(tag),
944
        info_(info) {}
945

946
  const char* name() const {
947 948 949
    return name_;
  }

950
  LineInfo* lineinfo() const { return lineinfo_; }
951 952 953 954 955

  GDBJITInterface::CodeTag tag() const {
    return tag_;
  }

956 957 958 959 960 961 962 963
  CompilationInfo* info() const {
    return info_;
  }

  bool IsInfoAvailable() const {
    return info_ != NULL;
  }

964 965
  uintptr_t CodeStart() const {
    return reinterpret_cast<uintptr_t>(code_->instruction_start());
966 967
  }

968 969
  uintptr_t CodeEnd() const {
    return reinterpret_cast<uintptr_t>(code_->instruction_end());
970 971
  }

972 973 974 975 976
  uintptr_t CodeSize() const {
    return CodeEnd() - CodeStart();
  }

  bool IsLineInfoAvailable() {
977 978 979 980 981 982 983
    return !script_.is_null() &&
        script_->source()->IsString() &&
        script_->HasValidSource() &&
        script_->name()->IsString() &&
        lineinfo_ != NULL;
  }

984
#if V8_TARGET_ARCH_X64
985
  uintptr_t GetStackStateStartAddress(StackState state) const {
986
    DCHECK(state < STACK_STATE_MAX);
987 988
    return stack_state_start_addresses_[state];
  }
989

990
  void SetStackStateStartAddress(StackState state, uintptr_t addr) {
991
    DCHECK(state < STACK_STATE_MAX);
992 993 994 995
    stack_state_start_addresses_[state] = addr;
  }
#endif

996
  SmartArrayPointer<char> GetFilename() {
997 998 999 1000
    return String::cast(script_->name())->ToCString();
  }

  int GetScriptLineNumber(int pos) {
1001
    return script_->GetLineNumber(pos) + 1;
1002 1003
  }

1004

1005 1006 1007 1008
 private:
  const char* name_;
  Code* code_;
  Handle<Script> script_;
1009
  LineInfo* lineinfo_;
1010
  GDBJITInterface::CodeTag tag_;
1011
  CompilationInfo* info_;
1012
#if V8_TARGET_ARCH_X64
1013 1014
  uintptr_t stack_state_start_addresses_[STACK_STATE_MAX];
#endif
1015 1016
};

1017
#if defined(__ELF)
1018
static void CreateSymbolsTable(CodeDescription* desc,
1019
                               Zone* zone,
1020 1021
                               ELF* elf,
                               int text_section_index) {
1022
  ELFSymbolTable* symtab = new(zone) ELFSymbolTable(".symtab", zone);
1023
  ELFStringTable* strtab = new(zone) ELFStringTable(".strtab");
1024 1025

  // Symbol table should be followed by the linked string table.
1026 1027
  elf->AddSection(symtab);
  elf->AddSection(strtab);
1028 1029 1030 1031 1032 1033

  symtab->Add(ELFSymbol("V8 Code",
                        0,
                        0,
                        ELFSymbol::BIND_LOCAL,
                        ELFSymbol::TYPE_FILE,
1034 1035
                        ELFSection::INDEX_ABSOLUTE),
              zone);
1036

1037
  symtab->Add(ELFSymbol(desc->name(),
1038
                        0,
1039
                        desc->CodeSize(),
1040 1041
                        ELFSymbol::BIND_GLOBAL,
                        ELFSymbol::TYPE_FUNC,
1042 1043
                        text_section_index),
              zone);
1044
}
1045
#endif  // defined(__ELF)
1046 1047


1048
class DebugInfoSection : public DebugSection {
1049 1050
 public:
  explicit DebugInfoSection(CodeDescription* desc)
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
#if defined(__ELF)
      : ELFSection(".debug_info", TYPE_PROGBITS, 1),
#else
      : MachOSection("__debug_info",
                     "__DWARF",
                     1,
                     MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
#endif
        desc_(desc) { }

  // DWARF2 standard
  enum DWARF2LocationOp {
    DW_OP_reg0 = 0x50,
    DW_OP_reg1 = 0x51,
    DW_OP_reg2 = 0x52,
    DW_OP_reg3 = 0x53,
    DW_OP_reg4 = 0x54,
    DW_OP_reg5 = 0x55,
    DW_OP_reg6 = 0x56,
    DW_OP_reg7 = 0x57,
    DW_OP_fbreg = 0x91  // 1 param: SLEB128 offset
  };

  enum DWARF2Encoding {
    DW_ATE_ADDRESS = 0x1,
    DW_ATE_SIGNED = 0x5
  };
1078

1079
  bool WriteBodyInternal(Writer* w) {
1080
    uintptr_t cu_start = w->position();
1081 1082 1083 1084 1085 1086 1087
    Writer::Slot<uint32_t> size = w->CreateSlotHere<uint32_t>();
    uintptr_t start = w->position();
    w->Write<uint16_t>(2);  // DWARF version.
    w->Write<uint32_t>(0);  // Abbreviation table offset.
    w->Write<uint8_t>(sizeof(intptr_t));

    w->WriteULEB128(1);  // Abbreviation code.
1088
    w->WriteString(desc_->GetFilename().get());
1089 1090
    w->Write<intptr_t>(desc_->CodeStart());
    w->Write<intptr_t>(desc_->CodeStart() + desc_->CodeSize());
1091
    w->Write<uint32_t>(0);
1092 1093 1094 1095 1096 1097 1098

    uint32_t ty_offset = static_cast<uint32_t>(w->position() - cu_start);
    w->WriteULEB128(3);
    w->Write<uint8_t>(kPointerSize);
    w->WriteString("v8value");

    if (desc_->IsInfoAvailable()) {
1099
      Scope* scope = desc_->info()->scope();
1100 1101 1102 1103 1104 1105
      w->WriteULEB128(2);
      w->WriteString(desc_->name());
      w->Write<intptr_t>(desc_->CodeStart());
      w->Write<intptr_t>(desc_->CodeStart() + desc_->CodeSize());
      Writer::Slot<uint32_t> fb_block_size = w->CreateSlotHere<uint32_t>();
      uintptr_t fb_block_start = w->position();
danno@chromium.org's avatar
danno@chromium.org committed
1106
#if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
1107
      w->Write<uint8_t>(DW_OP_reg5);  // The frame pointer's here on ia32
1108
#elif V8_TARGET_ARCH_X64
1109
      w->Write<uint8_t>(DW_OP_reg6);  // and here on x64.
1110
#elif V8_TARGET_ARCH_ARM
1111
      UNIMPLEMENTED();
1112
#elif V8_TARGET_ARCH_MIPS
1113
      UNIMPLEMENTED();
1114 1115
#elif V8_TARGET_ARCH_MIPS64
      UNIMPLEMENTED();
1116 1117 1118 1119 1120
#else
#error Unsupported target architecture.
#endif
      fb_block_size.set(static_cast<uint32_t>(w->position() - fb_block_start));

1121 1122 1123
      int params = scope->num_parameters();
      int slots = scope->num_stack_slots();
      int context_slots = scope->ContextLocalCount();
1124 1125
      // The real slot ID is internal_slots + context_slot_id.
      int internal_slots = Context::MIN_CONTEXT_SLOTS;
1126
      int locals = scope->StackLocalCount();
1127 1128 1129 1130 1131
      int current_abbreviation = 4;

      for (int param = 0; param < params; ++param) {
        w->WriteULEB128(current_abbreviation++);
        w->WriteString(
1132
            scope->parameter(param)->name()->ToCString(DISALLOW_NULLS).get());
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
        w->Write<uint32_t>(ty_offset);
        Writer::Slot<uint32_t> block_size = w->CreateSlotHere<uint32_t>();
        uintptr_t block_start = w->position();
        w->Write<uint8_t>(DW_OP_fbreg);
        w->WriteSLEB128(
          JavaScriptFrameConstants::kLastParameterOffset +
              kPointerSize * (params - param - 1));
        block_size.set(static_cast<uint32_t>(w->position() - block_start));
      }

      EmbeddedVector<char, 256> buffer;
      StringBuilder builder(buffer.start(), buffer.length());

      for (int slot = 0; slot < slots; ++slot) {
        w->WriteULEB128(current_abbreviation++);
        builder.Reset();
        builder.AddFormatted("slot%d", slot);
        w->WriteString(builder.Finalize());
      }

      // See contexts.h for more information.
1154 1155 1156 1157 1158
      DCHECK(Context::MIN_CONTEXT_SLOTS == 4);
      DCHECK(Context::CLOSURE_INDEX == 0);
      DCHECK(Context::PREVIOUS_INDEX == 1);
      DCHECK(Context::EXTENSION_INDEX == 2);
      DCHECK(Context::GLOBAL_OBJECT_INDEX == 3);
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
      w->WriteULEB128(current_abbreviation++);
      w->WriteString(".closure");
      w->WriteULEB128(current_abbreviation++);
      w->WriteString(".previous");
      w->WriteULEB128(current_abbreviation++);
      w->WriteString(".extension");
      w->WriteULEB128(current_abbreviation++);
      w->WriteString(".global");

      for (int context_slot = 0;
           context_slot < context_slots;
           ++context_slot) {
        w->WriteULEB128(current_abbreviation++);
        builder.Reset();
        builder.AddFormatted("context_slot%d", context_slot + internal_slots);
        w->WriteString(builder.Finalize());
      }

1177 1178 1179
      ZoneList<Variable*> stack_locals(locals, scope->zone());
      ZoneList<Variable*> context_locals(context_slots, scope->zone());
      scope->CollectStackAndContextLocals(&stack_locals, &context_locals);
1180 1181 1182
      for (int local = 0; local < locals; ++local) {
        w->WriteULEB128(current_abbreviation++);
        w->WriteString(
1183
            stack_locals[local]->name()->ToCString(DISALLOW_NULLS).get());
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
        w->Write<uint32_t>(ty_offset);
        Writer::Slot<uint32_t> block_size = w->CreateSlotHere<uint32_t>();
        uintptr_t block_start = w->position();
        w->Write<uint8_t>(DW_OP_fbreg);
        w->WriteSLEB128(
          JavaScriptFrameConstants::kLocal0Offset -
              kPointerSize * local);
        block_size.set(static_cast<uint32_t>(w->position() - block_start));
      }

      {
        w->WriteULEB128(current_abbreviation++);
        w->WriteString("__function");
        w->Write<uint32_t>(ty_offset);
        Writer::Slot<uint32_t> block_size = w->CreateSlotHere<uint32_t>();
        uintptr_t block_start = w->position();
        w->Write<uint8_t>(DW_OP_fbreg);
        w->WriteSLEB128(JavaScriptFrameConstants::kFunctionOffset);
        block_size.set(static_cast<uint32_t>(w->position() - block_start));
      }

      {
        w->WriteULEB128(current_abbreviation++);
        w->WriteString("__context");
        w->Write<uint32_t>(ty_offset);
        Writer::Slot<uint32_t> block_size = w->CreateSlotHere<uint32_t>();
        uintptr_t block_start = w->position();
        w->Write<uint8_t>(DW_OP_fbreg);
        w->WriteSLEB128(StandardFrameConstants::kContextOffset);
        block_size.set(static_cast<uint32_t>(w->position() - block_start));
      }
1215 1216

      w->WriteULEB128(0);  // Terminate the sub program.
1217 1218
    }

1219
    w->WriteULEB128(0);  // Terminate the compile unit.
1220 1221 1222 1223 1224 1225 1226 1227 1228
    size.set(static_cast<uint32_t>(w->position() - start));
    return true;
  }

 private:
  CodeDescription* desc_;
};


1229
class DebugAbbrevSection : public DebugSection {
1230
 public:
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
  explicit DebugAbbrevSection(CodeDescription* desc)
#ifdef __ELF
      : ELFSection(".debug_abbrev", TYPE_PROGBITS, 1),
#else
      : MachOSection("__debug_abbrev",
                     "__DWARF",
                     1,
                     MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
#endif
        desc_(desc) { }
1241 1242 1243

  // DWARF2 standard, figure 14.
  enum DWARF2Tags {
1244 1245 1246 1247 1248 1249 1250
    DW_TAG_FORMAL_PARAMETER = 0x05,
    DW_TAG_POINTER_TYPE = 0xf,
    DW_TAG_COMPILE_UNIT = 0x11,
    DW_TAG_STRUCTURE_TYPE = 0x13,
    DW_TAG_BASE_TYPE = 0x24,
    DW_TAG_SUBPROGRAM = 0x2e,
    DW_TAG_VARIABLE = 0x34
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
  };

  // DWARF2 standard, figure 16.
  enum DWARF2ChildrenDetermination {
    DW_CHILDREN_NO = 0,
    DW_CHILDREN_YES = 1
  };

  // DWARF standard, figure 17.
  enum DWARF2Attribute {
1261
    DW_AT_LOCATION = 0x2,
1262
    DW_AT_NAME = 0x3,
1263
    DW_AT_BYTE_SIZE = 0xb,
1264 1265
    DW_AT_STMT_LIST = 0x10,
    DW_AT_LOW_PC = 0x11,
1266 1267 1268 1269
    DW_AT_HIGH_PC = 0x12,
    DW_AT_ENCODING = 0x3e,
    DW_AT_FRAME_BASE = 0x40,
    DW_AT_TYPE = 0x49
1270 1271 1272 1273 1274
  };

  // DWARF2 standard, figure 19.
  enum DWARF2AttributeForm {
    DW_FORM_ADDR = 0x1,
1275
    DW_FORM_BLOCK4 = 0x4,
1276
    DW_FORM_STRING = 0x8,
1277 1278 1279 1280 1281
    DW_FORM_DATA4 = 0x6,
    DW_FORM_BLOCK = 0x9,
    DW_FORM_DATA1 = 0xb,
    DW_FORM_FLAG = 0xc,
    DW_FORM_REF4 = 0x13
1282 1283
  };

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
  void WriteVariableAbbreviation(Writer* w,
                                 int abbreviation_code,
                                 bool has_value,
                                 bool is_parameter) {
    w->WriteULEB128(abbreviation_code);
    w->WriteULEB128(is_parameter ? DW_TAG_FORMAL_PARAMETER : DW_TAG_VARIABLE);
    w->Write<uint8_t>(DW_CHILDREN_NO);
    w->WriteULEB128(DW_AT_NAME);
    w->WriteULEB128(DW_FORM_STRING);
    if (has_value) {
      w->WriteULEB128(DW_AT_TYPE);
      w->WriteULEB128(DW_FORM_REF4);
      w->WriteULEB128(DW_AT_LOCATION);
      w->WriteULEB128(DW_FORM_BLOCK4);
    }
    w->WriteULEB128(0);
    w->WriteULEB128(0);
  }

1303
  bool WriteBodyInternal(Writer* w) {
1304 1305
    int current_abbreviation = 1;
    bool extra_info = desc_->IsInfoAvailable();
1306
    DCHECK(desc_->IsLineInfoAvailable());
1307
    w->WriteULEB128(current_abbreviation++);
1308
    w->WriteULEB128(DW_TAG_COMPILE_UNIT);
1309
    w->Write<uint8_t>(extra_info ? DW_CHILDREN_YES : DW_CHILDREN_NO);
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
    w->WriteULEB128(DW_AT_NAME);
    w->WriteULEB128(DW_FORM_STRING);
    w->WriteULEB128(DW_AT_LOW_PC);
    w->WriteULEB128(DW_FORM_ADDR);
    w->WriteULEB128(DW_AT_HIGH_PC);
    w->WriteULEB128(DW_FORM_ADDR);
    w->WriteULEB128(DW_AT_STMT_LIST);
    w->WriteULEB128(DW_FORM_DATA4);
    w->WriteULEB128(0);
    w->WriteULEB128(0);
1320 1321

    if (extra_info) {
1322 1323 1324 1325
      Scope* scope = desc_->info()->scope();
      int params = scope->num_parameters();
      int slots = scope->num_stack_slots();
      int context_slots = scope->ContextLocalCount();
1326 1327
      // The real slot ID is internal_slots + context_slot_id.
      int internal_slots = Context::MIN_CONTEXT_SLOTS;
1328
      int locals = scope->StackLocalCount();
1329 1330
      // Total children is params + slots + context_slots + internal_slots +
      // locals + 2 (__function and __context).
1331 1332 1333 1334 1335

      // The extra duplication below seems to be necessary to keep
      // gdb from getting upset on OSX.
      w->WriteULEB128(current_abbreviation++);  // Abbreviation code.
      w->WriteULEB128(DW_TAG_SUBPROGRAM);
1336
      w->Write<uint8_t>(DW_CHILDREN_YES);
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
      w->WriteULEB128(DW_AT_NAME);
      w->WriteULEB128(DW_FORM_STRING);
      w->WriteULEB128(DW_AT_LOW_PC);
      w->WriteULEB128(DW_FORM_ADDR);
      w->WriteULEB128(DW_AT_HIGH_PC);
      w->WriteULEB128(DW_FORM_ADDR);
      w->WriteULEB128(DW_AT_FRAME_BASE);
      w->WriteULEB128(DW_FORM_BLOCK4);
      w->WriteULEB128(0);
      w->WriteULEB128(0);

      w->WriteULEB128(current_abbreviation++);
      w->WriteULEB128(DW_TAG_STRUCTURE_TYPE);
      w->Write<uint8_t>(DW_CHILDREN_NO);
      w->WriteULEB128(DW_AT_BYTE_SIZE);
      w->WriteULEB128(DW_FORM_DATA1);
      w->WriteULEB128(DW_AT_NAME);
      w->WriteULEB128(DW_FORM_STRING);
      w->WriteULEB128(0);
      w->WriteULEB128(0);

      for (int param = 0; param < params; ++param) {
        WriteVariableAbbreviation(w, current_abbreviation++, true, true);
      }

      for (int slot = 0; slot < slots; ++slot) {
        WriteVariableAbbreviation(w, current_abbreviation++, false, false);
      }

      for (int internal_slot = 0;
           internal_slot < internal_slots;
           ++internal_slot) {
        WriteVariableAbbreviation(w, current_abbreviation++, false, false);
      }

      for (int context_slot = 0;
           context_slot < context_slots;
           ++context_slot) {
        WriteVariableAbbreviation(w, current_abbreviation++, false, false);
      }

      for (int local = 0; local < locals; ++local) {
        WriteVariableAbbreviation(w, current_abbreviation++, true, false);
      }

      // The function.
      WriteVariableAbbreviation(w, current_abbreviation++, true, false);

      // The context.
      WriteVariableAbbreviation(w, current_abbreviation++, true, false);

1388
      w->WriteULEB128(0);  // Terminate the sibling list.
1389 1390 1391
    }

    w->WriteULEB128(0);  // Terminate the table.
1392 1393
    return true;
  }
1394 1395 1396

 private:
  CodeDescription* desc_;
1397 1398 1399
};


1400
class DebugLineSection : public DebugSection {
1401 1402
 public:
  explicit DebugLineSection(CodeDescription* desc)
1403
#ifdef __ELF
1404
      : ELFSection(".debug_line", TYPE_PROGBITS, 1),
1405 1406 1407 1408 1409 1410
#else
      : MachOSection("__debug_line",
                     "__DWARF",
                     1,
                     MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
#endif
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
        desc_(desc) { }

  // DWARF2 standard, figure 34.
  enum DWARF2Opcodes {
    DW_LNS_COPY = 1,
    DW_LNS_ADVANCE_PC = 2,
    DW_LNS_ADVANCE_LINE = 3,
    DW_LNS_SET_FILE = 4,
    DW_LNS_SET_COLUMN = 5,
    DW_LNS_NEGATE_STMT = 6
  };

  // DWARF2 standard, figure 35.
  enum DWARF2ExtendedOpcode {
    DW_LNE_END_SEQUENCE = 1,
    DW_LNE_SET_ADDRESS = 2,
    DW_LNE_DEFINE_FILE = 3
  };

1430
  bool WriteBodyInternal(Writer* w) {
1431 1432 1433 1434
    // Write prologue.
    Writer::Slot<uint32_t> total_length = w->CreateSlotHere<uint32_t>();
    uintptr_t start = w->position();

1435 1436 1437 1438 1439 1440
    // Used for special opcodes
    const int8_t line_base = 1;
    const uint8_t line_range = 7;
    const int8_t max_line_incr = (line_base + line_range - 1);
    const uint8_t opcode_base = DW_LNS_NEGATE_STMT + 1;

1441 1442 1443 1444 1445
    w->Write<uint16_t>(2);  // Field version.
    Writer::Slot<uint32_t> prologue_length = w->CreateSlotHere<uint32_t>();
    uintptr_t prologue_start = w->position();
    w->Write<uint8_t>(1);  // Field minimum_instruction_length.
    w->Write<uint8_t>(1);  // Field default_is_stmt.
1446 1447 1448
    w->Write<int8_t>(line_base);  // Field line_base.
    w->Write<uint8_t>(line_range);  // Field line_range.
    w->Write<uint8_t>(opcode_base);  // Field opcode_base.
1449 1450 1451 1452 1453 1454 1455
    w->Write<uint8_t>(0);  // DW_LNS_COPY operands count.
    w->Write<uint8_t>(1);  // DW_LNS_ADVANCE_PC operands count.
    w->Write<uint8_t>(1);  // DW_LNS_ADVANCE_LINE operands count.
    w->Write<uint8_t>(1);  // DW_LNS_SET_FILE operands count.
    w->Write<uint8_t>(1);  // DW_LNS_SET_COLUMN operands count.
    w->Write<uint8_t>(0);  // DW_LNS_NEGATE_STMT operands count.
    w->Write<uint8_t>(0);  // Empty include_directories sequence.
1456
    w->WriteString(desc_->GetFilename().get());  // File name.
1457 1458 1459 1460 1461 1462 1463
    w->WriteULEB128(0);  // Current directory.
    w->WriteULEB128(0);  // Unknown modification time.
    w->WriteULEB128(0);  // Unknown file size.
    w->Write<uint8_t>(0);
    prologue_length.set(static_cast<uint32_t>(w->position() - prologue_start));

    WriteExtendedOpcode(w, DW_LNE_SET_ADDRESS, sizeof(intptr_t));
1464
    w->Write<intptr_t>(desc_->CodeStart());
1465
    w->Write<uint8_t>(DW_LNS_COPY);
1466 1467 1468 1469 1470

    intptr_t pc = 0;
    intptr_t line = 1;
    bool is_statement = true;

1471
    List<LineInfo::PCInfo>* pc_info = desc_->lineinfo()->pc_info();
1472
    pc_info->Sort(&ComparePCInfo);
1473 1474 1475

    int pc_info_length = pc_info->length();
    for (int i = 0; i < pc_info_length; i++) {
1476
      LineInfo::PCInfo* info = &pc_info->at(i);
1477
      DCHECK(info->pc_ >= pc);
1478 1479 1480 1481 1482 1483

      // Reduce bloating in the debug line table by removing duplicate line
      // entries (per DWARF2 standard).
      intptr_t  new_line = desc_->GetScriptLineNumber(info->pos_);
      if (new_line == line) {
        continue;
1484
      }
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494

      // Mark statement boundaries.  For a better debugging experience, mark
      // the last pc address in the function as a statement (e.g. "}"), so that
      // a user can see the result of the last line executed in the function,
      // should control reach the end.
      if ((i+1) == pc_info_length) {
        if (!is_statement) {
          w->Write<uint8_t>(DW_LNS_NEGATE_STMT);
        }
      } else if (is_statement != info->is_statement_) {
1495 1496 1497
        w->Write<uint8_t>(DW_LNS_NEGATE_STMT);
        is_statement = !is_statement;
      }
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521

      // Generate special opcodes, if possible.  This results in more compact
      // debug line tables.  See the DWARF 2.0 standard to learn more about
      // special opcodes.
      uintptr_t pc_diff = info->pc_ - pc;
      intptr_t line_diff = new_line - line;

      // Compute special opcode (see DWARF 2.0 standard)
      intptr_t special_opcode = (line_diff - line_base) +
                                (line_range * pc_diff) + opcode_base;

      // If special_opcode is less than or equal to 255, it can be used as a
      // special opcode.  If line_diff is larger than the max line increment
      // allowed for a special opcode, or if line_diff is less than the minimum
      // line that can be added to the line register (i.e. line_base), then
      // special_opcode can't be used.
      if ((special_opcode >= opcode_base) && (special_opcode <= 255) &&
          (line_diff <= max_line_incr) && (line_diff >= line_base)) {
        w->Write<uint8_t>(special_opcode);
      } else {
        w->Write<uint8_t>(DW_LNS_ADVANCE_PC);
        w->WriteSLEB128(pc_diff);
        w->Write<uint8_t>(DW_LNS_ADVANCE_LINE);
        w->WriteSLEB128(line_diff);
1522 1523
        w->Write<uint8_t>(DW_LNS_COPY);
      }
1524 1525 1526 1527

      // Increment the pc and line operands.
      pc += pc_diff;
      line += line_diff;
1528
    }
1529 1530 1531 1532
    // Advance the pc to the end of the routine, since the end sequence opcode
    // requires this.
    w->Write<uint8_t>(DW_LNS_ADVANCE_PC);
    w->WriteSLEB128(desc_->CodeSize() - pc);
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
    WriteExtendedOpcode(w, DW_LNE_END_SEQUENCE, 0);
    total_length.set(static_cast<uint32_t>(w->position() - start));
    return true;
  }

 private:
  void WriteExtendedOpcode(Writer* w,
                           DWARF2ExtendedOpcode op,
                           size_t operands_size) {
    w->Write<uint8_t>(0);
    w->WriteULEB128(operands_size + 1);
    w->Write<uint8_t>(op);
  }

1547 1548
  static int ComparePCInfo(const LineInfo::PCInfo* a,
                           const LineInfo::PCInfo* b) {
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
    if (a->pc_ == b->pc_) {
      if (a->is_statement_ != b->is_statement_) {
        return b->is_statement_ ? +1 : -1;
      }
      return 0;
    } else if (a->pc_ > b->pc_) {
      return +1;
    } else {
      return -1;
    }
  }

  CodeDescription* desc_;
};


1565
#if V8_TARGET_ARCH_X64
1566

1567
class UnwindInfoSection : public DebugSection {
1568
 public:
1569
  explicit UnwindInfoSection(CodeDescription* desc);
1570
  virtual bool WriteBodyInternal(Writer* w);
1571

1572 1573
  int WriteCIE(Writer* w);
  void WriteFDE(Writer* w, int);
1574

1575 1576 1577 1578
  void WriteFDEStateOnEntry(Writer* w);
  void WriteFDEStateAfterRBPPush(Writer* w);
  void WriteFDEStateAfterRBPSet(Writer* w);
  void WriteFDEStateAfterRBPPop(Writer* w);
1579

1580
  void WriteLength(Writer* w,
1581 1582 1583 1584
                   Writer::Slot<uint32_t>* length_slot,
                   int initial_position);

 private:
1585
  CodeDescription* desc_;
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635

  // DWARF3 Specification, Table 7.23
  enum CFIInstructions {
    DW_CFA_ADVANCE_LOC = 0x40,
    DW_CFA_OFFSET = 0x80,
    DW_CFA_RESTORE = 0xC0,
    DW_CFA_NOP = 0x00,
    DW_CFA_SET_LOC = 0x01,
    DW_CFA_ADVANCE_LOC1 = 0x02,
    DW_CFA_ADVANCE_LOC2 = 0x03,
    DW_CFA_ADVANCE_LOC4 = 0x04,
    DW_CFA_OFFSET_EXTENDED = 0x05,
    DW_CFA_RESTORE_EXTENDED = 0x06,
    DW_CFA_UNDEFINED = 0x07,
    DW_CFA_SAME_VALUE = 0x08,
    DW_CFA_REGISTER = 0x09,
    DW_CFA_REMEMBER_STATE = 0x0A,
    DW_CFA_RESTORE_STATE = 0x0B,
    DW_CFA_DEF_CFA = 0x0C,
    DW_CFA_DEF_CFA_REGISTER = 0x0D,
    DW_CFA_DEF_CFA_OFFSET = 0x0E,

    DW_CFA_DEF_CFA_EXPRESSION = 0x0F,
    DW_CFA_EXPRESSION = 0x10,
    DW_CFA_OFFSET_EXTENDED_SF = 0x11,
    DW_CFA_DEF_CFA_SF = 0x12,
    DW_CFA_DEF_CFA_OFFSET_SF = 0x13,
    DW_CFA_VAL_OFFSET = 0x14,
    DW_CFA_VAL_OFFSET_SF = 0x15,
    DW_CFA_VAL_EXPRESSION = 0x16
  };

  // System V ABI, AMD64 Supplement, Version 0.99.5, Figure 3.36
  enum RegisterMapping {
    // Only the relevant ones have been added to reduce clutter.
    AMD64_RBP = 6,
    AMD64_RSP = 7,
    AMD64_RA = 16
  };

  enum CFIConstants {
    CIE_ID = 0,
    CIE_VERSION = 1,
    CODE_ALIGN_FACTOR = 1,
    DATA_ALIGN_FACTOR = 1,
    RETURN_ADDRESS_REGISTER = AMD64_RA
  };
};


1636
void UnwindInfoSection::WriteLength(Writer* w,
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
                                    Writer::Slot<uint32_t>* length_slot,
                                    int initial_position) {
  uint32_t align = (w->position() - initial_position) % kPointerSize;

  if (align != 0) {
    for (uint32_t i = 0; i < (kPointerSize - align); i++) {
      w->Write<uint8_t>(DW_CFA_NOP);
    }
  }

1647
  DCHECK((w->position() - initial_position) % kPointerSize == 0);
1648 1649 1650 1651
  length_slot->set(w->position() - initial_position);
}


1652
UnwindInfoSection::UnwindInfoSection(CodeDescription* desc)
1653 1654 1655 1656 1657 1658 1659
#ifdef __ELF
    : ELFSection(".eh_frame", TYPE_X86_64_UNWIND, 1),
#else
    : MachOSection("__eh_frame", "__TEXT", sizeof(uintptr_t),
                   MachOSection::S_REGULAR),
#endif
      desc_(desc) { }
1660

1661
int UnwindInfoSection::WriteCIE(Writer* w) {
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
  Writer::Slot<uint32_t> cie_length_slot = w->CreateSlotHere<uint32_t>();
  uint32_t cie_position = w->position();

  // Write out the CIE header. Currently no 'common instructions' are
  // emitted onto the CIE; every FDE has its own set of instructions.

  w->Write<uint32_t>(CIE_ID);
  w->Write<uint8_t>(CIE_VERSION);
  w->Write<uint8_t>(0);  // Null augmentation string.
  w->WriteSLEB128(CODE_ALIGN_FACTOR);
  w->WriteSLEB128(DATA_ALIGN_FACTOR);
  w->Write<uint8_t>(RETURN_ADDRESS_REGISTER);

  WriteLength(w, &cie_length_slot, cie_position);

  return cie_position;
}


1681
void UnwindInfoSection::WriteFDE(Writer* w, int cie_position) {
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
  // The only FDE for this function. The CFA is the current RBP.
  Writer::Slot<uint32_t> fde_length_slot = w->CreateSlotHere<uint32_t>();
  int fde_position = w->position();
  w->Write<int32_t>(fde_position - cie_position + 4);

  w->Write<uintptr_t>(desc_->CodeStart());
  w->Write<uintptr_t>(desc_->CodeSize());

  WriteFDEStateOnEntry(w);
  WriteFDEStateAfterRBPPush(w);
  WriteFDEStateAfterRBPSet(w);
  WriteFDEStateAfterRBPPop(w);

  WriteLength(w, &fde_length_slot, fde_position);
}


1699
void UnwindInfoSection::WriteFDEStateOnEntry(Writer* w) {
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
  // The first state, just after the control has been transferred to the the
  // function.

  // RBP for this function will be the value of RSP after pushing the RBP
  // for the previous function. The previous RBP has not been pushed yet.
  w->Write<uint8_t>(DW_CFA_DEF_CFA_SF);
  w->WriteULEB128(AMD64_RSP);
  w->WriteSLEB128(-kPointerSize);

  // The RA is stored at location CFA + kCallerPCOffset. This is an invariant,
  // and hence omitted from the next states.
  w->Write<uint8_t>(DW_CFA_OFFSET_EXTENDED);
  w->WriteULEB128(AMD64_RA);
  w->WriteSLEB128(StandardFrameConstants::kCallerPCOffset);

  // The RBP of the previous function is still in RBP.
  w->Write<uint8_t>(DW_CFA_SAME_VALUE);
  w->WriteULEB128(AMD64_RBP);

  // Last location described by this entry.
  w->Write<uint8_t>(DW_CFA_SET_LOC);
  w->Write<uint64_t>(
      desc_->GetStackStateStartAddress(CodeDescription::POST_RBP_PUSH));
}


1726
void UnwindInfoSection::WriteFDEStateAfterRBPPush(Writer* w) {
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
  // The second state, just after RBP has been pushed.

  // RBP / CFA for this function is now the current RSP, so just set the
  // offset from the previous rule (from -8) to 0.
  w->Write<uint8_t>(DW_CFA_DEF_CFA_OFFSET);
  w->WriteULEB128(0);

  // The previous RBP is stored at CFA + kCallerFPOffset. This is an invariant
  // in this and the next state, and hence omitted in the next state.
  w->Write<uint8_t>(DW_CFA_OFFSET_EXTENDED);
  w->WriteULEB128(AMD64_RBP);
  w->WriteSLEB128(StandardFrameConstants::kCallerFPOffset);

  // Last location described by this entry.
  w->Write<uint8_t>(DW_CFA_SET_LOC);
  w->Write<uint64_t>(
      desc_->GetStackStateStartAddress(CodeDescription::POST_RBP_SET));
}


1747
void UnwindInfoSection::WriteFDEStateAfterRBPSet(Writer* w) {
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
  // The third state, after the RBP has been set.

  // The CFA can now directly be set to RBP.
  w->Write<uint8_t>(DW_CFA_DEF_CFA);
  w->WriteULEB128(AMD64_RBP);
  w->WriteULEB128(0);

  // Last location described by this entry.
  w->Write<uint8_t>(DW_CFA_SET_LOC);
  w->Write<uint64_t>(
      desc_->GetStackStateStartAddress(CodeDescription::POST_RBP_POP));
}


1762
void UnwindInfoSection::WriteFDEStateAfterRBPPop(Writer* w) {
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
  // The fourth (final) state. The RBP has been popped (just before issuing a
  // return).

  // The CFA can is now calculated in the same way as in the first state.
  w->Write<uint8_t>(DW_CFA_DEF_CFA_SF);
  w->WriteULEB128(AMD64_RSP);
  w->WriteSLEB128(-kPointerSize);

  // The RBP
  w->Write<uint8_t>(DW_CFA_OFFSET_EXTENDED);
  w->WriteULEB128(AMD64_RBP);
  w->WriteSLEB128(StandardFrameConstants::kCallerFPOffset);

  // Last location described by this entry.
  w->Write<uint8_t>(DW_CFA_SET_LOC);
  w->Write<uint64_t>(desc_->CodeEnd());
}


1782
bool UnwindInfoSection::WriteBodyInternal(Writer* w) {
1783 1784 1785 1786 1787 1788 1789 1790
  uint32_t cie_position = WriteCIE(w);
  WriteFDE(w, cie_position);
  return true;
}


#endif  // V8_TARGET_ARCH_X64

1791 1792 1793
static void CreateDWARFSections(CodeDescription* desc,
                                Zone* zone,
                                DebugObject* obj) {
1794
  if (desc->IsLineInfoAvailable()) {
1795 1796 1797
    obj->AddSection(new(zone) DebugInfoSection(desc));
    obj->AddSection(new(zone) DebugAbbrevSection(desc));
    obj->AddSection(new(zone) DebugLineSection(desc));
1798
  }
1799
#if V8_TARGET_ARCH_X64
1800
  obj->AddSection(new(zone) UnwindInfoSection(desc));
1801
#endif
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
}


// -------------------------------------------------------------------
// Binary GDB JIT Interface as described in
//   http://sourceware.org/gdb/onlinedocs/gdb/Declarations.html
extern "C" {
  typedef enum {
    JIT_NOACTION = 0,
    JIT_REGISTER_FN,
    JIT_UNREGISTER_FN
  } JITAction;

  struct JITCodeEntry {
    JITCodeEntry* next_;
    JITCodeEntry* prev_;
    Address symfile_addr_;
    uint64_t symfile_size_;
  };

  struct JITDescriptor {
    uint32_t version_;
    uint32_t action_flag_;
1825 1826
    JITCodeEntry* relevant_entry_;
    JITCodeEntry* first_entry_;
1827 1828 1829 1830 1831 1832
  };

  // GDB will place breakpoint into this function.
  // To prevent GCC from inlining or removing it we place noinline attribute
  // and inline assembler statement inside.
  void __attribute__((noinline)) __jit_debug_register_code() {
1833
    __asm__("");
1834 1835 1836 1837 1838 1839
  }

  // GDB will inspect contents of this descriptor.
  // Static initialization is necessary to prevent GDB from seeing
  // uninitialized descriptor.
  JITDescriptor __jit_debug_descriptor = { 1, 0, 0, 0 };
1840 1841

#ifdef OBJECT_PRINT
1842
  void __gdb_print_v8_object(Object* object) {
1843 1844
    OFStream os(stdout);
    object->Print(os);
1845
    os << std::flush;
1846 1847
  }
#endif
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
}


static JITCodeEntry* CreateCodeEntry(Address symfile_addr,
                                     uintptr_t symfile_size) {
  JITCodeEntry* entry = static_cast<JITCodeEntry*>(
      malloc(sizeof(JITCodeEntry) + symfile_size));

  entry->symfile_addr_ = reinterpret_cast<Address>(entry + 1);
  entry->symfile_size_ = symfile_size;
1858
  MemCopy(entry->symfile_addr_, symfile_addr, symfile_size);
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870

  entry->prev_ = entry->next_ = NULL;

  return entry;
}


static void DestroyCodeEntry(JITCodeEntry* entry) {
  free(entry);
}


1871 1872 1873
static void RegisterCodeEntry(JITCodeEntry* entry,
                              bool dump_if_enabled,
                              const char* name_hint) {
1874
#if defined(DEBUG) && !V8_OS_WIN
1875
  static int file_num = 0;
1876
  if (FLAG_gdbjit_dump && dump_if_enabled) {
1877 1878 1879 1880 1881
    static const int kMaxFileNameSize = 64;
    static const char* kElfFilePrefix = "/tmp/elfdump";
    static const char* kObjFileExt = ".o";
    char file_name[64];

1882 1883 1884 1885 1886 1887
    SNPrintF(Vector<char>(file_name, kMaxFileNameSize),
             "%s%s%d%s",
             kElfFilePrefix,
             (name_hint != NULL) ? name_hint : "",
             file_num++,
             kObjFileExt);
1888 1889 1890 1891
    WriteBytes(file_name, entry->symfile_addr_, entry->symfile_size_);
  }
#endif

1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
  entry->next_ = __jit_debug_descriptor.first_entry_;
  if (entry->next_ != NULL) entry->next_->prev_ = entry;
  __jit_debug_descriptor.first_entry_ =
      __jit_debug_descriptor.relevant_entry_ = entry;

  __jit_debug_descriptor.action_flag_ = JIT_REGISTER_FN;
  __jit_debug_register_code();
}


static void UnregisterCodeEntry(JITCodeEntry* entry) {
  if (entry->prev_ != NULL) {
    entry->prev_->next_ = entry->next_;
  } else {
    __jit_debug_descriptor.first_entry_ = entry->next_;
  }

  if (entry->next_ != NULL) {
    entry->next_->prev_ = entry->prev_;
  }

  __jit_debug_descriptor.relevant_entry_ = entry;
  __jit_debug_descriptor.action_flag_ = JIT_UNREGISTER_FN;
  __jit_debug_register_code();
}


1919
static JITCodeEntry* CreateELFObject(CodeDescription* desc, Isolate* isolate) {
1920
#ifdef __MACH_O
1921 1922
  Zone zone(isolate);
  MachO mach_o(&zone);
1923 1924
  Writer w(&mach_o);

1925 1926 1927
  mach_o.AddSection(new(&zone) MachOTextSection(kCodeAlignment,
                                                desc->CodeStart(),
                                                desc->CodeSize()));
1928

1929
  CreateDWARFSections(desc, &zone, &mach_o);
1930

1931 1932
  mach_o.Write(&w, desc->CodeStart(), desc->CodeSize());
#else
1933 1934
  Zone zone(isolate);
  ELF elf(&zone);
1935 1936 1937
  Writer w(&elf);

  int text_section_index = elf.AddSection(
1938
      new(&zone) FullHeaderELFSection(
1939 1940 1941 1942 1943 1944
          ".text",
          ELFSection::TYPE_NOBITS,
          kCodeAlignment,
          desc->CodeStart(),
          0,
          desc->CodeSize(),
1945
          ELFSection::FLAG_ALLOC | ELFSection::FLAG_EXEC));
1946

1947
  CreateSymbolsTable(desc, &zone, &elf, text_section_index);
1948

1949
  CreateDWARFSections(desc, &zone, &elf);
1950 1951

  elf.Write(&w);
1952
#endif
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962

  return CreateCodeEntry(w.buffer(), w.position());
}


static bool SameCodeObjects(void* key1, void* key2) {
  return key1 == key2;
}


1963 1964 1965 1966 1967 1968 1969
static HashMap* GetEntries() {
  static HashMap* entries = NULL;
  if (entries == NULL) {
    entries = new HashMap(&SameCodeObjects);
  }
  return entries;
}
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986


static uint32_t HashForCodeObject(Code* code) {
  static const uintptr_t kGoldenRatio = 2654435761u;
  uintptr_t hash = reinterpret_cast<uintptr_t>(code->address());
  return static_cast<uint32_t>((hash >> kCodeAlignmentBits) * kGoldenRatio);
}


static const intptr_t kLineInfoTag = 0x1;


static bool IsLineInfoTagged(void* ptr) {
  return 0 != (reinterpret_cast<intptr_t>(ptr) & kLineInfoTag);
}


1987
static void* TagLineInfo(LineInfo* ptr) {
1988 1989 1990 1991 1992
  return reinterpret_cast<void*>(
      reinterpret_cast<intptr_t>(ptr) | kLineInfoTag);
}


1993 1994 1995
static LineInfo* UntagLineInfo(void* ptr) {
  return reinterpret_cast<LineInfo*>(reinterpret_cast<intptr_t>(ptr) &
                                     ~kLineInfoTag);
1996 1997 1998
}


1999
void GDBJITInterface::AddCode(Handle<Name> name,
2000
                              Handle<Script> script,
2001 2002
                              Handle<Code> code,
                              CompilationInfo* info) {
2003 2004
  if (!FLAG_gdbjit) return;

2005
  Script::InitLineEnds(script);
2006

2007 2008 2009
  if (!name.is_null() && name->IsString()) {
    SmartArrayPointer<char> name_cstring =
        Handle<String>::cast(name)->ToCString(DISALLOW_NULLS);
2010 2011
    AddCode(name_cstring.get(), *code, GDBJITInterface::FUNCTION, *script,
            info);
2012
  } else {
2013
    AddCode("", *code, GDBJITInterface::FUNCTION, *script, info);
2014 2015 2016
  }
}

2017

2018
static void AddUnwindInfo(CodeDescription* desc) {
2019
#if V8_TARGET_ARCH_X64
2020 2021
  if (desc->tag() == GDBJITInterface::FUNCTION) {
    // To avoid propagating unwinding information through
2022 2023
    // compilation pipeline we use an approximation.
    // For most use cases this should not affect usability.
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
    static const int kFramePointerPushOffset = 1;
    static const int kFramePointerSetOffset = 4;
    static const int kFramePointerPopOffset = -3;

    uintptr_t frame_pointer_push_address =
        desc->CodeStart() + kFramePointerPushOffset;

    uintptr_t frame_pointer_set_address =
        desc->CodeStart() + kFramePointerSetOffset;

    uintptr_t frame_pointer_pop_address =
        desc->CodeEnd() + kFramePointerPopOffset;

    desc->SetStackStateStartAddress(CodeDescription::POST_RBP_PUSH,
                                    frame_pointer_push_address);
    desc->SetStackStateStartAddress(CodeDescription::POST_RBP_SET,
                                    frame_pointer_set_address);
    desc->SetStackStateStartAddress(CodeDescription::POST_RBP_POP,
                                    frame_pointer_pop_address);
2043
  } else {
2044 2045 2046 2047 2048 2049
    desc->SetStackStateStartAddress(CodeDescription::POST_RBP_PUSH,
                                    desc->CodeStart());
    desc->SetStackStateStartAddress(CodeDescription::POST_RBP_SET,
                                    desc->CodeStart());
    desc->SetStackStateStartAddress(CodeDescription::POST_RBP_POP,
                                    desc->CodeEnd());
2050
  }
2051
#endif  // V8_TARGET_ARCH_X64
2052 2053 2054
}


2055
static base::LazyMutex mutex = LAZY_MUTEX_INITIALIZER;
2056 2057


2058 2059
void GDBJITInterface::AddCode(const char* name,
                              Code* code,
2060
                              GDBJITInterface::CodeTag tag,
2061 2062
                              Script* script,
                              CompilationInfo* info) {
2063
  base::LockGuard<base::Mutex> lock_guard(mutex.Pointer());
2064
  DisallowHeapAllocation no_gc;
2065

2066
  HashMap::Entry* e = GetEntries()->Lookup(code, HashForCodeObject(code), true);
2067 2068
  if (e->value != NULL && !IsLineInfoTagged(e->value)) return;

2069
  LineInfo* lineinfo = UntagLineInfo(e->value);
2070 2071 2072 2073
  CodeDescription code_desc(name,
                            code,
                            script != NULL ? Handle<Script>(script)
                                           : Handle<Script>(),
2074
                            lineinfo,
2075 2076
                            tag,
                            info);
2077

2078
  if (!FLAG_gdbjit_full && !code_desc.IsLineInfoAvailable()) {
2079
    delete lineinfo;
2080
    GetEntries()->Remove(code, HashForCodeObject(code));
2081 2082 2083
    return;
  }

2084
  AddUnwindInfo(&code_desc);
2085 2086
  Isolate* isolate = code->GetIsolate();
  JITCodeEntry* entry = CreateELFObject(&code_desc, isolate);
2087
  DCHECK(!IsLineInfoTagged(entry));
2088 2089 2090 2091

  delete lineinfo;
  e->value = entry;

2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
  const char* name_hint = NULL;
  bool should_dump = false;
  if (FLAG_gdbjit_dump) {
    if (strlen(FLAG_gdbjit_dump_filter) == 0) {
      name_hint = name;
      should_dump = true;
    } else if (name != NULL) {
      name_hint = strstr(name, FLAG_gdbjit_dump_filter);
      should_dump = (name_hint != NULL);
    }
  }
  RegisterCodeEntry(entry, should_dump, name_hint);
2104 2105 2106 2107 2108 2109
}


void GDBJITInterface::RemoveCode(Code* code) {
  if (!FLAG_gdbjit) return;

2110
  base::LockGuard<base::Mutex> lock_guard(mutex.Pointer());
2111 2112 2113
  HashMap::Entry* e = GetEntries()->Lookup(code,
                                           HashForCodeObject(code),
                                           false);
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
  if (e == NULL) return;

  if (IsLineInfoTagged(e->value)) {
    delete UntagLineInfo(e->value);
  } else {
    JITCodeEntry* entry = static_cast<JITCodeEntry*>(e->value);
    UnregisterCodeEntry(entry);
    DestroyCodeEntry(entry);
  }
  e->value = NULL;
2124
  GetEntries()->Remove(code, HashForCodeObject(code));
2125 2126 2127
}


2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145
void GDBJITInterface::RemoveCodeRange(Address start, Address end) {
  HashMap* entries = GetEntries();
  Zone zone(Isolate::Current());
  ZoneList<Code*> dead_codes(1, &zone);

  for (HashMap::Entry* e = entries->Start(); e != NULL; e = entries->Next(e)) {
    Code* code = reinterpret_cast<Code*>(e->key);
    if (code->address() >= start && code->address() < end) {
      dead_codes.Add(code, &zone);
    }
  }

  for (int i = 0; i < dead_codes.length(); i++) {
    RemoveCode(dead_codes.at(i));
  }
}


2146
static void RegisterDetailedLineInfo(Code* code, LineInfo* line_info) {
2147
  base::LockGuard<base::Mutex> lock_guard(mutex.Pointer());
2148
  DCHECK(!IsLineInfoTagged(line_info));
2149
  HashMap::Entry* e = GetEntries()->Lookup(code, HashForCodeObject(code), true);
2150
  DCHECK(e->value == NULL);
2151 2152 2153 2154
  e->value = TagLineInfo(line_info);
}


2155 2156 2157
void GDBJITInterface::EventHandler(const v8::JitCodeEvent* event) {
  if (!FLAG_gdbjit) return;
  switch (event->type) {
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
    case v8::JitCodeEvent::CODE_ADDED: {
      Code* code = Code::GetCodeFromTargetAddress(
          reinterpret_cast<Address>(event->code_start));
      if (code->kind() == Code::OPTIMIZED_FUNCTION ||
          code->kind() == Code::FUNCTION) {
        break;
      }
      EmbeddedVector<char, 256> buffer;
      StringBuilder builder(buffer.start(), buffer.length());
      builder.AddSubstring(event->name.str, static_cast<int>(event->name.len));
      AddCode(builder.Finalize(), code, NON_FUNCTION, NULL, NULL);
      break;
    }
2171 2172
    case v8::JitCodeEvent::CODE_MOVED:
      break;
2173 2174 2175 2176 2177 2178
    case v8::JitCodeEvent::CODE_REMOVED: {
      Code* code = Code::GetCodeFromTargetAddress(
          reinterpret_cast<Address>(event->code_start));
      RemoveCode(code);
      break;
    }
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
    case v8::JitCodeEvent::CODE_ADD_LINE_POS_INFO: {
      LineInfo* line_info = reinterpret_cast<LineInfo*>(event->user_data);
      line_info->SetPosition(static_cast<intptr_t>(event->line_info.offset),
                             static_cast<int>(event->line_info.pos),
                             event->line_info.position_type ==
                                 v8::JitCodeEvent::STATEMENT_POSITION);
      break;
    }
    case v8::JitCodeEvent::CODE_START_LINE_INFO_RECORDING: {
      v8::JitCodeEvent* mutable_event = const_cast<v8::JitCodeEvent*>(event);
      mutable_event->user_data = new LineInfo();
      break;
    }
    case v8::JitCodeEvent::CODE_END_LINE_INFO_RECORDING: {
      LineInfo* line_info = reinterpret_cast<LineInfo*>(event->user_data);
      Code* code = Code::GetCodeFromTargetAddress(
          reinterpret_cast<Address>(event->code_start));
      RegisterDetailedLineInfo(code, line_info);
      break;
    }
  }
}


2203 2204
} }  // namespace v8::internal
#endif