aboutsummaryrefslogtreecommitdiff
path: root/org.jacoco.core/src/org/jacoco/core/internal/analysis/filter/TryWithResourcesJavacFilter.java
blob: 23ecb0e6c74ea3ef6f2197ef3bce62d79e1f41df (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
/*******************************************************************************
 * Copyright (c) 2009, 2019 Mountainminds GmbH & Co. KG and Contributors
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Evgeny Mandrikov - initial API and implementation
 *
 *******************************************************************************/
package org.jacoco.core.internal.analysis.filter;

import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TryCatchBlockNode;

/**
 * Filters code which is generated for try-with-resources statement by javac
 * versions from 7 to 10.
 */
public final class TryWithResourcesJavacFilter implements IFilter {

	public void filter(final MethodNode methodNode,
			final IFilterContext context, final IFilterOutput output) {
		if (methodNode.tryCatchBlocks.isEmpty()) {
			return;
		}
		final Matcher matcher = new Matcher(output);
		for (final TryCatchBlockNode t : methodNode.tryCatchBlocks) {
			if ("java/lang/Throwable".equals(t.type)) {
				for (final Matcher.JavacPattern p : Matcher.JavacPattern
						.values()) {
					matcher.start(t.handler);
					if (matcher.matchJavac(p)) {
						break;
					}
				}
			}
		}
	}

	/**
	 * javac from JDK 7 and 8 generates bytecode that is equivalent to the
	 * compilation of source code that is described in <a href=
	 * "http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.3.1">JLS
	 * 14.20.3. try-with-resources</a>:
	 * 
	 * <pre>
	 *     Resource r = ...;
	 *     Throwable primaryExc = null;
	 *     try {
	 *         ...
	 *     } finally {
	 *         if (r != null) {
	 *             if (primaryExc != null) {
	 *                 try {
	 *                     r.close();
	 *                 } catch (Throwable suppressedExc) {
	 *                     primaryExc.addSuppressed(suppressedExc);
	 *                 }
	 *             } else {
	 *                 r.close();
	 *             }
	 *         }
	 *     }
	 * </pre>
	 *
	 * Case of multiple resources looks like multiple nested try-with-resources
	 * statements. javac from JDK 9 EA b160 does the same, but with some
	 * optimizations (see <a href=
	 * "https://bugs.openjdk.java.net/browse/JDK-7020499">JDK-7020499</a>):
	 * <ul>
	 * <li><code>null</code> check for resource is omitted when it is
	 * initialized using <code>new</code></li>
	 * <li>synthetic method <code>$closeResource</code> containing
	 * <code>null</code> check of primaryExc and calls to methods
	 * <code>addSuppressed</code> and <code>close</code> is used when number of
	 * copies of closing logic reaches threshold, <code>null</code> check of
	 * resource (if present) is done before call of this method</li>
	 * </ul>
	 * During matching association between resource and slot of variable is done
	 * on exceptional path and is used to find close of resource on normal path.
	 * Order of loading variables primaryExc and r is different in different
	 * cases, which implies that this order should be determined before
	 * association. So {@link JavacPattern} defines all possible variants that
	 * will be tried sequentially.
	 */
	static class Matcher extends AbstractMatcher {
		private final IFilterOutput output;

		private String expectedOwner;

		private AbstractInsnNode start;

		Matcher(final IFilterOutput output) {
			this.output = output;
		}

		private enum JavacPattern {
			/**
			 * resource is loaded after primaryExc, <code>null</code> check of
			 * resource is omitted, method <code>$closeResource</code> is used
			 */
			OPTIMAL,
			/**
			 * resource is loaded before primaryExc and both are checked on
			 * <code>null</code>
			 */
			FULL,
			/**
			 * resource is loaded after primaryExc, <code>null</code> check of
			 * resource is omitted
			 */
			OMITTED_NULL_CHECK,
			/**
			 * resource is loaded before primaryExc and checked on
			 * <code>null</code>, method <code>$closeResource</code> is used
			 */
			METHOD,
		}

		private void start(final AbstractInsnNode start) {
			this.start = start;
			cursor = start.getPrevious();
			vars.clear();
			expectedOwner = null;
		}

		private boolean matchJavac(final JavacPattern p) {
			// "catch (Throwable t)"
			nextIsVar(Opcodes.ASTORE, "t1");
			// "primaryExc = t"
			nextIsVar(Opcodes.ALOAD, "t1");
			nextIsVar(Opcodes.ASTORE, "primaryExc");
			// "throw t"
			nextIsVar(Opcodes.ALOAD, "t1");
			nextIs(Opcodes.ATHROW);

			// "catch (any t)"
			nextIsVar(Opcodes.ASTORE, "t2");
			nextIsJavacClose(p, "e");
			// "throw t"
			nextIsVar(Opcodes.ALOAD, "t2");
			nextIs(Opcodes.ATHROW);
			if (cursor == null) {
				return false;
			}
			final AbstractInsnNode end = cursor;

			AbstractInsnNode startOnNonExceptionalPath = start.getPrevious();
			cursor = startOnNonExceptionalPath;
			while (!nextIsJavacClose(p, "n")) {
				startOnNonExceptionalPath = startOnNonExceptionalPath
						.getPrevious();
				cursor = startOnNonExceptionalPath;
				if (cursor == null) {
					return false;
				}
			}
			startOnNonExceptionalPath = startOnNonExceptionalPath.getNext();

			final AbstractInsnNode m = cursor;
			next();
			if (cursor.getOpcode() != Opcodes.GOTO) {
				cursor = m;
			}

			output.ignore(startOnNonExceptionalPath, cursor);
			output.ignore(start, end);
			return true;
		}

		/**
		 * On a first invocation will associate variables with names "r" and
		 * "primaryExc", on subsequent invocations will use those associations
		 * for checks.
		 */
		private boolean nextIsJavacClose(final JavacPattern p,
				final String ctx) {
			switch (p) {
			case METHOD:
			case FULL:
				// "if (r != null)"
				nextIsVar(Opcodes.ALOAD, "r");
				nextIs(Opcodes.IFNULL);
			}
			switch (p) {
			case METHOD:
			case OPTIMAL:
				nextIsVar(Opcodes.ALOAD, "primaryExc");
				nextIsVar(Opcodes.ALOAD, "r");
				nextIs(Opcodes.INVOKESTATIC);
				if (cursor != null) {
					final MethodInsnNode m = (MethodInsnNode) cursor;
					if ("$closeResource".equals(m.name)
							&& "(Ljava/lang/Throwable;Ljava/lang/AutoCloseable;)V"
									.equals(m.desc)) {
						return true;
					}
					cursor = null;
				}
				return false;
			case FULL:
			case OMITTED_NULL_CHECK:
				nextIsVar(Opcodes.ALOAD, "primaryExc");
				// "if (primaryExc != null)"
				nextIs(Opcodes.IFNULL);
				// "r.close()"
				nextIsClose();
				nextIs(Opcodes.GOTO);
				// "catch (Throwable t)"
				nextIsVar(Opcodes.ASTORE, ctx + "t");
				// "primaryExc.addSuppressed(t)"
				nextIsVar(Opcodes.ALOAD, "primaryExc");
				nextIsVar(Opcodes.ALOAD, ctx + "t");
				nextIsInvoke(Opcodes.INVOKEVIRTUAL, "java/lang/Throwable",
						"addSuppressed", "(Ljava/lang/Throwable;)V");
				nextIs(Opcodes.GOTO);
				// "r.close()"
				nextIsClose();
				return cursor != null;
			default:
				throw new AssertionError();
			}
		}

		private void nextIsClose() {
			nextIsVar(Opcodes.ALOAD, "r");
			next();
			if (cursor == null) {
				return;
			}
			if (cursor.getOpcode() != Opcodes.INVOKEINTERFACE
					&& cursor.getOpcode() != Opcodes.INVOKEVIRTUAL) {
				cursor = null;
				return;
			}
			final MethodInsnNode m = (MethodInsnNode) cursor;
			if (!"close".equals(m.name) || !"()V".equals(m.desc)) {
				cursor = null;
				return;
			}
			final String actual = m.owner;
			if (expectedOwner == null) {
				expectedOwner = actual;
			} else if (!expectedOwner.equals(actual)) {
				cursor = null;
			}
		}

	}

}