aboutsummaryrefslogtreecommitdiff
path: root/org.jacoco.core.test/src/org/jacoco/core/instr/InstrumenterTest.java
blob: a3a49063fbca5f62982111e635659ca3eca4c717 (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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/*******************************************************************************
 * Copyright (c) 2009, 2021 Mountainminds GmbH & Co. KG and Contributors
 * This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *    Marc R. Hoffmann - initial API and implementation
 *
 *******************************************************************************/
package org.jacoco.core.instr;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.zip.CRC32;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.jacoco.core.analysis.AnalyzerTest;
import org.jacoco.core.internal.Pack200Streams;
import org.jacoco.core.internal.data.CRC64;
import org.jacoco.core.internal.instr.InstrSupport;
import org.jacoco.core.runtime.IExecutionDataAccessorGenerator;
import org.jacoco.core.test.TargetLoader;
import org.junit.AssumptionViolatedException;
import org.junit.Before;
import org.junit.Test;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 * Unit tests for {@link Instrumenter}.
 */
public class InstrumenterTest {

	// no serialVersionUID to enforce calculation
	@SuppressWarnings("serial")
	public static class SerializationTarget implements Serializable {

		private final String text;

		private final int nr;

		public SerializationTarget(final String text, final int nr) {
			this.text = text;
			this.nr = nr;
		}

		@Override
		public String toString() {
			return text + nr;
		}

	}

	private static final class AccessorGenerator
			implements IExecutionDataAccessorGenerator {

		long classId;

		public int generateDataAccessor(final long classId,
				final String classname, final int probeCount,
				final MethodVisitor mv) {
			this.classId = classId;
			InstrSupport.push(mv, probeCount);
			mv.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_BOOLEAN);
			return 1;
		}

	}

	private AccessorGenerator accessorGenerator;
	private Instrumenter instrumenter;

	@Before
	public void setup() throws Exception {
		accessorGenerator = new AccessorGenerator();
		instrumenter = new Instrumenter(accessorGenerator);
	}

	@Test
	public void should_not_modify_class_bytes_to_support_next_version()
			throws Exception {
		final byte[] originalBytes = createClass(Opcodes.V16);
		final byte[] bytes = new byte[originalBytes.length];
		System.arraycopy(originalBytes, 0, bytes, 0, originalBytes.length);
		final long expectedClassId = CRC64.classId(bytes);

		instrumenter.instrument(bytes, "");

		assertArrayEquals(originalBytes, bytes);
		assertEquals(expectedClassId, accessorGenerator.classId);
	}

	private static byte[] createClass(final int version) {
		final ClassWriter cw = new ClassWriter(0);
		cw.visit(version, 0, "Foo", null, "java/lang/Object", null);
		cw.visitEnd();
		return cw.toByteArray();
	}

	/**
	 * @see #instrumentAll_should_throw_exception_for_unsupported_class_file_version()
	 */
	@Test
	public void instrument_should_throw_exception_for_unsupported_class_file_version() {
		final byte[] bytes = createClass(Opcodes.V16 + 2);
		try {
			instrumenter.instrument(bytes, "UnsupportedVersion");
			fail("exception expected");
		} catch (final IOException e) {
			assertEquals("Error while instrumenting UnsupportedVersion.",
					e.getMessage());
			assertEquals("Unsupported class file major version 62",
					e.getCause().getMessage());
		}
	}

	@Test
	public void testInstrumentClass() throws Exception {
		byte[] bytes = instrumenter.instrument(
				TargetLoader.getClassDataAsBytes(InstrumenterTest.class),
				"Test");
		TargetLoader loader = new TargetLoader();
		Class<?> clazz = loader.add(InstrumenterTest.class, bytes);
		assertEquals("org.jacoco.core.instr.InstrumenterTest", clazz.getName());
	}

	/**
	 * Triggers exception in {@link Instrumenter#instrument(byte[], String)}.
	 */
	@Test
	public void testInstrumentBrokenClass1() throws IOException {
		final byte[] brokenclass = TargetLoader
				.getClassDataAsBytes(AnalyzerTest.class);
		brokenclass[10] = 0x23;
		try {
			instrumenter.instrument(brokenclass, "Broken.class");
			fail();
		} catch (IOException e) {
			assertEquals("Error while instrumenting Broken.class.",
					e.getMessage());
		}
	}

	private static class BrokenInputStream extends InputStream {
		@Override
		public int read() throws IOException {
			throw new IOException();
		}
	}

	/**
	 * Triggers exception in
	 * {@link Instrumenter#instrument(InputStream, String)}.
	 */
	@Test
	public void testInstrumentBrokenStream() {
		try {
			instrumenter.instrument(new BrokenInputStream(), "BrokenStream");
			fail("exception expected");
		} catch (IOException e) {
			assertEquals("Error while instrumenting BrokenStream.",
					e.getMessage());
		}
	}

	/**
	 * Triggers exception in
	 * {@link Instrumenter#instrument(InputStream, OutputStream, String)}.
	 */
	@Test
	public void testInstrumentBrokenStream2() {
		try {
			instrumenter.instrument(new BrokenInputStream(),
					new ByteArrayOutputStream(), "BrokenStream");
			fail("exception expected");
		} catch (IOException e) {
			assertEquals("Error while instrumenting BrokenStream.",
					e.getMessage());
		}
	}

	@Test
	public void testSerialization() throws Exception {
		// Create instrumented instance:
		byte[] bytes = instrumenter.instrument(
				TargetLoader.getClassData(SerializationTarget.class), "Test");
		TargetLoader loader = new TargetLoader();
		Object obj1 = loader.add(SerializationTarget.class, bytes)
				.getConstructor(String.class, Integer.TYPE)
				.newInstance("Hello", Integer.valueOf(42));

		// Serialize instrumented instance:
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		new ObjectOutputStream(buffer).writeObject(obj1);

		// Deserialize with original class definition:
		Object obj2 = new ObjectInputStream(
				new ByteArrayInputStream(buffer.toByteArray())).readObject();
		assertEquals("Hello42", obj2.toString());
	}

	/**
	 * @see #instrument_should_throw_exception_for_unsupported_class_file_version()
	 */
	@Test
	public void instrumentAll_should_throw_exception_for_unsupported_class_file_version() {
		final byte[] bytes = createClass(Opcodes.V16 + 2);
		try {
			instrumenter.instrumentAll(new ByteArrayInputStream(bytes),
					new ByteArrayOutputStream(), "UnsupportedVersion");
			fail("exception expected");
		} catch (final IOException e) {
			assertEquals("Error while instrumenting UnsupportedVersion.",
					e.getMessage());
			assertEquals("Unsupported class file major version 62",
					e.getCause().getMessage());
		}
	}

	@Test
	public void testInstrumentAll_Class() throws IOException {
		InputStream in = TargetLoader.getClassData(getClass());
		OutputStream out = new ByteArrayOutputStream();

		int count = instrumenter.instrumentAll(in, out, "Test");

		assertEquals(1, count);
	}

	@Test
	public void testInstrumentAll_Zip() throws IOException {
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		ZipOutputStream zipout = new ZipOutputStream(buffer);

		// Compressed Entry
		ZipEntry entry = new ZipEntry("TestCompressed.class");
		entry.setMethod(ZipEntry.DEFLATED);
		zipout.putNextEntry(entry);
		zipout.write(TargetLoader.getClassDataAsBytes(getClass()));

		// Uncompressed Entry
		entry = new ZipEntry("TestUncompressed.class");
		entry.setMethod(ZipEntry.STORED);
		entry.setSize(TargetLoader.getClassDataAsBytes(getClass()).length);
		CRC32 crc = new CRC32();
		crc.update(TargetLoader.getClassDataAsBytes(getClass()));
		entry.setCrc(crc.getValue());
		zipout.putNextEntry(entry);
		zipout.write(TargetLoader.getClassDataAsBytes(getClass()));

		zipout.finish();
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		int count = instrumenter.instrumentAll(
				new ByteArrayInputStream(buffer.toByteArray()), out, "Test");

		assertEquals(2, count);
		ZipInputStream zipin = new ZipInputStream(
				new ByteArrayInputStream(out.toByteArray()));
		entry = zipin.getNextEntry();
		assertEquals("TestCompressed.class", entry.getName());
		assertEquals(ZipEntry.DEFLATED, entry.getMethod());
		entry = zipin.getNextEntry();
		assertEquals("TestUncompressed.class", entry.getName());
		assertEquals(ZipEntry.STORED, entry.getMethod());
		assertNull(zipin.getNextEntry());
	}

	/**
	 * Triggers exception in
	 * {@link org.jacoco.core.internal.ContentTypeDetector#ContentTypeDetector(InputStream)}.
	 */
	@Test
	public void testInstrumentAll_Broken() {
		try {
			instrumenter.instrumentAll(new BrokenInputStream(),
					new ByteArrayOutputStream(), "Broken");
			fail("exception expected");
		} catch (IOException e) {
			assertEquals("Error while instrumenting Broken.", e.getMessage());
		}
	}

	/**
	 * Triggers exception in
	 * {@link Instrumenter#copy(InputStream, OutputStream)}.
	 */
	@Test
	public void testInstrumentAll_Broken2() {
		final InputStream inputStream = new InputStream() {
			private int count;

			@Override
			public int read() throws IOException {
				count++;
				if (count > 4) {
					throw new IOException();
				}
				return 0;
			}
		};

		try {
			instrumenter.instrumentAll(inputStream, new ByteArrayOutputStream(),
					"Broken");
		} catch (IOException e) {
			assertEquals("Error while instrumenting Broken.", e.getMessage());
		}
	}

	/**
	 * Triggers exception in
	 * {@link Instrumenter#nextEntry(ZipInputStream, String)}.
	 */
	@Test
	public void testInstrumentAll_BrokenZip() {
		final byte[] buffer = new byte[30];
		buffer[0] = 0x50;
		buffer[1] = 0x4b;
		buffer[2] = 0x03;
		buffer[3] = 0x04;
		Arrays.fill(buffer, 4, buffer.length, (byte) 0x42);

		try {
			instrumenter.instrumentAll(new ByteArrayInputStream(buffer),
					new ByteArrayOutputStream(), "Test.zip");
			fail("exception expected");
		} catch (IOException e) {
			assertEquals("Error while instrumenting Test.zip.", e.getMessage());
		}
	}

	/**
	 * With JDK <= 6 triggers exception in
	 * {@link Instrumenter#copy(InputStream, OutputStream)}.
	 *
	 * With JDK > 6 triggers exception in
	 * {@link org.jacoco.core.internal.ContentTypeDetector#ContentTypeDetector(InputStream)}.
	 */
	@Test
	public void testInstrumentAll_BrokenZipEntry() throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(out);
		zip.putNextEntry(new ZipEntry("brokenentry.txt"));
		out.write(0x23); // Unexpected data here
		zip.close();

		try {
			instrumenter.instrumentAll(
					new ByteArrayInputStream(out.toByteArray()),
					new ByteArrayOutputStream(), "broken.zip");
			fail("exception expected");
		} catch (IOException e) {
			assertEquals(
					"Error while instrumenting broken.zip@brokenentry.txt.",
					e.getMessage());
		}
	}

	@Test
	public void testInstrumentAll_BrokenClassFileInZip() throws IOException {
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		ZipOutputStream zipout = new ZipOutputStream(buffer);
		zipout.putNextEntry(new ZipEntry("Test.class"));
		final byte[] brokenclass = TargetLoader.getClassDataAsBytes(getClass());
		brokenclass[10] = 0x23;
		zipout.write(brokenclass);
		zipout.finish();
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		try {
			instrumenter.instrumentAll(
					new ByteArrayInputStream(buffer.toByteArray()), out,
					"test.zip");
			fail();
		} catch (IOException e) {
			assertEquals("Error while instrumenting test.zip@Test.class.",
					e.getMessage());
		}
	}

	/**
	 * Triggers exception in
	 * {@link Instrumenter#instrumentGzip(InputStream, OutputStream, String)}.
	 */
	@Test
	public void testInstrumentAll_BrokenGZ() {
		final byte[] buffer = new byte[] { 0x1f, (byte) 0x8b, 0x00, 0x00 };

		try {
			instrumenter.instrumentAll(new ByteArrayInputStream(buffer),
					new ByteArrayOutputStream(), "Test.gz");
			fail("exception expected");
		} catch (IOException e) {
			assertEquals("Error while instrumenting Test.gz.", e.getMessage());
		}
	}

	@Test
	public void testInstrumentAll_Pack200() throws IOException {
		try {
			Class.forName("java.util.jar.Pack200");
		} catch (ClassNotFoundException e) {
			throw new AssumptionViolatedException(
					"this test requires JDK with Pack200");
		}

		ByteArrayOutputStream jarbuffer = new ByteArrayOutputStream();
		ZipOutputStream zipout = new ZipOutputStream(jarbuffer);
		zipout.putNextEntry(new ZipEntry("Test.class"));
		zipout.write(TargetLoader.getClassDataAsBytes(getClass()));
		zipout.finish();

		ByteArrayOutputStream pack200buffer = new ByteArrayOutputStream();
		GZIPOutputStream gzipOutput = new GZIPOutputStream(pack200buffer);
		Pack200Streams.pack(jarbuffer.toByteArray(), gzipOutput);
		gzipOutput.finish();

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int count = instrumenter.instrumentAll(
				new ByteArrayInputStream(pack200buffer.toByteArray()), out,
				"Test");

		assertEquals(1, count);
		ZipInputStream zipin = new ZipInputStream(
				Pack200Streams.unpack(new GZIPInputStream(
						new ByteArrayInputStream(out.toByteArray()))));
		assertEquals("Test.class", zipin.getNextEntry().getName());
		assertNull(zipin.getNextEntry());
	}

	/**
	 * Triggers exception in
	 * {@link Instrumenter#instrumentPack200(InputStream, OutputStream, String)}.
	 */
	@Test
	public void testInstrumentAll_BrokenPack200() {
		final byte[] buffer = new byte[] { (byte) 0xca, (byte) 0xfe,
				(byte) 0xd0, 0x0d };

		try {
			instrumenter.instrumentAll(new ByteArrayInputStream(buffer),
					new ByteArrayOutputStream(), "Test.pack200");
		} catch (IOException e) {
			assertEquals("Error while instrumenting Test.pack200.",
					e.getMessage());
		}
	}

	@Test
	public void testInstrumentAll_Other() throws IOException {
		InputStream in = new ByteArrayInputStream("text".getBytes());
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		int count = instrumenter.instrumentAll(in, out, "Test");

		assertEquals(0, count);
		assertEquals("text", new String(out.toByteArray()));
	}

	@Test
	public void testInstrumentAll_RemoveSignatures() throws IOException {
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		ZipOutputStream zipout = new ZipOutputStream(buffer);
		zipout.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
		zipout.putNextEntry(new ZipEntry("META-INF/ALIAS.SF"));
		zipout.finish();
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		int count = instrumenter.instrumentAll(
				new ByteArrayInputStream(buffer.toByteArray()), out, "Test");

		assertEquals(0, count);
		ZipInputStream zipin = new ZipInputStream(
				new ByteArrayInputStream(out.toByteArray()));
		assertEquals("META-INF/MANIFEST.MF", zipin.getNextEntry().getName());
		assertNull(zipin.getNextEntry());
	}

	@Test
	public void testInstrumentAll_KeepSignatures() throws IOException {
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		ZipOutputStream zipout = new ZipOutputStream(buffer);
		zipout.putNextEntry(new ZipEntry("META-INF/ALIAS.SF"));
		zipout.finish();
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		instrumenter.setRemoveSignatures(false);
		int count = instrumenter.instrumentAll(
				new ByteArrayInputStream(buffer.toByteArray()), out, "Test");

		assertEquals(0, count);
		ZipInputStream zipin = new ZipInputStream(
				new ByteArrayInputStream(out.toByteArray()));
		assertEquals("META-INF/ALIAS.SF", zipin.getNextEntry().getName());
		assertNull(zipin.getNextEntry());
	}

}