1 /*
2  * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 package jdk.tools.jaotc;
25 
26 import java.io.BufferedReader;
27 import java.io.FileNotFoundException;
28 import java.io.FileReader;
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Set;
34 
35 import jdk.tools.jaotc.collect.ClassSearch;
36 import jdk.tools.jaotc.collect.FileSupport;
37 import jdk.tools.jaotc.collect.classname.ClassNameSourceProvider;
38 import jdk.tools.jaotc.collect.directory.DirectorySourceProvider;
39 import jdk.tools.jaotc.collect.jar.JarSourceProvider;
40 import jdk.tools.jaotc.collect.module.ModuleSourceProvider;
41 import jdk.vm.ci.meta.MetaAccessProvider;
42 import jdk.vm.ci.meta.ResolvedJavaMethod;
43 import jdk.vm.ci.meta.ResolvedJavaType;
44 
45 final class Collector {
46 
47     private final Main main;
48 
Collector(Main main)49     Collector(Main main) {
50         this.main = main;
51     }
52 
collectClassesToCompile()53     Set<Class<?>> collectClassesToCompile() {
54         Set<Class<?>> classesToCompile = new HashSet<>();
55         FileSupport fileSupport = new FileSupport();
56         ClassSearch lookup = new ClassSearch();
57         lookup.addProvider(new ModuleSourceProvider());
58         lookup.addProvider(new ClassNameSourceProvider(fileSupport));
59         lookup.addProvider(new JarSourceProvider());
60         lookup.addProvider(new DirectorySourceProvider(fileSupport));
61 
62         List<LoadedClass> foundClasses = null;
63         try {
64             foundClasses = lookup.search(main.options.files, main.options.searchPath, this::handleLoadingError);
65         } catch (InternalError e) {
66             main.printer.reportError(e);
67             return null;
68         }
69 
70         for (LoadedClass loadedClass : foundClasses) {
71             classesToCompile.add(loadedClass.getLoadedClass());
72         }
73         return classesToCompile;
74     }
75 
addMethods(AOTCompiledClass aotClass, ResolvedJavaMethod[] methods, CompilationSpec compilationRestrictions)76     private void addMethods(AOTCompiledClass aotClass, ResolvedJavaMethod[] methods, CompilationSpec compilationRestrictions) {
77         for (ResolvedJavaMethod m : methods) {
78             addMethod(aotClass, m, compilationRestrictions);
79         }
80     }
81 
addMethod(AOTCompiledClass aotClass, ResolvedJavaMethod method, CompilationSpec compilationRestrictions)82     private void addMethod(AOTCompiledClass aotClass, ResolvedJavaMethod method, CompilationSpec compilationRestrictions) {
83         // Don't compile native or abstract methods.
84         if (!method.hasBytecodes()) {
85             return;
86         }
87         if (!compilationRestrictions.shouldCompileMethod(method)) {
88             return;
89         }
90         if (!main.filters.shouldCompileMethod(method)) {
91             return;
92         }
93 
94         aotClass.addMethod(method);
95         main.printer.printlnVerbose("  added " + method.getName() + method.getSignature().toMethodDescriptor());
96     }
97 
98     /**
99      * Collect all method we should compile.
100      *
101      * @return array list of AOT classes which have compiled methods.
102      */
collectMethodsToCompile(Set<Class<?>> classesToCompile, MetaAccessProvider metaAccess)103     List<AOTCompiledClass> collectMethodsToCompile(Set<Class<?>> classesToCompile, MetaAccessProvider metaAccess) {
104         int total = 0;
105         int count = 0;
106         List<AOTCompiledClass> classes = new ArrayList<>();
107         CompilationSpec compilationRestrictions = collectSpecifiedMethods();
108 
109         for (Class<?> c : classesToCompile) {
110             ResolvedJavaType resolvedJavaType = metaAccess.lookupJavaType(c);
111             if (main.filters.shouldCompileAnyMethodInClass(resolvedJavaType)) {
112                 AOTCompiledClass aotClass = new AOTCompiledClass(resolvedJavaType);
113                 main.printer.printlnVerbose(" Scanning " + c.getName());
114 
115                 // Constructors
116                 try {
117                     ResolvedJavaMethod[] ctors = resolvedJavaType.getDeclaredConstructors();
118                     addMethods(aotClass, ctors, compilationRestrictions);
119                     total += ctors.length;
120                 } catch (Throwable e) {
121                     handleLoadingError(c.getName(), e);
122                 }
123 
124                 // Methods
125                 try {
126                     ResolvedJavaMethod[] methods = resolvedJavaType.getDeclaredMethods();
127                     addMethods(aotClass, methods, compilationRestrictions);
128                     total += methods.length;
129                 } catch (Throwable e) {
130                     handleLoadingError(c.getName(), e);
131                 }
132 
133                 // Class initializer
134                 try {
135                     ResolvedJavaMethod clinit = resolvedJavaType.getClassInitializer();
136                     if (clinit != null) {
137                         addMethod(aotClass, clinit, compilationRestrictions);
138                         total++;
139                     }
140                 } catch (Throwable e) {
141                     handleLoadingError(c.getName(), e);
142                 }
143 
144                 // Found any methods to compile? Add the class.
145                 if (aotClass.hasMethods()) {
146                     classes.add(aotClass);
147                     count += aotClass.getMethodCount();
148                 }
149             }
150         }
151         main.printer.printInfo(total + " methods total, " + count + " methods to compile");
152         return classes;
153     }
154 
155     /**
156      * If a file with compilation limitations is specified using flag --compile-commands, read the
157      * file's contents and collect the restrictions.
158      */
collectSpecifiedMethods()159     private CompilationSpec collectSpecifiedMethods() {
160         CompilationSpec compilationRestrictions = new CompilationSpec();
161         String methodListFileName = main.options.methodList;
162 
163         if (methodListFileName != null && !methodListFileName.equals("")) {
164             try {
165                 FileReader methListFile = new FileReader(methodListFileName);
166                 BufferedReader readBuf = new BufferedReader(methListFile);
167                 String line = null;
168                 while ((line = readBuf.readLine()) != null) {
169                     String trimmedLine = line.trim();
170                     if (!trimmedLine.startsWith("#")) {
171                         String[] components = trimmedLine.split(" ");
172                         if (components.length == 2) {
173                             String directive = components[0];
174                             String pattern = components[1];
175                             switch (directive) {
176                                 case "compileOnly":
177                                     compilationRestrictions.addCompileOnlyPattern(pattern);
178                                     break;
179                                 case "exclude":
180                                     compilationRestrictions.addExcludePattern(pattern);
181                                     break;
182                                 default:
183                                     System.out.println("Unrecognized command " + directive + ". Ignoring\n\t" + line + "\n encountered in " + methodListFileName);
184                             }
185                         } else {
186                             if (!trimmedLine.equals("")) {
187                                 System.out.println("Ignoring malformed line:\n\t " + line + "\n");
188                             }
189                         }
190                     }
191                 }
192                 readBuf.close();
193             } catch (FileNotFoundException e) {
194                 throw new InternalError("Unable to open method list file: " + methodListFileName, e);
195             } catch (IOException e) {
196                 throw new InternalError("Unable to read method list file: " + methodListFileName, e);
197             }
198         }
199 
200         return compilationRestrictions;
201     }
202 
handleLoadingError(String name, Throwable t)203     private void handleLoadingError(String name, Throwable t) {
204         if (main.options.ignoreClassLoadingErrors) {
205             main.printer.printError(name + ": " + t);
206         } else {
207             throw new InternalError(t);
208         }
209     }
210 }
211