LLVM API Documentation

MCAssembler.cpp

Go to the documentation of this file.
00001 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "llvm/MC/MCAssembler.h"
00011 
00012 #include "llvm/ADT/Twine.h"
00013 #include "llvm/MC/MCSectionMachO.h"
00014 #include "llvm/Support/DataTypes.h"
00015 #include "llvm/Support/ErrorHandling.h"
00016 #include "llvm/Support/raw_ostream.h"
00017 #include "llvm/Target/TargetMachOWriterInfo.h"
00018 
00019 using namespace llvm;
00020 
00021 namespace {
00022 
00023 class MachObjectWriter {
00024   // See <mach-o/loader.h>.
00025   enum {
00026     Header_Magic32 = 0xFEEDFACE,
00027     Header_Magic64 = 0xFEEDFACF
00028   };
00029   
00030   static const unsigned Header32Size = 28;
00031   static const unsigned Header64Size = 32;
00032   static const unsigned SegmentLoadCommand32Size = 56;
00033   static const unsigned Section32Size = 68;
00034 
00035   enum HeaderFileType {
00036     HFT_Object = 0x1
00037   };
00038 
00039   enum LoadCommandType {
00040     LCT_Segment = 0x1
00041   };
00042 
00043   raw_ostream &OS;
00044   bool IsLSB;
00045 
00046 public:
00047   MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true) 
00048     : OS(_OS), IsLSB(_IsLSB) {
00049   }
00050 
00051   /// @name Helper Methods
00052   /// @{
00053 
00054   void Write8(uint8_t Value) {
00055     OS << char(Value);
00056   }
00057 
00058   void Write16(uint16_t Value) {
00059     if (IsLSB) {
00060       Write8(uint8_t(Value >> 0));
00061       Write8(uint8_t(Value >> 8));
00062     } else {
00063       Write8(uint8_t(Value >> 8));
00064       Write8(uint8_t(Value >> 0));
00065     }
00066   }
00067 
00068   void Write32(uint32_t Value) {
00069     if (IsLSB) {
00070       Write16(uint16_t(Value >> 0));
00071       Write16(uint16_t(Value >> 16));
00072     } else {
00073       Write16(uint16_t(Value >> 16));
00074       Write16(uint16_t(Value >> 0));
00075     }
00076   }
00077 
00078   void Write64(uint64_t Value) {
00079     if (IsLSB) {
00080       Write32(uint32_t(Value >> 0));
00081       Write32(uint32_t(Value >> 32));
00082     } else {
00083       Write32(uint32_t(Value >> 32));
00084       Write32(uint32_t(Value >> 0));
00085     }
00086   }
00087 
00088   void WriteZeros(unsigned N) {
00089     const char Zeros[16] = { 0 };
00090     
00091     for (unsigned i = 0, e = N / 16; i != e; ++i)
00092       OS << StringRef(Zeros, 16);
00093     
00094     OS << StringRef(Zeros, N % 16);
00095   }
00096 
00097   void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
00098     OS << Str;
00099     if (ZeroFillSize)
00100       WriteZeros(ZeroFillSize - Str.size());
00101   }
00102 
00103   /// @}
00104   
00105   static unsigned getPrologSize32(unsigned NumSections) {
00106     return Header32Size + SegmentLoadCommand32Size + 
00107       NumSections * Section32Size;
00108   }
00109 
00110   void WriteHeader32(unsigned NumSections) {
00111     // struct mach_header (28 bytes)
00112 
00113     uint64_t Start = OS.tell();
00114     (void) Start;
00115 
00116     Write32(Header_Magic32);
00117 
00118     // FIXME: Support cputype.
00119     Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
00120 
00121     // FIXME: Support cpusubtype.
00122     Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
00123 
00124     Write32(HFT_Object);
00125 
00126     // Object files have a single load command, the segment.
00127     Write32(1);
00128     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
00129     Write32(0); // Flags
00130 
00131     assert(OS.tell() - Start == Header32Size);
00132   }
00133 
00134   void WriteLoadCommandHeader(uint32_t Cmd, uint32_t CmdSize) {
00135     assert((CmdSize & 0x3) == 0 && "Invalid size!");
00136 
00137     Write32(Cmd);
00138     Write32(CmdSize);
00139   }
00140 
00141   /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
00142   ///
00143   /// \arg NumSections - The number of sections in this segment.
00144   /// \arg SectionDataSize - The total size of the sections.
00145   void WriteSegmentLoadCommand32(unsigned NumSections,
00146                                  uint64_t SectionDataSize) {
00147     // struct segment_command (56 bytes)
00148 
00149     uint64_t Start = OS.tell();
00150     (void) Start;
00151 
00152     Write32(LCT_Segment);
00153     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
00154 
00155     WriteString("", 16);
00156     Write32(0); // vmaddr
00157     Write32(SectionDataSize); // vmsize
00158     Write32(Header32Size + SegmentLoadCommand32Size + 
00159             NumSections * Section32Size); // file offset
00160     Write32(SectionDataSize); // file size
00161     Write32(0x7); // maxprot
00162     Write32(0x7); // initprot
00163     Write32(NumSections);
00164     Write32(0); // flags
00165 
00166     assert(OS.tell() - Start == SegmentLoadCommand32Size);
00167   }
00168 
00169   void WriteSection32(const MCSectionData &SD) {
00170     // struct section (68 bytes)
00171 
00172     uint64_t Start = OS.tell();
00173     (void) Start;
00174 
00175     // FIXME: cast<> support!
00176     const MCSectionMachO &Section =
00177       static_cast<const MCSectionMachO&>(SD.getSection());
00178     WriteString(Section.getSectionName(), 16);
00179     WriteString(Section.getSegmentName(), 16);
00180     Write32(0); // address
00181     Write32(SD.getFileSize()); // size
00182     Write32(SD.getFileOffset());
00183 
00184     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
00185     Write32(Log2_32(SD.getAlignment()));
00186     Write32(0); // file offset of relocation entries
00187     Write32(0); // number of relocation entrions
00188     Write32(Section.getTypeAndAttributes());
00189     Write32(0); // reserved1
00190     Write32(Section.getStubSize()); // reserved2
00191 
00192     assert(OS.tell() - Start == Section32Size);
00193   }
00194 };
00195 
00196 }
00197 
00198 /* *** */
00199 
00200 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
00201 }
00202 
00203 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
00204   : Kind(_Kind),
00205     FileOffset(~UINT64_C(0)),
00206     FileSize(~UINT64_C(0))
00207 {
00208   if (SD)
00209     SD->getFragmentList().push_back(this);
00210 }
00211 
00212 MCFragment::~MCFragment() {
00213 }
00214 
00215 /* *** */
00216 
00217 MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
00218 
00219 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
00220   : Section(_Section),
00221     Alignment(1),
00222     FileOffset(~UINT64_C(0)),
00223     FileSize(~UINT64_C(0))
00224 {
00225   if (A)
00226     A->getSectionList().push_back(this);
00227 }
00228 
00229 /* *** */
00230 
00231 MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
00232 
00233 MCAssembler::~MCAssembler() {
00234 }
00235 
00236 void MCAssembler::LayoutSection(MCSectionData &SD) {
00237   uint64_t FileOffset = SD.getFileOffset();
00238   uint64_t SectionOffset = 0;
00239 
00240   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
00241     MCFragment &F = *it;
00242 
00243     F.setFileOffset(FileOffset);
00244 
00245     // Evaluate fragment size.
00246     switch (F.getKind()) {
00247     case MCFragment::FT_Align: {
00248       MCAlignFragment &AF = cast<MCAlignFragment>(F);
00249       
00250       uint64_t AlignedOffset =
00251         RoundUpToAlignment(SectionOffset, AF.getAlignment());
00252       uint64_t PaddingBytes = AlignedOffset - SectionOffset;
00253 
00254       if (PaddingBytes > AF.getMaxBytesToEmit())
00255         AF.setFileSize(0);
00256       else
00257         AF.setFileSize(PaddingBytes);
00258       break;
00259     }
00260 
00261     case MCFragment::FT_Data:
00262     case MCFragment::FT_Fill:
00263       F.setFileSize(F.getMaxFileSize());
00264       break;
00265 
00266     case MCFragment::FT_Org: {
00267       MCOrgFragment &OF = cast<MCOrgFragment>(F);
00268 
00269       if (!OF.getOffset().isAbsolute())
00270         llvm_unreachable("FIXME: Not yet implemented!");
00271       uint64_t OrgOffset = OF.getOffset().getConstant();
00272 
00273       // FIXME: We need a way to communicate this error.
00274       if (OrgOffset < SectionOffset)
00275         llvm_report_error("invalid .org offset '" + Twine(OrgOffset) + 
00276                           "' (section offset '" + Twine(SectionOffset) + "'");
00277         
00278       F.setFileSize(OrgOffset - SectionOffset);
00279       break;
00280     }      
00281     }
00282 
00283     FileOffset += F.getFileSize();
00284     SectionOffset += F.getFileSize();
00285   }
00286 
00287   // FIXME: Pad section?
00288   SD.setFileSize(FileOffset - SD.getFileOffset());
00289 }
00290 
00291 /// WriteFileData - Write the \arg F data to the output file.
00292 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
00293                           MachObjectWriter &MOW) {
00294   uint64_t Start = OS.tell();
00295   (void) Start;
00296     
00297   assert(F.getFileOffset() == Start && "Invalid file offset!");
00298 
00299   // FIXME: Embed in fragments instead?
00300   switch (F.getKind()) {
00301   case MCFragment::FT_Align: {
00302     MCAlignFragment &AF = cast<MCAlignFragment>(F);
00303     uint64_t Count = AF.getFileSize() / AF.getValueSize();
00304 
00305     // FIXME: This error shouldn't actually occur (the front end should emit
00306     // multiple .align directives to enforce the semantics it wants), but is
00307     // severe enough that we want to report it. How to handle this?
00308     if (Count * AF.getValueSize() != AF.getFileSize())
00309       llvm_report_error("undefined .align directive, value size '" + 
00310                         Twine(AF.getValueSize()) + 
00311                         "' is not a divisor of padding size '" +
00312                         Twine(AF.getFileSize()) + "'");
00313 
00314     for (uint64_t i = 0; i != Count; ++i) {
00315       switch (AF.getValueSize()) {
00316       default:
00317         assert(0 && "Invalid size!");
00318       case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
00319       case 2: MOW.Write16(uint16_t(AF.getValue())); break;
00320       case 4: MOW.Write32(uint32_t(AF.getValue())); break;
00321       case 8: MOW.Write64(uint64_t(AF.getValue())); break;
00322       }
00323     }
00324     break;
00325   }
00326 
00327   case MCFragment::FT_Data:
00328     OS << cast<MCDataFragment>(F).getContents().str();
00329     break;
00330 
00331   case MCFragment::FT_Fill: {
00332     MCFillFragment &FF = cast<MCFillFragment>(F);
00333 
00334     if (!FF.getValue().isAbsolute())
00335       llvm_unreachable("FIXME: Not yet implemented!");
00336     int64_t Value = FF.getValue().getConstant();
00337 
00338     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
00339       switch (FF.getValueSize()) {
00340       default:
00341         assert(0 && "Invalid size!");
00342       case 1: MOW.Write8 (uint8_t (Value)); break;
00343       case 2: MOW.Write16(uint16_t(Value)); break;
00344       case 4: MOW.Write32(uint32_t(Value)); break;
00345       case 8: MOW.Write64(uint64_t(Value)); break;
00346       }
00347     }
00348     break;
00349   }
00350     
00351   case MCFragment::FT_Org: {
00352     MCOrgFragment &OF = cast<MCOrgFragment>(F);
00353 
00354     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
00355       MOW.Write8(uint8_t(OF.getValue()));
00356 
00357     break;
00358   }
00359   }
00360 
00361   assert(OS.tell() - Start == F.getFileSize());
00362 }
00363 
00364 /// WriteFileData - Write the \arg SD data to the output file.
00365 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
00366                           MachObjectWriter &MOW) {
00367   uint64_t Start = OS.tell();
00368   (void) Start;
00369       
00370   for (MCSectionData::const_iterator it = SD.begin(),
00371          ie = SD.end(); it != ie; ++it)
00372     WriteFileData(OS, *it, MOW);
00373 
00374   assert(OS.tell() - Start == SD.getFileSize());
00375 }
00376 
00377 void MCAssembler::Finish() {
00378   unsigned NumSections = Sections.size();
00379 
00380   // Layout the sections and fragments.
00381   uint64_t Offset = MachObjectWriter::getPrologSize32(NumSections);
00382   uint64_t SectionDataSize = 0;
00383   for (iterator it = begin(), ie = end(); it != ie; ++it) {
00384     it->setFileOffset(Offset);
00385 
00386     LayoutSection(*it);
00387 
00388     Offset += it->getFileSize();
00389     SectionDataSize += it->getFileSize();
00390   }
00391 
00392   MachObjectWriter MOW(OS);
00393 
00394   // Write the prolog, starting with the header and load command...
00395   MOW.WriteHeader32(NumSections);
00396   MOW.WriteSegmentLoadCommand32(NumSections, SectionDataSize);
00397   
00398   // ... and then the section headers.
00399   for (iterator it = begin(), ie = end(); it != ie; ++it)
00400     MOW.WriteSection32(*it);
00401 
00402   // Finally, write the section data.
00403   for (iterator it = begin(), ie = end(); it != ie; ++it)
00404     WriteFileData(OS, *it, MOW);
00405 
00406   OS.flush();
00407 }