diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..8d8d301 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,62 @@ +name: Release +on: + push: + tags: ['v*'] +permissions: + contents: read +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false +jobs: + prepare: + runs-on: ubuntu-latest + outputs: + baseline: ${{ steps.version.outputs.baseline }} + steps: + - uses: actions/checkout@v7.0.1 + with: + fetch-depth: 0 + - name: Validate version and development ancestry + id: version + env: + TAG: ${{ github.ref_name }} + run: | + python scripts/build_release.py "$TAG" --output dist + git merge-base --is-ancestor HEAD origin/dev-0.1.0 + echo "baseline=$(git rev-parse HEAD^)" >> "$GITHUB_OUTPUT" + checks: + needs: prepare + uses: ./.github/workflows/tests.yml + with: + baseline_sha: ${{ needs.prepare.outputs.baseline }} + publish: + needs: checks + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v7.0.1 + - uses: actions/setup-python@v7.0.0 + with: + python-version: '3.12' + - name: Build release assets + env: + TAG: ${{ github.ref_name }} + run: python scripts/build_release.py "$TAG" --output dist + - name: Publish validated source release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TAG: ${{ github.ref_name }} + run: | + if gh release view "$TAG" --json isDraft > release.json; then + python -c 'import json; assert json.load(open("release.json"))["isDraft"], "Refusing to overwrite published release"' + else + gh release create "$TAG" --verify-tag --draft --title "ASC $TAG" --generate-notes + fi + gh release upload "$TAG" dist/* --clobber + if [[ "$TAG" == *-* ]]; then + gh release edit "$TAG" --draft=false --prerelease + else + gh release edit "$TAG" --draft=false --prerelease=false + fi diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..7bb9e3a --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,65 @@ +name: Tests +on: + push: + branches: ['**'] + pull_request: + workflow_dispatch: + workflow_call: + inputs: + baseline_sha: + required: true + type: string +permissions: + contents: read +jobs: + regression: + runs-on: ubuntu-latest + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + python-version: ['3.11', '3.12'] + steps: + - uses: actions/checkout@v7.0.1 + - name: Checkout performance baseline + uses: actions/checkout@v7.0.1 + with: + repository: ${{ github.event.pull_request.base.repo.full_name || (github.event_name == 'push' && github.ref_name == 'dev-0.1.0' && github.repository) || 'MG1937/ASC' }} + ref: ${{ inputs.baseline_sha || github.event.pull_request.base.sha || (github.event_name == 'push' && github.ref_name == 'dev-0.1.0' && github.event.before) || 'dev-0.1.0' }} + path: .performance-base + - uses: actions/setup-python@v7.0.0 + with: + python-version: ${{ matrix.python-version }} + cache: pip + - run: python -m pip install -r requirements.txt + - run: python -m pip check + - name: Unit tests (no skips) + run: python tests/run_tests.py --require-decompiler --suite unit + - name: Integration tests (no skips) + run: python tests/run_tests.py --require-decompiler --suite integration + - name: Reject material performance regressions against the target branch + run: python tests/benchmark_compare.py --baseline .performance-base --samples 31 + - name: Check cold-process startup with --debug + run: python tests/benchmark_startup.py --samples 9 --max-total-ms 100 --max-wall-ms 250 + - name: Check supplied DEX benchmarks and 0.0880 s budget + run: python tests/benchmark_reference.py --samples 9 + - name: Upload benchmark timings and raw debug logs + if: always() + uses: actions/upload-artifact@v7.0.1 + with: + name: benchmarks-python-${{ matrix.python-version }} + path: | + artifacts/startup/ + artifacts/reference/ + artifacts/comparison/ + if-no-files-found: warn + - name: Build source release preview + if: matrix.python-version == '3.12' + run: python scripts/build_release.py v0.1.0 --output dist + - name: Upload source release preview + if: matrix.python-version == '3.12' + uses: actions/upload-artifact@v7.0.1 + with: + name: source-release-preview + path: dist/ + if-no-files-found: error diff --git a/.gitignore b/.gitignore index ed7e329..b1b1a3e 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,16 @@ testcase.txt *.zip *.jar *.jadx +*.bak temp/* + +.venv/ + +artifacts/startup/ + +!tests/fixtures/reference-workload.zip +artifacts/reference/ + +.performance-base/ +artifacts/comparison/ +dist/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 290d0b6..d2215fd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Droid ASC: R8 Compiler Optimization as a DeCompiler Primitive +https://blackhat.com/europe/arsenal/schedule/index.html#droid-asc-r8-compiler-optimization-as-a-decompiler-primitive-54834 When decompiling massive Android APKs, the standard procedure is to wait. We wait for tools to eat gigabytes of RAM, fully inflate the artifacts, and spend tens of minutes building heavy global indexes and cross references... All of this is just to guarantee fast code searches later, but here is the contradiction. A compiled artifact is already highly structured, modern decompilers never utilize this, they waste massive amounts of time and memory reconstructing a bloated database of code relationships over already structured data. This engineering approach defies common sense. When I can directly extract any code relationship from the APK in milliseconds, does this preprocessing still hold any value? @@ -9,3 +10,5 @@ We will demonstrate this architecture live against a 352MB commercial APK. Droid # Benchmark ![Benchmark](./docs/benchmark_all_en.png) +https://github.com/user-attachments/assets/4c4a6813-8561-490c-a573-ef113da861b6 + diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 0000000..686d8ae --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,35 @@ +# Source releases + +Python 3.11 or 3.12 is required. Extract `ASC-vX.Y.Z-source.zip`, enter the +extracted directory, and run: + +```sh +python -m pip install -r requirements.txt +python main.py --help +python main.py getclass app.apk com.example.Main --debug +python main.py findrefs app.apk string token +python main.py app.apk --gui +``` + +The GUI additionally needs Tk (on Debian/Ubuntu: `python3-tk`). Dependencies +are installed separately; the archive is not a standalone executable. +`SHA256SUMS` verifies the downloaded ZIP; it does not change DEX signatures. + +## Maintainers + +Merge the PR into `dev-0.1.0` first, then tag the intended commit with +`vMAJOR.MINOR.PATCH` (or `-alpha.N`, `-beta.N`, `-rc.N`) and push that tag. +The Release workflow rejects tags outside the development branch and compares +performance against the tagged commit's first parent, by immutable SHA. +All unit/integration tests, paired performance checks, and absolute budgets +must pass on Python 3.11 and 3.12 before publication. A failed gate publishes +nothing. Prerelease tags create GitHub prereleases. + +PR CI also builds the source package and tests its CLI after extraction outside +the checkout. Only tracked runtime files, requirements, README and docs enter +the deterministic ZIP; test DEX/APK fixtures and local scripts are excluded. + +Local packaging: `python scripts/build_release.py v0.1.0 --output dist`. +The workflow creates a draft, uploads the ZIP and SHA256SUMS, then publishes it. +If upload fails, only a draft remains; rerunning replaces draft assets. +Published releases are never overwritten automatically. diff --git a/docs/benchmark_all_en.png b/docs/benchmark_all_en.png index b607e9a..4e6632d 100644 Binary files a/docs/benchmark_all_en.png and b/docs/benchmark_all_en.png differ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..7acecba --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +androguard==4.1.3 diff --git a/scripts/build_release.py b/scripts/build_release.py new file mode 100644 index 0000000..e6c5bad --- /dev/null +++ b/scripts/build_release.py @@ -0,0 +1,36 @@ +"""Build a source distribution from tracked runtime files.""" +import argparse +import hashlib +from pathlib import Path +import re +import subprocess +import zipfile + +ROOT = Path(__file__).resolve().parents[1] + + +def build(version, output): + if not re.fullmatch(r'v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:alpha|beta|rc)\.[1-9]\d*)?', version): + raise ValueError('expected vMAJOR.MINOR.PATCH or vMAJOR.MINOR.PATCH-rc.N (also alpha/beta)') + paths = subprocess.check_output( + ['git', 'ls-files', '-z', '--', 'main.py', 'requirements.txt', 'README.md', 'LICENSE', 'src', 'docs'], + cwd=ROOT).decode().split('\0') + output.mkdir(parents=True, exist_ok=True) + archive = output / f'ASC-{version}-source.zip' + with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED) as package: + for path in sorted(filter(None, paths)): + info = zipfile.ZipInfo(f'ASC-{version}/{path}') + info.compress_type = zipfile.ZIP_DEFLATED + info.external_attr = 0o100644 << 16 + package.writestr(info, (ROOT / path).read_bytes()) + digest = hashlib.sha256(archive.read_bytes()).hexdigest() + (output / 'SHA256SUMS').write_text(f'{digest} {archive.name}\n', encoding='ascii') + return archive + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('version') + parser.add_argument('--output', type=Path, default=Path('dist')) + args = parser.parse_args() + print(build(args.version, args.output)) diff --git a/src/asc_client/asc_handler.py b/src/asc_client/asc_handler.py index 1d8a166..7664075 100644 --- a/src/asc_client/asc_handler.py +++ b/src/asc_client/asc_handler.py @@ -78,9 +78,11 @@ def _format_matched_name(self, dex, find_type : str, idx : int) -> str: return f"{field.cls.fullname}->{field.name}" def findrefs(self, dex_name : str, dex_buf : bytes, find_type : str, find : dict, aggregate : bool = True) -> list: - _lazy_import() - dex = _DEX.parse(memoryview(dex_buf), dex_name) - ref_manager = _FindRefManager(dex) + from src.asc_core.findrefs.findrefs_manager import FindRefManager + from src.asc_core.utils.tinydex import DEX + + dex = DEX.parse(memoryview(dex_buf), dex_name) + ref_manager = FindRefManager(dex) query = copy.deepcopy(find) matched_idxs = ref_manager.find_ref(query, True) mids = query[find_type] diff --git a/src/asc_core/core/dex/dex_builder.py b/src/asc_core/core/dex/dex_builder.py index 39e87a2..2822df8 100644 --- a/src/asc_core/core/dex/dex_builder.py +++ b/src/asc_core/core/dex/dex_builder.py @@ -266,6 +266,11 @@ def build(self): class_data_off = 0 if len(self.im.fields_obj) > 0 or len(self.im.methods_obj) > 0: class_data_off = len(self.out) + # 20260912 here is the root cause for PR ASC/pull/8, code try to make sure diff idx inside class_data_item is valid, + # so code sorted every static field and methods, if the list is ordered by idx, there is no way to have diff idx invalid issue. + # however the sort behavior cause the static_fields we collected do not match the order of current static_fields ready to writen. + # fixed by pin class's own fields before remap fields used by bytecodes + # count s_f = sorted([f for f in self.im.fields_obj if f.is_static], key=lambda f: self.im.field_restruct_idx.get(f.index, 0)) i_f = sorted([f for f in self.im.fields_obj if not f.is_static], key=lambda f: self.im.field_restruct_idx.get(f.index, 0)) diff --git a/src/asc_core/core/dex/dex_constructor.py b/src/asc_core/core/dex/dex_constructor.py index 89b53a9..3d39279 100644 --- a/src/asc_core/core/dex/dex_constructor.py +++ b/src/asc_core/core/dex/dex_constructor.py @@ -304,6 +304,9 @@ def hollow(self): if static_values_off != 0: # which may never be executed, I tried many way to compile a java file contains static fields to dex, never meet static_value_off > 0 # but LLM still generate this parse, IDK why.. 20260729 + # AOSP framework.jar android.content.Context trigged it, and lead to a very serviously bug!! 20260912 + # this bug caused all field assignments to be misaligned! + # this PR try to fix it https://github.com/MG1937/ASC/pull/8/changes/462b0c3377e33f82e8284315a2bcc35e78c42084 self.static_values_elements = parse_encoded_array(self._raw_cache, static_values_off, self.hlw_strs, self.hlw_types, self.hlw_fields, self.hlw_methods) if self.debug: t_static = time.perf_counter() diff --git a/src/asc_core/core/dex/dex_manager.py b/src/asc_core/core/dex/dex_manager.py index 91c9dc2..a77452d 100644 --- a/src/asc_core/core/dex/dex_manager.py +++ b/src/asc_core/core/dex/dex_manager.py @@ -59,6 +59,9 @@ def extract_and_rebuild(self, dalvik_class_fmt: str): dvminterp = DvmInterpreter() dvminterp.addHandler(idx_handler) + # Pin own-field declaration order before any bytecode is rewritten. + idx_handler.preregister_own_fields(clazz.fields) + modified_bytecodes = {} t_setup_end = time.perf_counter() diff --git a/src/asc_core/core/dex/dex_remapper.py b/src/asc_core/core/dex/dex_remapper.py index 3448b5d..f346dca 100644 --- a/src/asc_core/core/dex/dex_remapper.py +++ b/src/asc_core/core/dex/dex_remapper.py @@ -306,16 +306,16 @@ def handle(self): if hasattr(self, 'hollower'): # map source file src_idx = self.hollower.clz_def_hlw_strs.get(0x10) - if src_idx and src_idx != 0xffffffff: + if src_idx is not None and src_idx != 0xffffffff: src_str = self.origin_strings[src_idx] self._add_str_restruct(src_str) # map class idx clz_idx = self.hollower.clz_def_hlw_types.get(0) - if clz_idx and clz_idx != 0xffffffff: + if clz_idx is not None and clz_idx != 0xffffffff: self._append_origin_type(clz_idx) # map superclass idx super_idx = self.hollower.clz_def_hlw_types.get(0x8) - if super_idx and super_idx != 0xffffffff: + if super_idx is not None and super_idx != 0xffffffff: self._append_origin_type(super_idx) # map interfaces ifs_list = self.hollower.ifs_list_hlw_types diff --git a/src/asc_core/core/dvm_handlers.py b/src/asc_core/core/dvm_handlers.py index 5f72eab..1dc19b0 100644 --- a/src/asc_core/core/dvm_handlers.py +++ b/src/asc_core/core/dvm_handlers.py @@ -45,6 +45,31 @@ def mapIndex(self, origin_idx, idx_type): return new_idx return rev[origin_idx] + def preregister_own_fields(self, fields): + """Pin this class's own declared fields to the leading new field + indices, ordered by original field_idx ascending. + + This is the single definition of the field declaration order: it makes + bytecode operands (rewritten here), the rebuilt field table + (DexIndexMapper), the class_data declaration (DexBuilder) and the + static_values encoded_array all follow the same original-index order, + so field initializers stay aligned with their fields. + + 20260912 + bad case example: + DEX: class -> fields [1732, 1733, 1734] + + 1. class bytecodes -> sput v0, 1733 + 2. remap bytecodes -> "FIELD" : {1733 : 0} -> sput v0, 0 + 3. restruct fields -> 0 -> 1733 + 4. restruct class -> 1 -> 1732, 2 -> 1734 + 5. dex builder sorted fields we collected for valid diff idx: static field [1733, 1732, 1734] mismatch to original class fields!!! + + so we need to pin our own class's fields before bytecode remap + """ + for field_obj in fields: # valid dex's fields already sorted + self.mapIndex(field_obj.index, "FIELD") + def getMapper(self): return self.mapper diff --git a/src/asc_core/findrefs/locator/insn_locator.py b/src/asc_core/findrefs/locator/insn_locator.py index 6ca775b..fd689d3 100644 --- a/src/asc_core/findrefs/locator/insn_locator.py +++ b/src/asc_core/findrefs/locator/insn_locator.py @@ -71,7 +71,7 @@ def _encoded_method_parse(self, data : bytes, pos, midx): old = insn_maps.get(insn_bucket_start) # R8 insn deduplicate machenism, different method may refer to same insn body - if old: + if old is not None: if isinstance(old, int): midx = [midx, old] else: @@ -119,7 +119,11 @@ def _build_map_bymap(self): # dont reuse tinydex, frequent lazy parser may cause bad performance # parse all items in one shot by map! buf = self.buf + if not self.mapoff: + self._build_map_bydef() + return mapsize = _STRUCT_I.unpack_from(buf, self.mapoff)[0] + mtype = None mapoff = self.mapoff + 4 for i in range(mapsize): mtype = _STRUCT_H.unpack_from(buf, mapoff)[0] @@ -140,6 +144,7 @@ def _build_map_bydef(self): if self.parsed: return class_def_off, class_def_size = self.header.classes + buf = self.buf data = bytes(buf) for i in range(class_def_size): class_data_off = _STRUCT_I.unpack_from(buf, class_def_off + 24)[0] @@ -154,8 +159,9 @@ def parse(self): t_start = time.perf_counter() if self.debug else None self._build_map_bymap() tmp_list = self.insn_maps.keys() - self.code_item_start = min(tmp_list) << 4 - self.code_item_end = (max(tmp_list) + 1) << 4 + if tmp_list: + self.code_item_start = min(tmp_list) << 4 + self.code_item_end = (max(tmp_list) + 1) << 4 self.parsed = True self._debug_log("parse", t_start, len(self.insn_maps)) @@ -169,7 +175,7 @@ def locate(self, offsets : list) -> set: insn_maps = self.insn_maps buf = self.buf - method_bounds = self.method_bounds.copy() + method_bounds = {} for off in offsets: midx = insn_maps.get(off >> 4) """ @@ -184,10 +190,10 @@ def locate(self, offsets : list) -> set: # which means there is no possible to backtracking inside one method, so we can update method # start insn offset once we fullmatch an insn, avoid re-fullmatch from start of method # bugfix for insn mismatch issue 20260729 - if isinstance(midx, int) and InsnLocator.INSN_VERIFY.fullmatch(buf, method_bounds[midx], off): + if isinstance(midx, int) and InsnLocator.INSN_VERIFY.fullmatch(buf, method_bounds.get(midx, self.method_bounds[midx]), off): ret_table.append(midx) method_bounds[midx] = off - elif isinstance(midx, list) and InsnLocator.INSN_VERIFY.fullmatch(buf, method_bounds[midx[0]], off): + elif isinstance(midx, list) and InsnLocator.INSN_VERIFY.fullmatch(buf, method_bounds.get(midx[0], self.method_bounds[midx[0]]), off): ret_table.append(midx) method_bounds[midx[0]] = off else: diff --git a/src/asc_core/findrefs/locator/string_locator.py b/src/asc_core/findrefs/locator/string_locator.py index 20230b0..7c822cc 100644 --- a/src/asc_core/findrefs/locator/string_locator.py +++ b/src/asc_core/findrefs/locator/string_locator.py @@ -1,19 +1,33 @@ from findrefs.locator.base_locator import BaseLocator import struct +import sys +from bisect import bisect_right +from utils.leb128 import read_uleb128_len import re import time # Auth: MG1937 _STRUCT_I = struct.Struct(' 0: + idx = next_idx - 1 + item = self.string_offsets[idx] + else: + item = self.string_offsets[bisect_right(self.string_offsets, start) - 1] + idx = self.stridx_map[item] + content_start = item + (read_uleb128_len(buf, item) if buf[item] & 128 else 1) + if mm.find(b'\x00', content_start, start) != -1: + continue + if literal and start < content_start: + if mm.find(string, content_start, content_end) != -1: + yield idx + elif start >= content_start and query_end <= content_end: + yield idx def locate(self, string : str) -> set: t_start = time.perf_counter() if self.debug else None if not self.parsed: self._build_map() - stridx_map = self.stridx_map - located_idx = set() - for offset in self._match_string_offset(string): - located_idx.add(stridx_map[offset] - 1) - # return set for O(1) lookup + if not self.string_offsets: + return set() + located_idx = set(self._match_string_index(string)) self._debug_log("locate", t_start, len(located_idx)) return located_idx diff --git a/src/asc_core/utils/dex_parser.py b/src/asc_core/utils/dex_parser.py index 18b3c5e..1e1846a 100644 --- a/src/asc_core/utils/dex_parser.py +++ b/src/asc_core/utils/dex_parser.py @@ -114,7 +114,7 @@ def parse_annotation_item(data, off, hlw_strs, hlw_types, hlw_fields, hlw_method def rebuild_encoded_value(elem, im): out = bytearray() value_type = elem[0] - + if value_type in (0x17, 0x18, 0x19, 0x1A, 0x1B): idx = elem[1] new_idx = 0 diff --git a/tests/TESTING.md b/tests/TESTING.md new file mode 100644 index 0000000..80800c3 --- /dev/null +++ b/tests/TESTING.md @@ -0,0 +1,74 @@ +# Test commands + +Use Python 3.11+ and install `requirements.txt` in a virtual environment. + +```sh +python tests/run_tests.py --require-decompiler +python tests/benchmark_startup.py --samples 9 +python tests/benchmark_reference.py --samples 9 +``` + +The regression runner fails if Androguard is missing or any test is skipped in +strict mode. It covers index zero, empty/fallback instruction maps, string layout, +zeroed reconstructed DEX signatures/checksums, dummy imports, the MUTF-8 shim, +CLI stored/Deflate multidex operation, GUI data-store reuse, and reference searches +without site packages. It does not open GUI windows. + +The synthetic startup gate measures `getclass --debug` in nine fresh interpreters. +Its median budgets are 100 ms internal time and 250 ms wall time on Linux CI. + +`fixtures/reference-workload.zip` is the supplied archive, unchanged. Its SHA-256 +is recorded in `fixtures/reference-baseline.json`. The reference runner extracts +its three files into a temporary directory and executes the original `test.py` +and `test_findrefs.py` with this checkout's core on `PYTHONPATH`. + +- `test.py` must output `ClockFaceView` source. The median of nine script-reported + times must be at most **0.0880 s**. Every measurement and the maximum are retained. +- Every `test_findrefs.py` run must match all **16 count metrics** exactly and + emit all **20 timing metrics**. Median timing differences from the supplied + baseline are reported; these individual times are not hard performance budgets. +- Both benchmark commands fail on process errors, missing output, or timeouts. + +These are fresh interpreter measurements with warm filesystem caches, not cold +storage measurements or a guarantee on arbitrary hardware. CI runs both Python +3.11 and 3.12, including real-DEX checks. Reports and stdout/stderr are uploaded +from `artifacts/startup/` and `artifacts/reference/` even when a gate fails. + +## Practical-regression comparison + +```sh +python tests/run_tests.py --require-decompiler --suite unit +python tests/run_tests.py --require-decompiler --suite integration +python tests/benchmark_compare.py --baseline /path/to/base-checkout --samples 31 +``` + +CI checks out the PR's exact base SHA. Direct pushes to `dev-0.1.0` compare +against the pre-push SHA, so the candidate cannot become its own baseline. +Other push/manual builds compare against `MG1937/ASC:dev-0.1.0`. A missing +baseline fails the job. The same interpreter, +runner, DEX, original scripts and query arguments exercise both revisions. On +Linux the comparison and its child processes use one fixed available CPU; both +sides use `PYTHONHASHSEED=0`. These controls are recorded in the report. + +The comparison covers 20 module timings from `test_findrefs.py`, core decompilation +from `test.py`, and real-APK CLI `getclass` / `findrefs`: **23 metrics** in total. +Each workload records an explicit warmup pair, then 31 independent-process pairs +in alternating base/candidate order. Warmups are retained in raw logs but excluded +from statistics. Reference counts and decompiled/CLI outputs must match before +any performance result can pass. + +Every metric remains in the report, but CI gates only the 11 aggregate user-visible +paths: module-level instruction, string, code, method, field, type, method-reference +and field-reference work; core decompilation; and CLI `getclass` / `findrefs`. +Fine-grained locator sub-metrics remain diagnostic only. A gated metric fails only +when it is both statistically significant in the one-sided exact paired sign test +(5% family-wise error budget with Bonferroni correction) and its paired median +slowdown is at least **3.0%**. Balanced noise, isolated scheduling outliers, and +statistically detectable sub-3% changes are reported but do not block CI. Passing +means no material statistically significant regression was observed in these +workloads, not proof of identical timing on every machine. + +The comparison's unit tests exercise small/large regressions, improvements, +identical timings, noise, outliers and incomplete/invalid measurements. The +original absolute startup and 0.0880 s gates remain mandatory. Paired timings, +base/candidate SHAs, p-values and raw logs are saved in `artifacts/comparison/`. diff --git a/tests/benchmark_compare.py b/tests/benchmark_compare.py new file mode 100644 index 0000000..011023e --- /dev/null +++ b/tests/benchmark_compare.py @@ -0,0 +1,154 @@ +"""Compare module and CLI performance against a base checkout on one runner.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import subprocess +import sys +import tempfile +import zipfile + +from performance_compare import compare_pairs + +ROOT = Path(__file__).resolve().parents[1] +FIXTURES = ROOT / 'tests' / 'fixtures' +EFFECT_FLOOR_PERCENT = 3.0 +GATED_METRICS = { + 'unit/insn_locator', + 'unit/string_locator', + 'unit/code_scan', + 'unit/method_locator', + 'unit/field_locator', + 'unit/type_locator', + 'unit/method_ref_scan', + 'unit/field_ref_scan', + 'core/decompile', + 'cli_getclass/cli_getclass', + 'cli_findrefs/cli_findrefs', +} + + +def should_gate(metric, result): + return metric in GATED_METRICS and result['regression'] + + +def revision(root): + return subprocess.check_output(['git', '-C', str(root), 'rev-parse', 'HEAD'], text=True).strip() + + +def measure(root, directory, case, output, sample): + env = dict(os.environ, PYTHONPATH=str(root / 'src' / 'asc_core'), PYTHONHASHSEED='0') + if case in ('unit', 'core'): + command = [sys.executable, 'test_findrefs.py' if case == 'unit' else 'test.py'] + else: + command = [sys.executable, str(root / 'main.py')] + if case == 'cli_getclass': + command += ['getclass', 'fixture.apk', 'com.google.android.material.timepicker.ClockFaceView', '--threads', '1', '--debug'] + else: + command += ['findrefs', 'fixture.apk', '--threads', '1', '--debug', 'string', 'create'] + result = subprocess.run(command, cwd=directory, env=env, capture_output=True, text=True, timeout=30) + (output / f'{case}-{sample}.stdout.log').write_text(result.stdout, encoding='utf-8') + (output / f'{case}-{sample}.stderr.log').write_text(result.stderr, encoding='utf-8') + if result.returncode: + raise ValueError(f'{case} exited {result.returncode}; see {output}') + if case == 'unit': + times = {key: float(value) for key, value in re.findall(r'\[DEBUG\] (\w+) Time: ([\d.]+) us', result.stdout)} + answer = {key: int(value) for key, value in re.findall(r'\[DEBUG\] ([\w ]+): (\d+)\s*$', result.stdout, re.M)} + elif case == 'core': + match = re.search(r'Total Execution Time in test.py: ([\d.]+) s', result.stdout) + if match is None: + raise ValueError('missing core timing') + times = {'decompile': float(match[1]) * 1e6} + answer = result.stdout.split('[INFO]')[0].strip() + else: + match = re.search(r'\[DEBUG\] Total Execution Time: ([\d.]+) us', result.stdout) + if match is None: + raise ValueError('missing CLI timing') + times = {case: float(match[1])} + answer = (result.stdout.split('-' * 50)[-1].strip() if case == 'cli_getclass' else + sorted(line for line in result.stdout.splitlines() if ' | ' in line)) + if not answer or (case in ('core', 'cli_getclass') and 'class ClockFaceView' not in answer): + raise ValueError(f'{case}: missing result') + return times, answer + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--baseline', type=Path, required=True) + parser.add_argument('--candidate', type=Path, default=ROOT) + parser.add_argument('--samples', type=int, default=31) + parser.add_argument('--cases', nargs='+', choices=('unit', 'core', 'cli_getclass', 'cli_findrefs'), + default=['unit', 'core', 'cli_getclass', 'cli_findrefs']) + parser.add_argument('--output', type=Path, default=Path('artifacts/comparison')) + args = parser.parse_args() + if args.samples < 15: + parser.error('at least 15 paired samples are required') + roots = {'base': args.baseline.resolve(), 'candidate': args.candidate.resolve()} + affinity = None + if hasattr(os, 'sched_getaffinity'): + affinity = [min(os.sched_getaffinity(0))] + os.sched_setaffinity(0, affinity) + report = {'python': sys.version, 'platform': platform.platform(), + 'cpu_affinity': affinity, 'pythonhashseed': '0', 'samples': {}, 'errors': []} + args.output.mkdir(parents=True, exist_ok=True) + for side in roots: + (args.output / side).mkdir(exist_ok=True) + try: + report['revisions'] = {side: revision(root) for side, root in roots.items()} + contract = json.loads((FIXTURES / 'reference-baseline.json').read_text()) + archive = FIXTURES / 'reference-workload.zip' + if hashlib.sha256(archive.read_bytes()).hexdigest() != contract['archive_sha256']: + raise ValueError('reference archive identity mismatch') + with tempfile.TemporaryDirectory() as directory: + with zipfile.ZipFile(archive) as source: + if set(source.namelist()) != {'classes.dex', 'test.py', 'test_findrefs.py'}: + raise ValueError('unexpected archive members') + source.extractall(directory) + with zipfile.ZipFile(Path(directory) / 'fixture.apk', 'w', compression=zipfile.ZIP_DEFLATED) as apk: + apk.write(Path(directory) / 'classes.dex', 'classes.dex') + for case in args.cases: + expected_keys = set(contract['findrefs_times_us']) if case == 'unit' else {'decompile' if case == 'core' else case} + samples = {key: {'base': [], 'candidate': []} for key in expected_keys} + report['samples'][case] = samples + for index in range(-1, args.samples): + answers = {} + order = ('base', 'candidate') if index % 2 == 0 else ('candidate', 'base') + for side in order: + times, answers[side] = measure(roots[side], directory, case, args.output / side, index) + if times.keys() != expected_keys: + raise ValueError(f'{case}: missing or unexpected timing metrics') + if case == 'unit' and answers[side] != contract['findrefs_counts']: + raise ValueError(f'{side}: reference count mismatch') + if index >= 0: + for key, value in times.items(): + samples[key][side].append(value) + if answers['base'] != answers['candidate']: + raise ValueError(f'{case}: base/candidate outputs differ') + metric_count = len(GATED_METRICS) + report['comparisons'] = {} + report['gated_metrics'] = sorted(GATED_METRICS) + report['effect_floor_percent'] = EFFECT_FLOOR_PERCENT + for case, metrics in report['samples'].items(): + for key, values in metrics.items(): + metric = f'{case}/{key}' + result = compare_pairs(values['base'], values['candidate'], metric_count, + effect_floor_percent=EFFECT_FLOOR_PERCENT) + result['gated'] = metric in GATED_METRICS + report['comparisons'][metric] = result + if should_gate(metric, result): + report['errors'].append( + f'{metric}: significant material slowdown ' + f'({result["paired_median_change_percent"]:+.2f}%)' + ) + except (ValueError, OSError, subprocess.SubprocessError, zipfile.BadZipFile) as error: + report['errors'].append(str(error)) + (args.output / 'report.json').write_text(json.dumps(report, indent=2), encoding='utf-8') + print(json.dumps({key: value for key, value in report.items() if key != 'samples'}, indent=2)) + return 1 if report['errors'] else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/benchmark_reference.py b/tests/benchmark_reference.py new file mode 100644 index 0000000..0ab1225 --- /dev/null +++ b/tests/benchmark_reference.py @@ -0,0 +1,91 @@ +"""Run the supplied DEX benchmarks unchanged in fresh Python processes.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import statistics +import subprocess +import sys +import tempfile +import time +import zipfile + +ROOT = Path(__file__).resolve().parents[1] +FIXTURES = Path(__file__).resolve().parent / 'fixtures' + + +def run_script(script, directory, output, index): + env = dict(os.environ, PYTHONPATH=str(ROOT / 'src' / 'asc_core')) + start = time.perf_counter() + result = subprocess.run([sys.executable, script], cwd=directory, env=env, + capture_output=True, text=True, timeout=30) + wall_ms = (time.perf_counter() - start) * 1000 + stem = output / f'{Path(script).stem}-{index:02d}' + stem.with_suffix('.stdout.log').write_text(result.stdout, encoding='utf-8') + stem.with_suffix('.stderr.log').write_text(result.stderr, encoding='utf-8') + if result.returncode: + raise ValueError(f'{script} sample {index}: exit {result.returncode}; see logs') + return result.stdout, wall_ms + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--samples', type=int, default=9) + parser.add_argument('--output', type=Path, default=Path('artifacts/reference')) + args = parser.parse_args() + if args.samples < 3: + parser.error('use at least 3 samples') + args.output.mkdir(parents=True, exist_ok=True) + baseline = json.loads((FIXTURES / 'reference-baseline.json').read_text()) + archive = FIXTURES / 'reference-workload.zip' + report = {'python': sys.version, 'platform': platform.platform(), + 'requested_samples': args.samples, 'baseline': baseline, + 'decompile': [], 'findrefs': [], 'errors': []} + try: + if hashlib.sha256(archive.read_bytes()).hexdigest() != baseline['archive_sha256']: + raise ValueError('Reference archive does not match the supplied sample') + with tempfile.TemporaryDirectory() as directory: + with zipfile.ZipFile(archive) as source: + if set(source.namelist()) != {'classes.dex', 'test.py', 'test_findrefs.py'}: + raise ValueError('Unexpected reference archive members') + source.extractall(directory) + for index in range(args.samples): + text, wall_ms = run_script('test.py', directory, args.output, index) + match = re.search(r'Total Execution Time in test.py: ([\d.]+) s', text) + if match is None or 'class ClockFaceView' not in text: + raise ValueError(f'test.py sample {index}: missing source or timing') + report['decompile'].append({'seconds': float(match[1]), 'wall_ms': wall_ms}) + text, wall_ms = run_script('test_findrefs.py', directory, args.output, index) + times = {key: float(value) for key, value in + re.findall(r'\[DEBUG\] (\w+) Time: ([\d.]+) us', text)} + counts = {key: int(value) for key, value in + re.findall(r'\[DEBUG\] ([\w ]+): (\d+)\s*$', text, re.M)} + report['findrefs'].append({'times_us': times, 'counts': counts, 'wall_ms': wall_ms}) + if counts != baseline['findrefs_counts']: + raise ValueError(f'test_findrefs.py sample {index}: count mismatch: {counts}') + if times.keys() != baseline['findrefs_times_us'].keys(): + raise ValueError(f'test_findrefs.py sample {index}: timing metrics changed') + median = statistics.median(row['seconds'] for row in report['decompile']) + report['decompile_median_seconds'] = median + report['decompile_max_seconds'] = max(row['seconds'] for row in report['decompile']) + if median > baseline['decompile_limit_seconds']: + report['errors'].append(f'Decompilation median {median:.4f} s exceeds 0.0880 s') + report['findrefs_comparison'] = [] + for metric, reference in baseline['findrefs_times_us'].items(): + measured = statistics.median(row['times_us'][metric] for row in report['findrefs']) + report['findrefs_comparison'].append({ + 'metric': metric, 'baseline_us': reference, 'median_us': measured, + 'change_percent': (measured / reference - 1) * 100}) + except (ValueError, OSError, subprocess.TimeoutExpired, zipfile.BadZipFile) as error: + report['errors'].append(str(error)) + (args.output / 'report.json').write_text(json.dumps(report, indent=2), encoding='utf-8') + print(json.dumps({key: value for key, value in report.items() + if key not in ('decompile', 'findrefs', 'baseline')}, indent=2)) + return 1 if report['errors'] else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/benchmark_startup.py b/tests/benchmark_startup.py new file mode 100644 index 0000000..fc694fb --- /dev/null +++ b/tests/benchmark_startup.py @@ -0,0 +1,79 @@ +"""Measure cold interpreter startup with a generated APK and the real CLI.""" +import argparse +import json +from pathlib import Path +import platform +import re +import statistics +import subprocess +import sys +import tempfile +import time +import zipfile + +from dex_fixture import make_dex + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--samples', type=int, default=9) + parser.add_argument('--max-total-ms', type=float, default=100) + parser.add_argument('--max-wall-ms', type=float, default=250) + parser.add_argument('--output', type=Path, default=Path('artifacts/startup')) + args = parser.parse_args() + if args.samples < 3 or args.max_total_ms <= 0 or args.max_wall_ms <= 0: + parser.error('use at least 3 samples and positive time budgets') + args.output.mkdir(parents=True, exist_ok=True) + records = [] + errors = [] + with tempfile.TemporaryDirectory() as directory: + apk = Path(directory) / 'fixture.apk' + with zipfile.ZipFile(apk, 'w', compression=zipfile.ZIP_DEFLATED) as archive: + archive.writestr('classes.dex', make_dex()) + command = [sys.executable, str(ROOT / 'main.py'), 'getclass', str(apk), + 'example.Test', '--threads', '1', '--debug'] + for index in range(args.samples): + start = time.perf_counter() + try: + result = subprocess.run(command, cwd=ROOT, capture_output=True, + text=True, timeout=30) + except subprocess.TimeoutExpired: + errors.append(f'sample {index}: CLI exceeded 30 seconds') + break + wall_ms = (time.perf_counter() - start) * 1000 + (args.output / f'{index:02d}.stdout.log').write_text(result.stdout, encoding='utf-8') + (args.output / f'{index:02d}.stderr.log').write_text(result.stderr, encoding='utf-8') + if result.returncode or any(text not in result.stdout for text in + ('class Test', 'void first()', 'void second()')): + errors.append(f'sample {index}: decompilation failed; see logs') + break + record = {'wall_ms': wall_ms} + for key, label in (('total_ms', 'Total Execution Time'), + ('extraction_ms', 'Total Extraction Time'), + ('apk_ms', 'APK Scan Time')): + match = re.search(r'\[DEBUG\] ' + label + r': ([\d.]+) us', result.stdout) + if match is None: + errors.append(f'sample {index}: missing debug metric {label}') + break + record[key] = float(match[1]) / 1000 + if errors: + break + records.append(record) + medians = {key: statistics.median(row[key] for row in records) + for key in records[0]} if records else {} + for metric, budget in (('total_ms', args.max_total_ms), ('wall_ms', args.max_wall_ms)): + if medians.get(metric, 0) > budget: + errors.append(f'{metric} median {medians[metric]:.2f} ms exceeds {budget:.2f} ms') + report = {'python': sys.version, 'platform': platform.platform(), + 'command': command, 'requested_samples': args.samples, + 'budgets_ms': {'total_ms': args.max_total_ms, 'wall_ms': args.max_wall_ms}, + 'samples': records, 'median_ms': medians, 'errors': errors} + (args.output / 'report.json').write_text(json.dumps(report, indent=2), encoding='utf-8') + print(json.dumps(report, indent=2)) + return 1 if errors else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/dex_fixture.py b/tests/dex_fixture.py new file mode 100644 index 0000000..30417a7 --- /dev/null +++ b/tests/dex_fixture.py @@ -0,0 +1,107 @@ +"""Build a small DEX with two static methods sharing one code_item.""" +import hashlib +import struct +import zlib + + +def uleb(value): + result = bytearray() + while value > 127: + result.append((value & 127) | 128) + value >>= 7 + result.append(value) + return result + + +def make_dex(): + strings = [b'Lexample/Test;', b'Ljava/lang/Object;', b'V', b'first', b'second', b'token'] + buf = bytearray(112) + sections = [(0, 1, 0)] + + def section(kind, size, data, align=4): + buf.extend(b'\0' * (-len(buf) % align)) + off = len(buf) + sections.append((kind, size, off)) + buf.extend(data) + return off + + string_ids = section(1, len(strings), bytes(4 * len(strings))) + type_ids = section(2, 3, struct.pack(' 1 for value in ratios) + faster = sum(value < 1 for value in ratios) + n = slower + faster + p_value = sum(math.comb(n, k) for k in range(slower, n + 1)) / 2 ** n + threshold = alpha / metric_count + paired_median_change_percent = (statistics.median(ratios) - 1) * 100 + statistically_significant = p_value < threshold + material_slowdown = paired_median_change_percent >= effect_floor_percent + return {'base_median': statistics.median(base), + 'candidate_median': statistics.median(candidate), + 'paired_median_change_percent': paired_median_change_percent, + 'slower_pairs': slower, 'faster_pairs': faster, + 'p_value': p_value, 'threshold': threshold, + 'effect_floor_percent': effect_floor_percent, + 'statistically_significant': statistically_significant, + 'material_slowdown': material_slowdown, + 'regression': statistically_significant and material_slowdown} diff --git a/tests/run_tests.py b/tests/run_tests.py index 06b13a7..9bd6b54 100644 --- a/tests/run_tests.py +++ b/tests/run_tests.py @@ -1,51 +1,33 @@ -import os -import subprocess +"""Run self-contained regression tests without an external APK.""" +import argparse +import importlib.util +from pathlib import Path import sys -import shutil +import unittest -WORKSPACE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) -AGENT_SCRIPT = os.path.join(WORKSPACE_ROOT, "agent_operator.py") +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) -MEITUAN_APK = os.path.join(WORKSPACE_ROOT, "meituan.apk") -MEITUAN_CLASS = "Lcom/meituan/android/cashier/activity/MTCashierWrapperActivity;" - -def run_test(apk_path, clazz_name): - print(f"\n{'='*80}") - print(f"Testing APK: {apk_path}") - print(f"Class: {clazz_name}") - print(f"{'='*80}\n") - - cmd = [sys.executable, AGENT_SCRIPT, "getclass", "-v", apk_path, clazz_name] - - print(f"Running command: {' '.join(cmd)}\n") - - process = subprocess.run(cmd, cwd=WORKSPACE_ROOT, capture_output=True, text=True) - - print(process.stdout) - if process.stderr: - print(f"STDERR:\n{process.stderr}") - - if process.returncode == 0 and "class" in process.stdout.lower(): - print("\n[SUCCESS] Test passed! Got decompiled code.") - else: - print(f"\n[FAILED] Test failed with return code {process.returncode}") - - return process.returncode - -def main(): - temp_dir = os.path.join(WORKSPACE_ROOT, "temp") - if os.path.exists(temp_dir): - print(f"Cleaning temp directory: {temp_dir}") - shutil.rmtree(temp_dir, ignore_errors=True) - - print("Starting NewTool tests...") - - if os.path.exists(MEITUAN_APK): - rc = run_test(MEITUAN_APK, MEITUAN_CLASS) - sys.exit(rc) - else: - print(f"[SKIP] {MEITUAN_APK} not found") - sys.exit(1) - -if __name__ == "__main__": - main() +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--require-decompiler', action='store_true') + parser.add_argument('--suite', choices=('all', 'unit', 'integration'), default='all') + args = parser.parse_args() + if args.require_decompiler and importlib.util.find_spec('androguard') is None: + parser.error('Androguard is required; install requirements.txt') + suite = unittest.defaultTestLoader.discover(str(ROOT / 'tests'), pattern='test_*.py') + if args.suite != 'all': + def tests(items): + for item in items: + if isinstance(item, unittest.TestSuite): + yield from tests(item) + else: + yield item + suite = unittest.TestSuite(test for test in tests(suite) + if ('test_decompiler.DecompilerTests.' in test.id() + or test.id().endswith('test_archive_is_reproducible_and_runs_outside_checkout')) + == (args.suite == 'integration')) + if suite.countTestCases() == 0: + parser.error('selected suite contains no tests') + result = unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(0 if result.wasSuccessful() and not (args.require_decompiler and result.skipped) else 1) diff --git a/tests/test_decompiler.py b/tests/test_decompiler.py new file mode 100644 index 0000000..45d177b --- /dev/null +++ b/tests/test_decompiler.py @@ -0,0 +1,95 @@ +import importlib +import importlib.util +from pathlib import Path +import subprocess +import struct +import sys +import tempfile +import unittest +import zipfile + +from dex_fixture import make_dex, make_static_field_dex +from src.asc_core.core.dex.dex_manager import DexManager +from src.asc_core.utils.dex_parser import parse_encoded_array +from src.asc_core.utils.tinydex import DEX + +ROOT = Path(__file__).resolve().parents[1] + + +class RebuildTests(unittest.TestCase): + def test_rebuilt_dex_keeps_signature_and_checksum_zero(self): + data = DexManager(make_dex()).extract_and_rebuild('Lexample/Test;') + self.assertEqual(data[8:32], bytes(24)) + + def test_rebuild_keeps_static_values_and_field_operands_aligned(self): + data = DexManager(make_static_field_dex()).extract_and_rebuild('Lexample/Statics;') + dex = DEX.parse(memoryview(data), 'rebuilt.dex') + clazz = dex.classes[0] + static_fields = [field for field in clazz.fields if field.is_static] + static_values_off = struct.unpack_from('first' in line for line in lines)) + self.assertTrue(any('->second' in line for line in lines)) + + +class StringTests(unittest.TestCase): + def locate(self, data, query): + from src.asc_core.findrefs.locator.string_locator import StringLocator + return StringLocator(DEX.parse(memoryview(data), 'fixture.dex')).locate(query) + + def test_last_string_is_searchable(self): + self.assertEqual(self.locate(make_dex(), 'token'), {5}) + + def test_physical_string_order_does_not_change_ids(self): + from dex_fixture import uleb + data = bytearray(make_dex()) + ids_off = struct.unpack_from('