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