Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions ffi/tests/api.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
#include <stdio.h>
#include <string.h>

#ifdef __linux__
#include <sys/prctl.h>
#endif

#include "api.h"

static api_buf str(const char *s) {
Expand Down Expand Up @@ -1850,6 +1854,14 @@ static int script(void) {

/* Each breaks a contract, which must abort with a message naming the function. */
static int broken(const char *which) {
#ifdef __linux__
/* Non-dumpable, the expected abort writes no core and never starts the host's crash
* handler. */
if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) != 0) {
perror("prctl");
return 1;
}
#endif
if (strcmp(which, "moved") == 0) {
api_Counter *c = api_Counter_new(str("c"), 0);
api_Label label = api_Counter_into_label(c, (api_option_Point){0});
Expand Down
12 changes: 12 additions & 0 deletions ffi/tests/api.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
#include <io.h>
#endif

#ifdef __linux__
#include <sys/prctl.h>
#endif

namespace {

// Print a returned buffer.
Expand Down Expand Up @@ -1720,6 +1724,14 @@ int lifetimes() {
// `tests/api_strict.cpp` refuses at compile time reach the object through a reference or
// pointer, whose state Clang does not track.
int broken(const char *which) {
#ifdef __linux__
// Non-dumpable, the expected abort writes no core and never starts the host's crash
// handler.
if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) != 0) {
std::perror("prctl");
return 1;
}
#endif
if (std::strcmp(which, "moved") == 0) {
api::Counter c = api::Counter::new_("c", 0);
api::Counter &same = c;
Expand Down
10 changes: 10 additions & 0 deletions ffi/tests/api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import 'dart:async';
import 'dart:convert';
import 'dart:ffi' as ffi;
import 'dart:io';
import 'dart:typed_data';

Expand Down Expand Up @@ -1312,6 +1313,15 @@ final class Thrower implements api.SeekableReader {

/// Each breaks a contract, which must fail with a message naming it.
void broken(String which) {
if (Platform.isLinux) {
// Non-dumpable, an expected abort writes no core and never starts the host's crash
// handler. PR_SET_DUMPABLE is 4.
final prctl = ffi.DynamicLibrary.process().lookupFunction<
ffi.Int Function(ffi.Int,
ffi.VarArgs<(ffi.UnsignedLong, ffi.UnsignedLong, ffi.UnsignedLong, ffi.UnsignedLong)>),
int Function(int, int, int, int, int)>('prctl');
check(prctl(4, 0, 0, 0, 0) == 0, 'prctl');
}
switch (which) {
case 'moved':
final c = api.Counter('c', 0);
Expand Down
7 changes: 7 additions & 0 deletions ffi/tests/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1417,6 +1417,13 @@ def raises(f, message):

def broken(which):
"""Each breaks a contract, which must fail with a message naming it."""
if sys.platform == "linux":
# Non-dumpable, an expected abort writes no core and never starts the host's crash
# handler. PR_SET_DUMPABLE is 4.
import ctypes

if ctypes.CDLL(None, use_errno=True).prctl(4, 0, 0, 0, 0) != 0:
raise OSError(ctypes.get_errno(), "prctl")
match which:
case "moved":
c = api.Counter.new("c", 0)
Expand Down
9 changes: 9 additions & 0 deletions ffi/tests/api.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
import Api
import BasicContainers
import Foundation
#if os(Linux)
import NoDump
#endif

// The Log callback: keeps even levels.
final class PrintLog: Log {
Expand Down Expand Up @@ -1273,6 +1276,12 @@ func lentKept() {

// Each breaks a contract, which must fail with a message naming it.
func broken(_ which: String) {
#if os(Linux)
if nodump() != 0 {
perror("prctl")
exit(1)
}
#endif
switch which {
// A lent return outliving its owner's change, which Rust checks.
case "outlived":
Expand Down
126 changes: 103 additions & 23 deletions ffi/tests/fixtures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ fn api_c() {
("zero", "api_next_hop: a NonZero is zero"),
] {
let output = Command::new(&exe).arg(case).output().unwrap();
assert!(!output.status.success(), "{case} did not abort");
failed(&output, case);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(message), "{case} printed {stderr}");
}
Expand Down Expand Up @@ -412,7 +412,7 @@ fn api_cpp() {
("outlived", OUTLIVED),
] {
let output = Command::new(&exe).arg(case).output().unwrap();
assert!(!output.status.success(), "C++{standard} {case} did not abort");
failed(&output, &format!("C++{standard} {case}"));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(message), "C++{standard} {case} printed {stderr}");
}
Expand All @@ -436,16 +436,33 @@ fn api_cpp() {
cxx(&api.link(), 17, true, &src, &exe);
}

// A C++ program whose header names another contract than its library's aborts at load.
// A C++ program whose header names another contract than its library's aborts at load,
// non-dumpable from a constructor that runs before the header's check, as `broken` is.
let mismatched = scratch().join("api").join("contract.cpp");
step::write(
&mismatched,
"#include \"api.h\"\n#undef API_CONTRACT\n#define API_CONTRACT ((uint64_t)0)\n#include \"api.hpp\"\nint main() {}\n",
r#"#ifdef __linux__
#include <cstdio>
#include <cstdlib>
#include <sys/prctl.h>
__attribute__((constructor(101))) static void nodump() {
if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) != 0) {
std::perror("prctl");
std::_Exit(1);
}
}
#endif
#include "api.h"
#undef API_CONTRACT
#define API_CONTRACT ((uint64_t)0)
#include "api.hpp"
int main() {}
"#,
);
let contract = scratch().join("api").join(format!("contract{EXE_SUFFIX}"));
cxx(&api.link(), 17, false, &mismatched, &contract);
let output = Command::new(&contract).output().unwrap();
assert!(!output.status.success(), "a mismatched contract did not abort");
failed(&output, "a mismatched contract");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("api/rt.hpp and the library are from different builds"),
Expand Down Expand Up @@ -654,7 +671,7 @@ fn api_kotlin() {
let shadow = scratch().join("api").join("kotlin-mismatched");
step::write(&shadow.join("api").join("Native.class"), &mismatched);
let output = java(&[&shadow, &classes], &[]).output().unwrap();
assert!(!output.status.success(), "a mismatched contract did not fail");
failed(&output, "a mismatched contract");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("api.kt and the library are from different builds"),
Expand Down Expand Up @@ -828,13 +845,59 @@ fn kotlin(native: &str, vm: &dyn Fn(&[&str]) -> Command) {
("stray", "MalformedInputException"),
("family", "an IPv6 address has no Rust SocketAddrV4"),
] {
let output = vm(&[case]).output().unwrap();
// Under a piped core pattern the handler still runs at a limit of 0, so the
// status reports a core though none is written.
let output = no_core(&mut vm(&[case])).output().unwrap();
assert!(!output.status.success(), "Kotlin {case} did not fail");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(message), "Kotlin {case} printed {stderr}");
}
}

/// Asserts the run of `what` failed, as a broken contract must, and on Linux, where the test
/// programs make themselves non-dumpable, without dumping core: each core costs the host a
/// write and a run of its crash handler. Elsewhere the host's own core limit decides.
fn failed(output: &Output, what: &str) {
assert!(!output.status.success(), "{what} did not fail");
#[cfg(target_os = "linux")]
assert!(
!std::os::unix::process::ExitStatusExt::core_dumped(&output.status),
"{what} dumped core"
);
}

/// `cmd` with a core-size limit of 0 on Linux, so a JVM case that aborts writes no core. The
/// JVM cannot mark itself non-dumpable as the other test programs do, since JDK 21 calls C
/// only through a preview API, so the host's crash handler still starts and logs the crash.
fn no_core(cmd: &mut Command) -> &mut Command {
#[cfg(target_os = "linux")]
{
use std::ffi::{c_int, c_ulong};
use std::os::unix::process::CommandExt;

#[repr(C)]
struct Rlimit {
cur: c_ulong,
max: c_ulong,
}
unsafe extern "C" {
fn setrlimit(resource: c_int, limit: *const Rlimit) -> c_int;
}
const RLIMIT_CORE: c_int = 4;
// SAFETY: setrlimit is async-signal-safe and touches only the child.
unsafe {
cmd.pre_exec(|| {
if setrlimit(RLIMIT_CORE, &Rlimit { cur: 0, max: 0 }) == 0 {
Ok(())
} else {
Err(std::io::Error::last_os_error())
}
});
}
}
cmd
}

/// The library `python/api.py` loads from beside itself.
const PYTHON_LIB: &str = match (cfg!(windows), cfg!(target_os = "macos")) {
(true, _) => "api.dll",
Expand Down Expand Up @@ -886,7 +949,7 @@ fn api_python() {
("reader kept", "read: a reader kept a view of its buffer past the read"),
] {
let output = python(&dir, &[case]).output().unwrap();
assert!(!output.status.success(), "Python {case} did not fail");
failed(&output, &format!("Python {case}"));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(message), "Python {case} printed {stderr}");
}
Expand All @@ -907,7 +970,7 @@ fn api_python() {
let source = format!("{}{flipped}{}", &source[..at], &source[at + 1..]);
step::write(&mismatched.join("api.py"), source);
let output = python(&mismatched, &[]).output().unwrap();
assert!(!output.status.success(), "a mismatched contract did not fail");
failed(&output, "a mismatched contract");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("api.py and the library are from different builds"),
Expand Down Expand Up @@ -996,9 +1059,20 @@ fn api_swift() {
// The test's executor preference is macOS 15's.
let exe = dir.join("api-test");
let test = manifest_dir().join("tests").join("api.swift");
// The Clang module the test and the contract program import on Linux.
let nodump = manifest_dir().join("tests").join("nodump");
let step = Step {
stamp: &step::stamp(&exe),
reads: &[&test, &module, &include, &built, &swiftmodule, &lib, &api.staticlib()],
reads: &[
&test,
&nodump,
&module,
&include,
&built,
&swiftmodule,
&lib,
&api.staticlib(),
],
writes: &[&exe],
};
step.run(
Expand Down Expand Up @@ -1034,7 +1108,7 @@ fn api_swift() {
] {
let step = Step {
stamp: &dir.join(format!("{case}.stamp")),
reads: &[&test, &module, &include, &built, &swiftmodule],
reads: &[&test, &nodump, &module, &include, &built, &swiftmodule],
writes: &[],
};
let output = step.output(
Expand All @@ -1061,7 +1135,7 @@ fn api_swift() {
("plain variant", "api_Family.Wasm: it is not on this library's target"),
] {
let output = Command::new(&exe).arg(case).output().unwrap();
assert!(!output.status.success(), "Swift {case} did not fail");
failed(&output, &format!("Swift {case}"));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(message), "Swift {case} printed {stderr}");
}
Expand All @@ -1079,11 +1153,15 @@ fn api_swift() {
let contract = dir.join("contract");
let (swift, main) = (contract.join("api.swift"), contract.join("main.swift"));
step::write(&swift, mismatched);
step::write(&main, "_ = dropped()\n");
// Non-dumpable before the check fails, as `broken` is.
step::write(
&main,
"#if os(Linux)\nimport Glibc\nimport NoDump\n\nif nodump() != 0 {\n\tperror(\"prctl\")\n\texit(1)\n}\n#endif\n_ = dropped()\n",
);
let exe = contract.join("contract");
let step = Step {
stamp: &step::stamp(&exe),
reads: &[&swift, &main, &module, &include, &built, &api.staticlib()],
reads: &[&swift, &main, &nodump, &module, &include, &built, &api.staticlib()],
writes: &[&exe],
};
step.run(
Expand All @@ -1098,7 +1176,7 @@ fn api_swift() {
.arg(&exe),
);
let output = Command::new(&exe).output().unwrap();
assert!(!output.status.success(), "a mismatched contract did not fail");
failed(&output, "a mismatched contract");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("api.swift and the library are from different builds"),
Expand Down Expand Up @@ -1160,7 +1238,7 @@ fn api_dart() {
("lent stray", "a path from Rust is not UTF-8"),
] {
let output = dart_run(&exe, &[case]).output().unwrap();
assert!(!output.status.success(), "Dart {case} did not fail");
failed(&output, &format!("Dart {case}"));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(message), "Dart {case} printed {stderr}");
}
Expand All @@ -1183,7 +1261,7 @@ fn api_dart() {
);
let exe = dart_compile("api", &contract, &package, &lib, &main);
let output = dart_run(&exe, &[]).output().unwrap();
assert!(!output.status.success(), "a mismatched contract did not fail");
failed(&output, "a mismatched contract");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("api.dart and the library are from different builds"),
Expand Down Expand Up @@ -1296,9 +1374,9 @@ fn collections_dir() -> PathBuf {
manifest_dir().join("target").join("swift-collections").join("build")
}

/// swiftc, with warnings as errors, finding the C header's module in `module` and
/// swift-collections' in [`collections_dir`], at this macOS deployment target on macOS: 13
/// is the oldest the generated `Swift.Duration` allows.
/// swiftc, with warnings as errors, finding the C header's module in `module`,
/// swift-collections' in [`collections_dir`], and `tests/nodump`'s, at this macOS deployment
/// target on macOS: 13 is the oldest the generated `Swift.Duration` allows.
fn swiftc(module: &Path, macos: u8) -> Command {
let mut cmd = Command::new("swiftc");
if cfg!(target_os = "macos") {
Expand All @@ -1311,7 +1389,9 @@ fn swiftc(module: &Path, macos: u8) -> Command {
cmd.args(["-warnings-as-errors", "-I"])
.arg(module)
.arg("-I")
.arg(collections_dir());
.arg(collections_dir())
.arg("-I")
.arg(manifest_dir().join("tests").join("nodump"));
cmd
}

Expand Down Expand Up @@ -1367,7 +1447,7 @@ fn api_go() {
("plain variant", "api_Family.Wasm: it is not on this library's target"),
] {
let output = Command::new(&exe).arg(case).output().unwrap();
assert!(!output.status.success(), "Go {case} did not fail");
failed(&output, &format!("Go {case}"));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(message), "Go {case} printed {stderr}");
}
Expand All @@ -1393,7 +1473,7 @@ fn api_go() {
let exe = dir.join(format!("contract-test{EXE_SUFFIX}"));
go_build(api, &contract, &exe);
let output = Command::new(&exe).output().unwrap();
assert!(!output.status.success(), "a mismatched contract did not fail");
failed(&output, "a mismatched contract");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("the Go of api and the library are from different builds"),
Expand Down
4 changes: 4 additions & 0 deletions ffi/tests/nodump/module.modulemap
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module NoDump {
header "nodump.h"
export *
}
9 changes: 9 additions & 0 deletions ffi/tests/nodump/nodump.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/* `prctl` for the Swift test, which cannot call it: Swift imports no variadic C function. */

#include <sys/prctl.h>

/* Marks the process non-dumpable, so an expected abort writes no core and never starts the
* host's crash handler. */
static inline int nodump(void) {
return prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
}
Loading