1 /*
   2  * Copyright (c) 2000, 2013, 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 sun.misc.Cleaner;
  32 import sun.misc.Unsafe;
  33 import sun.misc.VM;
  34 import sun.nio.ch.DirectBuffer;
  35 
  36 
  37 class Direct$Type$Buffer$RW$$BO$
  38 #if[rw]
  39     extends {#if[byte]?Mapped$Type$Buffer:$Type$Buffer}
  40 #else[rw]
  41     extends Direct$Type$Buffer$BO$
  42 #end[rw]
  43     implements DirectBuffer
  44 {
  45 
  46 #if[rw]
  47 
  48     // Cached unsafe-access object
  49     protected static final Unsafe unsafe = Bits.unsafe();
  50 
  51     // Cached array base offset
  52     private static final long arrayBaseOffset = (long)unsafe.arrayBaseOffset($type$[].class);
  53     private static final long arrayIndexScale = (long)unsafe.arrayIndexScale($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 cleaner;
 103 
 104     public Cleaner cleaner() { return cleaner; }
 105 
 106 #else[byte]
 107 
 108     public Cleaner 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 = Cleaner.create(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 = Cleaner.create(this, unmapper);
 181         att = null;
 182 #else[rw]
 183         super(cap, addr, fd, unmapper);
 184 #end[rw]
 185     }
 186 
 187 #end[byte]
 188 
 189     // For duplicates and slices
 190     //
 191     Direct$Type$Buffer$RW$$BO$(DirectBuffer db,         // package-private
 192                                int mark, int pos, int lim, int cap,
 193                                int off)
 194     {
 195 #if[rw]
 196         super(mark, pos, lim, cap);
 197         address = db.address() + off;
 198 #if[byte]
 199         cleaner = null;
 200 #end[byte]
 201         att = db;
 202 #else[rw]
 203         super(db, mark, pos, lim, cap, off);
 204 #end[rw]
 205     }
 206 
 207     public $Type$Buffer slice() {
 208         int pos = this.position();
 209         int lim = this.limit();
 210         assert (pos <= lim);
 211         int rem = (pos <= lim ? lim - pos : 0);
 212         int off = (pos << $LG_BYTES_PER_VALUE$);
 213         assert (off >= 0);
 214         return new Direct$Type$Buffer$RW$$BO$(this, -1, 0, rem, rem, off);
 215     }
 216 
 217     public $Type$Buffer duplicate() {
 218         return new Direct$Type$Buffer$RW$$BO$(this,
 219                                               this.markValue(),
 220                                               this.position(),
 221                                               this.limit(),
 222                                               this.capacity(),
 223                                               0);
 224     }
 225 
 226     public $Type$Buffer asReadOnlyBuffer() {
 227 #if[rw]
 228         return new Direct$Type$BufferR$BO$(this,
 229                                            this.markValue(),
 230                                            this.position(),
 231                                            this.limit(),
 232                                            this.capacity(),
 233                                            0);
 234 #else[rw]
 235         return duplicate();
 236 #end[rw]
 237     }
 238 
 239 #if[rw]
 240 
 241     public long address() {
 242         return address;
 243     }
 244 
 245     private long ix(int i) {
 246         return address + (i << $LG_BYTES_PER_VALUE$);
 247     }
 248 
 249     public $type$ get() {
 250         return $fromBits$($swap$(unsafe.get$Swaptype$(ix(nextGetIndex()))));
 251     }
 252 
 253     public $type$ get(int i) {
 254         return $fromBits$($swap$(unsafe.get$Swaptype$(ix(checkIndex(i)))));
 255     }
 256 
 257 #if[streamableType]
 258     $type$ getUnchecked(int i) {
 259         return $fromBits$($swap$(unsafe.get$Swaptype$(ix(i))));
 260     }
 261 #end[streamableType]
 262 
 263     public $Type$Buffer get($type$[] dst, int offset, int length) {
 264 #if[rw]
 265         if ((length << $LG_BYTES_PER_VALUE$) > Bits.JNI_COPY_TO_ARRAY_THRESHOLD) {
 266             checkBounds(offset, length, dst.length);
 267             int pos = position();
 268             int lim = limit();
 269             assert (pos <= lim);
 270             int rem = (pos <= lim ? lim - pos : 0);
 271             if (length > rem)
 272                 throw new BufferUnderflowException();
 273 
 274 #if[!byte]
 275             if (order() != ByteOrder.nativeOrder())
 276                 Bits.copyTo$Memtype$Array(ix(pos), dst,
 277                                           offset << $LG_BYTES_PER_VALUE$,
 278                                           length << $LG_BYTES_PER_VALUE$);
 279             else
 280 #end[!byte]
 281                 Bits.copyToArray(ix(pos), dst, arrayBaseOffset,
 282                                  offset * arrayIndexScale,
 283                                  length << $LG_BYTES_PER_VALUE$);
 284             position(pos + length);
 285         } else {
 286             super.get(dst, offset, length);
 287         }
 288         return this;
 289 #else[rw]
 290         throw new ReadOnlyBufferException();
 291 #end[rw]
 292     }
 293 
 294 #end[rw]
 295 
 296     public $Type$Buffer put($type$ x) {
 297 #if[rw]
 298         unsafe.put$Swaptype$(ix(nextPutIndex()), $swap$($toBits$(x)));
 299         return this;
 300 #else[rw]
 301         throw new ReadOnlyBufferException();
 302 #end[rw]
 303     }
 304 
 305     public $Type$Buffer put(int i, $type$ x) {
 306 #if[rw]
 307         unsafe.put$Swaptype$(ix(checkIndex(i)), $swap$($toBits$(x)));
 308         return this;
 309 #else[rw]
 310         throw new ReadOnlyBufferException();
 311 #end[rw]
 312     }
 313 
 314     public $Type$Buffer put($Type$Buffer src) {
 315 #if[rw]
 316         if (src instanceof Direct$Type$Buffer$BO$) {
 317             if (src == this)
 318                 throw new IllegalArgumentException();
 319             Direct$Type$Buffer$RW$$BO$ sb = (Direct$Type$Buffer$RW$$BO$)src;
 320 
 321             int spos = sb.position();
 322             int slim = sb.limit();
 323             assert (spos <= slim);
 324             int srem = (spos <= slim ? slim - spos : 0);
 325 
 326             int pos = position();
 327             int lim = limit();
 328             assert (pos <= lim);
 329             int rem = (pos <= lim ? lim - pos : 0);
 330 
 331             if (srem > rem)
 332                 throw new BufferOverflowException();
 333             unsafe.copyMemory(sb.ix(spos), ix(pos), srem << $LG_BYTES_PER_VALUE$);
 334             sb.position(spos + srem);
 335             position(pos + srem);
 336         } else if (src.hb != null) {
 337 
 338             int spos = src.position();
 339             int slim = src.limit();
 340             assert (spos <= slim);
 341             int srem = (spos <= slim ? slim - spos : 0);
 342 
 343             put(src.hb, src.offset + spos, srem);
 344             src.position(spos + srem);
 345 
 346         } else {
 347             super.put(src);
 348         }
 349         return this;
 350 #else[rw]
 351         throw new ReadOnlyBufferException();
 352 #end[rw]
 353     }
 354 
 355     public $Type$Buffer put($type$[] src, int offset, int length) {
 356 #if[rw]
 357         if ((length << $LG_BYTES_PER_VALUE$) > Bits.JNI_COPY_FROM_ARRAY_THRESHOLD) {
 358             checkBounds(offset, length, src.length);
 359             int pos = position();
 360             int lim = limit();
 361             assert (pos <= lim);
 362             int rem = (pos <= lim ? lim - pos : 0);
 363             if (length > rem)
 364                 throw new BufferOverflowException();
 365 
 366 #if[!byte]
 367             if (order() != ByteOrder.nativeOrder())
 368                 Bits.copyFrom$Memtype$Array(src, offset << $LG_BYTES_PER_VALUE$,
 369                                             ix(pos), length << $LG_BYTES_PER_VALUE$);
 370             else
 371 #end[!byte]
 372                 Bits.copyFromArray(src, arrayBaseOffset, offset * arrayIndexScale,
 373                                    ix(pos), length << $LG_BYTES_PER_VALUE$);
 374             position(pos + length);
 375         } else {
 376             super.put(src, offset, length);
 377         }
 378         return this;
 379 #else[rw]
 380         throw new ReadOnlyBufferException();
 381 #end[rw]
 382     }
 383 
 384     public $Type$Buffer compact() {
 385 #if[rw]
 386         int pos = position();
 387         int lim = limit();
 388         assert (pos <= lim);
 389         int rem = (pos <= lim ? lim - pos : 0);
 390 
 391         unsafe.copyMemory(ix(pos), ix(0), rem << $LG_BYTES_PER_VALUE$);
 392         position(rem);
 393         limit(capacity());
 394         discardMark();
 395         return this;
 396 #else[rw]
 397         throw new ReadOnlyBufferException();
 398 #end[rw]
 399     }
 400 
 401     public boolean isDirect() {
 402         return true;
 403     }
 404 
 405     public boolean isReadOnly() {
 406         return {#if[rw]?false:true};
 407     }
 408 
 409 
 410 #if[char]
 411 
 412     public String toString(int start, int end) {
 413         if ((end > limit()) || (start > end))
 414             throw new IndexOutOfBoundsException();
 415         try {
 416             int len = end - start;
 417             char[] ca = new char[len];
 418             CharBuffer cb = CharBuffer.wrap(ca);
 419             CharBuffer db = this.duplicate();
 420             db.position(start);
 421             db.limit(end);
 422             cb.put(db);
 423             return new String(ca);
 424         } catch (StringIndexOutOfBoundsException x) {
 425             throw new IndexOutOfBoundsException();
 426         }
 427     }
 428 
 429 
 430     // --- Methods to support CharSequence ---
 431 
 432     public CharBuffer subSequence(int start, int end) {
 433         int pos = position();
 434         int lim = limit();
 435         assert (pos <= lim);
 436         pos = (pos <= lim ? pos : lim);
 437         int len = lim - pos;
 438 
 439         if ((start < 0) || (end > len) || (start > end))
 440             throw new IndexOutOfBoundsException();
 441         return new DirectCharBuffer$RW$$BO$(this,
 442                                             -1,
 443                                             pos + start,
 444                                             pos + end,
 445                                             capacity(),
 446                                             offset);
 447     }
 448 
 449 #end[char]
 450 
 451 
 452 
 453 #if[!byte]
 454 
 455     public ByteOrder order() {
 456 #if[boS]
 457         return ((ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN)
 458                 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
 459 #end[boS]
 460 #if[boU]
 461         return ((ByteOrder.nativeOrder() != ByteOrder.BIG_ENDIAN)
 462                 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
 463 #end[boU]
 464     }
 465 
 466 #end[!byte]
 467 
 468 
 469 
 470 #if[byte]
 471 
 472     byte _get(int i) {                          // package-private
 473         return unsafe.getByte(address + i);
 474     }
 475 
 476     void _put(int i, byte b) {                  // package-private
 477 #if[rw]
 478         unsafe.putByte(address + i, b);
 479 #else[rw]
 480         throw new ReadOnlyBufferException();
 481 #end[rw]
 482     }
 483 
 484     // #BIN
 485     //
 486     // Binary-data access methods  for short, char, int, long, float,
 487     // and double will be inserted here
 488 
 489 #end[byte]
 490 
 491 }