LVTHarness.java revision 2649:e891e0c4edc5
1/*
2 * Copyright (c) 2013, 2014, 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/*
25 * @test
26 * @bug 7047734 8027660 8037937 8047719 8058708
27 * @summary The LVT is not generated correctly during some try/catch scenarios
28 *          javac crash while creating LVT entry for a local variable defined in
29 *          an inner block
30 * @library /tools/javac/lib
31 * @build JavacTestingAbstractProcessor LVTHarness
32 * @run main LVTHarness
33 */
34
35import java.io.File;
36import java.io.IOException;
37import java.lang.annotation.Annotation;
38import java.util.Set;
39import java.util.Arrays;
40import java.util.ArrayList;
41import java.util.Collections;
42import java.util.HashMap;
43import java.util.HashSet;
44import java.util.List;
45import java.util.Map;
46
47import javax.annotation.processing.RoundEnvironment;
48import javax.lang.model.element.Element;
49import javax.lang.model.element.TypeElement;
50import javax.tools.JavaCompiler;
51import javax.tools.JavaFileObject;
52import javax.tools.StandardJavaFileManager;
53import javax.tools.ToolProvider;
54
55import com.sun.source.util.JavacTask;
56import com.sun.tools.classfile.Attribute;
57import com.sun.tools.classfile.ClassFile;
58import com.sun.tools.classfile.ConstantPool;
59import com.sun.tools.classfile.ConstantPoolException;
60import com.sun.tools.classfile.Code_attribute;
61import com.sun.tools.classfile.ConstantPool.InvalidIndex;
62import com.sun.tools.classfile.ConstantPool.UnexpectedEntry;
63import com.sun.tools.classfile.Descriptor.InvalidDescriptor;
64import com.sun.tools.classfile.LocalVariableTable_attribute;
65import com.sun.tools.classfile.Method;
66
67import static javax.tools.StandardLocation.*;
68import static com.sun.tools.classfile.LocalVariableTable_attribute.Entry;
69import static javax.tools.JavaFileObject.Kind.SOURCE;
70
71public class LVTHarness {
72
73    static int nerrors = 0;
74
75    static final JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
76    static final StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
77
78    public static void main(String[] args) throws Exception {
79
80        String testDir = System.getProperty("test.src");
81        fm.setLocation(SOURCE_PATH, Arrays.asList(new File(testDir, "tests")));
82
83        // Make sure classes are written to scratch dir.
84        fm.setLocation(CLASS_OUTPUT, Arrays.asList(new File(".")));
85
86        for (JavaFileObject jfo : fm.list(SOURCE_PATH, "", Collections.singleton(SOURCE), true)) {
87            new LVTHarness(jfo).check();
88        }
89        if (nerrors > 0) {
90            throw new AssertionError("Errors were found");
91        }
92    }
93
94
95    JavaFileObject jfo;
96    Map<ElementKey, AliveRanges> aliveRangeMap = new HashMap<>();
97    Set<String> declaredKeys = new HashSet<>();
98    List<ElementKey> seenAliveRanges = new ArrayList<>();
99
100    protected LVTHarness(JavaFileObject jfo) {
101        this.jfo = jfo;
102    }
103
104    protected void check() throws Exception {
105
106        JavacTask ct = (JavacTask) comp.getTask(null, fm, null, Arrays.asList("-g"),
107                                                null, Arrays.asList(jfo));
108        System.err.println("compiling code " + jfo);
109        ct.setProcessors(Collections.singleton(new AliveRangeFinder()));
110        if (!ct.call()) {
111            throw new AssertionError("Error during compilation");
112        }
113
114
115        File javaFile = new File(jfo.getName());
116        File classFile = new File(javaFile.getName().replace(".java", ".class"));
117        checkClassFile(classFile);
118
119        //check all candidates have been used up
120        for (Map.Entry<ElementKey, AliveRanges> entry : aliveRangeMap.entrySet()) {
121            if (!seenAliveRanges.contains(entry.getKey())) {
122                error("Redundant @AliveRanges annotation on method " +
123                        entry.getKey().elem + " with key " + entry.getKey());
124            }
125        }
126    }
127
128    void checkClassFile(File file)
129            throws IOException, ConstantPoolException, InvalidDescriptor {
130        ClassFile classFile = ClassFile.read(file);
131        ConstantPool constantPool = classFile.constant_pool;
132
133        //lets get all the methods in the class file.
134        for (Method method : classFile.methods) {
135            for (ElementKey elementKey: aliveRangeMap.keySet()) {
136                String methodDesc = method.getName(constantPool) +
137                        method.descriptor.getParameterTypes(constantPool).replace(" ", "");
138                if (methodDesc.equals(elementKey.elem.toString())) {
139                    checkMethod(constantPool, method, aliveRangeMap.get(elementKey));
140                    seenAliveRanges.add(elementKey);
141                }
142            }
143        }
144    }
145
146    void checkMethod(ConstantPool constantPool, Method method, AliveRanges ranges)
147            throws InvalidIndex, UnexpectedEntry {
148        Code_attribute code = (Code_attribute) method.attributes.get(Attribute.Code);
149        LocalVariableTable_attribute lvt =
150            (LocalVariableTable_attribute) (code.attributes.get(Attribute.LocalVariableTable));
151        List<String> infoFromRanges = convertToStringList(ranges);
152        List<String> infoFromLVT = convertToStringList(constantPool, lvt);
153
154        // infoFromRanges most be contained in infoFromLVT
155        int i = 0;
156        int j = 0;
157        while (i < infoFromRanges.size() && j < infoFromLVT.size()) {
158            int comparison = infoFromRanges.get(i).compareTo(infoFromLVT.get(j));
159            if (comparison == 0) {
160                i++; j++;
161            } else if (comparison > 0) {
162                j++;
163            } else {
164                break;
165            }
166        }
167
168        if (i < infoFromRanges.size()) {
169            error(infoFromLVT, infoFromRanges);
170        }
171    }
172
173    List<String> convertToStringList(AliveRanges ranges) {
174        List<String> result = new ArrayList<>();
175        for (Annotation anno : ranges.value()) {
176            AliveRange range = (AliveRange)anno;
177            String str = formatLocalVariableData(range.varName(),
178                    range.bytecodeStart(), range.bytecodeLength());
179            result.add(str);
180        }
181        Collections.sort(result);
182        return result;
183    }
184
185    List<String> convertToStringList(ConstantPool constantPool,
186            LocalVariableTable_attribute lvt) throws InvalidIndex, UnexpectedEntry {
187        List<String> result = new ArrayList<>();
188        for (Entry entry : lvt.local_variable_table) {
189            String str = formatLocalVariableData(constantPool.getUTF8Value(entry.name_index),
190                    entry.start_pc, entry.length);
191            result.add(str);
192        }
193        Collections.sort(result);
194        return result;
195    }
196
197    String formatLocalVariableData(String varName, int start, int length) {
198        StringBuilder sb = new StringBuilder()
199                    .append("var name: ").append(varName)
200                    .append(" start: ").append(start)
201                    .append(" length: ").append(length);
202        return sb.toString();
203    }
204
205    protected void error(List<String> infoFromLVT, List<String> infoFromRanges) {
206        nerrors++;
207        System.err.printf("Error occurred while checking file: %s\n", jfo.getName());
208        System.err.println("The range info from the annotations is");
209        printStringListToErrOutput(infoFromRanges);
210        System.err.println();
211        System.err.println("And the range info from the class file is");
212        printStringListToErrOutput(infoFromLVT);
213        System.err.println();
214    }
215
216    void printStringListToErrOutput(List<String> list) {
217        for (String s : list) {
218            System.err.println("\t" + s);
219        }
220    }
221
222    protected void error(String msg) {
223        nerrors++;
224        System.err.printf("Error occurred while checking file: %s\nreason: %s\n",
225                jfo.getName(), msg);
226    }
227
228    class AliveRangeFinder extends JavacTestingAbstractProcessor {
229
230        @Override
231        public boolean process(Set<? extends TypeElement> annotations,
232            RoundEnvironment roundEnv) {
233            if (roundEnv.processingOver())
234                return true;
235
236            TypeElement aliveRangeAnno = elements.getTypeElement("AliveRanges");
237
238            if (!annotations.contains(aliveRangeAnno)) {
239                error("no @AliveRanges annotation found in test class");
240            }
241
242            for (Element elem: roundEnv.getElementsAnnotatedWith(aliveRangeAnno)) {
243                Annotation annotation = elem.getAnnotation(AliveRanges.class);
244                aliveRangeMap.put(new ElementKey(elem), (AliveRanges)annotation);
245            }
246            return true;
247        }
248    }
249
250    class ElementKey {
251
252        String key;
253        Element elem;
254
255        public ElementKey(Element elem) {
256            this.elem = elem;
257            this.key = computeKey(elem);
258        }
259
260        @Override
261        public boolean equals(Object obj) {
262            if (obj instanceof ElementKey) {
263                ElementKey other = (ElementKey)obj;
264                return other.key.equals(key);
265            }
266            return false;
267        }
268
269        @Override
270        public int hashCode() {
271            return key.hashCode();
272        }
273
274        String computeKey(Element e) {
275            StringBuilder buf = new StringBuilder();
276            while (e != null) {
277                buf.append(e.toString());
278                e = e.getEnclosingElement();
279            }
280            buf.append(jfo.getName());
281            return buf.toString();
282        }
283
284        @Override
285        public String toString() {
286            return "Key{" + key + "}";
287        }
288    }
289
290}
291