blob: 8daaef19dcaa84f6b8d142ad993f49a8cc0b0c0c [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
David Sehr5a1f6292018-01-19 11:08:51 -080026#include <fcntl.h>
27#include <inttypes.h>
Aart Bik3e40f4a2015-07-07 17:09:41 -070028#include <stdio.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070029#include <stdlib.h>
David Sehr5a1f6292018-01-19 11:08:51 -080030#include <sys/mman.h>
31#include <sys/types.h>
32#include <sys/stat.h>
33#include <unistd.h>
Aart Bik3e40f4a2015-07-07 17:09:41 -070034
David Sehr9e734c72018-01-04 17:56:19 -080035#include "dex/code_item_accessors-no_art-inl.h"
36#include "dex/dex_file-inl.h"
37#include "dex/dex_file_loader.h"
Aart Bik3e40f4a2015-07-07 17:09:41 -070038
39namespace art {
40
41static const char* gProgName = "dexlist";
42
43/* Command-line options. */
44static struct {
45 char* argCopy;
46 const char* classToFind;
47 const char* methodToFind;
48 const char* outputFileName;
49} gOptions;
50
51/*
52 * Output file. Defaults to stdout.
53 */
54static FILE* gOutFile = stdout;
55
56/*
57 * Data types that match the definitions in the VM specification.
58 */
59typedef uint8_t u1;
Aart Bik3e40f4a2015-07-07 17:09:41 -070060typedef uint32_t u4;
61typedef uint64_t u8;
Aart Bik3e40f4a2015-07-07 17:09:41 -070062
63/*
64 * Returns a newly-allocated string for the "dot version" of the class
65 * name for the given type descriptor. That is, The initial "L" and
66 * final ";" (if any) have been removed and all occurrences of '/'
67 * have been changed to '.'.
68 */
Aart Bikc05e2f22016-07-12 15:53:13 -070069static std::unique_ptr<char[]> descriptorToDot(const char* str) {
70 size_t len = strlen(str);
Aart Bik3e40f4a2015-07-07 17:09:41 -070071 if (str[0] == 'L') {
Aart Bikc05e2f22016-07-12 15:53:13 -070072 len -= 2; // Two fewer chars to copy (trims L and ;).
73 str++; // Start past 'L'.
Aart Bik3e40f4a2015-07-07 17:09:41 -070074 }
Aart Bikc05e2f22016-07-12 15:53:13 -070075 std::unique_ptr<char[]> newStr(new char[len + 1]);
76 for (size_t i = 0; i < len; i++) {
77 newStr[i] = (str[i] == '/') ? '.' : str[i];
Aart Bik3e40f4a2015-07-07 17:09:41 -070078 }
Aart Bikc05e2f22016-07-12 15:53:13 -070079 newStr[len] = '\0';
Aart Bik3e40f4a2015-07-07 17:09:41 -070080 return newStr;
81}
82
83/*
84 * Positions table callback; we just want to catch the number of the
85 * first line in the method, which *should* correspond to the first
86 * entry from the table. (Could also use "min" here.)
87 */
David Srbeckyb06e28e2015-12-10 13:15:00 +000088static bool positionsCb(void* context, const DexFile::PositionInfo& entry) {
Aart Bik3e40f4a2015-07-07 17:09:41 -070089 int* pFirstLine = reinterpret_cast<int *>(context);
90 if (*pFirstLine == -1) {
David Srbeckyb06e28e2015-12-10 13:15:00 +000091 *pFirstLine = entry.line_;
Aart Bik3e40f4a2015-07-07 17:09:41 -070092 }
93 return 0;
94}
95
96/*
97 * Dumps a method.
98 */
99static void dumpMethod(const DexFile* pDexFile,
David Srbeckyb06e28e2015-12-10 13:15:00 +0000100 const char* fileName, u4 idx, u4 flags ATTRIBUTE_UNUSED,
Aart Bik3e40f4a2015-07-07 17:09:41 -0700101 const DexFile::CodeItem* pCode, u4 codeOffset) {
102 // Abstract and native methods don't get listed.
103 if (pCode == nullptr || codeOffset == 0) {
104 return;
105 }
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800106 CodeItemDebugInfoAccessor accessor(*pDexFile, pCode, idx);
Aart Bik3e40f4a2015-07-07 17:09:41 -0700107
108 // Method information.
109 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
110 const char* methodName = pDexFile->StringDataByIdx(pMethodId.name_idx_);
111 const char* classDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
Aart Bikc05e2f22016-07-12 15:53:13 -0700112 std::unique_ptr<char[]> className(descriptorToDot(classDescriptor));
Aart Bik3e40f4a2015-07-07 17:09:41 -0700113 const u4 insnsOff = codeOffset + 0x10;
114
115 // Don't list methods that do not match a particular query.
116 if (gOptions.methodToFind != nullptr &&
Aart Bikc05e2f22016-07-12 15:53:13 -0700117 (strcmp(gOptions.classToFind, className.get()) != 0 ||
Aart Bik3e40f4a2015-07-07 17:09:41 -0700118 strcmp(gOptions.methodToFind, methodName) != 0)) {
Aart Bik3e40f4a2015-07-07 17:09:41 -0700119 return;
120 }
121
122 // If the filename is empty, then set it to something printable.
123 if (fileName == nullptr || fileName[0] == 0) {
124 fileName = "(none)";
125 }
126
127 // Find the first line.
128 int firstLine = -1;
Mathieu Chartier641a3af2017-12-15 11:42:58 -0800129 pDexFile->DecodeDebugPositionInfo(accessor.DebugInfoOffset(), positionsCb, &firstLine);
Aart Bik3e40f4a2015-07-07 17:09:41 -0700130
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",
Mathieu Chartier641a3af2017-12-15 11:42:58 -0800137 insnsOff, accessor.InsnsSizeInCodeUnits() * 2,
Aart Bikc05e2f22016-07-12 15:53:13 -0700138 className.get(), methodName, typeDesc, fileName, firstLine);
Aart Bik3e40f4a2015-07-07 17:09:41 -0700139
140 free(typeDesc);
Aart Bik3e40f4a2015-07-07 17:09:41 -0700141}
142
143/*
144 * Runs through all direct and virtual methods in the class.
145 */
146void dumpClass(const DexFile* pDexFile, u4 idx) {
147 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
148
149 const char* fileName;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800150 if (!pClassDef.source_file_idx_.IsValid()) {
Aart Bik3e40f4a2015-07-07 17:09:41 -0700151 fileName = nullptr;
152 } else {
153 fileName = pDexFile->StringDataByIdx(pClassDef.source_file_idx_);
154 }
155
156 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
157 if (pEncodedData != nullptr) {
158 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700159 pClassData.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800160 // Direct and virtual methods.
161 for (; pClassData.HasNextMethod(); pClassData.Next()) {
Aart Bik3e40f4a2015-07-07 17:09:41 -0700162 dumpMethod(pDexFile, fileName,
163 pClassData.GetMemberIndex(),
164 pClassData.GetRawMemberAccessFlags(),
165 pClassData.GetMethodCodeItem(),
166 pClassData.GetMethodCodeItemOffset());
167 }
168 }
169}
170
David Sehr5a1f6292018-01-19 11:08:51 -0800171static bool openAndMapFile(const char* fileName,
172 const uint8_t** base,
173 size_t* size,
174 std::string* error_msg) {
175 int fd = open(fileName, O_RDONLY);
176 if (fd < 0) {
177 *error_msg = "open failed";
178 return false;
179 }
180 struct stat st;
181 if (fstat(fd, &st) < 0) {
182 *error_msg = "stat failed";
183 return false;
184 }
185 *size = st.st_size;
186 if (*size == 0) {
187 *error_msg = "size == 0";
188 return false;
189 }
190 void* addr = mmap(nullptr /*addr*/, *size, PROT_READ, MAP_PRIVATE, fd, 0 /*offset*/);
191 if (addr == MAP_FAILED) {
192 *error_msg = "mmap failed";
193 return false;
194 }
195 *base = reinterpret_cast<const uint8_t*>(addr);
196 return true;
197}
198
Aart Bik3e40f4a2015-07-07 17:09:41 -0700199/*
200 * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
201 */
202static int processFile(const char* fileName) {
203 // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
204 // all of which are Zip archives with "classes.dex" inside.
Aart Bik37d6a3b2016-06-21 18:30:10 -0700205 static constexpr bool kVerifyChecksum = true;
David Sehr5a1f6292018-01-19 11:08:51 -0800206 const uint8_t* base = nullptr;
207 size_t size = 0;
Aart Bik3e40f4a2015-07-07 17:09:41 -0700208 std::string error_msg;
David Sehr5a1f6292018-01-19 11:08:51 -0800209 if (!openAndMapFile(fileName, &base, &size, &error_msg)) {
210 fputs(error_msg.c_str(), stderr);
211 fputc('\n', stderr);
212 return -1;
213 }
Aart Bik3e40f4a2015-07-07 17:09:41 -0700214 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr5a1f6292018-01-19 11:08:51 -0800215 const DexFileLoader dex_file_loader;
216 if (!dex_file_loader.OpenAll(
217 base, size, fileName, /*verify*/ true, kVerifyChecksum, &error_msg, &dex_files)) {
Aart Bik3e40f4a2015-07-07 17:09:41 -0700218 fputs(error_msg.c_str(), stderr);
219 fputc('\n', stderr);
220 return -1;
221 }
222
Aart Bik4e149602015-07-09 11:45:28 -0700223 // Success. Iterate over all dex files found in given file.
Aart Bik3e40f4a2015-07-07 17:09:41 -0700224 fprintf(gOutFile, "#%s\n", fileName);
Aart Bik4e149602015-07-09 11:45:28 -0700225 for (size_t i = 0; i < dex_files.size(); i++) {
226 // Iterate over all classes in one dex file.
227 const DexFile* pDexFile = dex_files[i].get();
228 const u4 classDefsSize = pDexFile->GetHeader().class_defs_size_;
229 for (u4 idx = 0; idx < classDefsSize; idx++) {
230 dumpClass(pDexFile, idx);
231 }
Aart Bik3e40f4a2015-07-07 17:09:41 -0700232 }
233 return 0;
234}
235
236/*
237 * Shows usage.
238 */
239static void usage(void) {
240 fprintf(stderr, "Copyright (C) 2007 The Android Open Source Project\n\n");
241 fprintf(stderr, "%s: [-m p.c.m] [-o outfile] dexfile...\n", gProgName);
242 fprintf(stderr, "\n");
243}
244
245/*
246 * Main driver of the dexlist utility.
247 */
248int dexlistDriver(int argc, char** argv) {
Aart Bik3e40f4a2015-07-07 17:09:41 -0700249 // Reset options.
250 bool wantUsage = false;
251 memset(&gOptions, 0, sizeof(gOptions));
252
253 // Parse all arguments.
254 while (1) {
255 const int ic = getopt(argc, argv, "o:m:");
256 if (ic < 0) {
257 break; // done
258 }
259 switch (ic) {
260 case 'o': // output file
261 gOptions.outputFileName = optarg;
262 break;
263 case 'm':
Aart Bikb1b45be2015-08-28 11:09:29 -0700264 // If -m p.c.m is given, then find all instances of the
Aart Bik3e40f4a2015-07-07 17:09:41 -0700265 // fully-qualified method name. This isn't really what
266 // dexlist is for, but it's easy to do it here.
267 {
268 gOptions.argCopy = strdup(optarg);
269 char* meth = strrchr(gOptions.argCopy, '.');
270 if (meth == nullptr) {
271 fprintf(stderr, "Expected: package.Class.method\n");
272 wantUsage = true;
273 } else {
274 *meth = '\0';
275 gOptions.classToFind = gOptions.argCopy;
276 gOptions.methodToFind = meth + 1;
277 }
278 }
279 break;
280 default:
281 wantUsage = true;
282 break;
283 } // switch
284 } // while
285
286 // Detect early problems.
287 if (optind == argc) {
288 fprintf(stderr, "%s: no file specified\n", gProgName);
289 wantUsage = true;
290 }
291 if (wantUsage) {
292 usage();
293 free(gOptions.argCopy);
294 return 2;
295 }
296
297 // Open alternative output file.
298 if (gOptions.outputFileName) {
299 gOutFile = fopen(gOptions.outputFileName, "w");
300 if (!gOutFile) {
301 fprintf(stderr, "Can't open %s\n", gOptions.outputFileName);
302 free(gOptions.argCopy);
303 return 1;
304 }
305 }
306
307 // Process all files supplied on command line. If one of them fails we
308 // continue on, only returning a failure at the end.
309 int result = 0;
310 while (optind < argc) {
311 result |= processFile(argv[optind++]);
312 } // while
313
314 free(gOptions.argCopy);
315 return result != 0;
316}
317
318} // namespace art
319
320int main(int argc, char** argv) {
321 return art::dexlistDriver(argc, argv);
322}
323