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