undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,200 @@
/*
* Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @library ../ /test/lib
*
* @run testng/othervm/native --enable-native-access=ALL-UNNAMED TestCritical
*/
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SegmentAllocator;
import java.lang.foreign.SequenceLayout;
import java.lang.foreign.StructLayout;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.util.ArrayList;
import java.util.List;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.testng.Assert.assertEquals;
public class TestCritical extends NativeTestHelper {
static final MemoryLayout CAPTURE_STATE_LAYOUT = Linker.Option.captureStateLayout();
static final VarHandle ERRNO_HANDLE = CAPTURE_STATE_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("errno"));
static {
System.loadLibrary("Critical");
}
@Test
public void testEmpty() throws Throwable {
MethodHandle handle = downcallHandle("empty", FunctionDescriptor.ofVoid(), Linker.Option.critical(false));
handle.invokeExact();
}
@Test
public void testIdentity() throws Throwable {
MethodHandle handle = downcallHandle("identity", FunctionDescriptor.of(C_INT, C_INT), Linker.Option.critical(false));
int result = (int) handle.invokeExact(42);
assertEquals(result, 42);
}
@Test
public void testWithReturnBuffer() throws Throwable {
StructLayout bigLayout = MemoryLayout.structLayout(
C_LONG_LONG.withName("x"),
C_LONG_LONG.withName("y"));
MethodHandle handle = downcallHandle("with_return_buffer", FunctionDescriptor.of(bigLayout), Linker.Option.critical(false));
VarHandle vhX = bigLayout.varHandle(MemoryLayout.PathElement.groupElement("x"));
VarHandle vhY = bigLayout.varHandle(MemoryLayout.PathElement.groupElement("y"));
try (Arena arena = Arena.ofConfined()) {
MemorySegment result = (MemorySegment) handle.invokeExact((SegmentAllocator) arena);
long x = (long) vhX.get(result, 0L);
assertEquals(x, 10);
long y = (long) vhY.get(result, 0L);
assertEquals(y, 11);
}
}
public record AllowHeapCase(IntFunction<MemorySegment> newArraySegment, ValueLayout elementLayout,
String fName, FunctionDescriptor fDesc, boolean readOnly, boolean captureErrno) {}
@Test(dataProvider = "allowHeapCases")
public void testAllowHeap(AllowHeapCase testCase) throws Throwable {
List<Linker.Option> options = new ArrayList<>();
options.add(Linker.Option.critical(true));
if (testCase.captureErrno()) {
options.add(Linker.Option.captureCallState("errno"));
}
MethodHandle handle = downcallHandle(testCase.fName(), testCase.fDesc(), options.toArray(Linker.Option[]::new));
int elementCount = 10;
MemorySegment heapSegment = testCase.newArraySegment().apply(elementCount);
if (testCase.readOnly()) {
heapSegment = heapSegment.asReadOnly();
}
SequenceLayout sequence = MemoryLayout.sequenceLayout(elementCount, testCase.elementLayout());
try (Arena arena = Arena.ofConfined()) {
TestValue[] tvs = genTestArgs(testCase.fDesc(), arena);
List<Object> args = Stream.of(tvs).map(TestValue::value).collect(Collectors.toCollection(ArrayList::new));
MemorySegment captureSegment = testCase.captureErrno()
? MemorySegment.ofArray(new int[((int) CAPTURE_STATE_LAYOUT.byteSize() + 3) / 4])
: null;
// inject our custom last three arguments
args.set(args.size() - 1, (int) sequence.byteSize());
TestValue sourceSegment = genTestValue(sequence, arena);
args.set(args.size() - 2, sourceSegment.value());
args.set(args.size() - 3, heapSegment);
if (testCase.captureErrno()) {
args.add(0, captureSegment);
}
if (handle.type().parameterType(0) == SegmentAllocator.class) {
args.add(0, arena);
}
Object o = handle.invokeWithArguments(args);
if (o != null) {
tvs[0].check(o);
}
// check that writes went through to array
sourceSegment.check(heapSegment);
if (testCase.captureErrno()) {
int errno = (int) ERRNO_HANDLE.get(captureSegment, 0L);
assertEquals(errno, 42);
}
}
}
@DataProvider
public Object[][] allowHeapCases() {
FunctionDescriptor voidDesc = FunctionDescriptor.ofVoid(C_POINTER, C_POINTER, C_INT);
FunctionDescriptor intDesc = voidDesc.changeReturnLayout(C_INT).insertArgumentLayouts(0, C_INT);
StructLayout L2 = MemoryLayout.structLayout(
C_LONG_LONG.withName("x"),
C_LONG_LONG.withName("y")
);
FunctionDescriptor L2Desc = voidDesc.changeReturnLayout(L2).insertArgumentLayouts(0, L2);
StructLayout L3 = MemoryLayout.structLayout(
C_LONG_LONG.withName("x"),
C_LONG_LONG.withName("y"),
C_LONG_LONG.withName("z")
);
FunctionDescriptor L3Desc = voidDesc.changeReturnLayout(L3).insertArgumentLayouts(0, L3);
FunctionDescriptor stackDesc = voidDesc.insertArgumentLayouts(0,
C_LONG_LONG, C_LONG_LONG, C_LONG_LONG, C_LONG_LONG,
C_LONG_LONG, C_LONG_LONG, C_LONG_LONG, C_LONG_LONG,
C_CHAR, C_SHORT, C_INT);
List<AllowHeapCase> cases = new ArrayList<>();
for (boolean doCapture : new boolean[]{ true, false }) {
for (HeapSegmentFactory hsf : HeapSegmentFactory.values()) {
cases.add(new AllowHeapCase(hsf.newArray, hsf.elementLayout, "test_allow_heap_void", voidDesc, false, doCapture));
cases.add(new AllowHeapCase(hsf.newArray, hsf.elementLayout, "test_allow_heap_int", intDesc, false, doCapture));
cases.add(new AllowHeapCase(hsf.newArray, hsf.elementLayout, "test_allow_heap_return_buffer", L2Desc, false, doCapture));
cases.add(new AllowHeapCase(hsf.newArray, hsf.elementLayout, "test_allow_heap_imr", L3Desc, false, doCapture));
cases.add(new AllowHeapCase(hsf.newArray, hsf.elementLayout, "test_allow_heap_void_stack", stackDesc, false, doCapture));
// readOnly
cases.add(new AllowHeapCase(hsf.newArray, hsf.elementLayout, "test_allow_heap_void", voidDesc, true, doCapture));
}
}
return cases.stream().map(e -> new Object[]{ e }).toArray(Object[][]::new);
}
private enum HeapSegmentFactory {
BYTE(i -> MemorySegment.ofArray(new byte[i]), ValueLayout.JAVA_BYTE),
SHORT(i -> MemorySegment.ofArray(new short[i]), ValueLayout.JAVA_SHORT),
CHAR(i -> MemorySegment.ofArray(new char[i]), ValueLayout.JAVA_CHAR),
INT(i -> MemorySegment.ofArray(new int[i]), ValueLayout.JAVA_INT),
LONG(i -> MemorySegment.ofArray(new long[i]), ValueLayout.JAVA_LONG),
FLOAT(i -> MemorySegment.ofArray(new float[i]), ValueLayout.JAVA_FLOAT),
DOUBLE(i -> MemorySegment.ofArray(new double[i]), ValueLayout.JAVA_DOUBLE);
IntFunction<MemorySegment> newArray;
ValueLayout elementLayout;
private HeapSegmentFactory(IntFunction<MemorySegment> newArray, ValueLayout elementLayout) {
this.newArray = newArray;
this.elementLayout = elementLayout;
}
}
}

View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @library ../ /test/lib
* @requires jdk.foreign.linker != "FALLBACK"
* @run testng/othervm/native --enable-native-access=ALL-UNNAMED TestCriticalUpcall
*/
import org.testng.annotations.Test;
import java.io.IOException;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.invoke.MethodHandle;
import java.util.List;
import static org.testng.Assert.fail;
public class TestCriticalUpcall extends UpcallTestHelper {
@Test
public void testUpcallFailure() throws IOException, InterruptedException {
// test to see if we catch a trivial downcall doing an upcall
runInNewProcess(Runner.class, true, List.of("-XX:-CreateCoredumpOnCrash"), List.of())
.shouldNotHaveExitValue(0)
.stdoutShouldContain("wrong thread state for upcall");
}
public static class Runner extends NativeTestHelper {
public static void main(String[] args) throws Throwable {
System.loadLibrary("Critical");
MethodHandle mh = downcallHandle("do_upcall", FunctionDescriptor.ofVoid(C_POINTER), Linker.Option.critical(false));
MemorySegment stub = upcallStub(Runner.class, "target", FunctionDescriptor.ofVoid());
mh.invokeExact(stub);
}
public static void target() {
fail("Should not get here");
}
}
}

View file

@ -0,0 +1,111 @@
/*
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @library ../ /test/lib
* @requires vm.debug
* @run main/othervm
* -Xms1g -Xmx1g
* -XX:+CheckUnhandledOops
* -Xlog:gc -Xlog:gc+jni=debug
* --enable-native-access=ALL-UNNAMED
* TestStressAllowHeap
*/
import java.lang.foreign.*;
import java.lang.invoke.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static jdk.test.lib.Asserts.*;
/**
* Test verifies the GCLocker::lock_critical slow path with FFM.
* This is the case where we enter a critical section with _needs_gc == true,
* and need to take a safepoint.
*
* Based on gc/TestJNICriticalStressTest
*/
public class TestStressAllowHeap {
private static final long DURATION_SECONDS = 30;
public static void main(String... args) throws Exception {
System.out.println("Running for " + DURATION_SECONDS + " secs");
int numCriticalThreads = Runtime.getRuntime().availableProcessors();
System.out.println("Starting " + numCriticalThreads + " critical threads");
for (int i = 0; i < numCriticalThreads; i += 1) {
Thread.ofPlatform().start(new CriticalWorker());
}
long durationMS = 1000L * DURATION_SECONDS;
try {
Thread.sleep(durationMS);
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(-1);
}
// hitting the problematic code path doesn't seem to be guaranteed
// and we can not guarantee it by, e.g. stalling in a critical method
// since that can lock up the VM (and our test code)
}
private static class CriticalWorker extends NativeTestHelper implements Runnable {
static {
System.loadLibrary("Critical");
}
private void doStep(MethodHandle handle, SequenceLayout sequence) throws Throwable {
try (Arena arena = Arena.ofConfined()) {
MemorySegment heapSegment = MemorySegment.ofArray(new int[(int) sequence.elementCount()]);
TestValue sourceSegment = genTestValue(sequence, arena);
handle.invokeExact(heapSegment, (MemorySegment) sourceSegment.value(), (int) sequence.byteSize());
// check that writes went through to array
sourceSegment.check(heapSegment);
}
}
@Override
public void run() {
FunctionDescriptor fDesc = FunctionDescriptor.ofVoid(C_POINTER, C_POINTER, C_INT);
MethodHandle handle = Linker.nativeLinker().downcallHandle(
SymbolLookup.loaderLookup().find("test_allow_heap_void").get(),
fDesc,
Linker.Option.critical(true));
int elementCount = 10;
SequenceLayout sequence = MemoryLayout.sequenceLayout(elementCount, C_INT);
while (true) {
try {
doStep(handle, sequence);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
}
}
}

View file

@ -0,0 +1,102 @@
/*
* Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#include <errno.h>
#include "export.h"
EXPORT void empty() {}
EXPORT int identity(int value) {
return value;
}
// 128 bit struct returned in buffer on SysV
struct Big {
long long x;
long long y;
};
EXPORT struct Big with_return_buffer() {
struct Big b;
b.x = 10;
b.y = 11;
return b;
}
EXPORT void do_upcall(void(*f)(void)) {
f();
}
// copy bytes into heap array
EXPORT void test_allow_heap_void(unsigned char* heapArr, unsigned char* nativeArr, int numBytes) {
for (int i = 0; i < numBytes; i++) {
heapArr[i] = nativeArr[i];
}
errno = 42;
}
EXPORT int test_allow_heap_int(int a0, unsigned char* heapArr, unsigned char* nativeArr, int numBytes) {
for (int i = 0; i < numBytes; i++) {
heapArr[i] = nativeArr[i];
}
errno = 42;
return a0;
}
struct L2 {
long long x;
long long y;
};
EXPORT struct L2 test_allow_heap_return_buffer(struct L2 a0, unsigned char* heapArr, unsigned char* nativeArr, int numBytes) {
for (int i = 0; i < numBytes; i++) {
heapArr[i] = nativeArr[i];
}
errno = 42;
return a0;
}
struct L3 {
long long x;
long long y;
long long z;
};
EXPORT struct L3 test_allow_heap_imr(struct L3 a0, unsigned char* heapArr, unsigned char* nativeArr, int numBytes) {
for (int i = 0; i < numBytes; i++) {
heapArr[i] = nativeArr[i];
}
errno = 42;
return a0;
}
// copy bytes into heap array
EXPORT void test_allow_heap_void_stack(long long a0, long long a1, long long a2, long long a3, long long a4, long long a5,
long long a6, long long a7, char c0, short s0, int i0,
unsigned char* heapArr, unsigned char* nativeArr, int numBytes) {
for (int i = 0; i < numBytes; i++) {
heapArr[i] = nativeArr[i];
}
errno = 42;
}