[Git][java-team/ipcsocket][master] 7 commits: d/copyright: declare Nailgun code in the named pipe provider
Juan Manuel Méndez Rey (@mendezr)
gitlab at salsa.debian.org
Thu Oct 29 13:02:13 GMT 2026
Juan Manuel Méndez Rey pushed to branch master at Debian Java Maintainers / ipcsocket
Commits:
2e90f13a by Juan Manuel Méndez Rey at 2026-10-28T15:46:50+01:00
d/copyright: declare Nailgun code in the named pipe provider
Also note that NativeLoader.java is adapted from swoval.
- - - - -
3aa12f89 by Juan Manuel Méndez Rey at 2026-10-28T15:49:42+01:00
Update changelog for 1.8.0+dfsg-2
- - - - -
3204b2c4 by Juan Manuel Méndez Rey at 2026-10-28T16:41:55+01:00
New upstream version 1.8.1+dfsg
- - - - -
ddc3854f by Juan Manuel Méndez Rey at 2026-10-28T16:41:55+01:00
Update upstream source from tag 'upstream/1.8.1+dfsg'
Update to upstream version '1.8.1+dfsg'
with Debian dir 43d560dbd7f410fb9cc24094460c6fd32d8d93b6
- - - - -
baa91b92 by Juan Manuel Méndez Rey at 2026-10-28T16:42:28+01:00
Update to 1.8.1+dfsg-1
1.8.1 no longer closes the socket fd twice after EOF, which sbt 2.0.12
hits. Run the new AvailableTest and CloseAfterEofTest (JNA).
- - - - -
e90baa90 by Juan Manuel Méndez Rey at 2026-10-28T16:45:49+01:00
d/poms: version 1.8.1
- - - - -
b00e3ad5 by Juan Manuel Méndez Rey at 2026-10-28T21:05:21+01:00
d/copyright: the LICENSE file is covered by Files: *, not its own stanza
- - - - -
27 changed files:
- build.sbt
- debian/changelog
- debian/copyright
- debian/poms/ipcsocket.pom
- debian/tests/run-junit
- jni/org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider.c
- jni/org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider.h
- jni/org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider.c
- jni/org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider.h
- jni/org_scalasbt_ipcsocket_UnixDomainSocketLibrary.h
- src/main/java/org/scalasbt/ipcsocket/JNAWin32NamedPipeLibraryProvider.java
- src/main/java/org/scalasbt/ipcsocket/JNIUnixDomainSocketLibraryProvider.java
- src/main/java/org/scalasbt/ipcsocket/JNIWin32NamedPipeLibraryProvider.java
- src/main/java/org/scalasbt/ipcsocket/UnixDomainSocket.java
- src/main/java/org/scalasbt/ipcsocket/UnixDomainSocketLibrary.java
- src/main/java/org/scalasbt/ipcsocket/UnixDomainSocketLibraryProvider.java
- src/main/java/org/scalasbt/ipcsocket/Win32NamedPipeLibrary.java
- src/main/java/org/scalasbt/ipcsocket/Win32NamedPipeLibraryProvider.java
- src/main/java/org/scalasbt/ipcsocket/Win32NamedPipeSocket.java
- src/main/java/org/scalasbt/ipcsocket/Win32SecurityLibrary.java
- + src/test/java-jdk11/org/scalasbt/ipcsocket/StreamUnderLoadTest.java
- + src/test/java-jdk11/org/scalasbt/ipcsocket/StreamUnderLoadTestJNI.java
- + src/test/java/org/scalasbt/ipcsocket/AvailableTest.java
- + src/test/java/org/scalasbt/ipcsocket/AvailableTestJNI.java
- + src/test/java/org/scalasbt/ipcsocket/CloseAfterEofTest.java
- + src/test/java/org/scalasbt/ipcsocket/CloseAfterEofTestJNI.java
- + src/test/java/org/scalasbt/ipcsocket/Win32SecurityLibraryTest.java
Changes:
=====================================
build.sbt
=====================================
@@ -105,6 +105,11 @@ buildWin32X86_64 / skip := {
}, _.isEmpty)
}
Test / fork := true
+// tests that need JDK 11+ APIs (e.g. JFR); CI runs them in its JDK 25 jobs
+Test / unmanagedSourceDirectories ++= {
+ if (scala.util.Properties.isJavaAtLeast("11")) Seq((Test / sourceDirectory).value / "java-jdk11")
+ else Nil
+}
Test / javaOptions ++= {
import scala.util.Properties
if (Properties.isJavaAtLeast("11")) Seq("--enable-native-access=ALL-UNNAMED")
=====================================
debian/changelog
=====================================
@@ -1,3 +1,14 @@
+ipcsocket (1.8.1+dfsg-1) unstable; urgency=medium
+
+ * New upstream version 1.8.1: no double close of the socket fd after EOF,
+ which sbt 2.0.12 hits. Run its new JNA tests.
+ * Declare the Nailgun code in the named pipe provider in
+ debian/copyright.
+ * debian/copyright: cover the LICENSE file with Files: *, not its own
+ stanza.
+
+ -- Juan Manuel Méndez Rey <juan.mendezr at proton.me> Wed, 28 Oct 2026 16:42:04 +0100
+
ipcsocket (1.8.0+dfsg-1) unstable; urgency=medium
* Initial release (Closes: #1152326)
=====================================
debian/copyright
=====================================
@@ -15,10 +15,11 @@ Copyright: 2018-2026 Eugene Yokota
2018-2026 other contributors to sbt/ipcsocket
License: Apache-2.0
Comment: Files without a header. LICENSE.txt and README.md state Apache-2.0
- for the whole project.
+ for the whole project; LICENSE.txt keeps Nailgun's Martian Software
+ copyright line. NativeLoader.java is adapted from swoval, MIT code
+ by the same author, Ethan Atkins.
Files:
- LICENSE.txt
src/main/java/org/scalasbt/ipcsocket/ReferenceCountedFileDescriptor.java
src/main/java/org/scalasbt/ipcsocket/UnixDomainServerSocket.java
src/main/java/org/scalasbt/ipcsocket/UnixDomainSocket.java
@@ -30,6 +31,15 @@ Copyright: 2004-2017 Martian Software, Inc.
License: Apache-2.0
Comment: Server socket code taken from Nailgun.
+Files:
+ jni/org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider.c
+ src/main/java/org/scalasbt/ipcsocket/JNAWin32NamedPipeLibraryProvider.java
+Copyright: 2004-2017 Martian Software, Inc.
+ 2020 Ethan Atkins
+License: Apache-2.0
+Comment: Named pipe read and write code moved, and translated to C, from
+ Nailgun's NGWin32NamedPipeSocket.java.
+
Files: debian/*
Copyright: 2026 Juan Manuel Méndez Rey <juan.mendezr at proton.me>
License: Apache-2.0
=====================================
debian/poms/ipcsocket.pom
=====================================
@@ -6,7 +6,7 @@
<packaging>jar</packaging>
<description>IPC: Unix Domain Socket and Windows Named Pipes for Java</description>
<url>https://github.com/sbt/ipcsocket</url>
- <version>1.8.0</version>
+ <version>1.8.1</version>
<licenses>
<license>
<name>Apache-2.0</name>
=====================================
debian/tests/run-junit
=====================================
@@ -1,6 +1,7 @@
#!/bin/sh
# Run the upstream JUnit tests that use JNA against the jar given as $1.
-# SocketTestJNI and UnixSocketLengthTest need the JNI library, not built.
+# The *JNI tests and UnixSocketLengthTest need the JNI library, not built.
+# src/test/java-jdk11 (JFR load test) is not run.
set -e
JAR=${1:-/usr/share/java/ipcsocket.jar}
@@ -14,5 +15,7 @@ javac --release 8 -encoding UTF-8 -nowarn -cp "$CP" -d "$WORK" \
java --enable-native-access=ALL-UNNAMED -Djava.io.tmpdir="$WORK" \
-cp "$WORK:$CP" org.junit.runner.JUnitCore \
+ org.scalasbt.ipcsocket.AvailableTest \
+ org.scalasbt.ipcsocket.CloseAfterEofTest \
org.scalasbt.ipcsocket.SocketTest \
org.scalasbt.ipcsocket.duplex.DuplexTest
=====================================
jni/org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider.c
=====================================
@@ -3,6 +3,8 @@
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
+#include "sys/ioctl.h"
+#include "sys/poll.h"
#include "sys/socket.h"
#include "sys/types.h"
#include "sys/un.h"
@@ -10,11 +12,18 @@
#include "org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider.h"
#define UNUSED __attribute__((unused))
+/*
+ * errno is only meaningful when the call failed: a successful call may leave
+ * a stale value in it, and so may any JNI call made after it. Entering the VM
+ * from native may wait on a pthread condition variable (e.g. for a handshake),
+ * and on macOS an interrupted wait leaves EINTR|ECVCLEARED (260) in errno.
+ * Capture errno right after the call, and only when res < 0.
+ */
+#define ERRNO_OF(res) ((res) < 0 ? (errno ? errno : EIO) : 0)
#define THROW_ON_ERROR(res) \
do { \
- int err = errno; \
- errno = 0; \
- return err ? -err : (int)res; \
+ int result = (int)(res); \
+ return result < 0 ? -ERRNO_OF(result) : result; \
} while (0);
static void native_sockaddr(JNIEnv *env, struct sockaddr_un *native,
@@ -86,25 +95,31 @@ jint JNICALL
Java_org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider_readNative(
UNUSED JNIEnv *env, UNUSED jclass clazz, jint fd, jbyteArray buffer,
jint offset, jint len) {
- errno = 0;
jbyte *bytes = malloc(len);
+ if (bytes == NULL) {
+ return -ENOMEM;
+ }
int bytes_read = read(fd, bytes, len);
+ int err = ERRNO_OF(bytes_read);
if (bytes_read > 0) {
(*env)->SetByteArrayRegion(env, buffer, offset, bytes_read, bytes);
}
free(bytes);
- THROW_ON_ERROR(bytes_read);
+ return err ? -err : bytes_read;
}
jint JNICALL
Java_org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider_writeNative(
UNUSED JNIEnv *env, UNUSED jclass clazz, jint fd, jbyteArray buffer,
jint offset, jint len) {
- errno = 0;
jbyte *bytes = (*env)->GetByteArrayElements(env, buffer, 0);
+ if (bytes == NULL) {
+ return -ENOMEM;
+ }
int bytes_written = write(fd, bytes + offset, len);
+ int err = ERRNO_OF(bytes_written);
(*env)->ReleaseByteArrayElements(env, buffer, bytes, JNI_ABORT);
- THROW_ON_ERROR(bytes_written);
+ return err ? -err : bytes_written;
}
jint JNICALL
@@ -136,3 +151,27 @@ Java_org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider_maxSocketLength(
struct sockaddr_un un;
return sizeof(un.sun_path);
}
+
+jint JNICALL
+Java_org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider_availableNative(
+ UNUSED JNIEnv *env, UNUSED jclass clazz, jint fd) {
+ int n = 0;
+ ioctl(fd, FIONREAD, &n);
+ return n;
+}
+
+jint JNICALL
+Java_org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider_pollReadNative(
+ UNUSED JNIEnv *env, UNUSED jclass clazz, jint fd, jint timeout) {
+ errno = 0;
+ struct pollfd p;
+ p.fd = fd;
+ p.events = POLLIN;
+ p.revents = 0;
+ THROW_ON_ERROR(poll(&p, 1, timeout));
+ if ((p.revents & POLLIN) != 0) {
+ return 1;
+ } else {
+ return 0;
+ }
+}
=====================================
jni/org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider.h
=====================================
@@ -79,6 +79,22 @@ JNIEXPORT jint JNICALL Java_org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryPro
JNIEXPORT jint JNICALL Java_org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider_shutdownNative
(JNIEnv *, jobject, jint, jint);
+/*
+ * Class: org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider
+ * Method: availableNative
+ * Signature: (I)I
+ */
+JNIEXPORT jint JNICALL Java_org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider_availableNative
+ (JNIEnv *, jobject, jint);
+
+/*
+ * Class: org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider
+ * Method: pollReadNative
+ * Signature: (II)I
+ */
+JNIEXPORT jint JNICALL Java_org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider_pollReadNative
+ (JNIEnv *, jobject, jint, jint);
+
/*
* Class: org_scalasbt_ipcsocket_JNIUnixDomainSocketLibraryProvider
* Method: maxSocketLength
=====================================
jni/org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider.c
=====================================
@@ -37,6 +37,7 @@
static int createSecurityWithDacl(PSECURITY_ATTRIBUTES pSA, DWORD accessMask,
BOOL logon);
+static void freeSecurityWithDacl(PSECURITY_ATTRIBUTES pSA);
BOOL WINAPI CancelIoEx(_In_ HANDLE hFile, _In_opt_ LPOVERLAPPED lpOverlapped);
@@ -65,8 +66,7 @@ Java_org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider_CreateNamedPipeNati
THROW_IO("Couldn't create named pipe for %s (%s)",
(*env)->GetStringUTFChars(env, lpName, 0), buf);
}
- if (pSA)
- HeapFree(GetProcessHeap(), 0, pSA);
+ freeSecurityWithDacl(pSA);
return handle;
} else {
char buf[512];
@@ -119,6 +119,21 @@ Java_org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider_DisconnectNamedPipe
return DisconnectNamedPipe((HANDLE)handlePointer);
}
+jlong JNICALL
+Java_org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider_PeekNamedPipeNative(
+ UNUSED JNIEnv *env, UNUSED jobject object, jlong handlePointer) {
+ DWORD n = 0;
+ BOOL immediate = PeekNamedPipe((HANDLE)handlePointer, NULL, 0, NULL, &n, NULL);
+ if (!immediate) {
+ if (GetLastError() != ERROR_IO_PENDING) {
+ char buf[256];
+ FILL_ERROR("PeekNamedPipe() failed: %s (error code %ld)", buf);
+ THROW_IO(NULL, buf);
+ }
+ }
+ return (jlong) n;
+}
+
jint JNICALL
Java_org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider_readNative(
JNIEnv *env, UNUSED jobject object, jlong waitable, jlong hFile,
@@ -344,7 +359,8 @@ Java_org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider_getErrorMessage(
static int createSecurityWithDacl(PSECURITY_ATTRIBUTES pSA, DWORD accessMask,
BOOL logon) {
- int result = 0;
+ int result = 1;
+ PACL pAcl = NULL;
PSECURITY_DESCRIPTOR pSD = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
SECURITY_DESCRIPTOR_MIN_LENGTH);
if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) {
@@ -356,7 +372,6 @@ static int createSecurityWithDacl(PSECURITY_ATTRIBUTES pSA, DWORD accessMask,
if (DEBUG)
wprintf(L"Failed to initialize security descriptor %d %s\n",
GetLastError(), buf);
- result = 1;
goto psdfail;
}
GetLastError();
@@ -369,10 +384,9 @@ static int createSecurityWithDacl(PSECURITY_ATTRIBUTES pSA, DWORD accessMask,
PTOKEN_OWNER owner = NULL;
if (logon) {
GetTokenInformation(phToken, TokenGroups, NULL, 0, &tokenInformationLength);
- groups =
- (PTOKEN_GROUPS)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
- tokenInformationLength * sizeof(TOKEN_GROUPS));
- GetTokenInformation(phToken, TokenOwner, groups, 0,
+ groups = (PTOKEN_GROUPS)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
+ tokenInformationLength);
+ GetTokenInformation(phToken, TokenGroups, groups, tokenInformationLength,
&tokenInformationLength);
GetLastError();
for (DWORD i = 0; i < groups->GroupCount; ++i) {
@@ -384,9 +398,8 @@ static int createSecurityWithDacl(PSECURITY_ATTRIBUTES pSA, DWORD accessMask,
}
} else {
GetTokenInformation(phToken, TokenOwner, NULL, 0, &tokenInformationLength);
- owner =
- (PTOKEN_OWNER)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
- tokenInformationLength * sizeof(TOKEN_OWNER));
+ owner = (PTOKEN_OWNER)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
+ tokenInformationLength);
GetTokenInformation(phToken, TokenOwner, owner, tokenInformationLength,
&tokenInformationLength);
psid = owner->Owner;
@@ -397,7 +410,7 @@ static int createSecurityWithDacl(PSECURITY_ATTRIBUTES pSA, DWORD accessMask,
DWORD cbAcl = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psid);
cbAcl = (cbAcl + (sizeof(DWORD) - 1)) & 0xfffffffc;
- PACL pAcl = HeapAlloc(GetProcessHeap(), 0, cbAcl);
+ pAcl = HeapAlloc(GetProcessHeap(), 0, cbAcl);
if (!InitializeAcl(pAcl, cbAcl, ACL_REVISION)) {
wchar_t buf[256];
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
@@ -406,7 +419,6 @@ static int createSecurityWithDacl(PSECURITY_ATTRIBUTES pSA, DWORD accessMask,
(sizeof(buf) / sizeof(wchar_t)), NULL);
if (DEBUG)
wprintf(L"Failed to initialize acl %d %s\n", GetLastError(), buf);
- result = 1;
goto exit;
}
if (!AddAccessAllowedAce(pAcl, ACL_REVISION, accessMask, psid)) {
@@ -417,7 +429,6 @@ static int createSecurityWithDacl(PSECURITY_ATTRIBUTES pSA, DWORD accessMask,
(sizeof(buf) / sizeof(wchar_t)), NULL);
if (DEBUG)
wprintf(L"Failed to add access allowed ace %d %s\n", GetLastError(), buf);
- result = 1;
goto exit;
}
if (!SetSecurityDescriptorDacl(pSD, TRUE, pAcl, FALSE)) {
@@ -429,18 +440,18 @@ static int createSecurityWithDacl(PSECURITY_ATTRIBUTES pSA, DWORD accessMask,
if (DEBUG)
wprintf(L"Failed to set security despcriptor %d %s\n", GetLastError(),
buf);
- result = 1;
- pSA->nLength = 0;
- pSA->lpSecurityDescriptor = NULL;
- pSA->bInheritHandle = FALSE;
- } else {
- pSA->nLength = SECURITY_DESCRIPTOR_SIZE;
- pSA->lpSecurityDescriptor = pSD;
- pSA->bInheritHandle = FALSE;
+ goto exit;
}
+ // The descriptor references the ACL, so freeSecurityWithDacl frees both
+ // after the pipe is created.
+ pSA->nLength = SECURITY_DESCRIPTOR_SIZE;
+ pSA->lpSecurityDescriptor = pSD;
+ pSA->bInheritHandle = FALSE;
+ result = 0;
exit:
- HeapFree(GetProcessHeap(), 0, pAcl);
+ if (result)
+ HeapFree(GetProcessHeap(), 0, pAcl);
psidfail:
if (groups)
HeapFree(GetProcessHeap(), 0, groups);
@@ -448,7 +459,24 @@ psidfail:
HeapFree(GetProcessHeap(), 0, owner);
CloseHandle(phToken);
psdfail:
- HeapFree(GetProcessHeap(), 0, pSD);
+ if (result)
+ HeapFree(GetProcessHeap(), 0, pSD);
return result;
}
+
+static void freeSecurityWithDacl(PSECURITY_ATTRIBUTES pSA) {
+ if (!pSA)
+ return;
+ PSECURITY_DESCRIPTOR pSD = pSA->lpSecurityDescriptor;
+ if (pSD) {
+ BOOL present = FALSE;
+ BOOL defaulted = FALSE;
+ PACL pAcl = NULL;
+ if (GetSecurityDescriptorDacl(pSD, &present, &pAcl, &defaulted) &&
+ present && pAcl)
+ HeapFree(GetProcessHeap(), 0, pAcl);
+ HeapFree(GetProcessHeap(), 0, pSD);
+ }
+ HeapFree(GetProcessHeap(), 0, pSA);
+}
=====================================
jni/org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider.h
=====================================
@@ -127,6 +127,14 @@ JNIEXPORT void JNICALL Java_org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvi
JNIEXPORT jstring JNICALL Java_org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider_getErrorMessage
(JNIEnv *, jobject, jint);
+/*
+ * Class: org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider
+ * Method: PeekNamedPipeNative
+ * Signature: (J)J
+ */
+JNIEXPORT jlong JNICALL Java_org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider_PeekNamedPipeNative
+ (JNIEnv *, jobject, jlong);
+
/*
* Class: org_scalasbt_ipcsocket_JNIWin32NamedPipeLibraryProvider
* Method: ERROR_IO_PENDING
=====================================
jni/org_scalasbt_ipcsocket_UnixDomainSocketLibrary.h
=====================================
@@ -17,6 +17,8 @@ extern "C" {
#define org_scalasbt_ipcsocket_UnixDomainSocketLibrary_SHUT_RD 0L
#undef org_scalasbt_ipcsocket_UnixDomainSocketLibrary_SHUT_WR
#define org_scalasbt_ipcsocket_UnixDomainSocketLibrary_SHUT_WR 1L
+#undef org_scalasbt_ipcsocket_UnixDomainSocketLibrary_POLL_IN
+#define org_scalasbt_ipcsocket_UnixDomainSocketLibrary_POLL_IN 1L
/*
* Class: org_scalasbt_ipcsocket_UnixDomainSocketLibrary
* Method: socket
@@ -89,6 +91,14 @@ JNIEXPORT jint JNICALL Java_org_scalasbt_ipcsocket_UnixDomainSocketLibrary_close
JNIEXPORT jint JNICALL Java_org_scalasbt_ipcsocket_UnixDomainSocketLibrary_shutdown
(JNIEnv *, jclass, jint, jint);
+/*
+ * Class: org_scalasbt_ipcsocket_UnixDomainSocketLibrary
+ * Method: poll
+ * Signature: (Lorg/scalasbt/ipcsocket/UnixDomainSocketLibrary/PollfdUn;II)I
+ */
+JNIEXPORT jint JNICALL Java_org_scalasbt_ipcsocket_UnixDomainSocketLibrary_poll
+ (JNIEnv *, jclass, jobject, jint, jint);
+
#ifdef __cplusplus
}
#endif
=====================================
src/main/java/org/scalasbt/ipcsocket/JNAWin32NamedPipeLibraryProvider.java
=====================================
@@ -103,6 +103,20 @@ class JNAWin32NamedPipeLibraryProvider implements Win32NamedPipeLibraryProvider
return delegate.DisconnectNamedPipe(pipe);
}
+ @Override
+ public long PeekNamedPipe(Handle hFile) throws IOException {
+ HANDLE handle = getHandle(hFile);
+ IntByReference n = new IntByReference();
+ boolean immediate = delegate.PeekNamedPipe(handle, null, 0, null, n, null);
+ if (!immediate) {
+ int lastError = delegate.GetLastError();
+ if (lastError != WinError.ERROR_IO_PENDING) {
+ throw new IOException("ReadFile() failed: " + lastError);
+ }
+ }
+ return n.getValue();
+ }
+
@Override
public int read(
Handle waitable,
=====================================
src/main/java/org/scalasbt/ipcsocket/JNIUnixDomainSocketLibraryProvider.java
=====================================
@@ -44,6 +44,15 @@ class JNIUnixDomainSocketLibraryProvider implements UnixDomainSocketLibraryProvi
return returnOrThrow(shutdownNative(fd, how), 0);
}
+ public int available(int fd) throws NativeErrorException {
+ int result = availableNative(fd);
+ if (result < 0) {
+ return returnOrThrow(pollReadNative(fd, 0), 0);
+ } else {
+ return returnOrThrow(result, 0);
+ }
+ }
+
private int returnOrThrow(int result, int threshold) throws NativeErrorException {
if (result < threshold) {
final String message = "Error " + (-result) + ": " + errString(-result);
@@ -70,6 +79,10 @@ class JNIUnixDomainSocketLibraryProvider implements UnixDomainSocketLibraryProvi
native int shutdownNative(int fd, int how);
+ native int availableNative(int fd);
+
+ native int pollReadNative(int fd, int timeout);
+
public native int maxSocketLength();
native String errString(int error);
=====================================
src/main/java/org/scalasbt/ipcsocket/JNIWin32NamedPipeLibraryProvider.java
=====================================
@@ -177,6 +177,13 @@ class JNIWin32NamedPipeLibraryProvider implements Win32NamedPipeLibraryProvider
native String getErrorMessage(int errorCode);
+ @Override
+ public long PeekNamedPipe(Handle handle) {
+ return PeekNamedPipeNative(getHandlePointer(handle));
+ }
+
+ native long PeekNamedPipeNative(long handle);
+
// Constants:
@Override
public native int ERROR_IO_PENDING();
=====================================
src/main/java/org/scalasbt/ipcsocket/UnixDomainSocket.java
=====================================
@@ -42,6 +42,7 @@ public class UnixDomainSocket extends Socket {
private final String path;
private static final int SHUT_RD = 0;
private static final int SHUT_WR = 1;
+ private static final int EINTR = 4; // the same on Linux and macOS
/** Creates a Unix domain socket backed by a file path. */
public UnixDomainSocket(String path, boolean useJNI) throws IOException {
@@ -119,6 +120,17 @@ public class UnixDomainSocket extends Socket {
}
private class UnixDomainSocketInputStream extends InputStream {
+ public int available() throws IOException {
+ int socketFd = fd.acquire();
+ try {
+ return provider.available(socketFd);
+ } catch (final NativeErrorException e) {
+ throw new IOException(e.getMessage(), e);
+ } finally {
+ fd.release();
+ }
+ }
+
public int read() throws IOException {
byte[] buf = new byte[1];
int result;
@@ -135,17 +147,20 @@ public class UnixDomainSocket extends Socket {
if (len == 0) {
return 0;
}
- int result = doRead(b, off, len);
- if (result == 0) {
- try {
- provider.close(fd.acquire());
- } catch (final NativeErrorException e) {
- throw new IOException(
- "Error closing " + fd.acquire() + (path == null ? "" : " for " + path));
+ int socketFd = fd.acquire();
+ try {
+ int result = doRead(b, off, len);
+ if (result == 0) {
+ // Close through fd, not the provider: fd then knows it is closed, and a later
+ // close() won't close the same number again (by then it may belong to another file).
+ // We hold a reference, so the close happens when the release below drops it.
+ fd.close();
+ result = -1;
}
- result = -1;
+ return result;
+ } finally {
+ fd.release();
}
- return result;
}
private int doRead(byte[] buf, int offset, int len) throws IOException {
@@ -182,16 +197,15 @@ public class UnixDomainSocket extends Socket {
if (fdToWrite == -1) {
return;
}
- int ret = provider.write(fdToWrite, b, off, len);
- if (ret != len) {
- // This shouldn't happen with standard blocking Unix domain sockets.
- throw new IOException(
- "Could not write "
- + len
- + " bytes as requested "
- + "(wrote "
- + ret
- + " bytes instead)");
+ // A blocking write may still be short, or fail with EINTR, if a signal
+ // arrives during it; write the rest rather than fail the stream.
+ int written = 0;
+ while (written < len) {
+ try {
+ written += provider.write(fdToWrite, b, off + written, len - written);
+ } catch (NativeErrorException e) {
+ if (e.returnCode() != EINTR) throw e;
+ }
}
} catch (NativeErrorException e) {
throw new IOException(e);
=====================================
src/main/java/org/scalasbt/ipcsocket/UnixDomainSocketLibrary.java
=====================================
@@ -18,7 +18,9 @@ limitations under the License.
package org.scalasbt.ipcsocket;
import com.sun.jna.LastErrorException;
+import com.sun.jna.Library;
import com.sun.jna.Native;
+import com.sun.jna.NativeLong;
import com.sun.jna.Platform;
import com.sun.jna.Structure;
import com.sun.jna.Union;
@@ -46,6 +48,11 @@ public class UnixDomainSocketLibrary {
public static final int SHUT_RD = 0;
public static final int SHUT_WR = 1;
+ public static final int POLL_IN = 1;
+
+ public static final NativeLong FIONREAD = new NativeLong(0x4004667FL);
+ public static final NativeLong FIONREAD_LINUX = new NativeLong(0x541BL);
+
// Utility class, do not instantiate.
private UnixDomainSocketLibrary() {}
@@ -125,6 +132,23 @@ public class UnixDomainSocketLibrary {
}
}
+ public static class PollfdUn extends Structure implements Structure.ByReference {
+ public int fd;
+ public short events;
+ public short revents;
+
+ public PollfdUn(int fd, short events, short revents) {
+ this.fd = fd;
+ this.events = events;
+ this.revents = revents;
+ allocateMemory();
+ }
+
+ protected List getFieldOrder() {
+ return Arrays.asList(new String[] {"fd", "events", "revents"});
+ }
+ }
+
static {
Native.register(Platform.C_LIBRARY_NAME);
}
@@ -149,6 +173,22 @@ public class UnixDomainSocketLibrary {
public static native int close(int fd) throws LastErrorException;
public static native int shutdown(int fd, int how) throws LastErrorException;
+
+ /**
+ * ioctl is variadic, and on macOS arm64 variadic arguments are passed differently from regular
+ * ones. Direct mapping cannot express that, so ioctl goes through a varargs interface method.
+ */
+ private interface Variadic extends Library {
+ Variadic INSTANCE = Native.load(Platform.C_LIBRARY_NAME, Variadic.class);
+
+ int ioctl(int fd, NativeLong request, Object... args) throws LastErrorException;
+ }
+
+ public static int ioctl(int fd, NativeLong param, IntByReference len) throws LastErrorException {
+ return Variadic.INSTANCE.ioctl(fd, param, len);
+ }
+
+ public static native int poll(PollfdUn fd, int nfds, int timeout) throws LastErrorException;
}
class JNAUnixDomainSocketLibraryProvider implements UnixDomainSocketLibraryProvider {
@@ -218,6 +258,35 @@ class JNAUnixDomainSocketLibraryProvider implements UnixDomainSocketLibraryProvi
}
}
+ @Override
+ public int available(int fd) throws NativeErrorException {
+ try {
+ final IntByReference len = new IntByReference();
+ NativeLong op;
+ if (Platform.isLinux()) {
+ op = UnixDomainSocketLibrary.FIONREAD_LINUX;
+ } else {
+ op = UnixDomainSocketLibrary.FIONREAD;
+ }
+ UnixDomainSocketLibrary.ioctl(fd, op, len);
+ return len.getValue();
+ } catch (final LastErrorException e) {
+ try {
+ UnixDomainSocketLibrary.PollfdUn pollfd =
+ new UnixDomainSocketLibrary.PollfdUn(
+ fd, (short) UnixDomainSocketLibrary.POLL_IN, (short) 0);
+ UnixDomainSocketLibrary.poll(pollfd, 1, 0);
+ if ((((int) pollfd.revents) & UnixDomainSocketLibrary.POLL_IN) != 0) {
+ return 1;
+ } else {
+ return 0;
+ }
+ } catch (final LastErrorException e2) {
+ throw new NativeErrorException(e2.getErrorCode(), e2.getMessage());
+ }
+ }
+ }
+
@Override
public int read(int fd, byte[] buffer, int offset, int len) throws NativeErrorException {
try {
=====================================
src/main/java/org/scalasbt/ipcsocket/UnixDomainSocketLibraryProvider.java
=====================================
@@ -19,6 +19,8 @@ public interface UnixDomainSocketLibraryProvider {
int shutdown(int fd, int how) throws NativeErrorException;
+ int available(int fd) throws NativeErrorException;
+
int maxSocketLength();
static UnixDomainSocketLibraryProvider get(boolean useJNI) {
=====================================
src/main/java/org/scalasbt/ipcsocket/Win32NamedPipeLibrary.java
=====================================
@@ -97,5 +97,13 @@ public interface Win32NamedPipeLibrary extends Library, WinNT {
boolean FlushFileBuffers(HANDLE hObject);
+ boolean PeekNamedPipe(
+ HANDLE hFile,
+ Memory lpBuffer,
+ int nBufferSize,
+ IntByReference lpBytesRead,
+ IntByReference lpTotalBytesAvail,
+ IntByReference lpBytesLeftThisMessage);
+
int GetLastError();
}
=====================================
src/main/java/org/scalasbt/ipcsocket/Win32NamedPipeLibraryProvider.java
=====================================
@@ -49,6 +49,8 @@ interface Win32NamedPipeLibraryProvider {
boolean FlushFileBuffers(Handle handle);
+ long PeekNamedPipe(Handle handle) throws IOException;
+
// Constants:
int ERROR_IO_PENDING();
=====================================
src/main/java/org/scalasbt/ipcsocket/Win32NamedPipeSocket.java
=====================================
@@ -121,6 +121,11 @@ public class Win32NamedPipeSocket extends Socket {
this.handle = handle;
}
+ @Override
+ public int available() throws IOException {
+ return (int) provider.PeekNamedPipe(this.handle);
+ }
+
@Override
public int read() throws IOException {
int result;
=====================================
src/main/java/org/scalasbt/ipcsocket/Win32SecurityLibrary.java
=====================================
@@ -18,11 +18,26 @@ import com.sun.jna.platform.win32.Kernel32Util;
import com.sun.jna.platform.win32.W32Errors;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.Native;
+import com.sun.jna.Structure;
public class Win32SecurityLibrary {
private static final long SE_GROUP_LOGON_ID = 0xC0000000L;
+ /**
+ * The security descriptor references the ACL by address, and the SID lives in the token
+ * information buffer. Both are JNA memory, freed by the GC once unreachable.
+ */
+ private static class SecurityAttributesWithDacl extends SECURITY_ATTRIBUTES {
+ private final ACL acl;
+ private final Structure tokenInformation;
+
+ SecurityAttributesWithDacl(ACL acl, Structure tokenInformation) {
+ this.acl = acl;
+ this.tokenInformation = tokenInformation;
+ }
+ }
+
public static SECURITY_ATTRIBUTES createSecurityWithLogonDacl(int accessMask) {
return createSecurityWithDacl(accessMask, Win32SecurityLevel.LOGON_DACL);
}
@@ -36,8 +51,8 @@ public class Win32SecurityLibrary {
ACL pAcl;
int cbAcl = 0;
PSIDByReference psid = new PSIDByReference();
- if (securityLevel == Win32SecurityLevel.LOGON_DACL) getLogonSID(psid);
- else getOwnerSID(psid);
+ Structure tokenInformation =
+ securityLevel == Win32SecurityLevel.LOGON_DACL ? logonSID(psid) : ownerSID(psid);
int sidLength = Advapi32.INSTANCE.GetLengthSid(psid.getValue());
cbAcl = Native.getNativeSize(ACL.class, null);
cbAcl += Native.getNativeSize(ACCESS_ALLOWED_ACE.class, null);
@@ -51,7 +66,7 @@ public class Win32SecurityLibrary {
Advapi32.INSTANCE.SetSecurityDescriptorDacl(sd, true, pAcl, false);
Native.getLastError();
- SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
+ SECURITY_ATTRIBUTES sa = new SecurityAttributesWithDacl(pAcl, tokenInformation);
sa.dwLength = new DWORD(sd.size());
sa.lpSecurityDescriptor = sd.getPointer();
sa.bInheritHandle = false;
@@ -60,6 +75,11 @@ public class Win32SecurityLibrary {
}
public static void getOwnerSID(PSIDByReference psid) {
+ ownerSID(psid);
+ }
+
+ /** Sets psid to the owner SID, which lives in the returned buffer. */
+ private static WinNT.TOKEN_OWNER ownerSID(PSIDByReference psid) {
HANDLEByReference phToken = new HANDLEByReference();
try {
Advapi32.INSTANCE.OpenProcessToken(
@@ -81,12 +101,18 @@ public class Win32SecurityLibrary {
tokenInformationLength);
Native.getLastError();
psid.setValue(owner.Owner);
+ return owner;
} finally {
Kernel32Util.closeHandleRef(phToken);
}
}
public static void getLogonSID(PSIDByReference psid) {
+ logonSID(psid);
+ }
+
+ /** Sets psid to the logon SID, which lives in the returned buffer. */
+ private static WinNT.TOKEN_GROUPS logonSID(PSIDByReference psid) {
HANDLEByReference phToken = new HANDLEByReference();
try {
Advapi32.INSTANCE.OpenProcessToken(
@@ -111,7 +137,7 @@ public class Win32SecurityLibrary {
for (SID_AND_ATTRIBUTES sidAndAttribute : groups.getGroups()) {
if ((sidAndAttribute.Attributes & SE_GROUP_LOGON_ID) == SE_GROUP_LOGON_ID) {
psid.setValue(sidAndAttribute.Sid);
- return;
+ return groups;
}
}
throw new RuntimeException("LogonSID was not found.");
=====================================
src/test/java-jdk11/org/scalasbt/ipcsocket/StreamUnderLoadTest.java
=====================================
@@ -0,0 +1,102 @@
+package org.scalasbt.ipcsocket;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import jdk.jfr.Configuration;
+import jdk.jfr.Recording;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ * Streams data through a socket while the JVM is busy with safepoints: a JFR recording, a thread
+ * spawning processes, and a busy thread per core. A read or write that succeeds must not be
+ * reported as failing: errno can hold a stale value from whatever ran after the syscall (on macOS,
+ * a JNI call that blocks for a safepoint leaves psynch bits such as 260 in it).
+ */
+public class StreamUnderLoadTest extends BaseSocketSetup {
+ @Test
+ public void streamUnderLoad() throws Exception {
+ if (isWin) return;
+ try (Recording recording = new Recording(Configuration.getConfiguration("profile"))) {
+ recording.start();
+ streamThroughSocket();
+ }
+ }
+
+ private void streamThroughSocket() throws IOException, InterruptedException {
+ withSocket(
+ sock -> {
+ ServerSocket serverSocket = newServerSocket(sock);
+ AtomicBoolean done = new AtomicBoolean(false);
+ Thread spawner =
+ new Thread(
+ () -> {
+ while (!done.get()) {
+ try {
+ new ProcessBuilder("true").start().waitFor();
+ } catch (IOException | InterruptedException e) {
+ return;
+ }
+ }
+ });
+ spawner.setDaemon(true);
+ spawner.start();
+ // busy threads make safepoints slower to reach, so JNI calls block for longer
+ for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) {
+ Thread burner =
+ new Thread(
+ () -> {
+ while (!done.get()) Thread.onSpinWait();
+ });
+ burner.setDaemon(true);
+ burner.start();
+ }
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+ CompletableFuture<Long> written =
+ CompletableFuture.supplyAsync(
+ () -> {
+ try (Socket server = serverSocket.accept()) {
+ OutputStream out = server.getOutputStream();
+ byte[] chunk = new byte[64 * 1024];
+ long n = 0;
+ while (System.nanoTime() < deadline) {
+ out.write(chunk);
+ n += chunk.length;
+ }
+ return n;
+ } catch (IOException e) {
+ throw new RuntimeException("write failed", e);
+ }
+ });
+ long read = 0;
+ // reading to EOF closes the socket, so it is not closed again here
+ Socket client = newClientSocket(sock);
+ try {
+ InputStream in = client.getInputStream();
+ byte[] buf = new byte[4096];
+ int r;
+ while ((r = in.read(buf)) >= 0) {
+ // a slow reader keeps the writer blocked, as a client printing to a terminal does
+ if ((read & 0xFFFFF) + r > 0xFFFFF) Thread.sleep(50);
+ read += r;
+ }
+ } finally {
+ done.set(true);
+ serverSocket.close();
+ }
+ long expected;
+ try {
+ expected = written.get(30, TimeUnit.SECONDS);
+ } catch (Exception e) {
+ throw new AssertionError("writer failed", e);
+ }
+ assertEquals("bytes read", expected, read);
+ });
+ }
+}
=====================================
src/test/java-jdk11/org/scalasbt/ipcsocket/StreamUnderLoadTestJNI.java
=====================================
@@ -0,0 +1,8 @@
+package org.scalasbt.ipcsocket;
+
+public class StreamUnderLoadTestJNI extends StreamUnderLoadTest {
+ @Override
+ boolean useJNI() {
+ return true;
+ }
+}
=====================================
src/test/java/org/scalasbt/ipcsocket/AvailableTest.java
=====================================
@@ -0,0 +1,37 @@
+package org.scalasbt.ipcsocket;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assume.assumeFalse;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+import org.junit.Test;
+
+public class AvailableTest extends BaseSocketSetup {
+ /**
+ * available() calls ioctl(FIONREAD), which is variadic. On macOS arm64, called like a regular
+ * function, ioctl wrote the count to a random address and available() returned 0.
+ */
+ @Test
+ public void availableCountsPendingBytes() throws IOException, InterruptedException {
+ assumeFalse(isWin);
+ withSocket(
+ sock -> {
+ try (ServerSocket server = newServerSocket(sock);
+ Socket client = newClientSocket(sock);
+ Socket accepted = server.accept()) {
+ OutputStream out = accepted.getOutputStream();
+ out.write(new byte[] {1, 2, 3});
+ out.flush();
+
+ InputStream in = client.getInputStream();
+ long deadline = System.currentTimeMillis() + 5000;
+ while (in.available() == 0 && System.currentTimeMillis() < deadline) Thread.sleep(10);
+ for (int i = 0; i < 1000; i++) assertEquals(3, in.available());
+ }
+ });
+ }
+}
=====================================
src/test/java/org/scalasbt/ipcsocket/AvailableTestJNI.java
=====================================
@@ -0,0 +1,8 @@
+package org.scalasbt.ipcsocket;
+
+public class AvailableTestJNI extends AvailableTest {
+ @Override
+ boolean useJNI() {
+ return true;
+ }
+}
=====================================
src/test/java/org/scalasbt/ipcsocket/CloseAfterEofTest.java
=====================================
@@ -0,0 +1,43 @@
+package org.scalasbt.ipcsocket;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ * Reading to EOF closes the socket's file descriptor. Closing the socket afterwards must not close
+ * that descriptor number again: by then the OS may have given the number to another file.
+ */
+public class CloseAfterEofTest extends BaseSocketSetup {
+ @Test
+ public void closeAfterEofLeavesOtherFilesAlone() throws IOException, InterruptedException {
+ if (isWin) return;
+ withSocket(
+ sock -> {
+ ServerSocket serverSocket = newServerSocket(sock);
+ Path file = Files.createTempFile("ipcsocket", ".txt");
+ try {
+ Files.write(file, "hello".getBytes());
+ Socket client = newClientSocket(sock);
+ serverSocket.accept().close();
+ InputStream in = client.getInputStream();
+ assertEquals("read at EOF", -1, in.read(new byte[16], 0, 16));
+ // POSIX gives a new file the lowest free number: the one the socket just released
+ try (FileInputStream other = new FileInputStream(file.toFile())) {
+ client.close();
+ byte[] buf = new byte[16];
+ assertEquals("the other file is still readable", 5, other.read(buf));
+ }
+ } finally {
+ serverSocket.close();
+ Files.deleteIfExists(file);
+ }
+ });
+ }
+}
=====================================
src/test/java/org/scalasbt/ipcsocket/CloseAfterEofTestJNI.java
=====================================
@@ -0,0 +1,8 @@
+package org.scalasbt.ipcsocket;
+
+public class CloseAfterEofTestJNI extends CloseAfterEofTest {
+ @Override
+ boolean useJNI() {
+ return true;
+ }
+}
=====================================
src/test/java/org/scalasbt/ipcsocket/Win32SecurityLibraryTest.java
=====================================
@@ -0,0 +1,158 @@
+package org.scalasbt.ipcsocket;
+
+import static org.junit.Assert.*;
+import static org.junit.Assume.assumeTrue;
+
+import com.sun.jna.Library;
+import com.sun.jna.Memory;
+import com.sun.jna.Native;
+import com.sun.jna.Pointer;
+import com.sun.jna.platform.win32.AccCtrl;
+import com.sun.jna.platform.win32.Advapi32;
+import com.sun.jna.platform.win32.Kernel32;
+import com.sun.jna.platform.win32.WinBase.SECURITY_ATTRIBUTES;
+import com.sun.jna.platform.win32.WinNT;
+import com.sun.jna.platform.win32.WinNT.HANDLE;
+import com.sun.jna.ptr.IntByReference;
+import com.sun.jna.ptr.PointerByReference;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.Test;
+
+public class Win32SecurityLibraryTest {
+ interface SecurityApi extends Library {
+ SecurityApi INSTANCE = Native.load("advapi32", SecurityApi.class);
+
+ boolean GetSecurityDescriptorDacl(
+ Pointer sd, IntByReference present, PointerByReference dacl, IntByReference defaulted);
+
+ boolean IsValidAcl(Pointer acl);
+ }
+
+ static boolean isWin() {
+ return System.getProperty("os.name", "").toLowerCase().startsWith("win");
+ }
+
+ /**
+ * The pipe's DACL grants access to a single SID. The JNI provider used to create LOGON_DACL pipes
+ * with the default DACL, which grants access to several.
+ */
+ @Test
+ public void pipeDaclHasOneAce() throws IOException {
+ assumeTrue(isWin());
+ JNIWin32NamedPipeLibraryProvider jni = JNIWin32NamedPipeLibraryProvider.instance();
+ for (int level : new int[] {Win32SecurityLevel.OWNER_DACL, Win32SecurityLevel.LOGON_DACL}) {
+ String name = "\\\\.\\pipe\\ipcsocket-dacl-" + System.nanoTime();
+ int openMode =
+ Win32NamedPipeLibrary.FILE_FLAG_FIRST_PIPE_INSTANCE
+ | Win32NamedPipeLibrary.PIPE_ACCESS_DUPLEX;
+
+ HANDLE jna =
+ Win32NamedPipeLibrary.INSTANCE.CreateNamedPipe(
+ name + "-jna",
+ openMode,
+ 0,
+ 1,
+ 1024,
+ 1024,
+ 0,
+ Win32SecurityLibrary.createSecurityWithDacl(WinNT.FILE_GENERIC_READ, level));
+ assertNotEquals(
+ "JNA CreateNamedPipe failed with error " + Native.getLastError(),
+ Win32NamedPipeLibrary.INVALID_HANDLE_VALUE,
+ jna);
+ try {
+ assertEquals("JNA, security level " + level, 1, aceCount(jna));
+ } finally {
+ Kernel32.INSTANCE.CloseHandle(jna);
+ }
+
+ Handle h =
+ jni.CreateNamedPipe(
+ name + "-jni", openMode, 0, 1, 1024, 1024, 0, jni.FILE_GENERIC_READ(), level);
+ try {
+ HANDLE handle =
+ new HANDLE(new Pointer(((JNIWin32NamedPipeLibraryProvider.JNIHandle) h).pointer));
+ assertEquals("JNI, security level " + level, 1, aceCount(handle));
+ } finally {
+ jni.CloseHandle(h);
+ }
+ }
+ }
+
+ static int aceCount(HANDLE pipe) {
+ PointerByReference dacl = new PointerByReference();
+ PointerByReference sd = new PointerByReference();
+ int error =
+ Advapi32.INSTANCE.GetSecurityInfo(
+ pipe,
+ AccCtrl.SE_OBJECT_TYPE.SE_KERNEL_OBJECT,
+ WinNT.DACL_SECURITY_INFORMATION,
+ null,
+ null,
+ dacl,
+ null,
+ sd);
+ assertEquals("GetSecurityInfo error", 0, error);
+ try {
+ return dacl.getValue().getShort(4) & 0xFFFF;
+ } finally {
+ Kernel32.INSTANCE.LocalFree(sd.getValue());
+ }
+ }
+
+ /** CreateNamedPipe failed with ERROR_INVALID_ACL (1336) when the GC freed the DACL. */
+ @Test
+ public void daclSurvivesGc() {
+ assumeTrue(isWin());
+ SECURITY_ATTRIBUTES sa =
+ Win32SecurityLibrary.createSecurityWithDacl(
+ WinNT.FILE_GENERIC_READ, Win32SecurityLevel.OWNER_DACL);
+
+ IntByReference present = new IntByReference();
+ PointerByReference dacl = new PointerByReference();
+ assertTrue(
+ SecurityApi.INSTANCE.GetSecurityDescriptorDacl(
+ sa.lpSecurityDescriptor, present, dacl, new IntByReference()));
+ assertEquals(1, present.getValue());
+ Pointer acl = dacl.getValue();
+ int aclSize = acl.getShort(2) & 0xFFFF;
+
+ // Overwrite freed blocks of the ACL's size, so a freed ACL becomes invalid.
+ List<Memory> spray = new ArrayList<>();
+ for (int round = 0; round < 10; round++) {
+ System.gc();
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ for (int i = 0; i < 5000; i++) {
+ Memory m = new Memory(aclSize);
+ m.setMemory(0, aclSize, (byte) 0xFF);
+ spray.add(m);
+ }
+ }
+ assertTrue("DACL is invalid after GC", SecurityApi.INSTANCE.IsValidAcl(acl));
+
+ String name = "\\\\.\\pipe\\ipcsocket-dacl-" + System.nanoTime();
+ HANDLE h =
+ Win32NamedPipeLibrary.INSTANCE.CreateNamedPipe(
+ name,
+ Win32NamedPipeLibrary.FILE_FLAG_FIRST_PIPE_INSTANCE
+ | Win32NamedPipeLibrary.PIPE_ACCESS_DUPLEX,
+ 0,
+ 1,
+ 1024,
+ 1024,
+ 0,
+ sa);
+ int error = Native.getLastError();
+ assertNotEquals(
+ "CreateNamedPipe failed with error " + error,
+ Win32NamedPipeLibrary.INVALID_HANDLE_VALUE,
+ h);
+ Kernel32.INSTANCE.CloseHandle(h);
+ }
+}
View it on GitLab: https://salsa.debian.org/java-team/ipcsocket/-/compare/448d828ba257c9a56697a9dffe525662c1319cc0...b00e3ad5b6c5d75e894d8c68d70917b8dd843ff6
--
View it on GitLab: https://salsa.debian.org/java-team/ipcsocket/-/compare/448d828ba257c9a56697a9dffe525662c1319cc0...b00e3ad5b6c5d75e894d8c68d70917b8dd843ff6
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-java-commits/attachments/20261029/8917db79/attachment.htm>
More information about the pkg-java-commits
mailing list