gdb-jit.cc 63.7 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
#include "src/diagnostics/gdb-jit.h"
6

7
#include <iterator>
8
#include <map>
9
#include <memory>
10
#include <vector>
11

12
#include "include/v8-callbacks.h"
13
#include "src/api/api-inl.h"
14
#include "src/base/address-region.h"
15
#include "src/base/bits.h"
16
#include "src/base/hashmap.h"
17
#include "src/base/memory.h"
18
#include "src/base/platform/platform.h"
19
#include "src/base/platform/wrappers.h"
20
#include "src/base/strings.h"
21
#include "src/base/vector.h"
22 23
#include "src/execution/frames-inl.h"
#include "src/execution/frames.h"
24
#include "src/handles/global-handles.h"
25
#include "src/init/bootstrapper.h"
26
#include "src/objects/code-inl.h"
27
#include "src/objects/objects.h"
28
#include "src/utils/ostreams.h"
29
#include "src/zone/zone-chunk-list.h"
30 31 32

namespace v8 {
namespace internal {
33 34 35
namespace GDBJITInterface {

#ifdef ENABLE_GDB_JIT_INTERFACE
36

37
#ifdef __APPLE__
38 39 40
#define __MACH_O
class MachO;
class MachOSection;
41 42
using DebugObject = MachO;
using DebugSection = MachOSection;
43 44
#else
#define __ELF
45
class ELF;
46
class ELFSection;
47 48
using DebugObject = ELF;
using DebugSection = ELFSection;
49
#endif
50

51
class Writer {
52
 public:
53 54
  explicit Writer(DebugObject* debug_object)
      : debug_object_(debug_object),
55 56
        position_(0),
        capacity_(1024),
57
        buffer_(reinterpret_cast<byte*>(base::Malloc(capacity_))) {}
58

59
  ~Writer() { base::Free(buffer_); }
60

61
  uintptr_t position() const { return position_; }
62

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

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

70 71 72
    void set(const T& value) {
      base::WriteUnalignedValue(w_->AddressAt<T>(offset_), value);
    }
73

74
    Slot<T> at(int i) { return Slot<T>(w_, offset_ + sizeof(T) * i); }
75 76 77 78 79 80

   private:
    Writer* w_;
    uintptr_t offset_;
  };

81
  template <typename T>
82 83
  void Write(const T& val) {
    Ensure(position_ + sizeof(T));
84
    base::WriteUnalignedValue(AddressAt<T>(position_), val);
85 86 87
    position_ += sizeof(T);
  }

88
  template <typename T>
89 90 91 92 93
  Slot<T> SlotAt(uintptr_t offset) {
    Ensure(offset + sizeof(T));
    return Slot<T>(this, offset);
  }

94
  template <typename T>
95 96 97 98
  Slot<T> CreateSlotHere() {
    return CreateSlotsHere<T>(1);
  }

99
  template <typename T>
100 101 102 103 104 105 106 107 108 109
  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;
110
      buffer_ = reinterpret_cast<byte*>(base::Realloc(buffer_, capacity_));
111 112 113
    }
  }

114
  DebugObject* debug_object() { return debug_object_; }
115 116 117 118 119 120 121 122

  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);
123
    DCHECK_EQ(position_ % align, 0);
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:
159 160
  template <typename T>
  friend class Slot;
161

162 163 164 165 166 167
  template <typename T>
  Address AddressAt(uintptr_t offset) {
    DCHECK(offset < capacity_ && offset + sizeof(T) <= capacity_);
    return reinterpret_cast<Address>(&buffer_[offset]);
  }

168
  template <typename T>
169
  T* RawSlotAt(uintptr_t offset) {
170
    DCHECK(offset < capacity_ && offset + sizeof(T) <= capacity_);
171 172 173
    return reinterpret_cast<T*>(&buffer_[offset]);
  }

174
  DebugObject* debug_object_;
175 176 177 178 179
  uintptr_t position_;
  uintptr_t capacity_;
  byte* buffer_;
};

180
class ELFStringTable;
181

182
template <typename THeader>
183
class DebugSectionBase : public ZoneObject {
184
 public:
185
  virtual ~DebugSectionBase() = default;
186 187 188

  virtual void WriteBody(Writer::Slot<THeader> header, Writer* writer) {
    uintptr_t start = writer->position();
189
    if (WriteBodyInternal(writer)) {
190
      uintptr_t end = writer->position();
191
      header->offset = static_cast<uint32_t>(start);
192 193 194 195 196 197 198
#if defined(__MACH_O)
      header->addr = 0;
#endif
      header->size = end - start;
    }
  }

199
  virtual bool WriteBodyInternal(Writer* writer) { return false; }
200

201
  using Header = THeader;
202 203 204 205 206
};

struct MachOSectionHeader {
  char sectname[16];
  char segname[16];
Jakob Kummerow's avatar
Jakob Kummerow committed
207
#if V8_TARGET_ARCH_IA32
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
  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,
227
    S_ATTR_COALESCED = 0xBu,
228 229 230
    S_ATTR_SOME_INSTRUCTIONS = 0x400u,
    S_ATTR_DEBUG = 0x02000000u,
    S_ATTR_PURE_INSTRUCTIONS = 0x80000000u
231 232
  };

233
  MachOSection(const char* name, const char* segment, uint32_t align,
234
               uint32_t flags)
235
      : name_(name), segment_(segment), align_(align), flags_(flags) {
236
    if (align_ != 0) {
237
      DCHECK(base::bits::IsPowerOfTwo(align));
238
      align_ = base::bits::WhichPowerOfTwo(align_);
239 240 241
    }
  }

242
  ~MachOSection() override = default;
243 244 245 246 247 248 249 250 251 252 253

  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;
254 255
    memset(header->sectname, 0, sizeof(header->sectname));
    memset(header->segname, 0, sizeof(header->segname));
256 257
    DCHECK(strlen(name_) < sizeof(header->sectname));
    DCHECK(strlen(segment_) < sizeof(header->segname));
258 259
    strncpy(header->sectname, name_, sizeof(header->sectname));
    strncpy(header->segname, segment_, sizeof(header->segname));
260 261 262 263 264
  }

 private:
  const char* name_;
  const char* segment_;
265
  uint32_t align_;
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
  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;
};
281

282 283 284
#if defined(__ELF)
class ELFSection : public DebugSectionBase<ELFSectionHeader> {
 public:
285 286 287 288 289 290 291 292 293 294 295 296 297 298
  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,
299
    TYPE_X86_64_UNWIND = 0x70000001,
300
    TYPE_HIPROC = 0x7FFFFFFF,
301
    TYPE_LOUSER = 0x80000000,
302
    TYPE_HIUSER = 0xFFFFFFFF
303 304
  };

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

307
  enum SpecialIndexes { INDEX_ABSOLUTE = 0xFFF1 };
308 309

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

312
  ~ELFSection() override = default;
313

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

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

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

  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_;
};
347
#endif  // defined(__ELF)
348

349 350 351
#if defined(__MACH_O)
class MachOTextSection : public MachOSection {
 public:
352 353
  MachOTextSection(uint32_t align, uintptr_t addr, uintptr_t size)
      : MachOSection("__text", "__TEXT", align,
354 355 356 357
                     MachOSection::S_REGULAR |
                         MachOSection::S_ATTR_SOME_INSTRUCTIONS |
                         MachOSection::S_ATTR_PURE_INSTRUCTIONS),
        addr_(addr),
358
        size_(size) {}
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

 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)
374 375
class FullHeaderELFSection : public ELFSection {
 public:
376 377
  FullHeaderELFSection(const char* name, Type type, uintptr_t align,
                       uintptr_t addr, uintptr_t offset, uintptr_t size,
378 379 380 381 382
                       uintptr_t flags)
      : ELFSection(name, type, align),
        addr_(addr),
        offset_(offset),
        size_(size),
383
        flags_(flags) {}
384 385

 protected:
386
  void PopulateHeader(Writer::Slot<Header> header) override {
387 388 389 390 391 392 393 394 395 396 397 398 399 400
    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_;
};

401
class ELFStringTable : public ELFSection {
402
 public:
403
  explicit ELFStringTable(const char* name)
404 405 406 407
      : ELFSection(name, TYPE_STRTAB, 1),
        writer_(nullptr),
        offset_(0),
        size_(0) {}
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424

  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("");
  }

425
  void DetachWriter() { writer_ = nullptr; }
426

427
  void WriteBody(Writer::Slot<Header> header, Writer* w) override {
428
    DCHECK_NULL(writer_);
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
    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,
450
                                ELFStringTable* strtab) {
451
  header->name = static_cast<uint32_t>(strtab->Add(name_));
452 453 454 455
  header->type = type_;
  header->alignment = align_;
  PopulateHeader(header);
}
456 457 458
#endif  // defined(__ELF)

#if defined(__MACH_O)
459
class MachO {
460
 public:
461
  explicit MachO(Zone* zone) : sections_(zone) {}
462

463 464 465
  size_t AddSection(MachOSection* section) {
    sections_.push_back(section);
    return sections_.size() - 1;
466 467 468 469 470
  }

  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();
471 472
    Writer::Slot<MachOSegmentCommand> cmd =
        WriteSegmentCommand(w, code_start, code_size);
473 474 475 476 477 478 479 480 481 482 483 484
    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;
485
#if V8_TARGET_ARCH_X64
486 487 488 489 490 491 492 493
    uint32_t reserved;
#endif
  };

  struct MachOSegmentCommand {
    uint32_t cmd;
    uint32_t cmdsize;
    char segname[16];
Jakob Kummerow's avatar
Jakob Kummerow committed
494
#if V8_TARGET_ARCH_IA32
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    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) {
517
    DCHECK_EQ(w->position(), 0);
518
    Writer::Slot<MachOHeader> header = w->CreateSlotHere<MachOHeader>();
Jakob Kummerow's avatar
Jakob Kummerow committed
519
#if V8_TARGET_ARCH_IA32
520
    header->magic = 0xFEEDFACEu;
521
    header->cputype = 7;     // i386
522
    header->cpusubtype = 3;  // CPU_SUBTYPE_I386_ALL
523
#elif V8_TARGET_ARCH_X64
524 525
    header->magic = 0xFEEDFACFu;
    header->cputype = 7 | 0x01000000;  // i386 | 64-bit ABI
526
    header->cpusubtype = 3;            // CPU_SUBTYPE_I386_ALL
527 528 529 530 531 532 533 534 535 536
    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;
  }
537

538 539 540 541 542
  Writer::Slot<MachOSegmentCommand> WriteSegmentCommand(Writer* w,
                                                        uintptr_t code_start,
                                                        uintptr_t code_size) {
    Writer::Slot<MachOSegmentCommand> cmd =
        w->CreateSlotHere<MachOSegmentCommand>();
Jakob Kummerow's avatar
Jakob Kummerow committed
543
#if V8_TARGET_ARCH_IA32
544 545 546 547 548 549 550 551 552 553 554
    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;
555
    cmd->nsects = static_cast<uint32_t>(sections_.size());
556
    memset(cmd->segname, 0, 16);
557 558
    cmd->cmdsize = sizeof(MachOSegmentCommand) +
                   sizeof(MachOSection::Header) * cmd->nsects;
559 560 561
    return cmd;
  }

562
  void WriteSections(Writer* w, Writer::Slot<MachOSegmentCommand> cmd,
563 564 565
                     Writer::Slot<MachOHeader> header,
                     uintptr_t load_command_start) {
    Writer::Slot<MachOSection::Header> headers =
566 567
        w->CreateSlotsHere<MachOSection::Header>(
            static_cast<uint32_t>(sections_.size()));
568
    cmd->fileoff = w->position();
569 570
    header->sizeofcmds =
        static_cast<uint32_t>(w->position() - load_command_start);
571 572 573 574 575
    uint32_t index = 0;
    for (MachOSection* section : sections_) {
      section->PopulateHeader(headers.at(index));
      section->WriteBody(headers.at(index), w);
      index++;
576 577 578 579
    }
    cmd->filesize = w->position() - (uintptr_t)cmd->fileoff;
  }

580
  ZoneChunkList<MachOSection*> sections_;
581 582 583 584
};
#endif  // defined(__MACH_O)

#if defined(__ELF)
585
class ELF {
586
 public:
587
  explicit ELF(Zone* zone) : sections_(zone) {
588 589
    sections_.push_back(zone->New<ELFSection>("", ELFSection::TYPE_NULL, 0));
    sections_.push_back(zone->New<ELFStringTable>(".shstrtab"));
590 591 592 593 594 595 596 597
  }

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

598
  ELFSection* SectionAt(uint32_t index) { return *sections_.Find(index); }
599

600 601 602 603
  size_t AddSection(ELFSection* section) {
    sections_.push_back(section);
    section->set_index(sections_.size() - 1);
    return sections_.size() - 1;
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
  }

 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) {
625
    DCHECK_EQ(w->position(), 0);
626
    Writer::Slot<ELFHeader> header = w->CreateSlotHere<ELFHeader>();
627
#if (V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_ARM)
628 629
    const uint8_t ident[16] = {0x7F, 'E', 'L', 'F', 1, 1, 1, 0,
                               0,    0,   0,   0,   0, 0, 0, 0};
630 631
#elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT || \
    V8_TARGET_ARCH_PPC64 && V8_TARGET_LITTLE_ENDIAN
632 633
    const uint8_t ident[16] = {0x7F, 'E', 'L', 'F', 2, 1, 1, 0,
                               0,    0,   0,   0,   0, 0, 0, 0};
634
#elif V8_TARGET_ARCH_PPC64 && V8_TARGET_BIG_ENDIAN && V8_OS_LINUX
635
    const uint8_t ident[16] = {0x7F, 'E', 'L', 'F', 2, 2, 1, 0,
636
                               0,    0,   0,   0,   0, 0, 0, 0};
637
#elif V8_TARGET_ARCH_S390X
638
    const uint8_t ident[16] = {0x7F, 'E', 'L', 'F', 2, 2, 1, 3,
639 640
                               0,    0,   0,   0,   0, 0, 0, 0};
#elif V8_TARGET_ARCH_S390
641
    const uint8_t ident[16] = {0x7F, 'E', 'L', 'F', 1, 2, 1, 3,
642
                               0,    0,   0,   0,   0, 0, 0, 0};
643 644 645
#else
#error Unsupported target architecture.
#endif
646
    memcpy(header->ident, ident, 16);
647
    header->type = 1;
Jakob Kummerow's avatar
Jakob Kummerow committed
648
#if V8_TARGET_ARCH_IA32
649
    header->machine = 3;
650
#elif V8_TARGET_ARCH_X64
651 652 653 654
    // 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;
655
#elif V8_TARGET_ARCH_ARM
656 657 658
    // 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;
659 660 661 662 663 664 665 666
#elif V8_TARGET_ARCH_PPC64 && V8_OS_LINUX
    // Set to EM_PPC64, defined as 21, in Power ABI,
    // Join the next 4 lines, omitting the spaces and double-slashes.
    // https://www-03.ibm.com/technologyconnect/tgcm/TGCMFileServlet.wss/
    // ABI64BitOpenPOWERv1.1_16July2015_pub.pdf?
    // id=B81AEC1A37F5DAF185257C3E004E8845&linkid=1n0000&c_t=
    // c9xw7v5dzsj7gt1ifgf4cjbcnskqptmr
    header->machine = 21;
667 668 669 670 671
#elif V8_TARGET_ARCH_S390
    // Processor identification value is 22 (EM_S390) as defined in the ABI:
    // http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_s390.html#AEN1691
    // http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_zSeries.html#AEN1599
    header->machine = 22;
672 673 674 675 676 677 678 679 680 681 682 683
#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);
684
    header->sht_entry_num = sections_.size();
685 686 687 688 689
    header->sht_strtab_index = 1;
  }

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

    Writer::Slot<ELFSection::Header> headers =
693 694
        w->CreateSlotsHere<ELFSection::Header>(
            static_cast<uint32_t>(sections_.size()));
695 696

    // String table for section table is the first section.
697
    ELFStringTable* strtab = static_cast<ELFStringTable*>(SectionAt(1));
698
    strtab->AttachWriter(w);
699 700 701 702
    uint32_t index = 0;
    for (ELFSection* section : sections_) {
      section->PopulateHeader(headers.at(index), strtab);
      index++;
703 704 705 706 707 708 709 710 711 712 713 714
    }
    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));

715 716 717 718
    uint32_t index = 0;
    for (ELFSection* section : sections_) {
      section->WriteBody(headers.at(index), w);
      index++;
719 720 721
    }
  }

722
  ZoneChunkList<ELFSection*> sections_;
723 724
};

725
class ELFSymbol {
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
 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
  };

745 746
  ELFSymbol(const char* name, uintptr_t value, uintptr_t size, Binding binding,
            Type type, uint16_t section)
747 748 749 750 751
      : name(name),
        value(value),
        size(size),
        info((binding << 4) | type),
        other(0),
752
        section(section) {}
753

754 755
  Binding binding() const { return static_cast<Binding>(info >> 4); }
#if (V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_ARM || \
756
     (V8_TARGET_ARCH_S390 && V8_TARGET_ARCH_32_BIT))
757
  struct SerializedLayout {
758 759
    SerializedLayout(uint32_t name, uintptr_t value, uintptr_t size,
                     Binding binding, Type type, uint16_t section)
760 761 762 763 764
        : name(name),
          value(value),
          size(size),
          info((binding << 4) | type),
          other(0),
765
          section(section) {}
766 767 768 769 770 771 772 773

    uint32_t name;
    uintptr_t value;
    uintptr_t size;
    uint8_t info;
    uint8_t other;
    uint16_t section;
  };
774 775
#elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT || \
    V8_TARGET_ARCH_PPC64 && V8_OS_LINUX || V8_TARGET_ARCH_S390X
776
  struct SerializedLayout {
777 778
    SerializedLayout(uint32_t name, uintptr_t value, uintptr_t size,
                     Binding binding, Type type, uint16_t section)
779 780 781 782 783
        : name(name),
          info((binding << 4) | type),
          other(0),
          section(section),
          value(value),
784
          size(size) {}
785 786 787 788 789 790 791 792 793 794

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

795
  void Write(Writer::Slot<SerializedLayout> s, ELFStringTable* t) const {
796
    // Convert symbol names from strings to indexes in the string table.
797
    s->name = static_cast<uint32_t>(t->Add(name));
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
    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:
816
  ELFSymbolTable(const char* name, Zone* zone)
817
      : ELFSection(name, TYPE_SYMTAB, sizeof(uintptr_t)),
818 819
        locals_(zone),
        globals_(zone) {}
820

821
  void WriteBody(Writer::Slot<Header> header, Writer* w) override {
822
    w->Align(header->alignment);
823
    size_t total_symbols = locals_.size() + globals_.size() + 1;
824 825 826
    header->offset = w->position();

    Writer::Slot<ELFSymbol::SerializedLayout> symbols =
827 828
        w->CreateSlotsHere<ELFSymbol::SerializedLayout>(
            static_cast<uint32_t>(total_symbols));
829 830 831 832

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

    // String table for this symbol table should follow it in the section table.
833 834
    ELFStringTable* strtab =
        static_cast<ELFStringTable*>(w->debug_object()->SectionAt(index() + 1));
835
    strtab->AttachWriter(w);
836 837
    symbols.at(0).set(ELFSymbol::SerializedLayout(
        0, 0, 0, ELFSymbol::BIND_LOCAL, ELFSymbol::TYPE_NOTYPE, 0));
838
    WriteSymbolsList(&locals_, symbols.at(1), strtab);
839 840 841
    WriteSymbolsList(&globals_,
                     symbols.at(static_cast<uint32_t>(locals_.size() + 1)),
                     strtab);
842 843 844
    strtab->DetachWriter();
  }

845
  void Add(const ELFSymbol& symbol) {
846
    if (symbol.binding() == ELFSymbol::BIND_LOCAL) {
847
      locals_.push_back(symbol);
848
    } else {
849
      globals_.push_back(symbol);
850 851 852 853
    }
  }

 protected:
854
  void PopulateHeader(Writer::Slot<Header> header) override {
855 856 857
    ELFSection::PopulateHeader(header);
    // We are assuming that string table will follow symbol table.
    header->link = index() + 1;
858
    header->info = static_cast<uint32_t>(locals_.size() + 1);
859 860 861 862
    header->entry_size = sizeof(ELFSymbol::SerializedLayout);
  }

 private:
863
  void WriteSymbolsList(const ZoneChunkList<ELFSymbol>* src,
864
                        Writer::Slot<ELFSymbol::SerializedLayout> dst,
865
                        ELFStringTable* strtab) {
866 867 868
    int i = 0;
    for (const ELFSymbol& symbol : *src) {
      symbol.Write(dst.at(i++), strtab);
869 870 871
    }
  }

872 873
  ZoneChunkList<ELFSymbol> locals_;
  ZoneChunkList<ELFSymbol> globals_;
874
};
875
#endif  // defined(__ELF)
876

877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
class LineInfo : public Malloced {
 public:
  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_;
  };

892
  std::vector<PCInfo>* pc_info() { return &pc_info_; }
893 894

 private:
895
  void AddPCInfo(const PCInfo& pc_info) { pc_info_.push_back(pc_info); }
896

897
  std::vector<PCInfo> pc_info_;
898 899
};

900
class CodeDescription {
901
 public:
902
#if V8_TARGET_ARCH_X64
903 904 905 906 907 908 909 910
  enum StackState {
    POST_RBP_PUSH,
    POST_RBP_SET,
    POST_RBP_POP,
    STACK_STATE_MAX
  };
#endif

911 912 913 914 915 916 917 918
  CodeDescription(const char* name, base::AddressRegion region,
                  SharedFunctionInfo shared, LineInfo* lineinfo,
                  bool is_function)
      : name_(name),
        shared_info_(shared),
        lineinfo_(lineinfo),
        is_function_(is_function),
        code_region_(region) {}
919

920
  const char* name() const { return name_; }
921

922
  LineInfo* lineinfo() const { return lineinfo_; }
923

924
  bool is_function() const { return is_function_; }
925

926
  bool has_scope_info() const { return !shared_info_.is_null(); }
927

928
  ScopeInfo scope_info() const {
929
    DCHECK(has_scope_info());
930
    return shared_info_.scope_info();
931 932
  }

933
  uintptr_t CodeStart() const { return code_region_.begin(); }
934

935
  uintptr_t CodeEnd() const { return code_region_.end(); }
936

937
  uintptr_t CodeSize() const { return code_region_.size(); }
938

939
  bool has_script() {
940
    return !shared_info_.is_null() && shared_info_.script().IsScript();
941 942
  }

943
  Script script() { return Script::cast(shared_info_.script()); }
944

945
  bool IsLineInfoAvailable() { return lineinfo_ != nullptr; }
946

947 948
  base::AddressRegion region() { return code_region_; }

949
#if V8_TARGET_ARCH_X64
950
  uintptr_t GetStackStateStartAddress(StackState state) const {
951
    DCHECK(state < STACK_STATE_MAX);
952 953
    return stack_state_start_addresses_[state];
  }
954

955
  void SetStackStateStartAddress(StackState state, uintptr_t addr) {
956
    DCHECK(state < STACK_STATE_MAX);
957 958 959 960
    stack_state_start_addresses_[state] = addr;
  }
#endif

961
  std::unique_ptr<char[]> GetFilename() {
962
    if (!shared_info_.is_null() && script().name().IsString()) {
963
      return String::cast(script().name()).ToCString();
964 965 966 967 968
    } else {
      std::unique_ptr<char[]> result(new char[1]);
      result[0] = 0;
      return result;
    }
969 970
  }

971
  int GetScriptLineNumber(int pos) {
972
    if (!shared_info_.is_null()) {
973
      return script().GetLineNumber(pos) + 1;
974 975 976 977
    } else {
      return 0;
    }
  }
978

979 980
 private:
  const char* name_;
981
  SharedFunctionInfo shared_info_;
982
  LineInfo* lineinfo_;
983 984
  bool is_function_;
  base::AddressRegion code_region_;
985
#if V8_TARGET_ARCH_X64
986 987
  uintptr_t stack_state_start_addresses_[STACK_STATE_MAX];
#endif
988 989
};

990
#if defined(__ELF)
991 992
static void CreateSymbolsTable(CodeDescription* desc, Zone* zone, ELF* elf,
                               size_t text_section_index) {
993 994
  ELFSymbolTable* symtab = zone->New<ELFSymbolTable>(".symtab", zone);
  ELFStringTable* strtab = zone->New<ELFStringTable>(".strtab");
995 996

  // Symbol table should be followed by the linked string table.
997 998
  elf->AddSection(symtab);
  elf->AddSection(strtab);
999

1000 1001 1002 1003 1004 1005
  symtab->Add(ELFSymbol("V8 Code", 0, 0, ELFSymbol::BIND_LOCAL,
                        ELFSymbol::TYPE_FILE, ELFSection::INDEX_ABSOLUTE));

  symtab->Add(ELFSymbol(desc->name(), 0, desc->CodeSize(),
                        ELFSymbol::BIND_GLOBAL, ELFSymbol::TYPE_FUNC,
                        text_section_index));
1006
}
1007
#endif  // defined(__ELF)
1008

1009
class DebugInfoSection : public DebugSection {
1010 1011
 public:
  explicit DebugInfoSection(CodeDescription* desc)
1012 1013 1014
#if defined(__ELF)
      : ELFSection(".debug_info", TYPE_PROGBITS, 1),
#else
1015
      : MachOSection("__debug_info", "__DWARF", 1,
1016 1017
                     MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
#endif
1018 1019
        desc_(desc) {
  }
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030

  // 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,
1031 1032
    DW_OP_reg8 = 0x58,
    DW_OP_reg9 = 0x59,
1033 1034 1035 1036 1037 1038
    DW_OP_reg10 = 0x5A,
    DW_OP_reg11 = 0x5B,
    DW_OP_reg12 = 0x5C,
    DW_OP_reg13 = 0x5D,
    DW_OP_reg14 = 0x5E,
    DW_OP_reg15 = 0x5F,
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
    DW_OP_reg16 = 0x60,
    DW_OP_reg17 = 0x61,
    DW_OP_reg18 = 0x62,
    DW_OP_reg19 = 0x63,
    DW_OP_reg20 = 0x64,
    DW_OP_reg21 = 0x65,
    DW_OP_reg22 = 0x66,
    DW_OP_reg23 = 0x67,
    DW_OP_reg24 = 0x68,
    DW_OP_reg25 = 0x69,
1049 1050 1051 1052 1053 1054
    DW_OP_reg26 = 0x6A,
    DW_OP_reg27 = 0x6B,
    DW_OP_reg28 = 0x6C,
    DW_OP_reg29 = 0x6D,
    DW_OP_reg30 = 0x6E,
    DW_OP_reg31 = 0x6F,
1055 1056 1057
    DW_OP_fbreg = 0x91  // 1 param: SLEB128 offset
  };

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

1060
  bool WriteBodyInternal(Writer* w) override {
1061
    uintptr_t cu_start = w->position();
1062 1063 1064 1065 1066 1067 1068
    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.
1069
    w->WriteString(desc_->GetFilename().get());
1070 1071
    w->Write<intptr_t>(desc_->CodeStart());
    w->Write<intptr_t>(desc_->CodeStart() + desc_->CodeSize());
1072
    w->Write<uint32_t>(0);
1073 1074 1075

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

1079
    if (desc_->has_scope_info()) {
1080
      ScopeInfo scope = desc_->scope_info();
1081 1082 1083 1084 1085 1086
      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();
Jakob Kummerow's avatar
Jakob Kummerow committed
1087
#if V8_TARGET_ARCH_IA32
1088
      w->Write<uint8_t>(DW_OP_reg5);  // The frame pointer's here on ia32
1089
#elif V8_TARGET_ARCH_X64
1090
      w->Write<uint8_t>(DW_OP_reg6);  // and here on x64.
1091
#elif V8_TARGET_ARCH_ARM
1092
      UNIMPLEMENTED();
1093
#elif V8_TARGET_ARCH_MIPS
1094
      UNIMPLEMENTED();
1095 1096
#elif V8_TARGET_ARCH_MIPS64
      UNIMPLEMENTED();
1097 1098
#elif V8_TARGET_ARCH_LOONG64
      UNIMPLEMENTED();
1099 1100
#elif V8_TARGET_ARCH_PPC64 && V8_OS_LINUX
      w->Write<uint8_t>(DW_OP_reg31);  // The frame pointer is here on PPC64.
1101 1102
#elif V8_TARGET_ARCH_S390
      w->Write<uint8_t>(DW_OP_reg11);  // The frame pointer's here on S390.
1103 1104 1105 1106 1107
#else
#error Unsupported target architecture.
#endif
      fb_block_size.set(static_cast<uint32_t>(w->position() - fb_block_start));

1108 1109
      int params = scope.ParameterCount();
      int context_slots = scope.ContextLocalCount();
1110
      // The real slot ID is internal_slots + context_slot_id.
1111
      int internal_slots = scope.ContextHeaderLength();
1112 1113 1114 1115
      int current_abbreviation = 4;

      for (int param = 0; param < params; ++param) {
        w->WriteULEB128(current_abbreviation++);
1116 1117
        w->WriteString("param");
        w->Write(std::to_string(param).c_str());
1118 1119 1120 1121
        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);
1122
        w->WriteSLEB128(StandardFrameConstants::kFixedFrameSizeAboveFp +
1123
                        kSystemPointerSize * (params - param - 1));
1124 1125 1126 1127
        block_size.set(static_cast<uint32_t>(w->position() - block_start));
      }

      // See contexts.h for more information.
1128
      DCHECK(internal_slots == 2 || internal_slots == 3);
1129
      DCHECK_EQ(Context::SCOPE_INFO_INDEX, 0);
1130 1131
      DCHECK_EQ(Context::PREVIOUS_INDEX, 1);
      DCHECK_EQ(Context::EXTENSION_INDEX, 2);
1132
      w->WriteULEB128(current_abbreviation++);
1133
      w->WriteString(".scope_info");
1134 1135
      w->WriteULEB128(current_abbreviation++);
      w->WriteString(".previous");
1136 1137 1138 1139
      if (internal_slots == 3) {
        w->WriteULEB128(current_abbreviation++);
        w->WriteString(".extension");
      }
1140

1141
      for (int context_slot = 0; context_slot < context_slots; ++context_slot) {
1142
        w->WriteULEB128(current_abbreviation++);
1143 1144
        w->WriteString("context_slot");
        w->Write(std::to_string(context_slot + internal_slots).c_str());
1145 1146 1147 1148 1149 1150 1151 1152 1153
      }

      {
        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);
1154
        w->WriteSLEB128(StandardFrameConstants::kFunctionOffset);
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
        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));
      }
1168 1169

      w->WriteULEB128(0);  // Terminate the sub program.
1170 1171
    }

1172
    w->WriteULEB128(0);  // Terminate the compile unit.
1173 1174 1175 1176 1177 1178 1179 1180
    size.set(static_cast<uint32_t>(w->position() - start));
    return true;
  }

 private:
  CodeDescription* desc_;
};

1181
class DebugAbbrevSection : public DebugSection {
1182
 public:
1183 1184 1185 1186
  explicit DebugAbbrevSection(CodeDescription* desc)
#ifdef __ELF
      : ELFSection(".debug_abbrev", TYPE_PROGBITS, 1),
#else
1187
      : MachOSection("__debug_abbrev", "__DWARF", 1,
1188 1189
                     MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
#endif
1190 1191
        desc_(desc) {
  }
1192 1193 1194

  // DWARF2 standard, figure 14.
  enum DWARF2Tags {
1195
    DW_TAG_FORMAL_PARAMETER = 0x05,
1196
    DW_TAG_POINTER_TYPE = 0xF,
1197 1198 1199
    DW_TAG_COMPILE_UNIT = 0x11,
    DW_TAG_STRUCTURE_TYPE = 0x13,
    DW_TAG_BASE_TYPE = 0x24,
1200
    DW_TAG_SUBPROGRAM = 0x2E,
1201
    DW_TAG_VARIABLE = 0x34
1202 1203 1204
  };

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

  // DWARF standard, figure 17.
  enum DWARF2Attribute {
1209
    DW_AT_LOCATION = 0x2,
1210
    DW_AT_NAME = 0x3,
1211
    DW_AT_BYTE_SIZE = 0xB,
1212 1213
    DW_AT_STMT_LIST = 0x10,
    DW_AT_LOW_PC = 0x11,
1214
    DW_AT_HIGH_PC = 0x12,
1215
    DW_AT_ENCODING = 0x3E,
1216 1217
    DW_AT_FRAME_BASE = 0x40,
    DW_AT_TYPE = 0x49
1218 1219 1220 1221 1222
  };

  // DWARF2 standard, figure 19.
  enum DWARF2AttributeForm {
    DW_FORM_ADDR = 0x1,
1223
    DW_FORM_BLOCK4 = 0x4,
1224
    DW_FORM_STRING = 0x8,
1225 1226
    DW_FORM_DATA4 = 0x6,
    DW_FORM_BLOCK = 0x9,
1227 1228
    DW_FORM_DATA1 = 0xB,
    DW_FORM_FLAG = 0xC,
1229
    DW_FORM_REF4 = 0x13
1230 1231
  };

1232 1233
  void WriteVariableAbbreviation(Writer* w, int abbreviation_code,
                                 bool has_value, bool is_parameter) {
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    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);
  }

1249
  bool WriteBodyInternal(Writer* w) override {
1250
    int current_abbreviation = 1;
1251
    bool extra_info = desc_->has_scope_info();
1252
    DCHECK(desc_->IsLineInfoAvailable());
1253
    w->WriteULEB128(current_abbreviation++);
1254
    w->WriteULEB128(DW_TAG_COMPILE_UNIT);
1255
    w->Write<uint8_t>(extra_info ? DW_CHILDREN_YES : DW_CHILDREN_NO);
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
    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);
1266 1267

    if (extra_info) {
1268
      ScopeInfo scope = desc_->scope_info();
1269 1270
      int params = scope.ParameterCount();
      int context_slots = scope.ContextLocalCount();
1271 1272
      // The real slot ID is internal_slots + context_slot_id.
      int internal_slots = Context::MIN_CONTEXT_SLOTS;
1273 1274
      // Total children is params + context_slots + internal_slots + 2
      // (__function and __context).
1275 1276 1277 1278 1279

      // 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);
1280
      w->Write<uint8_t>(DW_CHILDREN_YES);
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
      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);
      }

1306
      for (int internal_slot = 0; internal_slot < internal_slots;
1307 1308 1309 1310
           ++internal_slot) {
        WriteVariableAbbreviation(w, current_abbreviation++, false, false);
      }

1311
      for (int context_slot = 0; context_slot < context_slots; ++context_slot) {
1312 1313 1314 1315 1316 1317 1318 1319 1320
        WriteVariableAbbreviation(w, current_abbreviation++, false, false);
      }

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

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

1321
      w->WriteULEB128(0);  // Terminate the sibling list.
1322 1323 1324
    }

    w->WriteULEB128(0);  // Terminate the table.
1325 1326
    return true;
  }
1327 1328 1329

 private:
  CodeDescription* desc_;
1330 1331
};

1332
class DebugLineSection : public DebugSection {
1333 1334
 public:
  explicit DebugLineSection(CodeDescription* desc)
1335
#ifdef __ELF
1336
      : ELFSection(".debug_line", TYPE_PROGBITS, 1),
1337
#else
1338
      : MachOSection("__debug_line", "__DWARF", 1,
1339 1340
                     MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
#endif
1341 1342
        desc_(desc) {
  }
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360

  // 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
  };

1361
  bool WriteBodyInternal(Writer* w) override {
1362 1363 1364 1365
    // Write prologue.
    Writer::Slot<uint32_t> total_length = w->CreateSlotHere<uint32_t>();
    uintptr_t start = w->position();

1366 1367 1368 1369 1370 1371
    // 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;

1372 1373 1374
    w->Write<uint16_t>(2);  // Field version.
    Writer::Slot<uint32_t> prologue_length = w->CreateSlotHere<uint32_t>();
    uintptr_t prologue_start = w->position();
1375 1376 1377 1378
    w->Write<uint8_t>(1);            // Field minimum_instruction_length.
    w->Write<uint8_t>(1);            // Field default_is_stmt.
    w->Write<int8_t>(line_base);     // Field line_base.
    w->Write<uint8_t>(line_range);   // Field line_range.
1379
    w->Write<uint8_t>(opcode_base);  // Field opcode_base.
1380 1381 1382 1383 1384 1385 1386
    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.
1387
    w->WriteString(desc_->GetFilename().get());  // File name.
1388 1389 1390
    w->WriteULEB128(0);                          // Current directory.
    w->WriteULEB128(0);                          // Unknown modification time.
    w->WriteULEB128(0);                          // Unknown file size.
1391 1392 1393 1394
    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));
1395
    w->Write<intptr_t>(desc_->CodeStart());
1396
    w->Write<uint8_t>(DW_LNS_COPY);
1397 1398 1399 1400 1401

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

1402 1403
    std::vector<LineInfo::PCInfo>* pc_info = desc_->lineinfo()->pc_info();
    std::sort(pc_info->begin(), pc_info->end(), &ComparePCInfo);
1404

1405
    for (size_t i = 0; i < pc_info->size(); i++) {
1406
      LineInfo::PCInfo* info = &pc_info->at(i);
1407
      DCHECK(info->pc_ >= pc);
1408 1409 1410

      // Reduce bloating in the debug line table by removing duplicate line
      // entries (per DWARF2 standard).
1411
      intptr_t new_line = desc_->GetScriptLineNumber(info->pos_);
1412 1413
      if (new_line == line) {
        continue;
1414
      }
1415 1416 1417 1418 1419

      // 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.
1420
      if ((i + 1) == pc_info->size()) {
1421 1422 1423 1424
        if (!is_statement) {
          w->Write<uint8_t>(DW_LNS_NEGATE_STMT);
        }
      } else if (is_statement != info->is_statement_) {
1425 1426 1427
        w->Write<uint8_t>(DW_LNS_NEGATE_STMT);
        is_statement = !is_statement;
      }
1428 1429 1430 1431 1432 1433 1434 1435

      // 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)
1436 1437
      intptr_t special_opcode =
          (line_diff - line_base) + (line_range * pc_diff) + opcode_base;
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451

      // 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);
1452 1453
        w->Write<uint8_t>(DW_LNS_COPY);
      }
1454 1455 1456 1457

      // Increment the pc and line operands.
      pc += pc_diff;
      line += line_diff;
1458
    }
1459 1460 1461 1462
    // 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);
1463 1464 1465 1466 1467 1468
    WriteExtendedOpcode(w, DW_LNE_END_SEQUENCE, 0);
    total_length.set(static_cast<uint32_t>(w->position() - start));
    return true;
  }

 private:
1469
  void WriteExtendedOpcode(Writer* w, DWARF2ExtendedOpcode op,
1470 1471 1472 1473 1474 1475
                           size_t operands_size) {
    w->Write<uint8_t>(0);
    w->WriteULEB128(operands_size + 1);
    w->Write<uint8_t>(op);
  }

1476 1477 1478 1479 1480
  static bool ComparePCInfo(const LineInfo::PCInfo& a,
                            const LineInfo::PCInfo& b) {
    if (a.pc_ == b.pc_) {
      if (a.is_statement_ != b.is_statement_) {
        return !b.is_statement_;
1481
      }
1482
      return false;
1483
    }
1484
    return a.pc_ < b.pc_;
1485 1486 1487 1488 1489
  }

  CodeDescription* desc_;
};

1490
#if V8_TARGET_ARCH_X64
1491

1492
class UnwindInfoSection : public DebugSection {
1493
 public:
1494
  explicit UnwindInfoSection(CodeDescription* desc);
1495
  bool WriteBodyInternal(Writer* w) override;
1496

1497 1498
  int WriteCIE(Writer* w);
  void WriteFDE(Writer* w, int);
1499

1500 1501 1502 1503
  void WriteFDEStateOnEntry(Writer* w);
  void WriteFDEStateAfterRBPPush(Writer* w);
  void WriteFDEStateAfterRBPSet(Writer* w);
  void WriteFDEStateAfterRBPPop(Writer* w);
1504

1505
  void WriteLength(Writer* w, Writer::Slot<uint32_t>* length_slot,
1506 1507 1508
                   int initial_position);

 private:
1509
  CodeDescription* desc_;
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558

  // 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
  };
};

1559
void UnwindInfoSection::WriteLength(Writer* w,
1560 1561
                                    Writer::Slot<uint32_t>* length_slot,
                                    int initial_position) {
1562
  uint32_t align = (w->position() - initial_position) % kSystemPointerSize;
1563 1564

  if (align != 0) {
1565
    for (uint32_t i = 0; i < (kSystemPointerSize - align); i++) {
1566 1567 1568 1569
      w->Write<uint8_t>(DW_CFA_NOP);
    }
  }

1570
  DCHECK_EQ((w->position() - initial_position) % kSystemPointerSize, 0);
1571
  length_slot->set(static_cast<uint32_t>(w->position() - initial_position));
1572 1573
}

1574
UnwindInfoSection::UnwindInfoSection(CodeDescription* desc)
1575 1576 1577 1578 1579 1580
#ifdef __ELF
    : ELFSection(".eh_frame", TYPE_X86_64_UNWIND, 1),
#else
    : MachOSection("__eh_frame", "__TEXT", sizeof(uintptr_t),
                   MachOSection::S_REGULAR),
#endif
1581 1582
      desc_(desc) {
}
1583

1584
int UnwindInfoSection::WriteCIE(Writer* w) {
1585
  Writer::Slot<uint32_t> cie_length_slot = w->CreateSlotHere<uint32_t>();
1586
  uint32_t cie_position = static_cast<uint32_t>(w->position());
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602

  // 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;
}

1603
void UnwindInfoSection::WriteFDE(Writer* w, int cie_position) {
1604 1605
  // The only FDE for this function. The CFA is the current RBP.
  Writer::Slot<uint32_t> fde_length_slot = w->CreateSlotHere<uint32_t>();
1606
  int fde_position = static_cast<uint32_t>(w->position());
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
  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);
}

1620
void UnwindInfoSection::WriteFDEStateOnEntry(Writer* w) {
1621 1622 1623 1624 1625 1626 1627
  // 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);
1628
  w->WriteSLEB128(-kSystemPointerSize);
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645

  // 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));
}

1646
void UnwindInfoSection::WriteFDEStateAfterRBPPush(Writer* w) {
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
  // 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));
}

1666
void UnwindInfoSection::WriteFDEStateAfterRBPSet(Writer* w) {
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
  // 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));
}

1680
void UnwindInfoSection::WriteFDEStateAfterRBPPop(Writer* w) {
1681 1682 1683 1684 1685 1686
  // 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);
1687
  w->WriteSLEB128(-kSystemPointerSize);
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698

  // 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());
}

1699
bool UnwindInfoSection::WriteBodyInternal(Writer* w) {
1700 1701 1702 1703 1704 1705 1706
  uint32_t cie_position = WriteCIE(w);
  WriteFDE(w, cie_position);
  return true;
}

#endif  // V8_TARGET_ARCH_X64

1707
static void CreateDWARFSections(CodeDescription* desc, Zone* zone,
1708
                                DebugObject* obj) {
1709
  if (desc->IsLineInfoAvailable()) {
1710 1711 1712
    obj->AddSection(zone->New<DebugInfoSection>(desc));
    obj->AddSection(zone->New<DebugAbbrevSection>(desc));
    obj->AddSection(zone->New<DebugLineSection>(desc));
1713
  }
1714
#if V8_TARGET_ARCH_X64
1715
  obj->AddSection(zone->New<UnwindInfoSection>(desc));
1716
#endif
1717 1718 1719 1720 1721 1722
}

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

1725 1726 1727 1728 1729 1730
struct JITCodeEntry {
  JITCodeEntry* next_;
  JITCodeEntry* prev_;
  Address symfile_addr_;
  uint64_t symfile_size_;
};
1731

1732 1733 1734 1735 1736 1737
struct JITDescriptor {
  uint32_t version_;
  uint32_t action_flag_;
  JITCodeEntry* relevant_entry_;
  JITCodeEntry* first_entry_;
};
1738

1739 1740 1741 1742 1743 1744 1745 1746 1747
// 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() { __asm__(""); }

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

#ifdef OBJECT_PRINT
1750 1751
void __gdb_print_v8_object(Object object) {
  StdoutStream os;
1752
  object.Print(os);
1753 1754
  os << std::flush;
}
1755
#endif
1756 1757 1758 1759
}

static JITCodeEntry* CreateCodeEntry(Address symfile_addr,
                                     uintptr_t symfile_size) {
1760 1761
  JITCodeEntry* entry = static_cast<JITCodeEntry*>(
      base::Malloc(sizeof(JITCodeEntry) + symfile_size));
1762 1763 1764

  entry->symfile_addr_ = reinterpret_cast<Address>(entry + 1);
  entry->symfile_size_ = symfile_size;
1765 1766
  MemCopy(reinterpret_cast<void*>(entry->symfile_addr_),
          reinterpret_cast<void*>(symfile_addr), symfile_size);
1767

1768
  entry->prev_ = entry->next_ = nullptr;
1769 1770 1771 1772

  return entry;
}

1773
static void DestroyCodeEntry(JITCodeEntry* entry) { base::Free(entry); }
1774

1775
static void RegisterCodeEntry(JITCodeEntry* entry) {
1776
  entry->next_ = __jit_debug_descriptor.first_entry_;
1777
  if (entry->next_ != nullptr) entry->next_->prev_ = entry;
1778 1779
  __jit_debug_descriptor.first_entry_ = __jit_debug_descriptor.relevant_entry_ =
      entry;
1780 1781 1782 1783 1784 1785

  __jit_debug_descriptor.action_flag_ = JIT_REGISTER_FN;
  __jit_debug_register_code();
}

static void UnregisterCodeEntry(JITCodeEntry* entry) {
1786
  if (entry->prev_ != nullptr) {
1787 1788 1789 1790 1791
    entry->prev_->next_ = entry->next_;
  } else {
    __jit_debug_descriptor.first_entry_ = entry->next_;
  }

1792
  if (entry->next_ != nullptr) {
1793 1794 1795 1796 1797 1798 1799 1800
    entry->next_->prev_ = entry->prev_;
  }

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

1801
static JITCodeEntry* CreateELFObject(CodeDescription* desc, Isolate* isolate) {
1802
#ifdef __MACH_O
1803
  Zone zone(isolate->allocator(), ZONE_NAME);
1804
  MachO mach_o(&zone);
1805 1806
  Writer w(&mach_o);

1807 1808 1809 1810 1811
  const uint32_t code_alignment = static_cast<uint32_t>(kCodeAlignment);
  static_assert(code_alignment == kCodeAlignment,
                "Unsupported code alignment value");
  mach_o.AddSection(zone.New<MachOTextSection>(
      code_alignment, desc->CodeStart(), desc->CodeSize()));
1812

1813
  CreateDWARFSections(desc, &zone, &mach_o);
1814

1815 1816
  mach_o.Write(&w, desc->CodeStart(), desc->CodeSize());
#else
1817
  Zone zone(isolate->allocator(), ZONE_NAME);
1818
  ELF elf(&zone);
1819 1820
  Writer w(&elf);

1821
  size_t text_section_index = elf.AddSection(zone.New<FullHeaderELFSection>(
1822 1823
      ".text", ELFSection::TYPE_NOBITS, kCodeAlignment, desc->CodeStart(), 0,
      desc->CodeSize(), ELFSection::FLAG_ALLOC | ELFSection::FLAG_EXEC));
1824

1825
  CreateSymbolsTable(desc, &zone, &elf, text_section_index);
1826

1827
  CreateDWARFSections(desc, &zone, &elf);
1828 1829

  elf.Write(&w);
1830
#endif
1831

1832
  return CreateCodeEntry(reinterpret_cast<Address>(w.buffer()), w.position());
1833 1834
}

1835 1836 1837 1838 1839 1840 1841
// Like base::AddressRegion::StartAddressLess but also compares |end| when
// |begin| is equal.
struct AddressRegionLess {
  bool operator()(const base::AddressRegion& a,
                  const base::AddressRegion& b) const {
    if (a.begin() == b.begin()) return a.end() < b.end();
    return a.begin() < b.begin();
1842 1843 1844
  }
};

1845
using CodeMap = std::map<base::AddressRegion, JITCodeEntry*, AddressRegionLess>;
1846

1847
static CodeMap* GetCodeMap() {
1848
  // TODO(jgruber): Don't leak.
1849 1850
  static CodeMap* code_map = nullptr;
  if (code_map == nullptr) code_map = new CodeMap();
1851
  return code_map;
1852 1853
}

1854 1855
static uint32_t HashCodeAddress(Address addr) {
  static const uintptr_t kGoldenRatio = 2654435761u;
1856
  return static_cast<uint32_t>((addr >> kCodeAlignmentBits) * kGoldenRatio);
1857 1858
}

lpy's avatar
lpy committed
1859
static base::HashMap* GetLineMap() {
1860 1861
  static base::HashMap* line_map = nullptr;
  if (line_map == nullptr) {
1862
    line_map = new base::HashMap();
lpy's avatar
lpy committed
1863
  }
1864
  return line_map;
1865 1866
}

1867
static void PutLineInfo(Address addr, LineInfo* info) {
lpy's avatar
lpy committed
1868
  base::HashMap* line_map = GetLineMap();
1869 1870
  base::HashMap::Entry* e = line_map->LookupOrInsert(
      reinterpret_cast<void*>(addr), HashCodeAddress(addr));
1871
  if (e->value != nullptr) delete static_cast<LineInfo*>(e->value);
1872
  e->value = info;
1873 1874
}

1875
static LineInfo* GetLineInfo(Address addr) {
1876 1877
  void* value = GetLineMap()->Remove(reinterpret_cast<void*>(addr),
                                     HashCodeAddress(addr));
1878
  return static_cast<LineInfo*>(value);
1879 1880
}

1881
static void AddUnwindInfo(CodeDescription* desc) {
1882
#if V8_TARGET_ARCH_X64
1883
  if (desc->is_function()) {
1884
    // To avoid propagating unwinding information through
1885 1886
    // compilation pipeline we use an approximation.
    // For most use cases this should not affect usability.
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
    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);
1906
  } else {
1907 1908 1909 1910 1911 1912
    desc->SetStackStateStartAddress(CodeDescription::POST_RBP_PUSH,
                                    desc->CodeStart());
    desc->SetStackStateStartAddress(CodeDescription::POST_RBP_SET,
                                    desc->CodeStart());
    desc->SetStackStateStartAddress(CodeDescription::POST_RBP_POP,
                                    desc->CodeEnd());
1913
  }
1914
#endif  // V8_TARGET_ARCH_X64
1915 1916
}

1917
static base::LazyMutex mutex = LAZY_MUTEX_INITIALIZER;
1918

1919 1920
static base::Optional<std::pair<CodeMap::iterator, CodeMap::iterator>>
GetOverlappingRegions(CodeMap* map, const base::AddressRegion region) {
1921
  DCHECK_LT(region.begin(), region.end());
1922

1923
  if (map->empty()) return {};
1924 1925

  // Find the first overlapping entry.
1926

1927
  // If successful, points to the first element not less than `region`. The
1928
  // returned iterator has the key in `first` and the value in `second`.
1929
  auto it = map->lower_bound(region);
1930 1931 1932 1933
  auto start_it = it;

  if (it == map->end()) {
    start_it = map->begin();
1934 1935 1936 1937 1938 1939
    // Find the first overlapping entry.
    for (; start_it != map->end(); ++start_it) {
      if (start_it->first.end() > region.begin()) {
        break;
      }
    }
1940 1941
  } else if (it != map->begin()) {
    for (--it; it != map->begin(); --it) {
1942
      if ((*it).first.end() <= region.begin()) break;
1943
      start_it = it;
1944
    }
1945 1946 1947
    if (it == map->begin() && it->first.end() > region.begin()) {
      start_it = it;
    }
1948
  }
1949

1950 1951 1952
  if (start_it == map->end()) {
    return {};
  }
1953

1954
  // Find the first non-overlapping entry after `region`.
1955

1956
  const auto end_it = map->lower_bound({region.end(), 0});
1957

1958
  // Return a range containing intersecting regions.
1959

1960 1961
  if (std::distance(start_it, end_it) < 1)
    return {};  // No overlapping entries.
1962

1963 1964
  return {{start_it, end_it}};
}
1965

1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
// Remove entries from the map that intersect the given address region,
// and deregister them from GDB.
static void RemoveJITCodeEntries(CodeMap* map,
                                 const base::AddressRegion region) {
  if (auto overlap = GetOverlappingRegions(map, region)) {
    auto start_it = overlap->first;
    auto end_it = overlap->second;
    for (auto it = start_it; it != end_it; it++) {
      JITCodeEntry* old_entry = (*it).second;
      UnregisterCodeEntry(old_entry);
      DestroyCodeEntry(old_entry);
    }

    map->erase(start_it, end_it);
  }
1981 1982
}

1983
// Insert the entry into the map and register it with GDB.
1984
static void AddJITCodeEntry(CodeMap* map, const base::AddressRegion region,
1985 1986 1987 1988 1989 1990 1991 1992
                            JITCodeEntry* entry, bool dump_if_enabled,
                            const char* name_hint) {
#if defined(DEBUG) && !V8_OS_WIN
  static int file_num = 0;
  if (FLAG_gdbjit_dump && dump_if_enabled) {
    static const int kMaxFileNameSize = 64;
    char file_name[64];

1993 1994 1995
    SNPrintF(base::Vector<char>(file_name, kMaxFileNameSize),
             "/tmp/elfdump%s%d.o", (name_hint != nullptr) ? name_hint : "",
             file_num++);
1996
    WriteBytes(file_name, reinterpret_cast<byte*>(entry->symfile_addr_),
1997
               static_cast<int>(entry->symfile_size_));
1998 1999 2000
  }
#endif

2001
  auto result = map->emplace(region, entry);
2002 2003
  DCHECK(result.second);  // Insertion happened.
  USE(result);
2004 2005 2006 2007

  RegisterCodeEntry(entry);
}

2008 2009 2010
static void AddCode(const char* name, base::AddressRegion region,
                    SharedFunctionInfo shared, LineInfo* lineinfo,
                    Isolate* isolate, bool is_function) {
2011
  DisallowGarbageCollection no_gc;
2012
  CodeDescription code_desc(name, region, shared, lineinfo, is_function);
2013

2014
  CodeMap* code_map = GetCodeMap();
2015
  RemoveJITCodeEntries(code_map, region);
2016

2017
  if (!FLAG_gdbjit_full && !code_desc.IsLineInfoAvailable()) {
2018 2019 2020 2021
    delete lineinfo;
    return;
  }

2022
  AddUnwindInfo(&code_desc);
2023
  JITCodeEntry* entry = CreateELFObject(&code_desc, isolate);
2024 2025 2026

  delete lineinfo;

2027
  const char* name_hint = nullptr;
2028 2029 2030 2031 2032
  bool should_dump = false;
  if (FLAG_gdbjit_dump) {
    if (strlen(FLAG_gdbjit_dump_filter) == 0) {
      name_hint = name;
      should_dump = true;
2033
    } else if (name != nullptr) {
2034
      name_hint = strstr(name, FLAG_gdbjit_dump_filter);
2035
      should_dump = (name_hint != nullptr);
2036 2037
    }
  }
2038
  AddJITCodeEntry(code_map, region, entry, should_dump, name_hint);
2039 2040
}

2041
void EventHandler(const v8::JitCodeEvent* event) {
2042
  if (!FLAG_gdbjit) return;
2043 2044 2045 2046
  if ((event->code_type != v8::JitCodeEvent::JIT_CODE) &&
      (event->code_type != v8::JitCodeEvent::WASM_CODE)) {
    return;
  }
2047
  base::MutexGuard lock_guard(mutex.Pointer());
2048
  switch (event->type) {
2049
    case v8::JitCodeEvent::CODE_ADDED: {
2050 2051
      Address addr = reinterpret_cast<Address>(event->code_start);
      LineInfo* lineinfo = GetLineInfo(addr);
2052
      std::string event_name(event->name.str, event->name.len);
2053
      // It's called UnboundScript in the API but it's a SharedFunctionInfo.
2054 2055 2056
      SharedFunctionInfo shared = event->script.IsEmpty()
                                      ? SharedFunctionInfo()
                                      : *Utils::OpenHandle(*event->script);
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
      Isolate* isolate = reinterpret_cast<Isolate*>(event->isolate);
      bool is_function = false;
      // TODO(zhin): See if we can use event->code_type to determine
      // is_function, the difference currently is that JIT_CODE is SparkPlug,
      // TurboProp, TurboFan, whereas CodeKindIsOptimizedJSFunction is only
      // TurboProp and TurboFan. is_function is used for AddUnwindInfo, and the
      // prologue that SP generates probably matches that of TP/TF, so we can
      // use event->code_type here instead of finding the Code.
      // TODO(zhin): Rename is_function to be more accurate.
      if (event->code_type == v8::JitCodeEvent::JIT_CODE) {
2067 2068 2069 2070
        CodeLookupResult lookup_result =
            isolate->heap()->GcSafeFindCodeForInnerPointer(addr);
        CHECK(lookup_result.IsFound());
        is_function = CodeKindIsOptimizedJSFunction(lookup_result.kind());
2071 2072 2073
      }
      AddCode(event_name.c_str(), {addr, event->code_len}, shared, lineinfo,
              isolate, is_function);
2074 2075
      break;
    }
2076
    case v8::JitCodeEvent::CODE_MOVED:
2077 2078 2079 2080 2081
      // Enabling the GDB JIT interface should disable code compaction.
      UNREACHABLE();
    case v8::JitCodeEvent::CODE_REMOVED:
      // Do nothing.  Instead, adding code causes eviction of any entry whose
      // address range intersects the address range of the added code.
2082
      break;
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
    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);
2098
      PutLineInfo(reinterpret_cast<Address>(event->code_start), line_info);
2099 2100 2101 2102
      break;
    }
  }
}
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119

void AddRegionForTesting(const base::AddressRegion region) {
  // For testing purposes we don't care about JITCodeEntry, pass nullptr.
  auto result = GetCodeMap()->emplace(region, nullptr);
  DCHECK(result.second);  // Insertion happened.
  USE(result);
}

void ClearCodeMapForTesting() { GetCodeMap()->clear(); }

size_t NumOverlapEntriesForTesting(const base::AddressRegion region) {
  if (auto overlaps = GetOverlappingRegions(GetCodeMap(), region)) {
    return std::distance(overlaps->first, overlaps->second);
  }
  return 0;
}

2120
#endif
2121 2122 2123
}  // namespace GDBJITInterface
}  // namespace internal
}  // namespace v8
2124 2125 2126

#undef __MACH_O
#undef __ELF