llvm-capstone/lld/MachO/InputSection.cpp
Jez Ng 74871cdad7 [lld-macho] Ensure __bss sections we output have file offset of zero
Summary:
llvm-mc emits `__bss` sections with an offset of zero, but we weren't expecting
that in our input, so we were copying non-zero data from the start of the file and
putting it in `__bss`, with obviously undesirable runtime results. (It appears that
the kernel will copy those nonzero bytes as long as the offset is nonzero, regardless
of whether S_ZERO_FILL is set.)

I debated on whether to make a special ZeroFillSection -- separate from a
regular InputSection -- but it seemed like too much work for now. But I'm happy
to refactor if anyone feels strongly about having it as a separate class.

Depends on D80857.

Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee

Reviewed By: smeenai

Subscribers: llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D80859
2020-06-17 20:41:28 -07:00

49 lines
1.3 KiB
C++

//===- InputSection.cpp ---------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "InputSection.h"
#include "OutputSegment.h"
#include "Symbols.h"
#include "Target.h"
#include "lld/Common/Memory.h"
#include "llvm/Support/Endian.h"
using namespace llvm;
using namespace llvm::MachO;
using namespace llvm::support;
using namespace lld;
using namespace lld::macho;
std::vector<InputSection *> macho::inputSections;
uint64_t InputSection::getFileOffset() const {
return parent->fileOff + outSecFileOff;
}
uint64_t InputSection::getVA() const { return parent->addr + outSecOff; }
void InputSection::writeTo(uint8_t *buf) {
if (getFileSize() == 0)
return;
memcpy(buf, data.data(), data.size());
for (Reloc &r : relocs) {
uint64_t va = 0;
if (auto *s = r.target.dyn_cast<Symbol *>())
va = target->getSymbolVA(*s, r.type);
else if (auto *isec = r.target.dyn_cast<InputSection *>())
va = isec->getVA();
uint64_t val = va + r.addend;
if (r.pcrel)
val -= getVA() + r.offset;
target->relocateOne(buf + r.offset, r, val);
}
}