#!/usr/bin/env python3
"""Rewrite or verify the SQLite bitcode span of the pinned Linux x86-64 AOT image."""

import argparse
import hashlib
import json
import mmap
import os
from pathlib import Path
import shutil
import struct
import sys
import tempfile


IMAGE_SHA256 = "da6b5711711c3eb64ee01380c0d83127b31d818e36d5afc90f259761a2158e5f"
IMAGE_SIZE = 127404352
RESOURCE_SHA256 = "de12b326ec5546727fc179268127461c08672093211332ff3f071382ed6b09e8"
RESOURCE_START = 108534448
RESOURCE_SIZE = 2820756
RESOURCE_END = RESOURCE_START + RESOURCE_SIZE
HEAP_START = 0x3230000
HEAP_SIZE = 0x4750000
RAW_BITCODE_MAGIC = b"BC\xc0\xde"
WRAPPER_MAGIC = 0x0B17C0DE
WRAPPER = struct.Struct("<IIIII")
CPU_TYPE_X86_64 = 0x01000007
CHUNK_SIZE = 1024 * 1024


def digest(data):
    return hashlib.sha256(data).hexdigest()


def require(condition, message):
    if not condition:
        raise ValueError(message)


def original_resource(image):
    require(len(image) == IMAGE_SIZE and digest(image) == IMAGE_SHA256,
            "original ELF does not match the pinned image")
    require(HEAP_START <= RESOURCE_START < RESOURCE_END <= HEAP_START + HEAP_SIZE,
            "pinned resource span falls outside .svm_heap")
    resource = image[RESOURCE_START:RESOURCE_END]
    require(resource.startswith(RAW_BITCODE_MAGIC) and digest(resource) == RESOURCE_SHA256,
            "original resource does not match the pinned bitcode")
    require(image.find(resource) == RESOURCE_START
            and image.find(resource, RESOURCE_START + 1) == -1,
            "original bitcode is not unique at the pinned offset")
    return resource


def read_replacement(bitcode):
    limit = RESOURCE_SIZE - WRAPPER.size
    with bitcode.open("rb") as module:
        raw = module.read(limit + 1)
    require(len(raw) <= limit, "replacement exceeds the pinned resource size")
    require(raw.startswith(RAW_BITCODE_MAGIC), "expected raw LLVM bitcode")
    return raw


def wrap(raw):
    header = WRAPPER.pack(WRAPPER_MAGIC, 0, WRAPPER.size, len(raw), CPU_TYPE_X86_64)
    return (header + raw).ljust(RESOURCE_SIZE, b"\0")


def verify(image, resource, raw, wrapped, candidate):
    with candidate.open("rb") as file:
        require(os.fstat(file.fileno()).st_size == IMAGE_SIZE, "candidate ELF length changed")
        with mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as patched:
            require(patched[RESOURCE_START:RESOURCE_END] == wrapped,
                    "candidate resource does not match the expected bitcode and padding")
            for start, end in ((0, RESOURCE_START), (RESOURCE_END, IMAGE_SIZE)):
                for offset in range(start, end, CHUNK_SIZE):
                    limit = min(offset + CHUNK_SIZE, end)
                    require(patched[offset:limit] == image[offset:limit],
                            f"candidate bytes changed outside the resource in [{offset}, {limit})")
            image_sha256 = digest(patched)

    return {
        "original_image_sha256": IMAGE_SHA256,
        "patched_image_sha256": image_sha256,
        "original_resource_sha256": RESOURCE_SHA256,
        "raw_replacement_sha256": digest(raw),
        "wrapped_padded_resource_sha256": digest(wrapped),
        "image_bytes": IMAGE_SIZE,
        "section": ".svm_heap",
        "section_offset": HEAP_START,
        "section_bytes": HEAP_SIZE,
        "replacement_interval": [RESOURCE_START, RESOURCE_END],
        "wrapper_bytes": WRAPPER.size,
        "replacement_bitcode_bytes": len(raw),
        "padding_bytes": RESOURCE_SIZE - WRAPPER.size - len(raw),
        "changed_bytes_in_interval": sum(a != b for a, b in zip(resource, wrapped)),
        "changed_bytes_outside_interval": 0,
    }


def rewrite(source, image, resource, raw, wrapped, candidate):
    if os.path.lexists(candidate):
        raise FileExistsError(f"output already exists: {candidate}")

    candidate.parent.mkdir(parents=True, exist_ok=True)
    descriptor, name = tempfile.mkstemp(prefix=f".{candidate.name}.", dir=candidate.parent)
    temporary = Path(name)
    try:
        with os.fdopen(descriptor, "wb") as file:
            shutil.copyfileobj(source, file, CHUNK_SIZE)
            file.seek(RESOURCE_START)
            file.write(wrapped)
            os.fchmod(file.fileno(), os.fstat(source.fileno()).st_mode & 0o777)
        certificate = verify(image, resource, raw, wrapped, temporary)
        os.link(temporary, candidate)
        return certificate
    finally:
        temporary.unlink()


def main():
    parser = argparse.ArgumentParser(
        description=__doc__,
        epilog="The certificate covers the ELF bytes and LLVM bitcode wrapper. "
               "Guest behavior is tested with the SQLite shell contract.",
    )
    commands = parser.add_subparsers(dest="command", required=True)
    for command, help_text in (
        ("rewrite", "write a separate resource-replaced ELF"),
        ("verify", "check an existing resource-replaced ELF"),
    ):
        arguments = commands.add_parser(command, help=help_text)
        arguments.add_argument("original_elf", type=Path)
        arguments.add_argument("raw_bitcode", type=Path)
        arguments.add_argument("candidate_elf", type=Path)
    args = parser.parse_args()

    try:
        raw = read_replacement(args.raw_bitcode)
        wrapped = wrap(raw)
        with args.original_elf.open("rb") as source, \
                mmap.mmap(source.fileno(), 0, access=mmap.ACCESS_READ) as image:
            resource = original_resource(image)
            if args.command == "rewrite":
                certificate = rewrite(source, image, resource, raw, wrapped, args.candidate_elf)
            else:
                certificate = verify(image, resource, raw, wrapped, args.candidate_elf)
        print(json.dumps(certificate, indent=2))
    except (OSError, ValueError) as error:
        print(f"patch-aot-resource: {error}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
