axml

    Checked Android binary XML decoding, XML rendering and manifest metadata in pure MoonBit

    android
    axml
    binary-xml
    parser
    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    1 hour ago
    Downloads
    2

    No dependencies

    #MoonBit AXML

    A pure MoonBit decoder for Android binary XML: checked byte parsing, typed events, XML reconstruction, and manifest metadata. The offline CLI reads extracted AXML files. The package namespace is LING71671/axml.

    The source is available under Apache-2.0. The research and duplicate search are recorded in docs/RESEARCH.md.

    #Browser workbench

    Use the pinned MoonBit toolchain below, Node.js 22.18+, and pnpm 11.14.0:

    cd playground pnpm install --frozen-lockfile pnpm dev

    Open the local URL printed by Vite. Choose an owned sample, select a local extracted AXML file, or drop one onto the page. A module Worker runs the actual compiled MoonBit decoder; selected file bytes are not uploaded. The page fetches its own static assets and sample files. XML, manifest/intent declarations, structure statistics, and typed references share one analysis result. A new selection or Cancel terminates the previous task.

    Input is capped at 16 MiB, with a 10-second analysis watchdog. Browser XML generation allows 2,097,152 UTF-16 units; the screen previews the first 100,000, while copying/downloading uses the full successful XML result. Events retain the first 1,000 summaries; event/reference tables show 50 rows per page. Permissions, components, and intent filters each preview 50 entries, with totals and full JSON available through Copy/Download. These browser limits are separate from the library defaults below.

    The checkout also provides a Pretty XML toggle. Compact output is the default; formatted output adds two-space indentation between element-only children and preserves text-bearing subtrees. Copy/Download use the selected format. Both formats are generated in the Worker from one decoded document, with independent 2,097,152-unit budgets; a pretty-output failure leaves compact output available. The selection lasts for the current page session.

    Structure and References support local, case-insensitive literal filtering by name/origin, kind, namespace URI, ID, or byte offset; surrounding spaces are ignored. Queries survive view/language switches and reset for new input. Structure searches only its 1,000-event preview. Copy/Download ignore filters; Structure JSON still contains only that bounded preview. See the filter guide for fields and examples.

    Six Apache-2.0 owned fixtures cover basic/Unicode/reference manifests, menu XML, a UTF-16 string pool, and a deliberately truncated header. Provenance and hashes remain in the fixture manifest. The workbench does not extract APKs or resolve ARSC resources.

    From playground/, pnpm test runs 20 Node tests, pnpm build type-checks and builds a static bundle, and pnpm preview serves that bundle locally. Preparation rebuilds the MoonBit ESM and verifies copied sample hashes; no Mooncakes account is required. Relative asset paths support repository subpaths such as GitHub Pages. The Pages workflow tests/builds on main pushes or manual runs, then publishes only playground/dist. Deployment target: LING71671 AXML workbench. Deployed and browser-verified on 2026-11-02: samples, local Unicode input, reference source selection, and XML download. See the demo guide and browser bridge schema.

    #Run the CLI

    Install the MoonBit toolchain and use 1.0.0-rc1+3c0520448 (moon 0.1.20261126), the version pinned in CI. Check the installed compiler with moon version --all. The JavaScript CLI requires Node.js 22+; the native CLI requires a supported native compiler. Clone the repository and run a sample:

    git clone https://github.com/LING71671/moonbit-axml.git cd moonbit-axml moon run src/cmd/axml --target js -- inspect --json fixtures/valid/manifest_basic.axml

    The sample reports package org.example.axml.basic and its declared SDKs, permissions, and components. Other commands from the same checkout:

    moon run src/cmd/axml --target js -- decode fixtures/valid/manifest_unicode.axml moon run src/cmd/axml --target js -- decode --pretty fixtures/valid/manifest_basic.axml moon run src/cmd/axml --target js -- intents --json fixtures/valid/manifest_basic.axml moon run src/cmd/axml --target js -- validate fixtures/valid/menu.axml moon run src/cmd/axml --target js -- validate --json fixtures/valid/menu.axml moon run src/cmd/axml --target js -- stats --json fixtures/valid/menu.axml moon run src/cmd/axml --target js -- refs --json fixtures/valid/menu.axml

    The native equivalent uses src/cmd/axml-native --target native:

    moon run src/cmd/axml-native --target native -- inspect --json fixtures/valid/manifest_basic.axml

    For an APK, first extract its AndroidManifest.xml ZIP entry. Input is read locally with a 16 MiB limit. decode writes namespace-aware XML, inspect writes JSON, and validate checks binary structure and XML renderability. Exit codes are 0 for success, 1 for input/I/O errors, and 2 for invalid arguments. In text mode, diagnostics go to stderr and include a byte offset for errors in the binary XML.

    validate --json writes {"valid":true} to stdout on success. On exit code 1, stdout contains {"valid":false,"error":{"offset":0,"message":"…"}}, with the zero-based byte offset for a decoding or rendering error, or null for a file read error. Invalid arguments still produce a usage diagnostic on stderr.

    decode --pretty adds two-space indentation between element-only children. Text-bearing and xml:space="preserve" subtrees stay compact. This opt-in output adds whitespace text nodes; use ordinary decode for the original text sequence.

    stats reports pool sizes, event/attribute counts, and nesting. refs lists typed resource/theme references with their original locations; it does not resolve resource IDs. Both commands write JSON and accept optional --json.

    Use --version for the package version and decode --help (or the other subcommands) for usage. A -- terminator makes the next argument a literal file, for example axml decode -- --help reads a file named --help.

    intents exports declared intent filters as JSON, retaining component names, typed action/category/data attributes, and source locations. A manifest without supported filters returns []; non-manifest XML reports an error. See intent-filter export.

    #Library API

    Add version 0.1.0 from Mooncakes in your MoonBit project:

    moon add LING71671/axml@0.1.0

    Import LING71671/axml in your moon.pkg and pass the extracted AXML bytes to @axml.decode:

    let document = @axml.decode(input)
    let xml = @axml.to_xml(document)
    let manifest = @axml.inspect_manifest(document)

    These operations raise DecodeError::Invalid(offset, message). Document exposes string/resource pools and ordered namespace, element, and text events with input offsets and line numbers. Each attribute retains its namespace URI, name, optional resource ID, optional raw string, and TypedValue containing the Android type code, original 32-bit payload, and decoded string when applicable.

    Manifest inspection exposes package, version/versionCodeMajor, declared SDKs, permissions, application attributes, and activity/alias/service/receiver/provider records. Optional JSON fields are omitted when absent. Resource references remain numeric IDs; component names and Android defaults are not inferred by inspection.

    Additional APIs are documented separately:

    APIUse
    XML renderingChoose compact to_xml or bounded to_xml_pretty, preserving mixed-text subtrees
    Document queries and statisticsSelect expanded names and summarize stored pools, events, and depth
    Typed value views and dimensions/fractionsRead typed payloads and encoded units without coercion or display metrics
    Manifest helpers and intent filtersInspect component, permission, action/category, and data declarations without platform defaults
    Resource referencesRetain every reference kind, ID, location, and attribute/text origin
    Batch catalogImport LING71671/axml/catalog to process named byte inputs with independent results and diagnostics

    #Build and verify

    moon fmt --check moon check --target all --deny-warn moon test --target wasm-gc --deny-warn moon test --target js --deny-warn moon test --target native --deny-warn python scripts/verify_cli.py

    The verifier uses Python's standard library. Regenerating fixtures additionally requires pinned aapt2 and androguard; see fixture instructions. Local verification on 2026-11-28 covers 134 tests on wasm-gc, 137 on JavaScript (including the browser bridge), and 134 on Windows native, plus 19 fixtures, 7 independent XML trees checked in compact and pretty forms, 3 manifest and intent-filter records, menu statistics and typed reference locations, and 12 malformed-input cases through Node and native CLIs. Both hosts also check JSON validation for malformed input, rendering failures, and file read errors. Reference outputs come from aapt2/androguard, independently of this parser. Per-commit GitHub Actions results on Linux and Windows are recorded in the acceptance matrix.

    The bounded stress benchmarks cover 100,000 strings, depth 256, repeated string references, and a late malformed index. The recorded Windows snapshot checks output hashes, timings, and process peak memory; it is not a portable performance guarantee. Run python scripts/benchmark.py after building both CLI targets to write a fresh report under _build/benchmarks/.

    #Bounds and supported scope

    LimitDefault
    Input16 MiB
    String pool100,000 entries; 4,194,304 aggregate UTF-16 units
    Nesting256 elements
    Events / attributes500,000 events; 65,535 attributes per element
    Rendered output33,554,432 UTF-16 units

    decode(input, limits=...) and to_xml(document, max_output_chars=...) allow explicit budgets. UTF-8/UTF-16 strings, resource maps, namespace scopes, typed attributes, and CDATA are supported. Style spans are validated but their styling is discarded in XML output. Unknown chunks and malformed encodings/scopes are rejected. Resource-table resolution, AXML writing, APK signing, DEX decoding, repair of obfuscated manifests, and APK archive I/O are outside this version. The core has no Android/JVM dependency; CLI host adapters provide only file I/O.

    #Ownership and license

    The public GitHub repository is LING71671/moonbit-axml. For account-sensitive operations on the configured Windows workstation, use scripts/moon.ps1 and scripts/github.ps1; they select LING71671 without changing shared login state. See account isolation.

    Apache-2.0. Authored fixture sources, tool versions, hashes, and external reference licenses are documented in THIRD_PARTY.md.

    DecodeError

    pub suberror DecodeError {
    Invalid(Int, String)
    } derive(
    Debug
    ,
    ToJson
    )

    A structural or encoding failure, with its original byte offset.

    Attribute

    pub(all) struct Attribute {
    namespace_uri : String?
    name : String
    resource_id : UInt?
    raw_value : String?
    value : TypedValue
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    An attribute retains its expanded name, original string and typed value.

    Dimension

    pub(all) struct Dimension {
    magnitude : Double
    unit : DimensionUnit
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    DimensionUnit

    pub(all) enum DimensionUnit {
    Px
    Dip
    Sp
    Pt
    Inch
    Mm
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Encoded dimension units, without applying display or font metrics.

    Document

    pub(all) struct Document {
    strings : Array[String]
    resource_ids : Array[UInt]
    events : Array[Event]
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Decoded pools and events. Unresolved resources remain numeric IDs.

    Document::elements

    fn Document::elements(self : Document, namespace_uri : String?, name : String) -> Array[Event]

    Select start elements by their exact expanded name in document order. Returned events share their existing attribute arrays with the document.

    Document::resource_references

    fn Document::resource_references(self : Document) -> Array[ResourceUsage]

    Collect typed attribute and text references in event/attribute order. This does not interpret raw strings, resolve ARSC, or validate a manually constructed document. Attribute-name resource IDs are not value usages.

    Document::root

    fn Document::root(self : Document) -> Event?

    Return the first start-element event, or None if there is no element. This query does not validate a manually constructed event stream.

    Document::stats

    fn Document::stats(self : Document) -> DocumentStats

    Summarize stored entries in O(strings + events) time and constant space. Repeated pool entries and attribute occurrences are counted separately. This is not validation: manual streams need not be balanced or name-correct. An unmatched end at depth zero is ignored; open starts still affect depth.

    DocumentStats

    pub(all) struct DocumentStats {
    strings : Int
    string_utf16_units : Int64
    resource_ids : Int
    events : Int
    start_elements : Int
    attributes : Int64
    text_events : Int
    namespace_declarations : Int
    max_depth : Int
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Counts from the stored pools and event stream, without rendering or I/O. Aggregate UTF-16 units and attributes use Int64 for shared manual inputs.

    Event

    pub(all) struct Event {
    offset : Int
    line_number : UInt
    kind : EventKind
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Each event identifies its original chunk offset and source line number.

    Event::attribute

    fn Event::attribute(self : Event, namespace_uri : String?, name : String) -> Attribute?

    Find a start-element attribute by expanded name. An empty namespace URI means no namespace. Namespace prefix spellings are not part of the lookup.

    EventKind

    pub(all) enum EventKind {
    StartNamespace(String?, String)
    EndNamespace(String?, String)
    StartElement(String?, String, Array[Attribute])
    EndElement(String?, String)
    Text(String, TypedValue)
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Namespace-aware XML events in input order.

    Fraction

    pub(all) struct Fraction {
    ratio : Double
    unit : FractionUnit
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Ratio is the encoded number, so 50% has ratio 0.5.

    FractionUnit

    pub(all) enum FractionUnit {
    Base
    Parent
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Limits

    pub(all) struct Limits {
    max_input_bytes : Int
    max_strings : Int
    max_depth : Int
    max_events : Int
    max_attributes : Int
    max_string_units : Int
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Resource limits checked before allocation or event expansion. max_string_units caps aggregate decoded UTF-16 units across the pool.

    Limits::default

    fn Limits::default() -> Limits

    Conservative defaults for untrusted, extracted binary XML files.

    Manifest

    pub(all) struct Manifest {
    package_name : String
    version_code : Attribute?
    version_code_major : Attribute?
    version_name : Attribute?
    sdk : ManifestSdk?
    permissions : Array[ManifestPermission]
    application : ManifestApplication?
    components : Array[ManifestComponent]
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Manifest metadata preserves raw and typed values through Attribute.

    Manifest::components_of_kind

    fn Manifest::components_of_kind(self : Manifest, kind : String) -> Array[ManifestComponent]

    Select directly declared components by their exact element kind, preserving declaration order. For example, activity does not also select activity-alias.

    Manifest::requests_permission

    fn Manifest::requests_permission(self : Manifest, name : String) -> Bool

    Test whether a uses-permission variant requests this literal name. Resource references do not match, even if their raw text resembles a name. This does not evaluate maxSdkVersion or determine runtime permission grants.

    ManifestApplication

    pub(all) struct ManifestApplication {
    name : Attribute?
    label : Attribute?
    debuggable : Attribute?
    enabled : Attribute?
    attributes : Array[Attribute]
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Declared application attributes. Absent fields remain absent.

    ManifestComponent

    pub(all) struct ManifestComponent {
    kind : String
    name : Attribute?
    exported : Attribute?
    enabled : Attribute?
    authorities : Attribute?
    permission : Attribute?
    attributes : Array[Attribute]
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    An activity, alias, service, receiver or provider declared directly in application. Names and exported/enabled state are not expanded or inferred.

    ManifestComponent::qualified_name

    fn ManifestComponent::qualified_name(self : ManifestComponent, package_name : String) -> String? raise DecodeError

    Expand a literal android:name without changing this component's metadata. Missing, non-string and unresolved resource names return None. Empty literal names raise DecodeError. The package is supplied explicitly by the caller.

    ManifestIntentFilter

    pub(all) struct ManifestIntentFilter {
    component_kind : String
    component_name : Attribute?
    offset : Int
    line_number : UInt
    attributes : Array[Attribute]
    actions : Array[Attribute]
    categories : Array[Attribute]
    data : Array[Array[Attribute]]
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    A directly declared intent filter. All attributes retain raw and typed values, and no component defaults or intent matching rules are inferred.

    ManifestIntentFilter::has_action

    fn ManifestIntentFilter::has_action(self : ManifestIntentFilter, name : String) -> Bool

    Match an exact literal android:name declaration. References do not match.

    ManifestIntentFilter::has_category

    fn ManifestIntentFilter::has_category(self : ManifestIntentFilter, name : String) -> Bool

    Match an exact literal android:name declaration. References do not match.

    ManifestPermission

    pub(all) struct ManifestPermission {
    kind : String
    name : Attribute?
    max_sdk : Attribute?
    attributes : Array[Attribute]
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    A uses-permission declaration, retaining all original attributes.

    ManifestSdk

    pub(all) struct ManifestSdk {
    min_sdk : Attribute?
    target_sdk : Attribute?
    max_sdk : Attribute?
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    A declared SDK requirement. Values may be integer levels, codenames or unresolved resources; no platform defaults are inferred.

    ResourceUsage

    pub(all) struct ResourceUsage {
    offset : Int
    line_number : UInt
    origin : ResourceUsageOrigin
    reference : ValueReference
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    One unresolved typed reference, preserving its kind, ID and source location. Repeated references remain separate records in document order.

    ResourceUsageOrigin

    pub(all) enum ResourceUsageOrigin {
    Attribute(String?, String)
    Text
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    The attribute or text origin of a typed resource or theme reference. Attribute names retain their original namespace URI and local name.

    TypedValue

    pub(all) struct TypedValue {
    data_type : Int
    data : UInt
    string_value : String?
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Android's Res_value, preserving the exact type code and 32-bit payload. String values additionally contain the decoded string-pool entry.

    TypedValue::as_boolean

    fn TypedValue::as_boolean(self : TypedValue) -> Bool?

    Android booleans use zero for false and any nonzero payload for true.

    TypedValue::as_dimension

    fn TypedValue::as_dimension(self : TypedValue) -> Dimension?

    Read TYPE_DIMENSION. Wrong types and unknown unit codes return None.

    TypedValue::as_float

    fn TypedValue::as_float(self : TypedValue) -> Float?

    Interpret the original IEEE-754 payload without coercing other types. Non-finite values are retained here; XML rendering rejects them.

    TypedValue::as_fraction

    fn TypedValue::as_fraction(self : TypedValue) -> Fraction?

    Read TYPE_FRACTION without choosing base or parent dimensions.

    TypedValue::as_integer

    fn TypedValue::as_integer(self : TypedValue) -> Int?

    Read decimal/hex integer payloads as signed 32-bit Android integers. Booleans, colors and resource IDs retain their own distinct types.

    TypedValue::as_string

    fn TypedValue::as_string(self : TypedValue) -> String?

    Read a string only when its Android type is TYPE_STRING.

    TypedValue::reference

    fn TypedValue::reference(self : TypedValue) -> ValueReference?

    Inspect a resource/theme reference while preserving dynamic-reference kinds.

    TypedValue::text

    fn TypedValue::text(self : TypedValue) -> String raise DecodeError

    Format an Android value without resolving resources or attribute enums.

    ValueReference

    pub(all) enum ValueReference {
    Resource(UInt)
    ThemeAttribute(UInt)
    DynamicResource(UInt)
    DynamicThemeAttribute(UInt)
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    An unresolved reference distinguishes resources from theme attributes and dynamic package IDs. Numeric IDs are retained without resource-table lookup.

    decode

    fn decode(data : Bytes, limits? : Limits) -> Document raise DecodeError

    Decode one complete Android binary XML document with bounded allocation. Unknown chunks, broken Unicode, invalid references and unbalanced scopes fail with their original byte offset. The input must be extracted XML, not an APK.

    inspect_intent_filters

    fn inspect_intent_filters(document : Document) -> Array[ManifestIntentFilter] raise DecodeError

    Inspect direct intent-filter children of unqualified activity, activity-alias, service and receiver declarations under manifest/application. Missing action and category names are omitted; data declarations retain all attributes.

    inspect_manifest

    fn inspect_manifest(document : Document) -> Manifest raise DecodeError

    Read declarations from an AndroidManifest event stream. The root package must be a literal string. Android defaults and resource resolution require external context and are deliberately not guessed.

    resolve_component_name

    fn resolve_component_name(package_name : String, declared_name : String) -> String raise DecodeError

    Expand a declared component name relative to an explicit package name. Leading-dot and bare names are prefixed; names containing a dot are kept. This is syntactic expansion, not Java class validation or resource lookup. Empty inputs raise Invalid(-1, message), since no byte offset is available.

    to_xml

    fn to_xml(document : Document, max_output_chars? : Int) -> String raise DecodeError

    Render a namespace-aware document as XML 1.0. The output limit also bounds repeated references to long string-pool entries; it counts UTF-16 units.

    to_xml_pretty

    fn to_xml_pretty(document : Document, max_output_chars? : Int, max_depth? : Int) -> String raise DecodeError

    Render XML with two-space indentation and LF line endings between elements. Subtrees containing direct text, including whitespace/empty CDATA events, and xml:space="preserve" subtrees retain compact rendering throughout. Added indentation counts toward the UTF-16 output budget. Depth is checked before formatting even for manually constructed documents.