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