diff options
author | Brad King <brad.king@kitware.com> | 2021-02-04 13:29:52 (GMT) |
---|---|---|
committer | Kitware Robot <kwrobot@kitware.com> | 2021-02-04 13:29:57 (GMT) |
commit | 67cb0067328b158c730fbe009a91ae542238a456 (patch) | |
tree | 6a7e56966c0cc3e65817f4f3a79e48bfa6c2cc67 /Source | |
parent | 4cd23c5e0d5835781b95f6eda778a35d2f55beb8 (diff) | |
parent | e017ba046ccab62fcc67e7cf8fc858e991c1d3e7 (diff) | |
download | CMake-67cb0067328b158c730fbe009a91ae542238a456.zip CMake-67cb0067328b158c730fbe009a91ae542238a456.tar.gz CMake-67cb0067328b158c730fbe009a91ae542238a456.tar.bz2 |
Merge topic 'aix-xcoff-edit'
e017ba046c AIX: Enable XCOFF editing to replace RPATH on installation
56fc4a325f cmXCOFF: Add helper to parse and edit the XCOFF binary format
ddaaee907d CMakeDetermineCompilerId: Recognize XCOFF executable format
69e1d95a8a Tests: Add sample XCOFF binaries
f79d991dfd Tests: Convert CMake.ELF to RunCMake.file-RPATH ELF case
d8f3e68ca9 Ninja Multi-Config: Enable relink diagnostic message
cdcfe3eb99 Rename CMAKE_USE_MACH_PARSER to CMake_USE_MACH_PARSER
b6071c93f5 Rename CMAKE_USE_ELF_PARSER to CMake_USE_ELF_PARSER
Acked-by: Kitware Robot <kwrobot@kitware.com>
Merge-request: !5769
Diffstat (limited to 'Source')
-rw-r--r-- | Source/CMakeLists.txt | 24 | ||||
-rw-r--r-- | Source/cmConfigure.cmake.h.in | 5 | ||||
-rw-r--r-- | Source/cmELF.h | 4 | ||||
-rw-r--r-- | Source/cmFileCommand.cxx | 4 | ||||
-rw-r--r-- | Source/cmGeneratorTarget.cxx | 30 | ||||
-rw-r--r-- | Source/cmGlobalGenerator.h | 2 | ||||
-rw-r--r-- | Source/cmGlobalNinjaGenerator.h | 2 | ||||
-rw-r--r-- | Source/cmMachO.h | 4 | ||||
-rw-r--r-- | Source/cmSystemTools.cxx | 129 | ||||
-rw-r--r-- | Source/cmXCOFF.cxx | 356 | ||||
-rw-r--r-- | Source/cmXCOFF.h | 65 |
11 files changed, 588 insertions, 37 deletions
diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt index b3d8369..6adc9cf 100644 --- a/Source/CMakeLists.txt +++ b/Source/CMakeLists.txt @@ -19,7 +19,7 @@ else() CHECK_INCLUDE_FILE("elf.h" HAVE_ELF_H) endif() if(HAVE_ELF_H) - set(CMAKE_USE_ELF_PARSER 1) + set(CMake_USE_ELF_PARSER 1) elseif(HAIKU) # On Haiku, we need to include elf32.h from the private headers set(CMake_HAIKU_INCLUDE_DIRS @@ -32,13 +32,13 @@ elseif(HAIKU) unset(CMAKE_REQUIRED_INCLUDES) if(HAVE_ELF32_H) - set(CMAKE_USE_ELF_PARSER 1) + set(CMake_USE_ELF_PARSER 1) else() unset(CMake_HAIKU_INCLUDE_DIRS) - set(CMAKE_USE_ELF_PARSER) + set(CMake_USE_ELF_PARSER) endif() else() - set(CMAKE_USE_ELF_PARSER) + set(CMake_USE_ELF_PARSER) endif() if(NOT CMake_DEFAULT_RECURSION_LIMIT) @@ -54,7 +54,11 @@ if(NOT CMake_DEFAULT_RECURSION_LIMIT) endif() if(APPLE) - set(CMAKE_USE_MACH_PARSER 1) + set(CMake_USE_MACH_PARSER 1) +endif() + +if(CMAKE_SYSTEM_NAME STREQUAL "AIX") + set(CMake_USE_XCOFF_PARSER 1) endif() set(EXECUTABLE_OUTPUT_PATH ${CMake_BIN_DIR}) @@ -108,15 +112,20 @@ include_directories( ) # Check if we can build the ELF parser. -if(CMAKE_USE_ELF_PARSER) +if(CMake_USE_ELF_PARSER) set(ELF_SRCS cmELF.h cmELF.cxx) endif() # Check if we can build the Mach-O parser. -if(CMAKE_USE_MACH_PARSER) +if(CMake_USE_MACH_PARSER) set(MACH_SRCS cmMachO.h cmMachO.cxx) endif() +# Check if we can build the XCOFF parser. +if(CMake_USE_XCOFF_PARSER) + set(XCOFF_SRCS cmXCOFF.h cmXCOFF.cxx) +endif() + # # Sources for CMakeLib # @@ -465,6 +474,7 @@ set(SRCS cmWorkerPool.h cmWorkingDirectory.cxx cmWorkingDirectory.h + ${XCOFF_SRCS} cmXMLParser.cxx cmXMLParser.h cmXMLSafe.cxx diff --git a/Source/cmConfigure.cmake.h.in b/Source/cmConfigure.cmake.h.in index cf32b05..aeca6b4 100644 --- a/Source/cmConfigure.cmake.h.in +++ b/Source/cmConfigure.cmake.h.in @@ -16,8 +16,9 @@ #cmakedefine HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE #cmakedefine HAVE_UNSETENV -#cmakedefine CMAKE_USE_ELF_PARSER -#cmakedefine CMAKE_USE_MACH_PARSER +#cmakedefine CMake_USE_ELF_PARSER +#cmakedefine CMake_USE_MACH_PARSER +#cmakedefine CMake_USE_XCOFF_PARSER #define CMake_DEFAULT_RECURSION_LIMIT @CMake_DEFAULT_RECURSION_LIMIT@ #define CMAKE_BIN_DIR "/@CMAKE_BIN_DIR@" #define CMAKE_DATA_DIR "/@CMAKE_DATA_DIR@" diff --git a/Source/cmELF.h b/Source/cmELF.h index 99eb4f4..c479e2b 100644 --- a/Source/cmELF.h +++ b/Source/cmELF.h @@ -10,8 +10,8 @@ #include <utility> #include <vector> -#if !defined(CMAKE_USE_ELF_PARSER) -# error "This file may be included only if CMAKE_USE_ELF_PARSER is enabled." +#if !defined(CMake_USE_ELF_PARSER) +# error "This file may be included only if CMake_USE_ELF_PARSER is enabled." #endif class cmELFInternal; diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx index 031e0d7..f674833 100644 --- a/Source/cmFileCommand.cxx +++ b/Source/cmFileCommand.cxx @@ -64,7 +64,7 @@ # include "cmFileLockResult.h" #endif -#if defined(CMAKE_USE_ELF_PARSER) +#if defined(CMake_USE_ELF_PARSER) # include "cmELF.h" #endif @@ -1198,7 +1198,7 @@ bool HandleReadElfCommand(std::vector<std::string> const& args, return false; } -#if defined(CMAKE_USE_ELF_PARSER) +#if defined(CMake_USE_ELF_PARSER) cmELF elf(fileNameArg.c_str()); if (!arguments.RPath.empty()) { diff --git a/Source/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx index aaefe9c..9235faa 100644 --- a/Source/cmGeneratorTarget.cxx +++ b/Source/cmGeneratorTarget.cxx @@ -2003,17 +2003,16 @@ bool cmGeneratorTarget::NeedRelinkBeforeInstall( // this target must be relinked. bool have_rpath = this->HaveBuildTreeRPATH(config) || this->HaveInstallTreeRPATH(config); - bool is_ninja = - this->LocalGenerator->GetGlobalGenerator()->GetName() == "Ninja"; + bool is_ninja = this->LocalGenerator->GetGlobalGenerator()->IsNinja(); if (have_rpath && is_ninja) { std::ostringstream w; /* clang-format off */ w << - "The install of the " << this->GetName() << " target requires " - "changing an RPATH from the build tree, but this is not supported " - "with the Ninja generator unless on an ELF-based platform. The " - "CMAKE_BUILD_WITH_INSTALL_RPATH variable may be set to avoid this " + "The install of the " << this->GetName() << " target requires changing " + "an RPATH from the build tree, but this is not supported with the Ninja " + "generator unless on an ELF-based or XCOFF-based platform. " + "The CMAKE_BUILD_WITH_INSTALL_RPATH variable may be set to avoid this " "relinking step." ; /* clang-format on */ @@ -2059,20 +2058,29 @@ bool cmGeneratorTarget::IsChrpathUsed(const std::string& config) const return true; } -#if defined(CMAKE_USE_ELF_PARSER) - // Enable if the rpath flag uses a separator and the target uses ELF - // binaries. +#if defined(CMake_USE_ELF_PARSER) || defined(CMake_USE_XCOFF_PARSER) + // Enable if the rpath flag uses a separator and the target uses + // binaries we know how to edit. std::string ll = this->GetLinkerLanguage(config); if (!ll.empty()) { std::string sepVar = cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG_SEP"); cmProp sep = this->Makefile->GetDefinition(sepVar); if (cmNonempty(sep)) { - // TODO: Add ELF check to ABI detection and get rid of + // TODO: Add binary format check to ABI detection and get rid of // CMAKE_EXECUTABLE_FORMAT. if (cmProp fmt = this->Makefile->GetDefinition("CMAKE_EXECUTABLE_FORMAT")) { - return (*fmt == "ELF"); +# if defined(CMake_USE_ELF_PARSER) + if (*fmt == "ELF") { + return true; + } +# endif +# if defined(CMake_USE_XCOFF_PARSER) + if (*fmt == "XCOFF") { + return true; + } +# endif } } } diff --git a/Source/cmGlobalGenerator.h b/Source/cmGlobalGenerator.h index 86fb228..590de26 100644 --- a/Source/cmGlobalGenerator.h +++ b/Source/cmGlobalGenerator.h @@ -438,6 +438,8 @@ public: virtual bool IsVisualStudio() const { return false; } + virtual bool IsNinja() const { return false; } + /** Return true if we know the exact location of object files. If false, store the reason in the given string. This is meaningful only after EnableLanguage has been called. */ diff --git a/Source/cmGlobalNinjaGenerator.h b/Source/cmGlobalNinjaGenerator.h index 78fcb49..0c919ef 100644 --- a/Source/cmGlobalNinjaGenerator.h +++ b/Source/cmGlobalNinjaGenerator.h @@ -170,6 +170,8 @@ public: static std::string GetActualName() { return "Ninja"; } + bool IsNinja() const override { return true; } + /** Get encoding used by generator for ninja files */ codecvt::Encoding GetMakefileEncoding() const override; diff --git a/Source/cmMachO.h b/Source/cmMachO.h index be92c95..faa024b 100644 --- a/Source/cmMachO.h +++ b/Source/cmMachO.h @@ -7,8 +7,8 @@ #include <iosfwd> #include <string> -#if !defined(CMAKE_USE_MACH_PARSER) -# error "This file may be included only if CMAKE_USE_MACH_PARSER is enabled." +#if !defined(CMake_USE_MACH_PARSER) +# error "This file may be included only if CMake_USE_MACH_PARSER is enabled." #endif class cmMachOInternal; diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx index 18c266f..0807590 100644 --- a/Source/cmSystemTools.cxx +++ b/Source/cmSystemTools.cxx @@ -45,14 +45,18 @@ # include "cmCryptoHash.h" #endif -#if defined(CMAKE_USE_ELF_PARSER) +#if defined(CMake_USE_ELF_PARSER) # include "cmELF.h" #endif -#if defined(CMAKE_USE_MACH_PARSER) +#if defined(CMake_USE_MACH_PARSER) # include "cmMachO.h" #endif +#if defined(CMake_USE_XCOFF_PARSER) +# include "cmXCOFF.h" +#endif + #include <algorithm> #include <cassert> #include <cctype> @@ -2317,7 +2321,7 @@ bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath, { // For ELF shared libraries use a real parser to get the correct // soname. -#if defined(CMAKE_USE_ELF_PARSER) +#if defined(CMake_USE_ELF_PARSER) cmELF elf(fullPath.c_str()); if (elf) { return elf.GetSOName(soname); @@ -2347,7 +2351,7 @@ bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath, bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath, std::string& soname) { -#if defined(CMAKE_USE_MACH_PARSER) +#if defined(CMake_USE_MACH_PARSER) cmMachO macho(fullPath.c_str()); if (macho) { return macho.GetInstallName(soname); @@ -2360,9 +2364,9 @@ bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath, return false; } -#if defined(CMAKE_USE_ELF_PARSER) -std::string::size_type cmSystemToolsFindRPath(std::string const& have, - std::string const& want) +#if defined(CMake_USE_ELF_PARSER) || defined(CMake_USE_XCOFF_PARSER) +std::string::size_type cmSystemToolsFindRPath(cm::string_view const& have, + cm::string_view const& want) { std::string::size_type pos = 0; while (pos < have.size()) { @@ -2394,7 +2398,7 @@ std::string::size_type cmSystemToolsFindRPath(std::string const& have, } #endif -#if defined(CMAKE_USE_ELF_PARSER) +#if defined(CMake_USE_ELF_PARSER) struct cmSystemToolsRPathInfo { unsigned long Position; @@ -2404,7 +2408,8 @@ struct cmSystemToolsRPathInfo }; #endif -#if defined(CMAKE_USE_ELF_PARSER) +// FIXME: Dispatch if multiple formats are supported. +#if defined(CMake_USE_ELF_PARSER) bool cmSystemTools::ChangeRPath(std::string const& file, std::string const& oldRPath, std::string const& newRPath, @@ -2576,6 +2581,75 @@ bool cmSystemTools::ChangeRPath(std::string const& file, } return true; } +#elif defined(CMake_USE_XCOFF_PARSER) +bool cmSystemTools::ChangeRPath(std::string const& file, + std::string const& oldRPath, + std::string const& newRPath, + bool removeEnvironmentRPath, std::string* emsg, + bool* changed) +{ + if (changed) { + *changed = false; + } + + bool chg = false; + cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite); + if (cm::optional<cm::string_view> maybeLibPath = xcoff.GetLibPath()) { + cm::string_view libPath = *maybeLibPath; + // Make sure the current rpath contains the old rpath. + std::string::size_type pos = cmSystemToolsFindRPath(libPath, oldRPath); + if (pos == std::string::npos) { + // If it contains the new rpath instead then it is okay. + if (cmSystemToolsFindRPath(libPath, newRPath) != std::string::npos) { + return true; + } + if (emsg) { + std::ostringstream e; + /* clang-format off */ + e << "The current RPATH is:\n" + << " " << libPath << "\n" + << "which does not contain:\n" + << " " << oldRPath << "\n" + << "as was expected."; + /* clang-format on */ + *emsg = e.str(); + } + return false; + } + + // The prefix is either empty or ends in a ':'. + cm::string_view prefix = libPath.substr(0, pos); + if (newRPath.empty() && !prefix.empty()) { + prefix.remove_suffix(1); + } + + // The suffix is either empty or starts in a ':'. + cm::string_view suffix = libPath.substr(pos + oldRPath.length()); + + // Construct the new value which preserves the part of the path + // not being changed. + std::string newLibPath; + if (!removeEnvironmentRPath) { + newLibPath = std::string(prefix); + } + newLibPath += newRPath; + newLibPath += suffix; + + chg = xcoff.SetLibPath(newLibPath); + } + if (!xcoff) { + if (emsg) { + *emsg = xcoff.GetErrorMessage(); + } + return false; + } + + // Everything was updated successfully. + if (changed) { + *changed = chg; + } + return true; +} #else bool cmSystemTools::ChangeRPath(std::string const& /*file*/, std::string const& /*oldRPath*/, @@ -2720,7 +2794,8 @@ int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs) return cm_strverscmp(lhs.c_str(), rhs.c_str()); } -#if defined(CMAKE_USE_ELF_PARSER) +// FIXME: Dispatch if multiple formats are supported. +#if defined(CMake_USE_ELF_PARSER) bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg, bool* removed) { @@ -2861,6 +2936,28 @@ bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg, } return true; } +#elif defined(CMake_USE_XCOFF_PARSER) +bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg, + bool* removed) +{ + if (removed) { + *removed = false; + } + + cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite); + bool rm = xcoff.RemoveLibPath(); + if (!xcoff) { + if (emsg) { + *emsg = xcoff.GetErrorMessage(); + } + return false; + } + + if (removed) { + *removed = rm; + } + return true; +} #else bool cmSystemTools::RemoveRPath(std::string const& /*file*/, std::string* /*emsg*/, bool* /*removed*/) @@ -2869,10 +2966,11 @@ bool cmSystemTools::RemoveRPath(std::string const& /*file*/, } #endif +// FIXME: Dispatch if multiple formats are supported. bool cmSystemTools::CheckRPath(std::string const& file, std::string const& newRPath) { -#if defined(CMAKE_USE_ELF_PARSER) +#if defined(CMake_USE_ELF_PARSER) // Parse the ELF binary. cmELF elf(file.c_str()); @@ -2894,6 +2992,15 @@ bool cmSystemTools::CheckRPath(std::string const& file, } } return false; +#elif defined(CMake_USE_XCOFF_PARSER) + // Parse the XCOFF binary. + cmXCOFF xcoff(file.c_str()); + if (cm::optional<cm::string_view> libPath = xcoff.GetLibPath()) { + if (cmSystemToolsFindRPath(*libPath, newRPath) != std::string::npos) { + return true; + } + } + return false; #else (void)file; (void)newRPath; diff --git a/Source/cmXCOFF.cxx b/Source/cmXCOFF.cxx new file mode 100644 index 0000000..890636e --- /dev/null +++ b/Source/cmXCOFF.cxx @@ -0,0 +1,356 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmXCOFF.h" + +#include <algorithm> +#include <cstddef> + +#include <cm/memory> + +#include "cmsys/FStream.hxx" + +#include "cmStringAlgorithms.h" + +// Include the XCOFF format information system header. +#ifdef _AIX +# define __XCOFF32__ +# define __XCOFF64__ +# include <xcoff.h> +#else +# error "This source may be compiled only on AIX." +#endif + +class cmXCOFFInternal +{ +public: + // Construct and take ownership of the file stream object. + cmXCOFFInternal(cmXCOFF* external, std::unique_ptr<std::iostream> fin, + cmXCOFF::Mode mode) + : External(external) + , Stream(std::move(fin)) + , Mode(mode) + { + } + + // Destruct and delete the file stream object. + virtual ~cmXCOFFInternal() = default; + + cmXCOFF::Mode GetMode() const { return this->Mode; } + + virtual cm::optional<cm::string_view> GetLibPath() = 0; + + virtual bool SetLibPath(cm::string_view libPath) = 0; + virtual bool RemoveLibPath() = 0; + +protected: + // Data common to all ELF class implementations. + + // The external cmXCOFF object. + cmXCOFF* External; + + // The stream from which to read. + std::unique_ptr<std::iostream> Stream; + + cmXCOFF::Mode Mode; + + // Helper methods for subclasses. + void SetErrorMessage(const char* msg) { this->External->ErrorMessage = msg; } +}; + +namespace { + +struct XCOFF32 +{ + typedef struct filehdr filehdr; + typedef struct aouthdr aouthdr; + typedef struct scnhdr scnhdr; + typedef struct ldhdr ldhdr; + static const std::size_t aouthdr_size = _AOUTHSZ_EXEC; +}; +const unsigned char xcoff32_magic[] = { 0x01, 0xDF }; + +struct XCOFF64 +{ + typedef struct filehdr_64 filehdr; + typedef struct aouthdr_64 aouthdr; + typedef struct scnhdr_64 scnhdr; + typedef struct ldhdr_64 ldhdr; + static const std::size_t aouthdr_size = _AOUTHSZ_EXEC_64; +}; +const unsigned char xcoff64_magic[] = { 0x01, 0xF7 }; + +template <typename XCOFF> +class Impl : public cmXCOFFInternal +{ + static_assert(sizeof(typename XCOFF::aouthdr) == XCOFF::aouthdr_size, + "aouthdr structure size matches _AOUTHSZ_EXEC macro"); + + typename XCOFF::filehdr FileHeader; + typename XCOFF::aouthdr AuxHeader; + typename XCOFF::scnhdr LoaderSectionHeader; + typename XCOFF::ldhdr LoaderHeader; + + std::streamoff LoaderImportFileTablePos = 0; + std::vector<char> LoaderImportFileTable; + + bool Read(typename XCOFF::filehdr& x) + { + // FIXME: Add byte swapping if needed. + return static_cast<bool>( + this->Stream->read(reinterpret_cast<char*>(&x), sizeof(x))); + } + + bool Read(typename XCOFF::aouthdr& x) + { + // FIXME: Add byte swapping if needed. + return static_cast<bool>( + this->Stream->read(reinterpret_cast<char*>(&x), sizeof(x))); + } + + bool Read(typename XCOFF::scnhdr& x) + { + // FIXME: Add byte swapping if needed. + return static_cast<bool>( + this->Stream->read(reinterpret_cast<char*>(&x), sizeof(x))); + } + + bool Read(typename XCOFF::ldhdr& x) + { + // FIXME: Add byte swapping if needed. + return static_cast<bool>( + this->Stream->read(reinterpret_cast<char*>(&x), sizeof(x))); + } + + bool WriteLoaderImportFileTableLength(decltype(XCOFF::ldhdr::l_istlen) x) + { + // FIXME: Add byte swapping if needed. + return static_cast<bool>( + this->Stream->write(reinterpret_cast<char const*>(&x), sizeof(x))); + } + +public: + Impl(cmXCOFF* external, std::unique_ptr<std::iostream> fin, + cmXCOFF::Mode mode); + + cm::optional<cm::string_view> GetLibPath() override; + bool SetLibPath(cm::string_view libPath) override; + bool RemoveLibPath() override; +}; + +template <typename XCOFF> +Impl<XCOFF>::Impl(cmXCOFF* external, std::unique_ptr<std::iostream> fin, + cmXCOFF::Mode mode) + : cmXCOFFInternal(external, std::move(fin), mode) +{ + if (!this->Read(this->FileHeader)) { + this->SetErrorMessage("Failed to read XCOFF file header."); + return; + } + if (this->FileHeader.f_opthdr != XCOFF::aouthdr_size) { + this->SetErrorMessage("XCOFF auxiliary header missing."); + return; + } + if (!this->Read(this->AuxHeader)) { + this->SetErrorMessage("Failed to read XCOFF auxiliary header."); + return; + } + if (this->AuxHeader.o_snloader == 0) { + this->SetErrorMessage("XCOFF loader section missing."); + return; + } + if (!this->Stream->seekg((this->AuxHeader.o_snloader - 1) * + sizeof(typename XCOFF::scnhdr), + std::ios::cur)) { + this->SetErrorMessage("Failed to seek to XCOFF loader section header."); + return; + } + if (!this->Read(this->LoaderSectionHeader)) { + this->SetErrorMessage("Failed to read XCOFF loader section header."); + return; + } + if ((this->LoaderSectionHeader.s_flags & STYP_LOADER) == 0) { + this->SetErrorMessage("XCOFF loader section header missing STYP_LOADER."); + return; + } + if (!this->Stream->seekg(this->LoaderSectionHeader.s_scnptr, + std::ios::beg)) { + this->SetErrorMessage("Failed to seek to XCOFF loader header."); + return; + } + if (!this->Read(this->LoaderHeader)) { + this->SetErrorMessage("Failed to read XCOFF loader header."); + return; + } + this->LoaderImportFileTablePos = + this->LoaderSectionHeader.s_scnptr + this->LoaderHeader.l_impoff; + if (!this->Stream->seekg(this->LoaderImportFileTablePos)) { + this->SetErrorMessage( + "Failed to seek to XCOFF loader import file id table."); + return; + } + this->LoaderImportFileTable.resize(this->LoaderHeader.l_istlen); + if (!this->Stream->read(this->LoaderImportFileTable.data(), + this->LoaderImportFileTable.size())) { + this->SetErrorMessage("Failed to read XCOFF loader import file id table."); + return; + } +} + +template <typename XCOFF> +cm::optional<cm::string_view> Impl<XCOFF>::GetLibPath() +{ + cm::optional<cm::string_view> result; + auto end = std::find(this->LoaderImportFileTable.begin(), + this->LoaderImportFileTable.end(), '\0'); + if (end != this->LoaderImportFileTable.end()) { + result = cm::string_view(this->LoaderImportFileTable.data(), + end - this->LoaderImportFileTable.begin()); + } + return result; +} + +template <typename XCOFF> +bool Impl<XCOFF>::SetLibPath(cm::string_view libPath) +{ + // The new LIBPATH must end in the standard AIX LIBPATH. +#define CM_AIX_LIBPATH "/usr/lib:/lib" + std::string libPathBuf; + if (libPath != CM_AIX_LIBPATH && + !cmHasLiteralSuffix(libPath, ":" CM_AIX_LIBPATH)) { + libPathBuf = std::string(libPath); + if (!libPathBuf.empty() && libPathBuf.back() != ':') { + libPathBuf.push_back(':'); + } + libPathBuf += CM_AIX_LIBPATH; + libPath = libPathBuf; + } +#undef CM_AIX_LIBPATH + + auto oldEnd = std::find(this->LoaderImportFileTable.begin(), + this->LoaderImportFileTable.end(), '\0'); + if (oldEnd == this->LoaderImportFileTable.end()) { + this->SetErrorMessage("XCOFF loader import file id table is invalid."); + return false; + } + if ((this->LoaderImportFileTable.begin() + libPath.size()) > oldEnd) { + this->SetErrorMessage("XCOFF loader import file id table is too small."); + return false; + } + + { + std::vector<char> ift; + ift.reserve(this->LoaderImportFileTable.size()); + // Start with the new LIBPATH. + ift.insert(ift.end(), libPath.begin(), libPath.end()); + // Add the rest of the original table. + ift.insert(ift.end(), oldEnd, this->LoaderImportFileTable.end()); + // If the new table is shorter, zero out the leftover space. + ift.resize(this->LoaderImportFileTable.size(), 0); + this->LoaderHeader.l_istlen = + static_cast<decltype(XCOFF::ldhdr::l_istlen)>(ift.size()); + this->LoaderImportFileTable = std::move(ift); + } + + if (!this->Stream->seekp(this->LoaderSectionHeader.s_scnptr + + offsetof(typename XCOFF::ldhdr, l_istlen), + std::ios::beg)) { + this->SetErrorMessage( + "Failed to seek to XCOFF loader header import file id table length."); + return false; + } + if (!this->WriteLoaderImportFileTableLength(this->LoaderHeader.l_istlen)) { + this->SetErrorMessage( + "Failed to write XCOFF loader header import file id table length."); + return false; + } + if (!this->Stream->seekp(this->LoaderImportFileTablePos, std::ios::beg)) { + this->SetErrorMessage( + "Failed to seek to XCOFF loader import file id table."); + return false; + } + if (!this->Stream->write(this->LoaderImportFileTable.data(), + this->LoaderImportFileTable.size())) { + this->SetErrorMessage( + "Failed to write XCOFF loader import file id table."); + return false; + } + + return true; +} + +template <typename XCOFF> +bool Impl<XCOFF>::RemoveLibPath() +{ + return this->SetLibPath({}); +} +} + +//============================================================================ +// External class implementation. + +cmXCOFF::cmXCOFF(const char* fname, Mode mode) +{ + // Try to open the file. + std::ios::openmode fmode = std::ios::in | std::ios::binary; + if (mode == Mode::ReadWrite) { + fmode |= std::ios::out; + } + auto f = cm::make_unique<cmsys::fstream>(fname, fmode); + + // Quit now if the file could not be opened. + if (!f || !*f) { + this->ErrorMessage = "Error opening input file."; + return; + } + + // Read the XCOFF magic number. + unsigned char magic[2]; + if (!f->read(reinterpret_cast<char*>(magic), sizeof(magic))) { + this->ErrorMessage = "Error reading XCOFF magic number."; + return; + } + if (!f->seekg(0)) { + this->ErrorMessage = "Error seeking to beginning of file."; + return; + } + + // Check the XCOFF type. + if (magic[0] == xcoff32_magic[0] && magic[1] == xcoff32_magic[1]) { + this->Internal = cm::make_unique<Impl<XCOFF32>>(this, std::move(f), mode); + } else if (magic[0] == xcoff64_magic[0] && magic[1] == xcoff64_magic[1]) { + this->Internal = cm::make_unique<Impl<XCOFF64>>(this, std::move(f), mode); + } else { + this->ErrorMessage = "File is not a XCOFF32 or XCOFF64 binary."; + } +} + +cmXCOFF::~cmXCOFF() = default; + +cmXCOFF::cmXCOFF(cmXCOFF&&) = default; +cmXCOFF& cmXCOFF::operator=(cmXCOFF&&) = default; + +bool cmXCOFF::Valid() const +{ + return this->Internal && this->ErrorMessage.empty(); +} + +cm::optional<cm::string_view> cmXCOFF::GetLibPath() const +{ + cm::optional<cm::string_view> result; + if (this->Valid()) { + result = this->Internal->GetLibPath(); + } + return result; +} + +bool cmXCOFF::SetLibPath(cm::string_view libPath) +{ + return this->Valid() && this->Internal->GetMode() == Mode::ReadWrite && + this->Internal->SetLibPath(libPath); +} + +bool cmXCOFF::RemoveLibPath() +{ + return this->Valid() && this->Internal->GetMode() == Mode::ReadWrite && + this->Internal->RemoveLibPath(); +} diff --git a/Source/cmXCOFF.h b/Source/cmXCOFF.h new file mode 100644 index 0000000..16cda9d --- /dev/null +++ b/Source/cmXCOFF.h @@ -0,0 +1,65 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#pragma once + +#include "cmConfigure.h" // IWYU pragma: keep + +#include <iosfwd> +#include <memory> +#include <string> + +#include <cm/optional> +#include <cm/string_view> + +#if !defined(CMake_USE_XCOFF_PARSER) +# error "This file may be included only if CMake_USE_XCOFF_PARSER is enabled." +#endif + +class cmXCOFFInternal; + +/** \class cmXCOFF + * \brief XCOFF parser. + */ +class cmXCOFF +{ +public: + enum class Mode + { + ReadOnly, + ReadWrite + }; + + /** Construct with the name of the XCOFF input file to parse. */ + cmXCOFF(const char* fname, Mode = Mode::ReadOnly); + + /** Destruct. */ + ~cmXCOFF(); + + cmXCOFF(cmXCOFF&&); + cmXCOFF(cmXCOFF const&) = delete; + cmXCOFF& operator=(cmXCOFF&&); + cmXCOFF& operator=(cmXCOFF const&) = delete; + + /** Get the error message if any. */ + std::string const& GetErrorMessage() const { return this->ErrorMessage; } + + /** Boolean conversion. True if the XCOFF file is valid. */ + explicit operator bool() const { return this->Valid(); } + + /** Get the LIBPATH (RPATH) parsed from the file, if any. */ + cm::optional<cm::string_view> GetLibPath() const; + + /** Set the LIBPATH (RPATH). + Works only if cmXCOFF was constructed with Mode::ReadWrite. */ + bool SetLibPath(cm::string_view libPath); + + /** Remove the LIBPATH (RPATH). + Works only if cmXCOFF was constructed with Mode::ReadWrite. */ + bool RemoveLibPath(); + +private: + friend class cmXCOFFInternal; + bool Valid() const; + std::unique_ptr<cmXCOFFInternal> Internal; + std::string ErrorMessage; +}; |