aboutsummaryrefslogtreecommitdiff
path: root/test/tools/javac/flow/LVTHarness.java
blob: 33ab0441748cd2f665a31e7e09a1a452f8f01bcf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*
 * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @bug 7047734 8027660 8037937 8047719 8058708
 * @summary The LVT is not generated correctly during some try/catch scenarios
 *          javac crash while creating LVT entry for a local variable defined in
 *          an inner block
 * @library /tools/javac/lib
 * @build JavacTestingAbstractProcessor LVTHarness
 * @run main LVTHarness
 */

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Set;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

import com.sun.source.util.JavacTask;
import com.sun.tools.classfile.Attribute;
import com.sun.tools.classfile.ClassFile;
import com.sun.tools.classfile.ConstantPool;
import com.sun.tools.classfile.ConstantPoolException;
import com.sun.tools.classfile.Code_attribute;
import com.sun.tools.classfile.ConstantPool.InvalidIndex;
import com.sun.tools.classfile.ConstantPool.UnexpectedEntry;
import com.sun.tools.classfile.Descriptor.InvalidDescriptor;
import com.sun.tools.classfile.LocalVariableTable_attribute;
import com.sun.tools.classfile.Method;

import static javax.tools.StandardLocation.*;
import static com.sun.tools.classfile.LocalVariableTable_attribute.Entry;
import static javax.tools.JavaFileObject.Kind.SOURCE;

public class LVTHarness {

    static int nerrors = 0;

    static final JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    static final StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);

    public static void main(String[] args) throws Exception {

        String testDir = System.getProperty("test.src");
        fm.setLocation(SOURCE_PATH, Arrays.asList(new File(testDir, "tests")));

        // Make sure classes are written to scratch dir.
        fm.setLocation(CLASS_OUTPUT, Arrays.asList(new File(".")));

        for (JavaFileObject jfo : fm.list(SOURCE_PATH, "", Collections.singleton(SOURCE), true)) {
            new LVTHarness(jfo).check();
        }
        if (nerrors > 0) {
            throw new AssertionError("Errors were found");
        }
    }


    JavaFileObject jfo;
    Map<ElementKey, AliveRanges> aliveRangeMap = new HashMap<>();
    Set<String> declaredKeys = new HashSet<>();
    List<ElementKey> seenAliveRanges = new ArrayList<>();

    protected LVTHarness(JavaFileObject jfo) {
        this.jfo = jfo;
    }

    protected void check() throws Exception {

        JavacTask ct = (JavacTask) comp.getTask(null, fm, null, Arrays.asList("-g"),
                                                null, Arrays.asList(jfo));
        System.err.println("compiling code " + jfo);
        ct.setProcessors(Collections.singleton(new AliveRangeFinder()));
        if (!ct.call()) {
            throw new AssertionError("Error during compilation");
        }


        File javaFile = new File(jfo.getName());
        File classFile = new File(javaFile.getName().replace(".java", ".class"));
        checkClassFile(classFile);

        //check all candidates have been used up
        for (Map.Entry<ElementKey, AliveRanges> entry : aliveRangeMap.entrySet()) {
            if (!seenAliveRanges.contains(entry.getKey())) {
                error("Redundant @AliveRanges annotation on method " +
                        entry.getKey().elem + " with key " + entry.getKey());
            }
        }
    }

    void checkClassFile(File file)
            throws IOException, ConstantPoolException, InvalidDescriptor {
        ClassFile classFile = ClassFile.read(file);
        ConstantPool constantPool = classFile.constant_pool;

        //lets get all the methods in the class file.
        for (Method method : classFile.methods) {
            for (ElementKey elementKey: aliveRangeMap.keySet()) {
                String methodDesc = method.getName(constantPool) +
                        method.descriptor.getParameterTypes(constantPool).replace(" ", "");
                if (methodDesc.equals(elementKey.elem.toString())) {
                    checkMethod(constantPool, method, aliveRangeMap.get(elementKey));
                    seenAliveRanges.add(elementKey);
                }
            }
        }
    }

    void checkMethod(ConstantPool constantPool, Method method, AliveRanges ranges)
            throws InvalidIndex, UnexpectedEntry {
        Code_attribute code = (Code_attribute) method.attributes.get(Attribute.Code);
        LocalVariableTable_attribute lvt =
            (LocalVariableTable_attribute) (code.attributes.get(Attribute.LocalVariableTable));
        List<String> infoFromRanges = convertToStringList(ranges);
        List<String> infoFromLVT = convertToStringList(constantPool, lvt);

        // infoFromRanges most be contained in infoFromLVT
        int i = 0;
        int j = 0;
        while (i < infoFromRanges.size() && j < infoFromLVT.size()) {
            int comparison = infoFromRanges.get(i).compareTo(infoFromLVT.get(j));
            if (comparison == 0) {
                i++; j++;
            } else if (comparison > 0) {
                j++;
            } else {
                break;
            }
        }

        if (i < infoFromRanges.size()) {
            error(infoFromLVT, infoFromRanges);
        }
    }

    List<String> convertToStringList(AliveRanges ranges) {
        List<String> result = new ArrayList<>();
        for (Annotation anno : ranges.value()) {
            AliveRange range = (AliveRange)anno;
            String str = formatLocalVariableData(range.varName(),
                    range.bytecodeStart(), range.bytecodeLength());
            result.add(str);
        }
        Collections.sort(result);
        return result;
    }

    List<String> convertToStringList(ConstantPool constantPool,
            LocalVariableTable_attribute lvt) throws InvalidIndex, UnexpectedEntry {
        List<String> result = new ArrayList<>();
        for (Entry entry : lvt.local_variable_table) {
            String str = formatLocalVariableData(constantPool.getUTF8Value(entry.name_index),
                    entry.start_pc, entry.length);
            result.add(str);
        }
        Collections.sort(result);
        return result;
    }

    String formatLocalVariableData(String varName, int start, int length) {
        StringBuilder sb = new StringBuilder()
                    .append("var name: ").append(varName)
                    .append(" start: ").append(start)
                    .append(" length: ").append(length);
        return sb.toString();
    }

    protected void error(List<String> infoFromLVT, List<String> infoFromRanges) {
        nerrors++;
        System.err.printf("Error occurred while checking file: %s\n", jfo.getName());
        System.err.println("The range info from the annotations is");
        printStringListToErrOutput(infoFromRanges);
        System.err.println();
        System.err.println("And the range info from the class file is");
        printStringListToErrOutput(infoFromLVT);
        System.err.println();
    }

    void printStringListToErrOutput(List<String> list) {
        for (String s : list) {
            System.err.println("\t" + s);
        }
    }

    protected void error(String msg) {
        nerrors++;
        System.err.printf("Error occurred while checking file: %s\nreason: %s\n",
                jfo.getName(), msg);
    }

    class AliveRangeFinder extends JavacTestingAbstractProcessor {

        @Override
        public boolean process(Set<? extends TypeElement> annotations,
            RoundEnvironment roundEnv) {
            if (roundEnv.processingOver())
                return true;

            TypeElement aliveRangeAnno = elements.getTypeElement("AliveRanges");

            if (!annotations.contains(aliveRangeAnno)) {
                error("no @AliveRanges annotation found in test class");
            }

            for (Element elem: roundEnv.getElementsAnnotatedWith(aliveRangeAnno)) {
                Annotation annotation = elem.getAnnotation(AliveRanges.class);
                aliveRangeMap.put(new ElementKey(elem), (AliveRanges)annotation);
            }
            return true;
        }
    }

    class ElementKey {

        String key;
        Element elem;

        public ElementKey(Element elem) {
            this.elem = elem;
            this.key = computeKey(elem);
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof ElementKey) {
                ElementKey other = (ElementKey)obj;
                return other.key.equals(key);
            }
            return false;
        }

        @Override
        public int hashCode() {
            return key.hashCode();
        }

        String computeKey(Element e) {
            StringBuilder buf = new StringBuilder();
            while (e != null) {
                buf.append(e.toString());
                e = e.getEnclosingElement();
            }
            buf.append(jfo.getName());
            return buf.toString();
        }

        @Override
        public String toString() {
            return "Key{" + key + "}";
        }
    }

}