blob: d7c0e4cfc2d608f32686a306f000912616bcaba7 [file] [log] [blame]
Aart Bik3e40f4a2015-07-07 17:09:41 -07001/*
2 * Copyright (C) 2015 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 * Implementation file of the dexlist utility.
17 *
18 * This is a re-implementation of the original dexlist utility that was
19 * based on Dalvik functions in libdex into a new dexlist that is now
20 * based on Art functions in libart instead. The output is identical to
21 * the original for correct DEX files. Error messages may differ, however.
22 *
23 * List all methods in all concrete classes in one or more DEX files.
24 */
25
26#include <stdlib.h>
27#include <stdio.h>
28
29#include "dex_file-inl.h"
30#include "mem_map.h"
31#include "runtime.h"
32
33namespace art {
34
35static const char* gProgName = "dexlist";
36
37/* Command-line options. */
38static struct {
39 char* argCopy;
40 const char* classToFind;
41 const char* methodToFind;
42 const char* outputFileName;
43} gOptions;
44
45/*
46 * Output file. Defaults to stdout.
47 */
48static FILE* gOutFile = stdout;
49
50/*
51 * Data types that match the definitions in the VM specification.
52 */
53typedef uint8_t u1;
54typedef uint16_t u2;
55typedef uint32_t u4;
56typedef uint64_t u8;
57typedef int32_t s4;
58typedef int64_t s8;
59
60/*
61 * Returns a newly-allocated string for the "dot version" of the class
62 * name for the given type descriptor. That is, The initial "L" and
63 * final ";" (if any) have been removed and all occurrences of '/'
64 * have been changed to '.'.
65 */
66static char* descriptorToDot(const char* str) {
67 size_t at = strlen(str);
68 if (str[0] == 'L') {
69 at -= 2; // Two fewer chars to copy.
70 str++;
71 }
72 char* newStr = reinterpret_cast<char*>(malloc(at + 1));
73 newStr[at] = '\0';
74 while (at > 0) {
75 at--;
76 newStr[at] = (str[at] == '/') ? '.' : str[at];
77 }
78 return newStr;
79}
80
81/*
82 * Positions table callback; we just want to catch the number of the
83 * first line in the method, which *should* correspond to the first
84 * entry from the table. (Could also use "min" here.)
85 */
86static bool positionsCb(void* context, u4 /*address*/, u4 lineNum) {
87 int* pFirstLine = reinterpret_cast<int *>(context);
88 if (*pFirstLine == -1) {
89 *pFirstLine = lineNum;
90 }
91 return 0;
92}
93
94/*
95 * Dumps a method.
96 */
97static void dumpMethod(const DexFile* pDexFile,
98 const char* fileName, u4 idx, u4 flags,
99 const DexFile::CodeItem* pCode, u4 codeOffset) {
100 // Abstract and native methods don't get listed.
101 if (pCode == nullptr || codeOffset == 0) {
102 return;
103 }
104
105 // Method information.
106 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
107 const char* methodName = pDexFile->StringDataByIdx(pMethodId.name_idx_);
108 const char* classDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
109 char* className = descriptorToDot(classDescriptor);
110 const u4 insnsOff = codeOffset + 0x10;
111
112 // Don't list methods that do not match a particular query.
113 if (gOptions.methodToFind != nullptr &&
114 (strcmp(gOptions.classToFind, className) != 0 ||
115 strcmp(gOptions.methodToFind, methodName) != 0)) {
116 free(className);
117 return;
118 }
119
120 // If the filename is empty, then set it to something printable.
121 if (fileName == nullptr || fileName[0] == 0) {
122 fileName = "(none)";
123 }
124
125 // Find the first line.
126 int firstLine = -1;
127 bool is_static = (flags & kAccStatic) != 0;
128 pDexFile->DecodeDebugInfo(
129 pCode, is_static, idx, positionsCb, nullptr, &firstLine);
130
131 // Method signature.
132 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
133 char* typeDesc = strdup(signature.ToString().c_str());
134
135 // Dump actual method information.
136 fprintf(gOutFile, "0x%08x %d %s %s %s %s %d\n",
137 insnsOff, pCode->insns_size_in_code_units_ * 2,
138 className, methodName, typeDesc, fileName, firstLine);
139
140 free(typeDesc);
141 free(className);
142}
143
144/*
145 * Runs through all direct and virtual methods in the class.
146 */
147void dumpClass(const DexFile* pDexFile, u4 idx) {
148 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
149
150 const char* fileName;
151 if (pClassDef.source_file_idx_ == DexFile::kDexNoIndex) {
152 fileName = nullptr;
153 } else {
154 fileName = pDexFile->StringDataByIdx(pClassDef.source_file_idx_);
155 }
156
157 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
158 if (pEncodedData != nullptr) {
159 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
160 // Skip the fields.
161 for (; pClassData.HasNextStaticField(); pClassData.Next()) {}
162 for (; pClassData.HasNextInstanceField(); pClassData.Next()) {}
163 // Direct methods.
164 for (; pClassData.HasNextDirectMethod(); pClassData.Next()) {
165 dumpMethod(pDexFile, fileName,
166 pClassData.GetMemberIndex(),
167 pClassData.GetRawMemberAccessFlags(),
168 pClassData.GetMethodCodeItem(),
169 pClassData.GetMethodCodeItemOffset());
170 }
171 // Virtual methods.
172 for (; pClassData.HasNextVirtualMethod(); pClassData.Next()) {
173 dumpMethod(pDexFile, fileName,
174 pClassData.GetMemberIndex(),
175 pClassData.GetRawMemberAccessFlags(),
176 pClassData.GetMethodCodeItem(),
177 pClassData.GetMethodCodeItemOffset());
178 }
179 }
180}
181
182/*
183 * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
184 */
185static int processFile(const char* fileName) {
186 // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
187 // all of which are Zip archives with "classes.dex" inside.
188 std::string error_msg;
189 std::vector<std::unique_ptr<const DexFile>> dex_files;
190 if (!DexFile::Open(fileName, fileName, &error_msg, &dex_files)) {
191 fputs(error_msg.c_str(), stderr);
192 fputc('\n', stderr);
193 return -1;
194 }
195
196 // Determine if opening file yielded a single dex file.
197 //
198 // TODO(ajcbik): this restriction is not really needed, but kept
199 // for now to stay close to original dexlist; we can
200 // later relax this!
201 //
202 if (dex_files.size() != 1) {
203 fprintf(stderr, "ERROR: DEX parse failed\n");
204 return -1;
205 }
206 const DexFile* pDexFile = dex_files[0].get();
207
208 // Success. Iterate over all classes.
209 fprintf(gOutFile, "#%s\n", fileName);
210 const u4 classDefsSize = pDexFile->GetHeader().class_defs_size_;
211 for (u4 idx = 0; idx < classDefsSize; idx++) {
212 dumpClass(pDexFile, idx);
213 }
214 return 0;
215}
216
217/*
218 * Shows usage.
219 */
220static void usage(void) {
221 fprintf(stderr, "Copyright (C) 2007 The Android Open Source Project\n\n");
222 fprintf(stderr, "%s: [-m p.c.m] [-o outfile] dexfile...\n", gProgName);
223 fprintf(stderr, "\n");
224}
225
226/*
227 * Main driver of the dexlist utility.
228 */
229int dexlistDriver(int argc, char** argv) {
230 // Art specific set up.
231 InitLogging(argv);
232 MemMap::Init();
233
234 // Reset options.
235 bool wantUsage = false;
236 memset(&gOptions, 0, sizeof(gOptions));
237
238 // Parse all arguments.
239 while (1) {
240 const int ic = getopt(argc, argv, "o:m:");
241 if (ic < 0) {
242 break; // done
243 }
244 switch (ic) {
245 case 'o': // output file
246 gOptions.outputFileName = optarg;
247 break;
248 case 'm':
249 // If -m X.Y.Z is given, then find all instances of the
250 // fully-qualified method name. This isn't really what
251 // dexlist is for, but it's easy to do it here.
252 {
253 gOptions.argCopy = strdup(optarg);
254 char* meth = strrchr(gOptions.argCopy, '.');
255 if (meth == nullptr) {
256 fprintf(stderr, "Expected: package.Class.method\n");
257 wantUsage = true;
258 } else {
259 *meth = '\0';
260 gOptions.classToFind = gOptions.argCopy;
261 gOptions.methodToFind = meth + 1;
262 }
263 }
264 break;
265 default:
266 wantUsage = true;
267 break;
268 } // switch
269 } // while
270
271 // Detect early problems.
272 if (optind == argc) {
273 fprintf(stderr, "%s: no file specified\n", gProgName);
274 wantUsage = true;
275 }
276 if (wantUsage) {
277 usage();
278 free(gOptions.argCopy);
279 return 2;
280 }
281
282 // Open alternative output file.
283 if (gOptions.outputFileName) {
284 gOutFile = fopen(gOptions.outputFileName, "w");
285 if (!gOutFile) {
286 fprintf(stderr, "Can't open %s\n", gOptions.outputFileName);
287 free(gOptions.argCopy);
288 return 1;
289 }
290 }
291
292 // Process all files supplied on command line. If one of them fails we
293 // continue on, only returning a failure at the end.
294 int result = 0;
295 while (optind < argc) {
296 result |= processFile(argv[optind++]);
297 } // while
298
299 free(gOptions.argCopy);
300 return result != 0;
301}
302
303} // namespace art
304
305int main(int argc, char** argv) {
306 return art::dexlistDriver(argc, argv);
307}
308