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