├── dex-method-counts.bat ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── src ├── com │ └── android │ │ └── dexdeps │ │ ├── DexDataException.java │ │ ├── FieldRef.java │ │ ├── ClassRef.java │ │ ├── MethodRef.java │ │ ├── Output.java │ │ └── DexData.java └── info │ └── persistent │ └── dex │ ├── DexCount.java │ ├── DexFieldCounts.java │ ├── DexMethodCounts.java │ └── Main.java ├── README.md ├── gradlew.bat ├── dex-method-counts ├── gradlew └── LICENSE /dex-method-counts.bat: -------------------------------------------------------------------------------- 1 | java -jar build\jar\dex-method-counts.jar %* 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | // Sets the output JAR filename 2 | rootProject.name = 'dex-method-counts' 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mihaip/dex-method-counts/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Output directory for ANT and Gradle 2 | build/ 3 | 4 | # Intellij project files 5 | *.iml 6 | .idea/ 7 | 8 | #Gradle 9 | .gradle/ 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Sep 28 23:24:45 AEST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.1-all.zip 7 | -------------------------------------------------------------------------------- /src/com/android/dexdeps/DexDataException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.dexdeps; 18 | 19 | /** 20 | * Bad data found inside a DEX file. 21 | */ 22 | public class DexDataException extends RuntimeException { 23 | } 24 | -------------------------------------------------------------------------------- /src/com/android/dexdeps/FieldRef.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.dexdeps; 18 | 19 | public class FieldRef { 20 | private String mDeclClass, mFieldType, mFieldName; 21 | 22 | /** 23 | * Initializes a new field reference. 24 | */ 25 | public FieldRef(String declClass, String fieldType, String fieldName) { 26 | mDeclClass = declClass; 27 | mFieldType = fieldType; 28 | mFieldName = fieldName; 29 | } 30 | 31 | /** 32 | * Gets the name of the field's declaring class. 33 | */ 34 | public String getDeclClassName() { 35 | return mDeclClass; 36 | } 37 | 38 | /** 39 | * Gets the type name. Examples: "Ljava/lang/String;", "[I". 40 | */ 41 | public String getTypeName() { 42 | return mFieldType; 43 | } 44 | 45 | /** 46 | * Gets the field name. 47 | */ 48 | public String getName() { 49 | return mFieldName; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/com/android/dexdeps/ClassRef.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.dexdeps; 18 | 19 | import java.util.ArrayList; 20 | 21 | public class ClassRef { 22 | private String mClassName; 23 | private ArrayList mFieldRefs; 24 | private ArrayList mMethodRefs; 25 | 26 | /** 27 | * Initializes a new class reference. 28 | */ 29 | public ClassRef(String className) { 30 | mClassName = className; 31 | mFieldRefs = new ArrayList(); 32 | mMethodRefs = new ArrayList(); 33 | } 34 | 35 | /** 36 | * Adds the field to the field list. 37 | */ 38 | public void addField(FieldRef fref) { 39 | mFieldRefs.add(fref); 40 | } 41 | 42 | /** 43 | * Returns the field list as an array. 44 | */ 45 | public FieldRef[] getFieldArray() { 46 | return mFieldRefs.toArray(new FieldRef[mFieldRefs.size()]); 47 | } 48 | 49 | /** 50 | * Adds the method to the method list. 51 | */ 52 | public void addMethod(MethodRef mref) { 53 | mMethodRefs.add(mref); 54 | } 55 | 56 | /** 57 | * Returns the method list as an array. 58 | */ 59 | public MethodRef[] getMethodArray() { 60 | return mMethodRefs.toArray(new MethodRef[mMethodRefs.size()]); 61 | } 62 | 63 | /** 64 | * Gets the class name. 65 | */ 66 | public String getName() { 67 | return mClassName; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dex-method-counts 2 | 3 | Simple tool to output per-package method counts in an Android DEX executable grouped by package, to aid in getting under the 65,536 referenced method limit. More details are [in this blog post](http://blog.persistent.info/2014/05/per-package-method-counts-for-androids.html). 4 | 5 | To run it with Ant: 6 | 7 | $ ant jar 8 | $ ./dex-method-counts path/to/App.apk # or .zip or .dex or directory 9 | 10 | or with Gradle: 11 | 12 | $ ./gradlew assemble 13 | $ ./dex-method-counts path/to/App.apk # or .zip or .dex or directory 14 | 15 | on Windows: 16 | 17 | $ gradlew assemble 18 | $ dex-method-counts.bat path\to\App.apk 19 | 20 | You'll see output of the form: 21 | 22 | Read in 65490 method IDs. 23 | : 65490 24 | : 3 25 | android: 6837 26 | accessibilityservice: 6 27 | bluetooth: 2 28 | content: 248 29 | pm: 22 30 | res: 45 31 | ... 32 | com: 53881 33 | adjust: 283 34 | sdk: 283 35 | codebutler: 65 36 | android_websockets: 65 37 | ... 38 | Overall method count: 65490 39 | 40 | Supported options are: 41 | 42 | * `--count-fields`: Provide the field count instead of the method count. 43 | * `--include-classes`: Treat classes as packages and provide per-class method counts. One use-case is for protocol buffers where all generated code in a package ends up in a single class. 44 | * `--package-filter=...`: Only consider methods whose fully qualified name starts with this prefix. 45 | * `--max-depth=...`: Limit how far into package paths (or inner classes, with `--include-classes`) counts should be reported for. 46 | * `--filter=[all|defined_only|referenced_only]`: Whether to count all methods (the default), just those defined in the input file, or just those that are referenced in it. Note that referenced methods count against the 64K method limit too. 47 | * `--output-style=[flat|tree]`: Print the output as a list or as an indented tree. 48 | 49 | The DEX file parsing is based on the `dexdeps` tool from 50 | [the Android source tree](https://android.googlesource.com/platform/dalvik.git/+/master/tools/dexdeps/). 51 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /src/info/persistent/dex/DexCount.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed under the Apache License, Version 2.0 (the "License"); 3 | * you may not use this file except in compliance with the License. 4 | * You may obtain a copy of the License at 5 | * 6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package info.persistent.dex; 16 | 17 | import com.android.dexdeps.DexData; 18 | 19 | import java.io.PrintStream; 20 | import java.util.Map; 21 | import java.util.NavigableMap; 22 | import java.util.TreeMap; 23 | 24 | public abstract class DexCount { 25 | 26 | static final PrintStream out = System.out; 27 | final OutputStyle outputStyle; 28 | final Node packageTree; 29 | final Map packageCount; 30 | int overallCount = 0; 31 | 32 | DexCount(OutputStyle outputStyle) { 33 | this.outputStyle = outputStyle; 34 | packageTree = this.outputStyle == OutputStyle.TREE ? new Node() : null; 35 | packageCount = this.outputStyle == OutputStyle.FLAT 36 | ? new TreeMap() : null; 37 | } 38 | 39 | public abstract void generate( 40 | DexData dexData, boolean includeClasses, String packageFilter, int maxDepth, Filter filter); 41 | 42 | class IntHolder { 43 | 44 | int value; 45 | } 46 | 47 | enum Filter { 48 | ALL, 49 | DEFINED_ONLY, 50 | REFERENCED_ONLY 51 | } 52 | 53 | enum OutputStyle { 54 | TREE { 55 | @Override 56 | void output(DexCount counts) { 57 | counts.packageTree.output(""); 58 | } 59 | }, 60 | FLAT { 61 | @Override 62 | void output(DexCount counts) { 63 | for (Map.Entry e : counts.packageCount.entrySet()) { 64 | String packageName = e.getKey(); 65 | if (packageName == "") { 66 | packageName = ""; 67 | } 68 | System.out.printf("%6s %s\n", e.getValue().value, packageName); 69 | } 70 | } 71 | }; 72 | 73 | abstract void output(DexCount counts); 74 | } 75 | 76 | void output() { 77 | outputStyle.output(this); 78 | } 79 | 80 | int getOverallCount() { 81 | return overallCount; 82 | } 83 | 84 | static class Node { 85 | 86 | int count = 0; 87 | NavigableMap children = new TreeMap(); 88 | 89 | void output(String indent) { 90 | if (indent.length() == 0) { 91 | out.println(": " + count); 92 | } 93 | indent += " "; 94 | for (String name : children.navigableKeySet()) { 95 | Node child = children.get(name); 96 | out.println(indent + name + ": " + child.count); 97 | child.output(indent); 98 | } 99 | } 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/com/android/dexdeps/MethodRef.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.dexdeps; 18 | 19 | import java.util.Arrays; 20 | 21 | public class MethodRef { 22 | private String mDeclClass, mReturnType, mMethodName; 23 | private String[] mArgTypes; 24 | 25 | /** 26 | * Initializes a new field reference. 27 | */ 28 | public MethodRef(String declClass, String[] argTypes, String returnType, 29 | String methodName) { 30 | mDeclClass = declClass; 31 | mArgTypes = argTypes; 32 | mReturnType = returnType; 33 | mMethodName = methodName; 34 | } 35 | 36 | /** 37 | * Gets the name of the method's declaring class. 38 | */ 39 | public String getDeclClassName() { 40 | return mDeclClass; 41 | } 42 | 43 | /** 44 | * Gets the method's descriptor. 45 | */ 46 | public String getDescriptor() { 47 | return descriptorFromProtoArray(mArgTypes, mReturnType); 48 | } 49 | 50 | /** 51 | * Gets the method's name. 52 | */ 53 | public String getName() { 54 | return mMethodName; 55 | } 56 | 57 | /** 58 | * Gets an array of method argument types. 59 | */ 60 | public String[] getArgumentTypeNames() { 61 | return mArgTypes; 62 | } 63 | 64 | /** 65 | * Gets the method's return type. Examples: "Ljava/lang/String;", "[I". 66 | */ 67 | public String getReturnTypeName() { 68 | return mReturnType; 69 | } 70 | 71 | /** 72 | * Returns the method descriptor, given the argument and return type 73 | * prototype strings. 74 | */ 75 | private static String descriptorFromProtoArray(String[] protos, 76 | String returnType) { 77 | StringBuilder builder = new StringBuilder(); 78 | 79 | builder.append("("); 80 | for (int i = 0; i < protos.length; i++) { 81 | builder.append(protos[i]); 82 | } 83 | 84 | builder.append(")"); 85 | builder.append(returnType); 86 | 87 | return builder.toString(); 88 | } 89 | 90 | @Override public boolean equals(Object o) { 91 | if (!(o instanceof MethodRef)) { 92 | return false; 93 | } 94 | MethodRef other = (MethodRef) o; 95 | return other.mDeclClass.equals(mDeclClass) && 96 | other.mReturnType.equals(mReturnType) && 97 | other.mMethodName.equals(mMethodName) && 98 | Arrays.equals(other.mArgTypes, mArgTypes); 99 | } 100 | 101 | @Override public int hashCode() { 102 | return mDeclClass.hashCode() ^ mReturnType.hashCode() ^ 103 | mMethodName.hashCode() ^ Arrays.hashCode(mArgTypes); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /dex-method-counts: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright (C) 2009 The Android Open Source Project 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # ========================================== 18 | # BEGIN sh-realpath 19 | # see https://github.com/mkropat/sh-realpath 20 | # ========================================== 21 | # Copyright (c) 2014 Michael Kropat 22 | # Permission is hereby granted, free of charge, to any person obtaining a copy 23 | # of this software and associated documentation files (the "Software"), to deal 24 | # in the Software without restriction, including without limitation the rights 25 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 26 | # copies of the Software, and to permit persons to whom the Software is 27 | # furnished to do so, subject to the following conditions: 28 | 29 | realpath() { 30 | canonicalize_path "$(resolve_symlinks "$1")" 31 | } 32 | 33 | resolve_symlinks() { 34 | _resolve_symlinks "$1" 35 | } 36 | 37 | _resolve_symlinks() { 38 | _assert_no_path_cycles "$@" || return 39 | 40 | local dir_context path 41 | path=$(readlink -- "$1") 42 | if [ $? -eq 0 ]; then 43 | dir_context=$(dirname -- "$1") 44 | _resolve_symlinks "$(_prepend_dir_context_if_necessary "$dir_context" "$path")" "$@" 45 | else 46 | printf '%s\n' "$1" 47 | fi 48 | } 49 | 50 | _prepend_dir_context_if_necessary() { 51 | if [ "$1" = . ]; then 52 | printf '%s\n' "$2" 53 | else 54 | _prepend_path_if_relative "$1" "$2" 55 | fi 56 | } 57 | 58 | _prepend_path_if_relative() { 59 | case "$2" in 60 | /* ) printf '%s\n' "$2" ;; 61 | * ) printf '%s\n' "$1/$2" ;; 62 | esac 63 | } 64 | 65 | _assert_no_path_cycles() { 66 | local target path 67 | 68 | target=$1 69 | shift 70 | 71 | for path in "$@"; do 72 | if [ "$path" = "$target" ]; then 73 | return 1 74 | fi 75 | done 76 | } 77 | 78 | canonicalize_path() { 79 | if [ -d "$1" ]; then 80 | _canonicalize_dir_path "$1" 81 | else 82 | _canonicalize_file_path "$1" 83 | fi 84 | } 85 | 86 | _canonicalize_dir_path() { 87 | (cd "$1" 2>/dev/null && pwd -P) 88 | } 89 | 90 | _canonicalize_file_path() { 91 | local dir file 92 | dir=$(dirname -- "$1") 93 | file=$(basename -- "$1") 94 | (cd "$dir" 2>/dev/null && printf '%s/%s\n' "$(pwd -P)" "$file") 95 | } 96 | # ========================================== 97 | # END sh-realpath 98 | # see https://github.com/mkropat/sh-realpath 99 | # ========================================== 100 | 101 | if [ -h ${BASH_SOURCE[0]} ] 102 | then 103 | # If the file is a symlink, read the real location of the file and cd to it 104 | curdir="$( cd "$(dirname $( realpath "${BASH_SOURCE[0]}" ) )" && pwd )" 105 | else 106 | curdir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 107 | fi 108 | libdir="$curdir/build/jar" 109 | jarfile="dex-method-counts.jar" 110 | if [ ! -r "$libdir/$jarfile" ] 111 | then 112 | echo `basename "$prog"`": can't find $jarfile" 113 | exit 1 114 | fi 115 | 116 | javaOpts="" 117 | 118 | # Alternatively, this will extract any parameter "-Jxxx" from the command line 119 | # and pass them to Java (instead of to dexdeps). 120 | while expr "x$1" : 'x-J' >/dev/null; do 121 | opt=`expr "$1" : '-J\(.*\)'` 122 | javaOpts="${javaOpts} -${opt}" 123 | shift 124 | done 125 | 126 | if [ "$OSTYPE" = "cygwin" ] ; then 127 | jarpath=`cygpath -w "$libdir/$jarfile"` 128 | else 129 | jarpath="$libdir/$jarfile" 130 | fi 131 | 132 | exec java $javaOpts -jar "$jarpath" "$@" 133 | -------------------------------------------------------------------------------- /src/info/persistent/dex/DexFieldCounts.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed under the Apache License, Version 2.0 (the "License"); 3 | * you may not use this file except in compliance with the License. 4 | * You may obtain a copy of the License at 5 | * 6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package info.persistent.dex; 16 | 17 | import com.android.dexdeps.*; 18 | 19 | import java.util.*; 20 | 21 | public class DexFieldCounts extends DexCount { 22 | 23 | DexFieldCounts(OutputStyle outputStyle) { 24 | super(outputStyle); 25 | } 26 | 27 | @Override 28 | public void generate(DexData dexData, boolean includeClasses, String packageFilter, int maxDepth, Filter filter) { 29 | FieldRef[] fieldRefs = getFieldRefs(dexData, filter); 30 | 31 | for (FieldRef fieldRef : fieldRefs) { 32 | String classDescriptor = fieldRef.getDeclClassName(); 33 | String packageName = includeClasses ? 34 | Output.descriptorToDot(classDescriptor).replace('$', '.') : 35 | Output.packageNameOnly(classDescriptor); 36 | if (packageFilter != null && 37 | !packageName.startsWith(packageFilter)) { 38 | continue; 39 | } 40 | overallCount++; 41 | if (outputStyle == OutputStyle.TREE) { 42 | String packageNamePieces[] = packageName.split("\\."); 43 | Node packageNode = packageTree; 44 | for (int i = 0; i < packageNamePieces.length && i < maxDepth; i++) { 45 | packageNode.count++; 46 | String name = packageNamePieces[i]; 47 | if (packageNode.children.containsKey(name)) { 48 | packageNode = packageNode.children.get(name); 49 | } else { 50 | Node childPackageNode = new Node(); 51 | if (name.length() == 0) { 52 | // This field is declared in a class that is part of the default package. 53 | name = ""; 54 | } 55 | packageNode.children.put(name, childPackageNode); 56 | packageNode = childPackageNode; 57 | } 58 | } 59 | packageNode.count++; 60 | } else if (outputStyle == OutputStyle.FLAT) { 61 | IntHolder count = packageCount.get(packageName); 62 | if (count == null) { 63 | count = new IntHolder(); 64 | packageCount.put(packageName, count); 65 | } 66 | count.value++; 67 | } 68 | } 69 | } 70 | 71 | private static FieldRef[] getFieldRefs(DexData dexData, Filter filter) { 72 | FieldRef[] fieldRefs = dexData.getFieldRefs(); 73 | out.println("Read in " + fieldRefs.length + " field IDs."); 74 | if (filter == Filter.ALL) { 75 | return fieldRefs; 76 | } 77 | 78 | ClassRef[] externalClassRefs = dexData.getExternalReferences(); 79 | out.println("Read in " + externalClassRefs.length + " external class references."); 80 | Set externalFieldRefs = new HashSet(); 81 | for (ClassRef classRef : externalClassRefs) { 82 | Collections.addAll(externalFieldRefs, classRef.getFieldArray()); 83 | } 84 | out.println("Read in " + externalFieldRefs.size() + " external field references."); 85 | List filteredFieldRefs = new ArrayList(); 86 | for (FieldRef FieldRef : fieldRefs) { 87 | boolean isExternal = externalFieldRefs.contains(FieldRef); 88 | if ((filter == Filter.DEFINED_ONLY && !isExternal) 89 | || (filter == Filter.REFERENCED_ONLY && isExternal)) { 90 | filteredFieldRefs.add(FieldRef); 91 | } 92 | } 93 | out.println("Filtered to " + filteredFieldRefs.size() + " " + 94 | (filter == Filter.DEFINED_ONLY ? "defined" : "referenced") + " field IDs."); 95 | return filteredFieldRefs.toArray(new FieldRef[filteredFieldRefs.size()]); 96 | } 97 | 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/info/persistent/dex/DexMethodCounts.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed under the Apache License, Version 2.0 (the "License"); 3 | * you may not use this file except in compliance with the License. 4 | * You may obtain a copy of the License at 5 | * 6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package info.persistent.dex; 16 | 17 | import com.android.dexdeps.ClassRef; 18 | import com.android.dexdeps.DexData; 19 | import com.android.dexdeps.MethodRef; 20 | import com.android.dexdeps.Output; 21 | 22 | import java.util.*; 23 | 24 | public class DexMethodCounts extends DexCount { 25 | 26 | DexMethodCounts(OutputStyle outputStyle) { 27 | super(outputStyle); 28 | } 29 | 30 | @Override 31 | public void generate(DexData dexData, boolean includeClasses, String packageFilter, int maxDepth, Filter filter) { 32 | MethodRef[] methodRefs = getMethodRefs(dexData, filter); 33 | 34 | for (MethodRef methodRef : methodRefs) { 35 | String classDescriptor = methodRef.getDeclClassName(); 36 | String packageName = includeClasses ? 37 | Output.descriptorToDot(classDescriptor).replace('$', '.') : 38 | Output.packageNameOnly(classDescriptor); 39 | if (packageFilter != null && 40 | !packageName.startsWith(packageFilter)) { 41 | continue; 42 | } 43 | overallCount++; 44 | if (outputStyle == OutputStyle.TREE) { 45 | String packageNamePieces[] = packageName.split("\\."); 46 | Node packageNode = packageTree; 47 | for (int i = 0; i < packageNamePieces.length && i < maxDepth; i++) { 48 | packageNode.count++; 49 | String name = packageNamePieces[i]; 50 | if (packageNode.children.containsKey(name)) { 51 | packageNode = packageNode.children.get(name); 52 | } else { 53 | Node childPackageNode = new Node(); 54 | if (name.length() == 0) { 55 | // This method is declared in a class that is part of the default package. 56 | // Typical examples are methods that operate on arrays of primitive data types. 57 | name = ""; 58 | } 59 | packageNode.children.put(name, childPackageNode); 60 | packageNode = childPackageNode; 61 | } 62 | } 63 | packageNode.count++; 64 | } else if (outputStyle == OutputStyle.FLAT) { 65 | IntHolder count = packageCount.get(packageName); 66 | if (count == null) { 67 | count = new IntHolder(); 68 | packageCount.put(packageName, count); 69 | } 70 | count.value++; 71 | } 72 | } 73 | } 74 | 75 | private static MethodRef[] getMethodRefs(DexData dexData, Filter filter) { 76 | MethodRef[] methodRefs = dexData.getMethodRefs(); 77 | out.println("Read in " + methodRefs.length + " method IDs."); 78 | if (filter == Filter.ALL) { 79 | return methodRefs; 80 | } 81 | 82 | ClassRef[] externalClassRefs = dexData.getExternalReferences(); 83 | out.println("Read in " + externalClassRefs.length + 84 | " external class references."); 85 | Set externalMethodRefs = new HashSet(); 86 | for (ClassRef classRef : externalClassRefs) { 87 | Collections.addAll(externalMethodRefs, classRef.getMethodArray()); 88 | } 89 | out.println("Read in " + externalMethodRefs.size() + 90 | " external method references."); 91 | List filteredMethodRefs = new ArrayList(); 92 | for (MethodRef methodRef : methodRefs) { 93 | boolean isExternal = externalMethodRefs.contains(methodRef); 94 | if ((filter == Filter.DEFINED_ONLY && !isExternal) || 95 | (filter == Filter.REFERENCED_ONLY && isExternal)) { 96 | filteredMethodRefs.add(methodRef); 97 | } 98 | } 99 | out.println("Filtered to " + filteredMethodRefs.size() + " " + 100 | (filter == Filter.DEFINED_ONLY ? "defined" : "referenced") + 101 | " method IDs."); 102 | return filteredMethodRefs.toArray( 103 | new MethodRef[filteredMethodRefs.size()]); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /src/info/persistent/dex/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed under the Apache License, Version 2.0 (the "License"); 3 | * you may not use this file except in compliance with the License. 4 | * You may obtain a copy of the License at 5 | * 6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package info.persistent.dex; 16 | 17 | import com.android.dexdeps.DexData; 18 | import com.android.dexdeps.DexDataException; 19 | 20 | import java.io.File; 21 | import java.io.FileNotFoundException; 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.io.RandomAccessFile; 25 | import java.util.ArrayList; 26 | import java.util.Collections; 27 | import java.util.List; 28 | import java.util.zip.ZipEntry; 29 | import java.util.zip.ZipException; 30 | import java.util.zip.ZipFile; 31 | 32 | public class Main { 33 | private boolean countFields; 34 | private boolean includeClasses; 35 | private String packageFilter; 36 | private int maxDepth = Integer.MAX_VALUE; 37 | private DexMethodCounts.Filter filter = DexMethodCounts.Filter.ALL; 38 | private DexMethodCounts.OutputStyle outputStyle = DexMethodCounts.OutputStyle.TREE; 39 | 40 | public static void main(String[] args) { 41 | Main main = new Main(); 42 | main.run(args); 43 | } 44 | 45 | void run(String[] args) { 46 | try { 47 | String[] inputFileNames = parseArgs(args); 48 | int overallCount = 0; 49 | for (String fileName : collectFileNames(inputFileNames)) { 50 | System.out.println("Processing " + fileName); 51 | DexCount counts; 52 | if (countFields) { 53 | counts = new DexFieldCounts(outputStyle); 54 | } else { 55 | counts = new DexMethodCounts(outputStyle); 56 | } 57 | List dexFiles = openInputFiles(fileName); 58 | 59 | for (RandomAccessFile dexFile : dexFiles) { 60 | DexData dexData = new DexData(dexFile); 61 | dexData.load(); 62 | counts.generate(dexData, includeClasses, packageFilter, maxDepth, filter); 63 | dexFile.close(); 64 | } 65 | counts.output(); 66 | overallCount = counts.getOverallCount(); 67 | } 68 | System.out.println(String.format("Overall %s count: %d", countFields ? "field" : "method", overallCount)); 69 | } catch (UsageException ue) { 70 | usage(); 71 | System.exit(2); 72 | } catch (IOException ioe) { 73 | if (ioe.getMessage() != null) { 74 | System.err.println("Failed: " + ioe); 75 | } 76 | System.exit(1); 77 | } catch (DexDataException dde) { 78 | /* a message was already reported, just bail quietly */ 79 | System.exit(1); 80 | } 81 | } 82 | 83 | /** 84 | * Opens an input file, which could be a .dex or a .jar/.apk with a 85 | * classes.dex inside. If the latter, we extract the contents to a 86 | * temporary file. 87 | */ 88 | List openInputFiles(String fileName) throws IOException { 89 | List dexFiles = new ArrayList(); 90 | 91 | openInputFileAsZip(fileName, dexFiles); 92 | if (dexFiles.size() == 0) { 93 | File inputFile = new File(fileName); 94 | RandomAccessFile dexFile = new RandomAccessFile(inputFile, "r"); 95 | dexFiles.add(dexFile); 96 | } 97 | 98 | return dexFiles; 99 | } 100 | 101 | /** 102 | * Tries to open an input file as a Zip archive (jar/apk) with a 103 | * "classes.dex" inside. 104 | */ 105 | void openInputFileAsZip(String fileName, List dexFiles) throws IOException { 106 | ZipFile zipFile; 107 | 108 | // Try it as a zip file. 109 | try { 110 | zipFile = new ZipFile(fileName); 111 | } catch (FileNotFoundException fnfe) { 112 | // not found, no point in retrying as non-zip. 113 | System.err.println("Unable to open '" + fileName + "': " + 114 | fnfe.getMessage()); 115 | throw fnfe; 116 | } catch (ZipException ze) { 117 | // not a zip 118 | return; 119 | } 120 | 121 | // Open and add all files matching "classes.*\.dex" in the zip file. 122 | for (ZipEntry entry : Collections.list(zipFile.entries())) { 123 | if (entry.getName().matches("classes.*\\.dex")) { 124 | dexFiles.add(openDexFile(zipFile, entry)); 125 | } 126 | } 127 | 128 | zipFile.close(); 129 | } 130 | 131 | RandomAccessFile openDexFile(ZipFile zipFile, ZipEntry entry) throws IOException { 132 | // We know it's a zip; see if there's anything useful inside. A 133 | // failure here results in some type of IOException (of which 134 | // ZipException is a subclass). 135 | InputStream zis = zipFile.getInputStream(entry); 136 | 137 | // Create a temp file to hold the DEX data, open it, and delete it 138 | // to ensure it doesn't hang around if we fail. 139 | File tempFile = File.createTempFile("dexdeps", ".dex"); 140 | RandomAccessFile dexFile = new RandomAccessFile(tempFile, "rw"); 141 | tempFile.delete(); 142 | 143 | // Copy all data from input stream to output file. 144 | byte copyBuf[] = new byte[32768]; 145 | int actual; 146 | 147 | while (true) { 148 | actual = zis.read(copyBuf); 149 | if (actual == -1) 150 | break; 151 | 152 | dexFile.write(copyBuf, 0, actual); 153 | } 154 | 155 | dexFile.seek(0); 156 | 157 | return dexFile; 158 | } 159 | 160 | private String[] parseArgs(String[] args) { 161 | int idx; 162 | 163 | for (idx = 0; idx < args.length; idx++) { 164 | String arg = args[idx]; 165 | 166 | if (arg.equals("--") || !arg.startsWith("--")) { 167 | break; 168 | } else if (arg.equals("--count-fields")) { 169 | countFields = true; 170 | } else if (arg.equals("--include-classes")) { 171 | includeClasses = true; 172 | } else if (arg.startsWith("--package-filter=")) { 173 | packageFilter = arg.substring(arg.indexOf('=') + 1); 174 | } else if (arg.startsWith("--max-depth=")) { 175 | maxDepth = 176 | Integer.parseInt(arg.substring(arg.indexOf('=') + 1)); 177 | } else if (arg.startsWith("--filter=")) { 178 | filter = Enum.valueOf( 179 | DexMethodCounts.Filter.class, 180 | arg.substring(arg.indexOf('=') + 1).toUpperCase()); 181 | } else if (arg.startsWith("--output-style")) { 182 | outputStyle = Enum.valueOf( 183 | DexMethodCounts.OutputStyle.class, 184 | arg.substring(arg.indexOf('=') + 1).toUpperCase()); 185 | } else { 186 | System.err.println("Unknown option '" + arg + "'"); 187 | throw new UsageException(); 188 | } 189 | } 190 | 191 | // We expect at least one more argument (file name). 192 | int fileCount = args.length - idx; 193 | if (fileCount == 0) { 194 | throw new UsageException(); 195 | } 196 | String[] inputFileNames = new String[fileCount]; 197 | System.arraycopy(args, idx, inputFileNames, 0, fileCount); 198 | return inputFileNames; 199 | } 200 | 201 | private void usage() { 202 | System.err.print( 203 | "DEX per-package/class method counts v1.5\n" + 204 | "Usage: dex-method-counts [options] ...\n" + 205 | "Options:\n" + 206 | " --count-fields\n" + 207 | " --include-classes\n" + 208 | " --package-filter=com.foo.bar\n" + 209 | " --max-depth=N\n" + 210 | " --filter=ALL|DEFINED_ONLY|REFERENCED_ONLY\n" + 211 | " --output-style=FLAT|TREE\n" 212 | ); 213 | } 214 | 215 | /** 216 | * Checks if input files array contain directories and 217 | * adds it's contents to the file list if so. 218 | * Otherwise just adds a file to the list. 219 | * 220 | * @return a List of file names to process 221 | */ 222 | private List collectFileNames(String[] inputFileNames) { 223 | List fileNames = new ArrayList(); 224 | for (String inputFileName : inputFileNames) { 225 | File file = new File(inputFileName); 226 | if (file.isDirectory()) { 227 | String dirPath = file.getAbsolutePath(); 228 | for (String fileInDir: file.list()){ 229 | fileNames.add(dirPath + File.separator + fileInDir); 230 | } 231 | } else { 232 | fileNames.add(inputFileName); 233 | } 234 | } 235 | return fileNames; 236 | } 237 | 238 | private static class UsageException extends RuntimeException {} 239 | } 240 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /src/com/android/dexdeps/Output.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.dexdeps; 18 | 19 | import java.io.PrintStream; 20 | 21 | /** 22 | * Generate fancy output. 23 | */ 24 | public class Output { 25 | private static final String IN0 = ""; 26 | private static final String IN1 = " "; 27 | private static final String IN2 = " "; 28 | private static final String IN3 = " "; 29 | private static final String IN4 = " "; 30 | 31 | private static final PrintStream out = System.out; 32 | 33 | private static void generateHeader0(String fileName, String format) { 34 | if (format.equals("brief")) { 35 | if (fileName != null) { 36 | out.println("File: " + fileName); 37 | } 38 | } else if (format.equals("xml")) { 39 | if (fileName != null) { 40 | out.println(IN0 + ""); 41 | } else { 42 | out.println(IN0 + ""); 43 | } 44 | } else { 45 | /* should've been trapped in arg handler */ 46 | throw new RuntimeException("unknown output format"); 47 | } 48 | } 49 | 50 | public static void generateFirstHeader(String fileName, String format) { 51 | generateHeader0(fileName, format); 52 | } 53 | 54 | public static void generateHeader(String fileName, String format) { 55 | out.println(); 56 | generateHeader0(fileName, format); 57 | } 58 | 59 | public static void generateFooter(String format) { 60 | if (format.equals("brief")) { 61 | // Nothing to do. 62 | } else if (format.equals("xml")) { 63 | out.println(""); 64 | } else { 65 | /* should've been trapped in arg handler */ 66 | throw new RuntimeException("unknown output format"); 67 | } 68 | } 69 | 70 | public static void generate(DexData dexData, String format, 71 | boolean justClasses) { 72 | if (format.equals("brief")) { 73 | printBrief(dexData, justClasses); 74 | } else if (format.equals("xml")) { 75 | printXml(dexData, justClasses); 76 | } else { 77 | /* should've been trapped in arg handler */ 78 | throw new RuntimeException("unknown output format"); 79 | } 80 | } 81 | 82 | /** 83 | * Prints the data in a simple human-readable format. 84 | */ 85 | static void printBrief(DexData dexData, boolean justClasses) { 86 | ClassRef[] externClassRefs = dexData.getExternalReferences(); 87 | 88 | printClassRefs(externClassRefs, justClasses); 89 | 90 | if (!justClasses) { 91 | printFieldRefs(externClassRefs); 92 | printMethodRefs(externClassRefs); 93 | } 94 | } 95 | 96 | /** 97 | * Prints the list of classes in a simple human-readable format. 98 | */ 99 | static void printClassRefs(ClassRef[] classes, boolean justClasses) { 100 | if (!justClasses) { 101 | out.println("Classes:"); 102 | } 103 | 104 | for (int i = 0; i < classes.length; i++) { 105 | ClassRef ref = classes[i]; 106 | 107 | out.println(descriptorToDot(ref.getName())); 108 | } 109 | } 110 | 111 | /** 112 | * Prints the list of fields in a simple human-readable format. 113 | */ 114 | static void printFieldRefs(ClassRef[] classes) { 115 | out.println("\nFields:"); 116 | for (int i = 0; i < classes.length; i++) { 117 | FieldRef[] fields = classes[i].getFieldArray(); 118 | 119 | for (int j = 0; j < fields.length; j++) { 120 | FieldRef ref = fields[j]; 121 | 122 | out.println(descriptorToDot(ref.getDeclClassName()) + 123 | "." + ref.getName() + " : " + ref.getTypeName()); 124 | } 125 | } 126 | } 127 | 128 | /** 129 | * Prints the list of methods in a simple human-readable format. 130 | */ 131 | static void printMethodRefs(ClassRef[] classes) { 132 | out.println("\nMethods:"); 133 | for (int i = 0; i < classes.length; i++) { 134 | MethodRef[] methods = classes[i].getMethodArray(); 135 | 136 | for (int j = 0; j < methods.length; j++) { 137 | MethodRef ref = methods[j]; 138 | 139 | out.println(descriptorToDot(ref.getDeclClassName()) + 140 | "." + ref.getName() + " : " + ref.getDescriptor()); 141 | } 142 | } 143 | } 144 | 145 | /** 146 | * Prints the output in XML format. 147 | * 148 | * We shouldn't need to XML-escape the field/method info. 149 | */ 150 | static void printXml(DexData dexData, boolean justClasses) { 151 | ClassRef[] externClassRefs = dexData.getExternalReferences(); 152 | 153 | /* 154 | * Iterate through externClassRefs. For each class, dump all of 155 | * the matching fields and methods. 156 | */ 157 | String prevPackage = null; 158 | for (int i = 0; i < externClassRefs.length; i++) { 159 | ClassRef cref = externClassRefs[i]; 160 | String declClassName = cref.getName(); 161 | String className = classNameOnly(declClassName); 162 | String packageName = packageNameOnly(declClassName); 163 | 164 | /* 165 | * If we're in a different package, emit the appropriate tags. 166 | */ 167 | if (!packageName.equals(prevPackage)) { 168 | if (prevPackage != null) { 169 | out.println(IN1 + ""); 170 | } 171 | 172 | out.println(IN1 + 173 | ""); 174 | 175 | prevPackage = packageName; 176 | } 177 | 178 | out.println(IN2 + ""); 179 | if (!justClasses) { 180 | printXmlFields(cref); 181 | printXmlMethods(cref); 182 | } 183 | out.println(IN2 + ""); 184 | } 185 | 186 | if (prevPackage != null) 187 | out.println(IN1 + ""); 188 | } 189 | 190 | /** 191 | * Prints the externally-visible fields in XML format. 192 | */ 193 | private static void printXmlFields(ClassRef cref) { 194 | FieldRef[] fields = cref.getFieldArray(); 195 | for (int i = 0; i < fields.length; i++) { 196 | FieldRef fref = fields[i]; 197 | 198 | out.println(IN3 + ""); 200 | } 201 | } 202 | 203 | /** 204 | * Prints the externally-visible methods in XML format. 205 | */ 206 | private static void printXmlMethods(ClassRef cref) { 207 | MethodRef[] methods = cref.getMethodArray(); 208 | for (int i = 0; i < methods.length; i++) { 209 | MethodRef mref = methods[i]; 210 | String declClassName = mref.getDeclClassName(); 211 | boolean constructor; 212 | 213 | constructor = mref.getName().equals(""); 214 | if (constructor) { 215 | // use class name instead of method name 216 | out.println(IN3 + ""); 218 | } else { 219 | out.println(IN3 + ""); 222 | } 223 | String[] args = mref.getArgumentTypeNames(); 224 | for (int j = 0; j < args.length; j++) { 225 | out.println(IN4 + ""); 227 | } 228 | if (constructor) { 229 | out.println(IN3 + ""); 230 | } else { 231 | out.println(IN3 + ""); 232 | } 233 | } 234 | } 235 | 236 | 237 | /* 238 | * ======================================================================= 239 | * Utility functions 240 | * ======================================================================= 241 | */ 242 | 243 | /** 244 | * Converts a single-character primitive type into its human-readable 245 | * equivalent. 246 | */ 247 | public static String primitiveTypeLabel(char typeChar) { 248 | /* primitive type; substitute human-readable name in */ 249 | switch (typeChar) { 250 | case 'B': return "byte"; 251 | case 'C': return "char"; 252 | case 'D': return "double"; 253 | case 'F': return "float"; 254 | case 'I': return "int"; 255 | case 'J': return "long"; 256 | case 'S': return "short"; 257 | case 'V': return "void"; 258 | case 'Z': return "boolean"; 259 | default: 260 | /* huh? */ 261 | System.err.println("Unexpected class char " + typeChar); 262 | assert false; 263 | return "UNKNOWN"; 264 | } 265 | } 266 | 267 | /** 268 | * Converts a type descriptor to human-readable "dotted" form. For 269 | * example, "Ljava/lang/String;" becomes "java.lang.String", and 270 | * "[I" becomes "int[]. 271 | */ 272 | public static String descriptorToDot(String descr) { 273 | int targetLen = descr.length(); 274 | int offset = 0; 275 | int arrayDepth = 0; 276 | 277 | /* strip leading [s; will be added to end */ 278 | while (targetLen > 1 && descr.charAt(offset) == '[') { 279 | offset++; 280 | targetLen--; 281 | } 282 | arrayDepth = offset; 283 | 284 | if (targetLen == 1) { 285 | descr = primitiveTypeLabel(descr.charAt(offset)); 286 | offset = 0; 287 | targetLen = descr.length(); 288 | } else { 289 | /* account for leading 'L' and trailing ';' */ 290 | if (targetLen >= 2 && descr.charAt(offset) == 'L' && 291 | descr.charAt(offset+targetLen-1) == ';') 292 | { 293 | targetLen -= 2; /* two fewer chars to copy */ 294 | offset++; /* skip the 'L' */ 295 | } 296 | } 297 | 298 | char[] buf = new char[targetLen + arrayDepth * 2]; 299 | 300 | /* copy class name over */ 301 | int i; 302 | for (i = 0; i < targetLen; i++) { 303 | char ch = descr.charAt(offset + i); 304 | buf[i] = (ch == '/') ? '.' : ch; 305 | } 306 | 307 | /* add the appopriate number of brackets for arrays */ 308 | while (arrayDepth-- > 0) { 309 | buf[i++] = '['; 310 | buf[i++] = ']'; 311 | } 312 | assert i == buf.length; 313 | 314 | return new String(buf); 315 | } 316 | 317 | /** 318 | * Extracts the class name from a type descriptor. 319 | */ 320 | public static String classNameOnly(String typeName) { 321 | String dotted = descriptorToDot(typeName); 322 | 323 | int start = dotted.lastIndexOf("."); 324 | if (start < 0) { 325 | return dotted; 326 | } else { 327 | return dotted.substring(start+1); 328 | } 329 | } 330 | 331 | /** 332 | * Extracts the package name from a type descriptor, and returns it in 333 | * dotted form. 334 | */ 335 | public static String packageNameOnly(String typeName) { 336 | String dotted = descriptorToDot(typeName); 337 | 338 | int end = dotted.lastIndexOf("."); 339 | if (end < 0) { 340 | /* lives in default package */ 341 | return ""; 342 | } else { 343 | return dotted.substring(0, end); 344 | } 345 | } 346 | } 347 | -------------------------------------------------------------------------------- /src/com/android/dexdeps/DexData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.dexdeps; 18 | 19 | import java.io.IOException; 20 | import java.io.RandomAccessFile; 21 | import java.util.Arrays; 22 | 23 | /** 24 | * Data extracted from a DEX file. 25 | */ 26 | public class DexData { 27 | private RandomAccessFile mDexFile; 28 | private HeaderItem mHeaderItem; 29 | private String[] mStrings; // strings from string_data_* 30 | private TypeIdItem[] mTypeIds; 31 | private ProtoIdItem[] mProtoIds; 32 | private FieldIdItem[] mFieldIds; 33 | private MethodIdItem[] mMethodIds; 34 | private ClassDefItem[] mClassDefs; 35 | 36 | private byte tmpBuf[] = new byte[4]; 37 | private boolean isBigEndian = false; 38 | 39 | /** 40 | * Constructs a new DexData for this file. 41 | */ 42 | public DexData(RandomAccessFile raf) { 43 | mDexFile = raf; 44 | } 45 | 46 | /** 47 | * Loads the contents of the DEX file into our data structures. 48 | * 49 | * @throws IOException if we encounter a problem while reading 50 | * @throws DexDataException if the DEX contents look bad 51 | */ 52 | public void load() throws IOException { 53 | parseHeaderItem(); 54 | 55 | loadStrings(); 56 | loadTypeIds(); 57 | loadProtoIds(); 58 | loadFieldIds(); 59 | loadMethodIds(); 60 | loadClassDefs(); 61 | 62 | markInternalClasses(); 63 | } 64 | 65 | /** 66 | * Verifies the given magic number. 67 | */ 68 | private static boolean verifyMagic(byte[] magic) { 69 | return Arrays.equals(magic, HeaderItem.DEX_FILE_MAGIC) || 70 | Arrays.equals(magic, HeaderItem.DEX_FILE_MAGIC_API_13); 71 | } 72 | 73 | /** 74 | * Parses the interesting bits out of the header. 75 | */ 76 | void parseHeaderItem() throws IOException { 77 | mHeaderItem = new HeaderItem(); 78 | 79 | seek(0); 80 | 81 | byte[] magic = new byte[8]; 82 | readBytes(magic); 83 | if (!verifyMagic(magic)) { 84 | System.err.println("Magic number is wrong -- are you sure " + 85 | "this is a DEX file?"); 86 | throw new DexDataException(); 87 | } 88 | 89 | /* 90 | * Read the endian tag, so we properly swap things as we read 91 | * them from here on. 92 | */ 93 | seek(8+4+20+4+4); 94 | mHeaderItem.endianTag = readInt(); 95 | if (mHeaderItem.endianTag == HeaderItem.ENDIAN_CONSTANT) { 96 | /* do nothing */ 97 | } else if (mHeaderItem.endianTag == HeaderItem.REVERSE_ENDIAN_CONSTANT){ 98 | /* file is big-endian (!), reverse future reads */ 99 | isBigEndian = true; 100 | } else { 101 | System.err.println("Endian constant has unexpected value " + 102 | Integer.toHexString(mHeaderItem.endianTag)); 103 | throw new DexDataException(); 104 | } 105 | 106 | seek(8+4+20); // magic, checksum, signature 107 | mHeaderItem.fileSize = readInt(); 108 | mHeaderItem.headerSize = readInt(); 109 | /*mHeaderItem.endianTag =*/ readInt(); 110 | /*mHeaderItem.linkSize =*/ readInt(); 111 | /*mHeaderItem.linkOff =*/ readInt(); 112 | /*mHeaderItem.mapOff =*/ readInt(); 113 | mHeaderItem.stringIdsSize = readInt(); 114 | mHeaderItem.stringIdsOff = readInt(); 115 | mHeaderItem.typeIdsSize = readInt(); 116 | mHeaderItem.typeIdsOff = readInt(); 117 | mHeaderItem.protoIdsSize = readInt(); 118 | mHeaderItem.protoIdsOff = readInt(); 119 | mHeaderItem.fieldIdsSize = readInt(); 120 | mHeaderItem.fieldIdsOff = readInt(); 121 | mHeaderItem.methodIdsSize = readInt(); 122 | mHeaderItem.methodIdsOff = readInt(); 123 | mHeaderItem.classDefsSize = readInt(); 124 | mHeaderItem.classDefsOff = readInt(); 125 | /*mHeaderItem.dataSize =*/ readInt(); 126 | /*mHeaderItem.dataOff =*/ readInt(); 127 | } 128 | 129 | /** 130 | * Loads the string table out of the DEX. 131 | * 132 | * First we read all of the string_id_items, then we read all of the 133 | * string_data_item. Doing it this way should allow us to avoid 134 | * seeking around in the file. 135 | */ 136 | void loadStrings() throws IOException { 137 | int count = mHeaderItem.stringIdsSize; 138 | int stringOffsets[] = new int[count]; 139 | 140 | //System.out.println("reading " + count + " strings"); 141 | 142 | seek(mHeaderItem.stringIdsOff); 143 | for (int i = 0; i < count; i++) { 144 | stringOffsets[i] = readInt(); 145 | } 146 | 147 | mStrings = new String[count]; 148 | 149 | seek(stringOffsets[0]); 150 | for (int i = 0; i < count; i++) { 151 | seek(stringOffsets[i]); // should be a no-op 152 | mStrings[i] = readString(); 153 | //System.out.println("STR: " + i + ": " + mStrings[i]); 154 | } 155 | } 156 | 157 | /** 158 | * Loads the type ID list. 159 | */ 160 | void loadTypeIds() throws IOException { 161 | int count = mHeaderItem.typeIdsSize; 162 | mTypeIds = new TypeIdItem[count]; 163 | 164 | //System.out.println("reading " + count + " typeIds"); 165 | seek(mHeaderItem.typeIdsOff); 166 | for (int i = 0; i < count; i++) { 167 | mTypeIds[i] = new TypeIdItem(); 168 | mTypeIds[i].descriptorIdx = readInt(); 169 | 170 | //System.out.println(i + ": " + mTypeIds[i].descriptorIdx + 171 | // " " + mStrings[mTypeIds[i].descriptorIdx]); 172 | } 173 | } 174 | 175 | /** 176 | * Loads the proto ID list. 177 | */ 178 | void loadProtoIds() throws IOException { 179 | int count = mHeaderItem.protoIdsSize; 180 | mProtoIds = new ProtoIdItem[count]; 181 | 182 | //System.out.println("reading " + count + " protoIds"); 183 | seek(mHeaderItem.protoIdsOff); 184 | 185 | /* 186 | * Read the proto ID items. 187 | */ 188 | for (int i = 0; i < count; i++) { 189 | mProtoIds[i] = new ProtoIdItem(); 190 | mProtoIds[i].shortyIdx = readInt(); 191 | mProtoIds[i].returnTypeIdx = readInt(); 192 | mProtoIds[i].parametersOff = readInt(); 193 | 194 | //System.out.println(i + ": " + mProtoIds[i].shortyIdx + 195 | // " " + mStrings[mProtoIds[i].shortyIdx]); 196 | } 197 | 198 | /* 199 | * Go back through and read the type lists. 200 | */ 201 | for (int i = 0; i < count; i++) { 202 | ProtoIdItem protoId = mProtoIds[i]; 203 | 204 | int offset = protoId.parametersOff; 205 | 206 | if (offset == 0) { 207 | protoId.types = new int[0]; 208 | continue; 209 | } else { 210 | seek(offset); 211 | int size = readInt(); // #of entries in list 212 | protoId.types = new int[size]; 213 | 214 | for (int j = 0; j < size; j++) { 215 | protoId.types[j] = readShort() & 0xffff; 216 | } 217 | } 218 | } 219 | } 220 | 221 | /** 222 | * Loads the field ID list. 223 | */ 224 | void loadFieldIds() throws IOException { 225 | int count = mHeaderItem.fieldIdsSize; 226 | mFieldIds = new FieldIdItem[count]; 227 | 228 | //System.out.println("reading " + count + " fieldIds"); 229 | seek(mHeaderItem.fieldIdsOff); 230 | for (int i = 0; i < count; i++) { 231 | mFieldIds[i] = new FieldIdItem(); 232 | mFieldIds[i].classIdx = readShort() & 0xffff; 233 | mFieldIds[i].typeIdx = readShort() & 0xffff; 234 | mFieldIds[i].nameIdx = readInt(); 235 | 236 | //System.out.println(i + ": " + mFieldIds[i].nameIdx + 237 | // " " + mStrings[mFieldIds[i].nameIdx]); 238 | } 239 | } 240 | 241 | /** 242 | * Loads the method ID list. 243 | */ 244 | void loadMethodIds() throws IOException { 245 | int count = mHeaderItem.methodIdsSize; 246 | mMethodIds = new MethodIdItem[count]; 247 | 248 | //System.out.println("reading " + count + " methodIds"); 249 | seek(mHeaderItem.methodIdsOff); 250 | for (int i = 0; i < count; i++) { 251 | mMethodIds[i] = new MethodIdItem(); 252 | mMethodIds[i].classIdx = readShort() & 0xffff; 253 | mMethodIds[i].protoIdx = readShort() & 0xffff; 254 | mMethodIds[i].nameIdx = readInt(); 255 | 256 | //System.out.println(i + ": " + mMethodIds[i].nameIdx + 257 | // " " + mStrings[mMethodIds[i].nameIdx]); 258 | } 259 | } 260 | 261 | /** 262 | * Loads the class defs list. 263 | */ 264 | void loadClassDefs() throws IOException { 265 | int count = mHeaderItem.classDefsSize; 266 | mClassDefs = new ClassDefItem[count]; 267 | 268 | //System.out.println("reading " + count + " classDefs"); 269 | seek(mHeaderItem.classDefsOff); 270 | for (int i = 0; i < count; i++) { 271 | mClassDefs[i] = new ClassDefItem(); 272 | mClassDefs[i].classIdx = readInt(); 273 | 274 | /* access_flags = */ readInt(); 275 | /* superclass_idx = */ readInt(); 276 | /* interfaces_off = */ readInt(); 277 | /* source_file_idx = */ readInt(); 278 | /* annotations_off = */ readInt(); 279 | /* class_data_off = */ readInt(); 280 | /* static_values_off = */ readInt(); 281 | 282 | //System.out.println(i + ": " + mClassDefs[i].classIdx + " " + 283 | // mStrings[mTypeIds[mClassDefs[i].classIdx].descriptorIdx]); 284 | } 285 | } 286 | 287 | /** 288 | * Sets the "internal" flag on type IDs which are defined in the 289 | * DEX file or within the VM (e.g. primitive classes and arrays). 290 | */ 291 | void markInternalClasses() { 292 | for (int i = mClassDefs.length -1; i >= 0; i--) { 293 | mTypeIds[mClassDefs[i].classIdx].internal = true; 294 | } 295 | 296 | for (int i = 0; i < mTypeIds.length; i++) { 297 | String className = mStrings[mTypeIds[i].descriptorIdx]; 298 | 299 | if (className.length() == 1) { 300 | // primitive class 301 | mTypeIds[i].internal = true; 302 | } else if (className.charAt(0) == '[') { 303 | mTypeIds[i].internal = true; 304 | } 305 | 306 | //System.out.println(i + " " + 307 | // (mTypeIds[i].internal ? "INTERNAL" : "external") + " - " + 308 | // mStrings[mTypeIds[i].descriptorIdx]); 309 | } 310 | } 311 | 312 | 313 | /* 314 | * ======================================================================= 315 | * Queries 316 | * ======================================================================= 317 | */ 318 | 319 | /** 320 | * Returns the class name, given an index into the type_ids table. 321 | */ 322 | private String classNameFromTypeIndex(int idx) { 323 | return mStrings[mTypeIds[idx].descriptorIdx]; 324 | } 325 | 326 | /** 327 | * Returns an array of method argument type strings, given an index 328 | * into the proto_ids table. 329 | */ 330 | private String[] argArrayFromProtoIndex(int idx) { 331 | ProtoIdItem protoId = mProtoIds[idx]; 332 | String[] result = new String[protoId.types.length]; 333 | 334 | for (int i = 0; i < protoId.types.length; i++) { 335 | result[i] = mStrings[mTypeIds[protoId.types[i]].descriptorIdx]; 336 | } 337 | 338 | return result; 339 | } 340 | 341 | /** 342 | * Returns a string representing the method's return type, given an 343 | * index into the proto_ids table. 344 | */ 345 | private String returnTypeFromProtoIndex(int idx) { 346 | ProtoIdItem protoId = mProtoIds[idx]; 347 | return mStrings[mTypeIds[protoId.returnTypeIdx].descriptorIdx]; 348 | } 349 | 350 | /** 351 | * Returns an array with all of the class references that don't 352 | * correspond to classes in the DEX file. Each class reference has 353 | * a list of the referenced fields and methods associated with 354 | * that class. 355 | */ 356 | public ClassRef[] getExternalReferences() { 357 | // create a sparse array of ClassRef that parallels mTypeIds 358 | ClassRef[] sparseRefs = new ClassRef[mTypeIds.length]; 359 | 360 | // create entries for all externally-referenced classes 361 | int count = 0; 362 | for (int i = 0; i < mTypeIds.length; i++) { 363 | if (!mTypeIds[i].internal) { 364 | sparseRefs[i] = 365 | new ClassRef(mStrings[mTypeIds[i].descriptorIdx]); 366 | count++; 367 | } 368 | } 369 | 370 | // add fields and methods to the appropriate class entry 371 | addExternalFieldReferences(sparseRefs); 372 | addExternalMethodReferences(sparseRefs); 373 | 374 | // crunch out the sparseness 375 | ClassRef[] classRefs = new ClassRef[count]; 376 | int idx = 0; 377 | for (int i = 0; i < mTypeIds.length; i++) { 378 | if (sparseRefs[i] != null) 379 | classRefs[idx++] = sparseRefs[i]; 380 | } 381 | 382 | assert idx == count; 383 | 384 | return classRefs; 385 | } 386 | 387 | /** 388 | * Runs through the list of field references, inserting external 389 | * references into the appropriate ClassRef. 390 | */ 391 | private void addExternalFieldReferences(ClassRef[] sparseRefs) { 392 | for (int i = 0; i < mFieldIds.length; i++) { 393 | if (!mTypeIds[mFieldIds[i].classIdx].internal) { 394 | FieldIdItem fieldId = mFieldIds[i]; 395 | FieldRef newFieldRef = new FieldRef( 396 | classNameFromTypeIndex(fieldId.classIdx), 397 | classNameFromTypeIndex(fieldId.typeIdx), 398 | mStrings[fieldId.nameIdx]); 399 | sparseRefs[mFieldIds[i].classIdx].addField(newFieldRef); 400 | } 401 | } 402 | } 403 | 404 | /** 405 | * Runs through the list of method references, inserting external 406 | * references into the appropriate ClassRef. 407 | */ 408 | private void addExternalMethodReferences(ClassRef[] sparseRefs) { 409 | for (int i = 0; i < mMethodIds.length; i++) { 410 | if (!mTypeIds[mMethodIds[i].classIdx].internal) { 411 | MethodIdItem methodId = mMethodIds[i]; 412 | MethodRef newMethodRef = new MethodRef( 413 | classNameFromTypeIndex(methodId.classIdx), 414 | argArrayFromProtoIndex(methodId.protoIdx), 415 | returnTypeFromProtoIndex(methodId.protoIdx), 416 | mStrings[methodId.nameIdx]); 417 | sparseRefs[mMethodIds[i].classIdx].addMethod(newMethodRef); 418 | } 419 | } 420 | } 421 | 422 | /** 423 | * Returns the list of all method references. 424 | */ 425 | public MethodRef[] getMethodRefs() { 426 | MethodRef[] methodRefs = new MethodRef[mMethodIds.length]; 427 | for (int i = 0; i < mMethodIds.length; i++) { 428 | MethodIdItem methodId = mMethodIds[i]; 429 | methodRefs[i] = new MethodRef( 430 | classNameFromTypeIndex(methodId.classIdx), 431 | argArrayFromProtoIndex(methodId.protoIdx), 432 | returnTypeFromProtoIndex(methodId.protoIdx), 433 | mStrings[methodId.nameIdx]); 434 | } 435 | return methodRefs; 436 | } 437 | 438 | /** 439 | * Returns the list of all field references. 440 | */ 441 | public FieldRef[] getFieldRefs() { 442 | FieldRef[] fieldRefs = new FieldRef[mFieldIds.length]; 443 | for (int i = 0; i < mFieldIds.length; i++) { 444 | FieldIdItem fieldId = mFieldIds[i]; 445 | fieldRefs[i] = new FieldRef( 446 | classNameFromTypeIndex(fieldId.classIdx), 447 | classNameFromTypeIndex(fieldId.typeIdx), 448 | mStrings[fieldId.nameIdx]); 449 | } 450 | return fieldRefs; 451 | } 452 | 453 | /* 454 | * ======================================================================= 455 | * Basic I/O functions 456 | * ======================================================================= 457 | */ 458 | 459 | /** 460 | * Seeks the DEX file to the specified absolute position. 461 | */ 462 | void seek(int position) throws IOException { 463 | mDexFile.seek(position); 464 | } 465 | 466 | /** 467 | * Fills the buffer by reading bytes from the DEX file. 468 | */ 469 | void readBytes(byte[] buffer) throws IOException { 470 | mDexFile.readFully(buffer); 471 | } 472 | 473 | /** 474 | * Reads a single signed byte value. 475 | */ 476 | byte readByte() throws IOException { 477 | mDexFile.readFully(tmpBuf, 0, 1); 478 | return tmpBuf[0]; 479 | } 480 | 481 | /** 482 | * Reads a signed 16-bit integer, byte-swapping if necessary. 483 | */ 484 | short readShort() throws IOException { 485 | mDexFile.readFully(tmpBuf, 0, 2); 486 | if (isBigEndian) { 487 | return (short) ((tmpBuf[1] & 0xff) | ((tmpBuf[0] & 0xff) << 8)); 488 | } else { 489 | return (short) ((tmpBuf[0] & 0xff) | ((tmpBuf[1] & 0xff) << 8)); 490 | } 491 | } 492 | 493 | /** 494 | * Reads a signed 32-bit integer, byte-swapping if necessary. 495 | */ 496 | int readInt() throws IOException { 497 | mDexFile.readFully(tmpBuf, 0, 4); 498 | 499 | if (isBigEndian) { 500 | return (tmpBuf[3] & 0xff) | ((tmpBuf[2] & 0xff) << 8) | 501 | ((tmpBuf[1] & 0xff) << 16) | ((tmpBuf[0] & 0xff) << 24); 502 | } else { 503 | return (tmpBuf[0] & 0xff) | ((tmpBuf[1] & 0xff) << 8) | 504 | ((tmpBuf[2] & 0xff) << 16) | ((tmpBuf[3] & 0xff) << 24); 505 | } 506 | } 507 | 508 | /** 509 | * Reads a variable-length unsigned LEB128 value. Does not attempt to 510 | * verify that the value is valid. 511 | * 512 | * @throws IOException if we run off the end of the file 513 | */ 514 | int readUnsignedLeb128() throws IOException { 515 | int result = 0; 516 | byte val; 517 | 518 | do { 519 | val = readByte(); 520 | result = (result << 7) | (val & 0x7f); 521 | } while (val < 0); 522 | 523 | return result; 524 | } 525 | 526 | /** 527 | * Reads a UTF-8 string. 528 | * 529 | * We don't know how long the UTF-8 string is, so we have to read one 530 | * byte at a time. We could make an educated guess based on the 531 | * utf16_size and seek back if we get it wrong, but seeking backward 532 | * may cause the underlying implementation to reload I/O buffers. 533 | */ 534 | String readString() throws IOException { 535 | int utf16len = readUnsignedLeb128(); 536 | byte inBuf[] = new byte[utf16len * 3]; // worst case 537 | int idx; 538 | 539 | for (idx = 0; idx < inBuf.length; idx++) { 540 | byte val = readByte(); 541 | if (val == 0) 542 | break; 543 | inBuf[idx] = val; 544 | } 545 | 546 | return new String(inBuf, 0, idx, "UTF-8"); 547 | } 548 | 549 | 550 | /* 551 | * ======================================================================= 552 | * Internal "structure" declarations 553 | * ======================================================================= 554 | */ 555 | 556 | /** 557 | * Holds the contents of a header_item. 558 | */ 559 | static class HeaderItem { 560 | public int fileSize; 561 | public int headerSize; 562 | public int endianTag; 563 | public int stringIdsSize, stringIdsOff; 564 | public int typeIdsSize, typeIdsOff; 565 | public int protoIdsSize, protoIdsOff; 566 | public int fieldIdsSize, fieldIdsOff; 567 | public int methodIdsSize, methodIdsOff; 568 | public int classDefsSize, classDefsOff; 569 | 570 | /* expected magic values */ 571 | public static final byte[] DEX_FILE_MAGIC = { 572 | 0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x36, 0x00 }; 573 | public static final byte[] DEX_FILE_MAGIC_API_13 = { 574 | 0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0x00 }; 575 | public static final int ENDIAN_CONSTANT = 0x12345678; 576 | public static final int REVERSE_ENDIAN_CONSTANT = 0x78563412; 577 | } 578 | 579 | /** 580 | * Holds the contents of a type_id_item. 581 | * 582 | * This is chiefly a list of indices into the string table. We need 583 | * some additional bits of data, such as whether or not the type ID 584 | * represents a class defined in this DEX, so we use an object for 585 | * each instead of a simple integer. (Could use a parallel array, but 586 | * since this is a desktop app it's not essential.) 587 | */ 588 | static class TypeIdItem { 589 | public int descriptorIdx; // index into string_ids 590 | 591 | public boolean internal; // defined within this DEX file? 592 | } 593 | 594 | /** 595 | * Holds the contents of a proto_id_item. 596 | */ 597 | static class ProtoIdItem { 598 | public int shortyIdx; // index into string_ids 599 | public int returnTypeIdx; // index into type_ids 600 | public int parametersOff; // file offset to a type_list 601 | 602 | public int types[]; // contents of type list 603 | } 604 | 605 | /** 606 | * Holds the contents of a field_id_item. 607 | */ 608 | static class FieldIdItem { 609 | public int classIdx; // index into type_ids (defining class) 610 | public int typeIdx; // index into type_ids (field type) 611 | public int nameIdx; // index into string_ids 612 | } 613 | 614 | /** 615 | * Holds the contents of a method_id_item. 616 | */ 617 | static class MethodIdItem { 618 | public int classIdx; // index into type_ids 619 | public int protoIdx; // index into proto_ids 620 | public int nameIdx; // index into string_ids 621 | } 622 | 623 | /** 624 | * Holds the contents of a class_def_item. 625 | * 626 | * We don't really need a class for this, but there's some stuff in 627 | * the class_def_item that we might want later. 628 | */ 629 | static class ClassDefItem { 630 | public int classIdx; // index into type_ids 631 | } 632 | } 633 | --------------------------------------------------------------------------------