1 // Copyright 2022 Code Intelligence GmbH 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package com.code_intelligence.jazzer.instrumentor; 16 17 import java.lang.reflect.Field; 18 import sun.misc.Unsafe; 19 20 public final class UnsafeBranchfreeCoverageMap { 21 private static final Unsafe UNSAFE; 22 23 static { 24 Unsafe unsafe; 25 try { 26 Field f = Unsafe.class.getDeclaredField("theUnsafe"); 27 f.setAccessible(true); 28 unsafe = (Unsafe) f.get(null); 29 } catch (IllegalAccessException | NoSuchFieldException e) { 30 e.printStackTrace(); 31 System.exit(1); 32 // Not reached. 33 unsafe = null; 34 } 35 UNSAFE = unsafe; 36 } 37 38 // The current target, JsonSanitizer, uses less than 2048 coverage counters. 39 private static final long NUM_COUNTERS = 4096; 40 private static final long countersAddress = UNSAFE.allocateMemory(NUM_COUNTERS); 41 42 static { UNSAFE.setMemory(countersAddress, NUM_COUNTERS, (byte) 0)43 UNSAFE.setMemory(countersAddress, NUM_COUNTERS, (byte) 0); 44 } 45 enlargeIfNeeded(int nextId)46 public static void enlargeIfNeeded(int nextId) { 47 // Statically sized counters buffer. 48 } 49 recordCoverage(final int id)50 public static void recordCoverage(final int id) { 51 final long address = countersAddress + id; 52 final int incrementedCounter = UNSAFE.getByte(address) + 1; 53 UNSAFE.putByte(address, (byte) (incrementedCounter ^ (incrementedCounter >>> 8))); 54 } 55 } 56