• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 <inttypes.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 
30 #include <android-base/file.h>
31 #include <android-base/logging.h>
32 
33 #include "base/mem_map.h"
34 #include "dex/class_accessor-inl.h"
35 #include "dex/code_item_accessors-inl.h"
36 #include "dex/dex_file-inl.h"
37 #include "dex/dex_file_loader.h"
38 
39 namespace art {
40 
41 static const char* gProgName = "dexlist";
42 
43 /* Command-line options. */
44 static 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  */
54 static FILE* gOutFile = stdout;
55 
56 /*
57  * Data types that match the definitions in the VM specification.
58  */
59 using u1 = uint8_t;
60 using u4 = uint32_t;
61 using u8 = uint64_t;
62 
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  */
descriptorToDot(const char * str)69 static std::unique_ptr<char[]> descriptorToDot(const char* str) {
70   size_t len = strlen(str);
71   if (str[0] == 'L') {
72     len -= 2;  // Two fewer chars to copy (trims L and ;).
73     str++;     // Start past 'L'.
74   }
75   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];
78   }
79   newStr[len] = '\0';
80   return newStr;
81 }
82 
83 /*
84  * Dumps a method.
85  */
dumpMethod(const DexFile * pDexFile,const char * fileName,u4 idx,u4 flags ATTRIBUTE_UNUSED,const dex::CodeItem * pCode,u4 codeOffset)86 static void dumpMethod(const DexFile* pDexFile,
87                        const char* fileName, u4 idx, u4 flags ATTRIBUTE_UNUSED,
88                        const dex::CodeItem* pCode, u4 codeOffset) {
89   // Abstract and native methods don't get listed.
90   if (pCode == nullptr || codeOffset == 0) {
91     return;
92   }
93   CodeItemDebugInfoAccessor accessor(*pDexFile, pCode, idx);
94 
95   // Method information.
96   const dex::MethodId& pMethodId = pDexFile->GetMethodId(idx);
97   const char* methodName = pDexFile->StringDataByIdx(pMethodId.name_idx_);
98   const char* classDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
99   std::unique_ptr<char[]> className(descriptorToDot(classDescriptor));
100   const u4 insnsOff = codeOffset + 0x10;
101 
102   // Don't list methods that do not match a particular query.
103   if (gOptions.methodToFind != nullptr &&
104       (strcmp(gOptions.classToFind, className.get()) != 0 ||
105        strcmp(gOptions.methodToFind, methodName) != 0)) {
106     return;
107   }
108 
109   // If the filename is empty, then set it to something printable.
110   if (fileName == nullptr || fileName[0] == 0) {
111     fileName = "(none)";
112   }
113 
114   // We just want to catch the number of the first line in the method, which *should* correspond to
115   // the first entry from the table.
116   int first_line = -1;
117   accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
118     first_line = entry.line_;
119     return true;  // Early exit since we only want the first line.
120   });
121 
122   // Method signature.
123   const Signature signature = pDexFile->GetMethodSignature(pMethodId);
124   char* typeDesc = strdup(signature.ToString().c_str());
125 
126   // Dump actual method information.
127   fprintf(gOutFile, "0x%08x %d %s %s %s %s %d\n",
128           insnsOff, accessor.InsnsSizeInCodeUnits() * 2,
129           className.get(), methodName, typeDesc, fileName, first_line);
130 
131   free(typeDesc);
132 }
133 
134 /*
135  * Runs through all direct and virtual methods in the class.
136  */
dumpClass(const DexFile * pDexFile,u4 idx)137 void dumpClass(const DexFile* pDexFile, u4 idx) {
138   const dex::ClassDef& class_def = pDexFile->GetClassDef(idx);
139 
140   const char* fileName = nullptr;
141   if (class_def.source_file_idx_.IsValid()) {
142     fileName = pDexFile->StringDataByIdx(class_def.source_file_idx_);
143   }
144 
145   ClassAccessor accessor(*pDexFile, class_def);
146   for (const ClassAccessor::Method& method : accessor.GetMethods()) {
147     dumpMethod(pDexFile,
148                fileName,
149                method.GetIndex(),
150                method.GetAccessFlags(),
151                method.GetCodeItem(),
152                method.GetCodeItemOffset());
153   }
154 }
155 
156 /*
157  * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
158  */
processFile(const char * fileName)159 static int processFile(const char* fileName) {
160   // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
161   // all of which are Zip archives with "classes.dex" inside.
162   static constexpr bool kVerifyChecksum = true;
163   std::string content;
164   // TODO: add an api to android::base to read a std::vector<uint8_t>.
165   if (!android::base::ReadFileToString(fileName, &content)) {
166     LOG(ERROR) << "ReadFileToString failed";
167     return -1;
168   }
169   std::vector<std::unique_ptr<const DexFile>> dex_files;
170   DexFileLoaderErrorCode error_code;
171   std::string error_msg;
172   DexFileLoader dex_file_loader(
173       reinterpret_cast<const uint8_t*>(content.data()), content.size(), fileName);
174   if (!dex_file_loader.Open(
175           /*verify=*/true, kVerifyChecksum, &error_code, &error_msg, &dex_files)) {
176     LOG(ERROR) << error_msg;
177     return -1;
178   }
179 
180   // Success. Iterate over all dex files found in given file.
181   fprintf(gOutFile, "#%s\n", fileName);
182   for (size_t i = 0; i < dex_files.size(); i++) {
183     // Iterate over all classes in one dex file.
184     const DexFile* pDexFile = dex_files[i].get();
185     const u4 classDefsSize = pDexFile->GetHeader().class_defs_size_;
186     for (u4 idx = 0; idx < classDefsSize; idx++) {
187       dumpClass(pDexFile, idx);
188     }
189   }
190   return 0;
191 }
192 
193 /*
194  * Shows usage.
195  */
usage()196 static void usage() {
197   LOG(ERROR) << "Copyright (C) 2007 The Android Open Source Project\n";
198   LOG(ERROR) << gProgName << ": [-m p.c.m] [-o outfile] dexfile...";
199   LOG(ERROR) << "";
200 }
201 
202 /*
203  * Main driver of the dexlist utility.
204  */
dexlistDriver(int argc,char ** argv)205 int dexlistDriver(int argc, char** argv) {
206   // Reset options.
207   bool wantUsage = false;
208   memset(&gOptions, 0, sizeof(gOptions));
209 
210   // Parse all arguments.
211   while (true) {
212     const int ic = getopt(argc, argv, "o:m:");
213     if (ic < 0) {
214       break;  // done
215     }
216     switch (ic) {
217       case 'o':  // output file
218         gOptions.outputFileName = optarg;
219         break;
220       case 'm':
221         // If -m p.c.m is given, then find all instances of the
222         // fully-qualified method name. This isn't really what
223         // dexlist is for, but it's easy to do it here.
224         {
225           gOptions.argCopy = strdup(optarg);
226           char* meth = strrchr(gOptions.argCopy, '.');
227           if (meth == nullptr) {
228             LOG(ERROR) << "Expected: package.Class.method";
229             wantUsage = true;
230           } else {
231             *meth = '\0';
232             gOptions.classToFind = gOptions.argCopy;
233             gOptions.methodToFind = meth + 1;
234           }
235         }
236         break;
237       default:
238         wantUsage = true;
239         break;
240     }  // switch
241   }  // while
242 
243   // Detect early problems.
244   if (optind == argc) {
245     LOG(ERROR) << "No file specified";
246     wantUsage = true;
247   }
248   if (wantUsage) {
249     usage();
250     free(gOptions.argCopy);
251     return 2;
252   }
253 
254   // Open alternative output file.
255   if (gOptions.outputFileName) {
256     gOutFile = fopen(gOptions.outputFileName, "we");
257     if (!gOutFile) {
258       PLOG(ERROR) << "Can't open " << gOptions.outputFileName;
259       free(gOptions.argCopy);
260       return 1;
261     }
262   }
263 
264   // Process all files supplied on command line. If one of them fails we
265   // continue on, only returning a failure at the end.
266   int result = 0;
267   while (optind < argc) {
268     result |= processFile(argv[optind++]);
269   }  // while
270 
271   free(gOptions.argCopy);
272   return result != 0 ? 1 : 0;
273 }
274 
275 }  // namespace art
276 
main(int argc,char ** argv)277 int main(int argc, char** argv) {
278   // Output all logging to stderr.
279   android::base::SetLogger(android::base::StderrLogger);
280   art::MemMap::Init();
281 
282   return art::dexlistDriver(argc, argv);
283 }
284 
285