#!/usr/bin/env python3
"""Recover the AOT allocation bounds of the pinned GraalVM SQLite ELF."""

import argparse
import hashlib
import json
import mmap
import struct
import sys
from pathlib import Path


KNOWN_SHA256 = {
    "da6b5711711c3eb64ee01380c0d83127b31d818e36d5afc90f259761a2158e5f",
    "8d6f5e6d0b71a16d934940682f69703355fb84ee377ad66b84c8a0a86e4c65f5",
}
INDEX_GRANULARITY = 256
R_X86_64_RELATIVE = 8
ARRAY_HUB_WIDTH = 4
ARRAY_LENGTH_OFFSET = 12
ARRAY_DATA_OFFSET = 16
FRAME_SIZE_METHOD_START = 1
ENTRY_FIELD_WIDTHS = ((0, 1, 2, 4), (0, 1, 2, 4), (0, 0, 2, 4), (0, 4, 4, 4))


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


def section_headers(data):
    require(data[:7] == b"\x7fELF\x02\x01\x01", "expected a little-endian ELF64 file")
    require(struct.unpack_from("<HH", data, 16) == (3, 62), "expected an x86-64 PIE ELF")
    table = struct.unpack_from("<Q", data, 40)[0]
    entry_size, count, string_index = struct.unpack_from("<HHH", data, 58)
    require(entry_size == 64, "unexpected ELF section-header width")
    headers = [struct.unpack_from("<IIQQQQIIQQ", data, table + i * entry_size) for i in range(count)]
    string_offset = headers[string_index][4]
    result = {}
    for header in headers:
        start = string_offset + header[0]
        end = data.find(b"\0", start)
        result[data[start:end].decode("ascii")] = header
    return result


def file_offset(section, address, size):
    relative = address - section[3]
    require(0 <= relative and relative + size <= section[5], "address span lies outside ELF section")
    return section[4] + relative


def code_section_symbol(data, sections):
    symbols = sections[".dynsym"]
    strings = sections[".dynstr"][4]
    require(symbols[9] == 24, "unexpected ELF dynamic symbol width")
    for offset in range(symbols[4], symbols[4] + symbols[5], symbols[9]):
        name, _, _, _, address, _ = struct.unpack_from("<IBBHQQ", data, offset)
        name_offset = strings + name
        if data[name_offset:data.find(b"\0", name_offset)] == b"__svm_code_section":
            return address
    raise ValueError("missing __svm_code_section symbol")


def code_info_header(data, sections, code_start):
    heap, relocations = sections[".svm_heap"], sections[".rela.dyn"]
    require(relocations[9] == 24, "unexpected ELF relocation width")
    matches = []
    for offset in range(relocations[4], relocations[4] + relocations[5], relocations[9]):
        address, info, addend = struct.unpack_from("<QQq", data, offset)
        if info != R_X86_64_RELATIVE or addend != code_start:
            continue
        obj = address - 8
        if not heap[3] <= obj <= heap[3] + heap[5] - 0x48:
            continue
        pointer, size, data_offset, data_size, memory_size = struct.unpack_from(
            "<5Q", data, file_offset(heap, obj + 8, 40)
        )
        if pointer == code_start and size > 0 and data_offset == size and data_size == 0 and memory_size == size:
            matches.append((obj, size))
    require(len(matches) == 1, "expected one compiler-installed ImageCodeInfo object")
    return matches[0]


def java_array_pair(data, heap, code_info, code_size):
    checkpoint_count = (code_size + INDEX_GRANULARITY - 1) // INDEX_GRANULARITY
    index_size = 4 * checkpoint_count
    index_ref, encodings_ref = struct.unpack_from("<2Q", data, file_offset(heap, code_info + 0x38, 16))
    heap_offset, heap_size = heap[4], heap[5]
    heap_limit = heap_offset + heap_size
    length_bytes = struct.pack("<I", index_size)
    candidates = []
    position = heap_offset
    while (position := data.find(length_bytes, position, heap_limit)) != -1:
        index = position - ARRAY_LENGTH_OFFSET
        position += 1
        encoding = index - index_ref + encodings_ref
        if index % 8 or not heap_offset <= index <= heap_limit - ARRAY_DATA_OFFSET:
            continue
        if not heap_offset <= encoding <= heap_limit - ARRAY_DATA_OFFSET:
            continue
        if data[index:index + ARRAY_HUB_WIDTH] != data[encoding:encoding + ARRAY_HUB_WIDTH]:
            continue
        encoding_length = struct.unpack_from("<I", data, encoding + ARRAY_LENGTH_OFFSET)[0]
        index_payload, encoding_payload = index + ARRAY_DATA_OFFSET, encoding + ARRAY_DATA_OFFSET
        if index_payload + index_size > heap_limit or encoding_payload + encoding_length > heap_limit:
            continue
        first, second = struct.unpack_from("<2I", data, index_payload)
        if first == 0 and 0 < second < encoding_length:
            candidates.append((index_payload, encoding_payload, encoding_length, checkpoint_count))
    require(len(candidates) == 1, "expected one matching CodeInfo index/encoding array pair")
    return candidates[0]


def decode_starts(data, index, encodings, encoding_size, checkpoints, code_start, code_size):
    starts = []
    ip = entry = checkpoint = records = 0
    while True:
        require(entry + 2 <= encoding_size and ip < code_size, "CodeInfo entry exceeds its allocation")
        flags, delta = struct.unpack_from("<2B", data, encodings + entry)
        width = sum(widths[(flags >> (field * 2)) & 3] for field, widths in enumerate(ENTRY_FIELD_WIDTHS))
        require(entry + 2 + width <= encoding_size, "truncated CodeInfo fields")
        if ip % INDEX_GRANULARITY == 0:
            require(ip == checkpoint * INDEX_GRANULARITY and checkpoint < checkpoints, "unexpected CodeInfo index IP")
            recorded_entry = struct.unpack_from("<I", data, index + checkpoint * 4)[0]
            require(recorded_entry == entry, "CodeInfo index disagrees with linear decoding")
            checkpoint += 1
        if flags & 3 and data[encodings + entry + 2] & FRAME_SIZE_METHOD_START:
            require(ip % 16 == 0, "unexpected Native Image method alignment")
            starts.append(code_start + ip)
        entry += 2 + width
        records += 1
        if not delta:
            break
        ip += delta
    require(entry == encoding_size, "CodeInfo table ends at an unexpected encoded offset")
    require(checkpoint == checkpoints, "CodeInfo index is incomplete")
    require(len(starts) == 57_444 and starts[0] == code_start, "unexpected pinned AOT method count or first method")
    return starts, records


def read_map(data):
    original_sha256 = hashlib.sha256(data).hexdigest()
    require(original_sha256 in KNOWN_SHA256, "input is outside the pinned GraalVM SQLite ELF variants")
    sections = section_headers(data)
    code_start = code_section_symbol(data, sections)
    code_info, code_size = code_info_header(data, sections, code_start)
    file_offset(sections[".text"], code_start, code_size)
    index, encoding, encoding_size, checkpoints = java_array_pair(data, sections[".svm_heap"], code_info, code_size)
    starts, records = decode_starts(data, index, encoding, encoding_size, checkpoints, code_start, code_size)
    code_end = code_start + code_size
    return {
        "original_sha256": original_sha256,
        "provenance": {
            "source": "GraalVM Native Image ImageCodeInfo and code-info byte arrays",
            "range_semantics": "method allocations through the next start, including alignment padding",
            "code_start": code_start,
            "code_end": code_end,
            "image_code_info_address": code_info,
            "index_payload_file_offset": index,
            "encoding_payload_file_offset": encoding,
            "encoding_size": encoding_size,
            "verified_index_checkpoints": checkpoints,
            "code_info_records": records,
        },
        "functions": [{"start": start, "end": end} for start, end in zip(starts, starts[1:] + [code_end])],
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input_elf", type=Path)
    parser.add_argument("output_json", nargs="?", type=Path)
    args = parser.parse_args()
    try:
        with args.input_elf.open("rb") as binary, mmap.mmap(binary.fileno(), 0, access=mmap.ACCESS_READ) as data:
            result = read_map(data)
        output = json.dumps(result, separators=(",", ":")) + "\n"
        if args.output_json is None:
            sys.stdout.write(output)
        else:
            args.output_json.write_text(output, encoding="utf-8")
    except (OSError, ValueError, KeyError, IndexError, struct.error) as error:
        parser.exit(1, f"{error}\n")


if __name__ == "__main__":
    main()
