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