1 /*
2  * Copyright (C) 2010 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 
17 package com.android.cts.apicoverage;
18 
19 import com.android.compatibility.common.util.CddTest;
20 import com.android.compatibility.common.util.ReadElf;
21 
22 import org.jf.dexlib2.DexFileFactory;
23 import org.jf.dexlib2.Opcodes;
24 import org.jf.dexlib2.iface.Annotation;
25 import org.jf.dexlib2.iface.AnnotationElement;
26 import org.jf.dexlib2.iface.ClassDef;
27 import org.jf.dexlib2.iface.DexFile;
28 import org.jf.dexlib2.iface.Method;
29 import org.jf.dexlib2.iface.value.StringEncodedValue;
30 
31 import org.xml.sax.InputSource;
32 import org.xml.sax.SAXException;
33 import org.xml.sax.XMLReader;
34 import org.xml.sax.helpers.XMLReaderFactory;
35 
36 import java.io.File;
37 import java.io.FilenameFilter;
38 import java.io.FileOutputStream;
39 import java.io.FileReader;
40 import java.io.IOException;
41 import java.io.OutputStream;
42 import java.util.Arrays;
43 import java.util.ArrayList;
44 import java.util.Collection;
45 import java.util.List;
46 import java.util.Locale;
47 import java.util.Set;
48 import java.util.concurrent.ExecutorService;
49 import java.util.concurrent.Executors;
50 import java.util.concurrent.Future;
51 
52 import javax.xml.transform.TransformerException;
53 
54 /**
55  * Tool that generates a report of what Android framework methods are being called from a given
56  * set of APKS. See the {@link #printUsage()} method for more details.
57  */
58 public class CtsApiCoverage {
59 
60     private static final FilenameFilter SUPPORTED_FILE_NAME_FILTER = new FilenameFilter() {
61         public boolean accept(File dir, String name) {
62             String fileName = name.toLowerCase();
63             return fileName.endsWith(".apk") || fileName.endsWith(".jar");
64         }
65     };
66 
67     private static final int FORMAT_TXT = 0;
68 
69     private static final int FORMAT_XML = 1;
70 
71     private static final int FORMAT_HTML = 2;
72 
73     private static final String CDD_REQUIREMENT_ANNOTATION = "Lcom/android/compatibility/common/util/CddTest;";
74 
75     private static final String CDD_REQUIREMENT_ELEMENT_NAME = "requirement";
76 
77     private static final String NDK_PACKAGE_NAME = "ndk";
78 
printUsage()79     private static void printUsage() {
80         System.out.println("Usage: cts-api-coverage [OPTION]... [APK]...");
81         System.out.println();
82         System.out.println("Generates a report about what Android framework methods are called ");
83         System.out.println("from the given APKs.");
84         System.out.println();
85         System.out.println("Use the Makefiles rules in CtsCoverage.mk to generate the report ");
86         System.out.println("rather than executing this directly. If you still want to run this ");
87         System.out.println("directly, then this must be used from the $ANDROID_BUILD_TOP ");
88         System.out.println("directory and dexdeps must be built via \"make dexdeps\".");
89         System.out.println();
90         System.out.println("Options:");
91         System.out.println("  -o FILE                output file or standard out if not given");
92         System.out.println("  -f [txt|xml|html]      format of output");
93         System.out.println("  -d PATH                path to dexdeps or expected to be in $PATH");
94         System.out.println("  -a PATH                path to the API XML file");
95         System.out.println(
96                 "  -n PATH                path to the NDK API XML file, which can be updated via ndk-api-report with the ndk target");
97         System.out.println("  -p PACKAGENAMEPREFIX   report coverage only for package that start with");
98         System.out.println("  -t TITLE               report title");
99         System.out.println("  -a API                 the Android API Level");
100         System.out.println("  -b BITS                64 or 32 bits, default 64");
101         System.out.println();
102         System.exit(1);
103     }
104 
main(String[] args)105     public static void main(String[] args) throws Exception {
106         List<File> testApks = new ArrayList<File>();
107         File outputFile = null;
108         int format = FORMAT_TXT;
109         String dexDeps = "dexDeps";
110         String apiXmlPath = "";
111         String napiXmlPath = "";
112         PackageFilter packageFilter = new PackageFilter();
113         String reportTitle = "CTS API Coverage";
114         int apiLevel = Integer.MAX_VALUE;
115         String testCasesFolder = "";
116         String bits = "64";
117 
118         List<File> notFoundTestApks = new ArrayList<File>();
119         int numTestApkArgs = 0;
120         for (int i = 0; i < args.length; i++) {
121             if (args[i].startsWith("-")) {
122                 if ("-o".equals(args[i])) {
123                     outputFile = new File(getExpectedArg(args, ++i));
124                 } else if ("-f".equals(args[i])) {
125                     String formatSpec = getExpectedArg(args, ++i);
126                     if ("xml".equalsIgnoreCase(formatSpec)) {
127                         format = FORMAT_XML;
128                     } else if ("txt".equalsIgnoreCase(formatSpec)) {
129                         format = FORMAT_TXT;
130                     } else if ("html".equalsIgnoreCase(formatSpec)) {
131                         format = FORMAT_HTML;
132                     } else {
133                         printUsage();
134                     }
135                 } else if ("-d".equals(args[i])) {
136                     dexDeps = getExpectedArg(args, ++i);
137                 } else if ("-a".equals(args[i])) {
138                     apiXmlPath = getExpectedArg(args, ++i);
139                 } else if ("-n".equals(args[i])) {
140                     napiXmlPath = getExpectedArg(args, ++i);
141                 } else if ("-p".equals(args[i])) {
142                     packageFilter.addPrefixToFilter(getExpectedArg(args, ++i));
143                 } else if ("-t".equals(args[i])) {
144                     reportTitle = getExpectedArg(args, ++i);
145                 } else if ("-a".equals(args[i])) {
146                     apiLevel = Integer.parseInt(getExpectedArg(args, ++i));
147                 } else if ("-b".equals(args[i])) {
148                     bits = getExpectedArg(args, ++i);
149                 } else {
150                     printUsage();
151                 }
152             } else {
153                 File file = new File(args[i]);
154                 numTestApkArgs++;
155                 if (file.isDirectory()) {
156                     testApks.addAll(Arrays.asList(file.listFiles(SUPPORTED_FILE_NAME_FILTER)));
157                     testCasesFolder = args[i];
158                 } else if (file.isFile()) {
159                     testApks.add(file);
160                 } else {
161                     notFoundTestApks.add(file);
162                 }
163             }
164         }
165 
166         if (!notFoundTestApks.isEmpty()) {
167             String msg = String.format(Locale.US, "%d/%d testApks not found: %s",
168                     notFoundTestApks.size(), numTestApkArgs, notFoundTestApks);
169             throw new IllegalArgumentException(msg);
170         }
171 
172         /*
173          * 1. Create an ApiCoverage object that is a tree of Java objects representing the API
174          *    in current.xml. The object will have no information about the coverage for each
175          *    constructor or method yet.
176          *
177          * 2. For each provided APK, scan it using dexdeps, parse the output of dexdeps, and
178          *    call methods on the ApiCoverage object to cumulatively add coverage stats.
179          *
180          * 3. Output a report based on the coverage stats in the ApiCoverage object.
181          */
182 
183         ApiCoverage apiCoverage = getEmptyApiCoverage(apiXmlPath);
184         CddCoverage cddCoverage = getEmptyCddCoverage();
185 
186         if (!napiXmlPath.equals("")) {
187             System.out.println("napiXmlPath: " + napiXmlPath);
188             ApiCoverage napiCoverage = getEmptyApiCoverage(napiXmlPath);
189             ApiPackage napiPackage = napiCoverage.getPackage(NDK_PACKAGE_NAME);
190             System.out.println(
191                     String.format(
192                             "%s, NDK Methods = %d, MemberSize = %d",
193                             napiXmlPath,
194                             napiPackage.getTotalMethods(),
195                             napiPackage.getMemberSize()));
196             apiCoverage.addPackage(napiPackage);
197         }
198 
199         // Add superclass information into api coverage.
200         apiCoverage.resolveSuperClasses();
201 
202         ExecutorService service =
203             Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
204         List<Future> tasks = new ArrayList<>();
205         for (File testApk : testApks) {
206             tasks.add(addApiCoverage(service, apiCoverage, testApk, dexDeps));
207             tasks.add(addCddCoverage(service, cddCoverage, testApk, apiLevel));
208         }
209         // Wait until all tasks finish.
210         for (Future task : tasks) {
211             task.get();
212         }
213         service.shutdown();
214 
215         // The below two coverage methods assume all classes and methods have been already
216         // registered, which is why we don't run them parallelly with others.
217 
218         try {
219             // Add coverage for GTest modules
220             addGTestNdkApiCoverage(apiCoverage, testCasesFolder, bits);
221         } catch (Exception e) {
222             System.out.println("warning: addGTestNdkApiCoverage failed to add to apiCoverage:");
223             e.printStackTrace();
224         }
225 
226         try {
227             // Add coverage for APK with Share Objects
228             addNdkApiCoverage(apiCoverage, testCasesFolder, bits);
229         } catch (Exception e) {
230             System.out.println("warning: addNdkApiCoverage failed to add to apiCoverage:");
231             e.printStackTrace();
232         }
233 
234         outputCoverageReport(apiCoverage, cddCoverage, testApks, outputFile,
235             format, packageFilter, reportTitle);
236     }
237 
238     /** Get the argument or print out the usage and exit. */
getExpectedArg(String[] args, int index)239     private static String getExpectedArg(String[] args, int index) {
240         if (index < args.length) {
241             return args[index];
242         } else {
243             printUsage();
244             return null;    // Never will happen because printUsage will call exit(1)
245         }
246     }
247 
248     /**
249      * Creates an object representing the API that will be used later to collect coverage
250      * statistics as we iterate over the test APKs.
251      *
252      * @param apiXmlPath to the API XML file
253      * @return an {@link ApiCoverage} object representing the API in current.xml without any
254      *     coverage statistics yet
255      */
getEmptyApiCoverage(String apiXmlPath)256     private static ApiCoverage getEmptyApiCoverage(String apiXmlPath)
257             throws SAXException, IOException {
258         XMLReader xmlReader = XMLReaderFactory.createXMLReader();
259         CurrentXmlHandler currentXmlHandler = new CurrentXmlHandler();
260         xmlReader.setContentHandler(currentXmlHandler);
261 
262         File currentXml = new File(apiXmlPath);
263         FileReader fileReader = null;
264         try {
265             fileReader = new FileReader(currentXml);
266             xmlReader.parse(new InputSource(fileReader));
267         } finally {
268             if (fileReader != null) {
269                 fileReader.close();
270             }
271         }
272 
273         return currentXmlHandler.getApi();
274     }
275 
276     /**
277      * Adds coverage information gleamed from running dexdeps on the APK to the
278      * {@link ApiCoverage} object.
279      *
280      * @param apiCoverage object to which the coverage statistics will be added to
281      * @param testApk containing the tests that will be scanned by dexdeps
282      */
addApiCoverage( ExecutorService service, ApiCoverage apiCoverage, File testApk, String dexdeps)283     private static Future addApiCoverage(
284         ExecutorService service, ApiCoverage apiCoverage, File testApk, String dexdeps) {
285         return service.submit(() -> {
286             String apkPath = testApk.getPath();
287             try {
288                 XMLReader xmlReader = XMLReaderFactory.createXMLReader();
289                 String testApkName = testApk.getName();
290                 DexDepsXmlHandler dexDepsXmlHandler = new DexDepsXmlHandler(apiCoverage, testApkName);
291                 xmlReader.setContentHandler(dexDepsXmlHandler);
292 
293                 Process process = new ProcessBuilder(dexdeps, "--format=xml", apkPath).start();
294                 xmlReader.parse(new InputSource(process.getInputStream()));
295             } catch (SAXException e) {
296                 // Catch this exception, but continue. SAXException is acceptable in cases
297                 // where the apk does not contain a classes.dex and therefore parsing won't work.
298                 System.err.println("warning: dexdeps failed for: " + apkPath);
299             } catch (IOException e) {
300                 throw new RuntimeException(e);
301             }
302         });
303     }
304 
305     /**
306      * Adds coverage information from native code symbol array to the {@link ApiCoverage} object.
307      *
308      * @param apiPackage object to which the coverage statistics will be added to
309      * @param symArr containing native code symbols
310      * @param testModules containing a list of TestModule
311      * @param moduleName test module name
312      */
addNdkSymArrToApiCoverage( ApiCoverage apiCoverage, List<TestModule> testModules)313     private static void addNdkSymArrToApiCoverage(
314             ApiCoverage apiCoverage, List<TestModule> testModules)
315             throws SAXException, IOException {
316 
317         final List<String> parameterTypes = new ArrayList<String>();
318         final ApiPackage apiPackage = apiCoverage.getPackage(NDK_PACKAGE_NAME);
319 
320         if (apiPackage != null) {
321             for (TestModule tm : testModules) {
322                 final String moduleName = tm.getModuleName();
323                 final ReadElf.Symbol[] symArr = tm.getDynSymArr();
324                 if (symArr != null) {
325                     for (ReadElf.Symbol sym : symArr) {
326                         if (sym.isGlobalUnd()) {
327                             String className = sym.getExternalLibFileName();
328                             ApiClass apiClass = apiPackage.getClass(className);
329                             if (apiClass != null) {
330                                 apiClass.markMethodCovered(
331                                         sym.name,
332                                         parameterTypes,
333                                         moduleName);
334                             } else {
335                                 System.err.println(
336                                         String.format(
337                                                 "warning: addNdkApiCoverage failed to getClass: %s",
338                                                 className));
339                             }
340                         }
341                     }
342                 } else {
343                     System.err.println(
344                             String.format(
345                                     "warning: addNdkSymbolArrToApiCoverage failed to getSymArr: %s",
346                                     moduleName));
347                 }
348             }
349         } else {
350             System.err.println(
351                     String.format(
352                             "warning: addNdkApiCoverage failed to getPackage: %s",
353                             NDK_PACKAGE_NAME));
354         }
355     }
356 
357     /**
358      * Adds coverage information gleamed from readelf on so in the APK to the {@link ApiCoverage}
359      * object.
360      *
361      * @param apiCoverage object to which the coverage statistics will be added to
362      * @param testCasesFolder containing GTest modules
363      * @param bits 64 or 32 bits of executiable
364      */
addNdkApiCoverage( ApiCoverage apiCoverage, String testCasesFolder, String bits)365     private static void addNdkApiCoverage(
366             ApiCoverage apiCoverage, String testCasesFolder, String bits)
367             throws SAXException, IOException {
368         ApkNdkApiReport apiReport = ApkNdkApiReport.parseTestcasesFolder(testCasesFolder, bits);
369         if (apiReport != null) {
370             addNdkSymArrToApiCoverage(apiCoverage, apiReport.getTestModules());
371         } else {
372             System.err.println(
373                     String.format(
374                             "warning: addNdkApiCoverage failed to get GTestApiReport from: %s @ %s bits",
375                             testCasesFolder, bits));
376         }
377     }
378 
379     /**
380      * Adds GTest coverage information gleamed from running ReadElf on the executiable to the {@link
381      * ApiCoverage} object.
382      *
383      * @param apiCoverage object to which the coverage statistics will be added to
384      * @param testCasesFolder containing GTest modules
385      * @param bits 64 or 32 bits of executiable
386      */
addGTestNdkApiCoverage( ApiCoverage apiCoverage, String testCasesFolder, String bits)387     private static void addGTestNdkApiCoverage(
388             ApiCoverage apiCoverage, String testCasesFolder, String bits)
389             throws SAXException, IOException {
390         GTestApiReport apiReport = GTestApiReport.parseTestcasesFolder(testCasesFolder, bits);
391         if (apiReport != null) {
392             addNdkSymArrToApiCoverage(apiCoverage, apiReport.getTestModules());
393         } else {
394             System.err.println(
395                     String.format(
396                             "warning: addGTestNdkApiCoverage failed to get GTestApiReport from: %s @ %s bits",
397                             testCasesFolder, bits));
398         }
399     }
400 
addCddCoverage( ExecutorService service, CddCoverage cddCoverage, File testSource, int api)401     private static Future addCddCoverage(
402         ExecutorService service, CddCoverage cddCoverage, File testSource, int api) {
403         return service.submit(() -> {
404             try {
405                 if (testSource.getName().endsWith(".apk")) {
406                     addCddApkCoverage(cddCoverage, testSource, api);
407                 } else if (testSource.getName().endsWith(".jar")) {
408                     addCddJarCoverage(cddCoverage, testSource);
409                 } else {
410                     System.err
411                         .println("Unsupported file type for CDD coverage: " + testSource.getPath());
412                 }
413             } catch (IOException e) {
414                 throw new RuntimeException(e);
415             }
416         });
417     }
418 
419     private static void addCddJarCoverage(CddCoverage cddCoverage, File testSource)
420             throws IOException {
421 
422         Collection<Class<?>> classes = JarTestFinder.getClasses(testSource);
423         for (Class<?> c : classes) {
424             for (java.lang.reflect.Method m : c.getMethods()) {
425                 if (m.isAnnotationPresent(CddTest.class)) {
426                     CddTest cddTest = m.getAnnotation(CddTest.class);
427                     CddCoverage.TestMethod testMethod =
428                             new CddCoverage.TestMethod(
429                                     testSource.getName(), c.getName(), m.getName());
430                     cddCoverage.addCoverage(cddTest.requirement(), testMethod);
431                 }
432             }
433         }
434     }
435 
436     private static void addCddApkCoverage(
437         CddCoverage cddCoverage, File testSource, int api)
438             throws IOException {
439 
440         DexFile dexFile = null;
441         try {
442             dexFile = DexFileFactory.loadDexFile(testSource, Opcodes.forApi(api));
443         } catch (IOException | DexFileFactory.DexFileNotFoundException e) {
444             System.err.println("Unable to load dex file: " + testSource.getPath());
445             return;
446         }
447 
448         String moduleName = testSource.getName();
449         for (ClassDef classDef : dexFile.getClasses()) {
450             String className = classDef.getType();
451             handleAnnotations(
452                 cddCoverage, moduleName, className, null /*methodName*/,
453                 classDef.getAnnotations());
454 
455             for (Method method : classDef.getMethods()) {
456                 String methodName = method.getName();
457                 handleAnnotations(
458                     cddCoverage, moduleName, className, methodName, method.getAnnotations());
459             }
460         }
461     }
462 
463     private static void handleAnnotations(
464             CddCoverage cddCoverage, String moduleName, String className,
465                     String methodName, Set<? extends Annotation> annotations) {
466         for (Annotation annotation : annotations) {
467             if (annotation.getType().equals(CDD_REQUIREMENT_ANNOTATION)) {
468                 for (AnnotationElement annotationElement : annotation.getElements()) {
469                     if (annotationElement.getName().equals(CDD_REQUIREMENT_ELEMENT_NAME)) {
470                         String cddRequirement =
471                                 ((StringEncodedValue) annotationElement.getValue()).getValue();
472                         CddCoverage.TestMethod testMethod =
473                                 new CddCoverage.TestMethod(
474                                         moduleName, dexToJavaName(className), methodName);
475                         cddCoverage.addCoverage(cddRequirement, testMethod);
476                     }
477                 }
478             }
479         }
480     }
481 
482     /**
483      * Given a string like Landroid/app/cts/DownloadManagerTest;
484      * return android.app.cts.DownloadManagerTest.
485      */
486     private static String dexToJavaName(String dexName) {
487         if (!dexName.startsWith("L") || !dexName.endsWith(";")) {
488             return dexName;
489         }
490         dexName = dexName.replace('/', '.');
491         if (dexName.length() > 2) {
492             dexName = dexName.substring(1, dexName.length() - 1);
493         }
494         return dexName;
495     }
496 
497     private static CddCoverage getEmptyCddCoverage() {
498         CddCoverage cddCoverage = new CddCoverage();
499         // TODO(nicksauer): Read in the valid list of requirements
500         return cddCoverage;
501     }
502 
503     private static void outputCoverageReport(ApiCoverage apiCoverage, CddCoverage cddCoverage,
504             List<File> testApks, File outputFile, int format, PackageFilter packageFilter,
505             String reportTitle)
506                 throws IOException, TransformerException, InterruptedException {
507 
508         OutputStream out = outputFile != null
509                 ? new FileOutputStream(outputFile)
510                 : System.out;
511 
512         try {
513             switch (format) {
514                 case FORMAT_TXT:
515                     TextReport.printTextReport(apiCoverage, cddCoverage, packageFilter, out);
516                     break;
517 
518                 case FORMAT_XML:
519                     XmlReport.printXmlReport(testApks, apiCoverage, cddCoverage,
520                         packageFilter, reportTitle, out);
521                     break;
522 
523                 case FORMAT_HTML:
524                     HtmlReport.printHtmlReport(testApks, apiCoverage, cddCoverage,
525                         packageFilter, reportTitle, out);
526                     break;
527             }
528         } finally {
529             out.close();
530         }
531     }
532 }
533