• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2010 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "src/diagnostics/gdb-jit.h"
6 
7 #include <map>
8 #include <memory>
9 #include <vector>
10 
11 #include "src/api/api-inl.h"
12 #include "src/base/bits.h"
13 #include "src/base/hashmap.h"
14 #include "src/base/platform/platform.h"
15 #include "src/execution/frames-inl.h"
16 #include "src/execution/frames.h"
17 #include "src/handles/global-handles.h"
18 #include "src/init/bootstrapper.h"
19 #include "src/objects/objects.h"
20 #include "src/utils/ostreams.h"
21 #include "src/utils/vector.h"
22 #include "src/zone/zone-chunk-list.h"
23 
24 namespace v8 {
25 namespace internal {
26 namespace GDBJITInterface {
27 
28 #ifdef ENABLE_GDB_JIT_INTERFACE
29 
30 #ifdef __APPLE__
31 #define __MACH_O
32 class MachO;
33 class MachOSection;
34 using DebugObject = MachO;
35 using DebugSection = MachOSection;
36 #else
37 #define __ELF
38 class ELF;
39 class ELFSection;
40 using DebugObject = ELF;
41 using DebugSection = ELFSection;
42 #endif
43 
44 class Writer {
45  public:
Writer(DebugObject * debug_object)46   explicit Writer(DebugObject* debug_object)
47       : debug_object_(debug_object),
48         position_(0),
49         capacity_(1024),
50         buffer_(reinterpret_cast<byte*>(malloc(capacity_))) {}
51 
~Writer()52   ~Writer() { free(buffer_); }
53 
position() const54   uintptr_t position() const { return position_; }
55 
56   template <typename T>
57   class Slot {
58    public:
Slot(Writer * w,uintptr_t offset)59     Slot(Writer* w, uintptr_t offset) : w_(w), offset_(offset) {}
60 
operator ->()61     T* operator->() { return w_->RawSlotAt<T>(offset_); }
62 
set(const T & value)63     void set(const T& value) { *w_->RawSlotAt<T>(offset_) = value; }
64 
at(int i)65     Slot<T> at(int i) { return Slot<T>(w_, offset_ + sizeof(T) * i); }
66 
67    private:
68     Writer* w_;
69     uintptr_t offset_;
70   };
71 
72   template <typename T>
Write(const T & val)73   void Write(const T& val) {
74     Ensure(position_ + sizeof(T));
75     *RawSlotAt<T>(position_) = val;
76     position_ += sizeof(T);
77   }
78 
79   template <typename T>
SlotAt(uintptr_t offset)80   Slot<T> SlotAt(uintptr_t offset) {
81     Ensure(offset + sizeof(T));
82     return Slot<T>(this, offset);
83   }
84 
85   template <typename T>
CreateSlotHere()86   Slot<T> CreateSlotHere() {
87     return CreateSlotsHere<T>(1);
88   }
89 
90   template <typename T>
CreateSlotsHere(uint32_t count)91   Slot<T> CreateSlotsHere(uint32_t count) {
92     uintptr_t slot_position = position_;
93     position_ += sizeof(T) * count;
94     Ensure(position_);
95     return SlotAt<T>(slot_position);
96   }
97 
Ensure(uintptr_t pos)98   void Ensure(uintptr_t pos) {
99     if (capacity_ < pos) {
100       while (capacity_ < pos) capacity_ *= 2;
101       buffer_ = reinterpret_cast<byte*>(realloc(buffer_, capacity_));
102     }
103   }
104 
debug_object()105   DebugObject* debug_object() { return debug_object_; }
106 
buffer()107   byte* buffer() { return buffer_; }
108 
Align(uintptr_t align)109   void Align(uintptr_t align) {
110     uintptr_t delta = position_ % align;
111     if (delta == 0) return;
112     uintptr_t padding = align - delta;
113     Ensure(position_ += padding);
114     DCHECK_EQ(position_ % align, 0);
115   }
116 
WriteULEB128(uintptr_t value)117   void WriteULEB128(uintptr_t value) {
118     do {
119       uint8_t byte = value & 0x7F;
120       value >>= 7;
121       if (value != 0) byte |= 0x80;
122       Write<uint8_t>(byte);
123     } while (value != 0);
124   }
125 
WriteSLEB128(intptr_t value)126   void WriteSLEB128(intptr_t value) {
127     bool more = true;
128     while (more) {
129       int8_t byte = value & 0x7F;
130       bool byte_sign = byte & 0x40;
131       value >>= 7;
132 
133       if ((value == 0 && !byte_sign) || (value == -1 && byte_sign)) {
134         more = false;
135       } else {
136         byte |= 0x80;
137       }
138 
139       Write<int8_t>(byte);
140     }
141   }
142 
WriteString(const char * str)143   void WriteString(const char* str) {
144     do {
145       Write<char>(*str);
146     } while (*str++);
147   }
148 
149  private:
150   template <typename T>
151   friend class Slot;
152 
153   template <typename T>
RawSlotAt(uintptr_t offset)154   T* RawSlotAt(uintptr_t offset) {
155     DCHECK(offset < capacity_ && offset + sizeof(T) <= capacity_);
156     return reinterpret_cast<T*>(&buffer_[offset]);
157   }
158 
159   DebugObject* debug_object_;
160   uintptr_t position_;
161   uintptr_t capacity_;
162   byte* buffer_;
163 };
164 
165 class ELFStringTable;
166 
167 template <typename THeader>
168 class DebugSectionBase : public ZoneObject {
169  public:
170   virtual ~DebugSectionBase() = default;
171 
WriteBody(Writer::Slot<THeader> header,Writer * writer)172   virtual void WriteBody(Writer::Slot<THeader> header, Writer* writer) {
173     uintptr_t start = writer->position();
174     if (WriteBodyInternal(writer)) {
175       uintptr_t end = writer->position();
176       header->offset = static_cast<uint32_t>(start);
177 #if defined(__MACH_O)
178       header->addr = 0;
179 #endif
180       header->size = end - start;
181     }
182   }
183 
WriteBodyInternal(Writer * writer)184   virtual bool WriteBodyInternal(Writer* writer) { return false; }
185 
186   using Header = THeader;
187 };
188 
189 struct MachOSectionHeader {
190   char sectname[16];
191   char segname[16];
192 #if V8_TARGET_ARCH_IA32
193   uint32_t addr;
194   uint32_t size;
195 #else
196   uint64_t addr;
197   uint64_t size;
198 #endif
199   uint32_t offset;
200   uint32_t align;
201   uint32_t reloff;
202   uint32_t nreloc;
203   uint32_t flags;
204   uint32_t reserved1;
205   uint32_t reserved2;
206 };
207 
208 class MachOSection : public DebugSectionBase<MachOSectionHeader> {
209  public:
210   enum Type {
211     S_REGULAR = 0x0u,
212     S_ATTR_COALESCED = 0xBu,
213     S_ATTR_SOME_INSTRUCTIONS = 0x400u,
214     S_ATTR_DEBUG = 0x02000000u,
215     S_ATTR_PURE_INSTRUCTIONS = 0x80000000u
216   };
217 
MachOSection(const char * name,const char * segment,uint32_t align,uint32_t flags)218   MachOSection(const char* name, const char* segment, uint32_t align,
219                uint32_t flags)
220       : name_(name), segment_(segment), align_(align), flags_(flags) {
221     if (align_ != 0) {
222       DCHECK(base::bits::IsPowerOfTwo(align));
223       align_ = base::bits::WhichPowerOfTwo(align_);
224     }
225   }
226 
227   ~MachOSection() override = default;
228 
PopulateHeader(Writer::Slot<Header> header)229   virtual void PopulateHeader(Writer::Slot<Header> header) {
230     header->addr = 0;
231     header->size = 0;
232     header->offset = 0;
233     header->align = align_;
234     header->reloff = 0;
235     header->nreloc = 0;
236     header->flags = flags_;
237     header->reserved1 = 0;
238     header->reserved2 = 0;
239     memset(header->sectname, 0, sizeof(header->sectname));
240     memset(header->segname, 0, sizeof(header->segname));
241     DCHECK(strlen(name_) < sizeof(header->sectname));
242     DCHECK(strlen(segment_) < sizeof(header->segname));
243     strncpy(header->sectname, name_, sizeof(header->sectname));
244     strncpy(header->segname, segment_, sizeof(header->segname));
245   }
246 
247  private:
248   const char* name_;
249   const char* segment_;
250   uint32_t align_;
251   uint32_t flags_;
252 };
253 
254 struct ELFSectionHeader {
255   uint32_t name;
256   uint32_t type;
257   uintptr_t flags;
258   uintptr_t address;
259   uintptr_t offset;
260   uintptr_t size;
261   uint32_t link;
262   uint32_t info;
263   uintptr_t alignment;
264   uintptr_t entry_size;
265 };
266 
267 #if defined(__ELF)
268 class ELFSection : public DebugSectionBase<ELFSectionHeader> {
269  public:
270   enum Type {
271     TYPE_NULL = 0,
272     TYPE_PROGBITS = 1,
273     TYPE_SYMTAB = 2,
274     TYPE_STRTAB = 3,
275     TYPE_RELA = 4,
276     TYPE_HASH = 5,
277     TYPE_DYNAMIC = 6,
278     TYPE_NOTE = 7,
279     TYPE_NOBITS = 8,
280     TYPE_REL = 9,
281     TYPE_SHLIB = 10,
282     TYPE_DYNSYM = 11,
283     TYPE_LOPROC = 0x70000000,
284     TYPE_X86_64_UNWIND = 0x70000001,
285     TYPE_HIPROC = 0x7FFFFFFF,
286     TYPE_LOUSER = 0x80000000,
287     TYPE_HIUSER = 0xFFFFFFFF
288   };
289 
290   enum Flags { FLAG_WRITE = 1, FLAG_ALLOC = 2, FLAG_EXEC = 4 };
291 
292   enum SpecialIndexes { INDEX_ABSOLUTE = 0xFFF1 };
293 
ELFSection(const char * name,Type type,uintptr_t align)294   ELFSection(const char* name, Type type, uintptr_t align)
295       : name_(name), type_(type), align_(align) {}
296 
297   ~ELFSection() override = default;
298 
299   void PopulateHeader(Writer::Slot<Header> header, ELFStringTable* strtab);
300 
WriteBody(Writer::Slot<Header> header,Writer * w)301   void WriteBody(Writer::Slot<Header> header, Writer* w) override {
302     uintptr_t start = w->position();
303     if (WriteBodyInternal(w)) {
304       uintptr_t end = w->position();
305       header->offset = start;
306       header->size = end - start;
307     }
308   }
309 
WriteBodyInternal(Writer * w)310   bool WriteBodyInternal(Writer* w) override { return false; }
311 
index() const312   uint16_t index() const { return index_; }
set_index(uint16_t index)313   void set_index(uint16_t index) { index_ = index; }
314 
315  protected:
PopulateHeader(Writer::Slot<Header> header)316   virtual void PopulateHeader(Writer::Slot<Header> header) {
317     header->flags = 0;
318     header->address = 0;
319     header->offset = 0;
320     header->size = 0;
321     header->link = 0;
322     header->info = 0;
323     header->entry_size = 0;
324   }
325 
326  private:
327   const char* name_;
328   Type type_;
329   uintptr_t align_;
330   uint16_t index_;
331 };
332 #endif  // defined(__ELF)
333 
334 #if defined(__MACH_O)
335 class MachOTextSection : public MachOSection {
336  public:
MachOTextSection(uint32_t align,uintptr_t addr,uintptr_t size)337   MachOTextSection(uint32_t align, uintptr_t addr, uintptr_t size)
338       : MachOSection("__text", "__TEXT", align,
339                      MachOSection::S_REGULAR |
340                          MachOSection::S_ATTR_SOME_INSTRUCTIONS |
341                          MachOSection::S_ATTR_PURE_INSTRUCTIONS),
342         addr_(addr),
343         size_(size) {}
344 
345  protected:
PopulateHeader(Writer::Slot<Header> header)346   virtual void PopulateHeader(Writer::Slot<Header> header) {
347     MachOSection::PopulateHeader(header);
348     header->addr = addr_;
349     header->size = size_;
350   }
351 
352  private:
353   uintptr_t addr_;
354   uintptr_t size_;
355 };
356 #endif  // defined(__MACH_O)
357 
358 #if defined(__ELF)
359 class FullHeaderELFSection : public ELFSection {
360  public:
FullHeaderELFSection(const char * name,Type type,uintptr_t align,uintptr_t addr,uintptr_t offset,uintptr_t size,uintptr_t flags)361   FullHeaderELFSection(const char* name, Type type, uintptr_t align,
362                        uintptr_t addr, uintptr_t offset, uintptr_t size,
363                        uintptr_t flags)
364       : ELFSection(name, type, align),
365         addr_(addr),
366         offset_(offset),
367         size_(size),
368         flags_(flags) {}
369 
370  protected:
PopulateHeader(Writer::Slot<Header> header)371   void PopulateHeader(Writer::Slot<Header> header) override {
372     ELFSection::PopulateHeader(header);
373     header->address = addr_;
374     header->offset = offset_;
375     header->size = size_;
376     header->flags = flags_;
377   }
378 
379  private:
380   uintptr_t addr_;
381   uintptr_t offset_;
382   uintptr_t size_;
383   uintptr_t flags_;
384 };
385 
386 class ELFStringTable : public ELFSection {
387  public:
ELFStringTable(const char * name)388   explicit ELFStringTable(const char* name)
389       : ELFSection(name, TYPE_STRTAB, 1),
390         writer_(nullptr),
391         offset_(0),
392         size_(0) {}
393 
Add(const char * str)394   uintptr_t Add(const char* str) {
395     if (*str == '\0') return 0;
396 
397     uintptr_t offset = size_;
398     WriteString(str);
399     return offset;
400   }
401 
AttachWriter(Writer * w)402   void AttachWriter(Writer* w) {
403     writer_ = w;
404     offset_ = writer_->position();
405 
406     // First entry in the string table should be an empty string.
407     WriteString("");
408   }
409 
DetachWriter()410   void DetachWriter() { writer_ = nullptr; }
411 
WriteBody(Writer::Slot<Header> header,Writer * w)412   void WriteBody(Writer::Slot<Header> header, Writer* w) override {
413     DCHECK_NULL(writer_);
414     header->offset = offset_;
415     header->size = size_;
416   }
417 
418  private:
WriteString(const char * str)419   void WriteString(const char* str) {
420     uintptr_t written = 0;
421     do {
422       writer_->Write(*str);
423       written++;
424     } while (*str++);
425     size_ += written;
426   }
427 
428   Writer* writer_;
429 
430   uintptr_t offset_;
431   uintptr_t size_;
432 };
433 
PopulateHeader(Writer::Slot<ELFSection::Header> header,ELFStringTable * strtab)434 void ELFSection::PopulateHeader(Writer::Slot<ELFSection::Header> header,
435                                 ELFStringTable* strtab) {
436   header->name = static_cast<uint32_t>(strtab->Add(name_));
437   header->type = type_;
438   header->alignment = align_;
439   PopulateHeader(header);
440 }
441 #endif  // defined(__ELF)
442 
443 #if defined(__MACH_O)
444 class MachO {
445  public:
MachO(Zone * zone)446   explicit MachO(Zone* zone) : sections_(zone) {}
447 
AddSection(MachOSection * section)448   size_t AddSection(MachOSection* section) {
449     sections_.push_back(section);
450     return sections_.size() - 1;
451   }
452 
Write(Writer * w,uintptr_t code_start,uintptr_t code_size)453   void Write(Writer* w, uintptr_t code_start, uintptr_t code_size) {
454     Writer::Slot<MachOHeader> header = WriteHeader(w);
455     uintptr_t load_command_start = w->position();
456     Writer::Slot<MachOSegmentCommand> cmd =
457         WriteSegmentCommand(w, code_start, code_size);
458     WriteSections(w, cmd, header, load_command_start);
459   }
460 
461  private:
462   struct MachOHeader {
463     uint32_t magic;
464     uint32_t cputype;
465     uint32_t cpusubtype;
466     uint32_t filetype;
467     uint32_t ncmds;
468     uint32_t sizeofcmds;
469     uint32_t flags;
470 #if V8_TARGET_ARCH_X64
471     uint32_t reserved;
472 #endif
473   };
474 
475   struct MachOSegmentCommand {
476     uint32_t cmd;
477     uint32_t cmdsize;
478     char segname[16];
479 #if V8_TARGET_ARCH_IA32
480     uint32_t vmaddr;
481     uint32_t vmsize;
482     uint32_t fileoff;
483     uint32_t filesize;
484 #else
485     uint64_t vmaddr;
486     uint64_t vmsize;
487     uint64_t fileoff;
488     uint64_t filesize;
489 #endif
490     uint32_t maxprot;
491     uint32_t initprot;
492     uint32_t nsects;
493     uint32_t flags;
494   };
495 
496   enum MachOLoadCommandCmd {
497     LC_SEGMENT_32 = 0x00000001u,
498     LC_SEGMENT_64 = 0x00000019u
499   };
500 
WriteHeader(Writer * w)501   Writer::Slot<MachOHeader> WriteHeader(Writer* w) {
502     DCHECK_EQ(w->position(), 0);
503     Writer::Slot<MachOHeader> header = w->CreateSlotHere<MachOHeader>();
504 #if V8_TARGET_ARCH_IA32
505     header->magic = 0xFEEDFACEu;
506     header->cputype = 7;     // i386
507     header->cpusubtype = 3;  // CPU_SUBTYPE_I386_ALL
508 #elif V8_TARGET_ARCH_X64
509     header->magic = 0xFEEDFACFu;
510     header->cputype = 7 | 0x01000000;  // i386 | 64-bit ABI
511     header->cpusubtype = 3;            // CPU_SUBTYPE_I386_ALL
512     header->reserved = 0;
513 #else
514 #error Unsupported target architecture.
515 #endif
516     header->filetype = 0x1;  // MH_OBJECT
517     header->ncmds = 1;
518     header->sizeofcmds = 0;
519     header->flags = 0;
520     return header;
521   }
522 
WriteSegmentCommand(Writer * w,uintptr_t code_start,uintptr_t code_size)523   Writer::Slot<MachOSegmentCommand> WriteSegmentCommand(Writer* w,
524                                                         uintptr_t code_start,
525                                                         uintptr_t code_size) {
526     Writer::Slot<MachOSegmentCommand> cmd =
527         w->CreateSlotHere<MachOSegmentCommand>();
528 #if V8_TARGET_ARCH_IA32
529     cmd->cmd = LC_SEGMENT_32;
530 #else
531     cmd->cmd = LC_SEGMENT_64;
532 #endif
533     cmd->vmaddr = code_start;
534     cmd->vmsize = code_size;
535     cmd->fileoff = 0;
536     cmd->filesize = 0;
537     cmd->maxprot = 7;
538     cmd->initprot = 7;
539     cmd->flags = 0;
540     cmd->nsects = static_cast<uint32_t>(sections_.size());
541     memset(cmd->segname, 0, 16);
542     cmd->cmdsize = sizeof(MachOSegmentCommand) +
543                    sizeof(MachOSection::Header) * cmd->nsects;
544     return cmd;
545   }
546 
WriteSections(Writer * w,Writer::Slot<MachOSegmentCommand> cmd,Writer::Slot<MachOHeader> header,uintptr_t load_command_start)547   void WriteSections(Writer* w, Writer::Slot<MachOSegmentCommand> cmd,
548                      Writer::Slot<MachOHeader> header,
549                      uintptr_t load_command_start) {
550     Writer::Slot<MachOSection::Header> headers =
551         w->CreateSlotsHere<MachOSection::Header>(
552             static_cast<uint32_t>(sections_.size()));
553     cmd->fileoff = w->position();
554     header->sizeofcmds =
555         static_cast<uint32_t>(w->position() - load_command_start);
556     uint32_t index = 0;
557     for (MachOSection* section : sections_) {
558       section->PopulateHeader(headers.at(index));
559       section->WriteBody(headers.at(index), w);
560       index++;
561     }
562     cmd->filesize = w->position() - (uintptr_t)cmd->fileoff;
563   }
564 
565   ZoneChunkList<MachOSection*> sections_;
566 };
567 #endif  // defined(__MACH_O)
568 
569 #if defined(__ELF)
570 class ELF {
571  public:
ELF(Zone * zone)572   explicit ELF(Zone* zone) : sections_(zone) {
573     sections_.push_back(zone->New<ELFSection>("", ELFSection::TYPE_NULL, 0));
574     sections_.push_back(zone->New<ELFStringTable>(".shstrtab"));
575   }
576 
Write(Writer * w)577   void Write(Writer* w) {
578     WriteHeader(w);
579     WriteSectionTable(w);
580     WriteSections(w);
581   }
582 
SectionAt(uint32_t index)583   ELFSection* SectionAt(uint32_t index) { return *sections_.Find(index); }
584 
AddSection(ELFSection * section)585   size_t AddSection(ELFSection* section) {
586     sections_.push_back(section);
587     section->set_index(sections_.size() - 1);
588     return sections_.size() - 1;
589   }
590 
591  private:
592   struct ELFHeader {
593     uint8_t ident[16];
594     uint16_t type;
595     uint16_t machine;
596     uint32_t version;
597     uintptr_t entry;
598     uintptr_t pht_offset;
599     uintptr_t sht_offset;
600     uint32_t flags;
601     uint16_t header_size;
602     uint16_t pht_entry_size;
603     uint16_t pht_entry_num;
604     uint16_t sht_entry_size;
605     uint16_t sht_entry_num;
606     uint16_t sht_strtab_index;
607   };
608 
WriteHeader(Writer * w)609   void WriteHeader(Writer* w) {
610     DCHECK_EQ(w->position(), 0);
611     Writer::Slot<ELFHeader> header = w->CreateSlotHere<ELFHeader>();
612 #if (V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_ARM)
613     const uint8_t ident[16] = {0x7F, 'E', 'L', 'F', 1, 1, 1, 0,
614                                0,    0,   0,   0,   0, 0, 0, 0};
615 #elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT || \
616     V8_TARGET_ARCH_PPC64 && V8_TARGET_LITTLE_ENDIAN
617     const uint8_t ident[16] = {0x7F, 'E', 'L', 'F', 2, 1, 1, 0,
618                                0,    0,   0,   0,   0, 0, 0, 0};
619 #elif V8_TARGET_ARCH_PPC64 && V8_TARGET_BIG_ENDIAN && V8_OS_LINUX
620     const uint8_t ident[16] = {0x7F, 'E', 'L', 'F', 2, 2, 1, 0,
621                                0,    0,   0,   0,   0, 0, 0, 0};
622 #elif V8_TARGET_ARCH_S390X
623     const uint8_t ident[16] = {0x7F, 'E', 'L', 'F', 2, 2, 1, 3,
624                                0,    0,   0,   0,   0, 0, 0, 0};
625 #elif V8_TARGET_ARCH_S390
626     const uint8_t ident[16] = {0x7F, 'E', 'L', 'F', 1, 2, 1, 3,
627                                0,    0,   0,   0,   0, 0, 0, 0};
628 #else
629 #error Unsupported target architecture.
630 #endif
631     memcpy(header->ident, ident, 16);
632     header->type = 1;
633 #if V8_TARGET_ARCH_IA32
634     header->machine = 3;
635 #elif V8_TARGET_ARCH_X64
636     // Processor identification value for x64 is 62 as defined in
637     //    System V ABI, AMD64 Supplement
638     //    http://www.x86-64.org/documentation/abi.pdf
639     header->machine = 62;
640 #elif V8_TARGET_ARCH_ARM
641     // Set to EM_ARM, defined as 40, in "ARM ELF File Format" at
642     // infocenter.arm.com/help/topic/com.arm.doc.dui0101a/DUI0101A_Elf.pdf
643     header->machine = 40;
644 #elif V8_TARGET_ARCH_PPC64 && V8_OS_LINUX
645     // Set to EM_PPC64, defined as 21, in Power ABI,
646     // Join the next 4 lines, omitting the spaces and double-slashes.
647     // https://www-03.ibm.com/technologyconnect/tgcm/TGCMFileServlet.wss/
648     // ABI64BitOpenPOWERv1.1_16July2015_pub.pdf?
649     // id=B81AEC1A37F5DAF185257C3E004E8845&linkid=1n0000&c_t=
650     // c9xw7v5dzsj7gt1ifgf4cjbcnskqptmr
651     header->machine = 21;
652 #elif V8_TARGET_ARCH_S390
653     // Processor identification value is 22 (EM_S390) as defined in the ABI:
654     // http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_s390.html#AEN1691
655     // http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_zSeries.html#AEN1599
656     header->machine = 22;
657 #else
658 #error Unsupported target architecture.
659 #endif
660     header->version = 1;
661     header->entry = 0;
662     header->pht_offset = 0;
663     header->sht_offset = sizeof(ELFHeader);  // Section table follows header.
664     header->flags = 0;
665     header->header_size = sizeof(ELFHeader);
666     header->pht_entry_size = 0;
667     header->pht_entry_num = 0;
668     header->sht_entry_size = sizeof(ELFSection::Header);
669     header->sht_entry_num = sections_.size();
670     header->sht_strtab_index = 1;
671   }
672 
WriteSectionTable(Writer * w)673   void WriteSectionTable(Writer* w) {
674     // Section headers table immediately follows file header.
675     DCHECK(w->position() == sizeof(ELFHeader));
676 
677     Writer::Slot<ELFSection::Header> headers =
678         w->CreateSlotsHere<ELFSection::Header>(
679             static_cast<uint32_t>(sections_.size()));
680 
681     // String table for section table is the first section.
682     ELFStringTable* strtab = static_cast<ELFStringTable*>(SectionAt(1));
683     strtab->AttachWriter(w);
684     uint32_t index = 0;
685     for (ELFSection* section : sections_) {
686       section->PopulateHeader(headers.at(index), strtab);
687       index++;
688     }
689     strtab->DetachWriter();
690   }
691 
SectionHeaderPosition(uint32_t section_index)692   int SectionHeaderPosition(uint32_t section_index) {
693     return sizeof(ELFHeader) + sizeof(ELFSection::Header) * section_index;
694   }
695 
WriteSections(Writer * w)696   void WriteSections(Writer* w) {
697     Writer::Slot<ELFSection::Header> headers =
698         w->SlotAt<ELFSection::Header>(sizeof(ELFHeader));
699 
700     uint32_t index = 0;
701     for (ELFSection* section : sections_) {
702       section->WriteBody(headers.at(index), w);
703       index++;
704     }
705   }
706 
707   ZoneChunkList<ELFSection*> sections_;
708 };
709 
710 class ELFSymbol {
711  public:
712   enum Type {
713     TYPE_NOTYPE = 0,
714     TYPE_OBJECT = 1,
715     TYPE_FUNC = 2,
716     TYPE_SECTION = 3,
717     TYPE_FILE = 4,
718     TYPE_LOPROC = 13,
719     TYPE_HIPROC = 15
720   };
721 
722   enum Binding {
723     BIND_LOCAL = 0,
724     BIND_GLOBAL = 1,
725     BIND_WEAK = 2,
726     BIND_LOPROC = 13,
727     BIND_HIPROC = 15
728   };
729 
ELFSymbol(const char * name,uintptr_t value,uintptr_t size,Binding binding,Type type,uint16_t section)730   ELFSymbol(const char* name, uintptr_t value, uintptr_t size, Binding binding,
731             Type type, uint16_t section)
732       : name(name),
733         value(value),
734         size(size),
735         info((binding << 4) | type),
736         other(0),
737         section(section) {}
738 
binding() const739   Binding binding() const { return static_cast<Binding>(info >> 4); }
740 #if (V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_ARM || \
741      (V8_TARGET_ARCH_S390 && V8_TARGET_ARCH_32_BIT))
742   struct SerializedLayout {
SerializedLayoutv8::internal::GDBJITInterface::ELFSymbol::SerializedLayout743     SerializedLayout(uint32_t name, uintptr_t value, uintptr_t size,
744                      Binding binding, Type type, uint16_t section)
745         : name(name),
746           value(value),
747           size(size),
748           info((binding << 4) | type),
749           other(0),
750           section(section) {}
751 
752     uint32_t name;
753     uintptr_t value;
754     uintptr_t size;
755     uint8_t info;
756     uint8_t other;
757     uint16_t section;
758   };
759 #elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT || \
760     V8_TARGET_ARCH_PPC64 && V8_OS_LINUX || V8_TARGET_ARCH_S390X
761   struct SerializedLayout {
SerializedLayoutv8::internal::GDBJITInterface::ELFSymbol::SerializedLayout762     SerializedLayout(uint32_t name, uintptr_t value, uintptr_t size,
763                      Binding binding, Type type, uint16_t section)
764         : name(name),
765           info((binding << 4) | type),
766           other(0),
767           section(section),
768           value(value),
769           size(size) {}
770 
771     uint32_t name;
772     uint8_t info;
773     uint8_t other;
774     uint16_t section;
775     uintptr_t value;
776     uintptr_t size;
777   };
778 #endif
779 
Write(Writer::Slot<SerializedLayout> s,ELFStringTable * t) const780   void Write(Writer::Slot<SerializedLayout> s, ELFStringTable* t) const {
781     // Convert symbol names from strings to indexes in the string table.
782     s->name = static_cast<uint32_t>(t->Add(name));
783     s->value = value;
784     s->size = size;
785     s->info = info;
786     s->other = other;
787     s->section = section;
788   }
789 
790  private:
791   const char* name;
792   uintptr_t value;
793   uintptr_t size;
794   uint8_t info;
795   uint8_t other;
796   uint16_t section;
797 };
798 
799 class ELFSymbolTable : public ELFSection {
800  public:
ELFSymbolTable(const char * name,Zone * zone)801   ELFSymbolTable(const char* name, Zone* zone)
802       : ELFSection(name, TYPE_SYMTAB, sizeof(uintptr_t)),
803         locals_(zone),
804         globals_(zone) {}
805 
WriteBody(Writer::Slot<Header> header,Writer * w)806   void WriteBody(Writer::Slot<Header> header, Writer* w) override {
807     w->Align(header->alignment);
808     size_t total_symbols = locals_.size() + globals_.size() + 1;
809     header->offset = w->position();
810 
811     Writer::Slot<ELFSymbol::SerializedLayout> symbols =
812         w->CreateSlotsHere<ELFSymbol::SerializedLayout>(
813             static_cast<uint32_t>(total_symbols));
814 
815     header->size = w->position() - header->offset;
816 
817     // String table for this symbol table should follow it in the section table.
818     ELFStringTable* strtab =
819         static_cast<ELFStringTable*>(w->debug_object()->SectionAt(index() + 1));
820     strtab->AttachWriter(w);
821     symbols.at(0).set(ELFSymbol::SerializedLayout(
822         0, 0, 0, ELFSymbol::BIND_LOCAL, ELFSymbol::TYPE_NOTYPE, 0));
823     WriteSymbolsList(&locals_, symbols.at(1), strtab);
824     WriteSymbolsList(&globals_,
825                      symbols.at(static_cast<uint32_t>(locals_.size() + 1)),
826                      strtab);
827     strtab->DetachWriter();
828   }
829 
Add(const ELFSymbol & symbol)830   void Add(const ELFSymbol& symbol) {
831     if (symbol.binding() == ELFSymbol::BIND_LOCAL) {
832       locals_.push_back(symbol);
833     } else {
834       globals_.push_back(symbol);
835     }
836   }
837 
838  protected:
PopulateHeader(Writer::Slot<Header> header)839   void PopulateHeader(Writer::Slot<Header> header) override {
840     ELFSection::PopulateHeader(header);
841     // We are assuming that string table will follow symbol table.
842     header->link = index() + 1;
843     header->info = static_cast<uint32_t>(locals_.size() + 1);
844     header->entry_size = sizeof(ELFSymbol::SerializedLayout);
845   }
846 
847  private:
WriteSymbolsList(const ZoneChunkList<ELFSymbol> * src,Writer::Slot<ELFSymbol::SerializedLayout> dst,ELFStringTable * strtab)848   void WriteSymbolsList(const ZoneChunkList<ELFSymbol>* src,
849                         Writer::Slot<ELFSymbol::SerializedLayout> dst,
850                         ELFStringTable* strtab) {
851     int i = 0;
852     for (const ELFSymbol& symbol : *src) {
853       symbol.Write(dst.at(i++), strtab);
854     }
855   }
856 
857   ZoneChunkList<ELFSymbol> locals_;
858   ZoneChunkList<ELFSymbol> globals_;
859 };
860 #endif  // defined(__ELF)
861 
862 class LineInfo : public Malloced {
863  public:
SetPosition(intptr_t pc,int pos,bool is_statement)864   void SetPosition(intptr_t pc, int pos, bool is_statement) {
865     AddPCInfo(PCInfo(pc, pos, is_statement));
866   }
867 
868   struct PCInfo {
PCInfov8::internal::GDBJITInterface::LineInfo::PCInfo869     PCInfo(intptr_t pc, int pos, bool is_statement)
870         : pc_(pc), pos_(pos), is_statement_(is_statement) {}
871 
872     intptr_t pc_;
873     int pos_;
874     bool is_statement_;
875   };
876 
pc_info()877   std::vector<PCInfo>* pc_info() { return &pc_info_; }
878 
879  private:
AddPCInfo(const PCInfo & pc_info)880   void AddPCInfo(const PCInfo& pc_info) { pc_info_.push_back(pc_info); }
881 
882   std::vector<PCInfo> pc_info_;
883 };
884 
885 class CodeDescription {
886  public:
887 #if V8_TARGET_ARCH_X64
888   enum StackState {
889     POST_RBP_PUSH,
890     POST_RBP_SET,
891     POST_RBP_POP,
892     STACK_STATE_MAX
893   };
894 #endif
895 
CodeDescription(const char * name,Code code,SharedFunctionInfo shared,LineInfo * lineinfo)896   CodeDescription(const char* name, Code code, SharedFunctionInfo shared,
897                   LineInfo* lineinfo)
898       : name_(name), code_(code), shared_info_(shared), lineinfo_(lineinfo) {}
899 
name() const900   const char* name() const { return name_; }
901 
lineinfo() const902   LineInfo* lineinfo() const { return lineinfo_; }
903 
is_function() const904   bool is_function() const {
905     return CodeKindIsOptimizedJSFunction(code_.kind());
906   }
907 
has_scope_info() const908   bool has_scope_info() const { return !shared_info_.is_null(); }
909 
scope_info() const910   ScopeInfo scope_info() const {
911     DCHECK(has_scope_info());
912     return shared_info_.scope_info();
913   }
914 
CodeStart() const915   uintptr_t CodeStart() const {
916     return static_cast<uintptr_t>(code_.InstructionStart());
917   }
918 
CodeEnd() const919   uintptr_t CodeEnd() const {
920     return static_cast<uintptr_t>(code_.InstructionEnd());
921   }
922 
CodeSize() const923   uintptr_t CodeSize() const { return CodeEnd() - CodeStart(); }
924 
has_script()925   bool has_script() {
926     return !shared_info_.is_null() && shared_info_.script().IsScript();
927   }
928 
script()929   Script script() { return Script::cast(shared_info_.script()); }
930 
IsLineInfoAvailable()931   bool IsLineInfoAvailable() { return lineinfo_ != nullptr; }
932 
933 #if V8_TARGET_ARCH_X64
GetStackStateStartAddress(StackState state) const934   uintptr_t GetStackStateStartAddress(StackState state) const {
935     DCHECK(state < STACK_STATE_MAX);
936     return stack_state_start_addresses_[state];
937   }
938 
SetStackStateStartAddress(StackState state,uintptr_t addr)939   void SetStackStateStartAddress(StackState state, uintptr_t addr) {
940     DCHECK(state < STACK_STATE_MAX);
941     stack_state_start_addresses_[state] = addr;
942   }
943 #endif
944 
GetFilename()945   std::unique_ptr<char[]> GetFilename() {
946     if (!shared_info_.is_null()) {
947       return String::cast(script().name()).ToCString();
948     } else {
949       std::unique_ptr<char[]> result(new char[1]);
950       result[0] = 0;
951       return result;
952     }
953   }
954 
GetScriptLineNumber(int pos)955   int GetScriptLineNumber(int pos) {
956     if (!shared_info_.is_null()) {
957       return script().GetLineNumber(pos) + 1;
958     } else {
959       return 0;
960     }
961   }
962 
963  private:
964   const char* name_;
965   Code code_;
966   SharedFunctionInfo shared_info_;
967   LineInfo* lineinfo_;
968 #if V8_TARGET_ARCH_X64
969   uintptr_t stack_state_start_addresses_[STACK_STATE_MAX];
970 #endif
971 };
972 
973 #if defined(__ELF)
CreateSymbolsTable(CodeDescription * desc,Zone * zone,ELF * elf,size_t text_section_index)974 static void CreateSymbolsTable(CodeDescription* desc, Zone* zone, ELF* elf,
975                                size_t text_section_index) {
976   ELFSymbolTable* symtab = zone->New<ELFSymbolTable>(".symtab", zone);
977   ELFStringTable* strtab = zone->New<ELFStringTable>(".strtab");
978 
979   // Symbol table should be followed by the linked string table.
980   elf->AddSection(symtab);
981   elf->AddSection(strtab);
982 
983   symtab->Add(ELFSymbol("V8 Code", 0, 0, ELFSymbol::BIND_LOCAL,
984                         ELFSymbol::TYPE_FILE, ELFSection::INDEX_ABSOLUTE));
985 
986   symtab->Add(ELFSymbol(desc->name(), 0, desc->CodeSize(),
987                         ELFSymbol::BIND_GLOBAL, ELFSymbol::TYPE_FUNC,
988                         text_section_index));
989 }
990 #endif  // defined(__ELF)
991 
992 class DebugInfoSection : public DebugSection {
993  public:
DebugInfoSection(CodeDescription * desc)994   explicit DebugInfoSection(CodeDescription* desc)
995 #if defined(__ELF)
996       : ELFSection(".debug_info", TYPE_PROGBITS, 1),
997 #else
998       : MachOSection("__debug_info", "__DWARF", 1,
999                      MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
1000 #endif
1001         desc_(desc) {
1002   }
1003 
1004   // DWARF2 standard
1005   enum DWARF2LocationOp {
1006     DW_OP_reg0 = 0x50,
1007     DW_OP_reg1 = 0x51,
1008     DW_OP_reg2 = 0x52,
1009     DW_OP_reg3 = 0x53,
1010     DW_OP_reg4 = 0x54,
1011     DW_OP_reg5 = 0x55,
1012     DW_OP_reg6 = 0x56,
1013     DW_OP_reg7 = 0x57,
1014     DW_OP_reg8 = 0x58,
1015     DW_OP_reg9 = 0x59,
1016     DW_OP_reg10 = 0x5A,
1017     DW_OP_reg11 = 0x5B,
1018     DW_OP_reg12 = 0x5C,
1019     DW_OP_reg13 = 0x5D,
1020     DW_OP_reg14 = 0x5E,
1021     DW_OP_reg15 = 0x5F,
1022     DW_OP_reg16 = 0x60,
1023     DW_OP_reg17 = 0x61,
1024     DW_OP_reg18 = 0x62,
1025     DW_OP_reg19 = 0x63,
1026     DW_OP_reg20 = 0x64,
1027     DW_OP_reg21 = 0x65,
1028     DW_OP_reg22 = 0x66,
1029     DW_OP_reg23 = 0x67,
1030     DW_OP_reg24 = 0x68,
1031     DW_OP_reg25 = 0x69,
1032     DW_OP_reg26 = 0x6A,
1033     DW_OP_reg27 = 0x6B,
1034     DW_OP_reg28 = 0x6C,
1035     DW_OP_reg29 = 0x6D,
1036     DW_OP_reg30 = 0x6E,
1037     DW_OP_reg31 = 0x6F,
1038     DW_OP_fbreg = 0x91  // 1 param: SLEB128 offset
1039   };
1040 
1041   enum DWARF2Encoding { DW_ATE_ADDRESS = 0x1, DW_ATE_SIGNED = 0x5 };
1042 
WriteBodyInternal(Writer * w)1043   bool WriteBodyInternal(Writer* w) override {
1044     uintptr_t cu_start = w->position();
1045     Writer::Slot<uint32_t> size = w->CreateSlotHere<uint32_t>();
1046     uintptr_t start = w->position();
1047     w->Write<uint16_t>(2);  // DWARF version.
1048     w->Write<uint32_t>(0);  // Abbreviation table offset.
1049     w->Write<uint8_t>(sizeof(intptr_t));
1050 
1051     w->WriteULEB128(1);  // Abbreviation code.
1052     w->WriteString(desc_->GetFilename().get());
1053     w->Write<intptr_t>(desc_->CodeStart());
1054     w->Write<intptr_t>(desc_->CodeStart() + desc_->CodeSize());
1055     w->Write<uint32_t>(0);
1056 
1057     uint32_t ty_offset = static_cast<uint32_t>(w->position() - cu_start);
1058     w->WriteULEB128(3);
1059     w->Write<uint8_t>(kSystemPointerSize);
1060     w->WriteString("v8value");
1061 
1062     if (desc_->has_scope_info()) {
1063       ScopeInfo scope = desc_->scope_info();
1064       w->WriteULEB128(2);
1065       w->WriteString(desc_->name());
1066       w->Write<intptr_t>(desc_->CodeStart());
1067       w->Write<intptr_t>(desc_->CodeStart() + desc_->CodeSize());
1068       Writer::Slot<uint32_t> fb_block_size = w->CreateSlotHere<uint32_t>();
1069       uintptr_t fb_block_start = w->position();
1070 #if V8_TARGET_ARCH_IA32
1071       w->Write<uint8_t>(DW_OP_reg5);  // The frame pointer's here on ia32
1072 #elif V8_TARGET_ARCH_X64
1073       w->Write<uint8_t>(DW_OP_reg6);  // and here on x64.
1074 #elif V8_TARGET_ARCH_ARM
1075       UNIMPLEMENTED();
1076 #elif V8_TARGET_ARCH_MIPS
1077       UNIMPLEMENTED();
1078 #elif V8_TARGET_ARCH_MIPS64
1079       UNIMPLEMENTED();
1080 #elif V8_TARGET_ARCH_PPC64 && V8_OS_LINUX
1081       w->Write<uint8_t>(DW_OP_reg31);  // The frame pointer is here on PPC64.
1082 #elif V8_TARGET_ARCH_S390
1083       w->Write<uint8_t>(DW_OP_reg11);  // The frame pointer's here on S390.
1084 #else
1085 #error Unsupported target architecture.
1086 #endif
1087       fb_block_size.set(static_cast<uint32_t>(w->position() - fb_block_start));
1088 
1089       int params = scope.ParameterCount();
1090       int context_slots = scope.ContextLocalCount();
1091       // The real slot ID is internal_slots + context_slot_id.
1092       int internal_slots = Context::MIN_CONTEXT_SLOTS;
1093       int current_abbreviation = 4;
1094 
1095       EmbeddedVector<char, 256> buffer;
1096       StringBuilder builder(buffer.begin(), buffer.length());
1097 
1098       for (int param = 0; param < params; ++param) {
1099         w->WriteULEB128(current_abbreviation++);
1100         builder.Reset();
1101         builder.AddFormatted("param%d", param);
1102         w->WriteString(builder.Finalize());
1103         w->Write<uint32_t>(ty_offset);
1104         Writer::Slot<uint32_t> block_size = w->CreateSlotHere<uint32_t>();
1105         uintptr_t block_start = w->position();
1106         w->Write<uint8_t>(DW_OP_fbreg);
1107         w->WriteSLEB128(StandardFrameConstants::kFixedFrameSizeAboveFp +
1108                         kSystemPointerSize * (params - param - 1));
1109         block_size.set(static_cast<uint32_t>(w->position() - block_start));
1110       }
1111 
1112       // See contexts.h for more information.
1113       DCHECK_EQ(Context::MIN_CONTEXT_SLOTS, 3);
1114       DCHECK_EQ(Context::SCOPE_INFO_INDEX, 0);
1115       DCHECK_EQ(Context::PREVIOUS_INDEX, 1);
1116       DCHECK_EQ(Context::EXTENSION_INDEX, 2);
1117       w->WriteULEB128(current_abbreviation++);
1118       w->WriteString(".scope_info");
1119       w->WriteULEB128(current_abbreviation++);
1120       w->WriteString(".previous");
1121       w->WriteULEB128(current_abbreviation++);
1122       w->WriteString(".extension");
1123 
1124       for (int context_slot = 0; context_slot < context_slots; ++context_slot) {
1125         w->WriteULEB128(current_abbreviation++);
1126         builder.Reset();
1127         builder.AddFormatted("context_slot%d", context_slot + internal_slots);
1128         w->WriteString(builder.Finalize());
1129       }
1130 
1131       {
1132         w->WriteULEB128(current_abbreviation++);
1133         w->WriteString("__function");
1134         w->Write<uint32_t>(ty_offset);
1135         Writer::Slot<uint32_t> block_size = w->CreateSlotHere<uint32_t>();
1136         uintptr_t block_start = w->position();
1137         w->Write<uint8_t>(DW_OP_fbreg);
1138         w->WriteSLEB128(StandardFrameConstants::kFunctionOffset);
1139         block_size.set(static_cast<uint32_t>(w->position() - block_start));
1140       }
1141 
1142       {
1143         w->WriteULEB128(current_abbreviation++);
1144         w->WriteString("__context");
1145         w->Write<uint32_t>(ty_offset);
1146         Writer::Slot<uint32_t> block_size = w->CreateSlotHere<uint32_t>();
1147         uintptr_t block_start = w->position();
1148         w->Write<uint8_t>(DW_OP_fbreg);
1149         w->WriteSLEB128(StandardFrameConstants::kContextOffset);
1150         block_size.set(static_cast<uint32_t>(w->position() - block_start));
1151       }
1152 
1153       w->WriteULEB128(0);  // Terminate the sub program.
1154     }
1155 
1156     w->WriteULEB128(0);  // Terminate the compile unit.
1157     size.set(static_cast<uint32_t>(w->position() - start));
1158     return true;
1159   }
1160 
1161  private:
1162   CodeDescription* desc_;
1163 };
1164 
1165 class DebugAbbrevSection : public DebugSection {
1166  public:
DebugAbbrevSection(CodeDescription * desc)1167   explicit DebugAbbrevSection(CodeDescription* desc)
1168 #ifdef __ELF
1169       : ELFSection(".debug_abbrev", TYPE_PROGBITS, 1),
1170 #else
1171       : MachOSection("__debug_abbrev", "__DWARF", 1,
1172                      MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
1173 #endif
1174         desc_(desc) {
1175   }
1176 
1177   // DWARF2 standard, figure 14.
1178   enum DWARF2Tags {
1179     DW_TAG_FORMAL_PARAMETER = 0x05,
1180     DW_TAG_POINTER_TYPE = 0xF,
1181     DW_TAG_COMPILE_UNIT = 0x11,
1182     DW_TAG_STRUCTURE_TYPE = 0x13,
1183     DW_TAG_BASE_TYPE = 0x24,
1184     DW_TAG_SUBPROGRAM = 0x2E,
1185     DW_TAG_VARIABLE = 0x34
1186   };
1187 
1188   // DWARF2 standard, figure 16.
1189   enum DWARF2ChildrenDetermination { DW_CHILDREN_NO = 0, DW_CHILDREN_YES = 1 };
1190 
1191   // DWARF standard, figure 17.
1192   enum DWARF2Attribute {
1193     DW_AT_LOCATION = 0x2,
1194     DW_AT_NAME = 0x3,
1195     DW_AT_BYTE_SIZE = 0xB,
1196     DW_AT_STMT_LIST = 0x10,
1197     DW_AT_LOW_PC = 0x11,
1198     DW_AT_HIGH_PC = 0x12,
1199     DW_AT_ENCODING = 0x3E,
1200     DW_AT_FRAME_BASE = 0x40,
1201     DW_AT_TYPE = 0x49
1202   };
1203 
1204   // DWARF2 standard, figure 19.
1205   enum DWARF2AttributeForm {
1206     DW_FORM_ADDR = 0x1,
1207     DW_FORM_BLOCK4 = 0x4,
1208     DW_FORM_STRING = 0x8,
1209     DW_FORM_DATA4 = 0x6,
1210     DW_FORM_BLOCK = 0x9,
1211     DW_FORM_DATA1 = 0xB,
1212     DW_FORM_FLAG = 0xC,
1213     DW_FORM_REF4 = 0x13
1214   };
1215 
WriteVariableAbbreviation(Writer * w,int abbreviation_code,bool has_value,bool is_parameter)1216   void WriteVariableAbbreviation(Writer* w, int abbreviation_code,
1217                                  bool has_value, bool is_parameter) {
1218     w->WriteULEB128(abbreviation_code);
1219     w->WriteULEB128(is_parameter ? DW_TAG_FORMAL_PARAMETER : DW_TAG_VARIABLE);
1220     w->Write<uint8_t>(DW_CHILDREN_NO);
1221     w->WriteULEB128(DW_AT_NAME);
1222     w->WriteULEB128(DW_FORM_STRING);
1223     if (has_value) {
1224       w->WriteULEB128(DW_AT_TYPE);
1225       w->WriteULEB128(DW_FORM_REF4);
1226       w->WriteULEB128(DW_AT_LOCATION);
1227       w->WriteULEB128(DW_FORM_BLOCK4);
1228     }
1229     w->WriteULEB128(0);
1230     w->WriteULEB128(0);
1231   }
1232 
WriteBodyInternal(Writer * w)1233   bool WriteBodyInternal(Writer* w) override {
1234     int current_abbreviation = 1;
1235     bool extra_info = desc_->has_scope_info();
1236     DCHECK(desc_->IsLineInfoAvailable());
1237     w->WriteULEB128(current_abbreviation++);
1238     w->WriteULEB128(DW_TAG_COMPILE_UNIT);
1239     w->Write<uint8_t>(extra_info ? DW_CHILDREN_YES : DW_CHILDREN_NO);
1240     w->WriteULEB128(DW_AT_NAME);
1241     w->WriteULEB128(DW_FORM_STRING);
1242     w->WriteULEB128(DW_AT_LOW_PC);
1243     w->WriteULEB128(DW_FORM_ADDR);
1244     w->WriteULEB128(DW_AT_HIGH_PC);
1245     w->WriteULEB128(DW_FORM_ADDR);
1246     w->WriteULEB128(DW_AT_STMT_LIST);
1247     w->WriteULEB128(DW_FORM_DATA4);
1248     w->WriteULEB128(0);
1249     w->WriteULEB128(0);
1250 
1251     if (extra_info) {
1252       ScopeInfo scope = desc_->scope_info();
1253       int params = scope.ParameterCount();
1254       int context_slots = scope.ContextLocalCount();
1255       // The real slot ID is internal_slots + context_slot_id.
1256       int internal_slots = Context::MIN_CONTEXT_SLOTS;
1257       // Total children is params + context_slots + internal_slots + 2
1258       // (__function and __context).
1259 
1260       // The extra duplication below seems to be necessary to keep
1261       // gdb from getting upset on OSX.
1262       w->WriteULEB128(current_abbreviation++);  // Abbreviation code.
1263       w->WriteULEB128(DW_TAG_SUBPROGRAM);
1264       w->Write<uint8_t>(DW_CHILDREN_YES);
1265       w->WriteULEB128(DW_AT_NAME);
1266       w->WriteULEB128(DW_FORM_STRING);
1267       w->WriteULEB128(DW_AT_LOW_PC);
1268       w->WriteULEB128(DW_FORM_ADDR);
1269       w->WriteULEB128(DW_AT_HIGH_PC);
1270       w->WriteULEB128(DW_FORM_ADDR);
1271       w->WriteULEB128(DW_AT_FRAME_BASE);
1272       w->WriteULEB128(DW_FORM_BLOCK4);
1273       w->WriteULEB128(0);
1274       w->WriteULEB128(0);
1275 
1276       w->WriteULEB128(current_abbreviation++);
1277       w->WriteULEB128(DW_TAG_STRUCTURE_TYPE);
1278       w->Write<uint8_t>(DW_CHILDREN_NO);
1279       w->WriteULEB128(DW_AT_BYTE_SIZE);
1280       w->WriteULEB128(DW_FORM_DATA1);
1281       w->WriteULEB128(DW_AT_NAME);
1282       w->WriteULEB128(DW_FORM_STRING);
1283       w->WriteULEB128(0);
1284       w->WriteULEB128(0);
1285 
1286       for (int param = 0; param < params; ++param) {
1287         WriteVariableAbbreviation(w, current_abbreviation++, true, true);
1288       }
1289 
1290       for (int internal_slot = 0; internal_slot < internal_slots;
1291            ++internal_slot) {
1292         WriteVariableAbbreviation(w, current_abbreviation++, false, false);
1293       }
1294 
1295       for (int context_slot = 0; context_slot < context_slots; ++context_slot) {
1296         WriteVariableAbbreviation(w, current_abbreviation++, false, false);
1297       }
1298 
1299       // The function.
1300       WriteVariableAbbreviation(w, current_abbreviation++, true, false);
1301 
1302       // The context.
1303       WriteVariableAbbreviation(w, current_abbreviation++, true, false);
1304 
1305       w->WriteULEB128(0);  // Terminate the sibling list.
1306     }
1307 
1308     w->WriteULEB128(0);  // Terminate the table.
1309     return true;
1310   }
1311 
1312  private:
1313   CodeDescription* desc_;
1314 };
1315 
1316 class DebugLineSection : public DebugSection {
1317  public:
DebugLineSection(CodeDescription * desc)1318   explicit DebugLineSection(CodeDescription* desc)
1319 #ifdef __ELF
1320       : ELFSection(".debug_line", TYPE_PROGBITS, 1),
1321 #else
1322       : MachOSection("__debug_line", "__DWARF", 1,
1323                      MachOSection::S_REGULAR | MachOSection::S_ATTR_DEBUG),
1324 #endif
1325         desc_(desc) {
1326   }
1327 
1328   // DWARF2 standard, figure 34.
1329   enum DWARF2Opcodes {
1330     DW_LNS_COPY = 1,
1331     DW_LNS_ADVANCE_PC = 2,
1332     DW_LNS_ADVANCE_LINE = 3,
1333     DW_LNS_SET_FILE = 4,
1334     DW_LNS_SET_COLUMN = 5,
1335     DW_LNS_NEGATE_STMT = 6
1336   };
1337 
1338   // DWARF2 standard, figure 35.
1339   enum DWARF2ExtendedOpcode {
1340     DW_LNE_END_SEQUENCE = 1,
1341     DW_LNE_SET_ADDRESS = 2,
1342     DW_LNE_DEFINE_FILE = 3
1343   };
1344 
WriteBodyInternal(Writer * w)1345   bool WriteBodyInternal(Writer* w) override {
1346     // Write prologue.
1347     Writer::Slot<uint32_t> total_length = w->CreateSlotHere<uint32_t>();
1348     uintptr_t start = w->position();
1349 
1350     // Used for special opcodes
1351     const int8_t line_base = 1;
1352     const uint8_t line_range = 7;
1353     const int8_t max_line_incr = (line_base + line_range - 1);
1354     const uint8_t opcode_base = DW_LNS_NEGATE_STMT + 1;
1355 
1356     w->Write<uint16_t>(2);  // Field version.
1357     Writer::Slot<uint32_t> prologue_length = w->CreateSlotHere<uint32_t>();
1358     uintptr_t prologue_start = w->position();
1359     w->Write<uint8_t>(1);            // Field minimum_instruction_length.
1360     w->Write<uint8_t>(1);            // Field default_is_stmt.
1361     w->Write<int8_t>(line_base);     // Field line_base.
1362     w->Write<uint8_t>(line_range);   // Field line_range.
1363     w->Write<uint8_t>(opcode_base);  // Field opcode_base.
1364     w->Write<uint8_t>(0);            // DW_LNS_COPY operands count.
1365     w->Write<uint8_t>(1);            // DW_LNS_ADVANCE_PC operands count.
1366     w->Write<uint8_t>(1);            // DW_LNS_ADVANCE_LINE operands count.
1367     w->Write<uint8_t>(1);            // DW_LNS_SET_FILE operands count.
1368     w->Write<uint8_t>(1);            // DW_LNS_SET_COLUMN operands count.
1369     w->Write<uint8_t>(0);            // DW_LNS_NEGATE_STMT operands count.
1370     w->Write<uint8_t>(0);            // Empty include_directories sequence.
1371     w->WriteString(desc_->GetFilename().get());  // File name.
1372     w->WriteULEB128(0);                          // Current directory.
1373     w->WriteULEB128(0);                          // Unknown modification time.
1374     w->WriteULEB128(0);                          // Unknown file size.
1375     w->Write<uint8_t>(0);
1376     prologue_length.set(static_cast<uint32_t>(w->position() - prologue_start));
1377 
1378     WriteExtendedOpcode(w, DW_LNE_SET_ADDRESS, sizeof(intptr_t));
1379     w->Write<intptr_t>(desc_->CodeStart());
1380     w->Write<uint8_t>(DW_LNS_COPY);
1381 
1382     intptr_t pc = 0;
1383     intptr_t line = 1;
1384     bool is_statement = true;
1385 
1386     std::vector<LineInfo::PCInfo>* pc_info = desc_->lineinfo()->pc_info();
1387     std::sort(pc_info->begin(), pc_info->end(), &ComparePCInfo);
1388 
1389     for (size_t i = 0; i < pc_info->size(); i++) {
1390       LineInfo::PCInfo* info = &pc_info->at(i);
1391       DCHECK(info->pc_ >= pc);
1392 
1393       // Reduce bloating in the debug line table by removing duplicate line
1394       // entries (per DWARF2 standard).
1395       intptr_t new_line = desc_->GetScriptLineNumber(info->pos_);
1396       if (new_line == line) {
1397         continue;
1398       }
1399 
1400       // Mark statement boundaries.  For a better debugging experience, mark
1401       // the last pc address in the function as a statement (e.g. "}"), so that
1402       // a user can see the result of the last line executed in the function,
1403       // should control reach the end.
1404       if ((i + 1) == pc_info->size()) {
1405         if (!is_statement) {
1406           w->Write<uint8_t>(DW_LNS_NEGATE_STMT);
1407         }
1408       } else if (is_statement != info->is_statement_) {
1409         w->Write<uint8_t>(DW_LNS_NEGATE_STMT);
1410         is_statement = !is_statement;
1411       }
1412 
1413       // Generate special opcodes, if possible.  This results in more compact
1414       // debug line tables.  See the DWARF 2.0 standard to learn more about
1415       // special opcodes.
1416       uintptr_t pc_diff = info->pc_ - pc;
1417       intptr_t line_diff = new_line - line;
1418 
1419       // Compute special opcode (see DWARF 2.0 standard)
1420       intptr_t special_opcode =
1421           (line_diff - line_base) + (line_range * pc_diff) + opcode_base;
1422 
1423       // If special_opcode is less than or equal to 255, it can be used as a
1424       // special opcode.  If line_diff is larger than the max line increment
1425       // allowed for a special opcode, or if line_diff is less than the minimum
1426       // line that can be added to the line register (i.e. line_base), then
1427       // special_opcode can't be used.
1428       if ((special_opcode >= opcode_base) && (special_opcode <= 255) &&
1429           (line_diff <= max_line_incr) && (line_diff >= line_base)) {
1430         w->Write<uint8_t>(special_opcode);
1431       } else {
1432         w->Write<uint8_t>(DW_LNS_ADVANCE_PC);
1433         w->WriteSLEB128(pc_diff);
1434         w->Write<uint8_t>(DW_LNS_ADVANCE_LINE);
1435         w->WriteSLEB128(line_diff);
1436         w->Write<uint8_t>(DW_LNS_COPY);
1437       }
1438 
1439       // Increment the pc and line operands.
1440       pc += pc_diff;
1441       line += line_diff;
1442     }
1443     // Advance the pc to the end of the routine, since the end sequence opcode
1444     // requires this.
1445     w->Write<uint8_t>(DW_LNS_ADVANCE_PC);
1446     w->WriteSLEB128(desc_->CodeSize() - pc);
1447     WriteExtendedOpcode(w, DW_LNE_END_SEQUENCE, 0);
1448     total_length.set(static_cast<uint32_t>(w->position() - start));
1449     return true;
1450   }
1451 
1452  private:
WriteExtendedOpcode(Writer * w,DWARF2ExtendedOpcode op,size_t operands_size)1453   void WriteExtendedOpcode(Writer* w, DWARF2ExtendedOpcode op,
1454                            size_t operands_size) {
1455     w->Write<uint8_t>(0);
1456     w->WriteULEB128(operands_size + 1);
1457     w->Write<uint8_t>(op);
1458   }
1459 
ComparePCInfo(const LineInfo::PCInfo & a,const LineInfo::PCInfo & b)1460   static bool ComparePCInfo(const LineInfo::PCInfo& a,
1461                             const LineInfo::PCInfo& b) {
1462     if (a.pc_ == b.pc_) {
1463       if (a.is_statement_ != b.is_statement_) {
1464         return !b.is_statement_;
1465       }
1466       return false;
1467     }
1468     return a.pc_ < b.pc_;
1469   }
1470 
1471   CodeDescription* desc_;
1472 };
1473 
1474 #if V8_TARGET_ARCH_X64
1475 
1476 class UnwindInfoSection : public DebugSection {
1477  public:
1478   explicit UnwindInfoSection(CodeDescription* desc);
1479   bool WriteBodyInternal(Writer* w) override;
1480 
1481   int WriteCIE(Writer* w);
1482   void WriteFDE(Writer* w, int);
1483 
1484   void WriteFDEStateOnEntry(Writer* w);
1485   void WriteFDEStateAfterRBPPush(Writer* w);
1486   void WriteFDEStateAfterRBPSet(Writer* w);
1487   void WriteFDEStateAfterRBPPop(Writer* w);
1488 
1489   void WriteLength(Writer* w, Writer::Slot<uint32_t>* length_slot,
1490                    int initial_position);
1491 
1492  private:
1493   CodeDescription* desc_;
1494 
1495   // DWARF3 Specification, Table 7.23
1496   enum CFIInstructions {
1497     DW_CFA_ADVANCE_LOC = 0x40,
1498     DW_CFA_OFFSET = 0x80,
1499     DW_CFA_RESTORE = 0xC0,
1500     DW_CFA_NOP = 0x00,
1501     DW_CFA_SET_LOC = 0x01,
1502     DW_CFA_ADVANCE_LOC1 = 0x02,
1503     DW_CFA_ADVANCE_LOC2 = 0x03,
1504     DW_CFA_ADVANCE_LOC4 = 0x04,
1505     DW_CFA_OFFSET_EXTENDED = 0x05,
1506     DW_CFA_RESTORE_EXTENDED = 0x06,
1507     DW_CFA_UNDEFINED = 0x07,
1508     DW_CFA_SAME_VALUE = 0x08,
1509     DW_CFA_REGISTER = 0x09,
1510     DW_CFA_REMEMBER_STATE = 0x0A,
1511     DW_CFA_RESTORE_STATE = 0x0B,
1512     DW_CFA_DEF_CFA = 0x0C,
1513     DW_CFA_DEF_CFA_REGISTER = 0x0D,
1514     DW_CFA_DEF_CFA_OFFSET = 0x0E,
1515 
1516     DW_CFA_DEF_CFA_EXPRESSION = 0x0F,
1517     DW_CFA_EXPRESSION = 0x10,
1518     DW_CFA_OFFSET_EXTENDED_SF = 0x11,
1519     DW_CFA_DEF_CFA_SF = 0x12,
1520     DW_CFA_DEF_CFA_OFFSET_SF = 0x13,
1521     DW_CFA_VAL_OFFSET = 0x14,
1522     DW_CFA_VAL_OFFSET_SF = 0x15,
1523     DW_CFA_VAL_EXPRESSION = 0x16
1524   };
1525 
1526   // System V ABI, AMD64 Supplement, Version 0.99.5, Figure 3.36
1527   enum RegisterMapping {
1528     // Only the relevant ones have been added to reduce clutter.
1529     AMD64_RBP = 6,
1530     AMD64_RSP = 7,
1531     AMD64_RA = 16
1532   };
1533 
1534   enum CFIConstants {
1535     CIE_ID = 0,
1536     CIE_VERSION = 1,
1537     CODE_ALIGN_FACTOR = 1,
1538     DATA_ALIGN_FACTOR = 1,
1539     RETURN_ADDRESS_REGISTER = AMD64_RA
1540   };
1541 };
1542 
WriteLength(Writer * w,Writer::Slot<uint32_t> * length_slot,int initial_position)1543 void UnwindInfoSection::WriteLength(Writer* w,
1544                                     Writer::Slot<uint32_t>* length_slot,
1545                                     int initial_position) {
1546   uint32_t align = (w->position() - initial_position) % kSystemPointerSize;
1547 
1548   if (align != 0) {
1549     for (uint32_t i = 0; i < (kSystemPointerSize - align); i++) {
1550       w->Write<uint8_t>(DW_CFA_NOP);
1551     }
1552   }
1553 
1554   DCHECK_EQ((w->position() - initial_position) % kSystemPointerSize, 0);
1555   length_slot->set(static_cast<uint32_t>(w->position() - initial_position));
1556 }
1557 
UnwindInfoSection(CodeDescription * desc)1558 UnwindInfoSection::UnwindInfoSection(CodeDescription* desc)
1559 #ifdef __ELF
1560     : ELFSection(".eh_frame", TYPE_X86_64_UNWIND, 1),
1561 #else
1562     : MachOSection("__eh_frame", "__TEXT", sizeof(uintptr_t),
1563                    MachOSection::S_REGULAR),
1564 #endif
1565       desc_(desc) {
1566 }
1567 
WriteCIE(Writer * w)1568 int UnwindInfoSection::WriteCIE(Writer* w) {
1569   Writer::Slot<uint32_t> cie_length_slot = w->CreateSlotHere<uint32_t>();
1570   uint32_t cie_position = static_cast<uint32_t>(w->position());
1571 
1572   // Write out the CIE header. Currently no 'common instructions' are
1573   // emitted onto the CIE; every FDE has its own set of instructions.
1574 
1575   w->Write<uint32_t>(CIE_ID);
1576   w->Write<uint8_t>(CIE_VERSION);
1577   w->Write<uint8_t>(0);  // Null augmentation string.
1578   w->WriteSLEB128(CODE_ALIGN_FACTOR);
1579   w->WriteSLEB128(DATA_ALIGN_FACTOR);
1580   w->Write<uint8_t>(RETURN_ADDRESS_REGISTER);
1581 
1582   WriteLength(w, &cie_length_slot, cie_position);
1583 
1584   return cie_position;
1585 }
1586 
WriteFDE(Writer * w,int cie_position)1587 void UnwindInfoSection::WriteFDE(Writer* w, int cie_position) {
1588   // The only FDE for this function. The CFA is the current RBP.
1589   Writer::Slot<uint32_t> fde_length_slot = w->CreateSlotHere<uint32_t>();
1590   int fde_position = static_cast<uint32_t>(w->position());
1591   w->Write<int32_t>(fde_position - cie_position + 4);
1592 
1593   w->Write<uintptr_t>(desc_->CodeStart());
1594   w->Write<uintptr_t>(desc_->CodeSize());
1595 
1596   WriteFDEStateOnEntry(w);
1597   WriteFDEStateAfterRBPPush(w);
1598   WriteFDEStateAfterRBPSet(w);
1599   WriteFDEStateAfterRBPPop(w);
1600 
1601   WriteLength(w, &fde_length_slot, fde_position);
1602 }
1603 
WriteFDEStateOnEntry(Writer * w)1604 void UnwindInfoSection::WriteFDEStateOnEntry(Writer* w) {
1605   // The first state, just after the control has been transferred to the the
1606   // function.
1607 
1608   // RBP for this function will be the value of RSP after pushing the RBP
1609   // for the previous function. The previous RBP has not been pushed yet.
1610   w->Write<uint8_t>(DW_CFA_DEF_CFA_SF);
1611   w->WriteULEB128(AMD64_RSP);
1612   w->WriteSLEB128(-kSystemPointerSize);
1613 
1614   // The RA is stored at location CFA + kCallerPCOffset. This is an invariant,
1615   // and hence omitted from the next states.
1616   w->Write<uint8_t>(DW_CFA_OFFSET_EXTENDED);
1617   w->WriteULEB128(AMD64_RA);
1618   w->WriteSLEB128(StandardFrameConstants::kCallerPCOffset);
1619 
1620   // The RBP of the previous function is still in RBP.
1621   w->Write<uint8_t>(DW_CFA_SAME_VALUE);
1622   w->WriteULEB128(AMD64_RBP);
1623 
1624   // Last location described by this entry.
1625   w->Write<uint8_t>(DW_CFA_SET_LOC);
1626   w->Write<uint64_t>(
1627       desc_->GetStackStateStartAddress(CodeDescription::POST_RBP_PUSH));
1628 }
1629 
WriteFDEStateAfterRBPPush(Writer * w)1630 void UnwindInfoSection::WriteFDEStateAfterRBPPush(Writer* w) {
1631   // The second state, just after RBP has been pushed.
1632 
1633   // RBP / CFA for this function is now the current RSP, so just set the
1634   // offset from the previous rule (from -8) to 0.
1635   w->Write<uint8_t>(DW_CFA_DEF_CFA_OFFSET);
1636   w->WriteULEB128(0);
1637 
1638   // The previous RBP is stored at CFA + kCallerFPOffset. This is an invariant
1639   // in this and the next state, and hence omitted in the next state.
1640   w->Write<uint8_t>(DW_CFA_OFFSET_EXTENDED);
1641   w->WriteULEB128(AMD64_RBP);
1642   w->WriteSLEB128(StandardFrameConstants::kCallerFPOffset);
1643 
1644   // Last location described by this entry.
1645   w->Write<uint8_t>(DW_CFA_SET_LOC);
1646   w->Write<uint64_t>(
1647       desc_->GetStackStateStartAddress(CodeDescription::POST_RBP_SET));
1648 }
1649 
WriteFDEStateAfterRBPSet(Writer * w)1650 void UnwindInfoSection::WriteFDEStateAfterRBPSet(Writer* w) {
1651   // The third state, after the RBP has been set.
1652 
1653   // The CFA can now directly be set to RBP.
1654   w->Write<uint8_t>(DW_CFA_DEF_CFA);
1655   w->WriteULEB128(AMD64_RBP);
1656   w->WriteULEB128(0);
1657 
1658   // Last location described by this entry.
1659   w->Write<uint8_t>(DW_CFA_SET_LOC);
1660   w->Write<uint64_t>(
1661       desc_->GetStackStateStartAddress(CodeDescription::POST_RBP_POP));
1662 }
1663 
WriteFDEStateAfterRBPPop(Writer * w)1664 void UnwindInfoSection::WriteFDEStateAfterRBPPop(Writer* w) {
1665   // The fourth (final) state. The RBP has been popped (just before issuing a
1666   // return).
1667 
1668   // The CFA can is now calculated in the same way as in the first state.
1669   w->Write<uint8_t>(DW_CFA_DEF_CFA_SF);
1670   w->WriteULEB128(AMD64_RSP);
1671   w->WriteSLEB128(-kSystemPointerSize);
1672 
1673   // The RBP
1674   w->Write<uint8_t>(DW_CFA_OFFSET_EXTENDED);
1675   w->WriteULEB128(AMD64_RBP);
1676   w->WriteSLEB128(StandardFrameConstants::kCallerFPOffset);
1677 
1678   // Last location described by this entry.
1679   w->Write<uint8_t>(DW_CFA_SET_LOC);
1680   w->Write<uint64_t>(desc_->CodeEnd());
1681 }
1682 
WriteBodyInternal(Writer * w)1683 bool UnwindInfoSection::WriteBodyInternal(Writer* w) {
1684   uint32_t cie_position = WriteCIE(w);
1685   WriteFDE(w, cie_position);
1686   return true;
1687 }
1688 
1689 #endif  // V8_TARGET_ARCH_X64
1690 
CreateDWARFSections(CodeDescription * desc,Zone * zone,DebugObject * obj)1691 static void CreateDWARFSections(CodeDescription* desc, Zone* zone,
1692                                 DebugObject* obj) {
1693   if (desc->IsLineInfoAvailable()) {
1694     obj->AddSection(zone->New<DebugInfoSection>(desc));
1695     obj->AddSection(zone->New<DebugAbbrevSection>(desc));
1696     obj->AddSection(zone->New<DebugLineSection>(desc));
1697   }
1698 #if V8_TARGET_ARCH_X64
1699   obj->AddSection(zone->New<UnwindInfoSection>(desc));
1700 #endif
1701 }
1702 
1703 // -------------------------------------------------------------------
1704 // Binary GDB JIT Interface as described in
1705 //   http://sourceware.org/gdb/onlinedocs/gdb/Declarations.html
1706 extern "C" {
1707 enum JITAction { JIT_NOACTION = 0, JIT_REGISTER_FN, JIT_UNREGISTER_FN };
1708 
1709 struct JITCodeEntry {
1710   JITCodeEntry* next_;
1711   JITCodeEntry* prev_;
1712   Address symfile_addr_;
1713   uint64_t symfile_size_;
1714 };
1715 
1716 struct JITDescriptor {
1717   uint32_t version_;
1718   uint32_t action_flag_;
1719   JITCodeEntry* relevant_entry_;
1720   JITCodeEntry* first_entry_;
1721 };
1722 
1723 // GDB will place breakpoint into this function.
1724 // To prevent GCC from inlining or removing it we place noinline attribute
1725 // and inline assembler statement inside.
__jit_debug_register_code()1726 void __attribute__((noinline)) __jit_debug_register_code() { __asm__(""); }
1727 
1728 // GDB will inspect contents of this descriptor.
1729 // Static initialization is necessary to prevent GDB from seeing
1730 // uninitialized descriptor.
1731 JITDescriptor __jit_debug_descriptor = {1, 0, nullptr, nullptr};
1732 
1733 #ifdef OBJECT_PRINT
__gdb_print_v8_object(Object object)1734 void __gdb_print_v8_object(Object object) {
1735   StdoutStream os;
1736   object.Print(os);
1737   os << std::flush;
1738 }
1739 #endif
1740 }
1741 
CreateCodeEntry(Address symfile_addr,uintptr_t symfile_size)1742 static JITCodeEntry* CreateCodeEntry(Address symfile_addr,
1743                                      uintptr_t symfile_size) {
1744   JITCodeEntry* entry =
1745       static_cast<JITCodeEntry*>(malloc(sizeof(JITCodeEntry) + symfile_size));
1746 
1747   entry->symfile_addr_ = reinterpret_cast<Address>(entry + 1);
1748   entry->symfile_size_ = symfile_size;
1749   MemCopy(reinterpret_cast<void*>(entry->symfile_addr_),
1750           reinterpret_cast<void*>(symfile_addr), symfile_size);
1751 
1752   entry->prev_ = entry->next_ = nullptr;
1753 
1754   return entry;
1755 }
1756 
DestroyCodeEntry(JITCodeEntry * entry)1757 static void DestroyCodeEntry(JITCodeEntry* entry) { free(entry); }
1758 
RegisterCodeEntry(JITCodeEntry * entry)1759 static void RegisterCodeEntry(JITCodeEntry* entry) {
1760   entry->next_ = __jit_debug_descriptor.first_entry_;
1761   if (entry->next_ != nullptr) entry->next_->prev_ = entry;
1762   __jit_debug_descriptor.first_entry_ = __jit_debug_descriptor.relevant_entry_ =
1763       entry;
1764 
1765   __jit_debug_descriptor.action_flag_ = JIT_REGISTER_FN;
1766   __jit_debug_register_code();
1767 }
1768 
UnregisterCodeEntry(JITCodeEntry * entry)1769 static void UnregisterCodeEntry(JITCodeEntry* entry) {
1770   if (entry->prev_ != nullptr) {
1771     entry->prev_->next_ = entry->next_;
1772   } else {
1773     __jit_debug_descriptor.first_entry_ = entry->next_;
1774   }
1775 
1776   if (entry->next_ != nullptr) {
1777     entry->next_->prev_ = entry->prev_;
1778   }
1779 
1780   __jit_debug_descriptor.relevant_entry_ = entry;
1781   __jit_debug_descriptor.action_flag_ = JIT_UNREGISTER_FN;
1782   __jit_debug_register_code();
1783 }
1784 
CreateELFObject(CodeDescription * desc,Isolate * isolate)1785 static JITCodeEntry* CreateELFObject(CodeDescription* desc, Isolate* isolate) {
1786 #ifdef __MACH_O
1787   Zone zone(isolate->allocator(), ZONE_NAME);
1788   MachO mach_o(&zone);
1789   Writer w(&mach_o);
1790 
1791   const uint32_t code_alignment = static_cast<uint32_t>(kCodeAlignment);
1792   static_assert(code_alignment == kCodeAlignment,
1793                 "Unsupported code alignment value");
1794   mach_o.AddSection(zone.New<MachOTextSection>(
1795       code_alignment, desc->CodeStart(), desc->CodeSize()));
1796 
1797   CreateDWARFSections(desc, &zone, &mach_o);
1798 
1799   mach_o.Write(&w, desc->CodeStart(), desc->CodeSize());
1800 #else
1801   Zone zone(isolate->allocator(), ZONE_NAME);
1802   ELF elf(&zone);
1803   Writer w(&elf);
1804 
1805   size_t text_section_index = elf.AddSection(zone.New<FullHeaderELFSection>(
1806       ".text", ELFSection::TYPE_NOBITS, kCodeAlignment, desc->CodeStart(), 0,
1807       desc->CodeSize(), ELFSection::FLAG_ALLOC | ELFSection::FLAG_EXEC));
1808 
1809   CreateSymbolsTable(desc, &zone, &elf, text_section_index);
1810 
1811   CreateDWARFSections(desc, &zone, &elf);
1812 
1813   elf.Write(&w);
1814 #endif
1815 
1816   return CreateCodeEntry(reinterpret_cast<Address>(w.buffer()), w.position());
1817 }
1818 
1819 struct AddressRange {
1820   Address start;
1821   Address end;
1822 };
1823 
1824 struct AddressRangeLess {
operator ()v8::internal::GDBJITInterface::AddressRangeLess1825   bool operator()(const AddressRange& a, const AddressRange& b) const {
1826     if (a.start == b.start) return a.end < b.end;
1827     return a.start < b.start;
1828   }
1829 };
1830 
1831 struct CodeMapConfig {
1832   using Key = AddressRange;
1833   using Value = JITCodeEntry*;
1834   using Less = AddressRangeLess;
1835 };
1836 
1837 using CodeMap =
1838     std::map<CodeMapConfig::Key, CodeMapConfig::Value, CodeMapConfig::Less>;
1839 
GetCodeMap()1840 static CodeMap* GetCodeMap() {
1841   // TODO(jgruber): Don't leak.
1842   static CodeMap* code_map = nullptr;
1843   if (code_map == nullptr) code_map = new CodeMap();
1844   return code_map;
1845 }
1846 
HashCodeAddress(Address addr)1847 static uint32_t HashCodeAddress(Address addr) {
1848   static const uintptr_t kGoldenRatio = 2654435761u;
1849   return static_cast<uint32_t>((addr >> kCodeAlignmentBits) * kGoldenRatio);
1850 }
1851 
GetLineMap()1852 static base::HashMap* GetLineMap() {
1853   static base::HashMap* line_map = nullptr;
1854   if (line_map == nullptr) {
1855     line_map = new base::HashMap();
1856   }
1857   return line_map;
1858 }
1859 
PutLineInfo(Address addr,LineInfo * info)1860 static void PutLineInfo(Address addr, LineInfo* info) {
1861   base::HashMap* line_map = GetLineMap();
1862   base::HashMap::Entry* e = line_map->LookupOrInsert(
1863       reinterpret_cast<void*>(addr), HashCodeAddress(addr));
1864   if (e->value != nullptr) delete static_cast<LineInfo*>(e->value);
1865   e->value = info;
1866 }
1867 
GetLineInfo(Address addr)1868 static LineInfo* GetLineInfo(Address addr) {
1869   void* value = GetLineMap()->Remove(reinterpret_cast<void*>(addr),
1870                                      HashCodeAddress(addr));
1871   return static_cast<LineInfo*>(value);
1872 }
1873 
AddUnwindInfo(CodeDescription * desc)1874 static void AddUnwindInfo(CodeDescription* desc) {
1875 #if V8_TARGET_ARCH_X64
1876   if (desc->is_function()) {
1877     // To avoid propagating unwinding information through
1878     // compilation pipeline we use an approximation.
1879     // For most use cases this should not affect usability.
1880     static const int kFramePointerPushOffset = 1;
1881     static const int kFramePointerSetOffset = 4;
1882     static const int kFramePointerPopOffset = -3;
1883 
1884     uintptr_t frame_pointer_push_address =
1885         desc->CodeStart() + kFramePointerPushOffset;
1886 
1887     uintptr_t frame_pointer_set_address =
1888         desc->CodeStart() + kFramePointerSetOffset;
1889 
1890     uintptr_t frame_pointer_pop_address =
1891         desc->CodeEnd() + kFramePointerPopOffset;
1892 
1893     desc->SetStackStateStartAddress(CodeDescription::POST_RBP_PUSH,
1894                                     frame_pointer_push_address);
1895     desc->SetStackStateStartAddress(CodeDescription::POST_RBP_SET,
1896                                     frame_pointer_set_address);
1897     desc->SetStackStateStartAddress(CodeDescription::POST_RBP_POP,
1898                                     frame_pointer_pop_address);
1899   } else {
1900     desc->SetStackStateStartAddress(CodeDescription::POST_RBP_PUSH,
1901                                     desc->CodeStart());
1902     desc->SetStackStateStartAddress(CodeDescription::POST_RBP_SET,
1903                                     desc->CodeStart());
1904     desc->SetStackStateStartAddress(CodeDescription::POST_RBP_POP,
1905                                     desc->CodeEnd());
1906   }
1907 #endif  // V8_TARGET_ARCH_X64
1908 }
1909 
1910 static base::LazyMutex mutex = LAZY_MUTEX_INITIALIZER;
1911 
1912 // Remove entries from the map that intersect the given address range,
1913 // and deregister them from GDB.
RemoveJITCodeEntries(CodeMap * map,const AddressRange & range)1914 static void RemoveJITCodeEntries(CodeMap* map, const AddressRange& range) {
1915   DCHECK(range.start < range.end);
1916 
1917   if (map->empty()) return;
1918 
1919   // Find the first overlapping entry.
1920 
1921   // If successful, points to the first element not less than `range`. The
1922   // returned iterator has the key in `first` and the value in `second`.
1923   auto it = map->lower_bound(range);
1924   auto start_it = it;
1925 
1926   if (it == map->end()) {
1927     start_it = map->begin();
1928   } else if (it != map->begin()) {
1929     for (--it; it != map->begin(); --it) {
1930       if ((*it).first.end <= range.start) break;
1931       start_it = it;
1932     }
1933   }
1934 
1935   DCHECK(start_it != map->end());
1936 
1937   // Find the first non-overlapping entry after `range`.
1938 
1939   const auto end_it = map->lower_bound({range.end, 0});
1940 
1941   // Evict intersecting ranges.
1942 
1943   if (std::distance(start_it, end_it) < 1) return;  // No overlapping entries.
1944 
1945   for (auto it = start_it; it != end_it; it++) {
1946     JITCodeEntry* old_entry = (*it).second;
1947     UnregisterCodeEntry(old_entry);
1948     DestroyCodeEntry(old_entry);
1949   }
1950 
1951   map->erase(start_it, end_it);
1952 }
1953 
1954 // Insert the entry into the map and register it with GDB.
AddJITCodeEntry(CodeMap * map,const AddressRange & range,JITCodeEntry * entry,bool dump_if_enabled,const char * name_hint)1955 static void AddJITCodeEntry(CodeMap* map, const AddressRange& range,
1956                             JITCodeEntry* entry, bool dump_if_enabled,
1957                             const char* name_hint) {
1958 #if defined(DEBUG) && !V8_OS_WIN
1959   static int file_num = 0;
1960   if (FLAG_gdbjit_dump && dump_if_enabled) {
1961     static const int kMaxFileNameSize = 64;
1962     char file_name[64];
1963 
1964     SNPrintF(Vector<char>(file_name, kMaxFileNameSize), "/tmp/elfdump%s%d.o",
1965              (name_hint != nullptr) ? name_hint : "", file_num++);
1966     WriteBytes(file_name, reinterpret_cast<byte*>(entry->symfile_addr_),
1967                static_cast<int>(entry->symfile_size_));
1968   }
1969 #endif
1970 
1971   auto result = map->emplace(range, entry);
1972   DCHECK(result.second);  // Insertion happened.
1973   USE(result);
1974 
1975   RegisterCodeEntry(entry);
1976 }
1977 
AddCode(const char * name,Code code,SharedFunctionInfo shared,LineInfo * lineinfo)1978 static void AddCode(const char* name, Code code, SharedFunctionInfo shared,
1979                     LineInfo* lineinfo) {
1980   DisallowHeapAllocation no_gc;
1981 
1982   CodeMap* code_map = GetCodeMap();
1983   AddressRange range;
1984   range.start = code.address();
1985   range.end = code.address() + code.CodeSize();
1986   RemoveJITCodeEntries(code_map, range);
1987 
1988   CodeDescription code_desc(name, code, shared, lineinfo);
1989 
1990   if (!FLAG_gdbjit_full && !code_desc.IsLineInfoAvailable()) {
1991     delete lineinfo;
1992     return;
1993   }
1994 
1995   AddUnwindInfo(&code_desc);
1996   Isolate* isolate = code.GetIsolate();
1997   JITCodeEntry* entry = CreateELFObject(&code_desc, isolate);
1998 
1999   delete lineinfo;
2000 
2001   const char* name_hint = nullptr;
2002   bool should_dump = false;
2003   if (FLAG_gdbjit_dump) {
2004     if (strlen(FLAG_gdbjit_dump_filter) == 0) {
2005       name_hint = name;
2006       should_dump = true;
2007     } else if (name != nullptr) {
2008       name_hint = strstr(name, FLAG_gdbjit_dump_filter);
2009       should_dump = (name_hint != nullptr);
2010     }
2011   }
2012   AddJITCodeEntry(code_map, range, entry, should_dump, name_hint);
2013 }
2014 
EventHandler(const v8::JitCodeEvent * event)2015 void EventHandler(const v8::JitCodeEvent* event) {
2016   if (!FLAG_gdbjit) return;
2017   if (event->code_type != v8::JitCodeEvent::JIT_CODE) return;
2018   base::MutexGuard lock_guard(mutex.Pointer());
2019   switch (event->type) {
2020     case v8::JitCodeEvent::CODE_ADDED: {
2021       Address addr = reinterpret_cast<Address>(event->code_start);
2022       Isolate* isolate = reinterpret_cast<Isolate*>(event->isolate);
2023       Code code = isolate->heap()->GcSafeFindCodeForInnerPointer(addr);
2024       LineInfo* lineinfo = GetLineInfo(addr);
2025       EmbeddedVector<char, 256> buffer;
2026       StringBuilder builder(buffer.begin(), buffer.length());
2027       builder.AddSubstring(event->name.str, static_cast<int>(event->name.len));
2028       // It's called UnboundScript in the API but it's a SharedFunctionInfo.
2029       SharedFunctionInfo shared = event->script.IsEmpty()
2030                                       ? SharedFunctionInfo()
2031                                       : *Utils::OpenHandle(*event->script);
2032       AddCode(builder.Finalize(), code, shared, lineinfo);
2033       break;
2034     }
2035     case v8::JitCodeEvent::CODE_MOVED:
2036       // Enabling the GDB JIT interface should disable code compaction.
2037       UNREACHABLE();
2038     case v8::JitCodeEvent::CODE_REMOVED:
2039       // Do nothing.  Instead, adding code causes eviction of any entry whose
2040       // address range intersects the address range of the added code.
2041       break;
2042     case v8::JitCodeEvent::CODE_ADD_LINE_POS_INFO: {
2043       LineInfo* line_info = reinterpret_cast<LineInfo*>(event->user_data);
2044       line_info->SetPosition(static_cast<intptr_t>(event->line_info.offset),
2045                              static_cast<int>(event->line_info.pos),
2046                              event->line_info.position_type ==
2047                                  v8::JitCodeEvent::STATEMENT_POSITION);
2048       break;
2049     }
2050     case v8::JitCodeEvent::CODE_START_LINE_INFO_RECORDING: {
2051       v8::JitCodeEvent* mutable_event = const_cast<v8::JitCodeEvent*>(event);
2052       mutable_event->user_data = new LineInfo();
2053       break;
2054     }
2055     case v8::JitCodeEvent::CODE_END_LINE_INFO_RECORDING: {
2056       LineInfo* line_info = reinterpret_cast<LineInfo*>(event->user_data);
2057       PutLineInfo(reinterpret_cast<Address>(event->code_start), line_info);
2058       break;
2059     }
2060   }
2061 }
2062 #endif
2063 }  // namespace GDBJITInterface
2064 }  // namespace internal
2065 }  // namespace v8
2066 
2067 #undef __MACH_O
2068 #undef __ELF
2069