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