1 /*
   2  * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #warn This file is preprocessed before being compiled
  27 
  28 package java.nio;
  29 
  30 import java.io.FileDescriptor;
  31 import jdk.internal.misc.Unsafe;
  32 import jdk.internal.misc.VM;
  33 import java.lang.ref.Cleaner;
  34 import jdk.internal.ref.CleanerFactory;
  35 import sun.nio.ch.DirectBuffer;
  36 
  37 
  38 class Direct$Type$Buffer$RW$$BO$
  39 #if[rw]
  40     extends {#if[byte]?Mapped$Type$Buffer:$Type$Buffer}
  41 #else[rw]
  42     extends Direct$Type$Buffer$BO$
  43 #end[rw]
  44     implements DirectBuffer
  45 {
  46 
  47 #if[rw]
  48 
  49     // Cached unsafe-access object
  50     protected static final Unsafe unsafe = Bits.unsafe();
  51 
  52     // Cached array base offset
  53     private static final long arrayBaseOffset = (long)unsafe.arrayBaseOffset($type$[].class);
  54 
  55     // Cached unaligned-access capability
  56     protected static final boolean unaligned = Bits.unaligned();
  57 
  58     // Base address, used in all indexing calculations
  59     // NOTE: moved up to Buffer.java for speed in JNI GetDirectBufferAddress
  60     //    protected long address;
  61 
  62     // An object attached to this buffer. If this buffer is a view of another
  63     // buffer then we use this field to keep a reference to that buffer to
  64     // ensure that its memory isn't freed before we are done with it.
  65     private final Object att;
  66 
  67     public Object attachment() {
  68         return att;
  69     }
  70 
  71 #if[byte]
  72 
  73     private static class Deallocator
  74         implements Runnable
  75     {
  76 
  77         private static Unsafe unsafe = Unsafe.getUnsafe();
  78 
  79         private long address;
  80         private long size;
  81         private int capacity;
  82 
  83         private Deallocator(long address, long size, int capacity) {
  84             assert (address != 0);
  85             this.address = address;
  86             this.size = size;
  87             this.capacity = capacity;
  88         }
  89 
  90         public void run() {
  91             if (address == 0) {
  92                 // Paranoia
  93                 return;
  94             }
  95             unsafe.freeMemory(address);
  96             address = 0;
  97             Bits.unreserveMemory(size, capacity);
  98         }
  99 
 100     }
 101 
 102     private final Cleaner.Cleanable cleaner;
 103 
 104     public Cleaner.Cleanable cleaner() { return cleaner; }
 105 
 106 #else[byte]
 107 
 108     public Cleaner.Cleanable cleaner() { return null; }
 109 
 110 #end[byte]
 111 
 112 #end[rw]
 113 
 114 #if[byte]
 115 
 116     // Primary constructor
 117     //
 118     Direct$Type$Buffer$RW$(int cap) {                   // package-private
 119 #if[rw]
 120         super(-1, 0, cap, cap);
 121         boolean pa = VM.isDirectMemoryPageAligned();
 122         int ps = Bits.pageSize();
 123         long size = Math.max(1L, (long)cap + (pa ? ps : 0));
 124         Bits.reserveMemory(size, cap);
 125 
 126         long base = 0;
 127         try {
 128             base = unsafe.allocateMemory(size);
 129         } catch (OutOfMemoryError x) {
 130             Bits.unreserveMemory(size, cap);
 131             throw x;
 132         }
 133         unsafe.setMemory(base, size, (byte) 0);
 134         if (pa && (base % ps != 0)) {
 135             // Round up to page boundary
 136             address = base + ps - (base & (ps - 1));
 137         } else {
 138             address = base;
 139         }
 140         cleaner = CleanerFactory.cleaner().register(this, new Deallocator(base, size, cap));
 141         att = null;
 142 #else[rw]
 143         super(cap);
 144 #end[rw]
 145     }
 146 
 147 #if[rw]
 148 
 149     // Invoked to construct a direct ByteBuffer referring to the block of
 150     // memory. A given arbitrary object may also be attached to the buffer.
 151     //
 152     Direct$Type$Buffer(long addr, int cap, Object ob) {
 153         super(-1, 0, cap, cap);
 154         address = addr;
 155         cleaner = null;
 156         att = ob;
 157     }
 158 
 159 
 160     // Invoked only by JNI: NewDirectByteBuffer(void*, long)
 161     //
 162     private Direct$Type$Buffer(long addr, int cap) {
 163         super(-1, 0, cap, cap);
 164         address = addr;
 165         cleaner = null;
 166         att = null;
 167     }
 168 
 169 #end[rw]
 170 
 171     // For memory-mapped buffers -- invoked by FileChannelImpl via reflection
 172     //
 173     protected Direct$Type$Buffer$RW$(int cap, long addr,
 174                                      FileDescriptor fd,
 175                                      Runnable unmapper)
 176     {
 177 #if[rw]
 178         super(-1, 0, cap, cap, fd);
 179         address = addr;
 180         cleaner = (unmapper == null)
 181                   ? null
 182                   : CleanerFactory.cleaner().register(this, unmapper);
 183         att = null;
 184 #else[rw]
 185         super(cap, addr, fd, unmapper);
 186 #end[rw]
 187     }
 188 
 189 #end[byte]
 190 
 191     // For duplicates and slices
 192     //
 193     Direct$Type$Buffer$RW$$BO$(DirectBuffer db,         // package-private
 194                                int mark, int pos, int lim, int cap,
 195                                int off)
 196     {
 197 #if[rw]
 198         super(mark, pos, lim, cap);
 199         address = db.address() + off;
 200 #if[byte]
 201         cleaner = null;
 202 #end[byte]
 203         att = db;
 204 #else[rw]
 205         super(db, mark, pos, lim, cap, off);
 206 #end[rw]
 207     }
 208 
 209     public $Type$Buffer slice() {
 210         int pos = this.position();
 211         int lim = this.limit();
 212         assert (pos <= lim);
 213         int rem = (pos <= lim ? lim - pos : 0);
 214         int off = (pos << $LG_BYTES_PER_VALUE$);
 215         assert (off >= 0);
 216         return new Direct$Type$Buffer$RW$$BO$(this, -1, 0, rem, rem, off);
 217     }
 218 
 219     public $Type$Buffer duplicate() {
 220         return new Direct$Type$Buffer$RW$$BO$(this,
 221                                               this.markValue(),
 222                                               this.position(),
 223                                               this.limit(),
 224                                               this.capacity(),
 225                                               0);
 226     }
 227 
 228     public $Type$Buffer asReadOnlyBuffer() {
 229 #if[rw]
 230         return new Direct$Type$BufferR$BO$(this,
 231                                            this.markValue(),
 232                                            this.position(),
 233                                            this.limit(),
 234                                            this.capacity(),
 235                                            0);
 236 #else[rw]
 237         return duplicate();
 238 #end[rw]
 239     }
 240 
 241 #if[rw]
 242 
 243     public long address() {
 244         return address;
 245     }
 246 
 247     private long ix(int i) {
 248         return address + ((long)i << $LG_BYTES_PER_VALUE$);
 249     }
 250 
 251     public $type$ get() {
 252         return $fromBits$($swap$(unsafe.get$Swaptype$(ix(nextGetIndex()))));
 253     }
 254 
 255     public $type$ get(int i) {
 256         return $fromBits$($swap$(unsafe.get$Swaptype$(ix(checkIndex(i)))));
 257     }
 258 
 259 #if[streamableType]
 260     $type$ getUnchecked(int i) {
 261         return $fromBits$($swap$(unsafe.get$Swaptype$(ix(i))));
 262     }
 263 #end[streamableType]
 264 
 265     public $Type$Buffer get($type$[] dst, int offset, int length) {
 266 #if[rw]
 267         if (((long)length << $LG_BYTES_PER_VALUE$) > Bits.JNI_COPY_TO_ARRAY_THRESHOLD) {
 268             checkBounds(offset, length, dst.length);
 269             int pos = position();
 270             int lim = limit();
 271             assert (pos <= lim);
 272             int rem = (pos <= lim ? lim - pos : 0);
 273             if (length > rem)
 274                 throw new BufferUnderflowException();
 275 
 276 #if[!byte]
 277             if (order() != ByteOrder.nativeOrder())
 278                 Bits.copyTo$Memtype$Array(ix(pos), dst,
 279                                           (long)offset << $LG_BYTES_PER_VALUE$,
 280                                           (long)length << $LG_BYTES_PER_VALUE$);
 281             else
 282 #end[!byte]
 283                 Bits.copyToArray(ix(pos), dst, arrayBaseOffset,
 284                                  (long)offset << $LG_BYTES_PER_VALUE$,
 285                                  (long)length << $LG_BYTES_PER_VALUE$);
 286             position(pos + length);
 287         } else {
 288             super.get(dst, offset, length);
 289         }
 290         return this;
 291 #else[rw]
 292         throw new ReadOnlyBufferException();
 293 #end[rw]
 294     }
 295 
 296 #end[rw]
 297 
 298     public $Type$Buffer put($type$ x) {
 299 #if[rw]
 300         unsafe.put$Swaptype$(ix(nextPutIndex()), $swap$($toBits$(x)));
 301         return this;
 302 #else[rw]
 303         throw new ReadOnlyBufferException();
 304 #end[rw]
 305     }
 306 
 307     public $Type$Buffer put(int i, $type$ x) {
 308 #if[rw]
 309         unsafe.put$Swaptype$(ix(checkIndex(i)), $swap$($toBits$(x)));
 310         return this;
 311 #else[rw]
 312         throw new ReadOnlyBufferException();
 313 #end[rw]
 314     }
 315 
 316     public $Type$Buffer put($Type$Buffer src) {
 317 #if[rw]
 318         if (src instanceof Direct$Type$Buffer$BO$) {
 319             if (src == this)
 320                 throw createSameBufferException();
 321             Direct$Type$Buffer$RW$$BO$ sb = (Direct$Type$Buffer$RW$$BO$)src;
 322 
 323             int spos = sb.position();
 324             int slim = sb.limit();
 325             assert (spos <= slim);
 326             int srem = (spos <= slim ? slim - spos : 0);
 327 
 328             int pos = position();
 329             int lim = limit();
 330             assert (pos <= lim);
 331             int rem = (pos <= lim ? lim - pos : 0);
 332 
 333             if (srem > rem)
 334                 throw new BufferOverflowException();
 335             unsafe.copyMemory(sb.ix(spos), ix(pos), (long)srem << $LG_BYTES_PER_VALUE$);
 336             sb.position(spos + srem);
 337             position(pos + srem);
 338         } else if (src.hb != null) {
 339 
 340             int spos = src.position();
 341             int slim = src.limit();
 342             assert (spos <= slim);
 343             int srem = (spos <= slim ? slim - spos : 0);
 344 
 345             put(src.hb, src.offset + spos, srem);
 346             src.position(spos + srem);
 347 
 348         } else {
 349             super.put(src);
 350         }
 351         return this;
 352 #else[rw]
 353         throw new ReadOnlyBufferException();
 354 #end[rw]
 355     }
 356 
 357     public $Type$Buffer put($type$[] src, int offset, int length) {
 358 #if[rw]
 359         if (((long)length << $LG_BYTES_PER_VALUE$) > Bits.JNI_COPY_FROM_ARRAY_THRESHOLD) {
 360             checkBounds(offset, length, src.length);
 361             int pos = position();
 362             int lim = limit();
 363             assert (pos <= lim);
 364             int rem = (pos <= lim ? lim - pos : 0);
 365             if (length > rem)
 366                 throw new BufferOverflowException();
 367 
 368 #if[!byte]
 369             if (order() != ByteOrder.nativeOrder())
 370                 Bits.copyFrom$Memtype$Array(src,
 371                                             (long)offset << $LG_BYTES_PER_VALUE$,
 372                                             ix(pos),
 373                                             (long)length << $LG_BYTES_PER_VALUE$);
 374             else
 375 #end[!byte]
 376                 Bits.copyFromArray(src, arrayBaseOffset,
 377                                    (long)offset << $LG_BYTES_PER_VALUE$,
 378                                    ix(pos),
 379                                    (long)length << $LG_BYTES_PER_VALUE$);
 380             position(pos + length);
 381         } else {
 382             super.put(src, offset, length);
 383         }
 384         return this;
 385 #else[rw]
 386         throw new ReadOnlyBufferException();
 387 #end[rw]
 388     }
 389 
 390     public $Type$Buffer compact() {
 391 #if[rw]
 392         int pos = position();
 393         int lim = limit();
 394         assert (pos <= lim);
 395         int rem = (pos <= lim ? lim - pos : 0);
 396 
 397         unsafe.copyMemory(ix(pos), ix(0), (long)rem << $LG_BYTES_PER_VALUE$);
 398         position(rem);
 399         limit(capacity());
 400         discardMark();
 401         return this;
 402 #else[rw]
 403         throw new ReadOnlyBufferException();
 404 #end[rw]
 405     }
 406 
 407     public boolean isDirect() {
 408         return true;
 409     }
 410 
 411     public boolean isReadOnly() {
 412         return {#if[rw]?false:true};
 413     }
 414 
 415 
 416 #if[char]
 417 
 418     public String toString(int start, int end) {
 419         if ((end > limit()) || (start > end))
 420             throw new IndexOutOfBoundsException();
 421         try {
 422             int len = end - start;
 423             char[] ca = new char[len];
 424             CharBuffer cb = CharBuffer.wrap(ca);
 425             CharBuffer db = this.duplicate();
 426             db.position(start);
 427             db.limit(end);
 428             cb.put(db);
 429             return new String(ca);
 430         } catch (StringIndexOutOfBoundsException x) {
 431             throw new IndexOutOfBoundsException();
 432         }
 433     }
 434 
 435 
 436     // --- Methods to support CharSequence ---
 437 
 438     public CharBuffer subSequence(int start, int end) {
 439         int pos = position();
 440         int lim = limit();
 441         assert (pos <= lim);
 442         pos = (pos <= lim ? pos : lim);
 443         int len = lim - pos;
 444 
 445         if ((start < 0) || (end > len) || (start > end))
 446             throw new IndexOutOfBoundsException();
 447         return new DirectCharBuffer$RW$$BO$(this,
 448                                             -1,
 449                                             pos + start,
 450                                             pos + end,
 451                                             capacity(),
 452                                             offset);
 453     }
 454 
 455 #end[char]
 456 
 457 
 458 
 459 #if[!byte]
 460 
 461     public ByteOrder order() {
 462 #if[boS]
 463         return ((ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN)
 464                 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
 465 #end[boS]
 466 #if[boU]
 467         return ((ByteOrder.nativeOrder() != ByteOrder.BIG_ENDIAN)
 468                 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
 469 #end[boU]
 470     }
 471 
 472 #end[!byte]
 473 
 474 
 475 
 476 #if[byte]
 477 
 478     byte _get(int i) {                          // package-private
 479         return unsafe.getByte(address + i);
 480     }
 481 
 482     void _put(int i, byte b) {                  // package-private
 483 #if[rw]
 484         unsafe.putByte(address + i, b);
 485 #else[rw]
 486         throw new ReadOnlyBufferException();
 487 #end[rw]
 488     }
 489 
 490     // #BIN
 491     //
 492     // Binary-data access methods  for short, char, int, long, float,
 493     // and double will be inserted here
 494 
 495 #end[byte]
 496 
 497 }