├── tests ├── test.aab ├── test.apk ├── test.dex ├── test_multidex.aab ├── test_multidex.apk ├── __init__.py ├── test_multi_dex_aab.py ├── test_multi_dex_apk.py ├── test_single_dex_aab.py ├── test_single_dex_apk.py ├── test_load_dex.py └── test_parse_single_dex.py ├── dexparser ├── errors.py ├── utils.py ├── disassembler.py └── __init__.py ├── docs ├── dexparser.rst ├── index.rst ├── Makefile ├── make.bat └── conf.py ├── requirements.txt ├── .travis.yml ├── setup.py ├── LICENSE ├── README.md └── .gitignore /tests/test.aab: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bunseokbot/dexparser/HEAD/tests/test.aab -------------------------------------------------------------------------------- /tests/test.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bunseokbot/dexparser/HEAD/tests/test.apk -------------------------------------------------------------------------------- /tests/test.dex: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bunseokbot/dexparser/HEAD/tests/test.dex -------------------------------------------------------------------------------- /tests/test_multidex.aab: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bunseokbot/dexparser/HEAD/tests/test_multidex.aab -------------------------------------------------------------------------------- /tests/test_multidex.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bunseokbot/dexparser/HEAD/tests/test_multidex.apk -------------------------------------------------------------------------------- /dexparser/errors.py: -------------------------------------------------------------------------------- 1 | class InsufficientParameterError(Exception): 2 | pass 3 | 4 | 5 | class IsNotAPKFileFormatError(Exception): 6 | pass 7 | -------------------------------------------------------------------------------- /docs/dexparser.rst: -------------------------------------------------------------------------------- 1 | dexparser 2 | ====================================== 3 | 4 | .. automodule:: dexparser 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Modules 10 | ------- 11 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | atomicwrites==1.4.1 2 | attrs==22.2.0 3 | colorama==0.4.6 4 | coverage==7.2.1 5 | iniconfig==2.0.0 6 | more-itertools==9.1.0 7 | packaging==23.0 8 | pluggy==1.0.0 9 | py==1.11.0 10 | pycodestyle==2.10.0 11 | pytest==7.2.2 12 | wcwidth==0.2.6 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.5" 4 | - "3.6" 5 | - "3.7" 6 | - "3.8" 7 | - "nightly" 8 | - "pypy3" 9 | 10 | install: 11 | - pip install -r requirements.txt 12 | 13 | script: 14 | - python -m pytest -v 15 | - pycodestyle --max-line-length=120 --exclude=build . 16 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | TEST_DEX_FILEPATH = os.path.join("tests", "test.dex") 5 | TEST_SINGLE_APK_FILEPATH = os.path.join("tests", "test.apk") 6 | TEST_MULTI_APK_FILEPATH = os.path.join("tests", "test_multidex.apk") 7 | TEST_SINGLE_AAB_FILEPATH = os.path.join("tests", "test.aab") 8 | TEST_MULTI_AAB_FILEPATH = os.path.join("tests", "test_multidex.aab") 9 | -------------------------------------------------------------------------------- /tests/test_multi_dex_aab.py: -------------------------------------------------------------------------------- 1 | from dexparser import AABParser 2 | 3 | from . import TEST_MULTI_AAB_FILEPATH 4 | 5 | 6 | def test_load_aab_from_filedir(): 7 | aab = AABParser(filedir=TEST_MULTI_AAB_FILEPATH) 8 | assert aab.is_multidex is True 9 | 10 | 11 | def test_load_aab_file_fileobj(): 12 | with open(TEST_MULTI_AAB_FILEPATH, 'rb') as f: 13 | aab = AABParser(fileobj=f.read()) 14 | assert aab.is_multidex is True 15 | -------------------------------------------------------------------------------- /tests/test_multi_dex_apk.py: -------------------------------------------------------------------------------- 1 | from dexparser import APKParser 2 | 3 | from . import TEST_MULTI_APK_FILEPATH 4 | 5 | 6 | def test_load_apk_from_filedir(): 7 | dex = APKParser(filedir=TEST_MULTI_APK_FILEPATH) 8 | assert dex.is_multidex is True 9 | 10 | 11 | def test_load_apk_file_fileobj(): 12 | with open(TEST_MULTI_APK_FILEPATH, 'rb') as f: 13 | dex = APKParser(fileobj=f.read()) 14 | assert dex.is_multidex is True 15 | -------------------------------------------------------------------------------- /tests/test_single_dex_aab.py: -------------------------------------------------------------------------------- 1 | from dexparser import AABParser 2 | 3 | from . import TEST_SINGLE_AAB_FILEPATH 4 | 5 | 6 | def test_load_aab_from_filedir(): 7 | aab = AABParser(filedir=TEST_SINGLE_AAB_FILEPATH) 8 | assert aab.is_multidex is False 9 | 10 | 11 | def test_load_aab_file_fileobj(): 12 | with open(TEST_SINGLE_AAB_FILEPATH, 'rb') as f: 13 | aab = AABParser(fileobj=f.read()) 14 | assert aab.is_multidex is False 15 | -------------------------------------------------------------------------------- /tests/test_single_dex_apk.py: -------------------------------------------------------------------------------- 1 | from dexparser import APKParser 2 | 3 | from . import TEST_SINGLE_APK_FILEPATH 4 | 5 | 6 | def test_load_apk_from_filedir(): 7 | apk = APKParser(filedir=TEST_SINGLE_APK_FILEPATH) 8 | assert apk.is_multidex is False 9 | 10 | 11 | def test_load_apk_file_fileobj(): 12 | with open(TEST_SINGLE_APK_FILEPATH, 'rb') as f: 13 | apk = APKParser(fileobj=f.read()) 14 | assert apk.is_multidex is False 15 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. dexparser documentation master file, created by 2 | sphinx-quickstart on Wed Dec 25 07:57:40 2019. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to dexparser's documentation! 7 | ===================================== 8 | 9 | .. toctree:: 10 | :maxdepth: 3 11 | :caption: Contents: 12 | 13 | dexparser 14 | 15 | 16 | Indices and tables 17 | ================== 18 | 19 | * :ref:`genindex` 20 | * :ref:`modindex` 21 | * :ref:`search` 22 | -------------------------------------------------------------------------------- /tests/test_load_dex.py: -------------------------------------------------------------------------------- 1 | from dexparser import Dexparser, DEXParser 2 | 3 | from . import TEST_DEX_FILEPATH 4 | 5 | 6 | def test_load_dex_from_filedir(): 7 | dex = Dexparser(filedir=TEST_DEX_FILEPATH) 8 | 9 | 10 | def test_load_dex_from_filedir_with_new_dexparser(): 11 | dex = DEXParser(filedir=TEST_DEX_FILEPATH) 12 | 13 | 14 | def test_load_dex_file_fileobj(): 15 | with open(TEST_DEX_FILEPATH, 'rb') as f: 16 | dex = Dexparser(fileobj=f.read()) 17 | 18 | 19 | def test_load_dex_file_fileobj_with_new_dexparser(): 20 | with open(TEST_DEX_FILEPATH, 'rb') as f: 21 | dex = DEXParser(fileobj=f.read()) 22 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | with open("README.md") as f: 4 | long_description = f.read() 5 | 6 | setup( 7 | name='dexparser', 8 | version='1.2.0', 9 | py_modules=['dexparser'], 10 | author='austinkim', 11 | author_email='austin.njkim@gmail.com', 12 | url='https://github.com/bunseokbot/dexparser', 13 | packages=find_packages(), 14 | description='Powerful DEX file format parser for Pythonista', 15 | long_description=long_description, 16 | long_description_content_type='text/markdown', 17 | classifiers=[ 18 | 'Programming Language :: Python :: 3', 19 | 'Programming Language :: Python :: 3.5', 20 | 'Programming Language :: Python :: 3.6', 21 | 'Programming Language :: Python :: 3.7', 22 | 'Programming Language :: Python :: 3.8', 23 | 'Programming Language :: Python :: 3.9', 24 | 'Programming Language :: Python :: 3.10', 25 | "License :: OSI Approved :: MIT License", 26 | "Operating System :: OS Independent", 27 | ], 28 | python_requires='>=3.5', 29 | ) 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Kim Namjun 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /dexparser/utils.py: -------------------------------------------------------------------------------- 1 | def uleb128_value(data, off): 2 | size = 1 3 | result = data[off+0] 4 | if result > 0x7f: 5 | cur = data[off+1] 6 | result = (result & 0x7f) | ((cur & 0x7f) << 7) 7 | size += 1 8 | if cur > 0x7f: 9 | cur = data[off+2] 10 | result |= ((cur & 0x7f) << 14) 11 | size += 1 12 | if cur > 0x7f: 13 | cur = data[off+3] 14 | result |= ((cur & 0x7f) << 21) 15 | size += 1 16 | if cur > 0x7f: 17 | cur = data[off+4] 18 | result |= (cur << 28) 19 | size += 1 20 | 21 | return result, size 22 | 23 | 24 | def encoded_field(data, offset): 25 | myoff = offset 26 | 27 | field_idx_diff, size = uleb128_value(data, myoff) 28 | myoff += size 29 | access_flags, size = uleb128_value(data, myoff) 30 | myoff += size 31 | 32 | size = myoff - offset 33 | 34 | return [field_idx_diff, access_flags, size] 35 | 36 | 37 | def encoded_method(data, offset): 38 | myoff = offset 39 | 40 | method_idx_diff, size = uleb128_value(data, myoff) 41 | myoff += size 42 | access_flags, size = uleb128_value(data, myoff) 43 | myoff += size 44 | code_off, size = uleb128_value(data, myoff) 45 | myoff += size 46 | 47 | size = myoff - offset 48 | 49 | return [method_idx_diff, access_flags, code_off, size] 50 | 51 | 52 | def encoded_annotation(data, offset): 53 | myoff = offset 54 | 55 | type_idx_diff, size = uleb128_value(data, myoff) 56 | myoff += size 57 | size_diff, size = uleb128_value(data, myoff) 58 | myoff += size 59 | name_idx_diff, size = uleb128_value(data, myoff) 60 | myoff += size 61 | value_type = data[myoff:myoff+1] 62 | encoded_value = data[myoff+1:myoff+2] 63 | 64 | return [type_idx_diff, size_diff, name_idx_diff, value_type, encoded_value] 65 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | import os 14 | import sys 15 | sys.path.insert(0, os.path.abspath('..')) 16 | 17 | 18 | # -- Project information ----------------------------------------------------- 19 | 20 | project = 'dexparser' 21 | copyright = '2019, austinkim' 22 | author = 'austinkim' 23 | 24 | 25 | # -- General configuration --------------------------------------------------- 26 | 27 | # Add any Sphinx extension module names here, as strings. They can be 28 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 29 | # ones. 30 | extensions = [ 31 | 'sphinx.ext.autodoc', 32 | ] 33 | 34 | # Add any paths that contain templates here, relative to this directory. 35 | templates_path = ['_templates'] 36 | 37 | # List of patterns, relative to source directory, that match files and 38 | # directories to ignore when looking for source files. 39 | # This pattern also affects html_static_path and html_extra_path. 40 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 41 | 42 | 43 | # -- Options for HTML output ------------------------------------------------- 44 | 45 | # The theme to use for HTML and HTML Help pages. See the documentation for 46 | # a list of builtin themes. 47 | # 48 | html_theme = 'sphinx_rtd_theme' 49 | 50 | # Add any paths that contain custom static files (such as style sheets) here, 51 | # relative to this directory. They are copied after the builtin static files, 52 | # so a file named "default.css" will overwrite the builtin "default.css". 53 | html_static_path = ['_static'] 54 | 55 | master_doc = 'index' 56 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dexparser 2 | 3 | Powerful DEX file format parser for Pythonist! 4 | 5 | [![Build Status](https://travis-ci.com/bunseokbot/dexparser.svg?branch=master)](https://travis-ci.com/bunseokbot/dexparser) 6 | [![PyPI version](https://badge.fury.io/py/dexparser.svg)](https://badge.fury.io/py/dexparser) 7 | [![Documentation Status](https://readthedocs.org/projects/dexparser/badge/?version=latest)](https://dexparser.readthedocs.io/en/latest/?badge=latest) 8 | [![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fgithub.com%2Fbunseokbot%2Fdexparser&count_bg=%2379C83D&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=hits&edge_flat=false)](https://hits.seeyoufarm.com) 9 | 10 | ## Usage 11 | 12 | See the [docs](https://dexparser.readthedocs.io/en/latest/) for detail descriptions. 13 | 14 | ### Pre-requirements 15 | 16 | * Python 3.x (Unofficially, dexparser support Python 2.x) 17 | * DEX friendly mind 18 | 19 | ### Install 20 | `pip install dexparser` 21 | 22 | ### Load DEX from filename 23 | ``` 24 | from dexparser import DEXParser 25 | 26 | filedir = '/path/to/classes.dex' 27 | dex = DEXParser(filedir=filedir) 28 | ``` 29 | 30 | ### Load DEX file from object 31 | ``` 32 | from dexparser import DEXParser 33 | 34 | with open('classes.dex', 'rb') as fileobj: 35 | dex = DEXParser(fileobj=fileobj.read()) 36 | ``` 37 | 38 | ### Load APK file from object and filename 39 | ``` 40 | from dexparser import APKParser 41 | 42 | filedir = '/path/to/test.apk' 43 | apk = APKParser(filedir=filedir) 44 | 45 | with open('/path/to/test.apk', 'rb') as fileobj: 46 | apk = APKParser(fileobj=fileobj.read()) 47 | ``` 48 | 49 | ### Load AAB file from object and filename 50 | ``` 51 | from dexparser import AABParser 52 | 53 | filedir = '/path/to/test.apk' 54 | aab = AABParser(filedir=filedir) 55 | 56 | with open('/path/to/test.apk', 'rb') as fileobj: 57 | aab = AABParser(fileobj=fileobj.read()) 58 | ``` 59 | 60 | 61 | ## License 62 | This project is licensed under the MIT License 63 | 64 | ## Reference 65 | * [Dalvik Executable Format](https://source.android.com/devices/tech/dalvik/dex-format) 66 | * [dexparser released! (Korean)](https://iam.namjun.kim/opensource/2019/12/25/dexparser-released/) 67 | 68 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # Visual Studio code cache 132 | .vscode/ 133 | -------------------------------------------------------------------------------- /tests/test_parse_single_dex.py: -------------------------------------------------------------------------------- 1 | from dexparser import Dexparser, DEXParser 2 | 3 | from . import TEST_DEX_FILEPATH 4 | 5 | 6 | def test_parse_header(): 7 | dex = Dexparser(filedir=TEST_DEX_FILEPATH) 8 | assert dex.header.get('checksum') == 2459812747 9 | 10 | dex = DEXParser(filedir=TEST_DEX_FILEPATH) 11 | assert dex.header.get('checksum') == 2459812747 12 | 13 | 14 | def test_parse_strings(): 15 | dex = Dexparser(filedir=TEST_DEX_FILEPATH) 16 | assert dex.get_strings() 17 | 18 | dex = DEXParser(filedir=TEST_DEX_FILEPATH) 19 | assert dex.get_strings() 20 | 21 | 22 | def test_parse_typeids(): 23 | dex = Dexparser(filedir=TEST_DEX_FILEPATH) 24 | assert dex.get_typeids() 25 | 26 | dex = DEXParser(filedir=TEST_DEX_FILEPATH) 27 | assert dex.get_typeids() 28 | 29 | 30 | def test_parse_methods(): 31 | dex = Dexparser(filedir=TEST_DEX_FILEPATH) 32 | assert dex.get_methods() 33 | 34 | dex = DEXParser(filedir=TEST_DEX_FILEPATH) 35 | assert dex.get_methods() 36 | 37 | 38 | def test_parse_protoids(): 39 | dex = Dexparser(filedir=TEST_DEX_FILEPATH) 40 | assert dex.get_protoids() 41 | 42 | dex = DEXParser(filedir=TEST_DEX_FILEPATH) 43 | assert dex.get_protoids() 44 | 45 | 46 | def test_parse_fieldids(): 47 | dex = Dexparser(filedir=TEST_DEX_FILEPATH) 48 | assert dex.get_fieldids() 49 | 50 | dex = DEXParser(filedir=TEST_DEX_FILEPATH) 51 | assert dex.get_fieldids() 52 | 53 | 54 | def test_parse_classdef_data(): 55 | dex = Dexparser(filedir=TEST_DEX_FILEPATH) 56 | assert dex.get_classdef_data() 57 | 58 | dex = DEXParser(filedir=TEST_DEX_FILEPATH) 59 | assert dex.get_classdef_data() 60 | 61 | 62 | def test_parse_class_data(): 63 | dex = Dexparser(filedir=TEST_DEX_FILEPATH) 64 | offset = dex.get_classdef_data()[0]['class_data_off'] 65 | assert dex.get_class_data(offset=offset) 66 | 67 | dex = DEXParser(filedir=TEST_DEX_FILEPATH) 68 | offset = dex.get_classdef_data()[0]['class_data_off'] 69 | assert dex.get_class_data(offset=offset) 70 | 71 | 72 | def test_parse_annotations(): 73 | dex = Dexparser(filedir=TEST_DEX_FILEPATH) 74 | offset = dex.get_classdef_data()[0]['annotation_off'] 75 | assert dex.get_annotations(offset=offset) 76 | 77 | dex = DEXParser(filedir=TEST_DEX_FILEPATH) 78 | offset = dex.get_classdef_data()[0]['annotation_off'] 79 | assert dex.get_annotations(offset=offset) 80 | 81 | 82 | def test_parse_class_data(): 83 | dex = Dexparser(filedir=TEST_DEX_FILEPATH) 84 | for i, class_def in enumerate(dex.get_classdef_data()): 85 | offset = class_def['static_values_off'] 86 | if offset == 0: 87 | continue 88 | 89 | assert dex.get_static_values(offset=offset) 90 | 91 | dex = DEXParser(filedir=TEST_DEX_FILEPATH) 92 | offset = dex.get_classdef_data()[0]['static_values_off'] 93 | assert dex.get_static_values(offset=offset) 94 | -------------------------------------------------------------------------------- /dexparser/disassembler.py: -------------------------------------------------------------------------------- 1 | opcode = { 2 | 0x00: 'nop', 3 | 0x01: 'move', 4 | 0x02: 'move/from16', 5 | 0x03: 'move/16', 6 | 0x04: 'move-wide', 7 | 0x05: 'move-wide/from16', 8 | 0x06: 'move-wide/16', 9 | 0x07: 'move-object', 10 | 0x08: 'move-object/from16', 11 | 0x09: 'move-object/16', 12 | 0x0A: 'move-result', 13 | 0x0B: 'move-result-wide', 14 | 0x0C: 'move-result-object', 15 | 0x0D: 'move-exception', 16 | 0x0E: 'return-void', 17 | 0x0F: 'return', 18 | 19 | 0x10: 'return-wide', 20 | 0x11: 'return-object', 21 | 0x12: 'const/4', 22 | 0x13: 'const/16', 23 | 0x14: 'const', 24 | 0x15: 'const/high16', 25 | 0x16: 'const-wide/16', 26 | 0x17: 'const-wide/32', 27 | 0x18: 'const-wide', 28 | 0x19: 'const-wide/high16', 29 | 0x1A: 'const-string', 30 | 0x1B: 'const-string-jumbo', 31 | 0x1C: 'const-class', 32 | 0x1D: 'monitor-enter', 33 | 0x1E: 'monitor-exit', 34 | 0x1F: 'check-cast', 35 | 36 | 0x20: 'instance-of', 37 | 0x21: 'array-length', 38 | 0x22: 'new-instance', 39 | 0x23: 'new-array', 40 | 0x24: 'filled-new-array', 41 | 0x25: 'filled-new-array-range', 42 | 0x26: 'fill-array-data', 43 | 0x27: 'throw', 44 | 0x28: 'goto', 45 | 0x29: 'goto/16', 46 | 0x2A: 'goto/32', 47 | 0x2B: 'packed-switch', 48 | 0x2C: 'sparse-switch', 49 | 0x2D: 'cmpl-float', 50 | 0x2E: 'cmpg-float', 51 | 0x2F: 'cmpl-double', 52 | 53 | 0x30: 'cmpg-double', 54 | 0x31: 'cmp-long', 55 | 0x32: 'if-eq', 56 | 0x33: 'if-ne', 57 | 0x34: 'if-lt', 58 | 0x35: 'if-ge', 59 | 0x36: 'if-gt', 60 | 0x37: 'if-le', 61 | 0x38: 'if-eqz', 62 | 0x39: 'if-nez', 63 | 0x3A: 'if-ltz', 64 | 0x3B: 'if-gez', 65 | 0x3C: 'if-gtz', 66 | 0x3D: 'if-lez', 67 | 0x3E: 'unused', 68 | 0x3F: 'unused', 69 | 70 | 0x40: 'unused', 71 | 0x41: 'unused', 72 | 0x42: 'unused', 73 | 0x43: 'unused', 74 | 0x44: 'aget', 75 | 0x45: 'aget-wide', 76 | 0x46: 'aget-object', 77 | 0x47: 'aget-boolean', 78 | 0x48: 'aget-byte', 79 | 0x49: 'aget-char', 80 | 0x4A: 'aget-short', 81 | 0x4B: 'aput', 82 | 0x4C: 'aput-wide', 83 | 0x4D: 'aput-object', 84 | 0x4E: 'aput-boolean', 85 | 0x4F: 'aput-byte', 86 | 87 | 0x50: 'aput-char', 88 | 0x51: 'aput-short', 89 | 0x52: 'iget', 90 | 0x53: 'iget-wide', 91 | 0x54: 'iget-object', 92 | 0x55: 'iget-boolean', 93 | 0x56: 'iget-byte', 94 | 0x57: 'iget-char', 95 | 0x58: 'iget-short', 96 | 0x59: 'iput', 97 | 0x5A: 'iput-wide', 98 | 0x5B: 'iput-object', 99 | 0x5C: 'iput-boolean', 100 | 0x5D: 'iput-byte', 101 | 0x5E: 'iput-char', 102 | 0x5F: 'iput-short', 103 | 104 | 0x60: 'sget', 105 | 0x61: 'sget-wide', 106 | 0x62: 'sget-object', 107 | 0x63: 'sget-boolean', 108 | 0x64: 'sget-byte', 109 | 0x65: 'sget-char', 110 | 0x66: 'sget-short', 111 | 0x67: 'sput', 112 | 0x68: 'sput-wide', 113 | 0x69: 'sput-object', 114 | 0x6A: 'sput-boolean', 115 | 0x6B: 'sput-byte', 116 | 0x6C: 'sput-char', 117 | 0x6D: 'sput-short', 118 | 0x6E: 'invoke-virtual', 119 | 0x6F: 'invoke-super', 120 | 121 | 0x70: 'invoke-direct', 122 | 0x71: 'invoke-static', 123 | 0x72: 'invoke-interface', 124 | 0x73: 'unused', 125 | 0x74: 'invoke-virtual/range', 126 | 0x75: 'invoke-super/range', 127 | 0x76: 'invoke-direct/range', 128 | 0x77: 'invoke-static/range', 129 | 0x78: 'invoke-interface-range', 130 | 0x79: 'unused', 131 | 0x7A: 'unused', 132 | 0x7B: 'neg-int', 133 | 0x7C: 'not-long', 134 | 0x7D: 'neg-long', 135 | 0x7E: 'not-long', 136 | 0x7F: 'neg-float', 137 | 138 | 0x80: 'neg-double', 139 | 0x81: 'int-to-long', 140 | 0x82: 'int-to-float', 141 | 0x83: 'int-to-double', 142 | 0x84: 'long-to-int', 143 | 0x85: 'long-to-float', 144 | 0x86: 'long-to-double', 145 | 0x87: 'float-to-int', 146 | 0x88: 'float-to-long', 147 | 0x89: 'float-to-double', 148 | 0x8A: 'double-to-int', 149 | 0x8B: 'double-to-long', 150 | 0x8C: 'double-to-float', 151 | 0x8D: 'int-to-byte', 152 | 0x8E: 'int-to-char', 153 | 0x8F: 'int-to-short', 154 | 155 | 0x90: 'add-int', 156 | 0x91: 'sub-int', 157 | 0x92: 'mul-int', 158 | 0x93: 'div-int', 159 | 0x94: 'rem-int', 160 | 0x95: 'and-int', 161 | 0x96: 'or-int', 162 | 0x97: 'xor-int', 163 | 0x98: 'shl-int', 164 | 0x99: 'shr-int', 165 | 0x9A: 'ushr-int', 166 | 0x9B: 'add-long', 167 | 0x9C: 'sub-long', 168 | 0x9D: 'mul-long', 169 | 0x9E: 'div-long', 170 | 0x9F: 'rem-long', 171 | 172 | 0xA0: 'and-long', 173 | 0xA1: 'or-long', 174 | 0xA2: 'xor-long', 175 | 0xA3: 'shl-long', 176 | 0xA4: 'shr-long', 177 | 0xA5: 'ushr-long', 178 | 0xA6: 'add-float', 179 | 0xA7: 'sub-float', 180 | 0xA8: 'mul-float', 181 | 0xA9: 'div-float', 182 | 0xAA: 'rem-float', 183 | 0xAB: 'add-double', 184 | 0xAC: 'sub-double', 185 | 0xAD: 'mul-double', 186 | 0xAE: 'div-double', 187 | 0xAF: 'rem-double', 188 | 189 | 0xB0: 'add-int/2addr', 190 | 0xB1: 'sub-int/2addr', 191 | 0xB2: 'mul-int/2addr', 192 | 0xB3: 'div-int/2addr', 193 | 0xB4: 'rem-int/2addr', 194 | 0xB5: 'and-int/2addr', 195 | 0xB6: 'or-int/2addr', 196 | 0xB7: 'xor-int/2addr', 197 | 0xB8: 'shl-int/2addr', 198 | 0xB9: 'shr-int/2addr', 199 | 0xBA: 'ushr-int/2addr', 200 | 0xBB: 'add-long/2addr', 201 | 0xBC: 'sub-long/2addr', 202 | 0xBD: 'mul-long/2addr', 203 | 0xBE: 'div-long/2addr', 204 | 0xBF: 'rem-long/2addr', 205 | 206 | 0xC0: 'and-long/2addr', 207 | 0xC1: 'or-long/2addr', 208 | 0xC2: 'xor-long/2addr', 209 | 0xC3: 'shl-long/2addr', 210 | 0xC4: 'shr-long/2addr', 211 | 0xC5: 'ushr-long/2addr', 212 | 0xC6: 'add-float/2addr', 213 | 0xC7: 'sub-float/2addr', 214 | 0xC8: 'mul-float/2addr', 215 | 0xC9: 'div-float/2addr', 216 | 0xCA: 'rem-float/2addr', 217 | 0xCB: 'add-double/2addr', 218 | 0xCC: 'sub-double/2addr', 219 | 0xCD: 'mul-double/2addr', 220 | 0xCE: 'div-double/2addr', 221 | 0xCF: 'rem-double/2addr', 222 | 223 | 0xD0: 'add-int/lit16', 224 | 0xD1: 'sub-int/lit16', 225 | 0xD2: 'mul-int/lit16', 226 | 0xD3: 'div-int/lit16', 227 | 0xD4: 'rem-int/lit16', 228 | 0xD5: 'and-int/lit16', 229 | 0xD6: 'or-int/lit16', 230 | 0xD7: 'xor-int/lit16', 231 | 0xD8: 'add-int/lit8', 232 | 0xD9: 'sub-int/lit8', 233 | 0xDA: 'mul-int/lit8', 234 | 0xDB: 'div-int/lit8', 235 | 0xDC: 'rem-int/lit8', 236 | 0xDD: 'and-int/lit8', 237 | 0xDE: 'or-int/lit8', 238 | 0xDF: 'xor-int/lit8', 239 | 240 | 0xE0: 'shl-int/lit8', 241 | 0xE1: 'shr-int/lit8', 242 | 0xE2: 'ushr-int/lit8', 243 | 0xE3: 'unused', 244 | 0xE4: 'unused', 245 | 0xE5: 'unused', 246 | 0xE6: 'unused', 247 | 0xE7: 'unused', 248 | 0xE8: 'unused', 249 | 0xE9: 'unused', 250 | 0xEA: 'unused', 251 | 0xEB: 'unused', 252 | 0xEC: 'unused', 253 | 0xED: 'unused', 254 | 0xEE: 'execute-inline', 255 | 0xEF: 'unused', 256 | 257 | 0xF0: 'invoke-direct-empty', 258 | 0xF1: 'unused', 259 | 0xF2: 'iget-quick', 260 | 0xF3: 'iget-wide-quick', 261 | 0xF4: 'iget-object-quick', 262 | 0xF5: 'iput-quick', 263 | 0xF6: 'iput-wide-quick', 264 | 0xF7: 'iput-object-quick', 265 | 0xF8: 'invoke-virtual-quick', 266 | 0xF9: 'invoke-virtual-quick/range', 267 | 0xFA: 'invoke-super-quick', 268 | 0xFB: 'invoke-super-quick/range', 269 | 0xFC: 'unused', 270 | 0xFD: 'unused', 271 | 0xFE: 'unused', 272 | 0xFF: 'unused' 273 | } 274 | 275 | # type code list 276 | typecode = { 277 | 0x0000: 'TYPE_HEADER_ITEM', 278 | 0x0001: 'TYPE_STRING_ID_ITEM', 279 | 0x0002: 'TYPE_TYPE_ID_ITEM', 280 | 0x0003: 'TYPE_PROTO_ID_ITEM', 281 | 0x0004: 'TYPE_FIELD_ID_ITEM', 282 | 0x0005: 'TYPE_METHOD_ID_ITEM', 283 | 0x0006: 'TYPE_CLASS_DEF_ITEM', 284 | 0x1000: 'TYPE_MAP_LIST', 285 | 0x1001: 'TYPE_TYPE_LIST', 286 | 0x1002: 'TYPE_ANNOTATION_SET_REF_LIST', 287 | 0x1003: 'TYPE_ANNOTATION_SET_ITEM', 288 | 0x1004: 'TYPE_CLASS_DATA_ITEM', 289 | 0x2001: 'TYPE_CODE_ITEM', 290 | 0x2002: 'TYPE_STRING_DATA_ITEM', 291 | 0x2003: 'TYPE_DEBUG_INFO_ITEM', 292 | 0x2004: 'TYPE_ANNOTATION_ITEM', 293 | 0x2005: 'TYPE_ENCODED_ARRAY_ITEM', 294 | 0x2006: 'TYPE_ANNOTATIONS_DIRECTORY_ITEM' 295 | } 296 | 297 | access_flag = { 298 | 0x1: 'public', 299 | 0x2: 'private', 300 | 0x4: 'protected', 301 | 0x8: 'static', 302 | 0x10: 'final', 303 | 0x20: 'synchronized', 304 | 0x40: 'bridge', 305 | 0x80: 'varargs', 306 | 0x100: 'native', 307 | 0x200: 'interface', 308 | 0x400: 'abstract', 309 | 0x800: 'strictfp', 310 | 0x1000: 'synthetic', 311 | 0x2000: 'annotation', 312 | 0x4000: 'enum', 313 | 0x8000: 'unused', 314 | 0x10000: 'constructor', 315 | 0x20000: 'synchronized' 316 | } 317 | 318 | access_flag_classes = { 319 | 0x1: 'public', 320 | 0x2: 'private', 321 | 0x4: 'protected', 322 | 0x8: 'static', 323 | 0x10: 'final', 324 | 0x200: 'interface', 325 | 0x400: 'abstract', 326 | 0x1000: 'synthetic', 327 | 0x2000: 'annotation', 328 | 0x4000: 'enum', 329 | } 330 | 331 | access_flag_fields = { 332 | 0x1: 'public', 333 | 0x2: 'private', 334 | 0x4: 'protected', 335 | 0x8: 'static', 336 | 0x10: 'final', 337 | 0x40: 'volatile', 338 | 0x80: 'transient', 339 | 0x1000: 'synthetic', 340 | 0x4000: 'enum', 341 | } 342 | 343 | access_flag_methods = { 344 | 0x1: 'public', 345 | 0x2: 'private', 346 | 0x4: 'protected', 347 | 0x8: 'static', 348 | 0x10: 'final', 349 | 0x20: 'synchronized', 350 | 0x40: 'bridge', 351 | 0x80: 'varargs', 352 | 0x100: 'native', 353 | 0x400: 'abstract', 354 | 0x800: 'strictfp', 355 | 0x1000: 'synthetic', 356 | 0x10000: 'constructor', 357 | 0x20000: 'declared_synchronized', 358 | } 359 | 360 | ACCESS_ORDER = [ 361 | 0x1, 362 | 0x4, 363 | 0x2, 364 | 0x400, 365 | 0x8, 366 | 0x10, 367 | 0x80, 368 | 0x40, 369 | 0x20, 370 | 0x100, 371 | 0x800, 372 | 0x200, 373 | 0x1000, 374 | 0x2000, 375 | 0x4000, 376 | 0x10000, 377 | 0x20000 378 | ] 379 | 380 | field_descriptor = { 381 | 'V': 'void', 382 | 'B': 'byte', 383 | 'C': 'char', 384 | 'D': 'double', 385 | 'F': 'float', 386 | 'I': 'int', 387 | 'J': 'long', 388 | 'S': 'short', 389 | 'Z': 'boolean', 390 | '[': 'array', 391 | } 392 | 393 | type_descriptor = { 394 | 'V': 'void', 395 | 'Z': 'boolean', 396 | 'B': 'byte', 397 | 'S': 'short', 398 | 'C': 'char', 399 | 'I': 'int', 400 | 'J': 'long', 401 | 'F': 'float', 402 | 'D': 'double', 403 | 'L': 'class', 404 | '[': 'array' 405 | } 406 | 407 | visibility_values = { 408 | 0x00: 'VISIBILITY_BUILD', 409 | 0x01: 'VISIBILITY_RUNTIME', 410 | 0x02: 'VISIBILITY_SYSTEM' 411 | } 412 | 413 | 414 | value_types = { 415 | 0x00: 'VALUE_BYTE', 416 | 0x02: 'VALUE_SHORT', 417 | 0x03: 'VALUE_CHAR', 418 | 0x04: 'VALUE_INT', 419 | 0x06: 'VALUE_LONG', 420 | 0x10: 'VALUE_FLOAT', 421 | 0x11: 'VALUE_DOUBLE', 422 | 0x17: 'VALUE_STRING', 423 | 0x18: 'VALUE_TYPE', 424 | 0x19: 'VALUE_FIELD', 425 | 0x1a: 'VALUE_METHOD', 426 | 0x1b: 'VALUE_ENUM', 427 | 0x1c: 'VALUE_ARRAY', 428 | 0x1d: 'VALUE_ANNOTATION', 429 | 0x1e: 'VALUE_NULL', 430 | 0x1f: 'VALUE_BOOLEAN' 431 | } 432 | -------------------------------------------------------------------------------- /dexparser/__init__.py: -------------------------------------------------------------------------------- 1 | from io import BytesIO 2 | from dexparser import disassembler 3 | from dexparser.errors import InsufficientParameterError, IsNotAPKFileFormatError 4 | from dexparser.utils import uleb128_value, encoded_field, encoded_method, encoded_annotation 5 | from zipfile import ZipFile, is_zipfile 6 | 7 | import struct 8 | import mmap 9 | import os 10 | 11 | 12 | class Dexparser(object): 13 | """DEX file format parser class 14 | :param string filedir: DEX file path 15 | :param bytes fileobj: DEX file object 16 | """ 17 | 18 | def __init__(self, filedir=None, fileobj=None): 19 | if not filedir and not fileobj: 20 | raise InsufficientParameterError('fileobj or filedir parameter required.') 21 | 22 | if filedir: 23 | if not os.path.isfile(filedir): 24 | raise FileNotFoundError 25 | 26 | with open(filedir, 'rb') as f: 27 | self.data = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) 28 | 29 | if fileobj: 30 | self.data = fileobj 31 | 32 | self.header_data = { 33 | 'magic': self.data[0:8], 34 | 'checksum': struct.unpack('>> Dexparser(filedir='path/to/classes.dex').header 66 | {'magic': 'dex\x035' ...} 67 | """ 68 | return self.header_data 69 | 70 | @property 71 | def checksum(self): 72 | """Get checksum value of DEX file 73 | 74 | :returns: hexlify value of checksum 75 | 76 | example: 77 | >>> Dexparser(filedir='path/to/classes.dex').checksum 78 | 0x30405060 79 | """ 80 | return "%x" % self.header_data.get('checksum') 81 | 82 | def get_strings(self): 83 | """Get string items from DEX file 84 | 85 | :returns: strings extracted from string_data_item section 86 | 87 | example: 88 | >>> dex = Dexparser(filedir='path/to/classes.dex') 89 | >>> dex.get_strings() 90 | ['Ljava/utils/getJavaUtils', ...] 91 | """ 92 | strings = [] 93 | string_ids_off = self.header_data['string_ids_off'] 94 | 95 | for i in range(self.header_data['string_ids_size']): 96 | offset = struct.unpack('>> dex = Dexparser(filedir='path/to/classes.dex') 110 | >>> dex.get_typeids() 111 | [133, 355, 773, 494, ...] 112 | """ 113 | typeids = [] 114 | offset = self.header_data['type_ids_off'] 115 | 116 | for i in range(self.header_data['type_ids_size']): 117 | idx = struct.unpack('>> dex = Dexparser(filedir='path/to/classes.dex') 129 | >>> dex.get_methods() 130 | [{'class_idx': 132, 'proto_idx': 253, 'name_idx': 3005}, ...] 131 | """ 132 | methods = [] 133 | offset = self.header_data['method_ids_off'] 134 | 135 | for i in range(self.header_data['method_ids_size']): 136 | class_idx = struct.unpack('>> dex = Dexparser(filedir='path/to/classes.dex') 150 | >>> dex.get_protoids() 151 | [{'shorty_idx': 3000, 'return_type_idx': 330, 'param_off': 0}, ...] 152 | """ 153 | protoids = [] 154 | offset = self.header_data['proto_ids_off'] 155 | 156 | for i in range(self.header_data['proto_ids_size']): 157 | shorty_idx = struct.unpack('>> dex = Dexparser(filedir='path/to/classes.dex') 171 | >>> dex.get_fieldids() 172 | [{'class_idx': 339, 'type_idx': 334, 'name_idx': 340}, ...] 173 | """ 174 | fieldids = [] 175 | offset = self.header_data['field_ids_off'] 176 | 177 | for i in range(self.header_data['field_ids_size']): 178 | class_idx = struct.unpack('>> dex = Dexparser(filedir='path/to/classes.dex') 192 | >>> dex.get_classdef_data() 193 | [ 194 | { 195 | 'class_idx': 3049, 196 | 'access_flags': 4000, 197 | 'superclass_idx': 200, 198 | 'interfaces_off': 343, 199 | 'source_file_idx': 3182, 200 | 'annotation_off': 343, 201 | 'class_data_off': 345, 202 | 'static_values_off': 8830 203 | }, 204 | ... 205 | ] 206 | """ 207 | classdef_data = [] 208 | offset = self.header_data['class_defs_off'] 209 | 210 | for i in range(self.header_data['class_defs_size']): 211 | class_idx = struct.unpack('>> dex = Dexparser(filedir='path/to/classes.dex') 241 | >>> dex.get_class_data(offset=3022) 242 | { 243 | 'static_fields': [ 244 | { 245 | 'diff': 30, 'access_flags': 4000 246 | } 247 | ], 248 | 'instance_fields': [ 249 | { 250 | 'diff': 32, 'access_flags': 4000 251 | } 252 | ], 253 | 'direct_methods': [ 254 | { 255 | 'diff': 30, 'access_flags': 4000, 'code_off': 384304 256 | } 257 | ], 258 | 'virtual_methods': [ 259 | { 260 | 'diff': 63, 'access_flags': 4000, 'code_off': 483933 261 | } 262 | ] 263 | } 264 | """ 265 | static_fields = [] 266 | instance_fields = [] 267 | direct_methods = [] 268 | virtual_methods = [] 269 | 270 | static_field_size, sf_size = uleb128_value(self.data, offset) 271 | offset += sf_size 272 | instance_field_size, if_size = uleb128_value(self.data, offset) 273 | offset += if_size 274 | direct_method_size, dm_size = uleb128_value(self.data, offset) 275 | offset += dm_size 276 | virtual_method_size, vm_size = uleb128_value(self.data, offset) 277 | offset += vm_size 278 | 279 | for i in range(static_field_size): 280 | field_idx_diff, access_flags, size = encoded_field(self.data, offset) 281 | if i == 0: 282 | diff = field_idx_diff 283 | else: 284 | diff += field_idx_diff 285 | 286 | static_fields.append({'diff': diff, 'access_flags': access_flags}) 287 | offset += size 288 | 289 | for i in range(instance_field_size): 290 | field_idx_diff, access_flags, size = encoded_field(self.data, offset) 291 | if i == 0: 292 | diff = field_idx_diff 293 | else: 294 | diff += field_idx_diff 295 | 296 | instance_fields.append({'diff': diff, 'access_flags': access_flags}) 297 | offset += size 298 | 299 | for i in range(direct_method_size): 300 | method_idx_diff, access_flags, code_off, size = encoded_method(self.data, offset) 301 | if i == 0: 302 | diff = method_idx_diff 303 | else: 304 | diff += method_idx_diff 305 | 306 | direct_methods.append({ 307 | 'diff': diff, 308 | 'access_flags': access_flags, 309 | 'code_off': code_off 310 | }) 311 | offset += size 312 | 313 | for i in range(virtual_method_size): 314 | method_idx_diff, access_flags, code_off, size = encoded_method(self.data, offset) 315 | if i == 0: 316 | diff = method_idx_diff 317 | else: 318 | diff += method_idx_diff 319 | 320 | virtual_methods.append({ 321 | 'diff': diff, 322 | 'access_flags': access_flags, 323 | 'code_off': code_off 324 | }) 325 | offset += size 326 | 327 | return { 328 | 'static_fields': static_fields, 329 | 'instance_fields': instance_fields, 330 | 'direct_methods': direct_methods, 331 | 'virtual_methods': virtual_methods 332 | } 333 | 334 | def get_annotations(self, offset): 335 | """Get annotation data from DEX file 336 | 337 | :param integer offset: annotation_off offset value 338 | :returns: specific data of annotation 339 | 340 | example: 341 | >>> dex = Dexparser(filedir='path/to/classes.dex') 342 | >>> dex.get_annotations(offset=3022) 343 | { 344 | 'visibility': 3403, 345 | 'type_idx_diff': 3024, 346 | 'size_diff': 64, 347 | 'name_idx_diff': 30, 348 | 'value_type': 302, 349 | 'encoded_value': 7483 350 | } 351 | """ 352 | class_annotation_off = struct.unpack('>> dex = Dexparser(filedir='path/to/classes.dex') 377 | >>> dex.get_static_values(offset=3022) 378 | [b'android.annotation', 0.0, False, None] 379 | """ 380 | size, size_off = uleb128_value(self.data, offset) 381 | offset += size_off 382 | result = [] 383 | 384 | _strings = self.get_strings() 385 | 386 | for _ in range(size): 387 | value_arg = self.data[offset] >> 5 388 | value_type = self.data[offset] & 0b11111 389 | offset += 1 390 | 391 | if value_type == 0x00 or \ 392 | value_type == 0x02 or \ 393 | value_type == 0x03 or \ 394 | value_type == 0x04 or \ 395 | value_type == 0x06 or \ 396 | value_type == 0x18 or \ 397 | value_type == 0x19 or \ 398 | value_type == 0x1a or \ 399 | value_type == 0x1b: 400 | # VALUE_BYTE, VALUE_SHORT, VALUE_CHAR, VALUE_INT, VALUE_LONG, VALUE_TYPE 401 | # VALUE_TYPE, VALUE_FIELD, VALUE_METHOD, VALUE_ENUM 402 | value = 0 403 | for i in range(value_arg + 1): 404 | value |= (self.data[offset] << 8 * i) 405 | offset += 1 406 | result.append(value) 407 | 408 | elif value_type == 0x10 or value_type == 0x11: # VALUE_FLOAT, VALUE_DOUBLE 409 | value = 0 410 | for i in range(value_arg + 1): 411 | value |= (self.data[offset] << 8 * i) 412 | offset += 1 413 | result.append(float(value)) 414 | 415 | elif value_type == 0x17: # VALUE_STRING 416 | string_off = 0 417 | for i in range(value_arg + 1): 418 | string_off |= (self.data[offset] << 8 * i) 419 | offset += 1 420 | result.append(_strings[string_off]) 421 | 422 | elif value_type == 0x1c: # VALUE_ARRAY 423 | result.append(self.get_static_values(offset)) 424 | 425 | elif value_type == 0x1d: # VALUE_ANNOTATION 426 | result.append( 427 | encoded_annotation(self.data, offset) 428 | ) 429 | 430 | elif value_type == 0x1f: # VALUE_BOOLEAN 431 | result.append(bool(value_arg)) 432 | 433 | else: # VALUE_NULL 434 | result.append(None) 435 | 436 | return result 437 | 438 | 439 | class APKParser(object): 440 | """APK file format parser class 441 | :param string filedir: APK file path 442 | :param bytes fileobj: APK file object 443 | :param boolean deepscan: Scan all assets of APK file for detect adex file 444 | """ 445 | 446 | def __init__(self, filedir=None, fileobj=None, deepscan=False): 447 | if not filedir and not fileobj: 448 | raise InsufficientParameterError('fileobj or filedir parameter required.') 449 | 450 | if filedir: 451 | if not os.path.isfile(filedir): 452 | raise FileNotFoundError 453 | 454 | if not is_zipfile(filedir): 455 | raise IsNotAPKFileFormatError("{} is not an APK file format.".format(filedir)) 456 | 457 | self.zfile = ZipFile(filedir) 458 | 459 | if fileobj: 460 | if not is_zipfile(BytesIO(fileobj)): 461 | raise IsNotAPKFileFormatError("Invalid APK file format.") 462 | 463 | self.zfile = ZipFile(BytesIO(fileobj)) 464 | 465 | self.dexfiles = {} 466 | 467 | if deepscan: 468 | for filename in self.zfile.namelist(): 469 | stream = self.zfile.read(filename) 470 | if len(stream) < 8: 471 | continue 472 | 473 | if stream[0:4] == "dex\x0a": 474 | self.dexfiles[filename] = DEXParser(fileobj=stream) 475 | 476 | else: 477 | for filename in self.zfile.namelist(): 478 | if filename.endswith(".dex"): 479 | self.dexfiles[filename] = DEXParser(fileobj=self.zfile.read(filename)) 480 | 481 | @property 482 | def is_multidex(self): 483 | """Detect if APK is a multidex 484 | https://developer.android.com/studio/build/multidex 485 | 486 | :returns: boolean 487 | 488 | example: 489 | >>> APKParser(filedir='path/to/file.apk').is_multidex 490 | True 491 | """ 492 | return len(self.dexfiles.keys()) > 1 493 | 494 | def get_dex(self, filename="classes.dex"): 495 | """Get dex file with DEX parsed object 496 | 497 | :params: name of dexfile (default: classes.dex) 498 | :returns: DEXParser object 499 | 500 | example: 501 | >>> APKParser(filedir='path/to/file.apk').get_dex() 502 | True 503 | """ 504 | return self.dexfiles[filename] 505 | 506 | def get_all_dex_filenames(self): 507 | """Get all name of dex files 508 | :returns: list of dex filenames 509 | 510 | example: 511 | >>> APKParser(filedir='path/to/file.apk').get_all_dex_filenames() 512 | ['classes.dex', 'classes1.dex'] 513 | """ 514 | return list(self.dexfiles.keys()) 515 | 516 | 517 | class AABParser(APKParser): 518 | """AAB (Android App Bundle) file format parser class 519 | :param string filedir: AAB file path 520 | :param bytes fileobj: AAB file object 521 | :param boolean deepscan: Scan all assets of AAB file for detect adex file 522 | """ 523 | pass 524 | 525 | 526 | class DEXParser(Dexparser): 527 | """DEX file format parser subclass 528 | :param string filedir: DEX file path 529 | :param bytes fileobj: DEX file object 530 | """ 531 | pass 532 | --------------------------------------------------------------------------------