|
40 | 40 | */ |
41 | 41 | package com.oracle.graal.python.builtins.objects.cext.common; |
42 | 42 |
|
| 43 | +import static com.oracle.graal.python.builtins.objects.cext.capi.NativeCAPISymbol.FUN_GET_BYTE_ARRAY_TYPE_ID; |
| 44 | + |
| 45 | +import java.lang.reflect.Field; |
| 46 | +import java.nio.ByteBuffer; |
| 47 | +import java.nio.charset.StandardCharsets; |
| 48 | + |
43 | 49 | import com.oracle.graal.python.builtins.objects.cext.capi.CApiContext.LLVMType; |
44 | 50 | import com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.GetLLVMType; |
45 | 51 | import com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.IsPointerNode; |
|
63 | 69 | import com.oracle.truffle.api.library.ExportLibrary; |
64 | 70 | import com.oracle.truffle.api.library.ExportMessage; |
65 | 71 | import com.oracle.truffle.llvm.spi.NativeTypeLibrary; |
66 | | -import sun.misc.Unsafe; |
67 | 72 |
|
68 | | -import java.lang.reflect.Field; |
69 | | -import java.nio.ByteBuffer; |
70 | | -import java.nio.charset.StandardCharsets; |
71 | | - |
72 | | -import static com.oracle.graal.python.builtins.objects.cext.capi.NativeCAPISymbol.FUN_GET_BYTE_ARRAY_TYPE_ID; |
| 73 | +import sun.misc.Unsafe; |
73 | 74 |
|
74 | 75 | /** |
75 | 76 | * Native wrappers for managed objects such that they can be used as a C array by native code. The |
@@ -98,10 +99,13 @@ private static Unsafe getUnsafe() { |
98 | 99 | * the copies the contents to the native memory. |
99 | 100 | */ |
100 | 101 | @TruffleBoundary |
101 | | - public static long byteArrayToNativeInt8(byte[] data) { |
102 | | - int size = data.length * Byte.BYTES; |
| 102 | + public static long byteArrayToNativeInt8(byte[] data, boolean writeNullTerminator) { |
| 103 | + int size = (data.length + (writeNullTerminator ? 1 : 0)) * Byte.BYTES; |
103 | 104 | long ptr = UNSAFE.allocateMemory(size); |
104 | 105 | UNSAFE.copyMemory(data, Unsafe.ARRAY_BYTE_BASE_OFFSET, null, ptr, size); |
| 106 | + if (writeNullTerminator) { |
| 107 | + UNSAFE.putByte(ptr + data.length * Byte.BYTES, (byte) 0); |
| 108 | + } |
105 | 109 | return ptr; |
106 | 110 | } |
107 | 111 |
|
@@ -140,7 +144,7 @@ public static long stringToNativeUtf8Bytes(String string) { |
140 | 144 | ByteBuffer encoded = StandardCharsets.UTF_8.encode(string); |
141 | 145 | byte[] data = new byte[encoded.remaining() + 1]; |
142 | 146 | encoded.get(data, 0, data.length - 1); |
143 | | - return byteArrayToNativeInt8(data); |
| 147 | + return byteArrayToNativeInt8(data, true); |
144 | 148 | } |
145 | 149 |
|
146 | 150 | @TruffleBoundary |
@@ -326,7 +330,7 @@ void toNative( |
326 | 330 | @Exclusive @Cached InvalidateNativeObjectsAllManagedNode invalidateNode) { |
327 | 331 | invalidateNode.execute(); |
328 | 332 | if (!lib.isNative(this)) { |
329 | | - setNativePointer(byteArrayToNativeInt8(getByteArray(lib))); |
| 333 | + setNativePointer(byteArrayToNativeInt8(getByteArray(lib), true)); |
330 | 334 | } |
331 | 335 | } |
332 | 336 | } |
|
0 commit comments