1 /*
   2  * Copyright (c) 2000, 2018, 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 java.lang.ref.Reference;
  32 import jdk.internal.misc.VM;
  33 import jdk.internal.ref.Cleaner;
  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 array base offset
  49     private static final long ARRAY_BASE_OFFSET = UNSAFE.arrayBaseOffset($type$[].class);
  50 
  51     // Cached unaligned-access capability
  52     protected static final boolean UNALIGNED = Bits.unaligned();
  53 
  54     // Base address, used in all indexing calculations
  55     // NOTE: moved up to Buffer.java for speed in JNI GetDirectBufferAddress
  56     //    protected long address;
  57 
  58     // An object attached to this buffer. If this buffer is a view of another
  59     // buffer then we use this field to keep a reference to that buffer to
  60     // ensure that its memory isn't freed before we are done with it.
  61     private final Object att;
  62 
  63     public Object attachment() {
  64         return att;
  65     }
  66 
  67 #if[byte]
  68 
  69     private static class Deallocator
  70         implements Runnable
  71     {
  72 
  73         private long address;
  74         private long size;
  75         private int capacity;
  76 
  77         private Deallocator(long address, long size, int capacity) {
  78             assert (address != 0);
  79             this.address = address;
  80             this.size = size;
  81             this.capacity = capacity;
  82         }
  83 
  84         public void run() {
  85             if (address == 0) {
  86                 // Paranoia
  87                 return;
  88             }
  89             UNSAFE.freeMemory(address);
  90             address = 0;
  91             Bits.unreserveMemory(size, capacity);
  92         }
  93 
  94     }
  95 
  96     private final Cleaner cleaner;
  97 
  98     public Cleaner cleaner() { return cleaner; }
  99 
 100 #else[byte]
 101 
 102     public Cleaner cleaner() { return null; }
 103 
 104 #end[byte]
 105 
 106 #end[rw]
 107 
 108 #if[byte]
 109 
 110     // Primary constructor
 111     //
 112     Direct$Type$Buffer$RW$(int cap) {                   // package-private
 113 #if[rw]
 114         super(-1, 0, cap, cap);
 115         boolean pa = VM.isDirectMemoryPageAligned();
 116         int ps = Bits.pageSize();
 117         long size = Math.max(1L, (long)cap + (pa ? ps : 0));
 118         Bits.reserveMemory(size, cap);
 119 
 120         long base = 0;
 121         try {
 122             base = UNSAFE.allocateMemory(size);
 123         } catch (OutOfMemoryError x) {
 124             Bits.unreserveMemory(size, cap);
 125             throw x;
 126         }
 127         UNSAFE.setMemory(base, size, (byte) 0);
 128         if (pa && (base % ps != 0)) {
 129             // Round up to page boundary
 130             address = base + ps - (base & (ps - 1));
 131         } else {
 132             address = base;
 133         }
 134         cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
 135         att = null;
 136 #else[rw]
 137         super(cap);
 138         this.isReadOnly = true;
 139 #end[rw]
 140     }
 141 
 142 #if[rw]
 143 
 144     // Invoked to construct a direct ByteBuffer referring to the block of
 145     // memory. A given arbitrary object may also be attached to the buffer.
 146     //
 147     Direct$Type$Buffer(long addr, int cap, Object ob) {
 148         super(-1, 0, cap, cap);
 149         address = addr;
 150         cleaner = null;
 151         att = ob;
 152     }
 153 
 154 
 155     // Invoked only by JNI: NewDirectByteBuffer(void*, long)
 156     //
 157     private Direct$Type$Buffer(long addr, int cap) {
 158         super(-1, 0, cap, cap);
 159         address = addr;
 160         cleaner = null;
 161         att = null;
 162     }
 163 
 164 #end[rw]
 165 
 166     // For memory-mapped buffers -- invoked by FileChannelImpl via reflection
 167     //
 168     protected Direct$Type$Buffer$RW$(int cap, long addr,
 169                                      FileDescriptor fd,
 170                                      Runnable unmapper,
 171                                      boolean isPersistent)
 172     {
 173 #if[rw]
 174         super(-1, 0, cap, cap, fd, isPersistent);
 175         address = addr;
 176         cleaner = Cleaner.create(this, unmapper);
 177         att = null;
 178 #else[rw]
 179         super(cap, addr, fd, unmapper, isPersistent);
 180         this.isReadOnly = true;
 181 #end[rw]
 182     }
 183 
 184 #end[byte]
 185 
 186     // For duplicates and slices
 187     //
 188     Direct$Type$Buffer$RW$$BO$(DirectBuffer db,         // package-private
 189                                int mark, int pos, int lim, int cap,
 190                                int off)
 191     {
 192 #if[rw]
 193         super(mark, pos, lim, cap);
 194         address = db.address() + off;
 195 #if[byte]
 196         cleaner = null;
 197 #end[byte]
 198         Object attachment = db.attachment();
 199         att = (attachment == null ? db : attachment);
 200 #else[rw]
 201         super(db, mark, pos, lim, cap, off);
 202         this.isReadOnly = true;
 203 #end[rw]
 204     }
 205 
 206     @Override
 207     Object base() {
 208         return null;
 209     }
 210 
 211     public $Type$Buffer slice() {
 212         int pos = this.position();
 213         int lim = this.limit();
 214         assert (pos <= lim);
 215         int rem = (pos <= lim ? lim - pos : 0);
 216         int off = (pos << $LG_BYTES_PER_VALUE$);
 217         assert (off >= 0);
 218         return new Direct$Type$Buffer$RW$$BO$(this, -1, 0, rem, rem, off);
 219     }
 220 
 221 #if[byte]
 222     public $Type$Buffer slice(int pos, int lim) {
 223         assert (pos >= 0);
 224         assert (pos <= lim);
 225         int rem = lim - pos;
 226         return new Direct$Type$Buffer$RW$$BO$(this, -1, 0, rem, rem, pos);
 227     }
 228 #end[byte]
 229 
 230     public $Type$Buffer duplicate() {
 231         return new Direct$Type$Buffer$RW$$BO$(this,
 232                                               this.markValue(),
 233                                               this.position(),
 234                                               this.limit(),
 235                                               this.capacity(),
 236                                               0);
 237     }
 238 
 239     public $Type$Buffer asReadOnlyBuffer() {
 240 #if[rw]
 241         return new Direct$Type$BufferR$BO$(this,
 242                                            this.markValue(),
 243                                            this.position(),
 244                                            this.limit(),
 245                                            this.capacity(),
 246                                            0);
 247 #else[rw]
 248         return duplicate();
 249 #end[rw]
 250     }
 251 
 252 #if[rw]
 253 
 254     public long address() {
 255         return address;
 256     }
 257 
 258     private long ix(int i) {
 259         return address + ((long)i << $LG_BYTES_PER_VALUE$);
 260     }
 261 
 262     public $type$ get() {
 263         try {
 264             return $fromBits$($swap$(UNSAFE.get$Swaptype$(ix(nextGetIndex()))));
 265         } finally {
 266             Reference.reachabilityFence(this);
 267         }
 268     }
 269 
 270     public $type$ get(int i) {
 271         try {
 272             return $fromBits$($swap$(UNSAFE.get$Swaptype$(ix(checkIndex(i)))));
 273         } finally {
 274             Reference.reachabilityFence(this);
 275         }
 276     }
 277 
 278 #if[streamableType]
 279     $type$ getUnchecked(int i) {
 280         try {
 281             return $fromBits$($swap$(UNSAFE.get$Swaptype$(ix(i))));
 282         } finally {
 283             Reference.reachabilityFence(this);
 284         }
 285     }
 286 #end[streamableType]
 287 
 288     public $Type$Buffer get($type$[] dst, int offset, int length) {
 289 #if[rw]
 290         if (((long)length << $LG_BYTES_PER_VALUE$) > Bits.JNI_COPY_TO_ARRAY_THRESHOLD) {
 291             checkBounds(offset, length, dst.length);
 292             int pos = position();
 293             int lim = limit();
 294             assert (pos <= lim);
 295             int rem = (pos <= lim ? lim - pos : 0);
 296             if (length > rem)
 297                 throw new BufferUnderflowException();
 298 
 299             long dstOffset = ARRAY_BASE_OFFSET + ((long)offset << $LG_BYTES_PER_VALUE$);
 300             try {
 301 #if[!byte]
 302                 if (order() != ByteOrder.nativeOrder())
 303                     UNSAFE.copySwapMemory(null,
 304                                           ix(pos),
 305                                           dst,
 306                                           dstOffset,
 307                                           (long)length << $LG_BYTES_PER_VALUE$,
 308                                           (long)1 << $LG_BYTES_PER_VALUE$);
 309                 else
 310 #end[!byte]
 311                     UNSAFE.copyMemory(null,
 312                                       ix(pos),
 313                                       dst,
 314                                       dstOffset,
 315                                       (long)length << $LG_BYTES_PER_VALUE$);
 316             } finally {
 317                 Reference.reachabilityFence(this);
 318             }
 319             position(pos + length);
 320         } else {
 321             super.get(dst, offset, length);
 322         }
 323         return this;
 324 #else[rw]
 325         throw new ReadOnlyBufferException();
 326 #end[rw]
 327     }
 328 
 329 #end[rw]
 330 
 331     public $Type$Buffer put($type$ x) {
 332 #if[rw]
 333         try {
 334             UNSAFE.put$Swaptype$(ix(nextPutIndex()), $swap$($toBits$(x)));
 335         } finally {
 336             Reference.reachabilityFence(this);
 337         }
 338         return this;
 339 #else[rw]
 340         throw new ReadOnlyBufferException();
 341 #end[rw]
 342     }
 343 
 344     public $Type$Buffer put(int i, $type$ x) {
 345 #if[rw]
 346         try {
 347             UNSAFE.put$Swaptype$(ix(checkIndex(i)), $swap$($toBits$(x)));
 348         } finally {
 349             Reference.reachabilityFence(this);
 350         }
 351         return this;
 352 #else[rw]
 353         throw new ReadOnlyBufferException();
 354 #end[rw]
 355     }
 356 
 357     public $Type$Buffer put($Type$Buffer src) {
 358 #if[rw]
 359         if (src instanceof Direct$Type$Buffer$BO$) {
 360             if (src == this)
 361                 throw createSameBufferException();
 362             Direct$Type$Buffer$RW$$BO$ sb = (Direct$Type$Buffer$RW$$BO$)src;
 363 
 364             int spos = sb.position();
 365             int slim = sb.limit();
 366             assert (spos <= slim);
 367             int srem = (spos <= slim ? slim - spos : 0);
 368 
 369             int pos = position();
 370             int lim = limit();
 371             assert (pos <= lim);
 372             int rem = (pos <= lim ? lim - pos : 0);
 373 
 374             if (srem > rem)
 375                 throw new BufferOverflowException();
 376             try {
 377                 UNSAFE.copyMemory(sb.ix(spos), ix(pos), (long)srem << $LG_BYTES_PER_VALUE$);
 378             } finally {
 379                 Reference.reachabilityFence(sb);
 380                 Reference.reachabilityFence(this);
 381             }
 382             sb.position(spos + srem);
 383             position(pos + srem);
 384         } else if (src.hb != null) {
 385 
 386             int spos = src.position();
 387             int slim = src.limit();
 388             assert (spos <= slim);
 389             int srem = (spos <= slim ? slim - spos : 0);
 390 
 391             put(src.hb, src.offset + spos, srem);
 392             src.position(spos + srem);
 393 
 394         } else {
 395             super.put(src);
 396         }
 397         return this;
 398 #else[rw]
 399         throw new ReadOnlyBufferException();
 400 #end[rw]
 401     }
 402 
 403     public $Type$Buffer put($type$[] src, int offset, int length) {
 404 #if[rw]
 405         if (((long)length << $LG_BYTES_PER_VALUE$) > Bits.JNI_COPY_FROM_ARRAY_THRESHOLD) {
 406             checkBounds(offset, length, src.length);
 407             int pos = position();
 408             int lim = limit();
 409             assert (pos <= lim);
 410             int rem = (pos <= lim ? lim - pos : 0);
 411             if (length > rem)
 412                 throw new BufferOverflowException();
 413 
 414             long srcOffset = ARRAY_BASE_OFFSET + ((long)offset << $LG_BYTES_PER_VALUE$);
 415             try {
 416 #if[!byte]
 417                 if (order() != ByteOrder.nativeOrder())
 418                     UNSAFE.copySwapMemory(src,
 419                                           srcOffset,
 420                                           null,
 421                                           ix(pos),
 422                                           (long)length << $LG_BYTES_PER_VALUE$,
 423                                           (long)1 << $LG_BYTES_PER_VALUE$);
 424                 else
 425 #end[!byte]
 426                     UNSAFE.copyMemory(src,
 427                                       srcOffset,
 428                                       null,
 429                                       ix(pos),
 430                                       (long)length << $LG_BYTES_PER_VALUE$);
 431             } finally {
 432                 Reference.reachabilityFence(this);
 433             }
 434             position(pos + length);
 435         } else {
 436             super.put(src, offset, length);
 437         }
 438         return this;
 439 #else[rw]
 440         throw new ReadOnlyBufferException();
 441 #end[rw]
 442     }
 443 
 444     public $Type$Buffer compact() {
 445 #if[rw]
 446         int pos = position();
 447         int lim = limit();
 448         assert (pos <= lim);
 449         int rem = (pos <= lim ? lim - pos : 0);
 450         try {
 451             UNSAFE.copyMemory(ix(pos), ix(0), (long)rem << $LG_BYTES_PER_VALUE$);
 452         } finally {
 453             Reference.reachabilityFence(this);
 454         }
 455         position(rem);
 456         limit(capacity());
 457         discardMark();
 458         return this;
 459 #else[rw]
 460         throw new ReadOnlyBufferException();
 461 #end[rw]
 462     }
 463 
 464     public boolean isDirect() {
 465         return true;
 466     }
 467 
 468     public boolean isReadOnly() {
 469         return {#if[rw]?false:true};
 470     }
 471 
 472 
 473 #if[char]
 474 
 475     public String toString(int start, int end) {
 476         if ((end > limit()) || (start > end))
 477             throw new IndexOutOfBoundsException();
 478         try {
 479             int len = end - start;
 480             char[] ca = new char[len];
 481             CharBuffer cb = CharBuffer.wrap(ca);
 482             CharBuffer db = this.duplicate();
 483             db.position(start);
 484             db.limit(end);
 485             cb.put(db);
 486             return new String(ca);
 487         } catch (StringIndexOutOfBoundsException x) {
 488             throw new IndexOutOfBoundsException();
 489         }
 490     }
 491 
 492 
 493     // --- Methods to support CharSequence ---
 494 
 495     public CharBuffer subSequence(int start, int end) {
 496         int pos = position();
 497         int lim = limit();
 498         assert (pos <= lim);
 499         pos = (pos <= lim ? pos : lim);
 500         int len = lim - pos;
 501 
 502         if ((start < 0) || (end > len) || (start > end))
 503             throw new IndexOutOfBoundsException();
 504         return new DirectCharBuffer$RW$$BO$(this,
 505                                             -1,
 506                                             pos + start,
 507                                             pos + end,
 508                                             capacity(),
 509                                             offset);
 510     }
 511 
 512 #end[char]
 513 
 514 
 515 
 516 #if[!byte]
 517 
 518     public ByteOrder order() {
 519 #if[boS]
 520         return ((ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN)
 521                 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
 522 #end[boS]
 523 #if[boU]
 524         return ((ByteOrder.nativeOrder() != ByteOrder.BIG_ENDIAN)
 525                 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
 526 #end[boU]
 527     }
 528 
 529 #end[!byte]
 530 
 531 #if[char]
 532     ByteOrder charRegionOrder() {
 533         return order();
 534     }
 535 #end[char]
 536 
 537 
 538 #if[byte]
 539     // #BIN
 540     //
 541     // Binary-data access methods  for short, char, int, long, float,
 542     // and double will be inserted here
 543 
 544 #end[byte]
 545 
 546 }