#!/usr/bin/env python3
"""Extract defined class names from an explicitly supplied local DEX file.

Host-only, standard-library publication subset derived from the original
2026-09-26 scanner's dex_classes(data): class_defs -> type_ids -> string_ids,
then Lpackage/Class; -> package.Class. This release adds bounded parsing and
strict Modified UTF-8 decoding; it is not the historical scanner itself.
The retained historical independent comparison matched 80,225 defined classes
for one exact APK. That comparison did NOT execute this publication release.

Supports standard little-endian DEX 035, 037, 038, 039, 040 (112-byte header).
Rejects Compact DEX, other versions (including 041 containers), reverse endian,
and malformed accesses needed for extraction. This is NOT full DEX validation:
checksums, signatures, map consistency, bytecode, and SDK behavior are not
verified. Unused strings and unrelated sections are not decoded or verified.
Specification: https://source.android.com/docs/core/runtime/dex-format
Usage: python3 dex_classes.py classes.dex
No import-time I/O, device access, archive handling, or network access.
"""

import argparse
import json
import struct
import sys


class DexError(ValueError):
    """Unsupported DEX format or invalid extraction input."""


VERSIONS = (b"035", b"037", b"038", b"039", b"040")


def _uleb128(data, offset, end):
    value = 0
    for shift in range(0, 35, 7):
        if offset >= end:
            raise DexError("Truncated ULEB128 string length")
        byte = data[offset]
        offset += 1
        if shift == 28 and byte > 0x0f:
            raise DexError("ULEB128 string length exceeds 32 bits")
        value |= (byte & 0x7f) << shift
        if not byte & 0x80:
            return value, offset
    raise DexError("Unterminated ULEB128 string length")


def _string(data, offset, end):
    length, offset = _uleb128(data, offset, end)
    units = bytearray()
    count = 0
    while True:
        if offset >= end:
            raise DexError("Unterminated Modified UTF-8 string")
        first = data[offset]
        offset += 1
        if first == 0:
            break
        if first < 0x80:
            unit = first
        elif 0xc0 <= first <= 0xef:
            extra = 1 if first < 0xe0 else 2
            if offset + extra > end:
                raise DexError("Truncated Modified UTF-8 sequence")
            unit = first & (0x1f if extra == 1 else 0x0f)
            for byte in data[offset:offset + extra]:
                if byte & 0xc0 != 0x80:
                    raise DexError("Invalid Modified UTF-8 continuation")
                unit = (unit << 6) | (byte & 0x3f)
            offset += extra
            if extra == 1 and unit < 0x80 and not (first == 0xc0 and unit == 0):
                raise DexError("Overlong Modified UTF-8 sequence")
            if extra == 2 and unit < 0x800:
                raise DexError("Overlong Modified UTF-8 sequence")
        else:
            raise DexError("Invalid Modified UTF-8 leading byte")
        count += 1
        if count > length:
            raise DexError("String exceeds declared UTF-16 length")
        units.extend((unit & 0xff, unit >> 8))
    if count != length:
        raise DexError("String does not match declared UTF-16 length")
    try:
        return units.decode("utf-16-le", errors="strict")
    except UnicodeDecodeError as exc:
        raise DexError("Unsupported unpaired UTF-16 surrogate in string") from exc


def dex_classes(data):
    """Return normalized defined names, in class_defs order, or raise DexError.

    Only defined class descriptors are decoded. Proper surrogate pairs become
    supplementary Unicode characters; unpaired surrogates are rejected rather
    than replaced. No claim of whole-file validity accompanies the result.
    """
    if data.startswith(b"cdex"):
        raise DexError("Compact DEX is unsupported")
    if len(data) < 112:
        raise DexError("Truncated standard DEX header")
    if data[:4] != b"dex\n" or data[7] != 0:
        raise DexError("Not a standard DEX file")
    if data[4:7] not in VERSIONS:
        raise DexError("Unsupported DEX version; supported: 035, 037, 038, 039, 040")
    file_size, header_size, endian = struct.unpack_from("<3I", data, 32)
    if endian != 0x12345678:
        raise DexError("Unsupported endianness; little-endian DEX is required")
    if header_size != 112:
        raise DexError("Expected a 112-byte DEX header")
    if file_size != len(data):
        raise DexError("DEX file_size does not match supplied bytes")

    def table(count, offset, width, label):
        if count == 0:
            if offset != 0:
                raise DexError("Nonzero offset for empty " + label)
        elif offset < 112 or offset % 4 or offset + count * width > file_size:
            raise DexError("Invalid " + label + " bounds or alignment")

    string_count, string_off, type_count, type_off = struct.unpack_from("<4I", data, 56)
    class_count, class_off, data_size, data_off = struct.unpack_from("<4I", data, 96)
    table(string_count, string_off, 4, "string_ids")
    table(type_count, type_off, 4, "type_ids")
    table(class_count, class_off, 32, "class_defs")
    table(data_size, data_off, 1, "data section")
    data_end = data_off + data_size
    strings = {}
    classes = []
    for index in range(class_count):
        class_idx = struct.unpack_from("<I", data, class_off + index * 32)[0]
        if class_idx >= type_count:
            raise DexError("Class type index is out of range")
        string_idx = struct.unpack_from("<I", data, type_off + class_idx * 4)[0]
        if string_idx >= string_count:
            raise DexError("Type string index is out of range")
        if string_idx not in strings:
            start = struct.unpack_from("<I", data, string_off + string_idx * 4)[0]
            if not data_off <= start < data_end:
                raise DexError("String offset is outside the data section")
            descriptor = _string(data, start, data_end)
            if not (descriptor.startswith("L") and descriptor.endswith(";") and
                    all(descriptor[1:-1].split("/")) and
                    not any(char in descriptor[1:-1] for char in ".;[\x00")):
                raise DexError("Defined class requires a nonempty Lpackage/Class; descriptor")
            strings[string_idx] = descriptor[1:-1].replace("/", ".")
        classes.append(strings[string_idx])
    return classes


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("dex_file", help="Explicit local standard DEX file (not an APK)")
    args = parser.parse_args(argv)
    try:
        with open(args.dex_file, "rb") as source:
            names = dex_classes(source.read())
    except OSError:
        print("dex_classes: unable to read supplied local DEX file", file=sys.stderr)
        return 1
    except DexError as exc:
        print("dex_classes: " + str(exc), file=sys.stderr)
        return 1
    print(json.dumps({"defined_classes": names}, ensure_ascii=True))
    return 0


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