aboutsummaryrefslogtreecommitdiffhomepage
path: root/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
blob: ca80d9464a9d96549e027ffb23847fa3d766936e (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
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Google Inc. 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 com.google.protobuf;

import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.logging.Level;
import java.util.logging.Logger;

/** Utility class for working with unsafe operations. */
final class UnsafeUtil {
  private static final Logger logger = Logger.getLogger(UnsafeUtil.class.getName());
  private static final sun.misc.Unsafe UNSAFE = getUnsafe();
  private static final MemoryAccessor MEMORY_ACCESSOR = getMemoryAccessor();
  private static final boolean HAS_UNSAFE_BYTEBUFFER_OPERATIONS =
      supportsUnsafeByteBufferOperations();
  private static final boolean HAS_UNSAFE_ARRAY_OPERATIONS = supportsUnsafeArrayOperations();
  private static final boolean HAS_UNSAFE_COPY_MEMORY = supportsUnsafeCopyMemory();
  private static final long ARRAY_BASE_OFFSET = byteArrayBaseOffset();
  private static final long BUFFER_ADDRESS_OFFSET = fieldOffset(bufferAddressField());

  private UnsafeUtil() {}

  static boolean hasUnsafeArrayOperations() {
    return HAS_UNSAFE_ARRAY_OPERATIONS;
  }

  static boolean hasUnsafeCopyMemory() {
    return HAS_UNSAFE_COPY_MEMORY;
  }

  static boolean hasUnsafeByteBufferOperations() {
    return HAS_UNSAFE_BYTEBUFFER_OPERATIONS;
  }

  static long objectFieldOffset(Field field) {
    return MEMORY_ACCESSOR.objectFieldOffset(field);
  }

  static long getArrayBaseOffset() {
    return ARRAY_BASE_OFFSET;
  }

  static byte getByte(Object target, long offset) {
    return MEMORY_ACCESSOR.getByte(target, offset);
  }

  static void putByte(Object target, long offset, byte value) {
    MEMORY_ACCESSOR.putByte(target, offset, value);
  }

  static int getInt(Object target, long offset) {
    return MEMORY_ACCESSOR.getInt(target, offset);
  }

  static void putInt(Object target, long offset, int value) {
    MEMORY_ACCESSOR.putInt(target, offset, value);
  }

  static long getLong(Object target, long offset) {
    return MEMORY_ACCESSOR.getLong(target, offset);
  }

  static void putLong(Object target, long offset, long value) {
    MEMORY_ACCESSOR.putLong(target, offset, value);
  }

  static boolean getBoolean(Object target, long offset) {
    return MEMORY_ACCESSOR.getBoolean(target, offset);
  }

  static void putBoolean(Object target, long offset, boolean value) {
    MEMORY_ACCESSOR.putBoolean(target, offset, value);
  }

  static float getFloat(Object target, long offset) {
    return MEMORY_ACCESSOR.getFloat(target, offset);
  }

  static void putFloat(Object target, long offset, float value) {
    MEMORY_ACCESSOR.putFloat(target, offset, value);
  }

  static double getDouble(Object target, long offset) {
    return MEMORY_ACCESSOR.getDouble(target, offset);
  }

  static void putDouble(Object target, long offset, double value) {
    MEMORY_ACCESSOR.putDouble(target, offset, value);
  }

  static Object getObject(Object target, long offset) {
    return MEMORY_ACCESSOR.getObject(target, offset);
  }

  static void putObject(Object target, long offset, Object value) {
    MEMORY_ACCESSOR.putObject(target, offset, value);
  }

  static void copyMemory(
      Object src, long srcOffset, Object target, long targetOffset, long length) {
    MEMORY_ACCESSOR.copyMemory(src, srcOffset, target, targetOffset, length);
  }

  static byte getByte(long address) {
    return MEMORY_ACCESSOR.getByte(address);
  }

  static void putByte(long address, byte value) {
    MEMORY_ACCESSOR.putByte(address, value);
  }

  static int getInt(long address) {
    return MEMORY_ACCESSOR.getInt(address);
  }

  static void putInt(long address, int value) {
    MEMORY_ACCESSOR.putInt(address, value);
  }

  static long getLong(long address) {
    return MEMORY_ACCESSOR.getLong(address);
  }

  static void putLong(long address, long value) {
    MEMORY_ACCESSOR.putLong(address, value);
  }

  static void copyMemory(long srcAddress, long targetAddress, long length) {
    MEMORY_ACCESSOR.copyMemory(srcAddress, targetAddress, length);
  }

  /**
   * Gets the offset of the {@code address} field of the given direct {@link ByteBuffer}.
   */
  static long addressOffset(ByteBuffer buffer) {
    return MEMORY_ACCESSOR.getLong(buffer, BUFFER_ADDRESS_OFFSET);
  }

  static Object getStaticObject(Field field) {
    return MEMORY_ACCESSOR.getStaticObject(field);
  }

  /**
   * Gets the {@code sun.misc.Unsafe} instance, or {@code null} if not available on this platform.
   */
  private static sun.misc.Unsafe getUnsafe() {
    sun.misc.Unsafe unsafe = null;
    try {
      unsafe =
          AccessController.doPrivileged(
              new PrivilegedExceptionAction<sun.misc.Unsafe>() {
                @Override
                public sun.misc.Unsafe run() throws Exception {
                  Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;

                  for (Field f : k.getDeclaredFields()) {
                    f.setAccessible(true);
                    Object x = f.get(null);
                    if (k.isInstance(x)) {
                      return k.cast(x);
                    }
                  }
                  // The sun.misc.Unsafe field does not exist.
                  return null;
                }
              });
    } catch (Throwable e) {
      // Catching Throwable here due to the fact that Google AppEngine raises NoClassDefFoundError
      // for Unsafe.
    }
    return unsafe;
  }

  /** Get a {@link MemoryAccessor} appropriate for the platform, or null if not supported. */
  private static MemoryAccessor getMemoryAccessor() {
    if (UNSAFE == null) {
      return null;
    }
    return new JvmMemoryAccessor(UNSAFE);
  }

  /** Indicates whether or not unsafe array operations are supported on this platform. */
  private static boolean supportsUnsafeArrayOperations() {
    if (UNSAFE == null) {
      return false;
    }
    try {
      Class<?> clazz = UNSAFE.getClass();
      clazz.getMethod("objectFieldOffset", Field.class);
      clazz.getMethod("arrayBaseOffset", Class.class);
      clazz.getMethod("getInt", Object.class, long.class);
      clazz.getMethod("putInt", Object.class, long.class, int.class);
      clazz.getMethod("getLong", Object.class, long.class);
      clazz.getMethod("putLong", Object.class, long.class, long.class);
      clazz.getMethod("getObject", Object.class, long.class);
      clazz.getMethod("putObject", Object.class, long.class, Object.class);
      clazz.getMethod("getByte", Object.class, long.class);
      clazz.getMethod("putByte", Object.class, long.class, byte.class);
      clazz.getMethod("getBoolean", Object.class, long.class);
      clazz.getMethod("putBoolean", Object.class, long.class, boolean.class);
      clazz.getMethod("getFloat", Object.class, long.class);
      clazz.getMethod("putFloat", Object.class, long.class, float.class);
      clazz.getMethod("getDouble", Object.class, long.class);
      clazz.getMethod("putDouble", Object.class, long.class, double.class);

      return true;
    } catch (Throwable e) {
      logger.log(
          Level.WARNING,
          "platform method missing - proto runtime falling back to safer methods: " + e);
    }
    return false;
  }

  /**
   * Indicates whether or not unsafe copyMemory(object, long, object, long, long) operations are
   * supported on this platform.
   */
  private static boolean supportsUnsafeCopyMemory() {
    if (UNSAFE == null) {
      return false;
    }
    try {
      Class<?> clazz = UNSAFE.getClass();
      clazz.getMethod("copyMemory", Object.class, long.class, Object.class, long.class, long.class);

      return true;
    } catch (Throwable e) {
      logger.log(
          Level.WARNING,
          "copyMemory is missing from platform - proto runtime falling back to safer methods.");
    }
    return false;
  }

  private static boolean supportsUnsafeByteBufferOperations() {
    if (UNSAFE == null) {
      return false;
    }
    try {
      Class<?> clazz = UNSAFE.getClass();
      // Methods for getting direct buffer address.
      clazz.getMethod("objectFieldOffset", Field.class);
      clazz.getMethod("getLong", Object.class, long.class);

      clazz.getMethod("getByte", long.class);
      clazz.getMethod("putByte", long.class, byte.class);
      clazz.getMethod("getInt", long.class);
      clazz.getMethod("putInt", long.class, int.class);
      clazz.getMethod("getLong", long.class);
      clazz.getMethod("putLong", long.class, long.class);
      clazz.getMethod("copyMemory", long.class, long.class, long.class);
      return true;
    } catch (Throwable e) {
      logger.log(
          Level.WARNING,
          "platform method missing - proto runtime falling back to safer methods: " + e);
    }
    return false;
  }


  @SuppressWarnings("unchecked")
  private static <T> Class<T> getClassForName(String name) {
    try {
      return (Class<T>) Class.forName(name);
    } catch (Throwable e) {
      return null;
    }
  }

  /** Finds the address field within a direct {@link Buffer}. */
  private static Field bufferAddressField() {
    return field(Buffer.class, "address");
  }

  /**
   * Get the base offset for byte arrays, or {@code -1} if {@code sun.misc.Unsafe} is not available.
   */
  private static int byteArrayBaseOffset() {
    return HAS_UNSAFE_ARRAY_OPERATIONS ? MEMORY_ACCESSOR.arrayBaseOffset(byte[].class) : -1;
  }

  /**
   * Returns the offset of the provided field, or {@code -1} if {@code sun.misc.Unsafe} is not
   * available.
   */
  private static long fieldOffset(Field field) {
    return field == null || MEMORY_ACCESSOR == null ? -1 : MEMORY_ACCESSOR.objectFieldOffset(field);
  }

  /**
   * Gets the field with the given name within the class, or {@code null} if not found. If found,
   * the field is made accessible.
   */
  private static Field field(Class<?> clazz, String fieldName) {
    Field field;
    try {
      field = clazz.getDeclaredField(fieldName);
      field.setAccessible(true);
    } catch (Throwable t) {
      // Failed to access the fields.
      field = null;
    }
    return field;
  }

  private abstract static class MemoryAccessor {

    sun.misc.Unsafe unsafe;

    MemoryAccessor(sun.misc.Unsafe unsafe) {
      this.unsafe = unsafe;
    }

    public final long objectFieldOffset(Field field) {
      return unsafe.objectFieldOffset(field);
    }

    public abstract byte getByte(Object target, long offset);

    public abstract void putByte(Object target, long offset, byte value);

    public final int getInt(Object target, long offset) {
      return unsafe.getInt(target, offset);
    }

    public final void putInt(Object target, long offset, int value) {
      unsafe.putInt(target, offset, value);
    }

    public final long getLong(Object target, long offset) {
      return unsafe.getLong(target, offset);
    }

    public final void putLong(Object target, long offset, long value) {
      unsafe.putLong(target, offset, value);
    }

    public abstract boolean getBoolean(Object target, long offset);

    public abstract void putBoolean(Object target, long offset, boolean value);

    public abstract float getFloat(Object target, long offset);

    public abstract void putFloat(Object target, long offset, float value);

    public abstract double getDouble(Object target, long offset);

    public abstract void putDouble(Object target, long offset, double value);

    public final Object getObject(Object target, long offset) {
      return unsafe.getObject(target, offset);
    }

    public final void putObject(Object target, long offset, Object value) {
      unsafe.putObject(target, offset, value);
    }

    public final int arrayBaseOffset(Class<?> clazz) {
      return unsafe.arrayBaseOffset(clazz);
    }

    public abstract byte getByte(long address);

    public abstract void putByte(long address, byte value);

    public abstract int getInt(long address);

    public abstract void putInt(long address, int value);

    public abstract long getLong(long address);

    public abstract void putLong(long address, long value);

    public abstract void copyMemory(long srcAddress, long targetAddress, long length);

    public abstract void copyMemory(
        Object src, long srcOffset, Object target, long targetOffset, long length);

    public abstract Object getStaticObject(Field field);
  }

  private static final class JvmMemoryAccessor extends MemoryAccessor {

    JvmMemoryAccessor(sun.misc.Unsafe unsafe) {
      super(unsafe);
    }

    @Override
    public byte getByte(long address) {
      return unsafe.getByte(address);
    }

    @Override
    public void putByte(long address, byte value) {
      unsafe.putByte(address, value);
    }

    @Override
    public int getInt(long address) {
      return unsafe.getInt(address);
    }

    @Override
    public void putInt(long address, int value) {
      unsafe.putInt(address, value);
    }

    @Override
    public long getLong(long address) {
      return unsafe.getLong(address);
    }

    @Override
    public void putLong(long address, long value) {
      unsafe.putLong(address, value);
    }

    @Override
    public byte getByte(Object target, long offset) {
      return unsafe.getByte(target, offset);
    }

    @Override
    public void putByte(Object target, long offset, byte value) {
      unsafe.putByte(target, offset, value);
    }

    @Override
    public boolean getBoolean(Object target, long offset) {
      return unsafe.getBoolean(target, offset);
    }

    @Override
    public void putBoolean(Object target, long offset, boolean value) {
      unsafe.putBoolean(target, offset, value);
    }

    @Override
    public float getFloat(Object target, long offset) {
      return unsafe.getFloat(target, offset);
    }

    @Override
    public void putFloat(Object target, long offset, float value) {
      unsafe.putFloat(target, offset, value);
    }

    @Override
    public double getDouble(Object target, long offset) {
      return unsafe.getDouble(target, offset);
    }

    @Override
    public void putDouble(Object target, long offset, double value) {
      unsafe.putDouble(target, offset, value);
    }

    @Override
    public void copyMemory(
        Object src, long srcOffset, Object target, long targetOffset, long length) {
      unsafe.copyMemory(src, srcOffset, target, targetOffset, length);
    }

    @Override
    public void copyMemory(long srcAddress, long targetAddress, long length) {
      unsafe.copyMemory(srcAddress, targetAddress, length);
    }

    @Override
    public Object getStaticObject(Field field) {
      return getObject(unsafe.staticFieldBase(field), unsafe.staticFieldOffset(field));
    }
  }

}