1 //===- OutputSection.cpp --------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "MergedOutputSection.h" 10 #include "lld/Common/ErrorHandler.h" 11 #include "lld/Common/Memory.h" 12 #include "llvm/BinaryFormat/MachO.h" 13 14 using namespace llvm; 15 using namespace llvm::MachO; 16 using namespace lld; 17 using namespace lld::macho; 18 mergeInput(InputSection * input)19void MergedOutputSection::mergeInput(InputSection *input) { 20 if (inputs.empty()) { 21 align = input->align; 22 flags = input->flags; 23 } else { 24 mergeFlags(input->flags); 25 align = std::max(align, input->align); 26 } 27 28 inputs.push_back(input); 29 input->parent = this; 30 } 31 finalize()32void MergedOutputSection::finalize() { 33 uint64_t isecAddr = addr; 34 uint64_t isecFileOff = fileOff; 35 for (InputSection *isec : inputs) { 36 isecAddr = alignTo(isecAddr, isec->align); 37 isecFileOff = alignTo(isecFileOff, isec->align); 38 isec->outSecOff = isecAddr - addr; 39 isec->outSecFileOff = isecFileOff - fileOff; 40 isecAddr += isec->getSize(); 41 isecFileOff += isec->getFileSize(); 42 } 43 size = isecAddr - addr; 44 fileSize = isecFileOff - fileOff; 45 } 46 writeTo(uint8_t * buf) const47void MergedOutputSection::writeTo(uint8_t *buf) const { 48 for (InputSection *isec : inputs) { 49 isec->writeTo(buf + isec->outSecFileOff); 50 } 51 } 52 53 // TODO: this is most likely wrong; reconsider how section flags 54 // are actually merged. The logic presented here was written without 55 // any form of informed research. mergeFlags(uint32_t inputFlags)56void MergedOutputSection::mergeFlags(uint32_t inputFlags) { 57 uint8_t sectionFlag = MachO::SECTION_TYPE & inputFlags; 58 if (sectionFlag != (MachO::SECTION_TYPE & flags)) 59 error("Cannot add merge section; inconsistent type flags " + 60 Twine(sectionFlag)); 61 62 uint32_t inconsistentFlags = 63 MachO::S_ATTR_DEBUG | MachO::S_ATTR_STRIP_STATIC_SYMS | 64 MachO::S_ATTR_NO_DEAD_STRIP | MachO::S_ATTR_LIVE_SUPPORT; 65 if ((inputFlags ^ flags) & inconsistentFlags) 66 error("Cannot add merge section; cannot merge inconsistent flags"); 67 68 // Negate pure instruction presence if any section isn't pure. 69 uint32_t pureMask = ~MachO::S_ATTR_PURE_INSTRUCTIONS | (inputFlags & flags); 70 71 // Merge the rest 72 flags |= inputFlags; 73 flags &= pureMask; 74 } 75