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