• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.utils;
16 
17 import java.lang.reflect.Field;
18 import java.util.Arrays;
19 import sun.misc.Unsafe;
20 
21 public final class UnsafeProvider {
22   private static final Unsafe UNSAFE = getUnsafeInternal();
23 
getUnsafe()24   public static Unsafe getUnsafe() {
25     return UNSAFE;
26   }
27 
getUnsafeInternal()28   private static Unsafe getUnsafeInternal() {
29     try {
30       // The Jazzer runtime is loaded by the bootstrap class loader and should thus pass the
31       // security checks in getUnsafe, so try that first.
32       return Unsafe.getUnsafe();
33     } catch (Throwable unused) {
34       // If not running as an agent, use the classical reflection trick to get an Unsafe instance,
35       // taking into account that the private field may have a name other than "theUnsafe":
36       // https://android.googlesource.com/platform/libcore/+/gingerbread/luni/src/main/java/sun/misc/Unsafe.java#32
37       for (Field f : Unsafe.class.getDeclaredFields()) {
38         if (f.getType() == Unsafe.class) {
39           f.setAccessible(true);
40           try {
41             return (Unsafe) f.get(null);
42           } catch (IllegalAccessException e) {
43             throw new IllegalStateException(
44                 "Please file a bug at https://github.com/CodeIntelligenceTesting/jazzer/issues/new "
45                     + "with this information: Failed to access Unsafe member on Unsafe class",
46                 e);
47           }
48         }
49       }
50       throw new IllegalStateException(String.format(
51           "Please file a bug at https://github.com/CodeIntelligenceTesting/jazzer/issues/new with "
52           + "this information: Failed to find Unsafe member on Unsafe class, have: "
53           + Arrays.deepToString(Unsafe.class.getDeclaredFields())));
54     }
55   }
56 }
57