diff --git a/lld/MachO/CodeSigningTypes.h b/lld/MachO/CodeSigningTypes.h new file mode 100644 --- /dev/null +++ b/lld/MachO/CodeSigningTypes.h @@ -0,0 +1,154 @@ +/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- + * + * Copyright (c) 2015 Apple Inc. All rights reserved. + * + * @APPLE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this + * file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * @APPLE_LICENSE_HEADER_END@ + */ + +#ifndef _CODE_SIGNING_TYPES_ +#define _CODE_SIGNING_TYPES_ + +#include +#include + +// +// Magic numbers used by Code Signing +// +enum { + CSMAGIC_REQUIREMENT = 0xfade0c00, // single Requirement blob + CSMAGIC_REQUIREMENTS = + 0xfade0c01, // Requirements vector (internal requirements) + CSMAGIC_CODEDIRECTORY = 0xfade0c02, // CodeDirectory blob + CSMAGIC_EMBEDDED_SIGNATURE = 0xfade0cc0, // embedded form of signature data + CSMAGIC_DETACHED_SIGNATURE = + 0xfade0cc1, // multi-arch collection of embedded signatures + CSMAGIC_BLOBWRAPPER = 0xfade0b01, // used for the cms blob +}; + +enum { + CS_PAGE_SIZE_4K = 4096, + CS_PAGE_SIZE_16K = 16384, + + CS_HASHTYPE_SHA1 = 1, + CS_HASHTYPE_SHA256 = 2, + CS_HASHTYPE_SHA256_TRUNCATED = 3, + CS_HASHTYPE_SHA384 = 4, + + CS_HASH_SIZE_SHA1 = 20, + CS_HASH_SIZE_SHA256 = 32, + CS_HASH_SIZE_SHA256_TRUNCATED = 20, + + CSSLOT_CODEDIRECTORY = 0, + CSSLOT_INFOSLOT = 1, + CSSLOT_REQUIREMENTS = 2, + CSSLOT_RESOURCEDIR = 3, + CSSLOT_APPLICATION = 4, + CSSLOT_ENTITLEMENTS = 5, + CSSLOT_ALTERNATE_CODEDIRECTORIES = 0x1000, + CSSLOT_ALTERNATE_CODEDIRECTORY_MAX = 5, + CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT = + CSSLOT_ALTERNATE_CODEDIRECTORIES + CSSLOT_ALTERNATE_CODEDIRECTORY_MAX, + CSSLOT_CMS_SIGNATURE = 0x10000, + + kSecCodeSignatureAdhoc = 2 +}; + +enum { + CS_REQUIRE_LV = 0x0002000 // require library validation +}; + +// +// Structure of a SuperBlob +// +struct CS_BlobIndex { + uint32_t type; // type of entry + uint32_t offset; // offset of entry +}; + +struct CS_SuperBlob { + uint32_t magic; // magic number + uint32_t length; // total length of SuperBlob + uint32_t count; // number of index entries following + // CS_BlobIndex index[]; // (count) entries + // followed by Blobs in no particular order as indicated by offsets in index +}; + +// +// C form of a CodeDirectory. +// +struct CS_CodeDirectory { + uint32_t magic; // magic number (CSMAGIC_CODEDIRECTORY) */ + uint32_t length; // total length of CodeDirectory blob + uint32_t version; // compatibility version + uint32_t flags; // setup and mode flags + uint32_t hashOffset; // offset of hash slot element at index zero + uint32_t identOffset; // offset of identifier string + uint32_t nSpecialSlots; // number of special hash slots + uint32_t nCodeSlots; // number of ordinary (code) hash slots + uint32_t codeLimit; // limit to main image signature range + uint8_t hashSize; // size of each hash in bytes + uint8_t hashType; // type of hash (cdHashType* constants) + uint8_t platform; // platform identifier; zero if not platform binary + uint8_t pageSize; // log2(page size in bytes); 0 => infinite + uint32_t spare2; // unused (must be zero) + + // char end_earliest[0]; + + /* Version 0x20100 */ + uint32_t scatterOffset; /* offset of optional scatter vector */ + // char end_withScatter[0]; + + /* Version 0x20200 */ + uint32_t teamOffset; /* offset of optional team identifier */ + // char end_withTeam[0]; + + /* Version 0x20300 */ + uint32_t spare3; /* unused (must be zero) */ + uint64_t codeLimit64; /* limit to main image signature range, 64 bits */ + // char end_withCodeLimit64[0]; + + /* Version 0x20400 */ + uint64_t execSegBase; /* offset of executable segment */ + uint64_t execSegLimit; /* limit of executable segment */ + uint64_t execSegFlags; /* exec segment flags */ + // char end_withExecSeg[0]; + + /* followed by dynamic content as located by offset fields above */ +}; + +struct CS_Blob { + uint32_t magic; // magic number + uint32_t length; // total length of blob +}; + +struct CS_RequirementsBlob { + uint32_t magic; // magic number + uint32_t length; // total length of blob + uint32_t data; // zero for dyld shared cache +}; + +struct CS_Scatter { + uint32_t count; // number of pages; zero for sentinel (only) + uint32_t base; // first page number + uint64_t targetOffset; // byte offset in target + uint64_t spare; // reserved (must be zero) +}; + +#endif // _CODE_SIGNING_TYPES_ diff --git a/lld/MachO/OutputSegment.h b/lld/MachO/OutputSegment.h --- a/lld/MachO/OutputSegment.h +++ b/lld/MachO/OutputSegment.h @@ -45,6 +45,7 @@ size_t numNonHiddenSections() const; uint64_t fileOff = 0; + uint64_t fileSize = 0; StringRef name; uint32_t maxProt = 0; uint32_t initProt = 0; diff --git a/lld/MachO/SyntheticSections.h b/lld/MachO/SyntheticSections.h --- a/lld/MachO/SyntheticSections.h +++ b/lld/MachO/SyntheticSections.h @@ -9,6 +9,7 @@ #ifndef LLD_MACHO_SYNTHETIC_SECTIONS_H #define LLD_MACHO_SYNTHETIC_SECTIONS_H +#include "CodeSigningTypes.h" #include "Config.h" #include "ExportTrie.h" #include "InputSection.h" @@ -40,6 +41,7 @@ constexpr const char symbolTable[] = "__symbol_table"; constexpr const char indirectSymbolTable[] = "__ind_sym_tab"; constexpr const char stringTable[] = "__string_table"; +constexpr const char codeSignature[] = "__code_signature"; constexpr const char got[] = "__got"; constexpr const char threadPtrs[] = "__thread_ptrs"; constexpr const char unwindInfo[] = "__unwind_info"; @@ -94,7 +96,7 @@ // NOTE: This assumes that the extra bytes required for alignment can be // zero-valued bytes. uint64_t getSize() const override final { - return llvm::alignTo(getRawSize(), WordSize); + return llvm::alignTo(getRawSize(), align); } }; @@ -482,6 +484,28 @@ void writeTo(uint8_t *buf) const override; }; +// The code signature comes at the very end of the linked output file. +class CodeSignatureSection : public LinkEditSection { +public: + const uint8_t blockSizeShift = 12; + const ssize_t blockSize = (1 << blockSizeShift); // 4 KiB + const size_t hashSize = 256 / 8; + const uint32_t blobHeadersSize = sizeof(CS_SuperBlob) + sizeof(CS_BlobIndex); + const uint32_t fixedHeadersSize = blobHeadersSize + sizeof(CS_CodeDirectory); + + uint32_t fileNameSize = 0; + uint32_t fileNamePad = 0; + uint32_t allHeadersSize = 0; + StringRef fileName; + + CodeSignatureSection(); + uint64_t getRawSize() const override; + bool isNeeded() const override { return true; } + void writeTo(uint8_t *buf) const override; + uint32_t getBlockCount() const; + void writeHashes(uint8_t *buf) const; +}; + struct InStruct { MachHeaderSection *header = nullptr; RebaseSection *rebase = nullptr; diff --git a/lld/MachO/SyntheticSections.cpp b/lld/MachO/SyntheticSections.cpp --- a/lld/MachO/SyntheticSections.cpp +++ b/lld/MachO/SyntheticSections.cpp @@ -24,6 +24,7 @@ #include "llvm/Support/FileSystem.h" #include "llvm/Support/LEB128.h" #include "llvm/Support/Path.h" +#include "llvm/Support/SHA256.h" using namespace llvm; using namespace llvm::support; @@ -868,3 +869,83 @@ off += str.size() + 1; // account for null terminator } } + +CodeSignatureSection::CodeSignatureSection() + : LinkEditSection(segment_names::linkEdit, section_names::codeSignature) { + align = 16; // required by libstuff + fileName = config->outputFile; + size_t slashIndex = fileName.rfind("/"); + if (slashIndex != std::string::npos) + fileName = fileName.drop_front(slashIndex + 1); + fileNameSize = fileName.size(); + allHeadersSize = alignTo(fixedHeadersSize + fileNameSize + 1, WordSize); + fileNamePad = allHeadersSize - fixedHeadersSize - fileNameSize; +} + +uint32_t CodeSignatureSection::getBlockCount() const { + return (fileOff + blockSize - 1) / blockSize; +} + +uint64_t CodeSignatureSection::getRawSize() const { + return allHeadersSize + getBlockCount() * hashSize; +} + +void CodeSignatureSection::writeHashes(uint8_t *buf) const { + uint8_t *codeEnd = buf + fileOff; + uint8_t *hashes = codeEnd + allHeadersSize; + while (buf < codeEnd) { + StringRef block(reinterpret_cast(buf), + std::min(codeEnd - buf, blockSize)); + SHA256 Hasher; + Hasher.update(block); + StringRef hash = Hasher.final(); + assert(hash.size() == hashSize); + memcpy(hashes, hash.data(), hashSize); + buf += blockSize; + hashes += hashSize; + } +} + +void CodeSignatureSection::writeTo(uint8_t *buf) const { + using namespace llvm::support::endian; + uint32_t blobHeadersSize = sizeof(CS_SuperBlob) + sizeof(CS_BlobIndex); + uint32_t signatureSize = static_cast(getSize()); + auto *superBlob = reinterpret_cast(buf); + write32be(&superBlob->magic, CSMAGIC_EMBEDDED_SIGNATURE); + write32be(&superBlob->length, signatureSize); + write32be(&superBlob->count, 1); + auto *blobIndex = reinterpret_cast(&superBlob[1]); + write32be(&blobIndex->type, CSSLOT_CODEDIRECTORY); + write32be(&blobIndex->offset, blobHeadersSize); + auto *codeDirectory = reinterpret_cast(&blobIndex[1]); + write32be(&codeDirectory->magic, CSMAGIC_CODEDIRECTORY); + write32be(&codeDirectory->length, signatureSize - blobHeadersSize); + write32be(&codeDirectory->version, 0x20400); + write32be(&codeDirectory->flags, + 0x20002); // adhoc | linkerSigned + write32be(&codeDirectory->hashOffset, + sizeof(CS_CodeDirectory) + fileNameSize + fileNamePad); + write32be(&codeDirectory->identOffset, sizeof(CS_CodeDirectory)); + codeDirectory->nSpecialSlots = 0; + write32be(&codeDirectory->nCodeSlots, getBlockCount()); + write32be(&codeDirectory->codeLimit, fileOff); + codeDirectory->hashSize = hashSize; + codeDirectory->hashType = 2; // kSecCodeSignatureHashSHA256 + codeDirectory->platform = 0; + codeDirectory->pageSize = blockSizeShift; + codeDirectory->spare2 = 0; + codeDirectory->scatterOffset = 0; + codeDirectory->teamOffset = 0; + codeDirectory->spare3 = 0; + codeDirectory->codeLimit64 = 0; + OutputSegment *textSeg = getOrCreateOutputSegment(segment_names::text); + write64be(&codeDirectory->execSegBase, textSeg->fileOff); + write64be(&codeDirectory->execSegLimit, textSeg->fileSize); + write64be(&codeDirectory->execSegFlags, + config->outputType == llvm::MachO::MH_EXECUTE + ? 1 + : 0); // CS_EXECSEG_MAIN_BINARY + auto *id = reinterpret_cast(&codeDirectory[1]); + memcpy(id, fileName.begin(), fileNameSize); + memset(id + fileNameSize, 0, fileNamePad); +} diff --git a/lld/MachO/Writer.cpp b/lld/MachO/Writer.cpp --- a/lld/MachO/Writer.cpp +++ b/lld/MachO/Writer.cpp @@ -62,6 +62,7 @@ StringTableSection *stringTableSection = nullptr; SymtabSection *symtabSection = nullptr; IndirectSymtabSection *indirectSymtabSection = nullptr; + CodeSignatureSection *codeSignatureSection = nullptr; UnwindInfoSection *unwindInfoSection = nullptr; LCUuid *uuidCommand = nullptr; }; @@ -400,6 +401,24 @@ mutable uint8_t *uuidBuf; }; +// TODO(gkm): write block comment +class LCCodeSignature : public LoadCommand { +public: + LCCodeSignature(CodeSignatureSection *section) : section(section) {} + + uint32_t getSize() const override { return sizeof(linkedit_data_command); } + + void writeTo(uint8_t *buf) const override { + auto *c = reinterpret_cast(buf); + c->cmd = LC_CODE_SIGNATURE; + c->cmdsize = getSize(); + c->dataoff = static_cast(section->fileOff); + c->datasize = section->getSize(); + } + + CodeSignatureSection *section; +}; + } // namespace static void prepareSymbolRelocation(lld::macho::Symbol *sym, @@ -515,6 +534,9 @@ } } + if (codeSignatureSection) + in.header->addLoadCommand(make(codeSignatureSection)); + const uint32_t MACOS_MAXPATHLEN = 1024; config->headerPad = std::max( config->headerPad, (config->headerPadMaxInstallNames @@ -618,6 +640,7 @@ .Case(section_names::symbolTable, -3) .Case(section_names::indirectSymbolTable, -2) .Case(section_names::stringTable, -1) + .Case(section_names::codeSignature, std::numeric_limits::max()) .Default(0); } // ZeroFill sections must always be the at the end of their segments, @@ -672,6 +695,8 @@ unwindInfoSection = make(); // TODO(gkm): only when no -r symtabSection = make(*stringTableSection); indirectSymtabSection = make(); + if (config->arch == AK_arm64 || config->arch == AK_arm64e) + codeSignatureSection = make(); switch (config->outputType) { case MH_EXECUTE: @@ -737,6 +762,7 @@ addr += osec->getSize(); fileOff += osec->getFileSize(); } + seg->fileSize = fileOff - seg->fileOff; } void Writer::openFile() { @@ -759,8 +785,10 @@ } void Writer::writeUuid() { - uint64_t digest = - xxHash64({buffer->getBufferStart(), buffer->getBufferEnd()}); + uint8_t *codeEnd = + buffer->getBufferEnd() - + (codeSignatureSection ? codeSignatureSection->getSize() : 0); + uint64_t digest = xxHash64({buffer->getBufferStart(), codeEnd}); uuidCommand->writeUuid(digest); } @@ -811,6 +839,8 @@ writeSections(); writeUuid(); + if (codeSignatureSection) + codeSignatureSection->writeHashes(buffer->getBufferStart()); if (auto e = buffer->commit()) error("failed to write to the output file: " + toString(std::move(e))); diff --git a/llvm/include/llvm/Support/SHA256.h b/llvm/include/llvm/Support/SHA256.h new file mode 100644 --- /dev/null +++ b/llvm/include/llvm/Support/SHA256.h @@ -0,0 +1,81 @@ +/* + * The SHA-256 Secure Hash Standard was published by NIST in 2002. + * + * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf + */ +/* + The implementation is based on botans's SHA256 implementation [0]. + + [0] + https://github.com/randombit/botan/blob/master/src/lib/hash/sha2_32/sha2_32.cpp + */ + +#ifndef LLVM_SUPPORT_SHA2_H +#define LLVM_SUPPORT_SHA2_H + +#include +#include + +namespace llvm { + +template class ArrayRef; +class StringRef; + +class SHA256 { +public: + explicit SHA256() { init(); } + + /// Reinitialize the internal state + void init(); + + /// Digest more data. + void update(ArrayRef Data); + + /// Digest more data. + void update(StringRef Str); + + /// Return a reference to the current raw 256-bits SHA256 for the digested + /// data since the last call to init(). This call will add data to the + /// internal state and as such is not suited for getting an intermediate + /// result (see result()). + StringRef final(); + + /// Return a reference to the current raw 256-bits SHA256 for the digested + /// data since the last call to init(). This is suitable for getting the + /// SHA256 at any time without invalidating the internal state so that more + /// calls can be made into update. + StringRef result(); + + /// Returns a raw 256-bit SHA256 hash for the given data. + static std::array hash(ArrayRef Data); + +private: + /// Define some constants. + /// "static constexpr" would be cleaner but MSVC does not support it yet. + enum { BLOCK_LENGTH = 64 }; + enum { HASH_LENGTH = 32 }; + + // Internal State + struct { + union { + uint8_t C[BLOCK_LENGTH]; + uint32_t L[BLOCK_LENGTH / 4]; + } Buffer; + uint32_t State[HASH_LENGTH / 4]; + uint32_t ByteCount; + uint8_t BufferOffset; + } InternalState; + + // Internal copy of the hash, populated and accessed on calls to result() + uint32_t HashResult[HASH_LENGTH / 4]; + + // Helper + void writebyte(uint8_t data); + void hashBlock(); + void addUncounted(uint8_t data); + void pad(); +}; + +} // namespace llvm + +#endif // LLVM_SUPPORT_SHA2_H diff --git a/llvm/lib/Support/CMakeLists.txt b/llvm/lib/Support/CMakeLists.txt --- a/llvm/lib/Support/CMakeLists.txt +++ b/llvm/lib/Support/CMakeLists.txt @@ -162,6 +162,7 @@ ScaledNumber.cpp ScopedPrinter.cpp SHA1.cpp + SHA256.cpp Signposts.cpp SmallPtrSet.cpp SmallVector.cpp diff --git a/llvm/lib/Support/SHA256.cpp b/llvm/lib/Support/SHA256.cpp new file mode 100644 --- /dev/null +++ b/llvm/lib/Support/SHA256.cpp @@ -0,0 +1,264 @@ +#include "llvm/Support/SHA256.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/Endian.h" +#include "llvm/Support/Host.h" +#include + +#if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN +#define SHA_BIG_ENDIAN +#endif + +namespace llvm { + +#define ROTR(x, n) (((x) >> n) | ((x) << (32 - (n)))) + +#define SHA2_32_F(A, B, C, D, E, F, G, H, M1, M2, M3, M4, magic) \ + do { \ + uint32_t A_rho = ROTR(A, 2) ^ ROTR(A, 13) ^ ROTR(A, 22); \ + uint32_t E_rho = ROTR(E, 6) ^ ROTR(E, 11) ^ ROTR(E, 25); \ + uint32_t M2_sigma = ROTR(M2, 17) ^ ROTR(M2, 19) ^ (M2 >> 10); \ + uint32_t M4_sigma = ROTR(M4, 7) ^ ROTR(M4, 18) ^ (M4 >> 3); \ + H += magic + E_rho + ((E & F) ^ (~E & G)) + M1; \ + D += H; \ + H += A_rho + ((A & B) | ((A | B) & C)); \ + M1 += M2_sigma + M3 + M4_sigma; \ + } while (0); + +void SHA256::init() { + InternalState.State[0] = 0x6A09E667; + InternalState.State[1] = 0xBB67AE85; + InternalState.State[2] = 0x3C6EF372; + InternalState.State[3] = 0xA54FF53A; + InternalState.State[4] = 0x510E527F; + InternalState.State[5] = 0x9B05688C; + InternalState.State[6] = 0x1F83D9AB; + InternalState.State[7] = 0x5BE0CD19; + InternalState.ByteCount = 0; + InternalState.BufferOffset = 0; +} + +void SHA256::hashBlock() { + uint32_t A = InternalState.State[0]; + uint32_t B = InternalState.State[1]; + uint32_t C = InternalState.State[2]; + uint32_t D = InternalState.State[3]; + uint32_t E = InternalState.State[4]; + uint32_t F = InternalState.State[5]; + uint32_t G = InternalState.State[6]; + uint32_t H = InternalState.State[7]; + + uint32_t W00 = InternalState.Buffer.L[0]; + uint32_t W01 = InternalState.Buffer.L[1]; + uint32_t W02 = InternalState.Buffer.L[2]; + uint32_t W03 = InternalState.Buffer.L[3]; + uint32_t W04 = InternalState.Buffer.L[4]; + uint32_t W05 = InternalState.Buffer.L[5]; + uint32_t W06 = InternalState.Buffer.L[6]; + uint32_t W07 = InternalState.Buffer.L[7]; + uint32_t W08 = InternalState.Buffer.L[8]; + uint32_t W09 = InternalState.Buffer.L[9]; + uint32_t W10 = InternalState.Buffer.L[10]; + uint32_t W11 = InternalState.Buffer.L[11]; + uint32_t W12 = InternalState.Buffer.L[12]; + uint32_t W13 = InternalState.Buffer.L[13]; + uint32_t W14 = InternalState.Buffer.L[14]; + uint32_t W15 = InternalState.Buffer.L[15]; + + SHA2_32_F(A, B, C, D, E, F, G, H, W00, W14, W09, W01, 0x428A2F98); + SHA2_32_F(H, A, B, C, D, E, F, G, W01, W15, W10, W02, 0x71374491); + SHA2_32_F(G, H, A, B, C, D, E, F, W02, W00, W11, W03, 0xB5C0FBCF); + SHA2_32_F(F, G, H, A, B, C, D, E, W03, W01, W12, W04, 0xE9B5DBA5); + SHA2_32_F(E, F, G, H, A, B, C, D, W04, W02, W13, W05, 0x3956C25B); + SHA2_32_F(D, E, F, G, H, A, B, C, W05, W03, W14, W06, 0x59F111F1); + SHA2_32_F(C, D, E, F, G, H, A, B, W06, W04, W15, W07, 0x923F82A4); + SHA2_32_F(B, C, D, E, F, G, H, A, W07, W05, W00, W08, 0xAB1C5ED5); + SHA2_32_F(A, B, C, D, E, F, G, H, W08, W06, W01, W09, 0xD807AA98); + SHA2_32_F(H, A, B, C, D, E, F, G, W09, W07, W02, W10, 0x12835B01); + SHA2_32_F(G, H, A, B, C, D, E, F, W10, W08, W03, W11, 0x243185BE); + SHA2_32_F(F, G, H, A, B, C, D, E, W11, W09, W04, W12, 0x550C7DC3); + SHA2_32_F(E, F, G, H, A, B, C, D, W12, W10, W05, W13, 0x72BE5D74); + SHA2_32_F(D, E, F, G, H, A, B, C, W13, W11, W06, W14, 0x80DEB1FE); + SHA2_32_F(C, D, E, F, G, H, A, B, W14, W12, W07, W15, 0x9BDC06A7); + SHA2_32_F(B, C, D, E, F, G, H, A, W15, W13, W08, W00, 0xC19BF174); + + SHA2_32_F(A, B, C, D, E, F, G, H, W00, W14, W09, W01, 0xE49B69C1); + SHA2_32_F(H, A, B, C, D, E, F, G, W01, W15, W10, W02, 0xEFBE4786); + SHA2_32_F(G, H, A, B, C, D, E, F, W02, W00, W11, W03, 0x0FC19DC6); + SHA2_32_F(F, G, H, A, B, C, D, E, W03, W01, W12, W04, 0x240CA1CC); + SHA2_32_F(E, F, G, H, A, B, C, D, W04, W02, W13, W05, 0x2DE92C6F); + SHA2_32_F(D, E, F, G, H, A, B, C, W05, W03, W14, W06, 0x4A7484AA); + SHA2_32_F(C, D, E, F, G, H, A, B, W06, W04, W15, W07, 0x5CB0A9DC); + SHA2_32_F(B, C, D, E, F, G, H, A, W07, W05, W00, W08, 0x76F988DA); + SHA2_32_F(A, B, C, D, E, F, G, H, W08, W06, W01, W09, 0x983E5152); + SHA2_32_F(H, A, B, C, D, E, F, G, W09, W07, W02, W10, 0xA831C66D); + SHA2_32_F(G, H, A, B, C, D, E, F, W10, W08, W03, W11, 0xB00327C8); + SHA2_32_F(F, G, H, A, B, C, D, E, W11, W09, W04, W12, 0xBF597FC7); + SHA2_32_F(E, F, G, H, A, B, C, D, W12, W10, W05, W13, 0xC6E00BF3); + SHA2_32_F(D, E, F, G, H, A, B, C, W13, W11, W06, W14, 0xD5A79147); + SHA2_32_F(C, D, E, F, G, H, A, B, W14, W12, W07, W15, 0x06CA6351); + SHA2_32_F(B, C, D, E, F, G, H, A, W15, W13, W08, W00, 0x14292967); + + SHA2_32_F(A, B, C, D, E, F, G, H, W00, W14, W09, W01, 0x27B70A85); + SHA2_32_F(H, A, B, C, D, E, F, G, W01, W15, W10, W02, 0x2E1B2138); + SHA2_32_F(G, H, A, B, C, D, E, F, W02, W00, W11, W03, 0x4D2C6DFC); + SHA2_32_F(F, G, H, A, B, C, D, E, W03, W01, W12, W04, 0x53380D13); + SHA2_32_F(E, F, G, H, A, B, C, D, W04, W02, W13, W05, 0x650A7354); + SHA2_32_F(D, E, F, G, H, A, B, C, W05, W03, W14, W06, 0x766A0ABB); + SHA2_32_F(C, D, E, F, G, H, A, B, W06, W04, W15, W07, 0x81C2C92E); + SHA2_32_F(B, C, D, E, F, G, H, A, W07, W05, W00, W08, 0x92722C85); + SHA2_32_F(A, B, C, D, E, F, G, H, W08, W06, W01, W09, 0xA2BFE8A1); + SHA2_32_F(H, A, B, C, D, E, F, G, W09, W07, W02, W10, 0xA81A664B); + SHA2_32_F(G, H, A, B, C, D, E, F, W10, W08, W03, W11, 0xC24B8B70); + SHA2_32_F(F, G, H, A, B, C, D, E, W11, W09, W04, W12, 0xC76C51A3); + SHA2_32_F(E, F, G, H, A, B, C, D, W12, W10, W05, W13, 0xD192E819); + SHA2_32_F(D, E, F, G, H, A, B, C, W13, W11, W06, W14, 0xD6990624); + SHA2_32_F(C, D, E, F, G, H, A, B, W14, W12, W07, W15, 0xF40E3585); + SHA2_32_F(B, C, D, E, F, G, H, A, W15, W13, W08, W00, 0x106AA070); + + SHA2_32_F(A, B, C, D, E, F, G, H, W00, W14, W09, W01, 0x19A4C116); + SHA2_32_F(H, A, B, C, D, E, F, G, W01, W15, W10, W02, 0x1E376C08); + SHA2_32_F(G, H, A, B, C, D, E, F, W02, W00, W11, W03, 0x2748774C); + SHA2_32_F(F, G, H, A, B, C, D, E, W03, W01, W12, W04, 0x34B0BCB5); + SHA2_32_F(E, F, G, H, A, B, C, D, W04, W02, W13, W05, 0x391C0CB3); + SHA2_32_F(D, E, F, G, H, A, B, C, W05, W03, W14, W06, 0x4ED8AA4A); + SHA2_32_F(C, D, E, F, G, H, A, B, W06, W04, W15, W07, 0x5B9CCA4F); + SHA2_32_F(B, C, D, E, F, G, H, A, W07, W05, W00, W08, 0x682E6FF3); + SHA2_32_F(A, B, C, D, E, F, G, H, W08, W06, W01, W09, 0x748F82EE); + SHA2_32_F(H, A, B, C, D, E, F, G, W09, W07, W02, W10, 0x78A5636F); + SHA2_32_F(G, H, A, B, C, D, E, F, W10, W08, W03, W11, 0x84C87814); + SHA2_32_F(F, G, H, A, B, C, D, E, W11, W09, W04, W12, 0x8CC70208); + SHA2_32_F(E, F, G, H, A, B, C, D, W12, W10, W05, W13, 0x90BEFFFA); + SHA2_32_F(D, E, F, G, H, A, B, C, W13, W11, W06, W14, 0xA4506CEB); + SHA2_32_F(C, D, E, F, G, H, A, B, W14, W12, W07, W15, 0xBEF9A3F7); + SHA2_32_F(B, C, D, E, F, G, H, A, W15, W13, W08, W00, 0xC67178F2); + + InternalState.State[0] += A; + InternalState.State[1] += B; + InternalState.State[2] += C; + InternalState.State[3] += D; + InternalState.State[4] += E; + InternalState.State[5] += F; + InternalState.State[6] += G; + InternalState.State[7] += H; +} + +void SHA256::addUncounted(uint8_t Data) { +#ifdef SHA_BIG_ENDIAN + InternalState.Buffer.C[InternalState.BufferOffset] = Data; +#else + InternalState.Buffer.C[InternalState.BufferOffset ^ 3] = Data; +#endif + + InternalState.BufferOffset++; + if (InternalState.BufferOffset == BLOCK_LENGTH) { + hashBlock(); + InternalState.BufferOffset = 0; + } +} + +void SHA256::writebyte(uint8_t Data) { + ++InternalState.ByteCount; + addUncounted(Data); +} + +void SHA256::update(ArrayRef Data) { + InternalState.ByteCount += Data.size(); + + // Finish the current block. + if (InternalState.BufferOffset > 0) { + const size_t Remainder = std::min( + Data.size(), BLOCK_LENGTH - InternalState.BufferOffset); + for (size_t I = 0; I < Remainder; ++I) + addUncounted(Data[I]); + Data = Data.drop_front(Remainder); + } + + // Fast buffer filling for large inputs. + while (Data.size() >= BLOCK_LENGTH) { + assert(InternalState.BufferOffset == 0); + assert(BLOCK_LENGTH % 4 == 0); + constexpr size_t BLOCK_LENGTH_32 = BLOCK_LENGTH / 4; + for (size_t I = 0; I < BLOCK_LENGTH_32; ++I) + InternalState.Buffer.L[I] = support::endian::read32be(&Data[I * 4]); + hashBlock(); + Data = Data.drop_front(BLOCK_LENGTH); + } + + // Finish the remainder. + for (uint8_t C : Data) + addUncounted(C); +} + +void SHA256::update(StringRef Str) { + update( + ArrayRef((uint8_t *)const_cast(Str.data()), Str.size())); +} + +void SHA256::pad() { + // Implement SHA-2 padding (fips180-2 5.1.1) + + // Pad with 0x80 followed by 0x00 until the end of the block + addUncounted(0x80); + while (InternalState.BufferOffset != 56) + addUncounted(0x00); + + uint64_t len = InternalState.ByteCount << 3; // bit size + + // Append length in the last 8 bytes big edian encoded + addUncounted(len >> 56); + addUncounted(len >> 48); + addUncounted(len >> 40); + addUncounted(len >> 32); + addUncounted(len >> 24); + addUncounted(len >> 16); + addUncounted(len >> 8); + addUncounted(len); +} + +StringRef SHA256::final() { + // Pad to complete the last block + pad(); + +#ifdef SHA_BIG_ENDIAN + // Just copy the current state + for (int i = 0; i < 8; i++) { + HashResult[i] = InternalState.State[i]; + } +#else + // Swap byte order back + for (int i = 0; i < 8; i++) { + HashResult[i] = (((InternalState.State[i]) << 24) & 0xff000000) | + (((InternalState.State[i]) << 8) & 0x00ff0000) | + (((InternalState.State[i]) >> 8) & 0x0000ff00) | + (((InternalState.State[i]) >> 24) & 0x000000ff); + } +#endif + + // Return pointer to hash (32 characters) + return StringRef((char *)HashResult, HASH_LENGTH); +} + +StringRef SHA256::result() { + auto StateToRestore = InternalState; + + auto Hash = final(); + + // Restore the state + InternalState = StateToRestore; + + // Return pointer to hash (32 characters) + return Hash; +} + +std::array SHA256::hash(ArrayRef Data) { + SHA256 Hash; + Hash.update(Data); + StringRef S = Hash.final(); + + std::array Arr; + memcpy(Arr.data(), S.data(), S.size()); + return Arr; +} + +} // namespace llvm