1 /* 2 * Copyright (c) 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 27 package jdk.incubator.foreign; 28 29 import java.nio.ByteBuffer; 30 31 import jdk.internal.foreign.AbstractMemorySegmentImpl; 32 import jdk.internal.foreign.HeapMemorySegmentImpl; 33 import jdk.internal.foreign.MappedMemorySegmentImpl; 34 import jdk.internal.foreign.NativeMemorySegmentImpl; 35 import jdk.internal.foreign.Utils; 36 37 import java.io.IOException; 38 import java.nio.channels.FileChannel; 39 import java.nio.file.Path; 40 import java.util.Objects; 41 import java.util.Spliterator; 42 import java.util.function.Consumer; 43 44 /** 45 * A memory segment models a contiguous region of memory. A memory segment is associated with both spatial 46 * and temporal bounds. Spatial bounds ensure that memory access operations on a memory segment cannot affect a memory location 47 * which falls <em>outside</em> the boundaries of the memory segment being accessed. Temporal checks ensure that memory access 48 * operations on a segment cannot occur after a memory segment has been closed (see {@link MemorySegment#close()}). 49 * <p> 50 * All implementations of this interface must be <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>; 51 * use of identity-sensitive operations (including reference equality ({@code ==}), identity hash code, or synchronization) on 52 * instances of {@code MemorySegment} may have unpredictable results and should be avoided. The {@code equals} method should 53 * be used for comparisons. 54 * <p> 55 * Non-platform classes should not implement {@linkplain MemorySegment} directly. 56 * 57 * <h2>Constructing memory segments from different sources</h2> 58 * 59 * There are multiple ways to obtain a memory segment. First, memory segments backed by off-heap memory can 60 * be allocated using one of the many factory methods provided (see {@link MemorySegment#allocateNative(MemoryLayout)}, 61 * {@link MemorySegment#allocateNative(long)} and {@link MemorySegment#allocateNative(long, long)}). Memory segments obtained 62 * in this way are called <em>native memory segments</em>. 63 * <p> 64 * It is also possible to obtain a memory segment backed by an existing heap-allocated Java array, 65 * using one of the provided factory methods (e.g. {@link MemorySegment#ofArray(int[])}). Memory segments obtained 66 * in this way are called <em>array memory segments</em>. 67 * <p> 68 * It is possible to obtain a memory segment backed by an existing Java byte buffer (see {@link ByteBuffer}), 69 * using the factory method {@link MemorySegment#ofByteBuffer(ByteBuffer)}. 70 * Memory segments obtained in this way are called <em>buffer memory segments</em>. Note that buffer memory segments might 71 * be backed by native memory (as in the case of native memory segments) or heap memory (as in the case of array memory segments), 72 * depending on the characteristics of the byte buffer instance the segment is associated with. For instance, a buffer memory 73 * segment obtained from a byte buffer created with the {@link ByteBuffer#allocateDirect(int)} method will be backed 74 * by native memory. 75 * <p> 76 * Finally, it is also possible to obtain a memory segment backed by a memory-mapped file using the factory method 77 * {@link MemorySegment#mapFromPath(Path, long, FileChannel.MapMode)}. Such memory segments are called <em>mapped memory segments</em> 78 * (see {@link MappedMemorySegment}). 79 * 80 * <h2>Closing a memory segment</h2> 81 * 82 * Memory segments are closed explicitly (see {@link MemorySegment#close()}). In general when a segment is closed, all off-heap 83 * resources associated with it are released; this has different meanings depending on the kind of memory segment being 84 * considered: 85 * <ul> 86 * <li>closing a native memory segment results in <em>freeing</em> the native memory associated with it</li> 87 * <li>closing a mapped memory segment results in the backing memory-mapped file to be unmapped</li> 88 * <li>closing a buffer, or a heap segment does not have any side-effect, other than marking the segment 89 * as <em>not alive</em> (see {@link MemorySegment#isAlive()}). Also, since the buffer and heap segments might keep 90 * strong references to the original buffer or array instance, it is the responsibility of clients to ensure that 91 * these segments are discarded in a timely manner, so as not to prevent garbage collection to reclaim the underlying 92 * objects.</li> 93 * </ul> 94 * 95 * <h2><a id = "thread-confinement">Thread confinement</a></h2> 96 * 97 * Memory segments support strong thread-confinement guarantees. Upon creation, they are assigned an <em>owner thread</em>, 98 * typically the thread which initiated the creation operation. After creation, only the owner thread will be allowed 99 * to directly manipulate the memory segment (e.g. close the memory segment) or access the underlying memory associated with 100 * the segment using a memory access var handle. Any attempt to perform such operations from a thread other than the 101 * owner thread will result in a runtime failure. 102 * <p> 103 * Memory segments support <em>serial thread confinement</em>; that is, ownership of a memory segment can change (see 104 * {@link #withOwnerThread(Thread)}). This allows, for instance, for two threads {@code A} and {@code B} to share 105 * a segment in a controlled, cooperative and race-free fashion. 106 * <p> 107 * In some cases, it might be useful for multiple threads to process the contents of the same memory segment concurrently 108 * (e.g. in the case of parallel processing); while memory segments provide strong confinement guarantees, it is possible 109 * to obtain a {@link Spliterator} from a segment, which can be used to slice the segment and allow multiple thread to 110 * work in parallel on disjoint segment slices (this assumes that the access mode {@link #ACQUIRE} is set). 111 * For instance, the following code can be used to sum all int values in a memory segment in parallel: 112 * <blockquote><pre>{@code 113 SequenceLayout SEQUENCE_LAYOUT = MemoryLayout.ofSequence(1024, MemoryLayouts.JAVA_INT); 114 VarHandle VH_int = SEQUENCE_LAYOUT.elementLayout().varHandle(int.class); 115 int sum = StreamSupport.stream(segment.spliterator(SEQUENCE_LAYOUT), true) 116 .mapToInt(segment -> (int)VH_int.get(segment.baseAddress)) 117 .sum(); 118 * }</pre></blockquote> 119 * 120 * <h2><a id = "access-modes">Access modes</a></h2> 121 * 122 * Memory segments supports zero or more <em>access modes</em>. Supported access modes are {@link #READ}, 123 * {@link #WRITE}, {@link #CLOSE} and {@link #ACQUIRE}. The set of access modes supported by a segment alters the 124 * set of operations that are supported by that segment. For instance, attempting to call {@link #close()} on 125 * a segment which does not support the {@link #CLOSE} access mode will result in an exception. 126 * <p> 127 * The set of supported access modes can only be made stricter (by supporting <em>less</em> access modes). This means 128 * that restricting the set of access modes supported by a segment before sharing it with other clients 129 * is generally a good practice if the creator of the segment wants to retain some control over how the segment 130 * is going to be accessed. 131 * 132 * <h2>Memory segment views</h2> 133 * 134 * Memory segments support <em>views</em>. For instance, it is possible to alter the set of supported access modes, 135 * by creating an <em>immutable</em> view of a memory segment, as follows: 136 * <blockquote><pre>{@code 137 MemorySegment segment = ... 138 MemorySegment roSegment = segment.withAccessModes(segment.accessModes() & ~WRITE); 139 * }</pre></blockquote> 140 * It is also possible to create views whose spatial bounds are stricter than the ones of the original segment 141 * (see {@link MemorySegment#asSlice(long, long)}). 142 * <p> 143 * Temporal bounds of the original segment are inherited by the view; that is, closing a segment view, such as a sliced 144 * view, will cause the original segment to be closed; as such special care must be taken when sharing views 145 * between multiple clients. If a client want to protect itself against early closure of a segment by 146 * another actor, it is the responsibility of that client to take protective measures, such as removing {@link #CLOSE} 147 * from the set of supported access modes, before sharing the view with another client. 148 * <p> 149 * To allow for interoperability with existing code, a byte buffer view can be obtained from a memory segment 150 * (see {@link #asByteBuffer()}). This can be useful, for instance, for those clients that want to keep using the 151 * {@link ByteBuffer} API, but need to operate on large memory segments. Byte buffers obtained in such a way support 152 * the same spatial and temporal access restrictions associated to the memory address from which they originated. 153 * 154 * @apiNote In the future, if the Java language permits, {@link MemorySegment} 155 * may become a {@code sealed} interface, which would prohibit subclassing except by 156 * {@link MappedMemorySegment} and other explicitly permitted subtypes. 157 * 158 * @implSpec 159 * Implementations of this interface are immutable and thread-safe. 160 */ 161 public interface MemorySegment extends AutoCloseable { 162 163 /** 164 * The base memory address associated with this memory segment. The returned address is 165 * a <em>checked</em> memory address and can therefore be used in derefrence operations 166 * (see {@link MemoryAddress}). 167 * @return The base memory address. 168 */ 169 MemoryAddress baseAddress(); 170 171 /** 172 * Returns a spliterator for the given memory segment. The returned spliterator reports {@link Spliterator#SIZED}, 173 * {@link Spliterator#SUBSIZED}, {@link Spliterator#IMMUTABLE}, {@link Spliterator#NONNULL} and {@link Spliterator#ORDERED} 174 * characteristics. 175 * <p> 176 * The returned spliterator splits the segment according to the specified sequence layout; that is, 177 * if the supplied layout is a sequence layout whose element count is {@code N}, then calling {@link Spliterator#trySplit()} 178 * will result in a spliterator serving approximatively {@code N/2} elements (depending on whether N is even or not). 179 * As such, splitting is possible as long as {@code N >= 2}. 180 * <p> 181 * The returned spliterator effectively allows to slice a segment into disjoint sub-segments, which can then 182 * be processed in parallel by multiple threads (if the access mode {@link #ACQUIRE} is set). 183 * While closing the segment (see {@link #close()}) during pending concurrent execution will generally 184 * fail with an exception, it is possible to close a segment when a spliterator has been obtained but no thread 185 * is actively working on it using {@link Spliterator#tryAdvance(Consumer)}; in such cases, any subsequent call 186 * to {@link Spliterator#tryAdvance(Consumer)} will fail with an exception. 187 * @param segment the segment to be used for splitting. 188 * @param layout the layout to be used for splitting. 189 * @param <S> the memory segment type 190 * @return the element spliterator for this segment 191 * @throws IllegalStateException if the segment is not <em>alive</em>, or if access occurs from a thread other than the 192 * thread owning this segment 193 */ 194 static <S extends MemorySegment> Spliterator<S> spliterator(S segment, SequenceLayout layout) { 195 return AbstractMemorySegmentImpl.spliterator(segment, layout); 196 } 197 198 /** 199 * Fills a value into the given memory segment. 200 * <p> 201 * More specifically, the given value is filled into each address of the 202 * segment. Equivalent to (but likely more efficient than) the following code: 203 * 204 * <blockquote><pre> 205 * byteHandle = MemoryLayout.ofSequence(MemoryLayouts.JAVA_BYTE) 206 * .varHandle(byte.class, MemoryLayout.PathElement.sequenceElement()); 207 * for (long l = 0; l < segment.byteSize(); l++) { 208 * byteHandle.set(segment.baseAddress(), l, value); 209 * }</pre></blockquote> 210 * <p> 211 * Fill can be useful to initialize or reset the memory of a segment. 212 * 213 * @param segment the segment to fill 214 * @param value the value to fill into the segment 215 * @throws IllegalStateException if the segment is not <em>alive</em>, or if access occurs from a thread other than the 216 * thread owning this segment 217 * @throws UnsupportedOperationException if this segment does not support the {@link #WRITE} access mode 218 * @throws NullPointerException if {@code segment == null} 219 */ 220 static void fill(MemorySegment segment, byte value) { 221 AbstractMemorySegmentImpl.fill(segment, value); 222 } 223 224 /** 225 * The thread owning this segment. 226 * @return the thread owning this segment. 227 */ 228 Thread ownerThread(); 229 230 /** 231 * Obtains a new memory segment backed by the same underlying memory region as this segment, 232 * but with different owner thread. As a side-effect, this segment will be marked as <em>not alive</em>, 233 * and subsequent operations on this segment will result in runtime errors. 234 * <p> 235 * Write accesses to the segment's content <a href="../../../java/util/concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> 236 * hand-over from the current owner thread to the new owner thread, which in turn <i>happens before</i> read accesses to the segment's contents on 237 * the new owner thread. 238 * 239 * @param newOwner the new owner thread. 240 * @return a new memory segment backed by the same underlying memory region as this segment, 241 * owned by {@code newOwner}. 242 * @throws IllegalStateException if this segment is not <em>alive</em>, or if access occurs from a thread other than the 243 * thread owning this segment, or if the segment cannot be closed because it is being operated upon by a different 244 * thread (see {@link #spliterator(SequenceLayout)}). 245 * @throws NullPointerException if {@code newOwner == null} 246 * @throws IllegalArgumentException if the segment is already a confined segment owner by {@code newOnwer}. 247 * @throws UnsupportedOperationException if this segment does not support the {@link #HANDOFF} access mode. 248 */ 249 MemorySegment withOwnerThread(Thread newOwner); 250 251 /** 252 * The size (in bytes) of this memory segment. 253 * @return The size (in bytes) of this memory segment. 254 */ 255 long byteSize(); 256 257 /** 258 * Obtains a segment view with specific <a href="#access-modes">access modes</a>. Supported access modes are {@link #READ}, {@link #WRITE}, 259 * {@link #CLOSE} and {@link #ACQUIRE}. It is generally not possible to go from a segment with stricter access modes 260 * to one with less strict access modes. For instance, attempting to add {@link #WRITE} access mode to a read-only segment 261 * will be met with an exception. 262 * @param accessModes an ORed mask of zero or more access modes. 263 * @return a segment view with specific access modes. 264 * @throws UnsupportedOperationException when {@code mask} is an access mask which is less strict than the one supported by this 265 * segment. 266 */ 267 MemorySegment withAccessModes(int accessModes); 268 269 /** 270 * Does this segment support a given set of access modes? 271 * @param accessModes an ORed mask of zero or more access modes. 272 * @return true, if the access modes in {@code accessModes} are stricter than the ones supported by this segment. 273 */ 274 boolean hasAccessModes(int accessModes); 275 276 /** 277 * Returns the <a href="#access-modes">access modes</a> associated with this segment; the result is represented as ORed values from 278 * {@link #READ}, {@link #WRITE}, {@link #CLOSE} and {@link #ACQUIRE}. 279 * @return the access modes associated with this segment. 280 */ 281 int accessModes(); 282 283 /** 284 * Obtains a new memory segment view whose base address is the same as the base address of this segment plus a given offset, 285 * and whose new size is specified by the given argument. 286 * @param offset The new segment base offset (relative to the current segment base address), specified in bytes. 287 * @param newSize The new segment size, specified in bytes. 288 * @return a new memory segment view with updated base/limit addresses. 289 * @throws IndexOutOfBoundsException if {@code offset < 0}, {@code offset > byteSize()}, {@code newSize < 0}, or {@code newSize > byteSize() - offset} 290 */ 291 MemorySegment asSlice(long offset, long newSize); 292 293 /** 294 * Is this segment alive? 295 * @return true, if the segment is alive. 296 * @see MemorySegment#close() 297 */ 298 boolean isAlive(); 299 300 /** 301 * Closes this memory segment. Once a memory segment has been closed, any attempt to use the memory segment, 302 * or to access the memory associated with the segment will fail with {@link IllegalStateException}. Depending on 303 * the kind of memory segment being closed, calling this method further trigger deallocation of all the resources 304 * associated with the memory segment. 305 * @throws IllegalStateException if this segment is not <em>alive</em>, or if access occurs from a thread other than the 306 * thread owning this segment, or if the segment cannot be closed because it is being operated upon by a different 307 * thread (see {@link #spliterator(MemorySegment, SequenceLayout)}). 308 * @throws UnsupportedOperationException if this segment does not support the {@link #CLOSE} access mode. 309 */ 310 void close(); 311 312 /** 313 * Wraps this segment in a {@link ByteBuffer}. Some of the properties of the returned buffer are linked to 314 * the properties of this segment. For instance, if this segment is <em>immutable</em> 315 * (e.g. the segment has access mode {@link #READ} but not {@link #WRITE}), then the resulting buffer is <em>read-only</em> 316 * (see {@link ByteBuffer#isReadOnly()}. Additionally, if this is a native memory segment, the resulting buffer is 317 * <em>direct</em> (see {@link ByteBuffer#isDirect()}). 318 * <p> 319 * The life-cycle of the returned buffer will be tied to that of this segment. That means that if the this segment 320 * is closed (see {@link MemorySegment#close()}, accessing the returned 321 * buffer will throw an {@link IllegalStateException}. 322 * <p> 323 * The resulting buffer's byte order is {@link java.nio.ByteOrder#BIG_ENDIAN}; this can be changed using 324 * {@link ByteBuffer#order(java.nio.ByteOrder)}. 325 * 326 * @return a {@link ByteBuffer} view of this memory segment. 327 * @throws UnsupportedOperationException if this segment cannot be mapped onto a {@link ByteBuffer} instance, 328 * e.g. because it models an heap-based segment that is not based on a {@code byte[]}), or if its size is greater 329 * than {@link Integer#MAX_VALUE}, or if the segment does not support the {@link #READ} access mode. 330 */ 331 ByteBuffer asByteBuffer(); 332 333 /** 334 * Copy the contents of this memory segment into a fresh byte array. 335 * @return a fresh byte array copy of this memory segment. 336 * @throws UnsupportedOperationException if this segment's contents cannot be copied into a {@link byte[]} instance, 337 * e.g. its size is greater than {@link Integer#MAX_VALUE}. 338 * @throws IllegalStateException if this segment has been closed, or if access occurs from a thread other than the 339 * thread owning this segment. 340 */ 341 byte[] toByteArray(); 342 343 /** 344 * Creates a new buffer memory segment that models the memory associated with the given byte 345 * buffer. The segment starts relative to the buffer's position (inclusive) 346 * and ends relative to the buffer's limit (exclusive). 347 * <p> 348 * The resulting memory segment keeps a reference to the backing buffer, to ensure it remains <em>reachable</em> 349 * for the life-time of the segment. 350 * 351 * @param bb the byte buffer backing the buffer memory segment. 352 * @return a new buffer memory segment. 353 */ 354 static MemorySegment ofByteBuffer(ByteBuffer bb) { 355 return AbstractMemorySegmentImpl.ofBuffer(bb); 356 } 357 358 /** 359 * Creates a new array memory segment that models the memory associated with a given heap-allocated byte array. 360 * <p> 361 * The resulting memory segment keeps a reference to the backing array, to ensure it remains <em>reachable</em> 362 * for the life-time of the segment. 363 * 364 * @param arr the primitive array backing the array memory segment. 365 * @return a new array memory segment. 366 */ 367 static MemorySegment ofArray(byte[] arr) { 368 return HeapMemorySegmentImpl.makeArraySegment(arr); 369 } 370 371 /** 372 * Creates a new array memory segment that models the memory associated with a given heap-allocated char array. 373 * <p> 374 * The resulting memory segment keeps a reference to the backing array, to ensure it remains <em>reachable</em> 375 * for the life-time of the segment. 376 * 377 * @param arr the primitive array backing the array memory segment. 378 * @return a new array memory segment. 379 */ 380 static MemorySegment ofArray(char[] arr) { 381 return HeapMemorySegmentImpl.makeArraySegment(arr); 382 } 383 384 /** 385 * Creates a new array memory segment that models the memory associated with a given heap-allocated short array. 386 * <p> 387 * The resulting memory segment keeps a reference to the backing array, to ensure it remains <em>reachable</em> 388 * for the life-time of the segment. 389 * 390 * @param arr the primitive array backing the array memory segment. 391 * @return a new array memory segment. 392 */ 393 static MemorySegment ofArray(short[] arr) { 394 return HeapMemorySegmentImpl.makeArraySegment(arr); 395 } 396 397 /** 398 * Creates a new array memory segment that models the memory associated with a given heap-allocated int array. 399 * <p> 400 * The resulting memory segment keeps a reference to the backing array, to ensure it remains <em>reachable</em> 401 * for the life-time of the segment. 402 * 403 * @param arr the primitive array backing the array memory segment. 404 * @return a new array memory segment. 405 */ 406 static MemorySegment ofArray(int[] arr) { 407 return HeapMemorySegmentImpl.makeArraySegment(arr); 408 } 409 410 /** 411 * Creates a new array memory segment that models the memory associated with a given heap-allocated float array. 412 * <p> 413 * The resulting memory segment keeps a reference to the backing array, to ensure it remains <em>reachable</em> 414 * for the life-time of the segment. 415 * 416 * @param arr the primitive array backing the array memory segment. 417 * @return a new array memory segment. 418 */ 419 static MemorySegment ofArray(float[] arr) { 420 return HeapMemorySegmentImpl.makeArraySegment(arr); 421 } 422 423 /** 424 * Creates a new array memory segment that models the memory associated with a given heap-allocated long array. 425 * <p> 426 * The resulting memory segment keeps a reference to the backing array, to ensure it remains <em>reachable</em> 427 * for the life-time of the segment. 428 * 429 * @param arr the primitive array backing the array memory segment. 430 * @return a new array memory segment. 431 */ 432 static MemorySegment ofArray(long[] arr) { 433 return HeapMemorySegmentImpl.makeArraySegment(arr); 434 } 435 436 /** 437 * Creates a new array memory segment that models the memory associated with a given heap-allocated double array. 438 * <p> 439 * The resulting memory segment keeps a reference to the backing array, to ensure it remains <em>reachable</em> 440 * for the life-time of the segment. 441 * 442 * @param arr the primitive array backing the array memory segment. 443 * @return a new array memory segment. 444 */ 445 static MemorySegment ofArray(double[] arr) { 446 return HeapMemorySegmentImpl.makeArraySegment(arr); 447 } 448 449 /** 450 * Creates a new native memory segment that models a newly allocated block of off-heap memory with given layout. 451 * <p> 452 * This is equivalent to the following code: 453 * <blockquote><pre>{@code 454 allocateNative(layout.bytesSize(), layout.bytesAlignment()); 455 * }</pre></blockquote> 456 * 457 * @implNote The block of off-heap memory associated with the returned native memory segment is initialized to zero. 458 * Moreover, a client is responsible to call the {@link MemorySegment#close()} on a native memory segment, 459 * to make sure the backing off-heap memory block is deallocated accordingly. Failure to do so will result in off-heap memory leaks. 460 * 461 * @param layout the layout of the off-heap memory block backing the native memory segment. 462 * @return a new native memory segment. 463 * @throws IllegalArgumentException if the specified layout has illegal size or alignment constraint. 464 */ 465 static MemorySegment allocateNative(MemoryLayout layout) { 466 return allocateNative(layout.byteSize(), layout.byteAlignment()); 467 } 468 469 /** 470 * Creates a new native memory segment that models a newly allocated block of off-heap memory with given size (in bytes). 471 * <p> 472 * This is equivalent to the following code: 473 * <blockquote><pre>{@code 474 allocateNative(bytesSize, 1); 475 * }</pre></blockquote> 476 * 477 * @implNote The block of off-heap memory associated with the returned native memory segment is initialized to zero. 478 * Moreover, a client is responsible to call the {@link MemorySegment#close()} on a native memory segment, 479 * to make sure the backing off-heap memory block is deallocated accordingly. Failure to do so will result in off-heap memory leaks. 480 * 481 * @param bytesSize the size (in bytes) of the off-heap memory block backing the native memory segment. 482 * @return a new native memory segment. 483 * @throws IllegalArgumentException if {@code bytesSize < 0}. 484 */ 485 static MemorySegment allocateNative(long bytesSize) { 486 return allocateNative(bytesSize, 1); 487 } 488 489 /** 490 * Creates a new mapped memory segment that models a memory-mapped region of a file from a given path. 491 * 492 * @implNote When obtaining a mapped segment from a newly created file, the initialization state of the contents of the block 493 * of mapped memory associated with the returned mapped memory segment is unspecified and should not be relied upon. 494 * 495 * @param path the path to the file to memory map. 496 * @param bytesSize the size (in bytes) of the mapped memory backing the memory segment. 497 * @param mapMode a file mapping mode, see {@link FileChannel#map(FileChannel.MapMode, long, long)}; the chosen mapping mode 498 * might affect the behavior of the returned memory mapped segment (see {@link MappedMemorySegment#force()}). 499 * @return a new mapped memory segment. 500 * @throws IllegalArgumentException if {@code bytesSize < 0}. 501 * @throws UnsupportedOperationException if an unsupported map mode is specified. 502 * @throws IOException if the specified path does not point to an existing file, or if some other I/O error occurs. 503 */ 504 static MappedMemorySegment mapFromPath(Path path, long bytesSize, FileChannel.MapMode mapMode) throws IOException { 505 return MappedMemorySegmentImpl.makeMappedSegment(path, bytesSize, mapMode); 506 } 507 508 /** 509 * Creates a new native memory segment that models a newly allocated block of off-heap memory with given size and 510 * alignment constraint (in bytes). 511 * 512 * @implNote The block of off-heap memory associated with the returned native memory segment is initialized to zero. 513 * Moreover, a client is responsible to call the {@link MemorySegment#close()} on a native memory segment, 514 * to make sure the backing off-heap memory block is deallocated accordingly. Failure to do so will result in off-heap memory leaks. 515 * 516 * @param bytesSize the size (in bytes) of the off-heap memory block backing the native memory segment. 517 * @param alignmentBytes the alignment constraint (in bytes) of the off-heap memory block backing the native memory segment. 518 * @return a new native memory segment. 519 * @throws IllegalArgumentException if {@code bytesSize < 0}, {@code alignmentBytes < 0}, or if {@code alignmentBytes} 520 * is not a power of 2. 521 */ 522 static MemorySegment allocateNative(long bytesSize, long alignmentBytes) { 523 if (bytesSize <= 0) { 524 throw new IllegalArgumentException("Invalid allocation size : " + bytesSize); 525 } 526 527 if (alignmentBytes < 0 || 528 ((alignmentBytes & (alignmentBytes - 1)) != 0L)) { 529 throw new IllegalArgumentException("Invalid alignment constraint : " + alignmentBytes); 530 } 531 532 return NativeMemorySegmentImpl.makeNativeSegment(bytesSize, alignmentBytes); 533 } 534 535 /** 536 * Returns a new native memory segment with given base address and size; the returned segment has its own temporal 537 * bounds, and can therefore be closed; closing such a segment can optionally result in calling an user-provided cleanup 538 * action. This method can be very useful when interacting with custom native memory sources (e.g. custom allocators, 539 * GPU memory, etc.), where an address to some underlying memory region is typically obtained from native code 540 * (often as a plain {@code long} value). 541 * <p> 542 * This method is <em>restricted</em>. Restricted method are unsafe, and, if used incorrectly, their use might crash 543 * the JVM crash or, worse, silently result in memory corruption. Thus, clients should refrain from depending on 544 * restricted methods, and use safe and supported functionalities, where possible. 545 * 546 * @param addr the desired base address 547 * @param bytesSize the desired size. 548 * @param owner the desired owner thread. If {@code owner == null}, the returned segment is <em>not</em> confined. 549 * @param cleanup a cleanup action to be executed when the {@link MemorySegment#close()} method is called on the 550 * returned segment. If {@code cleanup == null}, no cleanup action is executed. 551 * @param attachment an object that must be kept alive by the returned segment; this can be useful when 552 * the returned segment depends on memory which could be released if a certain object 553 * is determined to be unreacheable. In most cases this will be set to {@code null}. 554 * @return a new native memory segment with given base address, size, owner, cleanup action and object attachment. 555 * @throws IllegalArgumentException if {@code bytesSize <= 0}. 556 * @throws UnsupportedOperationException if {@code addr} is associated with an heap segment. 557 * @throws IllegalAccessError if the runtime property {@code foreign.restricted} is not set to either 558 * {@code permit}, {@code warn} or {@code debug} (the default value is set to {@code deny}). 559 * @throws NullPointerException if {@code addr == null}. 560 */ 561 static MemorySegment ofNativeRestricted(MemoryAddress addr, long bytesSize, Thread owner, Runnable cleanup, Object attachment) { 562 Objects.requireNonNull(addr); 563 if (bytesSize <= 0) { 564 throw new IllegalArgumentException("Invalid size : " + bytesSize); 565 } 566 Utils.checkRestrictedAccess("MemorySegment.ofNativeRestricted"); 567 return NativeMemorySegmentImpl.makeNativeSegmentUnchecked(addr, bytesSize, owner, cleanup, attachment); 568 } 569 570 // access mode masks 571 572 /** 573 * Read access mode; read operations are supported by a segment which supports this access mode. 574 * @see MemorySegment#accessModes() 575 * @see MemorySegment#withAccessModes(int) 576 */ 577 int READ = 1; 578 579 /** 580 * Write access mode; write operations are supported by a segment which supports this access mode. 581 * @see MemorySegment#accessModes() 582 * @see MemorySegment#withAccessModes(int) 583 */ 584 int WRITE = READ << 1; 585 586 /** 587 * Close access mode; calling {@link #close()} is supported by a segment which supports this access mode. 588 * @see MemorySegment#accessModes() 589 * @see MemorySegment#withAccessModes(int) 590 */ 591 int CLOSE = WRITE << 1; 592 593 /** 594 * Acquire access mode; this segment support sharing with threads other than the owner thread, via spliterator 595 * (see {@link #spliterator(MemorySegment, SequenceLayout)}). 596 * @see MemorySegment#accessModes() 597 * @see MemorySegment#withAccessModes(int) 598 */ 599 int ACQUIRE = CLOSE << 1; 600 601 /** 602 * Handoff access mode; this segment support serial thread-confinement via thread ownership changes 603 * (see {@link #withOwnerThread(Thread)}). 604 * @see MemorySegment#accessModes() 605 * @see MemorySegment#withAccessModes(int) 606 */ 607 int HANDOFF = ACQUIRE << 1; 608 }