Path: blob/main/contrib/llvm-project/llvm/lib/ObjCopy/COFF/COFFObjcopy.cpp
35266 views
//===- COFFObjcopy.cpp ----------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "llvm/ObjCopy/COFF/COFFObjcopy.h"9#include "COFFObject.h"10#include "COFFReader.h"11#include "COFFWriter.h"12#include "llvm/ObjCopy/COFF/COFFConfig.h"13#include "llvm/ObjCopy/CommonConfig.h"1415#include "llvm/ADT/StringExtras.h"16#include "llvm/Object/Binary.h"17#include "llvm/Object/COFF.h"18#include "llvm/Support/CRC.h"19#include "llvm/Support/Errc.h"20#include "llvm/Support/Path.h"21#include <cassert>2223namespace llvm {24namespace objcopy {25namespace coff {2627using namespace object;28using namespace COFF;2930static bool isDebugSection(const Section &Sec) {31return Sec.Name.starts_with(".debug");32}3334static uint64_t getNextRVA(const Object &Obj) {35if (Obj.getSections().empty())36return 0;37const Section &Last = Obj.getSections().back();38return alignTo(Last.Header.VirtualAddress + Last.Header.VirtualSize,39Obj.IsPE ? Obj.PeHeader.SectionAlignment : 1);40}4142static Expected<std::vector<uint8_t>>43createGnuDebugLinkSectionContents(StringRef File) {44ErrorOr<std::unique_ptr<MemoryBuffer>> LinkTargetOrErr =45MemoryBuffer::getFile(File);46if (!LinkTargetOrErr)47return createFileError(File, LinkTargetOrErr.getError());48auto LinkTarget = std::move(*LinkTargetOrErr);49uint32_t CRC32 = llvm::crc32(arrayRefFromStringRef(LinkTarget->getBuffer()));5051StringRef FileName = sys::path::filename(File);52size_t CRCPos = alignTo(FileName.size() + 1, 4);53std::vector<uint8_t> Data(CRCPos + 4);54memcpy(Data.data(), FileName.data(), FileName.size());55support::endian::write32le(Data.data() + CRCPos, CRC32);56return Data;57}5859// Adds named section with given contents to the object.60static void addSection(Object &Obj, StringRef Name, ArrayRef<uint8_t> Contents,61uint32_t Characteristics) {62bool NeedVA = Characteristics & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ |63IMAGE_SCN_MEM_WRITE);6465Section Sec;66Sec.setOwnedContents(Contents);67Sec.Name = Name;68Sec.Header.VirtualSize = NeedVA ? Sec.getContents().size() : 0u;69Sec.Header.VirtualAddress = NeedVA ? getNextRVA(Obj) : 0u;70Sec.Header.SizeOfRawData =71NeedVA ? alignTo(Sec.Header.VirtualSize,72Obj.IsPE ? Obj.PeHeader.FileAlignment : 1)73: Sec.getContents().size();74// Sec.Header.PointerToRawData is filled in by the writer.75Sec.Header.PointerToRelocations = 0;76Sec.Header.PointerToLinenumbers = 0;77// Sec.Header.NumberOfRelocations is filled in by the writer.78Sec.Header.NumberOfLinenumbers = 0;79Sec.Header.Characteristics = Characteristics;8081Obj.addSections(Sec);82}8384static Error addGnuDebugLink(Object &Obj, StringRef DebugLinkFile) {85Expected<std::vector<uint8_t>> Contents =86createGnuDebugLinkSectionContents(DebugLinkFile);87if (!Contents)88return Contents.takeError();8990addSection(Obj, ".gnu_debuglink", *Contents,91IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ |92IMAGE_SCN_MEM_DISCARDABLE);9394return Error::success();95}9697static uint32_t flagsToCharacteristics(SectionFlag AllFlags, uint32_t OldChar) {98// Need to preserve alignment flags.99const uint32_t PreserveMask =100IMAGE_SCN_ALIGN_1BYTES | IMAGE_SCN_ALIGN_2BYTES | IMAGE_SCN_ALIGN_4BYTES |101IMAGE_SCN_ALIGN_8BYTES | IMAGE_SCN_ALIGN_16BYTES |102IMAGE_SCN_ALIGN_32BYTES | IMAGE_SCN_ALIGN_64BYTES |103IMAGE_SCN_ALIGN_128BYTES | IMAGE_SCN_ALIGN_256BYTES |104IMAGE_SCN_ALIGN_512BYTES | IMAGE_SCN_ALIGN_1024BYTES |105IMAGE_SCN_ALIGN_2048BYTES | IMAGE_SCN_ALIGN_4096BYTES |106IMAGE_SCN_ALIGN_8192BYTES;107108// Setup new section characteristics based on the flags provided in command109// line.110uint32_t NewCharacteristics = (OldChar & PreserveMask) | IMAGE_SCN_MEM_READ;111112if ((AllFlags & SectionFlag::SecAlloc) && !(AllFlags & SectionFlag::SecLoad))113NewCharacteristics |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;114if (AllFlags & SectionFlag::SecNoload)115NewCharacteristics |= IMAGE_SCN_LNK_REMOVE;116if (!(AllFlags & SectionFlag::SecReadonly))117NewCharacteristics |= IMAGE_SCN_MEM_WRITE;118if (AllFlags & SectionFlag::SecDebug)119NewCharacteristics |=120IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE;121if (AllFlags & SectionFlag::SecCode)122NewCharacteristics |= IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE;123if (AllFlags & SectionFlag::SecData)124NewCharacteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;125if (AllFlags & SectionFlag::SecShare)126NewCharacteristics |= IMAGE_SCN_MEM_SHARED;127if (AllFlags & SectionFlag::SecExclude)128NewCharacteristics |= IMAGE_SCN_LNK_REMOVE;129130return NewCharacteristics;131}132133static Error dumpSection(Object &O, StringRef SectionName, StringRef FileName) {134for (const coff::Section &Section : O.getSections()) {135if (Section.Name != SectionName)136continue;137138ArrayRef<uint8_t> Contents = Section.getContents();139140std::unique_ptr<FileOutputBuffer> Buffer;141if (auto B = FileOutputBuffer::create(FileName, Contents.size()))142Buffer = std::move(*B);143else144return B.takeError();145146llvm::copy(Contents, Buffer->getBufferStart());147if (Error E = Buffer->commit())148return E;149150return Error::success();151}152return createStringError(object_error::parse_failed, "section '%s' not found",153SectionName.str().c_str());154}155156static Error handleArgs(const CommonConfig &Config,157const COFFConfig &COFFConfig, Object &Obj) {158for (StringRef Op : Config.DumpSection) {159auto [Section, File] = Op.split('=');160if (Error E = dumpSection(Obj, Section, File))161return E;162}163164// Perform the actual section removals.165Obj.removeSections([&Config](const Section &Sec) {166// Contrary to --only-keep-debug, --only-section fully removes sections that167// aren't mentioned.168if (!Config.OnlySection.empty() && !Config.OnlySection.matches(Sec.Name))169return true;170171if (Config.StripDebug || Config.StripAll || Config.StripAllGNU ||172Config.DiscardMode == DiscardType::All || Config.StripUnneeded) {173if (isDebugSection(Sec) &&174(Sec.Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) != 0)175return true;176}177178if (Config.ToRemove.matches(Sec.Name))179return true;180181return false;182});183184if (Config.OnlyKeepDebug) {185// For --only-keep-debug, we keep all other sections, but remove their186// content. The VirtualSize field in the section header is kept intact.187Obj.truncateSections([](const Section &Sec) {188return !isDebugSection(Sec) && Sec.Name != ".buildid" &&189((Sec.Header.Characteristics &190(IMAGE_SCN_CNT_CODE | IMAGE_SCN_CNT_INITIALIZED_DATA)) != 0);191});192}193194// StripAll removes all symbols and thus also removes all relocations.195if (Config.StripAll || Config.StripAllGNU)196for (Section &Sec : Obj.getMutableSections())197Sec.Relocs.clear();198199// If we need to do per-symbol removals, initialize the Referenced field.200if (Config.StripUnneeded || Config.DiscardMode == DiscardType::All ||201!Config.SymbolsToRemove.empty())202if (Error E = Obj.markSymbols())203return E;204205for (Symbol &Sym : Obj.getMutableSymbols()) {206auto I = Config.SymbolsToRename.find(Sym.Name);207if (I != Config.SymbolsToRename.end())208Sym.Name = I->getValue();209}210211auto ToRemove = [&](const Symbol &Sym) -> Expected<bool> {212// For StripAll, all relocations have been stripped and we remove all213// symbols.214if (Config.StripAll || Config.StripAllGNU)215return true;216217if (Config.SymbolsToRemove.matches(Sym.Name)) {218// Explicitly removing a referenced symbol is an error.219if (Sym.Referenced)220return createStringError(221llvm::errc::invalid_argument,222"'" + Config.OutputFilename + "': not stripping symbol '" +223Sym.Name.str() + "' because it is named in a relocation");224return true;225}226227if (!Sym.Referenced) {228// With --strip-unneeded, GNU objcopy removes all unreferenced local229// symbols, and any unreferenced undefined external.230// With --strip-unneeded-symbol we strip only specific unreferenced231// local symbol instead of removing all of such.232if (Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC ||233Sym.Sym.SectionNumber == 0)234if (Config.StripUnneeded ||235Config.UnneededSymbolsToRemove.matches(Sym.Name))236return true;237238// GNU objcopy keeps referenced local symbols and external symbols239// if --discard-all is set, similar to what --strip-unneeded does,240// but undefined local symbols are kept when --discard-all is set.241if (Config.DiscardMode == DiscardType::All &&242Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC &&243Sym.Sym.SectionNumber != 0)244return true;245}246247return false;248};249250// Actually do removals of symbols.251if (Error Err = Obj.removeSymbols(ToRemove))252return Err;253254if (!Config.SetSectionFlags.empty())255for (Section &Sec : Obj.getMutableSections()) {256const auto It = Config.SetSectionFlags.find(Sec.Name);257if (It != Config.SetSectionFlags.end())258Sec.Header.Characteristics = flagsToCharacteristics(259It->second.NewFlags, Sec.Header.Characteristics);260}261262for (const NewSectionInfo &NewSection : Config.AddSection) {263uint32_t Characteristics;264const auto It = Config.SetSectionFlags.find(NewSection.SectionName);265if (It != Config.SetSectionFlags.end())266Characteristics = flagsToCharacteristics(It->second.NewFlags, 0);267else268Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_ALIGN_1BYTES;269270addSection(Obj, NewSection.SectionName,271ArrayRef(reinterpret_cast<const uint8_t *>(272NewSection.SectionData->getBufferStart()),273NewSection.SectionData->getBufferSize()),274Characteristics);275}276277for (const NewSectionInfo &NewSection : Config.UpdateSection) {278auto It = llvm::find_if(Obj.getMutableSections(), [&](auto &Sec) {279return Sec.Name == NewSection.SectionName;280});281if (It == Obj.getMutableSections().end())282return createStringError(errc::invalid_argument,283"could not find section with name '%s'",284NewSection.SectionName.str().c_str());285size_t ContentSize = It->getContents().size();286if (!ContentSize)287return createStringError(288errc::invalid_argument,289"section '%s' cannot be updated because it does not have contents",290NewSection.SectionName.str().c_str());291if (ContentSize < NewSection.SectionData->getBufferSize())292return createStringError(293errc::invalid_argument,294"new section cannot be larger than previous section");295It->setOwnedContents({NewSection.SectionData->getBufferStart(),296NewSection.SectionData->getBufferEnd()});297}298299if (!Config.AddGnuDebugLink.empty())300if (Error E = addGnuDebugLink(Obj, Config.AddGnuDebugLink))301return E;302303if (COFFConfig.Subsystem || COFFConfig.MajorSubsystemVersion ||304COFFConfig.MinorSubsystemVersion) {305if (!Obj.IsPE)306return createStringError(307errc::invalid_argument,308"'" + Config.OutputFilename +309"': unable to set subsystem on a relocatable object file");310if (COFFConfig.Subsystem)311Obj.PeHeader.Subsystem = *COFFConfig.Subsystem;312if (COFFConfig.MajorSubsystemVersion)313Obj.PeHeader.MajorSubsystemVersion = *COFFConfig.MajorSubsystemVersion;314if (COFFConfig.MinorSubsystemVersion)315Obj.PeHeader.MinorSubsystemVersion = *COFFConfig.MinorSubsystemVersion;316}317318return Error::success();319}320321Error executeObjcopyOnBinary(const CommonConfig &Config,322const COFFConfig &COFFConfig, COFFObjectFile &In,323raw_ostream &Out) {324COFFReader Reader(In);325Expected<std::unique_ptr<Object>> ObjOrErr = Reader.create();326if (!ObjOrErr)327return createFileError(Config.InputFilename, ObjOrErr.takeError());328Object *Obj = ObjOrErr->get();329assert(Obj && "Unable to deserialize COFF object");330if (Error E = handleArgs(Config, COFFConfig, *Obj))331return createFileError(Config.InputFilename, std::move(E));332COFFWriter Writer(*Obj, Out);333if (Error E = Writer.write())334return createFileError(Config.OutputFilename, std::move(E));335return Error::success();336}337338} // end namespace coff339} // end namespace objcopy340} // end namespace llvm341342343