summaryrefslogtreecommitdiff
path: root/asm-commons/src/test/java/org/objectweb/asm/commons/AnalyzerAdapterTest.java
blob: 9866c0099bc961922b3615b56082bcc2ac23fe74 (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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// ASM: a very small and fast Java bytecode manipulation framework
// Copyright (c) 2000-2011 INRIA, France Telecom
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holders nor the names of its
//    contributors may be used to endorse or promote products derived from
//    this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
package org.objectweb.asm.commons;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.test.AsmTest;
import org.objectweb.asm.test.ClassFile;

/**
 * Unit tests for {@link AnalyzerAdapter}.
 *
 * @author Eric Bruneton
 */
class AnalyzerAdapterTest extends AsmTest {

  @Test
  void testConstructor() {
    assertDoesNotThrow(
        () -> new AnalyzerAdapter("pkg/Class", Opcodes.ACC_PUBLIC, "name", "()V", null));
    assertThrows(
        IllegalStateException.class,
        () -> new AnalyzerAdapter("pkg/Class", Opcodes.ACC_PUBLIC, "name", "()V", null) {});
  }

  @Test
  void testVisitFrame_emptyFrame() {
    AnalyzerAdapter analyzerAdapter =
        new AnalyzerAdapter("pkg/Class", Opcodes.ACC_PUBLIC, "name", "()V", null);

    Executable visitFrame = () -> analyzerAdapter.visitFrame(Opcodes.F_NEW, 0, null, 0, null);

    assertDoesNotThrow(visitFrame);
  }

  @Test
  void testVisitFrame_invalidFrameType() {
    AnalyzerAdapter analyzerAdapter =
        new AnalyzerAdapter("pkg/Class", Opcodes.ACC_PUBLIC, "name", "()V", null);

    Executable visitFrame = () -> analyzerAdapter.visitFrame(Opcodes.F_FULL, 0, null, 0, null);

    Exception exception = assertThrows(IllegalArgumentException.class, visitFrame);
    assertEquals(
        "AnalyzerAdapter only accepts expanded frames (see ClassReader.EXPAND_FRAMES)",
        exception.getMessage());
  }

  /**
   * Tests that classes with additional frames inserted at each instruction, using the results of an
   * AnalyzerAdapter, can be instantiated and loaded. This makes sure the intermediate frames
   * computed by AnalyzerAdapter are correct, i.e. pass bytecode verification.
   */
  @ParameterizedTest
  @MethodSource(ALL_CLASSES_AND_ALL_APIS)
  void testAllMethods_precompiledClass(
      final PrecompiledClass classParameter, final Api apiParameter) throws Exception {
    byte[] classFile = classParameter.getBytes();
    ClassReader classReader = new ClassReader(classFile);
    ClassWriter classWriter = new ClassWriter(0);
    ClassVisitor classAnalyzerAdapter = new ClassAnalyzerAdapter(apiParameter.value(), classWriter);

    Executable accept = () -> classReader.accept(classAnalyzerAdapter, ClassReader.EXPAND_FRAMES);

    // jdk3.AllInstructions and jdk3.LargeMethod contain unsupported jsr/ret instructions.
    if (classParameter == PrecompiledClass.JDK3_ALL_INSTRUCTIONS
        || classParameter == PrecompiledClass.JDK3_LARGE_METHOD) {
      Exception exception = assertThrows(IllegalArgumentException.class, accept);
      assertEquals("JSR/RET are not supported", exception.getMessage());
    } else if (classParameter.isMoreRecentThan(apiParameter)) {
      Exception exception = assertThrows(UnsupportedOperationException.class, accept);
      assertTrue(exception.getMessage().matches(UNSUPPORTED_OPERATION_MESSAGE_PATTERN));
    } else {
      assertDoesNotThrow(accept);
      Executable newInstance = () -> new ClassFile(classWriter.toByteArray()).newInstance();
      if (classParameter.isNotCompatibleWithCurrentJdk()) {
        assertThrows(UnsupportedClassVersionError.class, newInstance);
      } else {
        assertDoesNotThrow(newInstance);
      }
    }
  }

  /**
   * A ClassVisitor that inserts intermediate frames before each instruction of each method, using
   * the types computed with an AnalyzerAdapter (in order to check that these intermediate frames
   * are correct).
   */
  static class ClassAnalyzerAdapter extends ClassVisitor {

    private String owner;

    ClassAnalyzerAdapter(final int api, final ClassVisitor classVisitor) {
      super(api, classVisitor);
    }

    @Override
    public void visit(
        final int version,
        final int access,
        final String name,
        final String signature,
        final String superName,
        final String[] interfaces) {
      owner = name;
      super.visit(version, access, name, signature, superName, interfaces);
    }

    @Override
    public MethodVisitor visitMethod(
        final int access,
        final String name,
        final String descriptor,
        final String signature,
        final String[] exceptions) {
      MethodVisitor methodVisitor =
          super.visitMethod(access, name, descriptor, signature, exceptions);
      AnalyzedFramesInserter inserter = new AnalyzedFramesInserter(methodVisitor);
      AnalyzerAdapter analyzerAdapter =
          new AnalyzerAdapter(api, owner, access, name, descriptor, inserter) {

            @Override
            public void visitMaxs(final int maxStack, final int maxLocals) {
              // AnalyzerAdapter should correctly recompute maxLocals from scratch.
              super.visitMaxs(maxStack, 0);
            }
          };
      inserter.setAnalyzerAdapter(analyzerAdapter);
      return analyzerAdapter;
    }
  }

  /**
   * Inserts intermediate frames before each instruction, using the types computed with an
   * AnalyzerAdapter.
   */
  static class AnalyzedFramesInserter extends MethodVisitor {

    private AnalyzerAdapter analyzerAdapter;
    private boolean hasOriginalFrame;

    AnalyzedFramesInserter(final MethodVisitor methodVisitor) {
      super(/* latest */ Opcodes.ASM10_EXPERIMENTAL, methodVisitor);
    }

    void setAnalyzerAdapter(final AnalyzerAdapter analyzerAdapter) {
      this.analyzerAdapter = analyzerAdapter;
    }

    @Override
    public void visitFrame(
        final int type,
        final int numLocal,
        final Object[] local,
        final int numStack,
        final Object[] stack) {
      super.visitFrame(type, numLocal, local, numStack, stack);
      hasOriginalFrame = true;
    }

    private void maybeInsertFrame() {
      // Don't insert a frame if we already have one for this instruction, from the original class.
      if (!hasOriginalFrame) {
        if (analyzerAdapter.locals != null && analyzerAdapter.stack != null) {
          ArrayList<Object> local = toFrameTypes(analyzerAdapter.locals);
          ArrayList<Object> stack = toFrameTypes(analyzerAdapter.stack);
          super.visitFrame(
              Opcodes.F_NEW, local.size(), local.toArray(), stack.size(), stack.toArray());
        }
      }
      hasOriginalFrame = false;
    }

    /**
     * Converts local and stack types from AnalyzerAdapter to visitFrame format (long and double are
     * represented with one element in visitFrame, but with two elements in AnalyzerAdapter).
     */
    private ArrayList<Object> toFrameTypes(final List<Object> analyzerTypes) {
      ArrayList<Object> frameTypes = new ArrayList<>();
      for (int i = 0; i < analyzerTypes.size(); ++i) {
        if (i > 0
            && (analyzerTypes.get(i - 1) == Opcodes.LONG
                || analyzerTypes.get(i - 1) == Opcodes.DOUBLE)) {
          continue;
        }
        Object value = analyzerTypes.get(i);
        frameTypes.add(value);
      }
      return frameTypes;
    }

    @Override
    public void visitInsn(final int opcode) {
      maybeInsertFrame();
      super.visitInsn(opcode);
    }

    @Override
    public void visitIntInsn(final int opcode, final int operand) {
      maybeInsertFrame();
      super.visitIntInsn(opcode, operand);
    }

    @Override
    public void visitVarInsn(final int opcode, final int varIndex) {
      maybeInsertFrame();
      super.visitVarInsn(opcode, varIndex);
    }

    @Override
    public void visitTypeInsn(final int opcode, final String type) {
      maybeInsertFrame();
      super.visitTypeInsn(opcode, type);
    }

    @Override
    public void visitFieldInsn(
        final int opcode, final String owner, final String name, final String descriptor) {
      maybeInsertFrame();
      super.visitFieldInsn(opcode, owner, name, descriptor);
    }

    @Override
    public void visitMethodInsn(
        final int opcode,
        final String owner,
        final String name,
        final String descriptor,
        final boolean isInterface) {
      maybeInsertFrame();
      super.visitMethodInsn(opcode, owner, name, descriptor, isInterface);
    }

    @Override
    public void visitInvokeDynamicInsn(
        final String name,
        final String descriptor,
        final Handle bootstrapMethodHandle,
        final Object... bootstrapMethodArguments) {
      maybeInsertFrame();
      super.visitInvokeDynamicInsn(
          name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
    }

    @Override
    public void visitJumpInsn(final int opcode, final Label label) {
      maybeInsertFrame();
      super.visitJumpInsn(opcode, label);
    }

    @Override
    public void visitLdcInsn(final Object value) {
      maybeInsertFrame();
      super.visitLdcInsn(value);
    }

    @Override
    public void visitIincInsn(final int varIndex, final int increment) {
      maybeInsertFrame();
      super.visitIincInsn(varIndex, increment);
    }

    @Override
    public void visitTableSwitchInsn(
        final int min, final int max, final Label dflt, final Label... labels) {
      maybeInsertFrame();
      super.visitTableSwitchInsn(min, max, dflt, labels);
    }

    @Override
    public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) {
      maybeInsertFrame();
      super.visitLookupSwitchInsn(dflt, keys, labels);
    }

    @Override
    public void visitMultiANewArrayInsn(final String descriptor, final int numDimensions) {
      maybeInsertFrame();
      super.visitMultiANewArrayInsn(descriptor, numDimensions);
    }
  }
}