Skip to content
Open
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
8 changes: 4 additions & 4 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ jobs:
matrix:
# The same OS images and MATLAB releases as the MATLAB CI in Cantera: each
# image runs the oldest supported release (R2024b) and the newest one.
os: [ubuntu-24.04, windows-2025, macos-14]
os: [ubuntu-24.04, windows-2025, macos-15]
release: [R2024b, latest]
include:
- os: macos-15
- os: macos-26
release: latest

env:
Expand Down Expand Up @@ -147,7 +147,7 @@ jobs:
uses: actions/cache@v4 # zizmor: ignore[cache-poisoning]
with:
path: build/canteraLib
key: canteraLib-${{ matrix.os }}-${{ hashFiles('cantera/interfaces/matlab/buildUtilities/build_cantera_library.py') }}-${{ steps.cantera.outputs.sha }}
key: canteraLib-${{ matrix.os }}-${{ hashFiles('buildUtilities/build_cantera_library.py') }}-${{ steps.cantera.outputs.sha }}

- name: Set up MATLAB
uses: matlab-actions/setup-matlab@f9e43010f1ae678f7cfa0542fe2a4f60f7d1ad8d # v3.1.0
Expand All @@ -160,7 +160,7 @@ jobs:
tasks: buildCanteraLibrary

- name: Audit the Cantera library
run: python TMP/toolbox/buildUtilities/audit_library.py --prefix build/canteraLib
run: python buildUtilities/audit_library.py --prefix build/canteraLib

- name: Add the Cantera library to PATH (Windows)
if: runner.os == 'Windows'
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ jobs:
include:
- os: ubuntu-24.04
label: linux
- os: macos-14
- os: macos-15
label: macos
- os: windows-2025
label: windows
Expand Down Expand Up @@ -195,7 +195,7 @@ jobs:
-name '*cantera_shared*' ! -type l | head -1)
echo "shipped library: $lib"
test -n "$lib" || { echo "no library beside the interface"; exit 1; }
python TMP/toolbox/buildUtilities/audit_library.py --library "$lib"
python buildUtilities/audit_library.py --library "$lib"

- name: Upload the interface
uses: actions/upload-artifact@v4
Expand Down
38 changes: 13 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ the toolbox ships Cantera's standard data files (`gri30.yaml`, `air.yaml`, and
the rest). No conda environment, no `LD_LIBRARY_PATH`, no compiler.

> **Prefer a guided walkthrough?** When you install the toolbox, MATLAB opens
> its **Getting Started** guide — a live script that runs `ct.install` and a
> its **Getting Started** guide — a live script that loads Cantera and runs a
> first simulation step by step. You can follow it instead of the steps below.
> To reopen it later, go to **Home > Add-Ons > Manage Add-Ons**, click the
> **⋮** menu next to *Cantera MATLAB Toolbox*, and choose **Open Getting
Expand All @@ -50,19 +50,10 @@ the rest). No conda environment, no `LD_LIBRARY_PATH`, no compiler.

Download the `.mltbx` and double-click it (or use the MATLAB Add-On Manager).

### 2. Run `ct.install` once
### 2. Use Cantera

```matlab
ct.install
```

This registers the bundled data directory and verifies that Cantera loads. The settings are saved as
MATLAB preferences, so this is needed only once; running it again does nothing
unless the installation is incomplete. To redo it, use `ct.install(Force=true)`.

### 3. Use Cantera

Load Cantera at the start of each session:
Load Cantera at the start of each session. The data files shipped with the
toolbox are found automatically:

```matlab
ct.load
Expand All @@ -86,9 +77,9 @@ open CanteraTutorial

### Uninstalling

Run `ct.uninstall` **first**, then remove the toolbox in the Add-On Manager.
`ct.uninstall` clears the saved Cantera preferences and unloads Cantera, and it is
part of the toolbox, so it is no longer available once the toolbox is removed.
Remove the toolbox in the Add-On Manager. On Windows, Cantera's files cannot be
removed while Cantera is loaded: run `ct.unload` first, or restart MATLAB if
Cantera was loaded in-process.

---

Expand Down Expand Up @@ -137,11 +128,8 @@ Set these environment variables before building:

`buildtool buildCanteraLibrary` builds Cantera with every third-party
dependency vendored and statically linked (`system_*=n`, no external
BLAS/LAPACK, no HDF5), then checks with `audit_library.py` that
BLAS/LAPACK, no HDF5), then checks with `buildUtilities/audit_library.py` that
the result depends on nothing outside a per-platform allowlist of OS libraries.
Both scripts (`build_cantera_library.py` and `audit_library.py`) live in Cantera's
`interfaces/matlab/buildUtilities`; `buildtool stage` copies them into the staged
toolbox, and `buildtool package` leaves them out of the MLTBX.
MATLAB's `clibgen` copies it next to the generated interface, so it ships
inside the `ctMatlab` bundle automatically.

Expand Down Expand Up @@ -172,13 +160,13 @@ repository root:
| `buildtool package` | Build the `.mltbx`, binaries included, into `release/` (depends on `buildInterface`). |
| `buildtool` | Run `test` and `package`, the default tasks. |

`buildCanteraLibrary` builds from `CANTERA_ROOT`, but runs the build scripts
from the staged copy of Cantera's `interfaces/matlab/buildUtilities`, so it
depends on `stage`:
`buildCanteraLibrary` builds from `CANTERA_ROOT` rather than the staged tree,
so it is a second root task joining the chain at `buildInterface`:

```
stage ─→ buildCanteraLibrary ─→ buildInterface ─┬─→ test
└─→ package
stage ───────────────┐
├─→ buildInterface ─┬─→ test
buildCanteraLibrary ─┘ └─→ package
```

A local `buildtool package` includes only the current platform's binaries, and
Expand Down
216 changes: 216 additions & 0 deletions buildUtilities/audit_library.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
#!/usr/bin/env python3
"""Verify that a built Cantera library depends only on system libraries.

Inspects the dynamic dependencies of a built cantera_shared and fails if
anything outside a per-platform allowlist appears.

Run standalone against any prefix:
python audit_library.py --prefix build/canteraLib
"""

from __future__ import annotations

import argparse
import platform
import re
import shutil
import subprocess
import sys
from pathlib import Path

# Libraries that are part of the OS (or of MATLAB's guaranteed runtime).
# libstdc++ and libgcc_s are deliberately absent on Linux: the build links them
# statically, so their appearance means -static-libstdc++ did not take effect.
ALLOWLISTS = {
"Linux": [
r"^linux-vdso\.so\.1$",
r"^libc\.so\.6$",
r"^libm\.so\.6$",
r"^libdl\.so\.2$",
r"^libpthread\.so\.0$",
r"^librt\.so\.1$",
r"^ld-linux-.*\.so\.\d+$",
],
"Darwin": [
r"^/usr/lib/libSystem\.B\.dylib$",
r"^/usr/lib/libc\+\+\.1\.dylib$",
r"^/usr/lib/libobjc\.A\.dylib$",
r"^/System/Library/Frameworks/Accelerate\.framework/",
# The library's own id and its co-located siblings.
r"^@rpath/libcantera_shared",
r"^@loader_path/",
],
"Windows": [
r"^KERNEL32\.dll$",
r"^ADVAPI32\.dll$",
r"^USER32\.dll$",
r"^SHELL32\.dll$",
r"^ole32\.dll$",
r"^OLEAUT32\.dll$",
r"^bcrypt\.dll$",
r"^dbgeng\.dll$",
r"^api-ms-win-.*\.dll$",
# The MSVC redistributable, which MATLAB ships.
r"^MSVCP140.*\.dll$",
r"^VCRUNTIME140.*\.dll$",
],
}


def find_library(prefix: Path) -> Path:
"""Locate the real (non-symlink) shared library under the prefix."""
patterns = {
"Linux": "libcantera_shared.so*",
"Darwin": "libcantera_shared*.dylib",
"Windows": "cantera_shared.dll",
}[platform.system()]

candidates = [p for p in (prefix / "lib").glob(patterns) if not p.is_symlink()]
if not candidates:
raise FileNotFoundError(
f"No cantera_shared library found in {prefix / 'lib'}"
)
# Prefer the fully versioned file, which is the real object on Linux/macOS.
return max(candidates, key=lambda p: len(p.name))


def dependencies(library: Path) -> list[str]:
"""Return the library's direct dynamic dependencies, as recorded names."""
system = platform.system()

if system == "Linux":
# readelf reports DT_NEEDED. ldd would resolve the transitive graph
# through this machine's paths and hide a missing dependency behind a
# locally installed copy.
out = _run(["readelf", "-d", str(library)])
return re.findall(r"Shared library: \[([^\]]+)\]", out)

if system == "Darwin":
# First line is the file name; the rest are deps, starting with the
# library's own install id.
out = _run(["otool", "-L", str(library)])
return [line.strip().split(" (")[0]
for line in out.splitlines()[1:] if line.startswith("\t")]

if system == "Windows":
# Parsed in-process; dumpbin only exists in a Visual Studio developer
# shell, and CI runs these steps under plain bash.
return pe_imports(library)

raise RuntimeError(f"Unsupported platform: {system}")


def pe_imports(library: Path) -> list[str]:
"""Read the DLL names from a PE file's import directory."""
data = library.read_bytes()

def u16(off: int) -> int:
return int.from_bytes(data[off:off + 2], "little")

def u32(off: int) -> int:
return int.from_bytes(data[off:off + 4], "little")

if data[:2] != b"MZ":
raise ValueError(f"{library} is not a PE image")

pe = u32(0x3C)
if data[pe:pe + 4] != b"PE\0\0":
raise ValueError(f"{library} has no PE signature")

coff = pe + 4
n_sections = u16(coff + 2)
opt_size = u16(coff + 16)
opt = coff + 20

# Data directories sit at offset 96 in a PE32 optional header, 112 in
# PE32+, where several fields widen to 8 bytes.
magic = u16(opt)
dir_off = opt + (96 if magic == 0x10B else 112)
import_rva = u32(dir_off + 8 * 1) # data directory 1 = imports
if import_rva == 0:
return []

sections = []
sec_table = opt + opt_size
for i in range(n_sections):
s = sec_table + 40 * i
sections.append((u32(s + 12), u32(s + 8), u32(s + 20))) # va, vsize, raw

def to_offset(rva: int) -> int:
for va, vsize, raw in sections:
if va <= rva < va + max(vsize, 1):
return raw + (rva - va)
raise ValueError(f"RVA {rva:#x} is outside every section")

def cstring(rva: int) -> str:
start = to_offset(rva)
end = data.index(b"\0", start)
return data[start:end].decode("ascii", "replace")

names, entry = [], to_offset(import_rva)
while True:
# IMAGE_IMPORT_DESCRIPTOR is 20 bytes with the name RVA at offset 12;
# an all-zero descriptor terminates the table.
descriptor = data[entry:entry + 20]
if len(descriptor) < 20 or descriptor == b"\0" * 20:
break
names.append(cstring(u32(entry + 12)))
entry += 20

return names


def _run(cmd: list[str]) -> str:
"""Run a required inspection tool and return its stdout."""
if shutil.which(cmd[0]) is None:
raise RuntimeError(
f"'{cmd[0]}' not found; it is required to audit the built library."
)
return subprocess.run(cmd, capture_output=True, text=True, check=True).stdout


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
source = parser.add_mutually_exclusive_group(required=True)
source.add_argument("--prefix", help="Install prefix containing lib/")
source.add_argument("--library",
help="Audit this library file directly, e.g. the copy "
"clibgen placed in the staged ctMatlab folder.")
args = parser.parse_args()

if args.library:
library = Path(args.library).resolve()
if not library.is_file():
print(f"error: no such file: {library}", file=sys.stderr)
return 1
else:
library = find_library(Path(args.prefix).resolve())
allowed = [re.compile(p) for p in ALLOWLISTS[platform.system()]]

deps = dependencies(library)
unexpected = [d for d in deps if not any(p.search(d) for p in allowed)]

print(f"[audit_library] {library.name} depends on {len(deps)} libraries:")
for dep in deps:
mark = " " if dep not in unexpected else "->"
print(f" {mark} {dep}")

if unexpected:
sys.stdout.flush() # keep the listing above the error in CI logs
print(
f"\nerror: {library.name} has {len(unexpected)} dependency/ies "
f"outside the {platform.system()} allowlist:\n"
+ "\n".join(f" {d}" for d in unexpected)
+ "\n\nEither vendor them into the build or, if genuinely part of "
"the OS, add them to ALLOWLISTS in this file.",
file=sys.stderr,
)
return 1

print(f"\n[audit_library] OK: no dependencies outside the "
f"{platform.system()} system allowlist.")
return 0


if __name__ == "__main__":
sys.exit(main())
Loading
Loading