push sheeet
Some checks failed
Periodic Merges (6h) / master → staging-nixos (push) Failing after 12m50s
Periodic Merges (6h) / master → staging-next (push) Failing after 12m54s
Periodic Merges (24h) / merge-base(master,staging) → haskell-updates (push) Failing after 11m54s
Periodic Merges (6h) / staging-next → staging (push) Failing after 12m13s
Periodic Merges (24h) / staging-next-25.05 → staging-25.05 (push) Failing after 13m24s
Periodic Merges (24h) / release-25.05 → staging-next-25.05 (push) Failing after 14m28s

This commit is contained in:
Dark Steveneq
2025-10-09 14:15:47 +02:00
commit 646b892680
49168 changed files with 5897842 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
{
lib,
stdenv,
fetchurl,
}:
stdenv.mkDerivation rec {
pname = "DarwinTools";
version = "1";
src = fetchurl {
url = "https://web.archive.org/web/20180408044816/https://opensource.apple.com/tarballs/DarwinTools/DarwinTools-${version}.tar.gz";
hash = "sha256-Fzo5QhLd3kZHVFKhJe7xzV6bmRz5nAsG2mNLkAqVBEI=";
};
patches = [
./sw_vers-CFPriv.patch
];
configurePhase = ''
export SRCROOT=.
export SYMROOT=.
export DSTROOT=$out
'';
makeFlags = [
"CC=${stdenv.cc.targetPrefix}cc"
"STRIP=${stdenv.cc.targetPrefix}strip"
];
postInstall = ''
mv $out/usr/* $out
rmdir $out/usr
'';
meta = {
maintainers = [ lib.maintainers.matthewbauer ];
platforms = lib.platforms.darwin;
};
}

View File

@@ -0,0 +1,19 @@
--- a/sw_vers.c 2021-04-19 13:06:50.131346864 +0900
+++ b/sw_vers.c 2021-04-19 13:07:32.481967474 +0900
@@ -28,7 +28,15 @@
*/
#include <CoreFoundation/CoreFoundation.h>
-#include <CoreFoundation/CFPriv.h>
+
+// Avoid dependency on CoreFoundation/CFPriv, which no longer appears to be
+// part of the upstream sdk.
+
+CFDictionaryRef _CFCopyServerVersionDictionary(void);
+CFDictionaryRef _CFCopySystemVersionDictionary(void);
+extern CFStringRef _kCFSystemVersionProductNameKey;
+extern CFStringRef _kCFSystemVersionProductVersionKey;
+extern CFStringRef _kCFSystemVersionBuildVersionKey;
void usage(char *progname) {
fprintf(stderr, "Usage: %s [-productName|-productVersion|-buildVersion]\n", progname);

View File

@@ -0,0 +1,117 @@
{
lib,
apple-sdk,
buildPackages,
mkAppleDerivation,
unifdef,
}:
let
inherit (buildPackages) gnused python3;
xnu = apple-sdk.sourceRelease "xnu";
in
mkAppleDerivation (finalAttrs: {
releaseName = "AvailabilityVersions";
patches = [
# Add support for setting an upper bound, which is needed by the `gen-headers` script.
# It avoids having pre-process the DSL to remove unwanted versions.
./patches/0001-Support-setting-an-upper-bound-on-versions.patch
];
noCC = true;
nativeBuildInputs = [ unifdef ];
buildPhase = ''
runHook preBuild
declare -a unifdef_sources=(
os_availability.modulemap
os_availability_private.modulemap
)
unifdef -x2 -UBUILD_FOR_DRIVERKIT -m $(for x in "''${unifdef_sources[@]}"; do echo templates/$x; done)
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p "$out/bin" "$out/libexec" "$out/share/availability"
cp -r availability.dsl templates "$out/share/availability/"
substitute availability "$out/libexec/availability" \
--replace-fail '/usr/bin/env python3' '${lib.getExe python3}' \
--replace-fail 'f"{os.path.abspath(os.path.dirname(sys.argv[0]))}/' "\"$out/share/availability/"
chmod a+x "$out/libexec/availability"
substitute ${xnu}/bsd/sys/make_symbol_aliasing.sh "$out/libexec/make_symbol_aliasing.sh" \
${
if lib.versionOlder (lib.getVersion xnu) "6153.11.26" then
''--replace-fail "\''${SDKROOT}/usr/local/libexec/availability.pl" "$out/libexec/availability" \''
else
''--replace-fail "\''${SDKROOT}/\''${DRIVERKITROOT}/usr/local/libexec/availability.pl" "$out/libexec/availability" \''
}
--replace-fail '--macosx' '--macosx --threshold $SDKROOT'
chmod a+x "$out/libexec/make_symbol_aliasing.sh"
cat <<SCRIPT > "$out/bin/gen-headers"
#!/usr/bin/env bash
set -eu
declare -a headers=(
Availability.h
AvailabilityInternal.h
AvailabilityInternalLegacy.h
AvailabilityMacros.h
AvailabilityVersions.h
os/availability.h
)
dest=\$2
threshold=\$1
for header in "\''${headers[@]}"; do
header_src=\''${header/\//_}
mkdir -p "\$(dirname "\$dest/include/\$header")"
"$out/libexec/availability" \\
--threshold "\$threshold" \\
--preprocess "$out/share/availability/templates/\$header_src" "\$dest/include/\$header"
done
"$out/libexec/make_symbol_aliasing.sh" \$threshold "\$dest/include/sys/_symbol_aliasing.h"
# Remove macros from newer SDKs because they can confuse some programs about the SDK version.
declare -a versionParts=(\''${threshold//./ })
if [ "\''${versionParts[0]}" == "10" ]; then
sdkMajor=\''${versionParts[1]}
sdkMinor=\''${versionParts[2]:-0}
for minor in \$(seq \$(("\$sdkMinor" + 1)) 9); do
${lib.getExe gnused} \\
-E "/VERSION_10_\''${sdkMajor}_\$minor/,/#endif/c\\ */" \\
-i "\$dest/include/AvailabilityMacros.h"
done
for major in \$(seq \$(("\$sdkMajor" + 1)) 15); do
${lib.getExe gnused} \\
-E "/VERSION_10_\$major/,/#endif/c\\ */" \\
-i "\$dest/include/AvailabilityMacros.h"
done
fi
cp "$out/share/availability/templates/os_availability.modulemap" "\$dest/include/"
SCRIPT
chmod a+x "$out/bin/gen-headers"
patchShebangs "$out/bin"
runHook postInstall
'';
meta = {
description = "Generates Darwin Availability headers";
mainProgram = "gen-headers";
platforms = lib.platforms.unix;
};
})

View File

@@ -0,0 +1,244 @@
From dd3a2378cca465ec783fd792158b2fc11f83722c Mon Sep 17 00:00:00 2001
From: Randy Eckenrode <randy@largeandhighquality.com>
Date: Tue, 2 Jul 2024 20:04:56 -0400
Subject: [PATCH] Support setting an upper bound on versions
---
availability | 94 ++++++++++++++++++++++++++++++++++------------------
1 file changed, 61 insertions(+), 33 deletions(-)
diff --git a/availability b/availability
index 8ebd250..5bb9edb 100755
--- a/availability
+++ b/availability
@@ -17,12 +17,34 @@ MIN_PYTHON = (3, 7) #Required for ordered dictionaries as default
if sys.version_info < MIN_PYTHON:
sys.exit("Python %s.%s or later is required.\n" % MIN_PYTHON)
+
+def parse_version(ver):
+ if hasattr(ver, "string"):
+ ver = ver.string()
+
+ return (tuple(map(int, ver.split("."))) + (0, 0))[:3]
+
+
+def version_older_or_equal(lhs, rhs):
+ if not rhs:
+ return True
+
+ lhs_major, lhs_minor, lhs_patch = parse_version(lhs)
+ rhs_major, rhs_minor, rhs_patch = parse_version(rhs)
+
+ return (
+ lhs_major < rhs_major
+ or (lhs_major == rhs_major and lhs_minor < rhs_minor)
+ or (lhs_major == rhs_major and lhs_minor == rhs_minor and lhs_patch <= rhs_patch)
+ )
+
+
# The build script will embed the DSL content here, otherwise we build it at runtime
dslContent = None
# @@INSERT_DSL_CONTENT()@@
class VersionSetDSL:
- def __init__(self, data): self.parsedDSL = self.Parser(data)
+ def __init__(self, data, threshold): self.parsedDSL = self.Parser(data, threshold)
def sets(self): return self.parsedDSL.version_sets
def platforms(self): return self.parsedDSL.platforms
@@ -104,12 +126,15 @@ class VersionSetDSL:
self.availability_deprecation_define_name = optionals["availability_deprecation_define_name"]
if "version_define_name" in optionals:
self.availability_define_prefix = f"__{optionals['version_define_name']}_"
- def add_version(self, version): return self.versions.append(version);
+ def add_version(self, version, threshold):
+ if version_older_or_equal(version, threshold):
+ self.versions.append(version)
def add_variant(self, variant): return self.variants.append(variant);
class Parser:
platforms = {}
version_sets = []
- def __init__(self, data):
+ def __init__(self, data, threshold):
+ self.threshold = threshold
for line in data.splitlines():
line = line.strip().split('#',1)[0]
if not line:
@@ -129,7 +154,7 @@ class VersionSetDSL:
def set(self, name, version, uversion):
platforms = {}
for (platformName, platform) in self.platforms.items():
- if platform.versioned:
+ if platform.versioned and platform.versions:
platforms[platformName] = platform.versions[-1]
version_set = {}
version_set["name"] = name
@@ -138,7 +163,7 @@ class VersionSetDSL:
self.version_sets.append(version_set)
# TODO add error checking for version decrease
def version(self, platform, version):
- if platform in self.platforms: self.platforms[platform].add_version(VersionSetDSL.Version(version))
+ if platform in self.platforms: self.platforms[platform].add_version(VersionSetDSL.Version(version), self.threshold)
else:
print(f"Unknown platform \"{platform}\"")
exit(-1)
@@ -165,9 +190,8 @@ if not dslContent:
parts = line.split()
if uversion and parts and parts[0] == "set" and parts[3] == uversion:
break
-versions = VersionSetDSL(dslContent)
-def print_sets():
+def print_sets(versions):
print("---")
for set in versions.sets():
print(f'{set["name"]}:')
@@ -178,7 +202,8 @@ def print_versions(platform):
print(" ".join([version.string() for version in versions.platforms()[platform].versions]))
class Preprocessor:
- def __init__(self, inputFile, outputFile):
+ def __init__(self, versions, inputFile, outputFile):
+ self.versions = versions
bufferedOutput = ""
with tempfile.NamedTemporaryFile('w') as tmp:
with open(inputFile, 'r') as input:
@@ -207,10 +232,10 @@ class Preprocessor:
output.write("\"\"\"\n")
def VERSION_MAP(self, output):
sets = []
- for set in versions.sets():
+ for set in self.versions.sets():
set_string = ", ".join(sorted({".{} = {}".format(os,osVersion.hex()) for (os,osVersion) in set["platforms"].items()}))
sets.append("\t{{ .set = {}, {} }}".format(set["version"].hex(), set_string))
- platform_string = "\n".join([" uint32_t {} = 0;".format(name) for name in versions.platforms().keys()])
+ platform_string = "\n".join([" uint32_t {} = 0;".format(name) for name in self.versions.platforms().keys()])
output.write("""
#include <set>
#include <array>
@@ -229,16 +254,16 @@ static const std::array<VersionSetEntry, {}> sVersionMap = {{{{
}};
""".format(platform_string, len(sets), ",\n".join(sets)))
def DYLD_HEADER_VERSIONS(self, output):
- for (name,platform) in versions.platforms().items():
+ for (name,platform) in self.versions.platforms().items():
for version in platform.versions:
output.write(f"#define {platform.dyld_version_define_name + version.symbol() : <48}{version.hex()}\n");
output.write("\n")
- for set in versions.sets():
+ for set in self.versions.sets():
set_string = " / ".join(sorted({"{} {}".format(os,osVersion.string()) for(os,osVersion) in set["platforms"].items()}))
output.write("// dyld_{}_os_versions => {}\n".format(set["name"], set_string))
output.write("#define dyld_{}_os_versions".format(set["name"]).ljust(56, ' '))
output.write("({{ (dyld_build_version_t){{0xffffffff, {}}}; }})\n\n".format(set["version"].hex()))
- for (name,platform) in versions.platforms().items():
+ for (name,platform) in self.versions.platforms().items():
for version in platform.versions:
output.write("#define dyld_platform_version_{}_{}".format(platform.stylized_name, version.symbol()).ljust(56, ' '))
output.write("({{ (dyld_build_version_t){{{}, {}{}}}; }})\n".format(platform.platform_define, platform.dyld_version_define_name, version.symbol()))
@@ -247,14 +272,14 @@ static const std::array<VersionSetEntry, {}> sVersionMap = {{{{
def ALIAS_VERSION_MACROS(self, output, platformString, newName, oldName, **optionals):
minVersion = literal_eval(optionals.get("minVersion", "0x00000000"))
maxVersion = literal_eval(optionals.get("maxVersion", "0xFFFFFFFF"))
- platform = versions.platforms()[platformString];
+ platform = self.versions.platforms()[platformString];
for version in platform.versions:
if literal_eval(version.hex()) < minVersion: continue
if literal_eval(version.hex()) >= maxVersion: continue
output.write(f'#define {newName + version.symbol() : <48} {oldName + version.symbol()}\n')
def AVAILABILITY_DEFINES(self, output):
- for platformString in versions.platforms():
- platform = versions.platforms()[platformString];
+ for platformString in self.versions.platforms():
+ platform = self.versions.platforms()[platformString];
if platform.bleached:
output.write(f"#ifndef __APPLE_BLEACH_SDK__\n")
output.write(f"#ifndef __API_TO_BE_DEPRECATED_{platform.availability_deprecation_define_name}\n")
@@ -268,16 +293,16 @@ static const std::array<VersionSetEntry, {}> sVersionMap = {{{{
output.write(f"#endif /* __APPLE_BLEACH_SDK__ */\n")
output.write(f"\n");
def AVAILABILITY_VERSION_DEFINES(self, output):
- for platformString in versions.platforms():
- short = platform = versions.platforms()[platformString].short_version_numbers
- platform = versions.platforms()[platformString];
+ for platformString in self.versions.platforms():
+ short = platform = self.versions.platforms()[platformString].short_version_numbers
+ platform = self.versions.platforms()[platformString];
for version in platform.versions:
output.write(f"#define {platform.availability_define_prefix + version.symbol() : <48}{version.decimal(short)}\n")
output.write(f"/* {platform.availability_define_prefix}_NA is not defined to a value but is used as a token by macros to indicate that the API is unavailable */\n\n")
def AVAILABILITY_MIN_MAX_DEFINES(self, output):
- for platformString in versions.platforms():
- platform = versions.platforms()[platformString];
- if not platform.versioned:
+ for platformString in self.versions.platforms():
+ platform = self.versions.platforms()[platformString];
+ if not platform.versioned or not platform.versions:
continue
if platform.bleached:
output.write(f"#ifndef __APPLE_BLEACH_SDK__\n")
@@ -310,8 +335,8 @@ static const std::array<VersionSetEntry, {}> sVersionMap = {{{{
output.write(f" #define __API_UNAVAILABLE_PLATFORM_{displayName} {realName},unavailable\n")
output.write(f"#if defined(__has_feature) && defined(__has_attribute)\n")
output.write(f" #if __has_attribute(availability)\n")
- for platformString in versions.platforms():
- platform = versions.platforms()[platformString];
+ for platformString in self.versions.platforms():
+ platform = self.versions.platforms()[platformString];
if platform.bleached:
output.write(f"#ifndef __APPLE_BLEACH_SDK__\n")
writeDefines(platformString, platformString, platform.versioned)
@@ -326,9 +351,9 @@ static const std::array<VersionSetEntry, {}> sVersionMap = {{{{
output.write(f" #endif /* __has_attribute(availability) */\n")
output.write(f"#endif /* defined(__has_feature) && defined(__has_attribute) */\n")
def AVAILABILITY_MACRO_IMPL(self, output, prefix, dispatcher, **optionals):
- count = len(versions.platforms())
- for platformString in versions.platforms():
- platform = versions.platforms()[platformString]
+ count = len(self.versions.platforms())
+ for platformString in self.versions.platforms():
+ platform = self.versions.platforms()[platformString]
count = count + len(platform.variants)
platformList = []
argList = []
@@ -344,9 +369,9 @@ static const std::array<VersionSetEntry, {}> sVersionMap = {{{{
scoped_availablity = False
if "scoped_availablity" in optionals and optionals["scoped_availablity"] == "TRUE":
scoped_availablity=True
- count = len(versions.platforms())
- for platformString in versions.platforms():
- platform = versions.platforms()[platformString]
+ count = len(self.versions.platforms())
+ for platformString in self.versions.platforms():
+ platform = self.versions.platforms()[platformString]
count = count + len(platform.variants)
argList = ','.join([f'{macroName}{x}' for x in reversed(range(0, count))])
if "argCount" in optionals:
@@ -358,8 +383,9 @@ static const std::array<VersionSetEntry, {}> sVersionMap = {{{{
output.write(f" #define {name}(...) {macroName}_GET_MACRO(__VA_ARGS__,{argList},0)(__VA_ARGS__)\n")
parser = argparse.ArgumentParser()
+parser.add_argument("--threshold", default=False, help='Specifies the maximum version (inclusive) included in pre-processed headers')
group = parser.add_mutually_exclusive_group()
-for (name, platform) in versions.platforms().items():
+for (name, platform) in VersionSetDSL(dslContent, threshold=None).platforms().items():
group.add_argument("--{}".format(name), default=False, action='store_true', help="Prints all SDK versions defined for {}".format(name))
for alias in platform.cmd_aliases:
group.add_argument("--{}".format(alias), dest=name, default=False, action='store_true', help="Alias for --{}".format(name))
@@ -367,8 +393,10 @@ group.add_argument("--sets", default=False, actio
group.add_argument("--preprocess", nargs=2, help=argparse.SUPPRESS)
args = parser.parse_args()
-if args.sets: print_sets();
-elif args.preprocess: Preprocessor(args.preprocess[0], args.preprocess[1]);
+versions = VersionSetDSL(dslContent, threshold=args.threshold)
+
+if args.sets: print_sets(versions);
+elif args.preprocess: Preprocessor(versions, args.preprocess[0], args.preprocess[1]);
else:
for platform in versions.platforms().keys():
if getattr(args, platform, None):
--
2.45.2

View File

@@ -0,0 +1,31 @@
{
lib,
makeSetupHook,
mkAppleDerivation,
stdenv,
}:
mkAppleDerivation {
releaseName = "Csu";
makeFlags = [
"CC=${stdenv.cc.targetPrefix}clang"
"CHMOD=chmod"
"MKDIR=mkdir"
"USRLIBDIR=/lib"
"LOCLIBDIR=/lib"
];
installFlags = [ "DSTROOT=$(out)" ];
setupHooks = [
../../../../build-support/setup-hooks/role.bash
# ccWrapper_addCVars doesnt add Csu to `NIX_LDFLAGS` because it contains objects and no dylibs.
./setup-hooks/add-Csu-lib-path.sh
];
meta = {
description = "Common startup stubs for Darwin";
badPlatforms = [ lib.systems.inspect.patterns.isAarch ];
};
}

View File

@@ -0,0 +1,4 @@
local role_post
getHostRole
export NIX_LDFLAGS${role_post}+=" -L@out@/lib"
unset -v role_post

View File

@@ -0,0 +1,214 @@
{
lib,
bootstrapStdenv,
buildPackages,
fetchpatch2,
mkAppleDerivation,
python3,
testers,
}:
# Based on:
# - ../../../development/libraries/icu/make-icu.nix
# - https://github.com/apple-oss-distributions/ICU/blob/main/makefile
let
stdenv = bootstrapStdenv;
withStatic = stdenv.hostPlatform.isStatic;
# Cross-compiled icu4c requires a build-root of a native compile
nativeBuildRoot = buildPackages.darwin.ICU.buildRootOnly;
baseAttrs = finalAttrs: {
releaseName = "ICU";
sourceRoot = "${finalAttrs.src.name}/icu/icu4c/source";
patches = [
# Skip MessageFormatTest test, which is known to crash sometimes and should be suppressed if it does.
./patches/suppress-icu-check-crash.patch
# Python 3.13 compatibility
(fetchpatch2 {
url = "https://github.com/unicode-org/icu/commit/60d6bd71efc0cde8f861b109ff87dbbf9fc96586.patch?full_index=1";
hash = "sha256-aJBSVvKidPUjD956jLjyRk8fewUZ9f+Ip4ka6rjevzU=";
stripLen = 2;
})
];
preConfigure = ''
sed -i -e "s|/bin/sh|${stdenv.shell}|" configure
patchShebangs --build .
# $(includedir) is different from $(prefix)/include due to multiple outputs
sed -i -e 's|^\(CPPFLAGS = .*\) -I\$(prefix)/include|\1 -I$(includedir)|' config/Makefile.inc.in
'';
dontDisableStatic = withStatic;
configureFlags = [
(lib.enableFeature false "debug")
(lib.enableFeature false "renaming")
(lib.enableFeature false "extras")
(lib.enableFeature false "layout")
(lib.enableFeature false "samples")
]
++ lib.optionals (stdenv.hostPlatform.isFreeBSD || stdenv.hostPlatform.isDarwin) [
(lib.enableFeature true "rpath")
]
++ lib.optionals (stdenv.buildPlatform != stdenv.hostPlatform) [
(lib.withFeatureAs true "cross-build" nativeBuildRoot)
]
++ lib.optionals withStatic [ (lib.enableFeature true "static") ];
nativeBuildInputs = [ python3 ];
enableParallelBuilding = true;
# Per the source-release makefile, these are enabled.
env.NIX_CFLAGS_COMPILE = toString [
"-DU_SHOW_CPLUSPLUS_API=1"
"-DU_SHOW_INTERNAL_API=1"
];
passthru.tests.pkg-config = testers.testMetaPkgConfig finalAttrs.finalPackage;
passthru.buildRootOnly = mkWithAttrs buildRootOnlyAttrs;
meta = {
description = "Unicode and globalization support library with Apple customizations";
license = [ lib.licenses.icu ];
teams = [ lib.teams.darwin ];
platforms = lib.platforms.darwin;
pkgConfigModules = [
"icu-i18n"
"icu-io"
"icu-uc"
];
};
};
realAttrs = self: super: {
outputs = [
"out"
"dev"
]
++ lib.optional withStatic "static";
outputBin = "dev";
postPatch = lib.optionalString self.finalPackage.doCheck ''
# Skip test for missing encodingSamples data.
substituteInPlace test/cintltst/ucsdetst.c \
--replace-fail "&TestMailFilterCSS" "NULL"
# Disable failing tests
substituteInPlace test/cintltst/cloctst.c \
--replace-fail 'TESTCASE(TestCanonicalForm);' ""
substituteInPlace test/intltest/rbbitst.cpp \
--replace-fail 'TESTCASE_AUTO(TestExternalBreakEngineWithFakeYue);' ""
# Otherwise `make install` is broken.
substituteInPlace Makefile.in \
--replace-fail '$(top_srcdir)/../LICENSE' "$NIX_BUILD_TOP/source/icu/LICENSE"
substituteInPlace config/dist-data.sh \
--replace-fail "\''${top_srcdir}/../LICENSE" "$NIX_BUILD_TOP/source/icu/LICENSE"
'';
# remove dependency on bootstrap-tools in early stdenv build
postInstall =
lib.optionalString withStatic ''
mkdir -p $static/lib
mv -v lib/*.a $static/lib
''
+ lib.optionalString stdenv.hostPlatform.isDarwin ''
sed -i 's/INSTALL_CMD=.*install/INSTALL_CMD=install/' $out/lib/icu/*/pkgdata.inc
''
+ (
let
replacements = [
{
from = "\${prefix}/include";
to = "${placeholder "dev"}/include";
} # --cppflags-searchpath
{
from = "\${pkglibdir}/Makefile.inc";
to = "${placeholder "dev"}/lib/icu/Makefile.inc";
} # --incfile
{
from = "\${pkglibdir}/pkgdata.inc";
to = "${placeholder "dev"}/lib/icu/pkgdata.inc";
} # --incpkgdatafile
];
in
''
rm $out/share/icu/*/install-sh $out/share/icu/*/mkinstalldirs # Avoid having a runtime dependency on bash
substituteInPlace "$dev/bin/icu-config" \
${lib.concatMapStringsSep " " (r: "--replace-fail '${r.from}' '${r.to}'") replacements}
''
# Create library with everything reexported to provide the same ABI as the system ICU.
+ lib.optionalString stdenv.hostPlatform.isDarwin (
if stdenv.hostPlatform.isStatic then
''
${stdenv.cc.targetPrefix}ar qL "$out/lib/libicucore.a" \
"$out/lib/libicuuc.a" \
"$out/lib/libicudata.a" \
"$out/lib/libicui18n.a" \
"$out/lib/libicuio.a"
''
else
''
icuVersion=$(basename "$out/share/icu/"*)
${stdenv.cc.targetPrefix}clang -dynamiclib \
-L "$out/lib" \
-Wl,-reexport-licuuc \
-Wl,-reexport-licudata \
-Wl,-reexport-licui18n \
-Wl,-reexport-licuio \
-compatibility_version 1 \
-current_version "$icuVersion" \
-install_name "$out/lib/libicucore.A.dylib" \
-o "$out/lib/libicucore.A.dylib"
ln -s libicucore.A.dylib "$out/lib/libicucore.dylib"
''
)
);
postFixup = ''moveToOutput lib/icu "$dev" '';
doCheck = stdenv.buildPlatform.canExecute stdenv.hostPlatform;
nativeCheckInputs = [ python3 ];
# Some tests use `log(name)`, which clang identifies as potentially insecure.
checkFlags = [
"CFLAGS+=-Wno-format-security"
"CXXFLAGS+=-Wno-format-security"
];
checkTarget = "check";
};
buildRootOnlyAttrs = self: super: {
pname = "ICU-build-root";
preConfigure = super.preConfigure + ''
mkdir build
cd build
configureScript=../configure
# Apples customizations require building and linking additional files, which are handled via `Makefile.local`.
# These need copied into the build environment to avoid link errors from not building them.
mkdir common i18n
cp ../common/Makefile.local common/Makefile.local
cp ../i18n/Makefile.local i18n/Makefile.local
'';
postBuild = ''
cd ..
mv build $out
echo "Doing build-root only, exiting now" >&2
exit 0
'';
};
mkWithAttrs = attrs: mkAppleDerivation (lib.extends attrs baseAttrs);
in
mkWithAttrs realAttrs

View File

@@ -0,0 +1,13 @@
diff --git a/test/cintltst/cmsgtst.c b/test/cintltst/cmsgtst.c
index cb328707..1073e6c1 100644
--- a/test/cintltst/cmsgtst.c
+++ b/test/cintltst/cmsgtst.c
@@ -231,7 +231,7 @@ static void MessageFormatTest( void )
austrdup(result), austrdup(testResultStrings[i]) );
}
-#if (U_PLATFORM == U_PF_LINUX) /* add platforms here .. */
+#if (U_PLATFORM == U_PF_LINUX || U_PLATFORM == U_PF_DARWIN) /* add platforms here .. */
log_verbose("Skipping potentially crashing test for mismatched varargs.\n");
#else
log_verbose("Note: the next is a platform dependent test. If it crashes, add an exclusion for your platform near %s:%d\n", __FILE__, __LINE__);

View File

@@ -0,0 +1,75 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/IOKitTools/blob/main/IOKitTools.xcodeproj/project.pbxproj
# Project settings
project('IOKitTools', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
ncurses = dependency('ncurses')
core_foundation = dependency('appleframeworks', modules : 'CoreFoundation')
iokit = dependency('appleframeworks', modules : 'IOKit')
core_symbolication = dependency('appleframeworks', modules : 'CoreSymbolication')
perfdata = dependency('appleframeworks', modules : 'perfdata')
# Compatibility tests
iomainport_test = '''
#include <IOKit/IOKit.h>
int main(int argc, char* argv[]) {
const mach_port_t port = kIOMasterPortDefault;
}
'''
if not cc.compiles(iomainport_test, name : 'supports IOMainPort', dependencies : [ iokit ])
add_project_arguments(
'-DIOMainPort=IOMasterPort',
'-DkIOMainPortDefault=kIOMasterPortDefault',
language : 'c'
)
message('Redefining IOMainPort to IOMasterPort.')
endif
kiouserclasseskey_test = '''
#include <IOKit/IOKit.h>
int main(int argc, char* argv[]) {
const char* key = kIOUserClassesKey;
}
'''
if not cc.compiles(iomainport_test, name : 'supports IOUserClasses', dependencies : [ iokit ])
add_project_arguments(
'-DkIOUserClassesKey="IOUserClasses"',
language : 'c'
)
message('Manually defining IOUserClasses constants.')
endif
# Binaries
executable(
'ioalloccount',
dependencies : [ core_foundation, iokit ],
install : true,
sources : [ 'ioalloccount.tproj/ioalloccount.c' ],
)
install_man('ioalloccount.tproj/ioalloccount.8')
executable(
'ioclasscount',
dependencies : [ core_foundation, core_symbolication, iokit, perfdata ],
install : true,
sources : [ 'ioclasscount.tproj/ioclasscount.c' ],
)
install_man('ioclasscount.tproj/ioclasscount.8')
executable(
'ioreg',
dependencies : [ core_foundation, iokit, ncurses ],
install : true,
sources : [ 'ioreg.tproj/ioreg.c' ],
)
install_man('ioreg.tproj/ioreg.8')

View File

@@ -0,0 +1,61 @@
{
lib,
apple-sdk,
mkAppleDerivation,
ncurses,
pkg-config,
stdenvNoCC,
}:
let
iokitUser = apple-sdk.sourceRelease "IOKitUser";
xnu = apple-sdk.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "IOKitTools-deps-private-headers";
buildCommand = ''
install -D -t "$out/include/IOKit/" \
'${iokitUser}/IOKitLibPrivate.h' \
'${xnu}/iokit/IOKit/IOKitKeysPrivate.h'
install -D -t "$out/include/Kernel/libkern" \
'${xnu}/libkern/libkern/OSKextLibPrivate.h'
mkdir -p "$out/include/perfdata"
cat <<EOF > "$out/include/perfdata/perfdata.h"
#pragma once
typedef void* pdunit_t;
#define PDUNIT_CUSTOM(x) ((void*)("#\"" x "\""))
extern const pdunit_t pdunit_B;
typedef void* pdwriter_t;
extern pdwriter_t pdwriter_open(const char*, const char*, size_t, size_t);
extern void pdwriter_close(pdwriter_t);
extern void pdwriter_new_value(pdwriter_t, const char*, pdunit_t, double);
extern void pdwriter_record_variable_str(pdwriter_t, char*, const char*);
EOF
'';
};
in
mkAppleDerivation {
releaseName = "IOKitTools";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-qFG4sB8NXNPTSvYTEX2E1ReOX+NcMBHrS2NuNBLO7zw=";
nativeBuildInputs = [ pkg-config ];
buildInputs = [
apple-sdk.privateFrameworksHook
ncurses
];
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
meta.description = "IOKit tools";
}

View File

@@ -0,0 +1,23 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/PowerManagement/blob/main/PowerManagement.xcodeproj/project.pbxproj
# Project settings
project('PowerManagement', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
# Binaries
caffeinate = executable(
'caffeinate',
dependencies : dependency('appleframeworks', modules : ['CoreFoundation', 'IOKit']),
install : true,
sources : [
'caffeinate/caffeinate.c',
],
)
install_man(
'caffeinate/caffeinate.8',
)

View File

@@ -0,0 +1,28 @@
{
lib,
apple-sdk,
mkAppleDerivation,
stdenvNoCC,
}:
let
iokitUser = apple-sdk.sourceRelease "IOKitUser";
privateHeaders = stdenvNoCC.mkDerivation {
name = "file_cmds-deps-private-headers";
buildCommand = ''
install -D -t "$out/include/IOKit/pwr_mgt" \
'${iokitUser}/pwr_mgt.subproj/IOPMLibPrivate.h'
'';
};
in
mkAppleDerivation {
releaseName = "PowerManagement";
xcodeHash = "sha256-l6lm8aaiJg4H2BQVCjlFldpfhnmPAlsiMK7Cghzuh1E=";
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
meta.description = "Contains the Darwin caffeinate command";
}

View File

@@ -0,0 +1,225 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/adv_cmds/blob/main/adv_cmds.xcodeproj/project.pbxproj
# Project settings
project('adv_cmds', 'c', 'cpp', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
cxx = meson.get_compiler('cpp')
dbm = cc.find_library('dbm')
libxo = dependency('libxo')
ncurses = dependency('ncurses')
# Generators
bison_bin = find_program('bison', required : true)
flex_bin = find_program('flex', required : true)
bison = generator(
bison_bin,
arguments : ['@INPUT@', '--header=@OUTPUT0@', '--output=@OUTPUT1@'],
output : [ '@BASENAME@.tab.h', '@BASENAME@.tab.c'],
)
flex = generator(
flex_bin,
arguments : ['--header-file=@OUTPUT0@', '--outfile=@OUTPUT1@', '@INPUT@'],
output : ['@BASENAME@.yy.h', '@BASENAME@.yy.c'],
)
# Binaries
executable(
'cap_mkdb',
dependencies : dbm,
install : true,
sources : ['cap_mkdb/cap_mkdb.c'],
)
install_man('cap_mkdb/cap_mkdb.1')
executable(
'colldef',
dependencies : dbm,
include_directories : [
'colldef',
'colldef/locale',
],
install : true,
sources : [
bison.process('colldef/parse.y'),
flex.process('colldef/scan.l'),
],
)
install_man('colldef/colldef.1')
executable(
'finger',
dependencies : dbm,
install : true,
sources : [
'finger/finger.c',
'finger/lprint.c',
'finger/net.c',
'finger/sprint.c',
'finger/util.c',
],
)
install_man(
'finger/finger.1',
'finger/finger.conf.5'
)
executable(
'gencat',
install : true,
sources : [
'gencat/gencat.c',
'gencat/genlib.c',
],
)
install_man('gencat/gencat.1')
executable(
'genwrap',
include_directories : 'genwrap',
install : true,
sources : [
'genwrap/genwrap.c',
bison.process('genwrap/genwrap.y'),
flex.process('genwrap/lex.l'),
],
)
install_data(
'genwrap/wrapper-head.c',
'genwrap/wrapper-tail.c',
install_dir : get_option('datadir') + '/genwrap'
)
install_data(
'genwrap/sample.make',
'genwrap/sample.rsync',
install_dir : get_option('datadir') + '/genwrap/examples'
)
install_man('genwrap/genwrap.8')
executable(
'last',
dependencies : libxo,
install : true,
sources : ['last/last.c'],
)
install_man('last/last.1')
executable(
'locale',
install : true,
sources : ['locale/locale.cc'],
)
install_man('locale/locale.1')
executable(
'localedef',
include_directories : [ 'localedef', 'localedef/libc' ],
install : true,
sources : [
'localedef/charmap.c',
'localedef/collate.c',
'localedef/ctype.c',
'localedef/localedef.c',
'localedef/messages.c',
'localedef/monetary.c',
'localedef/numeric.c',
'localedef/scanner.c',
'localedef/time.c',
'localedef/wide.c',
bison.process('localedef/parser.y'),
],
)
install_man('localedef/localedef.1')
executable(
'lsvfs',
install : true,
sources : ['lsvfs/lsvfs.c'],
)
install_man('lsvfs/lsvfs.1')
executable(
'mklocale',
include_directories : 'mklocale',
install : true,
sources : [
bison.process('mklocale/yacc.y'),
flex.process('mklocale/lex.l'),
],
)
install_man('mklocale/mklocale.1')
executable(
'pkill',
# Requires undocumented, private sysmon.h.
build_by_default : false,
install : false,
sources : ['pkill/pkill.c'],
)
# install_man('pkill/pkill.1')
executable(
'ps',
c_args : [
# Needed for `persona.h`
'-DPRIVATE',
# From bsd/sys/event_private.h
'-Dkqueue_id_t=uint64_t'
],
install : true,
sources : [
'ps/fmt.c',
'ps/keyword.c',
'ps/nlist.c',
'ps/print.c',
'ps/ps.c',
'ps/tasks.c',
],
)
install_man('ps/ps.1')
executable(
'stty',
install : true,
sources : [
'stty/cchar.c',
'stty/gfmt.c',
'stty/key.c',
'stty/modes.c',
'stty/print.c',
'stty/stty.c',
'stty/util.c',
],
)
install_man('stty/stty.1')
executable(
'tabs',
dependencies : ncurses,
install : true,
sources : ['tabs/tabs.c'],
)
install_man('tabs/tabs.1')
executable(
'tty',
install : true,
sources : ['tty/tty.c'],
)
install_man('tty/tty.1')
executable(
'whois',
install : true,
sources : ['whois/whois.c'],
)
install_man('whois/whois.1')

View File

@@ -0,0 +1,86 @@
{
lib,
apple-sdk,
bison,
flex,
libxo,
mkAppleDerivation,
ncurses,
pkg-config,
stdenvNoCC,
}:
let
Libc = apple-sdk.sourceRelease "Libc";
libplatform = apple-sdk.sourceRelease "libplatform";
xnu = apple-sdk.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "adv_cmds-deps-private-headers";
buildCommand = ''
install -D -m644 -t "$out/include" \
'${libplatform}/private/_simple.h' \
'${Libc}/nls/FreeBSD/msgcat.h'
install -D -m644 -t "$out/include/System/sys" \
'${xnu}/bsd/sys/persona.h' \
'${xnu}/bsd/sys/proc.h'
'';
};
in
mkAppleDerivation {
releaseName = "adv_cmds";
outputs = [
"out"
"ps"
"man"
];
xcodeHash = "sha256-2p/JyMPw6acHphvzkaJXPXGwxCUEoxryCejww5kPHvQ=";
postPatch = ''
# Meson generators require using @BASENAME@ in the output.
substituteInPlace mklocale/lex.l \
--replace-fail y.tab.h yacc.tab.h
substituteInPlace genwrap/lex.l \
--replace-fail y.tab.h genwrap.tab.h
substituteInPlace colldef/scan.l \
--replace-fail y.tab.h parse.tab.h
find localedef -name '*.c' -exec sed -e 's/parser.h/parser.tab.h/' -i {} \;
# Fix paths to point to the store
for file in genwrap.c genwrap.8; do
substituteInPlace genwrap/$file \
--replace-fail '/usr/local' "$out"
done
'';
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
buildInputs = [
libxo
ncurses
];
nativeBuildInputs = [
bison
flex
pkg-config
];
postInstall = ''
moveToOutput bin/ps "$ps"
ln -s "$ps/bin/ps" "$out/bin/ps"
'';
meta = {
description = "Advanced commands package for Darwin";
license = [
lib.licenses.apsl10
lib.licenses.apsl20
];
};
}

View File

@@ -0,0 +1,25 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/basic_cmds/blob/main/basic_cmds.xcodeproj/project.pbxproj
# Project settings
project('basic_cmds', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
# Binaries
executable(
'mesg',
install : true,
sources : [ 'mesg/mesg.c' ],
)
install_man('mesg/mesg.1')
executable(
'write',
install : true,
sources : [ 'write/write.c' ],
)
install_man('write/write.1')

View File

@@ -0,0 +1,20 @@
{ lib, mkAppleDerivation }:
mkAppleDerivation {
releaseName = "basic_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-gT7kP/w23d5kGKgNPYS9ydCbeVaLwriMJj0BPIHgQ4U=";
meta = {
description = "Basic commands for Darwin";
license = [
lib.licenses.isc
lib.licenses.bsd3
];
};
}

View File

@@ -0,0 +1,61 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/bootstrap_cmds/blob/main/mig.xcodeproj/project.pbxproj
# Project settings
project('bootstrap_cmds', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
# Generators
bison_bin = find_program('bison', required : true)
flex_bin = find_program('flex', required : true)
bison = generator(
bison_bin,
arguments : ['@INPUT@', '--header=@OUTPUT0@', '--output=@OUTPUT1@'],
output : [ '@BASENAME@.tab.h', '@BASENAME@.tab.c'],
)
flex = generator(
flex_bin,
arguments : ['--header-file=@OUTPUT0@', '--outfile=@OUTPUT1@', '@INPUT@'],
output : ['@BASENAME@.yy.h', '@BASENAME@.yy.c'],
)
# Binaries
executable(
'migcom',
c_args: ['-DMIG_VERSION="migcom-@version@"'],
include_directories : 'migcom.tproj',
install : true,
install_dir : get_option('libexecdir'),
sources : [
'migcom.tproj/error.c',
'migcom.tproj/global.c',
# Redundant file thats not actually used. Trying to compile it results in compile errors.
# 'migcom.tproj/handler.c',
'migcom.tproj/header.c',
'migcom.tproj/mig.c',
'migcom.tproj/routine.c',
'migcom.tproj/server.c',
'migcom.tproj/statement.c',
'migcom.tproj/string.c',
'migcom.tproj/type.c',
'migcom.tproj/user.c',
'migcom.tproj/utils.c',
bison.process('migcom.tproj/parser.y'),
flex.process('migcom.tproj/lexxer.l'),
],
)
install_data(
'migcom.tproj/mig.sh',
install_dir : get_option('bindir'),
)
install_man(
'migcom.tproj/mig.1',
'migcom.tproj/migcom.1',
)

View File

@@ -0,0 +1,84 @@
{
lib,
apple-sdk,
apple-sdk_12,
bison,
buildPackages,
flex,
meson,
mkAppleDerivation,
replaceVars,
stdenv,
stdenvNoCC,
}:
let
Libc = apple-sdk.sourceRelease "Libc";
# Older versions of xnu are missing required headers. The one for the 11.3 SDK doesnt define a needed function
# that was added in 11.3. This version of xnu has everything thats needed.
xnu = apple-sdk_12.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "adv_cmds-deps-private-headers";
buildCommand = ''
install -D -t "$out/include/os" \
'${Libc}/os/assumes.h' \
'${xnu}/libkern/os/base_private.h'
'';
};
# bootstrap_cmds is used to build libkrb5, which is a transitive dependency of Meson due to OpenLDAP.
# This causes an infinite recursion unless Mesons tests are disabled.
mkAppleDerivation' = mkAppleDerivation.override {
meson = meson.overrideAttrs { doInstallCheck = false; };
};
in
mkAppleDerivation' {
releaseName = "bootstrap_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-N28WLkFo8fXiQqqpmRmOBE3BzqXHIy94fhZIxEkmOw4=";
xcodeProject = "mig.xcodeproj";
patches = [
# Make sure that `mig` in nixpkgs uses the correct clang
(replaceVars ./patches/0001-Specify-MIGCC-for-use-with-substitute.patch {
clang = "${lib.getBin buildPackages.targetPackages.clang}/bin/${buildPackages.targetPackages.clang.targetPrefix}clang";
})
# `mig` by default only removes the working directory at the end of the script.
# If an error happens, it is left behind. Always clean it up.
./patches/0002-Always-remove-working-directory.patch
];
postPatch = ''
# Fix the name to something Meson will like.
substituteInPlace migcom.tproj/lexxer.l \
--replace-fail 'y.tab.h' 'parser.tab.h'
'';
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
nativeBuildInputs = [
bison
flex
];
postInstall = ''
mv "$out/bin/mig.sh" "$out/bin/mig"
chmod a+x "$out/bin/mig"
patchShebangs --build "$out/bin/mig"
substituteInPlace "$out/bin/mig" \
--replace-fail 'arch=`/usr/bin/arch`' 'arch=${stdenv.targetPlatform.darwinArch}' \
--replace-fail '/usr/bin/mktemp' '${lib.getBin buildPackages.coreutils}/bin/mktemp' \
--replace-fail '/usr/bin/xcrun' '${buildPackages.xcbuild.xcrun}/bin/xcrun'
'';
meta.description = "Contains mig command for generating headers from definitions";
}

View File

@@ -0,0 +1,13 @@
diff --git a/migcom.tproj/mig.sh b/migcom.tproj/mig.sh
index 3f6b0b544a..f91f1a0112 100644
--- a/migcom.tproj/mig.sh
+++ b/migcom.tproj/mig.sh
@@ -47,6 +47,8 @@
# the rights to redistribute these changes.
#
+MIGCC=@clang@
+
realpath()
{
local FILE="$1"

View File

@@ -0,0 +1,19 @@
diff --git a/migcom.tproj/mig.sh b/migcom.tproj/mig.sh
index f91f1a0112..191eee0461 100644
--- a/migcom.tproj/mig.sh
+++ b/migcom.tproj/mig.sh
@@ -101,6 +101,7 @@
echo "Exiting..."
exit 1
fi
+trap 'rm -rf -- "$WORKTMP"' EXIT
# parse out the arguments until we hit plain file name(s)
@@ -232,6 +233,5 @@
rm -f "${temp}.c"
done
-/bin/rmdir "${WORKTMP}"
exit 0

View File

@@ -0,0 +1,38 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/copyfile/blob/main/copyfile.xcodeproj/project.pbxproj
# Project settings
project('copyfile', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
# Libraries
library(
'copyfile',
c_args : [
'-D__DARWIN_NOW_CANCELABLE=1',
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/clonefile.h#L35
'-DCLONE_ACL=0x0004',
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/kdebug.h#L691
'-DDBG_DECMP=0x12',
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/libkern/os/base.h#L129
'-DOS_FALLTHROUGH=__attribute__((__fallthrough__))',
],
install : true,
sources : [
'copyfile.c',
'xattr_flags.c',
],
)
install_headers(
'copyfile.h',
'xattr_flags.h',
'xattr_properties.h',
)
install_man(
'copyfile.3',
'xattr_name_with_flags.3',
)

View File

@@ -0,0 +1,86 @@
{
lib,
apple-sdk,
mkAppleDerivation,
stdenvNoCC,
}:
let
xnu = apple-sdk.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "copyfile-deps-private-headers";
buildCommand = ''
install -D -t "$out/include/Kernel/sys" \
'${xnu}/bsd/sys/decmpfs.h'
install -D -t "$out/include/System/sys" \
'${xnu}/bsd/sys/content_protection.h' \
'${xnu}/bsd/sys/fsctl.h'
substituteInPlace "$out/include/System/sys/content_protection.h" \
--replace-fail '#ifdef PRIVATE' '#if 1'
mkdir -p "$out/include/xpc"
cat <<EOF > "$out/include/xpc/private.h"
#pragma once
extern int _xpc_runtime_is_app_sandboxed();
EOF
# https://github.com/apple-oss-distributions/copyfile/blob/ed3f0a8bf8b6bac6838c92c297afcc826fec75f4/copyfile.c#L64-L74
cat <<EOF > "$out/include/quarantine.h"
#pragma once
typedef void* qtn_file_t;
#define QTN_SERIALIZED_DATA_MAX 4096
#define qtn_file_alloc _qtn_file_alloc
#define qtn_file_init_with_fd _qtn_file_init_with_fd
#define qtn_file_init_with_path _qtn_file_init_with_path
#define qtn_file_init_with_data _qtn_file_init_with_data
#define qtn_file_free _qtn_file_free
#define qtn_file_apply_to_fd _qtn_file_apply_to_fd
#define qtn_error _qtn_error
#define qtn_file_to_data _qtn_file_to_data
#define qtn_file_clone _qtn_file_clone
#define qtn_file_get_flags _qtn_file_get_flags
#define qtn_file_set_flags _qtn_file_set_flags
extern void * qtn_file_alloc(void);
extern int qtn_file_init_with_fd(void *x, int y);
extern int qtn_file_init_with_path(void *x, const char *path);
extern int qtn_file_init_with_data(void *x, const void *data, size_t len);
extern void qtn_file_free(void *);
extern int qtn_file_apply_to_fd(void *x, int y);
extern char *qtn_error(int x);
extern int qtn_file_to_data(void *x, char *y, size_t *z);
extern void *qtn_file_clone(void *x);
extern uint32_t qtn_file_get_flags(void *x);
extern int qtn_file_set_flags(void *x, uint32_t flags);
#define qtn_xattr_name "com.apple.quarantine"
#define QTN_FLAG_DO_NOT_TRANSLOCATE 0x100
EOF
'';
};
in
mkAppleDerivation {
releaseName = "copyfile";
outputs = [
"out"
"dev"
"man"
];
xcodeHash = "sha256-SYW6pBlCQkcbkBqCq+W/mDYZZ7/co2HlPZwXzgh/LnI=";
postPatch = ''
# Disable experimental bounds safety stuff thats not available in LLVM 16.
for header in copyfile.h xattr_flags.h; do
substituteInPlace "$header" \
--replace-fail '__ptrcheck_abi_assume_single()' "" \
--replace-fail '__unsafe_indexable' ""
done
'';
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
meta.description = "Darwin file copying library";
}

View File

@@ -0,0 +1,92 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/developer_cmds/blob/main/developer_cmds.xcodeproj/project.pbxproj
# Project settings
project('developer_cmds', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
# Binaries
executable(
'asa',
install : true,
sources : [ 'asa/asa.c' ],
)
install_man('asa/asa.1')
executable(
'ctags',
install : true,
sources : [
'ctags/C.c',
'ctags/ctags.c',
'ctags/fortran.c',
'ctags/lisp.c',
'ctags/print.c',
'ctags/tree.c',
'ctags/yacc.c',
],
)
install_man('ctags/ctags.1')
executable(
'indent',
install : true,
sources : [
'indent/args.c',
'indent/indent.c',
'indent/io.c',
'indent/lexi.c',
'indent/parse.c',
'indent/pr_comment.c',
],
)
install_man('indent/indent.1')
install_data(
'lorder/lorder.sh',
install_dir : get_option('bindir'),
install_mode : 'r-xr-xr-x',
rename : 'lorder'
)
install_man('lorder/lorder.1')
executable(
'rpcgen',
install : true,
sources : [
'rpcgen/rpc_clntout.c',
'rpcgen/rpc_cout.c',
'rpcgen/rpc_hout.c',
'rpcgen/rpc_main.c',
'rpcgen/rpc_parse.c',
'rpcgen/rpc_sample.c',
'rpcgen/rpc_scan.c',
'rpcgen/rpc_svcout.c',
'rpcgen/rpc_tblout.c',
'rpcgen/rpc_util.c',
],
)
install_man('rpcgen/rpcgen.1')
executable(
'unifdef',
install : true,
sources : [ 'unifdef/unifdef.c' ],
)
install_man('unifdef/unifdef.1')
install_data(
'unifdef/unifdefall.sh',
install_dir : get_option('bindir'),
install_mode : 'r-xr-xr-x',
rename : 'unifdefall',
)
install_symlink(
'unifdefall.1',
install_dir : get_option('mandir') / 'man1',
pointing_to : 'unifdef.1',
)

View File

@@ -0,0 +1,35 @@
{
lib,
clang,
mkAppleDerivation,
buildPackages,
shell_cmds,
}:
mkAppleDerivation {
releaseName = "developer_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-NurkF9AnPuaQ7Ev36PCknuTNV6z622yFi2bXZsow+xA=";
postPatch = ''
substituteInPlace rpcgen/rpc_main.c \
--replace-fail '/usr/bin/cpp' '${lib.getBin buildPackages.clang}/bin/${buildPackages.clang.targetPrefix}cpp'
'';
postInstall = ''
HOST_PATH='${lib.getBin shell_cmds}/bin' patchShebangs --host "$out/bin"
'';
meta = {
description = "Developer commands for Darwin";
license = [
lib.licenses.bsd3
lib.licenses.bsdOriginal
];
};
}

View File

@@ -0,0 +1,223 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/diskdev_cmds/blob/main/diskdev_cmds.xcodeproj/project.pbxproj
# Project settings
project('diskdev_cmds', 'c', 'objc', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
apfs = dependency('appleframeworks', modules : 'APFS')
removefile = cc.find_library('removefile')
# Static Libraries
libdisk = declare_dependency(
include_directories : 'disklib',
link_with : static_library(
'disk',
include_directories : 'disklib',
sources : [
'disklib/dkcksum.c',
'disklib/dkdisklabel.c',
'disklib/dkopen.c',
'disklib/dksecsize.c',
'disklib/fskit_support.m',
'disklib/preen.c',
'disklib/vfslist.c',
],
),
)
# Binaries
# Note: newfs_fskit and fsck_fskit require private entitlements. They are not built.
executable(
'dev_mkdb',
install : true,
sources : [ 'dev_mkdb.tproj/dev_mkdb.c' ],
)
install_man('dev_mkdb.tproj/dev_mkdb.8')
executable(
'dirs_cleaner',
dependencies : [ removefile ],
install : true,
install_dir : get_option('libexecdir'),
sources : [ 'dirs_cleaner/dirs_cleaner.c' ],
)
install_man('dirs_cleaner/dirs_cleaner.8')
executable(
'edquota',
dependencies : [ libdisk ],
install : true,
sources : [ 'edquota.tproj/edquota.c' ],
)
install_man('edquota.tproj/edquota.8')
executable(
'fdisk',
install : true,
sources : [
'fdisk.tproj/auto.c',
'fdisk.tproj/cmd.c',
'fdisk.tproj/disk.c',
'fdisk.tproj/fdisk.c',
'fdisk.tproj/getrawpartition.c',
'fdisk.tproj/mbr.c',
'fdisk.tproj/misc.c',
'fdisk.tproj/opendev.c',
'fdisk.tproj/part.c',
'fdisk.tproj/user.c',
],
)
install_man('fdisk.tproj/fdisk.8')
executable(
'fsck',
include_directories : [ 'edt_fstab', 'fsck.tproj' ],
install : true,
sources : [
'edt_fstab/edt_fstab.c',
'fsck.tproj/fsck.c',
],
)
install_man('fsck.tproj/fsck.8')
foreach fstyp : [ 'fstyp', 'fstyp_msdos', 'fstyp_ntfs', 'fstyp_udf' ]
executable(
f'@fstyp@',
install : true,
sources : [ f'fstyp.tproj/@fstyp@.c' ],
)
install_man(f'fstyp.tproj/@fstyp@.8')
endforeach
install_man('fuser.tproj/fuser.1')
executable(
'mount',
c_args : [
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/mount.h#L107
'-DMNT_EXT_ROOT_DATA_VOL=0x00000001',
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/mount.h#L108
'-DMNT_EXT_FSKIT=0x00000002',
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/mount.h#L337
'-DMNT_NOFOLLOW=0x08000000',
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/mount.h#L340
'-DMNT_STRICTATIME=0x80000000',
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/attr.h#L300
'-DVOL_CAP_FMT_SEALED=0x02000000',
],
dependencies : [ apfs, libdisk ],
include_directories : [ 'edt_fstab', 'fsck.tproj', 'mount_flags_dir' ],
install : true,
link_args : host_machine.cpu_family() == 'x86_64' ? [ '-Wl,-undefined,dynamic_lookup' ] : [ ],
sources : [
'edt_fstab/edt_fstab.c',
'mount.tproj/mount.c',
'mount.tproj/mount_tmpfs.c',
'mount_flags_dir/mount_flags.c',
],
)
install_man(
'mount.tproj/fstab.5',
'mount.tproj/mount.8',
)
# executable(
# 'mount_devfs',
# install : true,
# sources : [ 'mount_devfs.tproj/mount_devfs.c' ],
# )
# executable(
# 'mount_fdesc',
# install : true,
# sources : [ 'mount_fdesc.tproj/mount_fdesc.c' ],
# )
# install_man('mount_fdesc.tproj/mount_fdesc.8')
executable(
'quota',
install : true,
sources : [ 'quota.tproj/quota.c' ],
)
install_man('quota.tproj/quota.1')
executable(
'quotacheck',
dependencies : [ libdisk ],
install : true,
sources : [
'quotacheck.tproj/hfs_quotacheck.c',
'quotacheck.tproj/quotacheck.c',
],
)
install_man('quotacheck.tproj/quotacheck.8')
executable(
'quotaon',
install : true,
sources : [ 'quotaon.tproj/quotaon.c' ],
)
install_man('quotaon.tproj/quotaon.8')
install_symlink(
'quotaoff',
install_dir : get_option('bindir'),
pointing_to : 'quotaon',
)
executable(
'repquota',
install : true,
sources : [ 'repquota.tproj/repquota.c' ],
)
install_man('repquota.tproj/repquota.8')
executable(
'setclass',
install : true,
sources : [ 'setclass.tproj/setclass.c' ],
)
install_man('setclass.tproj/setclass.8')
# tmp_cleaner
install_man('tmp_cleaner/tmp_cleaner.8')
executable(
'umount',
dependencies : [ libdisk ],
include_directories : 'edt_fstab',
install : true,
sources : [
'edt_fstab/edt_fstab.c',
'umount.tproj/umount.c',
],
)
install_man('umount.tproj/umount.8')
executable(
'vsdbutil',
c_args : [
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/mount.h#L107
'-DMNT_EXT_ROOT_DATA_VOL=0x00000001',
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/mount.h#L108
'-DMNT_EXT_FSKIT=0x00000002',
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/mount.h#L337
'-DMNT_NOFOLLOW=0x08000000',
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/mount.h#L340
'-DMNT_STRICTATIME=0x80000000',
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/attr.h#L300
'-DVOL_CAP_FMT_SEALED=0x02000000',
],
dependencies : [ apfs ],
install : true,
sources : [
'mount_flags_dir/mount_flags.c',
'vsdbutil.tproj/vsdbutil_main.c',
],
)
install_man('vsdbutil.tproj/vsdbutil.8')

View File

@@ -0,0 +1,68 @@
{
lib,
apple-sdk,
libutil,
mkAppleDerivation,
removefile,
stdenvNoCC,
}:
let
Libc = apple-sdk.sourceRelease "Libc";
xnu = apple-sdk.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "diskdev_cmds-deps-private-headers";
buildCommand = ''
for dir in arm i386 machine sys; do
install -D -t "$out/include/$dir" '${xnu}'"/bsd/$dir/disklabel.h"
done
install -D -t "$out/include/os" \
'${Libc}/os/api.h' \
'${Libc}/os/variant_private.h' \
'${Libc}/libdarwin/h/bsd.h' \
'${Libc}/libdarwin/h/errno.h'
install -D -t "$out/include/System/sys" \
'${xnu}/bsd/sys/fsctl.h' \
'${xnu}/bsd/sys/reason.h'
install -D -t "$out/include/System/uuid" \
'${Libc}/uuid/namespace.h'
mkdir -p "$out/include/APFS"
touch "$out/include/APFS/APFS.h"
touch "$out/include/APFS/APFSConstants.h"
substituteInPlace "$out/include/os/variant_private.h" \
--replace-fail ', bridgeos(4.0)' "" \
--replace-fail ', bridgeos' ""
'';
};
in
mkAppleDerivation {
releaseName = "diskdev_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-P2dg3B5pU2ayasMHIM5nI0iG+YDdYQNcEpnJzZxm1kw=";
postPatch =
# Fix incompatible pointer to integer conversion. The last parameter is size_t not a pointer.
# https://developer.apple.com/documentation/kernel/1387446-sysctlbyname
''
substituteInPlace mount.tproj/mount.c \
--replace-fail 'sysctlbyname ("vfs.generic.apfs.rosp", &is_rosp, &rospsize, NULL, NULL);' 'sysctlbyname ("vfs.generic.apfs.rosp", &is_rosp, &rospsize, NULL, 0);'
'';
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
buildInputs = [
apple-sdk.privateFrameworksHook
libutil
removefile
];
meta.description = "Disk commands for Darwin";
}

View File

@@ -0,0 +1,31 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/doc_cmds/blob/main/doc_cmds.xcodeproj/project.pbxproj
# Project settings
project('doc_cmds', 'c', version : '@version@')
add_global_arguments('-D__FBSDID=__RCSID', language : 'c')
# Dependencies
cc = meson.get_compiler('c')
zlib = dependency('zlib')
# Binaries
executable(
'makewhatis',
dependencies : [ zlib ],
install : true,
install_dir : get_option('libexecdir'),
sources : [ 'makewhatis/makewhatis.c' ],
)
install_man('makewhatis/makewhatis.8')
install_data(
'makewhatis/makewhatis.local.sh',
install_dir : get_option('libexecdir'),
install_mode : 'r-xr-xr-x',
rename : 'makewhatis.local'
)
install_man('makewhatis/makewhatis.local.8')

View File

@@ -0,0 +1,33 @@
{
lib,
mkAppleDerivation,
pkg-config,
shell_cmds,
zlib,
}:
mkAppleDerivation {
releaseName = "doc_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-7/ADsfXTKqQhgratg2Twj7JgfFV0/U9rEvtsnX+NFPw=";
nativeBuildInputs = [ pkg-config ];
buildInputs = [ zlib ];
postInstall = ''
HOST_PATH='${lib.getBin shell_cmds}/bin' patchShebangs --host "$out/libexec"
'';
meta = {
description = "makewhatis commands for Darwin";
license = [
lib.licenses.bsd2
lib.licenses.bsd3
];
};
}

View File

@@ -0,0 +1,205 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/dyld/blob/main/dyld.xcodeproj/project.pbxproj
# Project settings
project(
'dyld',
'c', 'cpp',
default_options : { 'cpp_std': 'c++20' },
version : '@version@'
)
add_project_arguments(
# Prevent build failures due to these targets not being defined
'-DTARGET_OS_BRIDGE=0',
'-DTARGET_OS_EXCLAVEKIT=0',
# Enable support for arm64 variants
'-DSUPPORT_ARCH_arm64e=1',
'-DSUPPORT_ARCH_arm64_32=1',
# Per base.xcconfig
'-Wmost',
'-Wimplicit-fallthrough',
'-Wno-unknown-pragmas',
'-Wno-assume',
'-Wformat-nonliteral',
'-Wno-vla-extension',
'-Wundef-prefix=SUPPORT_',
language : [ 'c', 'cpp' ],
)
# Dependencies
cc = meson.get_compiler('c')
cxx = meson.get_compiler('cpp')
llvm_dep = dependency('llvm')
openssl_dep = dependency('openssl', version : '>=3.0')
common_inc = [
'common',
'dyld',
'include',
'mach_o',
]
# Internal dependencies
corecrypto = static_library(
'corecrypto',
include_directories : [
common_inc,
'compat',
],
sources : [
'compat/corecrypto/ccdigest.c',
'compat/corecrypto/ccsha1.c',
'compat/corecrypto/ccsha2.c',
],
)
corecrypto_dep = declare_dependency(
dependencies : [ openssl_dep ],
include_directories : 'compat',
link_with : corecrypto,
)
lsl = static_library(
'lsl',
cpp_args : [
# Required for `_COMM_PAGE_CPU_CAPABILITIES64` in <System/machine/cpu_capabilities.h>
'-DPRIVATE',
],
include_directories : [
common_inc,
'cache-builder',
'cache_builder',
'libdyld',
'lsl',
],
sources : [
'lsl/Allocator.cpp',
'lsl/CRC32c.cpp',
'lsl/PVLEInt64.cpp',
],
)
lsl_dep = declare_dependency(
include_directories : [ 'lsl' ],
link_with : lsl,
)
# These files need to be built with `BUILDING_LIBDYLD` not `BUILDING_DYLDINFO`.
# `dyld_info` cant just link against `libdyld` because the symbols it needs are not publicly exported.
# Building `libdyld` as a static archive doesnt work because it results in internal error when linking with ld64.
libminidyld = static_library(
'minidyld',
cpp_args : [
# Required for `openbyid_np` in <System/sys/fsgetpath.h>
'-DPRIVATE',
'-DBUILDING_LIBDYLD=1',
],
dependencies : [ corecrypto_dep, lsl_dep ],
include_directories : [
common_inc,
'cache-builder',
'cache_builder',
'libdyld',
'libdyld_introspection',
],
sources : [
'common/CachePatching.cpp',
'common/MachOLayout.cpp',
'common/MachOLoaded.cpp',
'libdyld/CrashReporterAnnotations.c',
'mach_o/ChainedFixups.cpp',
'mach_o/GradedArchitectures.cpp',
],
)
libdsc_extractor = shared_library(
'dsc_extractor',
cpp_args : [ '-DBUILDING_SHARED_CACHE_EXTRACTOR=1' ],
dependencies : [ corecrypto_dep, lsl_dep ],
include_directories : [
common_inc,
'cache-builder',
'cache_builder',
],
install : true,
link_args : [ '-Wl,-exported_symbol,_dyld_shared_cache_extract_dylibs_progress' ],
link_with : [ libminidyld ],
name_prefix : '',
name_suffix : 'bundle',
sources : [
'common/DyldSharedCache.cpp',
'common/MachOFile.cpp',
'other-tools/dsc_extractor.cpp',
'other-tools/dsc_iterator.cpp',
'common/MachOLayout.cpp',
'common/Diagnostics.cpp',
],
)
# Binaries
executable(
'dsc_extractor',
install : true,
link_args : [ '-Wl,-exported_symbol,_dyld_shared_cache_extract_dylibs_progress' ],
link_with : [ libdsc_extractor ],
sources : [ 'other-tools/dsc_extractor_bin.cpp' ],
)
executable(
'dyld_info',
cpp_args : [
'-DBUILDING_DYLDINFO=1',
'-DBUILDING_FOR_TOOLCHAIN=1',
],
dependencies : [
corecrypto_dep,
llvm_dep,
lsl_dep,
],
include_directories : [
common_inc,
'cache-builder',
'cache_builder',
],
install : true,
link_args : [ '-Wl,-weak-lLTO' ],
link_with : [ libminidyld ],
sources : [
'cache-builder/FileUtils.cpp',
'common/Diagnostics.cpp',
'common/DyldSharedCache.cpp',
'common/MachOAnalyzer.cpp',
'common/MachOFile.cpp',
'common/MetadataVisitor.cpp',
'common/SwiftVisitor.cpp',
'mach_o/Architecture.cpp',
'mach_o/Archive.cpp',
'mach_o/BindOpcodes.cpp',
'mach_o/ChainedFixups.cpp',
'mach_o/CompactUnwind.cpp',
'mach_o/Error.cpp',
'mach_o/ExportsTrie.cpp',
'mach_o/Fixups.cpp',
'mach_o/FunctionStarts.cpp',
'mach_o/Header.cpp',
'mach_o/Image.cpp',
'mach_o/Instructions.cpp',
'mach_o/LoggingStub.cpp',
'mach_o/Misc.cpp',
'mach_o/NListSymbolTable.cpp',
'mach_o/ObjC.cpp',
'mach_o/Platform.cpp',
'mach_o/Policy.cpp',
'mach_o/RebaseOpcodes.cpp',
'mach_o/SplitSeg.cpp',
'mach_o/Symbol.cpp',
'mach_o/Universal.cpp',
'mach_o/Version32.cpp',
'mach_o/Version64.cpp',
'other-tools/dyld_info.cpp',
],
)
install_man('doc/man/man1/dyld_info.1')

View File

@@ -0,0 +1,171 @@
{
lib,
apple-sdk_12,
ld64,
mkAppleDerivation,
cmake,
llvmPackages,
openssl,
pkg-config,
stdenvNoCC,
fetchurl,
}:
let
# libdyld needs CrashReporterClient.h, which is hard to find, but WebKit2 has it.
# Fetch it directly because the Darwin stdenv bootstrap cant depend on fetchgit.
crashreporter_h = fetchurl {
url = "https://raw.githubusercontent.com/apple-oss-distributions/WebKit2/WebKit2-7605.1.33.0.2/Platform/spi/Cocoa/CrashReporterClientSPI.h";
hash = "sha256-0ybVcwHuGEdThv0PPjYQc3SW0YVOyrM3/L9zG/l1Vtk=";
};
launchd = apple-sdk_12.sourceRelease "launchd";
Libc = apple-sdk_12.sourceRelease "Libc";
libplatform = apple-sdk_12.sourceRelease "libplatform";
libpthread = apple-sdk_12.sourceRelease "libpthread";
xnu = apple-sdk_12.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "dyld-deps-private-headers";
buildCommand = ''
mkdir -p "$out/include/System"
for dir in arm i386 machine; do
mkdir -p "$out/include/$dir"
for file in '${xnu}/osfmk/'$dir/*; do
name=$(basename "$file")
# Skip copying `endian.h` because it conflicts with the SDK, breaking the build on x86_64-darwin.
test "$name" != endian.h && cp -r "$file" "$out/include/$dir/$name"
done
ln -s "$out/include/$dir" "$out/include/System/$dir"
done
install -D -m644 -t "$out/include/System" \
'${Libc}/stdlib/FreeBSD/atexit.h'
mkdir -p "$out/include/System/sys"
substitute '${xnu}/bsd/sys/fsgetpath.h' "$out/include/System/sys/fsgetpath.h" \
--replace-fail '#ifdef __APPLE_API_PRIVATE' '#if 1'
install -D -m644 -t "$out/include" \
'${libplatform}/private/_simple.h' \
'${Libc}/darwin/libc_private.h' \
'${Libc}/darwin/subsystem.h' \
'${ld64.src}/src/ld/cs_blobs.h' \
'${launchd}/liblaunch/vproc_priv.h'
substitute '${crashreporter_h}' "$out/include/CrashReporterClient.h" \
--replace-fail 'USE(APPLE_INTERNAL_SDK)' '1' \
--replace-fail '#import <CrashReporterClient.h>' '#include <stdint.h>' \
--replace-fail '#else' '#define CRSetCrashLogMessage2 CRSetCrashLogMessage'
install -D -m644 -t "$out/include/pthread" \
'${libpthread}/private/pthread/spinlock_private.h' \
'${libpthread}/private/pthread/tsd_private.h'
install -D -m644 -t "$out/include/os" \
'${xnu}/libsyscall/os/tsd.h' \
'${xnu}/libkern/os/atomic_private.h' \
'${xnu}/libkern/os/atomic_private_arch.h' \
'${xnu}/libkern/os/atomic_private_impl.h' \
'${xnu}/libkern/os/base_private.h' \
'${libplatform}/private/os/lock_private.h'
substituteInPlace "$out/include/os/lock_private.h" \
--replace-fail ', bridgeos(4.0)' ""
# This file is part of ld-prime, which is unhelpfully not included in the dyld source release.
# Fortunately, nothing in it is actually needed to build `dyld_info` and `dsc_extractor`.
touch "$out/include/File.h"
'';
};
in
mkAppleDerivation {
releaseName = "dyld";
outputs = [
"out"
"lib"
"man"
];
propagatedBuildOutputs = [ ];
xcodeHash = "sha256-NfaENSF699xjc+eKtOm1RyXUCMD6xTaJ5+9arLllqyw=";
patches = [
# Disable use of private kdebug API
./patches/0001-Disable-kdebug-trace.patch
# dyld_info requires `startsWith`, but its not normally built for `dyld_info`.
./patches/0002-Provide-startsWith-for-dyld_info.patch
# dyld_info tries to weakly link against libLTO using this macro.
./patches/0003-Add-weaklinking_h.patch
# The LLVMOpInfoCallback args comment out one of the args. Fix that for compatibility with nixpkgs LLVM.
./patches/0004-Fix-llvm-op-info-callback-args.patch
# Some private headers depend on corecrypto, which we cant use.
# Use the headers from the ld64 port, which delegates to OpenSSL.
./patches/0005-Add-OpenSSL-based-CoreCrypto-digest-functions.patch
# `dsc_extractor` builds a dylib, but it includes a program that can perform cache extraction.
# This extracts just the driver into a file to make building the actual program easier.
./patches/0006-Add-dsc_extractor_bin_cpp.patch
];
postPatch = ''
substituteInPlace include/mach-o/dyld.h \
--replace-fail '#ifdef __DRIVERKIT_19_0' "#if 0" \
--replace-fail ', bridgeos(5.0)' "" \
--replace-fail 'DYLD_EXCLAVEKIT_UNAVAILABLE' "" \
--replace-fail '__API_UNAVAILABLE(ios, tvos, watchos) __API_UNAVAILABLE(bridgeos)' ""
substituteInPlace include/mach-o/dyld_priv.h \
--replace-fail ', bridgeos(3.0)' ""
substituteInPlace include/mach-o/dyld_process_info.h \
--replace-fail '__API_UNAVAILABLE(ios, tvos, watchos) __API_UNAVAILABLE(bridgeos)' ""
substituteInPlace include/mach-o/utils_priv.h \
--replace-fail 'SPI_AVAILABLE(macos(15.0), ios(18.0), tvos(18.0), watchos(11.0))' ""
substituteInPlace libdyld/utils.cpp \
--replace-fail 'DYLD_EXCLAVEKIT_UNAVAILABLE' ""
cat <<EOF > libdyld/CrashReporterAnnotations.c
#include <CrashReporterClient.h>
struct crashreporter_annotations_t gCRAnnotations
__attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION)))
= { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 };
EOF
# Fix header includes
substituteInPlace libdyld_introspection/dyld_introspection.cpp \
--replace-fail 'dyld_introspection.h' 'mach-o/dyld_introspection.h'
substituteInPlace dyld/Loader.h \
--replace-fail 'dyld_priv.h' 'mach-o/dyld_priv.h'
# Remove unused header include (since the compat shims dont provide it).
substituteInPlace other-tools/dsc_extractor.cpp \
--replace-fail '#include <CommonCrypto/CommonHMAC.h>' ""
# Specify path to `dsc_extractor.bundle` for `dlopen`
substituteInPlace other-tools/dsc_extractor_bin.cpp \
--subst-var lib
'';
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
buildInputs = [
apple-sdk_12 # Needed for `PLATFORM_FIRMWARE` and `PLATFORM_SEPOS` defines in `mach-o/loader.h`.
llvmPackages.llvm
openssl
];
nativeBuildInputs = [
cmake # CMake is required for Meson to find LLVM as a dependency.
pkg-config
];
dontUseCmakeConfigure = true;
meta.description = "Dyld-related commands for Darwin";
}

View File

@@ -0,0 +1,108 @@
diff --git a/dyld/Tracing.h b/dyld/Tracing.h
index 1e6e3027d9..bac62cf72d 100644
--- a/dyld/Tracing.h
+++ b/dyld/Tracing.h
@@ -31,29 +31,25 @@
#include <mach-o/loader.h>
#include <TargetConditionals.h>
#include "Defines.h"
-#if TARGET_OS_EXCLAVEKIT
- #define KDBG_CODE(a, b, c) (c)
- #define DBG_DYLD_UUID (5)
- #define DBG_DYLD_UUID_MAP_A (0)
- #define DBG_DYLD_UUID_MAP_B (1)
- #define DBG_DYLD_UUID_MAP_32_A (2)
- #define DBG_DYLD_UUID_MAP_32_B (3)
- #define DBG_DYLD_UUID_MAP_32_C (4)
- #define DBG_DYLD_UUID_UNMAP_A (5)
- #define DBG_DYLD_UUID_UNMAP_B (6)
- #define DBG_DYLD_UUID_UNMAP_32_A (7)
- #define DBG_DYLD_UUID_UNMAP_32_B (8)
- #define DBG_DYLD_UUID_UNMAP_32_C (9)
- #define DBG_DYLD_UUID_SHARED_CACHE_A (10)
- #define DBG_DYLD_UUID_SHARED_CACHE_B (11)
- #define DBG_DYLD_UUID_SHARED_CACHE_32_A (12)
- #define DBG_DYLD_UUID_SHARED_CACHE_32_B (13)
- #define DBG_DYLD_UUID_SHARED_CACHE_32_C (14)
- #define DBG_DYLD_AOT_UUID_MAP_A (15)
- #define DBG_DYLD_AOT_UUID_MAP_B (16)
-#else
- #include <sys/kdebug_private.h>
-#endif
+#define KDBG_CODE(a, b, c) (c)
+#define DBG_DYLD_UUID (5)
+#define DBG_DYLD_UUID_MAP_A (0)
+#define DBG_DYLD_UUID_MAP_B (1)
+#define DBG_DYLD_UUID_MAP_32_A (2)
+#define DBG_DYLD_UUID_MAP_32_B (3)
+#define DBG_DYLD_UUID_MAP_32_C (4)
+#define DBG_DYLD_UUID_UNMAP_A (5)
+#define DBG_DYLD_UUID_UNMAP_B (6)
+#define DBG_DYLD_UUID_UNMAP_32_A (7)
+#define DBG_DYLD_UUID_UNMAP_32_B (8)
+#define DBG_DYLD_UUID_UNMAP_32_C (9)
+#define DBG_DYLD_UUID_SHARED_CACHE_A (10)
+#define DBG_DYLD_UUID_SHARED_CACHE_B (11)
+#define DBG_DYLD_UUID_SHARED_CACHE_32_A (12)
+#define DBG_DYLD_UUID_SHARED_CACHE_32_B (13)
+#define DBG_DYLD_UUID_SHARED_CACHE_32_C (14)
+#define DBG_DYLD_AOT_UUID_MAP_A (15)
+#define DBG_DYLD_AOT_UUID_MAP_B (16)
#include "Defines.h"
@@ -111,24 +107,10 @@
uint64_t value() const { return _value; }
private:
void prepare(uint32_t code) {
-#if !TARGET_OS_EXCLAVEKIT
- if (_str) {
- _value = kdebug_trace_string(code, 0, _str);
- if (_value == (uint64_t)-1) _value = 0;
- }
-#endif
}
void destroy(uint32_t code) {
-#if !TARGET_OS_EXCLAVEKIT
- if (_str && _value) {
- kdebug_trace_string(code, _value, nullptr);
- }
-#endif
}
friend class ScopedTimer;
- friend uint64_t kdebug_trace_dyld_duration_start(uint32_t code, kt_arg data1, kt_arg data2, kt_arg data3);
- friend void kdebug_trace_dyld_duration_end(uint64_t pair_id, uint32_t code, kt_arg data4, kt_arg data5, kt_arg data6);
- friend void kdebug_trace_dyld_marker(uint32_t code, kt_arg data1, kt_arg data2, kt_arg data3, kt_arg data4);
uint64_t _value;
const char* _str;
};
@@ -168,29 +150,6 @@
uint64_t current_trace_id = 0;
};
-#if !TARGET_OS_EXCLAVEKIT
-VIS_HIDDEN
-void kdebug_trace_dyld_image(const uint32_t code, const char* path, const uuid_t* uuid_bytes,
- const fsobj_id_t fsobjid, const fsid_t fsid, const void* load_addr,
- uint32_t cpusubtype);
-#endif
-
-VIS_HIDDEN
-void kdebug_trace_dyld_cache(uint64_t fsobjid, uint64_t fsid, uint64_t sharedCacheBaseAddress,
- const uint8_t sharedCacheUUID[16]);
-
-VIS_HIDDEN
-bool kdebug_trace_dyld_enabled(uint32_t code);
-
-VIS_HIDDEN
-void kdebug_trace_dyld_marker(uint32_t code, kt_arg data1, kt_arg data2, kt_arg data3, kt_arg data4);
-
-VIS_HIDDEN
-uint64_t kdebug_trace_dyld_duration_start(uint32_t code, kt_arg data1, kt_arg data2, kt_arg data3);
-
-VIS_HIDDEN
-void kdebug_trace_dyld_duration_end(uint64_t trace_id, uint32_t code, kt_arg data4, kt_arg data5, kt_arg data6);
-
VIS_HIDDEN
void syntheticBacktrace(const char *reason, bool enableExternally=false);

View File

@@ -0,0 +1,20 @@
diff --git a/common/MachOFile.cpp b/common/MachOFile.cpp
index 3e7b95bcfe..265ae7c475 100644
--- a/common/MachOFile.cpp
+++ b/common/MachOFile.cpp
@@ -2493,7 +2493,14 @@
}
#endif // BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO
-#if BUILDING_CACHE_BUILDER || BUILDING_CACHE_BUILDER_UNIT_TESTS
+#if BUILDING_DYLDINFO || BUILDING_CACHE_BUILDER || BUILDING_CACHE_BUILDER_UNIT_TESTS
+
+#if BUILDING_DYLDINFO
+static bool startsWith(const char* buffer, const char* valueToFind) {
+ return strncmp(buffer, valueToFind, strlen(valueToFind)) == 0;
+}
+#endif
+
static bool platformExcludesPrebuiltClosure_macOS(const char* path) {
// We no longer support ROSP, so skip all paths which start with the special prefix
if ( startsWith(path, "/System/Library/Templates/Data/") )

View File

@@ -0,0 +1,34 @@
diff --git a/include/SoftLinking/WeakLinking.h b/include/SoftLinking/WeakLinking.h
new file mode 100644
index 0000000000..82755e2a43
--- /dev/null
+++ b/include/SoftLinking/WeakLinking.h
@@ -1,0 +1,28 @@
+/*
+ * Copyright (C) 2017 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#define WEAK_LINK_FORCE_IMPORT(sym) extern __attribute__((weak_import)) __typeof__(sym) sym

View File

@@ -0,0 +1,13 @@
diff --git a/other-tools/dyld_info.cpp b/other-tools/dyld_info.cpp
index 2de4978ba5..2ce27257d9 100644
--- a/other-tools/dyld_info.cpp
+++ b/other-tools/dyld_info.cpp
@@ -991,7 +991,7 @@
return ((SymbolicatedImage*)di)->lookupSymbol(referencePC, referenceValue, *referenceType, *referenceName);
}
-static int printDumpOpInfoCallback(void* di, uint64_t pc, uint64_t offset, uint64_t opSize, /* uint64_t instSize, */
+static int printDumpOpInfoCallback(void* di, uint64_t pc, uint64_t offset, uint64_t opSize, uint64_t instSize,
int tagType, void* tagBuf)
{
return ((SymbolicatedImage*)di)->opInfo(pc, offset, opSize, tagType, tagBuf);

View File

@@ -0,0 +1,370 @@
From 36767c7345161baf0ab125f95c8557f8e24f25db Mon Sep 17 00:00:00 2001
From: Randy Eckenrode <randy@largeandhighquality.com>
Date: Tue, 9 Apr 2024 19:28:17 -0400
Subject: [PATCH 7/8] Add OpenSSL-based CoreCrypto digest functions
---
compat/CommonCrypto/CommonDigest.h | 6 +++
compat/CommonCrypto/CommonDigestSPI.c | 21 +++++++++++
compat/CommonCrypto/CommonDigestSPI.h | 14 +++++++
compat/corecrypto/api_defines.h | 10 +++++
compat/corecrypto/ccdigest.c | 53 +++++++++++++++++++++++++++
compat/corecrypto/ccdigest.h | 27 ++++++++++++++
compat/corecrypto/ccdigest_private.h | 19 ++++++++++
compat/corecrypto/ccsha1.c | 22 +++++++++++
compat/corecrypto/ccsha1.h | 9 +++++
compat/corecrypto/ccsha2.c | 22 +++++++++++
compat/corecrypto/ccsha2.h | 9 +++++
11 files changed, 212 insertions(+)
create mode 100644 compat/CommonCrypto/CommonDigest.h
create mode 100644 compat/CommonCrypto/CommonDigestSPI.c
create mode 100644 compat/CommonCrypto/CommonDigestSPI.h
create mode 100644 compat/corecrypto/api_defines.h
create mode 100644 compat/corecrypto/ccdigest.c
create mode 100644 compat/corecrypto/ccdigest.h
create mode 100644 compat/corecrypto/ccdigest_private.h
create mode 100644 compat/corecrypto/ccsha1.c
create mode 100644 compat/corecrypto/ccsha1.h
create mode 100644 compat/corecrypto/ccsha2.c
create mode 100644 compat/corecrypto/ccsha2.h
diff --git a/compat/CommonCrypto/CommonDigest.h b/compat/CommonCrypto/CommonDigest.h
new file mode 100644
index 0000000..a60eba7
--- /dev/null
+++ b/compat/CommonCrypto/CommonDigest.h
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
diff --git a/compat/CommonCrypto/CommonDigestSPI.c b/compat/CommonCrypto/CommonDigestSPI.c
new file mode 100644
index 0000000..41269fc
--- /dev/null
+++ b/compat/CommonCrypto/CommonDigestSPI.c
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#include "CommonDigestSPI.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <corecrypto/ccsha2.h>
+
+void CCDigest(int type, const uint8_t* bytes, size_t count, uint8_t* digest) {
+ if (type != kCCDigestSHA256) {
+ abort();
+ }
+ const struct ccdigest_info* di = ccsha256_di();
+
+ ccdigest_di_decl(_di, ctx);
+ ccdigest_init(di, ctx);
+ ccdigest_update(di, ctx, count, bytes);
+ ccdigest_final(di, ctx, digest);
+}
diff --git a/compat/CommonCrypto/CommonDigestSPI.h b/compat/CommonCrypto/CommonDigestSPI.h
new file mode 100644
index 0000000..172742a
--- /dev/null
+++ b/compat/CommonCrypto/CommonDigestSPI.h
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#include <stdint.h>
+
+#include <corecrypto/ccdigest.h>
+#include <CodeSigningTypes.h>
+
+
+#define kCCDigestNone 0
+#define kCCDigestSHA1 8
+#define kCCDigestSHA256 10
+
+EXTERN_C void CCDigest(int type, const uint8_t* bytes, size_t count, uint8_t* digest);
diff --git a/compat/corecrypto/api_defines.h b/compat/corecrypto/api_defines.h
new file mode 100644
index 0000000..13d1e7a
--- /dev/null
+++ b/compat/corecrypto/api_defines.h
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#ifdef __cplusplus
+#define EXTERN_C extern "C"
+#else
+#define EXTERN_C
+#endif
diff --git a/compat/corecrypto/ccdigest.c b/compat/corecrypto/ccdigest.c
new file mode 100644
index 0000000..e29dcb8
--- /dev/null
+++ b/compat/corecrypto/ccdigest.c
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#include "ccdigest.h"
+#include "ccdigest_private.h"
+
+#include <stdlib.h>
+
+#include <openssl/err.h>
+
+
+struct ccdigest_context* _ccdigest_context_new(void)
+{
+ struct ccdigest_context* ctx = malloc(sizeof(struct ccdigest_context));
+ ctx->context = EVP_MD_CTX_new();
+ return ctx;
+}
+
+struct ccdigest_info* _ccdigest_newprovider(const char* name)
+{
+ struct ccdigest_info* di = malloc(sizeof(struct ccdigest_info));
+ di->provider = EVP_MD_fetch(NULL, name, NULL);
+ return di;
+}
+
+void ccdigest_init(const struct ccdigest_info* di, struct ccdigest_context* ctx)
+{
+ if (!EVP_DigestInit_ex2(ctx->context, di->provider, NULL)) {
+ ERR_print_errors_fp(stderr);
+ abort();
+ }
+}
+
+void ccdigest_update(
+ const struct ccdigest_info* _di,
+ struct ccdigest_context* ctx,
+ size_t count,
+ const void* bytes
+)
+{
+ if (!EVP_DigestUpdate(ctx->context, bytes, count)) {
+ ERR_print_errors_fp(stderr);
+ abort();
+ }
+}
+
+void ccdigest_final(const struct ccdigest_info* _di, struct ccdigest_context* ctx, uint8_t* digest)
+{
+ if (!EVP_DigestFinal_ex(ctx->context, digest, NULL)) {
+ ERR_print_errors_fp(stderr);
+ abort();
+ }
+}
diff --git a/compat/corecrypto/ccdigest.h b/compat/corecrypto/ccdigest.h
new file mode 100644
index 0000000..9af2394
--- /dev/null
+++ b/compat/corecrypto/ccdigest.h
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "api_defines.h"
+
+
+struct ccdigest_info;
+struct ccdigest_context;
+
+EXTERN_C struct ccdigest_context* _ccdigest_context_new(void);
+
+#define ccdigest_di_decl(_di, ctxvar) \
+ struct ccdigest_context* (ctxvar) = _ccdigest_context_new()
+
+EXTERN_C void ccdigest_init(const struct ccdigest_info* di, struct ccdigest_context* ctx);
+EXTERN_C void ccdigest_update(
+ const struct ccdigest_info* _di,
+ struct ccdigest_context* ctx,
+ size_t count,
+ const void* bytes
+);
+EXTERN_C void ccdigest_final(const struct ccdigest_info* _di, struct ccdigest_context* ctx, uint8_t* digest);
diff --git a/compat/corecrypto/ccdigest_private.h b/compat/corecrypto/ccdigest_private.h
new file mode 100644
index 0000000..0ea9759
--- /dev/null
+++ b/compat/corecrypto/ccdigest_private.h
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#include "api_defines.h"
+
+#include <openssl/evp.h>
+
+
+struct ccdigest_info {
+ EVP_MD* provider;
+};
+
+struct ccdigest_context {
+ EVP_MD_CTX* context;
+};
+
+EXTERN_C struct ccdigest_info* _ccdigest_newprovider(const char* name);
diff --git a/compat/corecrypto/ccsha1.c b/compat/corecrypto/ccsha1.c
new file mode 100644
index 0000000..e02b2b6
--- /dev/null
+++ b/compat/corecrypto/ccsha1.c
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#include "ccsha1.h"
+
+#include <assert.h>
+
+#include <cs_blobs.h>
+
+#include "ccdigest_private.h"
+
+
+static struct ccdigest_info* di = NULL;
+
+const struct ccdigest_info* ccsha1_di(void)
+{
+ if (!di) {
+ di = _ccdigest_newprovider("SHA-1");
+ assert(EVP_MD_get_size(di->provider) == CS_SHA1_LEN);
+ }
+ return di;
+}
diff --git a/compat/corecrypto/ccsha1.h b/compat/corecrypto/ccsha1.h
new file mode 100644
index 0000000..8e3f85f
--- /dev/null
+++ b/compat/corecrypto/ccsha1.h
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#include <corecrypto/ccdigest.h>
+
+
+EXTERN_C const struct ccdigest_info* ccsha1_di(void);
diff --git a/compat/corecrypto/ccsha2.c b/compat/corecrypto/ccsha2.c
new file mode 100644
index 0000000..6504503
--- /dev/null
+++ b/compat/corecrypto/ccsha2.c
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#include "ccsha2.h"
+
+#include <assert.h>
+
+#include <cs_blobs.h>
+
+#include "ccdigest_private.h"
+
+
+static struct ccdigest_info* di = NULL;
+
+const struct ccdigest_info* ccsha256_di(void)
+{
+ if (!di) {
+ di = _ccdigest_newprovider("SHA-256");
+ assert(EVP_MD_get_size(di->provider) == CS_SHA256_LEN);
+ }
+ return di;
+}
diff --git a/compat/corecrypto/ccsha2.h b/compat/corecrypto/ccsha2.h
new file mode 100644
index 0000000..9f30e03
--- /dev/null
+++ b/compat/corecrypto/ccsha2.h
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#include <corecrypto/ccdigest.h>
+
+#define CCSHA256_OUTPUT_SIZE 32
+
+EXTERN_C const struct ccdigest_info* ccsha256_di(void);
-diff --git a/compat/corecrypto/ccdigest.c b/compat/corecrypto/ccdigest.c
index e29dcb8..3949861 100644
--- a/compat/corecrypto/ccdigest.c
+++ b/compat/corecrypto/ccdigest.c
@@ -23,6 +23,12 @@ struct ccdigest_info* _ccdigest_newprovider(const char* name)
return di;
}
+void ccdigest_di_clear(const struct ccdigest_info* di, struct ccdigest_context* ctx)
+{
+ EVP_MD_CTX_free(ctx->context);
+ ctx->context = EVP_MD_CTX_new();
+}
+
void ccdigest_init(const struct ccdigest_info* di, struct ccdigest_context* ctx)
{
if (!EVP_DigestInit_ex2(ctx->context, di->provider, NULL)) {
diff --git a/compat/corecrypto/ccdigest.h b/compat/corecrypto/ccdigest.h
index 9af2394..d693fb7 100644
--- a/compat/corecrypto/ccdigest.h
+++ b/compat/corecrypto/ccdigest.h
@@ -17,6 +17,7 @@ EXTERN_C struct ccdigest_context* _ccdigest_context_new(void);
#define ccdigest_di_decl(_di, ctxvar) \
struct ccdigest_context* (ctxvar) = _ccdigest_context_new()
+EXTERN_C void ccdigest_di_clear(const struct ccdigest_info* _di, struct ccdigest_context* ctx);
EXTERN_C void ccdigest_init(const struct ccdigest_info* di, struct ccdigest_context* ctx);
EXTERN_C void ccdigest_update(
const struct ccdigest_info* _di,
diff --git a/compat/corecrypto/ccsha2.c b/compat/corecrypto/ccsha2.c
index 6504503..ed4de54 100644
--- a/compat/corecrypto/ccsha2.c
+++ b/compat/corecrypto/ccsha2.c
@@ -20,3 +20,12 @@ const struct ccdigest_info* ccsha256_di(void)
}
return di;
}
+
+const struct ccdigest_info* ccsha384_di(void)
+{
+ if (!di) {
+ di = _ccdigest_newprovider("SHA-384");
+ assert(EVP_MD_get_size(di->provider) == CS_SHA384_LEN);
+ }
+ return di;
+}
diff --git a/compat/corecrypto/ccsha2.h b/compat/corecrypto/ccsha2.h
index 9f30e03..bee18e8 100644
--- a/compat/corecrypto/ccsha2.h
+++ b/compat/corecrypto/ccsha2.h
@@ -5,6 +5,9 @@
#include <corecrypto/ccdigest.h>
#define CCSHA256_OUTPUT_SIZE 32
+#define CCSHA384_OUTPUT_SIZE 48
+#define CS_SHA384_LEN CCSHA384_OUTPUT_SIZE
EXTERN_C const struct ccdigest_info* ccsha256_di(void);
+EXTERN_C const struct ccdigest_info* ccsha384_di(void);

View File

@@ -0,0 +1,39 @@
diff --git a/other-tools/dsc_extractor_bin.cpp b/other-tools/dsc_extractor_bin.cpp
new file mode 100644
index 0000000000..2f26fbe4db
--- /dev/null
+++ b/other-tools/dsc_extractor_bin.cpp
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: APSL-2.0
+
+#include <stdio.h>
+#include <stddef.h>
+#include <dlfcn.h>
+
+
+typedef int (*extractor_proc)(const char* shared_cache_file_path, const char* extraction_root_path,
+ void (^progress)(unsigned current, unsigned total));
+
+int main(int argc, const char* argv[])
+{
+ if ( argc != 3 ) {
+ fprintf(stderr, "usage: dsc_extractor <path-to-cache-file> <path-to-device-dir>\n");
+ return 1;
+ }
+
+ void* handle = dlopen("@lib@/lib/dsc_extractor.bundle", RTLD_LAZY);
+ if ( handle == NULL ) {
+ fprintf(stderr, "dsc_extractor.bundle could not be loaded\n");
+ return 1;
+ }
+
+ extractor_proc proc = (extractor_proc)dlsym(handle, "dyld_shared_cache_extract_dylibs_progress");
+ if ( proc == NULL ) {
+ fprintf(stderr, "dsc_extractor.bundle did not have dyld_shared_cache_extract_dylibs_progress symbol\n");
+ return 1;
+ }
+
+ int result = (*proc)(argv[1], argv[2], ^(unsigned c, unsigned total) { printf("%d/%d\n", c, total); } );
+ fprintf(stderr, "dyld_shared_cache_extract_dylibs_progress() => %d\n", result);
+ return 0;
+}

View File

@@ -0,0 +1,387 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/file_cmds/blob/main/file_cmds.xcodeproj/project.pbxproj
# Project settings
project('file_cmds', 'c', version : '@version@')
add_global_arguments(
'-DTARGET_OS_BRIDGE=0',
language : 'c',
)
# Dependencies
cc = meson.get_compiler('c')
core_foundation = dependency('appleframeworks', modules : 'CoreFoundation')
bzip2 = dependency('bzip2')
xz = dependency('liblzma')
libmd = dependency('libmd')
libxo = dependency('libxo')
zlib = dependency('zlib')
copyfile = cc.find_library('copyfile')
removefile = cc.find_library('removefile')
libutil = cc.find_library('util')
# Binaries
executable(
'chflags',
install : true,
sources: [ 'chflags/chflags.c' ],
)
install_man('chflags/chflags.1')
executable(
'chmod',
install : true,
sources: [
'chmod/chmod.c',
'chmod/chmod_acl.c',
]
)
install_man('chmod/chmod.1')
executable(
'chown',
install : true,
sources: [ 'chown/chown.c' ],
)
install_man('chown/chown.8')
install_symlink(
'chgrp',
install_dir : get_option('bindir'),
pointing_to : 'chown',
)
install_man('chown/chgrp.1')
executable(
'cksum',
install : true,
sources: [
'cksum/cksum.c',
'cksum/crc.c',
'cksum/crc32.c',
'cksum/print.c',
'cksum/sum1.c',
'cksum/sum2.c',
]
)
install_man('cksum/cksum.1')
install_symlink(
'sum',
install_dir : get_option('bindir'),
pointing_to : 'cksum',
)
install_man('cksum/sum.1')
executable(
'compress',
install : true,
sources: [
'compress/compress.c',
'compress/zopen.c',
]
)
install_man('compress/compress.1')
install_symlink(
'uncompress',
install_dir : get_option('bindir'),
pointing_to : 'compress',
)
install_man('compress/uncompress.1')
install_man('compress/zopen.3')
executable(
'cp',
dependencies : [ copyfile ],
install : true,
sources: [
'cp/cp.c',
'cp/utils.c',
]
)
install_man('cp/cp.1')
executable(
'dd',
dependencies : [ libutil ],
install : true,
sources: [
'dd/args.c',
'dd/conv.c',
'dd/conv_tab.c',
'dd/dd.c',
# 'dd/gen.c', # Not compiled in the Xcode project. Building it causes a duplicate symbol error when linking.
'dd/misc.c',
'dd/position.c',
]
)
install_man('dd/dd.1')
executable(
'df',
dependencies : [ libutil, libxo ],
install : true,
sources: [ 'df/df.c' ],
)
install_man('df/df.1')
executable(
'du',
dependencies : [ libutil ],
install : true,
sources: [ 'du/du.c' ],
)
install_man('du/du.1')
executable(
'gzip',
c_args : [ '-DGZIP_APPLE_VERSION="@version@"' ],
dependencies : [ bzip2, copyfile, xz, zlib ],
install : true,
sources: [
'gzip/futimens.c',
'gzip/gzip.c',
# Apple only builds with gzip support
# 'gzip/unbzip2.c',
# 'gzip/unlz.c',
# 'gzip/unpack.c',
# 'gzip/unxz.c',
# 'gzip/zuncompress.c',
]
)
install_man('gzip/gzip.1')
foreach cmd : [ 'gzexe', 'zdiff', 'zforce', 'zmore', 'znew' ]
install_data(
f'gzip/@cmd@',
install_dir : get_option('bindir'),
install_mode : 'r-xr-xr-x',
)
install_man(f'gzip/@cmd@.1')
endforeach
install_symlink(
'zless',
install_dir : get_option('bindir'),
pointing_to : 'zmore',
)
executable(
'install-bin', # Meson reserves the name “install”, so use a different name and rename in install phase.
dependencies : [ copyfile, libmd ],
install : true,
sources: [
'install/xinstall.c',
],
)
install_man('install/install.1')
executable(
'ipcrm',
install : true,
sources: [ 'ipcrm/ipcrm.c' ],
)
install_man('ipcrm/ipcrm.1')
executable(
'ipcs',
install : true,
sources: [ 'ipcs/ipcs.c' ],
)
install_man('ipcs/ipcs.1')
executable(
'ln',
install : true,
sources: [ 'ln/ln.c' ],
)
install_man('ln/ln.1')
install_symlink(
'link',
install_dir : get_option('bindir'),
pointing_to : 'ln',
)
install_man('ln/link.1')
install_man(f'ln/symlink.7')
executable(
'ls',
c_args : [
# https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/sys/stat.h#L520
'-DSF_DATALESS=0x40000000',
],
dependencies : [ libutil ],
install : true,
sources: [
'ls/cmp.c',
'ls/util.c',
'ls/ls.c',
'ls/print.c',
]
)
install_man('ls/ls.1')
executable(
'mkdir',
install : true,
sources: [ 'mkdir/mkdir.c' ],
)
install_man('mkdir/mkdir.1')
executable(
'mkfifo',
install : true,
sources: [ 'mkfifo/mkfifo.c' ],
)
install_man('mkfifo/mkfifo.1')
executable(
'mknod',
install : true,
sources: [
'mknod/mknod.c',
'mknod/pack_dev.c',
],
)
install_man('mknod/mknod.8')
executable(
'mtree',
dependencies : [ core_foundation, removefile ],
install : true,
sources: [
'cksum/crc.c',
'mtree/commoncrypto.c',
'mtree/compare.c',
'mtree/create.c',
'mtree/excludes.c',
'mtree/metrics.c',
'mtree/misc.c',
'mtree/mtree.c',
'mtree/spec.c',
'mtree/specspec.c',
'mtree/verify.c',
]
)
install_man('mtree/mtree.8')
executable(
'mv',
dependencies : [ copyfile ],
install : true,
sources: [
'mv/mv.c',
],
)
install_man('mv/mv.1')
executable(
'pathchk',
install : true,
sources: [ 'pathchk/pathchk.c' ],
)
install_man('pathchk/pathchk.1')
executable(
'pax',
dependencies : [ copyfile ],
install : true,
sources: [
'pax/ar_io.c',
'pax/ar_subs.c',
'pax/buf_subs.c',
'pax/cache.c',
'pax/cpio.c',
'pax/file_subs.c',
'pax/ftree.c',
'pax/gen_subs.c',
'pax/getoldopt.c',
'pax/options.c',
'pax/pat_rep.c',
'pax/pax.c',
'pax/pax_format.c',
'pax/sel_subs.c',
'pax/tables.c',
'pax/tar.c',
'pax/tty_subs.c',
]
)
install_man('pax/pax.1')
executable(
'rm',
dependencies : [ removefile ],
install : true,
sources: [
'rm/rm.c',
],
)
install_man('rm/rm.1')
install_symlink(
'unlink',
install_dir : get_option('bindir'),
pointing_to : 'rm',
)
install_man('rm/unlink.1')
executable(
'rmdir',
install : true,
sources: [ 'rmdir/rmdir.c' ],
)
install_man('rmdir/rmdir.1')
install_data(
'shar/shar.sh',
install_dir : get_option('bindir'),
install_mode : 'r-xr-xr-x',
rename : 'shar',
)
install_man('shar/shar.1')
executable(
'stat',
install : true,
sources: [ 'stat/stat.c' ],
)
install_man('stat/stat.1')
install_symlink(
'readlink',
install_dir : get_option('bindir'),
pointing_to : 'stat',
)
install_man('stat/readlink.1')
executable(
'touch',
install : true,
sources: [
'touch/touch.c',
],
)
install_man('touch/touch.1')
executable(
'truncate',
dependencies : [ libutil ],
install : true,
sources: [ 'truncate/truncate.c' ],
)
install_man('truncate/truncate.1')
executable(
'xattr',
install : true,
sources: [ 'xattr/xattr.c' ],
)
install_man('xattr/xattr.1')

View File

@@ -0,0 +1,143 @@
{
lib,
apple-sdk,
bzip2,
copyfile,
less,
libmd,
libutil,
libxo,
mkAppleDerivation,
pkg-config,
removefile,
shell_cmds,
stdenvNoCC,
xz,
zlib,
}:
let
Libc = apple-sdk.sourceRelease "Libc";
Libinfo = apple-sdk.sourceRelease "Libinfo";
CommonCrypto = apple-sdk.sourceRelease "CommonCrypto";
libplatform = apple-sdk.sourceRelease "libplatform";
xnu = apple-sdk.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "file_cmds-deps-private-headers";
buildCommand = ''
install -D -t "$out/include" \
'${Libinfo}/membership.subproj/membershipPriv.h' \
'${libplatform}/private/_simple.h'
install -D -t "$out/include/os" \
'${Libc}/os/assumes.h' \
'${xnu}/libkern/os/base_private.h'
install -D -t "$out/include/sys" \
'${xnu}/bsd/sys/ipcs.h' \
'${xnu}/bsd/sys/sem_internal.h' \
'${xnu}/bsd/sys/shm_internal.h'
install -D -t "$out/include/CommonCrypto" \
'${CommonCrypto}/include/Private/CommonDigestSPI.h'
install -D -t "$out/include/System/sys" \
'${xnu}/bsd/sys/fsctl.h'
mkdir -p "$out/include/apfs"
# APFS group is 'J' per https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/vfs/vfs_fsevents.c#L1054
cat <<EOF > "$out/include/apfs/apfs_fsctl.h"
#pragma once
#include <stdint.h>
#include <sys/ioccom.h>
struct xdstream_obj_id {
char* xdi_name;
uint64_t xdi_xdtream_obj_id;
};
#define APFS_CLEAR_PURGEABLE 0
#define APFSIOC_MARK_PURGEABLE _IOWR('J', 68, uint64_t)
#define APFSIOC_XDSTREAM_OBJ_ID _IOWR('J', 53, struct xdstream_obj_id)
EOF
cat <<EOF > "$out/include/sys/types.h"
#pragma once
#include <stdint.h>
#if defined(__arm64__)
/* https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/arm/types.h#L120-L133 */
typedef int32_t user32_addr_t;
typedef int32_t user32_time_t;
typedef int64_t user64_addr_t;
typedef int64_t user64_time_t;
#elif defined(__x86_64__)
/* https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/i386/types.h#L128-L142 */
typedef int32_t user32_addr_t;
typedef int32_t user32_time_t;
typedef int64_t user64_addr_t __attribute__((aligned(8)));
typedef int64_t user64_time_t __attribute__((aligned(8)));
#else
#error "Tried to build file_cmds for an unsupported architecture"
#endif
#include_next <sys/types.h>
EOF
'';
};
in
mkAppleDerivation {
releaseName = "file_cmds";
outputs = [
"out"
"man"
"xattr"
];
xcodeHash = "sha256-u23AoLa7J0eFtf4dXKkVO59eYL2I3kRsHcWPfT03MCU=";
patches = [
# Fixes build of ls
./patches/0001-Add-missing-extern-unix2003_compat-to-ls.patch
# Add missing conditional to avoid using private APFS APIs that we lack headers for using.
./patches/0002-Add-missing-ifdef-for-private-APFS-APIs.patch
];
nativeBuildInputs = [ pkg-config ];
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
buildInputs = [
bzip2
copyfile
libmd
libutil
libxo
removefile
xz
zlib
];
postInstall = ''
HOST_PATH='${lib.getBin shell_cmds}/bin' patchShebangs --host "$out/bin"
substituteInPlace "$out/bin/zmore" \
--replace-fail 'PAGER-less' '${lib.getBin less}/bin/less' \
--replace-fail 'PAGER-more' '${lib.getBin less}/bin/more'
# Work around Meson limitations.
mv "$out/bin/install-bin" "$out/bin/install"
# Make xattr available in its own output, so darwin.xattr can be an alias to it.
moveToOutput bin/xattr "$xattr"
ln -s "$xattr/bin/xattr" "$out/bin/xattr"
'';
meta = {
description = "File commands for Darwin";
license = with lib.licenses; [
apple-psl10
bsd2
# bsd2-freebsd
# bsd2-netbsd
bsd3
bsdOriginal
mit
];
};
}

View File

@@ -0,0 +1,26 @@
From 9e2185bde1320273b6465d272e1a36bff29fb9d6 Mon Sep 17 00:00:00 2001
From: Randy Eckenrode <randy@largeandhighquality.com>
Date: Sat, 7 Sep 2024 09:37:31 -0400
Subject: [PATCH 1/3] Add missing extern unix2003_compat to ls
---
ls/ls.h | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/ls/ls.h b/ls/ls.h
index 2a41c8b..ff9c3a9 100644
--- a/ls/ls.h
+++ b/ls/ls.h
@@ -114,4 +114,9 @@ typedef struct {
char data[1];
} NAMES;
+#ifdef __APPLE__
+#include <stdbool.h>
+extern bool unix2003_compat;
+#endif
+
#endif /* _LS_H_ */
--
2.46.0

View File

@@ -0,0 +1,33 @@
From c40768a7a0cd4bcc75a408880e79135ad33292b5 Mon Sep 17 00:00:00 2001
From: Randy Eckenrode <randy@largeandhighquality.com>
Date: Sat, 7 Sep 2024 09:44:20 -0400
Subject: [PATCH 2/3] Add missing #ifdef for private APFS APIs
---
mtree/commoncrypto.c | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/mtree/commoncrypto.c b/mtree/commoncrypto.c
index 75790dd..e04d1c6 100644
--- a/mtree/commoncrypto.c
+++ b/mtree/commoncrypto.c
@@ -254,6 +254,7 @@ get_xdstream_privateid(char *path, char *buf) {
nextName += strlen(name) + 1;
}
+#ifdef APFSIOC_XDSTREAM_OBJ_ID
for (int i = 0; i < xattrIndex; i++) {
char *name = xattrs[i];
// System volume has stream based xattrs only in form of resource forks
@@ -275,7 +276,7 @@ get_xdstream_privateid(char *path, char *buf) {
}
}
}
-
+#endif
ai->xdstream_priv_id = xd_obj_id;
// insert a dummy value as digest is not used in presence of mflag
ai->digest = "authapfs";
--
2.46.0

View File

@@ -0,0 +1,124 @@
{
lib,
autoreconfHook,
dejagnu,
mkAppleDerivation,
stdenv,
testers,
texinfo,
# test suite depends on dejagnu which cannot be used during bootstrapping
# dejagnu also requires tcl which can't be built statically at the moment
doCheck ? !(stdenv.hostPlatform.isStatic),
}:
mkAppleDerivation (finalAttrs: {
releaseName = "libffi";
outputs = [
"out"
"dev"
"man"
"info"
];
patches = [
# Clang 18 requires that no non-private symbols by defined after cfi_startproc. Apply the upstream libffi fix.
./patches/llvm-18-compatibility.patch
# Fix a memory leak when using the trampoline dylib. See https://github.com/libffi/libffi/pull/621#discussion_r955298301.
./patches/fix-tramponline-memory-leak.patch
# Fix automake-18.18 compatibility, https://github.com/libffi/libffi/issues/853#issuecomment-2909994482
./patches/automake-1.18.patch
];
# Make sure libffi is using the trampolines dylib in this package not the system one.
postPatch = ''
substituteInPlace src/closures.c --replace-fail /usr/lib "$out/lib"
'';
enableParallelBuilding = true;
nativeBuildInputs = [
autoreconfHook
texinfo
];
configurePlatforms = [
"build"
"host"
];
configureFlags = [
"--with-gcc-arch=generic" # no detection of -march= or -mtune=
"--enable-builddir=build"
];
postConfigure = ''
# Use Apples configuration instead of the one generated by the `configure` script.
cp darwin/include/fficonfig_${stdenv.hostPlatform.darwinArch}.h build/fficonfig.h
cp darwin/include/ffitarget_${
if stdenv.hostPlatform.isAarch64 then "arm64" else "x86"
}.h build/include/ffitarget.h
# Use `macCatalyst` instead of `iosmac` to avoid errors due to invalid availability annotations.
substitute darwin/include/ffi.h build/include/ffi.h \
--replace-fail iosmac macCatalyst
'';
postBuild = lib.optionalString stdenv.hostPlatform.isAarch64 ''
$CC -Os -Wl,-allowable_client,! -Wl,-not_for_dyld_shared_cache -Wl,-no_compact_unwind \
src/aarch64/trampoline.S -dynamiclib -o libffi-trampolines.dylib \
-Iinclude -Ibuild -Ibuild/include \
-install_name "$out/lib/libffi-trampoline.dylib" -Wl,-compatibility_version,1 -Wl,-current_version,1
'';
postInstall =
# The Darwin SDK puts the headers in `include/ffi`. Add a symlink for compatibility.
''
ln -s "$dev/include" "$dev/include/ffi"
''
# Install the trampoline dylib since it is build manually.
+ lib.optionalString stdenv.hostPlatform.isAarch64 ''
cp libffi-trampolines.dylib "$out/lib/libffi-trampolines.dylib"
'';
preCheck = ''
# The tests use -O0 which is not compatible with -D_FORTIFY_SOURCE.
NIX_HARDENING_ENABLE=''${NIX_HARDENING_ENABLE/fortify3/}
NIX_HARDENING_ENABLE=''${NIX_HARDENING_ENABLE/fortify/}
'';
dontStrip = stdenv.hostPlatform != stdenv.buildPlatform; # Don't run the native `strip' when cross-compiling.
inherit doCheck;
nativeCheckInputs = [ dejagnu ];
passthru = {
tests = {
pkg-config = testers.hasPkgConfigModules {
package = finalAttrs.finalPackage;
};
};
};
meta = {
description = "Foreign function call interface library";
longDescription = ''
The libffi library provides a portable, high level programming
interface to various calling conventions. This allows a
programmer to call any function specified by a call interface
description at run-time.
FFI stands for Foreign Function Interface. A foreign function
interface is the popular name for the interface that allows code
written in one language to call code written in another
language. The libffi library really only provides the lowest,
machine dependent layer of a fully featured foreign function
interface. A layer must exist above libffi that handles type
conversions for values passed between the two languages.
'';
homepage = "https://github.com/apple-oss-distributions/libffi/";
license = lib.licenses.mit;
pkgConfigModules = [ "libffi" ];
};
})

View File

@@ -0,0 +1,14 @@
The hunk is used from https://github.com/libffi/libffi/issues/853#issuecomment-2909994482
--- a/Makefile.am
+++ b/Makefile.am
@@ -4,6 +4,10 @@ AUTOMAKE_OPTIONS = foreign subdir-objects
ACLOCAL_AMFLAGS = -I m4
+# Alias required by AX_ENABLE_BUILDDIR / config-ml
+.PHONY: all-configured
+all-configured: all
+
SUBDIRS = include testsuite man
if BUILD_DOCS
## This hack is needed because it doesn't seem possible to make a

View File

@@ -0,0 +1,13 @@
diff --git a/src/closures.c b/src/closures.c
index 01f9950cd0..1dfd375cff 100644
--- a/src/closures.c
+++ b/src/closures.c
@@ -329,7 +329,7 @@
table->next->prev = table->prev;
/* Deallocate pages */
- vm_deallocate (mach_task_self (), table->config_page, PAGE_MAX_SIZE * 2);
+ vm_deallocate (mach_task_self (), table->config_page, FFI_TRAMPOLINE_ALLOCATION_PAGE_COUNT * PAGE_MAX_SIZE);
/* Deallocate free list */
free (table->free_list_pool);

View File

@@ -0,0 +1,34 @@
diff --git a/src/aarch64/sysv.S b/src/aarch64/sysv.S
index eeaf3f8..329889c 100644
--- a/src/aarch64/sysv.S
+++ b/src/aarch64/sysv.S
@@ -76,8 +76,8 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
x5 closure
*/
- cfi_startproc
CNAME(ffi_call_SYSV):
+ cfi_startproc
/* Sign the lr with x1 since that is where it will be stored */
SIGN_LR_WITH_REG(x1)
@@ -268,8 +268,8 @@ CNAME(ffi_closure_SYSV_V):
#endif
.align 4
- cfi_startproc
CNAME(ffi_closure_SYSV):
+ cfi_startproc
SIGN_LR
stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
@@ -500,8 +500,8 @@ CNAME(ffi_go_closure_SYSV_V):
#endif
.align 4
- cfi_startproc
CNAME(ffi_go_closure_SYSV):
+ cfi_startproc
stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
cfi_rel_offset (x29, 0)

View File

@@ -0,0 +1,347 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/libiconv/blob/main/libiconv.xcodeproj/project.pbxproj
# Project settings
project('libiconv', 'c', version : '@version@')
fs = import('fs')
# Dependencies
cc = meson.get_compiler('c')
# Definitions
prefix_libdir = get_option('prefix') / get_option('libdir')
prefix_datadir = get_option('prefix') / get_option('datadir')
i18nmoduledir = prefix_libdir / 'i18n'
esdbdir = prefix_datadir / 'i18n/esdb'
csmapperdir = prefix_datadir / 'i18n/csmapper'
is_static = get_option('default_library') == 'static'
static_suffix = is_static ? '_static' : ''
# Generators
if is_static
gperf_bin = find_program('gperf', required : true)
gperf = generator(
gperf_bin,
arguments : ['@INPUT@', '--output-file=@OUTPUT@'],
output : '@BASENAME@.h'
)
endif
# Libraries
libcharset = library(
'charset',
darwin_versions : '1',
install : true,
include_directories : ['libcharset'],
sources : [
'libcharset/libcharset.c'
],
soversion : '1'
)
install_headers(
'libcharset/libcharset.h',
'libcharset/localcharset.h'
)
libiconv = library(
'iconv' + static_suffix,
build_rpath : fs.parent(libcharset.full_path()),
c_args : [
f'-D_PATH_I18NMODULE="@i18nmoduledir@"',
f'-D_PATH_ESDB="@esdbdir@"',
f'-D_PATH_CSMAPPER="@csmapperdir@"',
is_static ? '-DENABLE_STATIC=1' : [ ]
],
darwin_versions : '7',
install : not is_static,
include_directories : ['citrus', 'libcharset'],
link_args : ['-Wl,-reexport_library', fs.name(libcharset.full_path())],
link_depends : [libcharset],
override_options : {'b_asneeded' : false}, # Make sure the libcharset reexport is not stripped
sources : [
'citrus/__iconv_get_list.c',
'citrus/__iconv_free_list.c',
'citrus/__iconv.c',
'citrus/bsd_iconv.c',
'citrus/citrus_bcs_strtol.c',
'citrus/citrus_bcs_strtoul.c',
'citrus/citrus_bcs.c',
'citrus/citrus_csmapper.c',
'citrus/citrus_db.c',
'citrus/citrus_db_factory.c',
'citrus/citrus_db_hash.c',
'citrus/citrus_esdb.c',
'citrus/citrus_hash.c',
'citrus/citrus_iconv.c',
'citrus/citrus_lookup_factory.c',
'citrus/citrus_lookup.c',
'citrus/citrus_mapper.c',
'citrus/citrus_memstream.c',
'citrus/citrus_mmap.c',
'citrus/citrus_module.c',
'citrus/citrus_none.c',
'citrus/citrus_pivot_factory.c',
'citrus/citrus_prop.c',
'citrus/citrus_stdenc.c',
'citrus/iconv_canonicalize.c',
'citrus/iconv_close.c',
'citrus/iconv_compat.c',
'citrus/iconv_open_into.c',
'citrus/iconv_open.c',
'citrus/iconv_set_relocation_prefix.c',
'citrus/iconvctl.c',
'citrus/iconvlist.c',
'citrus/iconv.c',
is_static ? gperf.process('static-modules.gperf') : [ ]
],
soversion : '2'
)
install_headers(
'citrus/iconv.h'
)
install_man(
'citrus/__iconv_get_list.3',
'citrus/iconv_canonicalize.3',
'citrus/iconv.3',
'citrus/iconvctl.3',
'citrus/iconvlist.3',
)
# Data
## csmapper
csmapper_modules = [
'APPLE',
'AST',
'BIG5',
'CNS',
'CP',
'EBCDIC',
'GB',
'GEORGIAN',
'ISO-8859',
'ISO646',
'JIS',
'KAZAKH',
'KOI',
'KS',
'MISC',
'TCVN'
]
foreach module : csmapper_modules
mps_files = run_command(
'find', 'i18n/csmapper' / module, '-regex', '.*\\.\\(mps\\|646\\)',
check : true
).stdout().strip().split('\n')
install_data(mps_files, install_dir : csmapperdir / module)
endforeach
install_data(
'i18n/csmapper/charset.pivot',
'i18n/csmapper/charset.pivot.pvdb',
'i18n/csmapper/mapper.dir',
'i18n/csmapper/mapper.dir.db',
install_dir : csmapperdir
)
## esdb
esdb_modules = [
'APPLE',
'AST',
'BIG5',
'CP',
'DEC',
'EBCDIC',
'EUC',
'GB',
'GEORGIAN',
'ISO-2022',
'ISO-8859',
'ISO646',
'KAZAKH',
'KOI',
'MISC',
'TCVN',
'UTF'
]
foreach module : esdb_modules
esdb_files = run_command(
'find', 'i18n/esdb' / module, '-name', '*.esdb',
check : true
).stdout().strip().split('\n')
install_data(esdb_files, install_dir : esdbdir / module)
endforeach
install_data(
'i18n/esdb/esdb.alias',
'i18n/esdb/esdb.alias.db',
'i18n/esdb/esdb.dir',
'i18n/esdb/esdb.dir.db',
install_dir : esdbdir
)
# Modules
libiconv_modules = [
'BIG5',
'DECHanyu',
'DECKanji',
'EUC',
'EUCTW',
'GBK2K',
'HZ',
'ISO2022',
'JOHAB',
'MSKanji',
'UES',
'UTF1632',
'UTF7',
'UTF8',
'UTF8MAC',
'VIQR',
'ZW',
'iconv_none',
'iconv_std',
'mapper_646',
'mapper_none',
'mapper_serial',
'mapper_parallel',
'mapper_std',
'mapper_zone'
]
modules = [ ]
foreach module : libiconv_modules
module_source = module.to_lower()
module_path = 'libiconv_modules' / module
if module == 'UTF8MAC'
extra_headers = 'libiconv_modules/UTF8'
else
extra_headers = [ ]
endif
# Upstream builds this module under both names.
# See: https://github.com/apple-oss-distributions/libiconv/blob/81be60a93521c931a01aab9c747dd2b078bc0679/libiconv.xcodeproj/project.pbxproj#L2549-L2556
# See also: https://cgit.freebsd.org/src/tree/lib/libiconv_modules/mapper_parallel/Makefile?id=9241ebc796c11cf133c550f188f324bd2c12d89a
if module == 'mapper_parallel'
# Skip including mapper_parallel since its the same as mapper_serial, which would result in duplicate symbols.
if is_static
continue
endif
module_source = 'mapper_serial'
module_path = 'libiconv_modules/mapper_serial'
endif
modules += library(
module,
darwin_versions : '1',
install : not is_static,
install_dir : i18nmoduledir,
include_directories : [module_path, 'citrus', 'libcharset'] + extra_headers,
link_with : [libiconv],
override_options : {'b_asneeded' : false}, # Upstream always links libiconv
sources : [
module_path / f'citrus_@module_source@.c'
]
)
endforeach
# Bundle the modules into libiconv.a
if is_static
objects = [libiconv.extract_all_objects(recursive : true)]
foreach module : modules
objects += module.extract_all_objects(recursive : true)
endforeach
libiconv = static_library(
'iconv',
install : true,
objects : objects
)
endif
# Binaries
executable(
'iconv',
install : true,
include_directories : ['citrus', 'libcharset'],
link_with : [
libiconv,
# Darwins system `iconv` relies on the reexported symbols from libiconv
is_static ? libcharset : [ ]
],
sources : [
'iconv/iconv.c'
]
)
install_man('iconv/iconv.1')
# Tests
if get_option('tests') == true
## Only required for running the tests
atf = dependency('atf-c')
foreach suite : ['fallback_test', 'libiconv_test', 'mbopt_test', 'nixpkgs_test']
test_src = f'tests/libiconv/@suite@.c'
test_exe = executable(
suite,
dependencies : [atf],
include_directories : ['citrus', 'libcharset'],
link_with : [
libiconv,
# Make sure the libcharset reexport is working by relying on libiconv to provide its symbols.
is_static ? libcharset : [ ]
],
sources : [test_src]
)
# Extract the tests to run from the test source code.
tests = run_command(
'sed', '-n', '-E', 's|.*ATF_TP_ADD_TC\\([^,]*, ([^)]*).*$|\\1|p', test_src,
check : true
).stdout().strip().split('\n')
foreach test : tests
test(test, test_exe, args : [test], suite : suite, timeout : 300)
endforeach
endforeach
# These tests depend on `os_variant_has_internal_content`, which is stubbed out.
# atf_sh = find_program('atf-sh')
# print_charset = executable(
# 'print_charset',
# include_directories : ['citrus', 'libcharset'],
# link_with : [libiconv],
# sources : 'tests/libcharset/print_charset.c'
# )
#
# test_charset = custom_target(
# 'test_charset.sh',
# command : ['cp', '@INPUT@', '@OUTPUT@'],
# depends : print_charset,
# input : 'tests/libcharset/test_charset.sh',
# output : 'test_charset.sh'
# )
#
# # Extract the tests to run from the test source code.
# tests = run_command(
# 'sed', '-n', '-E', 's|.*atf_add_test_case (.*$)|\\1|p', 'tests/libcharset/test_charset.sh',
# check : true
# ).stdout().strip().split('\n')
#
# foreach test : tests
# test(test, atf_sh, args : [test_charset, test], suite : 'libcharset', timeout : 300)
# endforeach
endif

View File

@@ -0,0 +1 @@
option('tests', type : 'boolean')

View File

@@ -0,0 +1,116 @@
#include <atf-c.h>
#include <iconv.h>
#include <stdint.h>
// The following tests were failing in libarchive due to libiconv issues.
// 218: test_read_format_cab_filename (4 failures)
// 415: test_read_format_zip_filename_CP932_eucJP (4 failures)
// 426: test_read_format_zip_filename_CP932_CP932 (2 failures)
ATF_TC(test_cp932_eucjp);
ATF_TC_HEAD(test_cp932_eucjp, tc)
{
atf_tc_set_md_var(tc, "descr", "regression test for CP932 to EUC-JP conversion");
}
ATF_TC_BODY(test_cp932_eucjp, tc)
{
char expected[] = "\xc9\xbd\xa4\xc0\xa4\xe8\x5c\xb4\xc1\xbb\xfa\x2e\x74\x78\x74";
size_t expected_length = sizeof(expected) - 1;
char input[] = "\x95\x5c\x82\xbe\x82\xe6\x5c\x8a\xbf\x8e\x9a\x2e\x74\x78\x74";
size_t input_length = sizeof(input) - 1;
size_t output_available = sizeof(expected) - 1 ;
char output[sizeof(expected)] = { 0 };
iconv_t cd = iconv_open("eucJP", "CP932");
ATF_REQUIRE((size_t)cd != -1);
char* input_buf = input;
char* output_buf = output;
size_t res = iconv(cd, &input_buf, &input_length, &output_buf, &output_available);
iconv_close(cd);
ATF_CHECK(res != -1);
size_t output_length = sizeof(output) - output_available - 1;
ATF_CHECK_INTEQ(expected_length, output_length);
ATF_CHECK_STREQ(expected, output);
}
ATF_TC(test_cp932_cp932);
ATF_TC_HEAD(test_cp932_cp932, tc)
{
atf_tc_set_md_var(tc, "descr", "regression test for CP932 to CP932 conversion");
}
ATF_TC_BODY(test_cp932_cp932, tc)
{
char expected[] = "\x95\x5c\x82\xbe\x82\xe6\x5c\x8a\xbf\x8e\x9a\x2e\x74\x78\x74";
size_t expected_length = sizeof(expected) - 1;
char input[] = "\x95\x5c\x82\xbe\x82\xe6\x5c\x8a\xbf\x8e\x9a\x2e\x74\x78\x74";
size_t input_length = sizeof(input) - 1;
size_t output_available = sizeof(expected) - 1 ;
char output[sizeof(expected)] = { 0 };
iconv_t cd = iconv_open("CP932", "CP932");
ATF_REQUIRE((size_t)cd != -1);
char* input_buf = input;
char* output_buf = output;
size_t res = iconv(cd, &input_buf, &input_length, &output_buf, &output_available);
iconv_close(cd);
ATF_CHECK(res != -1);
size_t output_length = sizeof(output) - output_available - 1;
ATF_CHECK_INTEQ(expected_length, output_length);
ATF_CHECK_STREQ(expected, output);
}
ATF_TC(test_iso2022_crash);
ATF_TC_HEAD(test_iso2022_crash, tc)
{
atf_tc_set_md_var(tc, "descr", "regression test for converting to ISO-2022 with escape sequences");
}
ATF_TC_BODY(test_iso2022_crash, tc)
{
char expected[] = "";
size_t expected_length = sizeof(expected) - 1;
char input[] = "\x41\x41\x41\x41\x41\xe5\x8a\x84";
size_t input_length = sizeof(input) - 1;
size_t output_available = sizeof(expected) - 1 ;
char output[sizeof(expected)] = { 0 };
iconv_t cd = iconv_open("ISO-2022-CN-EXT", "UTF-8");
ATF_REQUIRE((size_t)cd != -1);
char* input_buf = input;
char* output_buf = output;
size_t res = iconv(cd, &input_buf, &input_length, &output_buf, &output_available);
iconv_close(cd);
ATF_CHECK(res == -1);
size_t output_length = sizeof(output) - output_available - 1;
ATF_CHECK_INTEQ(expected_length, output_length);
ATF_CHECK_STREQ(expected, output);
}
ATF_TP_ADD_TCS(tp)
{
ATF_TP_ADD_TC(tp, test_cp932_eucjp);
ATF_TP_ADD_TC(tp, test_cp932_cp932);
ATF_TP_ADD_TC(tp, test_iso2022_crash);
return atf_no_error();
}

View File

@@ -0,0 +1,93 @@
{
lib,
atf,
gperf,
mkAppleDerivation,
pkg-config,
stdenv,
}:
let
inherit (stdenv) hostPlatform;
in
mkAppleDerivation (finalAttrs: {
releaseName = "libiconv";
outputs = [
"out"
"dev"
];
xcodeHash = "sha256-IiTqhEJIZ8JYjlpBS7ITwYlp8ndU6cehus9TIr+5LYM=";
patches = [
# Use gperf to implement module loading statically by looking up the module functions in the static binary.
./patches/0001-Support-static-module-loading.patch
# Avoid out of bounds write with ISO-2022
./patches/0002-Fix-ISO-2022-out-of-bounds-write-with-encoded-charac.patch
];
# Propagate `out` only when there are dylibs to link (i.e., dont propagate when doing a static build).
propagatedBuildOutputs = lib.optionalString (!hostPlatform.isStatic) "out";
postPatch = ''
# Work around unnecessary private API usage in libcharset.
mkdir -p libcharset/os && cat <<EOF > libcharset/os/variant_private.h
#pragma once
#include <stdbool.h>
static inline bool os_variant_has_internal_content(const char*) { return false; }
EOF
# Add additional test cases found while working on packaging libiconv in nixpkgs.
cp ${./nixpkgs_test.c} tests/libiconv/nixpkgs_test.c
''
+ lib.optionalString hostPlatform.isStatic ''
cp ${./static-modules.gperf} static-modules.gperf
'';
# Dynamic builds use `dlopen` to load modules, but static builds have to link them all.
# `gperf` is used to generate a lookup table from module to ops functions.
nativeBuildInputs = lib.optionals hostPlatform.isStatic [ gperf ];
mesonFlags = [ (lib.mesonBool "tests" finalAttrs.finalPackage.doInstallCheck) ];
postBuild =
# Add `libcharset.a` contents to `libiconv.a` to duplicate the reexport from `libiconv.dylib`.
lib.optionalString hostPlatform.isStatic ''
${stdenv.cc.targetPrefix}ar qL libiconv.a libcharset.a
'';
postInstall =
lib.optionalString (hostPlatform.isDarwin && !hostPlatform.isStatic) ''
${stdenv.cc.targetPrefix}install_name_tool "$out/lib/libiconv.2.dylib" \
-change '@rpath/libcharset.1.dylib' "$out/lib/libcharset.1.dylib"
''
# Move the static library to the `dev` output
+ lib.optionalString hostPlatform.isStatic ''
moveToOutput lib "$dev"
'';
# Tests have to be run in `installCheckPhase` because libiconv expects to `dlopen`
# modules from `$out/lib/i18n`.
nativeInstallCheckInputs = [ pkg-config ];
installCheckInputs = [ atf ];
doInstallCheck = stdenv.buildPlatform.canExecute hostPlatform;
# Cant use `mesonCheckPhase` because it runs the wrong hooks for `installCheckPhase`.
installCheckPhase = ''
runHook preInstallCheck
meson test --no-rebuild --print-errorlogs --timeout-multiplier=0
runHook postInstallCheck
'';
meta = {
description = "Iconv(3) implementation";
license = [
lib.licenses.bsd2
lib.licenses.bsd3
]
++ lib.optional finalAttrs.finalPackage.doInstallCheck lib.licenses.apple-psl10;
mainProgram = "iconv";
};
})

View File

@@ -0,0 +1,73 @@
From cf3bcbf4444d73cb3d1a9369c569338ae0fcb668 Mon Sep 17 00:00:00 2001
From: Randy Eckenrode <randy@largeandhighquality.com>
Date: Sat, 25 May 2024 19:03:58 -0400
Subject: [PATCH 1/2] Support static module loading
---
citrus/citrus_module.c | 20 ++++++++++++++++++--
1 file changed, 18 insertions(+), 2 deletions(-)
diff --git a/citrus/citrus_module.c b/citrus/citrus_module.c
index 8ca4702..7667868 100644
--- a/citrus/citrus_module.c
+++ b/citrus/citrus_module.c
@@ -324,16 +324,24 @@ out:
return (path[0] ? path : NULL);
}
+#if defined(ENABLE_STATIC)
+#include "static-modules.h"
+#endif
+
void *
_citrus_find_getops(_citrus_module_t handle, const char *modname,
const char *ifname)
{
char name[PATH_MAX];
void *p;
-
+#if defined(ENABLE_STATIC)
+ const struct getops_pair* res = lookup_getops(modname, strlen(modname));
+ p = res ? res->opsfn : NULL;
+#else
snprintf(name, sizeof(name), "_citrus_%s_%s_getops",
modname, ifname);
p = dlsym((void *)handle, name);
+#endif
return (p);
}
@@ -345,6 +353,12 @@ _citrus_load_module(_citrus_module_t *rhandle, const char *encname)
return (0);
#else
+#if defined(ENABLE_STATIC)
+ if (is_known_encoding(encname, strnlen(encname, MAX_WORD_LENGTH)) > MAX_HASH_VALUE) {
+ return (EINVAL);
+ }
+ *rhandle = (_citrus_module_t)encodings;
+#else
const char *p;
char path[PATH_MAX];
void *handle;
@@ -373,7 +387,7 @@ _citrus_load_module(_citrus_module_t *rhandle, const char *encname)
}
*rhandle = (_citrus_module_t)handle;
-
+#endif
return (0);
#endif
}
@@ -390,6 +404,8 @@ _citrus_unload_module(_citrus_module_t handle)
assert(handle != RTLD_SELF);
#endif /* FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION */
#endif /* __APPLE__ */
+#if !defined(ENABLE_STATIC)
if (handle)
dlclose((void *)handle);
+#endif
}
--
2.46.0

View File

@@ -0,0 +1,43 @@
From 6a2c81d23558d19a68d5494f8f8618bd55c89405 Mon Sep 17 00:00:00 2001
From: Randy Eckenrode <randy@largeandhighquality.com>
Date: Mon, 27 May 2024 13:43:43 -0400
Subject: [PATCH 2/2] Fix ISO-2022 out-of-bounds write with encoded characters
---
libiconv_modules/ISO2022/citrus_iso2022.c | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/libiconv_modules/ISO2022/citrus_iso2022.c b/libiconv_modules/ISO2022/citrus_iso2022.c
index 46da1d6..c2eeaa8 100644
--- a/libiconv_modules/ISO2022/citrus_iso2022.c
+++ b/libiconv_modules/ISO2022/citrus_iso2022.c
@@ -1031,7 +1031,7 @@ _ISO2022_sputwchar(_ISO2022EncodingInfo * __restrict ei, wchar_t wc,
{
_ISO2022Charset cs;
char *p;
- char tmp[MB_LEN_MAX];
+ char tmp[MB_LEN_MAX + 4];
size_t len;
int bit8, i = 0, target;
unsigned char mask;
@@ -1196,7 +1196,7 @@ _citrus_ISO2022_put_state_reset(_ISO2022EncodingInfo * __restrict ei,
size_t * __restrict nresult)
{
char *result;
- char buf[MB_LEN_MAX];
+ char buf[MB_LEN_MAX + 4];
size_t len;
int ret;
@@ -1225,7 +1225,7 @@ _citrus_ISO2022_wcrtomb_priv(_ISO2022EncodingInfo * __restrict ei,
_ISO2022State * __restrict psenc, size_t * __restrict nresult)
{
char *result;
- char buf[MB_LEN_MAX];
+ char buf[MB_LEN_MAX + 4];
size_t len;
int ret;
--
2.44.1

View File

@@ -0,0 +1,73 @@
%language=ANSI-C
%compare-strncmp
%pic
%readonly-tables
%{
#include "citrus_namespace.h"
#include "citrus_types.h"
#include "citrus_module.h"
#include "citrus_hash.h"
#include "citrus_iconv.h"
#include "citrus_mapper.h"
#include "citrus_stdenc.h"
extern _CITRUS_STDENC_GETOPS_FUNC(BIG5);
extern _CITRUS_STDENC_GETOPS_FUNC(DECHanyu);
extern _CITRUS_STDENC_GETOPS_FUNC(DECKanji);
extern _CITRUS_STDENC_GETOPS_FUNC(EUC);
extern _CITRUS_STDENC_GETOPS_FUNC(EUCTW);
extern _CITRUS_STDENC_GETOPS_FUNC(GBK2K);
extern _CITRUS_STDENC_GETOPS_FUNC(HZ);
extern _CITRUS_STDENC_GETOPS_FUNC(ISO2022);
extern _CITRUS_STDENC_GETOPS_FUNC(JOHAB);
extern _CITRUS_STDENC_GETOPS_FUNC(MSKanji);
extern _CITRUS_STDENC_GETOPS_FUNC(UES);
extern _CITRUS_STDENC_GETOPS_FUNC(UTF1632);
extern _CITRUS_STDENC_GETOPS_FUNC(UTF7);
extern _CITRUS_STDENC_GETOPS_FUNC(UTF8);
extern _CITRUS_STDENC_GETOPS_FUNC(UTF8MAC);
extern _CITRUS_STDENC_GETOPS_FUNC(VIQR);
extern _CITRUS_STDENC_GETOPS_FUNC(ZW);
extern _CITRUS_ICONV_GETOPS_FUNC(iconv_none);
extern _CITRUS_ICONV_GETOPS_FUNC(iconv_std);
extern _CITRUS_MAPPER_GETOPS_FUNC(mapper_646);
extern _CITRUS_MAPPER_GETOPS_FUNC(mapper_none);
extern _CITRUS_MAPPER_GETOPS_FUNC(mapper_parallel);
extern _CITRUS_MAPPER_GETOPS_FUNC(mapper_serial);
extern _CITRUS_MAPPER_GETOPS_FUNC(mapper_std);
extern _CITRUS_MAPPER_GETOPS_FUNC(mapper_zone);
%}
%define lookup-function-name lookup_getops
%define hash-function-name is_known_encoding
%define string-pool-name encodings
%struct-type
struct getops_pair { int name; void* opsfn; };
%%
BIG5, _citrus_BIG5_stdenc_getops
DECHanyu, _citrus_DECHanyu_stdenc_getops
DECKanji, _citrus_DECKanji_stdenc_getops
EUC, _citrus_EUC_stdenc_getops
EUCTW, _citrus_EUCTW_stdenc_getops
GBK2K, _citrus_GBK2K_stdenc_getops
HZ, _citrus_HZ_stdenc_getops
ISO2022, _citrus_ISO2022_stdenc_getops
JOHAB, _citrus_JOHAB_stdenc_getops
MSKanji, _citrus_MSKanji_stdenc_getops
UES, _citrus_UES_stdenc_getops
UTF1632, _citrus_UTF1632_stdenc_getops
UTF7, _citrus_UTF7_stdenc_getops
UTF8, _citrus_UTF8_stdenc_getops
UTF8MAC, _citrus_UTF8MAC_stdenc_getops
VIQR, _citrus_VIQR_stdenc_getops
ZW, _citrus_ZW_stdenc_getops
iconv_none, _citrus_iconv_none_iconv_getops
iconv_std, _citrus_iconv_std_iconv_getops
mapper_646, _citrus_mapper_646_mapper_getops
mapper_none, _citrus_mapper_none_mapper_getops
mapper_serial, _citrus_mapper_serial_mapper_getops
mapper_parallel, _citrus_mapper_parallel_mapper_getops
mapper_std, _citrus_mapper_std_mapper_getops
mapper_zone, _citrus_mapper_zone_mapper_getops

View File

@@ -0,0 +1,100 @@
{
lib,
apple-sdk_15,
bison,
bluez,
flex,
mkAppleDerivation,
stdenv,
stdenvNoCC,
unifdef,
# Provided for compatibility with the top-level derivation.
withBluez ? false,
withRemote ? false,
}:
let
xnu = apple-sdk_15.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "libpcap-deps-private-headers";
nativeBuildInputs = [ unifdef ];
buildCommand = ''
mkdir -p "$out/include/net"
unifdef -x 1 -DPRIVATE -o "$out/include/net/droptap.h" '${xnu}/bsd/net/droptap.h'
unifdef -x 1 -DPRIVATE -o "$out/include/net/iptap.h" '${xnu}/bsd/net/iptap.h'
unifdef -x 1 -DPRIVATE -o "$out/include/net/pktap.h" '${xnu}/bsd/net/pktap.h'
unifdef -x 1 -DPRIVATE -o "$out/include/net/bpf.h" '${xnu}/bsd/net/bpf.h'
cat <<EOF > "$out/include/net/if.h"
#pragma once
#include_next <net/if.h>
#include <net/if_private.h>
EOF
cat <<EOF > "$out/include/net/if_private.h"
#pragma once
$(sed -n \
-e '/^#define IF_DESCSIZE\s/p' \
-e '/^struct if_descreq\s*{/,/};/p' \
'${xnu}/bsd/net/if_private.h')
EOF
mkdir -p "$out/include/sys"
cat <<EOF > "$out/include/sys/socket.h"
#pragma once
#include <sys/param.h>
#include <sys/_types/_socklen_t.h>
$(sed -n \
-e '/^#define SO_TC/p' \
'${xnu}/bsd/sys/socket_private.h')
#include_next <sys/socket.h>
EOF
cat <<EOF > "$out/include/sys/sockio.h"
#pragma once
$(sed -n \
-e '/^#define SIOCGIFDESC\s/p' \
-e '/^#define SIOCSIFDESC\s/p' \
'${xnu}/bsd/sys/sockio_private.h')
#include_next <sys/sockio.h>
EOF
'';
};
in
mkAppleDerivation {
releaseName = "libpcap";
postPatch = ''
substituteInPlace libpcap/Makefile.in \
--replace-fail '@PLATFORM_C_SRC@' '@PLATFORM_C_SRC@ pcap-darwin.c pcap-util.c pcapng.c'
substituteInPlace libpcap/pcap/pcap.h \
--replace-fail '#if PRIVATE' '#if 1'
'';
configureFlags = [
(lib.withFeatureAs true "pcap" (if stdenv.hostPlatform.isLinux then "linux" else "bpf"))
(lib.enableFeature withRemote "remote")
]
++ lib.optionals stdenv.hostPlatform.isDarwin [ (lib.enableFeature false "universal") ];
preConfigure = ''
cd libpcap
'';
env.NIX_CFLAGS_COMPILE = "-DHAVE_PKTAP_API -I${privateHeaders}/include";
nativeBuildInputs = [
bison
flex
]
++ lib.optionals withBluez [ bluez.dev ];
meta = {
description = "Packet Capture Library (with Apple modifications)";
mainProgram = "pcap-config";
};
}

View File

@@ -0,0 +1,57 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/libresolv/blob/main/libresolv.xcodeproj/project.pbxproj
# Project settings
project('libresolv', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
# Libraries
libresolv = library(
'resolv',
darwin_versions : '1',
install : true,
sources : [
'base64.c',
'dns.c',
'dns_async.c',
'dns_util.c',
'dst_api.c',
'dst_hmac_link.c',
'dst_support.c',
'ns_date.c',
'ns_name.c',
'ns_netint.c',
'ns_parse.c',
'ns_print.c',
'ns_samedomain.c',
'ns_sign.c',
'ns_ttl.c',
'ns_verify.c',
'res_comp.c',
'res_data.c',
'res_debug.c',
'res_findzonecut.c',
'res_init.c',
'res_mkquery.c',
'res_mkupdate.c',
'res_query.c',
'res_send.c',
'res_sendsigned.c',
'res_update.c',
],
soversion : '9'
)
install_headers(
'dns.h',
'dns_util.h',
'nameser.h',
'resolv.h',
)
install_man(
'resolver.3',
'resolver.5',
)

View File

@@ -0,0 +1,42 @@
{
lib,
apple-sdk,
mkAppleDerivation,
}:
let
configd = apple-sdk.sourceRelease "configd";
Libinfo = apple-sdk.sourceRelease "Libinfo";
# `arpa/nameser_compat.h` is included in the Libc source release instead of libresolv.
Libc = apple-sdk.sourceRelease "Libc";
in
mkAppleDerivation {
releaseName = "libresolv";
outputs = [
"out"
"dev"
"man"
];
xcodeHash = "sha256-yHNa6cpI3T4R/iakeHmL6S/c9p+VpYR4fudv2UXUpnY=";
postUnpack = ''
mkdir -p "$sourceRoot/arpa"
ln -s "$NIX_BUILD_TOP/$sourceRoot/nameser.h" "$sourceRoot/arpa/nameser.h"
'';
env.NIX_CFLAGS_COMPILE = "-I${configd}/dnsinfo -I${Libinfo}/lookup.subproj";
postInstall = ''
mkdir -p "$out/include/arpa"
ln -s ../nameser.h "$out/include/arpa"
cp ${Libc}/include/arpa/nameser_compat.h "$out/include/arpa"
'';
meta = {
description = "Libresolv implementation for Darwin";
license = lib.licenses.apple-psl10;
};
}

View File

@@ -0,0 +1,17 @@
# Project settings
project('libsbuf', 'c', version : '@version@')
# Libraries
library(
'sbuf',
darwin_versions : '1',
install : true,
sources : [
'subr_prf.c',
'subr_sbuf.c',
],
soversion : '6',
)
install_headers('usbuf.h')
install_man('sbuf.9')

View File

@@ -0,0 +1,86 @@
{
lib,
bootstrapStdenv,
fetchurl,
meson,
ninja,
stdenv,
}:
# Apple ships libsbuf with macOS 14 but does not provide any source releases.
# Fortunately, its a single file library that can be made to build on Darwin using the source from FreeBSD.
bootstrapStdenv.mkDerivation (finalAttrs: {
pname = "libsbuf";
version = "14.1.0";
outputs = [
"out"
"dev"
"man"
];
srcs = [
(fetchurl {
name = "subr_sbuf.c";
url = "https://cgit.freebsd.org/src/plain/sys/kern/subr_sbuf.c?h=release/${finalAttrs.version}";
hash = "sha256-+wIcXz2wuYzOXmbxjDYBh7lIpoVtw+SW/l7oMXFJUcc=";
})
(fetchurl {
name = "subr_prf.c";
url = "https://cgit.freebsd.org/src/plain/sys/kern/subr_prf.c?h=release/${finalAttrs.version}";
hash = "sha256-Sd+kJ7/RwwndK1N6YvqQqPTQRA0ajPAT0yk0rOPRpW8=";
})
(fetchurl {
name = "usbuf.h";
url = "https://cgit.freebsd.org/src/plain/sys/sys/sbuf.h?h=release/${finalAttrs.version}";
hash = "sha256-CCwh9kI/X1u16hHWiiBipvBzDKvo2S2OFtI4Jo6HF0E=";
})
(fetchurl {
name = "sbuf.9";
url = "https://cgit.freebsd.org/src/plain/share/man/man9/sbuf.9?h=release/${finalAttrs.version}";
hash = "sha256-43uUIGvYX0NvikcGTTJHrokHvubQ89ztLv/BK3MP0YY=";
})
];
sourceRoot = "source";
unpackPhase = ''
runHook preUnpack
mkdir "$sourceRoot"
for src in "''${srcs[@]}"; do
destFilename=$(basename "$src")
cp "$src" "$sourceRoot/''${src#*-}"
done
runHook postUnpack
'';
patches = [
# Fix up sources to build on Darwin and follow the same ABI used by Apple.
./patches/0001-darwin-compatibility.patch
];
postPatch = lib.optionalString stdenv.hostPlatform.isDarwin ''
substitute '${./meson.build.in}' "meson.build" --subst-var version
'';
strictDeps = true;
nativeBuildInputs = [
meson
ninja
];
__structuredAttrs = true;
meta = {
description = "Safely compose and manipulate strings in C";
homepage = "https://www.freebsd.org";
license = [
lib.licenses.bsd2
lib.licenses.bsd3
];
platforms = lib.platforms.darwin;
};
})

View File

@@ -0,0 +1,137 @@
diff '--color=auto' -ur a/subr_prf.c b/subr_prf.c
--- a/subr_prf.c 2024-09-04 20:07:10.149623000 -0400
+++ b/subr_prf.c 2024-09-04 20:14:10.265336775 -0400
@@ -64,8 +64,8 @@
#else /* !_KERNEL */
#include <errno.h>
#endif
-#include <sys/ctype.h>
-#include <sys/sbuf.h>
+#include <ctype.h>
+#include <usbuf.h>
#ifdef DDB
#include <ddb/ddb.h>
diff '--color=auto' -ur a/subr_sbuf.c b/subr_sbuf.c
--- a/subr_sbuf.c 2024-09-04 20:07:10.149810000 -0400
+++ b/subr_sbuf.c 2024-09-04 20:22:20.289037135 -0400
@@ -50,7 +50,7 @@
#include <string.h>
#endif /* _KERNEL */
-#include <sys/sbuf.h>
+#include <usbuf.h>
#ifdef _KERNEL
static MALLOC_DEFINE(M_SBUF, "sbuf", "string buffers");
@@ -96,6 +96,18 @@
#define SBUF_MAXEXTENDINCR 4096
#endif
+/* Per https://cgit.freebsd.org/src/commit/?id=8fa6abb6f4f64f4f23e2920e2aea7996566851a4 */
+#define roundup2 __builtin_align_up
+/* From https://cgit.freebsd.org/src/tree/sys/sys/cdefs.h?id=8fa6abb6f4f64f4f23e2920e2aea7996566851a4 */
+#define __predict_false(exp) __builtin_expect((exp),0)
+
+/* These symbols are exported even though the functions arent defined in the public header.
+ Redefine them for consistency. */
+#define sbuf_count_drain usbuf_count_drain
+#define sbuf_drain usbuf_drain
+#define sbuf_nl_terminate usbuf_nl_terminate
+#define sbuf_put_bytes usbuf_put_bytes
+
/*
* Debugging support
*/
diff '--color=auto' -ur a/usbuf.h b/usbuf.h
--- a/usbuf.h 2024-09-04 20:07:10.150177000 -0400
+++ b/usbuf.h 2024-09-04 20:13:26.469610458 -0400
@@ -33,6 +33,50 @@
#include <sys/_types.h>
+#include <stdarg.h>
+
+#define sbuf_new usbuf_new
+#define sbuf_clear usbuf_clear
+#define sbuf_setpos usbuf_setpos
+#define sbuf_bcat usbuf_bcat
+#define sbuf_bcpy usbuf_bcpy
+#define sbuf_cat usbuf_cat
+#define sbuf_cpy usbuf_cpy
+#define sbuf_printf usbuf_printf
+#define sbuf_vprintf usbuf_vprintf
+#define sbuf_putc usbuf_putc
+#define sbuf_set_drain usbuf_set_drain
+#define sbuf_trim usbuf_trim
+#define sbuf_error usbuf_error
+#define sbuf_finish usbuf_finish
+#define sbuf_data usbuf_data
+#define sbuf_len usbuf_len
+#define sbuf_done usbuf_done
+#define sbuf_delete usbuf_delete
+#define sbuf_clear_flags usbuf_clear_flags
+#define sbuf_get_flags usbuf_get_flags
+#define sbuf_set_flags usbuf_set_flags
+#define sbuf_start_section usbuf_start_section
+#define sbuf_end_section usbuf_end_section
+#define sbuf_hexdump usbuf_hexdump
+#define sbuf_putbuf usbuf_putbuf
+#define sbuf_printf_drain usbuf_printf_drain
+
+#define SBUF_FIXEDLEN USBUF_FIXEDLEN
+#define SBUF_AUTOEXTEND USBUF_AUTOEXTEND
+#define SBUF_INCLUDENUL USBUF_INCLUDENUL
+#define SBUF_DRAINTOEOR USBUF_DRAINTOEOR
+#define SBUF_NOWAIT USBUF_NOWAIT
+#define SBUF_USRFLAGMSK USBUF_USRFLAGMSK
+#define SBUF_DYNAMIC USBUF_DYNAMIC
+#define SBUF_FINISHED USBUF_FINISHED
+#define SBUF_DYNSTRUCT USBUF_DYNSTRUCT
+#define SBUF_INSECTION USBUF_INSECTION
+#define SBUF_DRAINATEOL USBUF_DRAINATEOL
+
+#define sbuf usbuf
+#define sbuf_drain_func usbuf_drain_func
+
struct sbuf;
typedef int (sbuf_drain_func)(void *, const char *, int);
@@ -46,17 +90,17 @@
int s_error; /* current error code */
ssize_t s_size; /* size of storage buffer */
ssize_t s_len; /* current length of string */
-#define SBUF_FIXEDLEN 0x00000000 /* fixed length buffer (default) */
-#define SBUF_AUTOEXTEND 0x00000001 /* automatically extend buffer */
-#define SBUF_INCLUDENUL 0x00000002 /* nulterm byte is counted in len */
-#define SBUF_DRAINTOEOR 0x00000004 /* use section 0 as drain EOR marker */
-#define SBUF_NOWAIT 0x00000008 /* Extend with non-blocking malloc */
-#define SBUF_USRFLAGMSK 0x0000ffff /* mask of flags the user may specify */
-#define SBUF_DYNAMIC 0x00010000 /* s_buf must be freed */
-#define SBUF_FINISHED 0x00020000 /* set by sbuf_finish() */
-#define SBUF_DYNSTRUCT 0x00080000 /* sbuf must be freed */
-#define SBUF_INSECTION 0x00100000 /* set by sbuf_start_section() */
-#define SBUF_DRAINATEOL 0x00200000 /* drained contents ended in \n */
+#define USBUF_FIXEDLEN 0x00000000 /* fixed length buffer (default) */
+#define USBUF_AUTOEXTEND 0x00000001 /* automatically extend buffer */
+#define USBUF_INCLUDENUL 0x00000002 /* nulterm byte is counted in len */
+#define USBUF_DRAINTOEOR 0x00000004 /* use section 0 as drain EOR marker */
+#define USBUF_NOWAIT 0x00000008 /* Extend with non-blocking malloc */
+#define USBUF_USRFLAGMSK 0x0000ffff /* mask of flags the user may specify */
+#define USBUF_DYNAMIC 0x00010000 /* s_buf must be freed */
+#define USBUF_FINISHED 0x00020000 /* set by sbuf_finish() */
+#define USBUF_DYNSTRUCT 0x00080000 /* sbuf must be freed */
+#define USBUF_INSECTION 0x00100000 /* set by sbuf_start_section() */
+#define USBUF_DRAINATEOL 0x00200000 /* drained contents ended in \n */
int s_flags; /* flags */
ssize_t s_sect_len; /* current length of section */
ssize_t s_rec_off; /* current record start offset */
@@ -88,7 +132,7 @@
int sbuf_cpy(struct sbuf *, const char *);
int sbuf_printf(struct sbuf *, const char *, ...)
__printflike(2, 3);
-int sbuf_vprintf(struct sbuf *, const char *, __va_list)
+int sbuf_vprintf(struct sbuf *, const char *, va_list)
__printflike(2, 0);
int sbuf_nl_terminate(struct sbuf *);
int sbuf_putc(struct sbuf *, int);

View File

@@ -0,0 +1,49 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/libutil/blob/main/libutil.xcodeproj/project.pbxproj
# Project settings
project('libutil', 'c', 'cpp', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
cxx = meson.get_compiler('cpp')
# Libraries
libutil = library(
'util',
darwin_versions : '1',
install : true,
sources : [
'ExtentManager.cpp',
'expand_number.c',
'getmntopts.c',
'humanize_number.c',
'pidfile.c',
'realhostname.c',
'reexec_to_match_kernel.c',
'trimdomain.c',
'tzbootuuid.c',
'tzlink.c',
'tzlink.h',
'wipefs.cpp',
],
)
install_headers(
'libutil.h',
'mntopts.h',
'tzlink.h',
'wipefs.h',
)
install_man(
'expand_number.3',
'getmntopts.3',
'humanize_number.3',
'pidfile.3',
'realhostname.3',
'realhostname_sa.3',
'reexec_to_match_kernel.3',
'trimdomain.3',
'wipefs.3',
)

View File

@@ -0,0 +1,29 @@
{
apple-sdk_14,
copyfile,
mkAppleDerivation,
}:
mkAppleDerivation {
releaseName = "libutil";
outputs = [
"out"
"dev"
"man"
];
xcodeHash = "sha256-LwR9fmvcdJ/QYlOx+7ffhV4mKvjkwN3rX3+yHSCovKQ=";
patches = [
# The only change from macOS 13 to 14 was setting this flag. Check at runtime and only set if supported.
./patches/0001-Conditionally-pre-condition.patch
];
buildInputs = [
(apple-sdk_14.override { enableBootstrap = true; })
copyfile
];
meta.description = "System utilities library";
}

View File

@@ -0,0 +1,26 @@
From ca796729722da704e8a9c64c7a201cbe0a9cb9be Mon Sep 17 00:00:00 2001
From: Randy Eckenrode <randy@largeandhighquality.com>
Date: Mon, 5 Aug 2024 22:21:47 -0400
Subject: [PATCH] Conditionally pre-condition
---
wipefs.cpp | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/wipefs.cpp b/wipefs.cpp
index d8e6339..6cb7963 100644
--- a/wipefs.cpp
+++ b/wipefs.cpp
@@ -391,7 +391,9 @@ wipefs_wipe(wipefs_ctx handle)
// Since we always issue a a single extent, set the kIOStorageUnmapOptionWhole
// option flag for drive pre-conditioning.
//
- unmap.options = kIOStorageUnmapOptionWhole;
+ if (__builtin_available(macOS 14.0, *)) {
+ unmap.options = kIOStorageUnmapOptionWhole;
+ }
//
// Don't bother to check the return value since this is mostly
--
2.44.1

View File

@@ -0,0 +1,63 @@
{
lib,
adv_cmds,
bmake,
fetchFromGitHub,
stdenvNoCC,
}:
stdenvNoCC.mkDerivation (finalAttrs: {
pname = "locale";
version = "118";
# This data is old, but its closer to what macOS has than FreeBSD. Trying to use the FreeBSD data
# results in test failures due to different behavior (e.g., with zh_CN and spaces in gnulibs `trim` test).
# TODO(@reckenrode) Update locale data using https://cldr.unicode.org to match current macOS locale data.
src = fetchFromGitHub {
owner = "apple-oss-distributions";
repo = "adv_cmds";
rev = "adv_cmds-118";
hash = "sha256-KzaAlqXqfJW2s31qmA0D7qteaZY57Va2o86aZrwyR74=";
};
sourceRoot = "${finalAttrs.src.name}/usr-share-locale.tproj";
postPatch = ''
# bmake expects `Makefile` not `BSDmakefile`.
find . -name Makefile -exec rm {} \; -exec ln -s BSDmakefile {} \;
# Update `Makefile`s to: get commands from `PATH`, and install to the correct location.
# Note: not every `Makefile` has `rsync` or the project name in it.
for subproject in colldef mklocale monetdef msgdef numericdef timedef; do
substituteInPlace "$subproject/BSDmakefile" \
--replace-warn "../../$subproject.tproj/" "" \
--replace-fail /usr/share/locale /share/locale \
--replace-fail '-o ''${BINOWN} -g ''${BINGRP}' "" \
--replace-warn "rsync -a" "cp -r"
done
# Update `bsdmake` references to `bmake`
substituteInPlace Makefile \
--replace-fail bsdmake bmake
'';
enableParallelBuilding = true;
nativeBuildInputs = [
adv_cmds
bmake
];
enableParallelInstalling = true;
installFlags = [ "DESTDIR=${placeholder "out"}" ];
meta = {
description = "Locale data for Darwin";
license = [
lib.licenses.apsl10
lib.licenses.apsl20
];
teams = [ lib.teams.darwin ];
};
})

View File

@@ -0,0 +1,53 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/mail_cmds/blob/main/mail_cmds.xcodeproj/project.pbxproj
# Project settings
project('mail_cmds', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
# Binaries
executable(
'mail',
install : true,
sources : [
'mail/cmd1.c',
'mail/cmd2.c',
'mail/cmd3.c',
'mail/cmdtab.c',
'mail/collect.c',
'mail/edit.c',
'mail/fio.c',
'mail/getname.c',
'mail/head.c',
'mail/lex.c',
'mail/list.c',
'mail/main.c',
'mail/names.c',
'mail/popen.c',
'mail/quit.c',
'mail/send.c',
'mail/strings.c',
'mail/temp.c',
'mail/tty.c',
'mail/util.c',
'mail/v7.local.c',
'mail/vars.c',
'mail/version.c',
],
)
install_man('mail/mail.1')
install_symlink(
'mailx',
install_dir : get_option('bindir'),
pointing_to : 'mail',
)
install_symlink(
'mailx.1',
install_dir : get_option('mandir') / 'man1',
pointing_to : 'mail.1',
)

View File

@@ -0,0 +1,20 @@
{
lib,
apple-sdk,
file_cmds,
mkAppleDerivation,
pkg-config,
}:
mkAppleDerivation {
releaseName = "mail_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-6rBflDgQkqWDc8XPLgKIO703bMamg2QlhUnP71hBX3I=";
meta.description = "Traditional mail command for Darwin";
}

View File

@@ -0,0 +1,92 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/misc_cmds/blob/main/misc_cmds.xcodeproj/project.pbxproj
# Project settings
project('misc_cmds', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
libedit = dependency('libedit')
libutil = cc.find_library('util')
ncurses = dependency('ncurses')
# Binaries
executable(
'calendar',
c_args : [ '-D__FBSDID=__RCSID' ],
dependencies : [ libutil ],
install : true,
sources : [
'calendar/calendar.c',
'calendar/dates.c',
'calendar/day.c',
'calendar/events.c',
'calendar/io.c',
'calendar/locale.c',
'calendar/ostern.c',
'calendar/parsedata.c',
'calendar/paskha.c',
'calendar/pom.c',
'calendar/sunpos.c',
],
)
install_data(
'calendar/calendars/calendar.apple',
'calendar/calendars/calendar.freebsd',
install_dir : get_option('datadir') / 'calendar',
)
install_man('calendar/calendar.1')
executable(
'leave',
c_args : [
'-D__FBSDID=__RCSID',
'-Du_int=uint32_t',
'-include', 'stdint.h',
],
install : true,
sources : [ 'leave/leave.c' ],
)
install_man('leave/leave.1')
executable(
'ncal',
dependencies : [ ncurses ],
include_directories : 'ncal',
install : true,
sources : [
'ncal/calendar.c',
'ncal/easter.c',
'ncal/ncal.c',
],
)
install_man('ncal/ncal.1')
install_symlink(
'cal',
install_dir : get_option('bindir'),
pointing_to : 'ncal',
)
install_symlink(
'cal.1',
install_dir : get_option('mandir') / 'man1',
pointing_to : 'ncal.1',
)
executable(
'tsort',
install : true,
sources : [ 'tsort/tsort.c' ],
)
install_man('tsort/tsort.1')
executable(
'units',
dependencies : [ libedit ],
install : true,
sources : [ 'units/units.c' ],
)
install_man('units/units.1')

View File

@@ -0,0 +1,38 @@
{
lib,
libedit,
libutil,
mkAppleDerivation,
ncurses,
pkg-config,
}:
mkAppleDerivation {
releaseName = "misc_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-xuEHBlgys/xI9lm/wtiVAKi+AWWvRluW2I4rWOmS1kw=";
postPatch = ''
substituteInPlace calendar/pathnames.h \
--replace-fail '/usr' "$out"
substituteInPlace calendar/io.c \
--replace-fail '/usr/local' "$out"
substituteInPlace calendar/calendar.1 \
--replace-fail '/usr/local/share/calendar, /usr/share/calendar' "$out/share/calendar"
'';
nativeBuildInputs = [ pkg-config ];
buildInputs = [
libedit
libutil
ncurses
];
meta.description = "Miscellaneous commands for Darwin";
}

View File

@@ -0,0 +1,90 @@
let
versions = builtins.fromJSON (builtins.readFile ./versions.json);
in
{
lib,
bootstrapStdenv,
fetchFromGitHub,
meson,
ninja,
stdenv,
stdenvNoCC,
xcodeProjectCheckHook,
}:
let
hasBasenamePrefix = prefix: file: lib.hasPrefix prefix (baseNameOf file);
in
lib.makeOverridable (
attrs:
let
attrs' = if lib.isFunction attrs then attrs else _: attrs;
attrsFixed = lib.fix attrs';
stdenv' =
if attrsFixed.noCC or false then
stdenvNoCC
else if attrsFixed.noBootstrap or false then
stdenv
else
bootstrapStdenv;
in
stdenv'.mkDerivation (
lib.extends (
self: super:
assert super ? releaseName;
let
inherit (super) releaseName;
info = versions.${releaseName};
files = lib.filesystem.listFilesRecursive (lib.path.append ./. releaseName);
mesonFiles = lib.filter (hasBasenamePrefix "meson") files;
in
# You have to have at least `meson.build.in` when using xcodeHash to trigger the Meson
# build support in `mkAppleDerivation`.
assert super ? xcodeHash -> lib.length mesonFiles > 0;
{
pname = super.pname or releaseName;
inherit (info) version;
src = super.src or fetchFromGitHub {
owner = "apple-oss-distributions";
repo = releaseName;
rev = info.rev or "${releaseName}-${info.version}";
inherit (info) hash;
};
strictDeps = true;
__structuredAttrs = true;
meta = {
homepage = "https://opensource.apple.com/releases/";
license = lib.licenses.apple-psl20;
teams = [ lib.teams.darwin ];
platforms = lib.platforms.darwin;
}
// super.meta or { };
}
// lib.optionalAttrs (super ? xcodeHash) {
postUnpack =
super.postUnpack or ""
+ lib.concatMapStrings (
file:
if baseNameOf file == "meson.build.in" then
"substitute ${lib.escapeShellArg "${file}"} \"$sourceRoot/meson.build\" --subst-var version\n"
else
"cp ${lib.escapeShellArg "${file}"} \"$sourceRoot/\"${lib.escapeShellArg (baseNameOf file)}\n"
) mesonFiles;
xcodeProject = super.xcodeProject or "${releaseName}.xcodeproj";
nativeBuildInputs = super.nativeBuildInputs or [ ] ++ [
meson
ninja
xcodeProjectCheckHook
];
mesonBuildType = "release";
}
) attrs'
)
)

View File

@@ -0,0 +1,361 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/network_cmds/blob/main/network_cmds.xcodeproj/project.pbxproj
# Project settings
project('network_cmds', 'c', version : '@version@')
add_global_arguments(
# Many programs use old prototypes
'-Wno-deprecated-non-prototype',
# Suppresses suffixing symbols with '$UNIX2003', which causes link failures.
'-D__DARWIN_ONLY_UNIX_CONFORMANCE=1',
# Use 64-bit inode symbols without an '$INODE64' suffix, which causes link failures.
'-D__DARWIN_ONLY_64_BIT_INO_T=1',
# Per the Xcode project
'-DUSE_RFC2292BIS=1',
'-D__APPLE_USE_RFC_3542=1',
'-D__APPLE_API_OBSOLETE=1',
language : 'c',
)
# Dependencies
cc = meson.get_compiler('c')
libipsec = cc.find_library('ipsec')
libresolv = cc.find_library('resolv')
libpcap = dependency('pcap')
openssl = dependency('openssl')
# Internal Libraries
corecrypto = declare_dependency(
dependencies : [ openssl ],
include_directories : 'compat',
link_with : static_library(
'corecrypto',
include_directories : 'compat',
sources : [
'compat/corecrypto/ccdigest.c',
'compat/corecrypto/ccsha1.c',
'compat/corecrypto/ccsha2.c',
],
),
)
libnetwork_cmds = declare_dependency(
include_directories : 'network_cmds_lib',
link_with : static_library(
'network_cmds',
include_directories : 'network_cmds_lib',
sources : [
'network_cmds_lib/network_cmds_lib.c',
'network_cmds_lib/network_cmds_lib_test.c',
],
),
)
# Binaries
executable(
'arp',
dependencies : [ libnetwork_cmds ],
install : true,
sources : [ 'arp.tproj/arp.c' ],
)
install_man(
'arp.tproj/arp.8',
'arp.tproj/arp4.4',
)
executable(
'cfilutil',
dependencies : [ corecrypto ],
install : true,
sources : [
'cfilutil/cfilstat.c',
'cfilutil/cfilutil.c',
],
)
install_man('cfilutil/cfilutil.1')
executable(
'dnctl',
install : true,
sources : [ 'dnctl/dnctl.c' ],
)
install_man('dnctl/dnctl.8')
executable(
'ecnprobe',
dependencies : [ libnetwork_cmds, libpcap ],
install : true,
sources : [
'ecnprobe/capture.c',
'ecnprobe/ecn.c',
'ecnprobe/ecn_probe.c',
'ecnprobe/gmt2local.c',
'ecnprobe/history.c',
'ecnprobe/inet.c',
'ecnprobe/session.c',
'ecnprobe/support.c',
],
)
install_man('ecnprobe/ecnprobe.1')
executable(
'frame_delay',
install : true,
sources : [ 'frame_delay/frame_delay.c' ],
)
install_man('frame_delay/frame_delay.8')
executable(
'ifconfig',
c_args : [
'-DUSE_BONDS',
'-DUSE_VLANS',
],
install : true,
sources : [
'ifconfig.tproj/af_inet.c',
'ifconfig.tproj/af_inet6.c',
'ifconfig.tproj/af_link.c',
'ifconfig.tproj/ifbond.c',
'ifconfig.tproj/ifbridge.c',
'ifconfig.tproj/ifclone.c',
'ifconfig.tproj/ifconfig.c',
'ifconfig.tproj/iffake.c',
'ifconfig.tproj/ifmedia.c',
'ifconfig.tproj/ifvlan.c',
'ifconfig.tproj/nexus.c',
],
)
install_man('ifconfig.tproj/ifconfig.8')
executable(
'ip6addrctl',
install : true,
sources : [ 'ip6addrctl.tproj/ip6addrctl.c' ],
)
install_man('ip6addrctl.tproj/ip6addrctl.8')
executable(
'kdumpd',
dependencies : [ libnetwork_cmds ],
install : true,
sources : [
'kdumpd.tproj/kdumpd.c',
'kdumpd.tproj/kdumpsubs.c',
],
)
install_man('kdumpd.tproj/kdumpd.8')
executable(
'mnc',
install : true,
sources : [
'mnc.tproj/mnc_main.c',
'mnc.tproj/mnc_multicast.c',
'mnc.tproj/mnc_opts.c',
],
)
install_man('mnc.tproj/mnc.1')
executable(
'mptcp_client',
install : true,
sources : [
'mptcp_client/conn_lib.c',
'mptcp_client/mptcp_client.c',
],
)
install_man('mptcp_client/mptcp_client.1')
executable(
'mtest',
install : true,
sources : [ 'mtest.tproj/mtest.c' ],
)
install_man('mtest.tproj/mtest.8')
executable(
'ndp',
c_args : [
'-DINET6',
'-DISPEC_DEBUG',
'-DKAME_SCOPEID',
],
install : true,
sources : [ 'ndp.tproj/ndp.c' ],
)
install_man('ndp.tproj/ndp.8')
executable(
'netstat',
c_args : [
'-DINET6',
'-DIPSEC',
],
dependencies : [ libnetwork_cmds ],
install : true,
sources : [
# 'netstat.tproj/bpf.c',
'netstat.tproj/data.c',
'netstat.tproj/if.c',
'netstat.tproj/inet.c',
'netstat.tproj/inet6.c',
'netstat.tproj/ipsec.c',
'netstat.tproj/main.c',
'netstat.tproj/mbuf.c',
'netstat.tproj/mcast.c',
'netstat.tproj/misc.c',
'netstat.tproj/mptcp.c',
'netstat.tproj/route.c',
'netstat.tproj/systm.c',
'netstat.tproj/tp_astring.c',
'netstat.tproj/unix.c',
'netstat.tproj/vsock.c',
],
)
install_man('netstat.tproj/netstat.1')
executable(
'ping',
dependencies : [ libnetwork_cmds ],
install : true,
sources : [
'ecnprobe/gmt2local.c',
'ping.tproj/ping.c'
],
)
install_man('ping.tproj/ping.8')
executable(
'ping6',
dependencies : [ libnetwork_cmds, libresolv ],
install : true,
sources : [
'ecnprobe/gmt2local.c',
'ping6.tproj/md5.c',
'ping6.tproj/ping6.c',
],
)
install_man('ping6.tproj/ping6.8')
executable(
'pktapctl',
install : true,
sources : [ 'pktapctl/pktapctl.c' ],
)
install_man('pktapctl/pktapctl.8')
executable(
'pktmnglr',
install : true,
sources : [ 'pktmnglr/packet_mangler.c' ],
)
executable(
'rarpd',
c_args : [ '-DTFTP_DIR="tftpboot"' ],
install : true,
sources : [ 'rarpd.tproj/rarpd.c' ],
)
install_man('rarpd.tproj/rarpd.8')
executable(
'route',
c_args : [
'-DINET6',
'-DIPSEC',
],
dependencies : [ libnetwork_cmds ],
install : true,
sources : [ 'route.tproj/route.c' ],
)
install_man('route.tproj/route.8')
# Depends on a bunch of IPv6 stuff from later SDKs (>11.3). Package once those become the default.
# executable(
# 'rtadvd',
# c_args : [
# '-DINET6',
# '-DHAVE_GETIFADDRS',
# ],
# install : true,
# sources : [
# 'rtadvd.tproj/advcap.c',
# 'rtadvd.tproj/config.c',
# 'rtadvd.tproj/dump.c',
# 'rtadvd.tproj/if.c',
# 'rtadvd.tproj/rrenum.c',
# 'rtadvd.tproj/rtadvd.c',
# 'rtadvd.tproj/rtadvd_logging.c',
# 'rtadvd.tproj/timer.c',
# ],
# )
# install_man(
# 'rtadvd.tproj/rtadvd.8',
# 'rtadvd.tproj/rtadvd.conf.5',
# )
executable(
'rtsol',
c_args : [
'-DINET6',
'-DHAVE_GETIFADDRS',
],
install : true,
sources : [
'rtsol.tproj/dump.c',
'rtsol.tproj/if.c',
'rtsol.tproj/probe.c',
'rtsol.tproj/rtsock.c',
'rtsol.tproj/rtsol.c',
'rtsol.tproj/rtsold.c',
],
)
install_man('rtsol.tproj/rtsol.8')
executable(
'spray',
install : true,
sources : [
'spray.tproj/spray.c',
'spray.tproj/spray_xdr.c',
],
)
install_man('spray.tproj/spray.8')
executable(
'traceroute',
c_args : [ '-DHAVE_SOCKADDR_SA_LEN' ],
dependencies : [ libnetwork_cmds, libpcap ],
install : true,
sources : [
'traceroute.tproj/as.c',
'traceroute.tproj/findsaddr-socket.c',
'traceroute.tproj/ifaddrlist.c',
'traceroute.tproj/traceroute.c',
'traceroute.tproj/version.c',
],
)
install_man('traceroute.tproj/traceroute.8')
executable(
'traceroute6',
c_args : [
'-include', 'net/if_var.h', # Fix missing definition of `IFNAMSIZE`
'-DINET6',
'-DIPSEC',
],
dependencies : [ libipsec, libnetwork_cmds, libpcap ],
include_directories : 'traceroute.tproj',
install : true,
sources : [
'traceroute.tproj/as.c',
'traceroute6.tproj/traceroute6.c'
],
)
install_man('traceroute6.tproj/traceroute6.8')

View File

@@ -0,0 +1,456 @@
{
lib,
apple-sdk,
fetchurl,
libpcap,
libresolv,
mkAppleDerivation,
openssl,
pkg-config,
stdenvNoCC,
unifdef,
}:
let
# Newer releases of ifconfig use `ioctls` and undocumented APIs newer than 11.x.
# Use files from an older release for now.
old_ifconfig = {
ifconfig = fetchurl {
url = "https://github.com/apple-oss-distributions/network_cmds/raw/2e18102a14ab72b25caf3a5007c92b9f23e723fc/ifconfig.tproj/ifconfig.c";
hash = "sha256-yuUpdRHRwYLnivuaQuh8HJdLj/8ppq+K1NFqA8Bg+1k=";
};
af_inet = fetchurl {
url = "https://github.com/apple-oss-distributions/network_cmds/raw/2e18102a14ab72b25caf3a5007c92b9f23e723fc/ifconfig.tproj/af_inet.c";
hash = "sha256-sqcCEzhTur43DG6Ac/1Rt8Kx0umWhDzlV58t+6FlzNU=";
};
af_inet6 = fetchurl {
url = "https://github.com/apple-oss-distributions/network_cmds/raw/2e18102a14ab72b25caf3a5007c92b9f23e723fc/ifconfig.tproj/af_inet6.c";
hash = "sha256-jp0R0Ncwvp9G/lIzKW6wBTAiO8yNyII5c49feTanbIo=";
};
af_link = fetchurl {
url = "https://github.com/apple-oss-distributions/network_cmds/raw/2e18102a14ab72b25caf3a5007c92b9f23e723fc/ifconfig.tproj/af_link.c";
hash = "sha256-5rXJg5azy9SjK675Djt4K1PaczsoVjQ/Lls/u5Kk1+A=";
};
};
# Newer releases of netstat use struct members that arent present with the 11.x headers.
# Use files from an older release for now.
old_netstat = {
"if.c" = fetchurl {
url = "https://github.com/apple-oss-distributions/network_cmds/raw/2e18102a14ab72b25caf3a5007c92b9f23e723fc/netstat.tproj/if.c";
hash = "sha256-P87rexLkoV1BCyUghVrkGoG6r9rAoWynfpvlwIj7A40=";
};
"main.c" = fetchurl {
url = "https://github.com/apple-oss-distributions/network_cmds/raw/2e18102a14ab72b25caf3a5007c92b9f23e723fc/netstat.tproj/main.c";
hash = "sha256-e3n54l6Wo+G5koMhGMfOTo8+QIkJRurr2fBOjg/nFgI=";
};
"inet.c" = fetchurl {
url = "https://github.com/apple-oss-distributions/network_cmds/raw/2e18102a14ab72b25caf3a5007c92b9f23e723fc/netstat.tproj/inet.c";
hash = "sha256-X1+dz+D6xR2Xqoxypjmy65pKBCh4iGVfByJGI0wVGO0=";
};
"inet6.c" = fetchurl {
url = "https://github.com/apple-oss-distributions/network_cmds/raw/2e18102a14ab72b25caf3a5007c92b9f23e723fc/netstat.tproj/inet6.c";
hash = "sha256-av5K1UQE3edUbzKN9FIn/DOeibsJaTZc0xJzDu9VZ5Q=";
};
"netstat.h" = fetchurl {
url = "https://github.com/apple-oss-distributions/network_cmds/raw/2e18102a14ab72b25caf3a5007c92b9f23e723fc/netstat.tproj/netstat.h";
hash = "sha256-UYi3lmA8G0wRJqVA2NYyMj0yCBUlxu0gMoMYW7NauJg=";
};
"unix.c" = fetchurl {
url = "https://github.com/apple-oss-distributions/network_cmds/raw/2e18102a14ab72b25caf3a5007c92b9f23e723fc/netstat.tproj/unix.c";
hash = "sha256-txs/mnR4WK8JAUN3PtqZsp6q2h+nx5VFKxI/itCTBNo=";
};
"systm.c" = fetchurl {
url = "https://github.com/apple-oss-distributions/network_cmds/raw/2e18102a14ab72b25caf3a5007c92b9f23e723fc/netstat.tproj/systm.c";
hash = "sha256-bISSIsA6OYfkHNOKB4dj9KNLBHfcelGVzwGiYiVqnRM=";
};
};
xnu = apple-sdk.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "network_cmds-deps-private-headers";
nativeBuildInputs = [ unifdef ];
buildCommand = ''
# Different strategies are needed to make private headers available to network_cmds:
# - If the headers can be used as-is, copy them;
# - If the required symbols are hidden behind a 'PRIVATE' define, `unifdef` is used to expose only those symbols
# for that header. Processing the header avoids exposing unwanted private symbols and requiring more headers;
# - If the symbol is hidden behind a kernel-related define, grep them out of the header. Otherwise,
# the required headers can conflict with system-related headers and require many, many more headers be copied.
install -D -t "$out/include" \
'${xnu}/osfmk/kern/cs_blobs.h'
install -D -t "$out/firehose" \
'${xnu}/libkern/firehose/tracepoint_private.h'
install -D -t "$out/include/net" \
'${xnu}/bsd/net/if_bond_internal.h' \
'${xnu}/bsd/net/if_bond_var.h' \
'${xnu}/bsd/net/if_fake_var.h' \
'${xnu}/bsd/net/if_vlan_var.h' \
'${xnu}/bsd/net/lacp.h' \
'${xnu}/bsd/net/net_perf.h'
mkdir -p "$out/include/net/classq" "$out/include/net/pktsched"
# IFNET constants are defined as enums, so they have to be pre-processed and grepped from the file.
cat <<EOF > "$out/include/net/if.h"
#pragma once
#include <uuid/uuid.h>
$(sed \
-e 's/^\s*\(IFNET_[^=]*\)=\s*\([^,]*\),*/#define \1\2/' \
'${xnu}/bsd/net/if.h' | grep '^#define IFNET_')
#include_next <net/if.h>
#include <netinet/in.h>
#define ifreq ifreq_private
$(sed -n \
-e '/^#define IFEF_TXSTART/p' \
-e '/^#define IFLPRF/p' \
-e '/^#define IFNAMSIZ\s/p' \
-e '/^#define IFRLOGF/p' \
-e '/^#define IFRTYPE/p' \
-e '/^#define IF_DESCSIZE\s/p' \
-e '/^#define IF_NAMESIZE\s/p' \
-e '/^#define NAT64_MAX_NUM_PREFIXES\s/p' \
-e '/^#define ifr_fastlane_capable\s/p' \
-e '/^#define ifr_fastlane_enabled\s/p' \
-e '/^#define ifr_qosmarking_enabled\s/p' \
-e '/^#define ifr_qosmarking_mode\s/p' \
-e '/^struct if_agentidsreq\s*{/,/^};/p' \
-e '/^struct if_clat46req\s*{/,/^};/p' \
-e '/^struct if_descreq\s*{/,/^};/p' \
-e '/^struct if_ipv6_address\s*{/,/^};/p' \
-e '/^struct if_linkparamsreq\s*{/,/^};/p' \
-e '/^struct if_qstatsreq\s*{/,/^};/p' \
-e '/^struct if_nat64req\s*{/,/^};/p' \
-e '/^struct if_nexusreq\s*{/,/^};/p' \
-e '/^struct if_throttlereq\s*{/,/^};/p' \
-e '/^struct ipv6_prefix\s*{/,/^};/p' \
-e '/^struct ifreq\s*{/,/^};/p' \
'${xnu}/bsd/net/if.h')
#undef ifreq
EOF
unifdef -x 1 -DPRIVATE -m "$out/include/net/if.h"
cat <<EOF > "$out/include/net/content_filter.h"
#pragma once
#include <uuid/uuid.h>
#include <net/content_filter_impl.h>
EOF
cat <<EOF > "$out/include/net/if_var.h"
#pragma once
#include_next <net/if_var.h>
$(sed -n \
-e '/^#define IFNAMSIZ\s/p' \
-e '/^#define IF_NETEM/p' \
-e '/^struct if_bandwidths\s*{/,/^};/p' \
-e '/^struct if_data_extended\s*{/,/^};/p' \
-e '/^struct if_interface_state\s*{/,/^};/p' \
-e '/^struct if_latencies\s*{/,/^};/p' \
-e '/^struct if_linkparamsreq\s*{/,/^};/p' \
-e '/^struct if_netem_params\s*{/,/^};/p' \
-e '/^struct if_netif_stats\s*{/,/^};/p' \
-e '/^struct if_packet_stats\s*{/,/^};/p' \
-e '/^struct if_rxpoll_stats\s*{/,/^};/p' \
-e '/^struct if_traffic_class\s*{/,/^};/p' \
'${xnu}/bsd/net/if_var.h')
EOF
cat <<EOF > "$out/include/net/route.h"
#pragma once
#include_next <net/route.h>
$(sed -n \
-e '/^struct rt_msghdr_ext\s*{/,/^};/p' \
-e '/^struct rt_reach_info\s*{/,/^};/p' \
'${xnu}/bsd/net/route.h')
EOF
ln -s "$out/include/net/route.h" "$out/include/net/route_private.h"
install -D -t "$out/include/netinet" \
'${xnu}/bsd/netinet/ip_flowid.h'
cat <<EOF > "$out/include/netinet/in.h"
#pragma once
#include_next <netinet/in.h>
$(sed -n \
-e '/^#define _DSCP/p' \
-e '/^#define IP_NO/p' \
-e '/^union sockaddr_in_4_6\s*{/,/^};/p' \
'${xnu}/bsd/netinet/in.h')
#include <uuid/uuid.h>
EOF
cat <<EOF > "$out/include/netinet/tcp.h"
#pragma once
$(sed -n \
-e '/^struct tcp_info\s*{/,/^};/p' \
-e '/^struct tcp_conn_status\s*{/,/^};/p' \
-e '/^typedef struct conninfo_tcp\s*{/,/} conninfo_tcp_t;/p' \
'${xnu}/bsd/netinet/tcp.h')
#include_next <netinet/tcp.h>
EOF
install -D -t "$out/include/netinet6" \
'${xnu}/bsd/netinet6/in6_pcb.h' \
'${xnu}/bsd/netinet6/ip6_var.h'
cat <<EOF > "$out/include/netinet6/in6.h"
#pragma once
$(sed -n \
-e '/^#define IPV6_/p' \
'${xnu}/bsd/netinet6/in6.h')
#include_next <netinet6/in6.h>
EOF
cat <<EOF > "$out/include/netinet6/in6_var.h"
#pragma once
$(sed -n \
-e '/^#define IN6_CGA/p' \
-e '/^#define SIOCSETROUTERMODE_IN6\s/p' \
-e '/^struct in6_cga_modifier\s*{/,/^};/p' \
-e '/^struct in6_cga_nodecfg\s*{/,/^};/p' \
-e '/^struct in6_cga_prepare\s*{/,/^};/p' \
'${xnu}/bsd/netinet6/in6_var.h')
#include_next <netinet6/in6_var.h>
EOF
mkdir -p "$out/include/netinet6"
cat <<EOF > "$out/include/netinet6/nd6.h"
#pragma once
$(sed -n \
-e '/^#define ND6_IFF/p' \
'${xnu}/bsd/netinet6/nd6.h')
#include_next <netinet6/nd6.h>
EOF
install -D -t "$out/include/os" \
'${xnu}/libkern/os/log_private.h'
declare -a privateHeaders=(
net/classq/classq.h
net/classq/if_classq.h
net/if_bridgevar.h
net/if_llreach.h
net/if_mib.h
net/if_ports_used.h
net/net_api_stats.h
net/network_agent.h
net/ntstat.h
net/packet_mangler.h
net/pktap.h
net/pktsched/pktsched.h
net/pktsched/pktsched_fq_codel.h
net/radix.h
netinet/igmp_var.h
netinet/in_pcb.h
netinet/in_stat.h
netinet/ip_dummynet.h
netinet/mptcp_var.h
netinet/tcp_var.h
netinet6/mld6_var.h
sys/mbuf.h
)
mkdir -p "$out/include/sys"
for header in "''${privateHeaders[@]}"; do
unifdef -x 1 -DPRIVATE -o "$out/include/$header" '${xnu}/bsd/'$header
done
unifdef -x 1 -DPRIVATE -o "$out/include/net/content_filter_impl.h" '${xnu}/bsd/net/content_filter.h'
cat <<EOF > "$out/include/sys/kern_control.h"
#pragma once
$(sed -n \
-e '/^#define MAX_KCTL_NAME\s/p' \
-e '/^struct kctlstat\s*{/,/^};/p' \
-e '/^struct xkctl_reg\s*{/,/^};/p' \
-e '/^struct xkctlpcb\s*{/,/^};/p' \
'${xnu}/bsd/sys/kern_control.h')
#include_next <sys/kern_control.h>
EOF
cat <<EOF > "$out/include/sys/kern_event.h"
#pragma once
$(sed -n \
-e '/^struct kevtstat\s*{/,/^};/p' \
-e '/^struct xkevtpcb\s*{/,/^};/p' \
'${xnu}/bsd/sys/kern_event.h')
#include_next <sys/kern_event.h>
EOF
cat <<EOF > "$out/include/sys/socket.h"
#pragma once
#include <sys/param.h>
#include <sys/_types/_socklen_t.h>
$(sed -n \
-e '/^#define AF_MULTIPATH\s/p' \
-e '/^#define CIAUX_TCP\s/p' \
-e '/^#define NET_RT_/p' \
-e '/^#define SO_RECV/p' \
-e '/^#define SO_TRAFFIC_CLASS\s/,/^#define SO_TC_MAX/p' \
-e '/^typedef.*sae_associd_t/p' \
-e '/^typedef.*sae_connid_t/p' \
-e '/^struct so_aidreq\s*{/,/^};/p' \
-e '/^struct so_cidreq\s*{/,/^};/p' \
-e '/^struct so_cinforeq\s*{/,/^};/p' \
-e '/^struct so_cordreq\s*{/,/^};/p' \
'${xnu}/bsd/sys/socket.h')
#include_next <sys/socket.h>
EOF
cat <<EOF > "$out/include/sys/socketvar.h"
#pragma once
$(sed -n \
-e '/^#define SO_TC_STATS_MAX\s/p' \
-e '/^#define XSO_/p' \
-e '/^struct data_stats\s*{/,/^};/p' \
-e '/^struct soextbkidlestat\s*{/,/^};/p' \
-e '/^struct xsocket_n\s*{/,/^};/p' \
-e '/^struct xsockbuf_n\s*{/,/^};/p' \
-e '/^struct xsockstat_n\s*{/,/^};/p' \
'${xnu}/bsd/sys/socketvar.h')
#include_next <sys/socketvar.h>
EOF
cat <<EOF > "$out/include/sys/sockio.h"
#pragma once
#define ifreq ifreq_private
$(sed -n \
-e '/^#define SIOCGASSOCIDS\s/p' \
-e '/^#define SIOCGCONNIDS\s/p' \
-e '/^#define SIOCGCONNINFO\s/p' \
-e '/^#define SIOCGIFAGENTDATA\s/p' \
-e '/^#define SIOCGIFAGENTIDS\s/p' \
-e '/^#define SIOCGIFCLAT46ADDR\s/p' \
-e '/^#define SIOCGIFDELEGATE\s/p' \
-e '/^#define SIOCGIFDESC\s/p' \
-e '/^#define SIOCGIFEFLAGS\s/p' \
-e '/^#define SIOCGIFGETRTREFCNT\s/p' \
-e '/^#define SIOCGIFINTERFACESTATE\s/p' \
-e '/^#define SIOCGIFLINKPARAMS\s/p' \
-e '/^#define SIOCGIFLINKQUALITYMETRIC\s/p' \
-e '/^#define SIOCGIFLOG\s/p' \
-e '/^#define SIOCGIFLOWPOWER\s/p' \
-e '/^#define SIOCGIFMPKLOG\s/p' \
-e '/^#define SIOCGIFNAT64PREFIX\s/p' \
-e '/^#define SIOCGIFNEXUS\s/p' \
-e '/^#define SIOCGIFQUEUESTATS\s/p' \
-e '/^#define SIOCGIFTHROTTLE\s/p' \
-e '/^#define SIOCGIFTIMESTAMPENABLED\s/p' \
-e '/^#define SIOCGIFTYPE\s/p' \
-e '/^#define SIOCGIFXFLAGS\s/p' \
-e '/^#define SIOCGSTARTDELAY\s/p' \
-e '/^#define SIOCSECNMODE\s/p' \
-e '/^#define SIOCSETROUTERMODE\s/p' \
-e '/^#define SIOCSFASTLANECAPABLE\s/p' \
-e '/^#define SIOCSFASTLEENABLED\s/p' \
-e '/^#define SIOCSIF2KCL\s/p' \
-e '/^#define SIOCSIFDESC\s/p' \
-e '/^#define SIOCSIFDISABLEOUTPUT\s/p' \
-e '/^#define SIOCSIFEXPENSIVE\s/p' \
-e '/^#define SIOCSIFINTERFACESTATE\s/p' \
-e '/^#define SIOCSIFLINKPARAMS\s/p' \
-e '/^#define SIOCSIFLOG\s/p' \
-e '/^#define SIOCSIFLOWPOWER\s/p' \
-e '/^#define SIOCSIFMPKLOG\s/p' \
-e '/^#define SIOCSIFPROBECONNECTIVITY\s/p' \
-e '/^#define SIOCSIFSUBFAMILY\s/p' \
-e '/^#define SIOCSIFTHROTTLE\s/p' \
-e '/^#define SIOCSIFTIMESTAMPDISABLE\s/p' \
-e '/^#define SIOCSIFTIMESTAMPENABLE\s/p' \
-e '/^#define SIOCSQOSMARKINGENABLED\s/p' \
-e '/^#define SIOCSQOSMARKINGMODE\s/p' \
'${xnu}/bsd/sys/sockio.h')
#undef ifreq
#include_next <sys/sockio.h>
EOF
cat <<EOF > "$out/include/sys/sys_domain.h"
#pragma once
$(sed -n \
-e '/^#define AF_SYS/p' \
-e '/^#define SYSPROTO/p' \
-e '/^struct xsystmgen\s*{/,/^};/p' \
'${xnu}/bsd/sys/sys_domain.h')
#include_next <sys/sys_domain.h>
EOF
cat <<EOF > "$out/include/sys/syslimits.h"
#pragma once
$(grep '^#define LINE_MAX\s' '${xnu}/bsd/sys/syslimits.h')
#include_next <sys/syslimits.h>
EOF
cat <<EOF > "$out/include/sys/unpcb.h"
#pragma once
#include_next <sys/unpcb.h>
$(sed -n \
-e '/^#define xu_addr/p' \
-e '/^struct xunpcb64_list_entry\s*{/,/^};/p' \
-e '/^struct xunpcb64\s*{/,/^};/p' \
'${xnu}/bsd/sys/unpcb.h')
'';
};
in
mkAppleDerivation {
releaseName = "network_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-HkcIvKB4ektuk+3J/Sque8Pr5dMeNFZRlENuiu3KdsA=";
patches = [
# Some private headers depend on corecrypto, which we cant use.
# Use the headers from the ld64 port, which delegates to OpenSSL.
./patches/0007-Add-OpenSSL-based-CoreCrypto-digest-functions.patch
];
postPatch = ''
# Fix invalid pointer conversion error from trying to pass `NULL` to a `size_t`.
substituteInPlace ndp.tproj/ndp.c --replace-fail 'NULL, NULL);' 'NULL, 0);'
# Copy older files that are more compatible with the current SDK.
${lib.concatLines (
lib.mapAttrsToList (name: path: "cp '${path}' 'ifconfig.tproj/${name}.c'") old_ifconfig
)}
${lib.concatLines (
lib.mapAttrsToList (name: path: "cp '${path}' 'netstat.tproj/${name}'") old_netstat
)}
# Use private struct ifreq instead of the one defined in the system header.
substituteInPlace ifconfig.tproj/ifconfig.c \
--replace-fail $'struct\tifreq' 'struct ifreq' \
--replace-fail 'struct ifreq' 'struct ifreq_private'
substituteInPlace ifconfig.tproj/ifvlan.c \
--replace-fail 'struct ifreq' 'struct ifreq_private'
substituteInPlace ifconfig.tproj/ifconfig.h \
--replace-fail 'struct ifreq' 'struct ifreq_private'
substituteInPlace netstat.tproj/if.c \
--replace-fail 'struct ifreq' 'struct ifreq_private'
'';
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
nativeBuildInputs = [
pkg-config
];
buildInputs = [
libpcap
libresolv
openssl
];
meta.description = "Network commands for Darwin";
}

View File

@@ -0,0 +1,311 @@
From 36767c7345161baf0ab125f95c8557f8e24f25db Mon Sep 17 00:00:00 2001
From: Randy Eckenrode <randy@largeandhighquality.com>
Date: Tue, 9 Apr 2024 19:28:17 -0400
Subject: [PATCH 7/8] Add OpenSSL-based CoreCrypto digest functions
---
compat/CommonCrypto/CommonDigest.h | 6 +++
compat/CommonCrypto/CommonDigestSPI.c | 21 +++++++++++
compat/CommonCrypto/CommonDigestSPI.h | 14 +++++++
compat/corecrypto/api_defines.h | 10 +++++
compat/corecrypto/ccdigest.c | 53 +++++++++++++++++++++++++++
compat/corecrypto/ccdigest.h | 27 ++++++++++++++
compat/corecrypto/ccdigest_private.h | 19 ++++++++++
compat/corecrypto/ccsha1.c | 22 +++++++++++
compat/corecrypto/ccsha1.h | 9 +++++
compat/corecrypto/ccsha2.c | 22 +++++++++++
compat/corecrypto/ccsha2.h | 9 +++++
11 files changed, 212 insertions(+)
create mode 100644 compat/CommonCrypto/CommonDigest.h
create mode 100644 compat/CommonCrypto/CommonDigestSPI.c
create mode 100644 compat/CommonCrypto/CommonDigestSPI.h
create mode 100644 compat/corecrypto/api_defines.h
create mode 100644 compat/corecrypto/ccdigest.c
create mode 100644 compat/corecrypto/ccdigest.h
create mode 100644 compat/corecrypto/ccdigest_private.h
create mode 100644 compat/corecrypto/ccsha1.c
create mode 100644 compat/corecrypto/ccsha1.h
create mode 100644 compat/corecrypto/ccsha2.c
create mode 100644 compat/corecrypto/ccsha2.h
diff --git a/compat/CommonCrypto/CommonDigest.h b/compat/CommonCrypto/CommonDigest.h
new file mode 100644
index 0000000..a60eba7
--- /dev/null
+++ b/compat/CommonCrypto/CommonDigest.h
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
diff --git a/compat/CommonCrypto/CommonDigestSPI.c b/compat/CommonCrypto/CommonDigestSPI.c
new file mode 100644
index 0000000..41269fc
--- /dev/null
+++ b/compat/CommonCrypto/CommonDigestSPI.c
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#include "CommonDigestSPI.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <corecrypto/ccsha2.h>
+
+void CCDigest(int type, const uint8_t* bytes, size_t count, uint8_t* digest) {
+ if (type != kCCDigestSHA256) {
+ abort();
+ }
+ const struct ccdigest_info* di = ccsha256_di();
+
+ ccdigest_di_decl(_di, ctx);
+ ccdigest_init(di, ctx);
+ ccdigest_update(di, ctx, count, bytes);
+ ccdigest_final(di, ctx, digest);
+}
diff --git a/compat/CommonCrypto/CommonDigestSPI.h b/compat/CommonCrypto/CommonDigestSPI.h
new file mode 100644
index 0000000..172742a
--- /dev/null
+++ b/compat/CommonCrypto/CommonDigestSPI.h
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#include <stdint.h>
+
+#include <corecrypto/ccdigest.h>
+#include <cs_blobs.h>
+
+
+#define kCCDigestSHA256 10
+
+EXTERN_C void CCDigest(int type, const uint8_t* bytes, size_t count, uint8_t* digest);
diff --git a/compat/corecrypto/api_defines.h b/compat/corecrypto/api_defines.h
new file mode 100644
index 0000000..13d1e7a
--- /dev/null
+++ b/compat/corecrypto/api_defines.h
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#ifdef __cplusplus
+#define EXTERN_C extern "C"
+#else
+#define EXTERN_C
+#endif
diff --git a/compat/corecrypto/ccdigest.c b/compat/corecrypto/ccdigest.c
new file mode 100644
index 0000000..e29dcb8
--- /dev/null
+++ b/compat/corecrypto/ccdigest.c
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#include "ccdigest.h"
+#include "ccdigest_private.h"
+
+#include <stdlib.h>
+
+#include <openssl/err.h>
+
+
+struct ccdigest_context* _ccdigest_context_new(void)
+{
+ struct ccdigest_context* ctx = malloc(sizeof(struct ccdigest_context));
+ ctx->context = EVP_MD_CTX_new();
+ return ctx;
+}
+
+struct ccdigest_info* _ccdigest_newprovider(const char* name)
+{
+ struct ccdigest_info* di = malloc(sizeof(struct ccdigest_info));
+ di->provider = EVP_MD_fetch(NULL, name, NULL);
+ return di;
+}
+
+void ccdigest_init(const struct ccdigest_info* di, struct ccdigest_context* ctx)
+{
+ if (!EVP_DigestInit_ex2(ctx->context, di->provider, NULL)) {
+ ERR_print_errors_fp(stderr);
+ abort();
+ }
+}
+
+void ccdigest_update(
+ const struct ccdigest_info* _di,
+ struct ccdigest_context* ctx,
+ size_t count,
+ const void* bytes
+)
+{
+ if (!EVP_DigestUpdate(ctx->context, bytes, count)) {
+ ERR_print_errors_fp(stderr);
+ abort();
+ }
+}
+
+void ccdigest_final(const struct ccdigest_info* _di, struct ccdigest_context* ctx, uint8_t* digest)
+{
+ if (!EVP_DigestFinal_ex(ctx->context, digest, NULL)) {
+ ERR_print_errors_fp(stderr);
+ abort();
+ }
+}
diff --git a/compat/corecrypto/ccdigest.h b/compat/corecrypto/ccdigest.h
new file mode 100644
index 0000000..9af2394
--- /dev/null
+++ b/compat/corecrypto/ccdigest.h
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "api_defines.h"
+
+
+struct ccdigest_info;
+struct ccdigest_context;
+
+EXTERN_C struct ccdigest_context* _ccdigest_context_new(void);
+
+#define ccdigest_di_decl(_di, ctxvar) \
+ struct ccdigest_context* (ctxvar) = _ccdigest_context_new()
+
+EXTERN_C void ccdigest_init(const struct ccdigest_info* di, struct ccdigest_context* ctx);
+EXTERN_C void ccdigest_update(
+ const struct ccdigest_info* _di,
+ struct ccdigest_context* ctx,
+ size_t count,
+ const void* bytes
+);
+EXTERN_C void ccdigest_final(const struct ccdigest_info* _di, struct ccdigest_context* ctx, uint8_t* digest);
diff --git a/compat/corecrypto/ccdigest_private.h b/compat/corecrypto/ccdigest_private.h
new file mode 100644
index 0000000..0ea9759
--- /dev/null
+++ b/compat/corecrypto/ccdigest_private.h
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#include "api_defines.h"
+
+#include <openssl/evp.h>
+
+
+struct ccdigest_info {
+ EVP_MD* provider;
+};
+
+struct ccdigest_context {
+ EVP_MD_CTX* context;
+};
+
+EXTERN_C struct ccdigest_info* _ccdigest_newprovider(const char* name);
diff --git a/compat/corecrypto/ccsha1.c b/compat/corecrypto/ccsha1.c
new file mode 100644
index 0000000..e02b2b6
--- /dev/null
+++ b/compat/corecrypto/ccsha1.c
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#include "ccsha1.h"
+
+#include <assert.h>
+
+#include <cs_blobs.h>
+
+#include "ccdigest_private.h"
+
+
+static struct ccdigest_info* di = NULL;
+
+const struct ccdigest_info* ccsha1_di(void)
+{
+ if (!di) {
+ di = _ccdigest_newprovider("SHA-1");
+ assert(EVP_MD_get_size(di->provider) == CS_SHA1_LEN);
+ }
+ return di;
+}
diff --git a/compat/corecrypto/ccsha1.h b/compat/corecrypto/ccsha1.h
new file mode 100644
index 0000000..8e3f85f
--- /dev/null
+++ b/compat/corecrypto/ccsha1.h
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#include <corecrypto/ccdigest.h>
+
+
+EXTERN_C const struct ccdigest_info* ccsha1_di(void);
diff --git a/compat/corecrypto/ccsha2.c b/compat/corecrypto/ccsha2.c
new file mode 100644
index 0000000..6504503
--- /dev/null
+++ b/compat/corecrypto/ccsha2.c
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#include "ccsha2.h"
+
+#include <assert.h>
+
+#include <cs_blobs.h>
+
+#include "ccdigest_private.h"
+
+
+static struct ccdigest_info* di = NULL;
+
+const struct ccdigest_info* ccsha256_di(void)
+{
+ if (!di) {
+ di = _ccdigest_newprovider("SHA-256");
+ assert(EVP_MD_get_size(di->provider) == CS_SHA256_LEN);
+ }
+ return di;
+}
diff --git a/compat/corecrypto/ccsha2.h b/compat/corecrypto/ccsha2.h
new file mode 100644
index 0000000..9f30e03
--- /dev/null
+++ b/compat/corecrypto/ccsha2.h
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: APSL-2.0
+// CoreCrypto compatibility shims written by Randy Eckenrode © 2024
+
+#pragma once
+
+#include <corecrypto/ccdigest.h>
+
+#define CCSHA256_OUTPUT_SIZE 32
+
+EXTERN_C const struct ccdigest_info* ccsha256_di(void);
--
2.44.1

View File

@@ -0,0 +1,103 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/patch_cmds/blob/main/patch_cmds.xcodeproj/project.pbxproj
# Project settings
project('patch_cmds', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
libutil = cc.find_library('util')
# Binaries
executable(
'cmp',
include_directories : 'cmp',
dependencies : [ libutil ],
install : true,
sources : [
'cmp/cmp.c',
'cmp/link.c',
'cmp/misc.c',
'cmp/regular.c',
'cmp/special.c',
],
)
install_man('cmp/cmp.1')
executable(
'diff',
include_directories : 'diff',
install : true,
sources : [
'diff/diff.c',
'diff/diff_atomize_text.c',
'diff/diff_main.c',
'diff/diff_myers.c',
'diff/diff_output.c',
'diff/diff_output_edscript.c',
'diff/diff_output_plain.c',
'diff/diff_output_unidiff.c',
'diff/diff_patience.c',
'diff/diffdir.c',
'diff/diffreg.c',
'diff/diffreg_new.c',
'diff/pr.c',
'diff/recallocarray.c',
'diff/xmalloc.c',
],
)
install_man('diff/diff.1')
executable(
'diff3',
include_directories : 'diff3',
install : true,
sources : [
'diff3/diff3.c',
'diff3/xmalloc.c',
],
)
install_man('diff3/diff3.1')
executable(
'diffstat',
include_directories : 'diffstat',
c_args : [
'-DHAVE_CONFIG_H',
'-D_XOPEN_SOURCE=500',
'-D_DARWIN_C_SOURCE',
],
install : true,
sources : [ 'diffstat/diffstat.c' ],
)
install_man('diffstat/diffstat.1')
executable(
'patch',
include_directories : 'patch',
install : true,
sources : [
'patch/backupfile.c',
'patch/inp.c',
'patch/mkpath.c',
'patch/patch.c',
'patch/pch.c',
'patch/util.c',
'patch/vcs.c',
],
)
install_man('patch/patch.1')
executable(
'sdiff',
include_directories : 'sdiff',
install : true,
sources : [
'sdiff/edit.c',
'sdiff/sdiff.c',
],
)
install_man('sdiff/sdiff.1')

View File

@@ -0,0 +1,32 @@
{
lib,
apple-sdk,
libutil,
mkAppleDerivation,
pkg-config,
}:
mkAppleDerivation {
releaseName = "patch_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-FLCJY40l74ExO0WTaA8hb9guhOBXeui2GqWL/7QeJJk=";
nativeBuildInputs = [ pkg-config ];
buildInputs = [ libutil ];
meta = {
description = "BSD patch commands for Darwin";
license = [
lib.licenses.apple-psl10
lib.licenses.bsd2 # -freebsd
lib.licenses.bsd3
lib.licenses.bsdOriginal
];
};
}

View File

@@ -0,0 +1,180 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/remote_cmds/blob/main/remote_cmds.xcodeproj/project.pbxproj
# Project settings
project('text_cmds', 'c', version : '@version@')
add_global_arguments(
# Many programs use old prototypes
'-Wno-deprecated-non-prototype',
language : 'c',
)
# Dependencies
cc = meson.get_compiler('c')
libedit = dependency('libedit')
ncurses = dependency('ncurses')
# Binaries
executable(
'logger',
install : true,
sources : [ 'logger/logger.c' ],
)
install_man('logger/logger.1')
executable(
'talk',
dependencies : [ ncurses ],
install : true,
sources : [
'talk/ctl.c',
'talk/ctl_transact.c',
'talk/display.c',
'talk/get_addrs.c',
'talk/get_iface.c',
'talk/get_names.c',
'talk/init_disp.c',
'talk/invite.c',
'talk/io.c',
'talk/look_up.c',
'talk/msgs.c',
'talk/talk.c',
],
)
install_man('talk/talk.1')
executable(
'talkd',
c_args : [
'-D__FBSDID=__RCSID',
'-DCOLLATE_DEBUG',
'-DYY_NO_UNPUT',
],
install : true,
sources : [
'talkd/announce.c',
'talkd/print.c',
'talkd/process.c',
'talkd/table.c',
'talkd/talkd.c',
'wall/ttymsg.c',
],
)
install_man('talkd/talkd.8')
install_symlink(
'ntalkd',
install_dir : get_option('bindir'),
pointing_to : 'talkd',
)
install_symlink(
'ntalkd.8',
install_dir : get_option('mandir') + '/man8',
pointing_to : 'talkd.8',
)
# Telnet is insecure and obsolete. Apple also no longer ships it.
# executable(
# 'telnet',
# dependencies : [ ncurses ],
# c_args : [
# '-D__FBSDID=__RCSID',
# '-DAUTHENTICATION',
# '-DENV_HACK',
# '-DINET6',
# '-DIPSEC',
# '-DKLUDGELINEMODE',
# '-DKRB5',
# '-DSKEY',
# '-DTERMCAP',
# '-DUSE_TERMIO',
# ],
# install : true,
# sources : [
# 'telnet/authenc.c',
# 'telnet/commands.c',
# 'telnet/main.c',
# 'telnet/network.c',
# 'telnet/ring.c',
# 'telnet/sys_bsd.c',
# 'telnet/telnet.c',
# 'telnet/terminal.c',
# 'telnet/tn3270.c',
# 'telnet/utilities.c',
# ],
# )
# install_man('telnet/telnet.1')
# executable(
# 'telnetd',
# c_args : [
# '-D__FBSDID=__RCSID',
# '-DDIAGNOSTICS',
# '-DENV_HACK',
# '-DINET6',
# '-DKLUDGELINEMODE',
# '-DLINEMODE',
# '-DNO_UTMP',
# '-DOLD_ENVIRON',
# '-DUSE_TERMIO',
# ],
# install : true,
# sources : [
# 'telnetd/authenc.c',
# 'telnetd/global.c',
# 'telnetd/slc.c',
# 'telnetd/state.c',
# # 'telnetd/strlcpy.c', # Not used
# 'telnetd/sys_term.c',
# 'telnetd/telnetd.c',
# 'telnetd/termstat.c',
# 'telnetd/utility.c',
# ],
# )
# install_man('telnetd/telnetd.8')
executable(
'tftp',
dependencies : [ libedit ],
include_directories : [ 'tftp', 'tftpd' ],
install : true,
sources : [
'tftp/main.c',
'tftp/tftp.c',
'tftpd/tftp-file.c',
'tftpd/tftp-io.c',
'tftpd/tftp-options.c',
'tftpd/tftp-transfer.c',
'tftpd/tftp-utils.c',
],
)
install_man('tftp/tftp.1')
executable(
'tftpd',
include_directories : [ 'tftp', 'tftpd' ],
install : true,
sources : [
'tftpd/tftp-file.c',
'tftpd/tftp-io.c',
'tftpd/tftp-options.c',
'tftpd/tftp-transfer.c',
'tftpd/tftp-utils.c',
'tftpd/tftpd.c',
],
)
install_man('tftpd/tftpd.8')
executable(
'wall',
c_args : [ '-D__FBSDID=__RCSID' ],
install : true,
sources : [
'wall/ttymsg.c',
'wall/wall.c',
],
)
install_man('wall/wall.1')

View File

@@ -0,0 +1,38 @@
{
lib,
libedit,
mkAppleDerivation,
ncurses,
pkg-config,
}:
mkAppleDerivation {
releaseName = "remote_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-+hC3yJwwwXr01Aa47K5dv4gL0+IlTQZU9YYgygXkTSI=";
postPatch = ''
# Avoid a conflict with the definition in SDKs headers.
sed -e '/MAXPKTSIZE/d' -i tftpd/tftp-utils.h
# Avoid a conflict with libedit when building statically
for file in tftpd/tftp-file.c tftpd/tftp-file.h tftp/tftp.c tftpd/tftpd.c; do
substituteInPlace $file \
--replace-fail read_init read_init_tftpd
done
'';
nativeBuildInputs = [ pkg-config ];
buildInputs = [
libedit
ncurses
];
meta.description = "Remote commands for Darwin";
}

View File

@@ -0,0 +1,34 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/removefile/blob/main/removefile.xcodeproj/project.pbxproj
# Project settings
project('removefile', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
# Libraries
library(
'removefile',
c_args : [
'-D__DARWIN_NOW_CANCELABLE=1',
],
install : true,
sources : [
'removefile.c',
'removefile_random.c',
'removefile_rename_unlink.c',
'removefile_sunlink.c',
'removefile_tree_walker.c',
],
)
install_headers(
'checkint.h',
'removefile.h',
)
install_man(
'checkint.3',
'removefile.3',
)

View File

@@ -0,0 +1,52 @@
{
apple-sdk,
mkAppleDerivation,
stdenvNoCC,
}:
let
xnu = apple-sdk.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "removefile-deps-private-headers";
buildCommand = ''
mkdir -p "$out/include/apfs"
# APFS group is 'J' per https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/vfs/vfs_fsevents.c#L1054
cat <<EOF > "$out/include/apfs/apfs_fsctl.h"
#pragma once
#include <stdint.h>
#include <sys/ioccom.h>
struct xdstream_obj_id {
char* xdi_name;
uint64_t xdi_xdtream_obj_id;
};
#define APFS_CLEAR_PURGEABLE 0
#define APFSIOC_MARK_PURGEABLE _IOWR('J', 68, uint64_t)
#define APFSIOC_XDSTREAM_OBJ_ID _IOR('J', 35, struct xdstream_obj_id)
EOF
'';
};
in
mkAppleDerivation {
releaseName = "removefile";
outputs = [
"out"
"dev"
"man"
];
xcodeHash = "sha256-pE92mVI0KTHOVKBA4T5R1rHy5//uipOimas7DaTVe0U=";
postPatch = ''
# Disable experimental bounds safety stuff thats not available in LLVM 16.
substituteInPlace removefile.h \
--replace-fail '__ptrcheck_abi_assume_single()' "" \
--replace-fail '__unsafe_indexable' ""
'';
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
meta.description = "Darwin file removing library";
}

View File

@@ -0,0 +1,423 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/shell_cmds/blob/main/shell_cmds.xcodeproj/project.pbxproj
# Project settings
project('shell_cmds', 'c', 'cpp', version : '@version@')
add_global_arguments('-D__FBSDID=__RCSID', language : 'c')
fs = import('fs')
# Dependencies
build_cc = meson.get_compiler('c', native : true)
host_cc = meson.get_compiler('c')
host_cxx = meson.get_compiler('cpp')
# pam = cc.find_library('pam')
libedit = dependency('libedit')
libresolv = host_cc.find_library('resolv')
libsbuf = host_cc.find_library('sbuf')
libutil = host_cc.find_library('util')
libxo = dependency('libxo')
# Generators
bison = generator(
find_program('bison', required : true),
arguments : ['@INPUT@', '--header=@OUTPUT0@', '--output=@OUTPUT1@'],
output : [ '@BASENAME@.tab.h', '@BASENAME@.tab.c'],
)
# Binaries
## These commands all are single files with a man page.
single_file_cmds = [
'basename',
'chroot',
'dirname',
'echo',
'false',
'getopt',
'hostname',
'jot',
'kill',
'killall',
'lastcomm',
'logname',
'mktemp',
'nice',
'nohup', # needs vproc_priv.h
'path_helper',
'printenv',
'printf',
'pwd',
'realpath',
'renice',
'script',
'seq',
'shlock',
'sleep',
'systime',
'tee',
'time',
'true',
'uname',
'what',
'whereis',
'which',
'yes',
]
foreach cmd : single_file_cmds
executable(
cmd,
install : true,
sources : [ f'@cmd@/@cmd@.c' ],
)
foreach section : [ 1, 2, 3, 4, 5, 6, 7, 8 ]
if fs.exists(f'@cmd@/@cmd@.@section@')
install_man(f'@cmd@/@cmd@.@section@')
endif
endforeach
endforeach
install_data(
'alias/generic.sh',
install_dir : get_option('bindir'),
install_mode : 'r-xr-xr-x',
rename : 'alias',
)
install_man(
'alias/alias.1',
'alias/builtin.1',
)
foreach alias : run_command('cat', 'xcodescripts/builtins.txt', check : true).stdout().strip().split('\n')
install_symlink(
alias,
install_dir : get_option('bindir'),
pointing_to : 'alias',
)
endforeach
executable(
'apply',
dependencies : libsbuf,
install : true,
sources : [ 'apply/apply.c' ],
)
install_man('apply/apply.1')
executable(
'date',
include_directories : 'date',
install : true,
sources : [
'date/date.c',
'date/vary.c',
],
)
install_man('date/date.1')
executable(
'env',
include_directories : 'env',
install : true,
sources : [
'env/env.c',
'env/envopts.c',
],
)
install_man('env/env.1')
executable(
'expr',
install : true,
sources : [
bison.process('expr/expr.y')
],
)
install_man('expr/expr.1')
executable(
'find',
c_args : [ '-D_DARWIN_USE_64_BIT_INODE' ],
include_directories : 'find',
install : true,
sources : [
'find/find.c',
'find/function.c',
'find/ls.c',
'find/main.c',
'find/misc.c',
'find/operator.c',
'find/option.c',
bison.process('find/getdate.y'),
],
)
install_man('find/find.1')
executable(
'hexdump',
include_directories : 'hexdump',
install : true,
sources : [
'hexdump/conv.c',
'hexdump/display.c',
'hexdump/hexdump.c',
'hexdump/hexsyntax.c',
'hexdump/odsyntax.c',
'hexdump/parse.c',
],
)
install_man(
'hexdump/hexdump.1',
'hexdump/od.1',
)
install_symlink(
'od',
install_dir : get_option('bindir'),
pointing_to : 'hexdump',
)
executable(
'id',
c_args : [ '-DUSE_BSM_AUDIT' ],
include_directories : 'id',
install : true,
sources : [
'id/id.c',
# 'id/open_directory.c', # Not actually used and doesnt compile anyway.
],
)
install_man(
'id/groups.1',
'id/id.1',
'id/whoami.1',
)
foreach cmd : [ 'groups', 'whoami' ]
install_symlink(
cmd,
install_dir : get_option('bindir'),
pointing_to : 'id',
)
endforeach
executable(
'locate',
include_directories : 'locate/locate',
install : true,
sources : [
'locate/locate/locate.c',
'locate/locate/util.c',
],
)
executable(
'locate.bigram',
include_directories : 'locate/locate',
install : true,
sources : [ 'locate/bigram/locate.bigram.c', ],
)
executable(
'locate.code',
include_directories : 'locate/locate',
install : true,
sources : [ 'locate/code/locate.code.c', ],
)
install_data(
'locate/locate/locate.rc',
install_dir : get_option('sysconfdir'),
)
install_data(
'locate/locate/concatdb.sh',
'locate/locate/updatedb.sh',
'locate/locate/mklocatedb.sh',
install_dir : get_option('libexecdir'),
install_mode : 'r-xr-xr-x',
rename : [
'locate.concatdb',
'locate.updatedb',
'locate.mklocatedb',
],
)
install_man(
'locate/locate/locate.1',
'locate/locate/locate.updatedb.8',
'locate/bigram/locate.bigram.8',
'locate/code/locate.code.8',
)
foreach manpage : [ 'concatdb', 'mklocatedb' ]
install_symlink(
f'locate.@manpage@.8',
install_dir : get_option('mandir') + '/man8',
pointing_to : 'locate.updatedb.8',
)
endforeach
executable(
'lockf',
install : true,
sources : [ 'lockf/lockf.c' ],
)
install_man('lockf/lockf.1')
# Building `sh` requires several custom targets to generate files it needs.
bash_bin = find_program('bash')
mknodes = executable('mknodes', sources : 'sh/mknodes.c', native : true)
mksyntax = executable('mksyntax', sources : 'sh/mksyntax.c', native : true)
builtins = custom_target(
command : [ bash_bin, '@SOURCE_ROOT@/sh/mkbuiltins', '@SOURCE_ROOT@/sh'],
output : [ 'builtins.c', 'builtins.h' ],
)
nodes = custom_target(
command : [ mknodes, '@SOURCE_ROOT@/sh/nodetypes', '@SOURCE_ROOT@/sh/nodes.c.pat' ],
output : [ 'nodes.c', 'nodes.h' ],
)
syntax = custom_target(
command : [ mksyntax ],
output : [ 'syntax.c', 'syntax.h' ],
)
tokens = custom_target(
command : [ bash_bin, '@SOURCE_ROOT@/sh/mktokens' ],
output : 'token.h',
)
executable(
'sh',
c_args : [ '-DSHELL' ],
dependencies : [ libedit ],
include_directories : [ 'sh', 'sh/bltin' ],
install : true,
sources : [
'kill/kill.c',
'printf/printf.c',
'sh/alias.c',
'sh/arith_yacc.c',
'sh/arith_yylex.c',
'sh/bltin/echo.c',
'sh/cd.c',
'sh/error.c',
'sh/eval.c',
'sh/exec.c',
'sh/expand.c',
'sh/histedit.c',
'sh/input.c',
'sh/jobs.c',
'sh/mail.c',
'sh/main.c',
'sh/memalloc.c',
'sh/miscbltin.c',
'sh/mystring.c',
'sh/options.c',
'sh/output.c',
'sh/parser.c',
'sh/redir.c',
'sh/show.c',
'sh/trap.c',
'sh/var.c',
'test/test.c',
builtins,
nodes,
syntax,
tokens,
],
)
install_man('sh/sh.1')
# Requires entitlements
# executable(
# 'su',
# dependencies : pam,
# sources : [ 'su/su.c' ],
# )
# install_data(
# 'su/su.pam',
# install_dir : get_option('sysconfdir') + 'pam.d',
# rename : 'su'
# )
# install_man('su/su.1')
executable(
'stdbuf',
install : true,
sources : [ 'stdbuf/stdbuf.c' ],
)
install_man('stdbuf/stdbuf.1')
executable(
'[',
install : true,
sources : [ 'test/test.c' ],
)
install_man(
'test/[.1',
'test/test.1',
)
install_symlink(
'test',
install_dir : get_option('bindir'),
pointing_to : '[',
)
executable(
'users',
install : true,
sources : [ 'users/users.cc' ],
)
install_man('users/users.1')
executable(
'w',
c_args : [
'-DHAVE_KVM=0',
'-DHAVE_UTMPX=1',
],
dependencies : [ libresolv, libsbuf, libutil, libxo ],
include_directories : 'w',
install : true,
sources : [
'w/fmt.c',
'w/pr_time.c',
'w/proc_compare.c',
'w/w.c',
],
)
install_man(
'w/uptime.1',
'w/w.1',
)
install_symlink(
'uptime',
install_dir : get_option('bindir'),
pointing_to : 'w',
)
executable(
'who',
c_args : [
'-D_UTMPX_COMPAT',
'-DSUPPORT_UTMPX',
],
install : true,
sources : [ 'who/who.c' ],
)
install_man('who/who.1')
executable(
'xargs',
include_directories : 'xargs',
install : true,
sources : [
'xargs/strnsubst.c',
'xargs/xargs.c',
],
)
install_man('xargs/xargs.1')

View File

@@ -0,0 +1,71 @@
{
lib,
apple-sdk,
bison,
clang,
libedit,
libresolv,
libsbuf,
libutil,
libxo,
pkg-config,
mkAppleDerivation,
}:
let
# nohup requires vproc_priv.h from launchd
launchd = apple-sdk.sourceRelease "launchd";
in
mkAppleDerivation {
releaseName = "shell_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-26N7AZV/G+ryc2Nu1v91rEdb1a6jDpnj6t5rzEG2YA4=";
postPatch = ''
# Fix `mktemp` templates
substituteInPlace sh/mkbuiltins \
--replace-fail '-t ka' '-t ka.XXXXXX'
substituteInPlace sh/mktokens \
--replace-fail '-t ka' '-t ka.XXXXXX'
# Update `/etc/locate.rc` paths to point to the store.
for path in locate/locate/locate.updatedb.8 locate/locate/locate.rc locate/locate/updatedb.sh; do
substituteInPlace $path --replace-fail '/etc/locate.rc' "$out/etc/locate.rc"
done
'';
env.NIX_CFLAGS_COMPILE = "-I${launchd}/liblaunch";
depsBuildBuild = [ clang ];
nativeBuildInputs = [
bison
pkg-config
];
buildInputs = [
libedit
libresolv
libsbuf
libutil
libxo
];
postInstall = ''
# Patch the shebangs to use `sh` from shell_cmds.
HOST_PATH="$out/bin" patchShebangs --host "$out/bin" "$out/libexec"
'';
meta = {
description = "Darwin shell commands and the Almquist shell";
license = [
lib.licenses.bsd2
lib.licenses.bsd3
];
};
}

View File

@@ -0,0 +1,602 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/system_cmds/blob/main/system_cmds.xcodeproj/project.pbxproj
# Project settings
project('system_cmds', 'c', 'objc', version : '@version@')
add_project_arguments(
'-D__FreeBSD__',
# Suppresses suffixing symbols with '$UNIX2003', which causes link failures.
'-D__DARWIN_ONLY_UNIX_CONFORMANCE=1',
# Make sure Darwin is correctly detected as macOS
'-DPLATFORM_MacOSX=1',
# Access private definitions
'-DPRIVATE=1',
# From bsd/sys/private_event.h in xnu
'-Dkqueue_id_t=uint64_t',
language : 'c',
)
sdk_version = get_option('sdk_version')
# Dependencies
cc = meson.get_compiler('c')
# Upstream uses awk to process `.gperf` files instead of gperf, which cant process them.
fake_gperf = find_program('awk', required : true)
## Frameworks
core_foundation = dependency('appleframeworks', modules : 'CoreFoundation')
core_symbolication = dependency('appleframeworks', modules : 'CoreSymbolication')
directory_service = dependency('appleframeworks', modules : 'DirectoryService')
iokit = dependency('appleframeworks', modules : 'IOKit')
open_directory = dependency('appleframeworks', modules : 'OpenDirectory')
cfopen_directory = dependency('appleframeworks', modules : 'CFOpenDirectory')
## Libraries
dbm = cc.find_library('dbm')
ncurses = dependency('ncurses')
openbsm = cc.find_library('bsm')
pam = cc.find_library('pam')
# Feature Tests
if sdk_version.version_compare('<12')
add_project_arguments(
'-DIOMainPort=IOMasterPort',
'-DkIOMainPortDefault=kIOMasterPortDefault',
language : 'c'
)
endif
# Generators
pgperf = generator(
fake_gperf,
arguments : [ '-f', meson.source_root() + '/getconf/fake-gperf.awk', '@INPUT@' ],
capture : true,
output : '@BASENAME@.gperf.c',
)
# Binaries
executable(
'ac',
install : true,
sources : 'ac/ac.c',
)
install_man('ac/ac.8')
executable(
'accton',
install : true,
sources : 'accton/accton.c',
)
install_man('accton/accton.8')
executable(
'arch',
dependencies : [ core_foundation ],
install : true,
sources : 'arch/arch.c',
)
install_man(
'arch/arch.1',
'arch/machine.1',
)
executable(
'at',
c_args : [
'-DDAEMON_UID=1',
'-DDAEMON_GID=1',
'-DDEFAULT_AT_QUEUE=\'a\'',
'-DDEFAULT_BATCH_QUEUE=\'b\'',
'-DPERM_PATH="/usr/lib/cron"',
],
install : true,
sources : [
'at/at.c',
'at/panic.c',
'at/parsetime.c',
'at/perm.c',
],
)
install_man('at/at.1')
executable(
'atrun',
c_args : [
'-DDAEMON_UID=1',
'-DDAEMON_GID=1',
],
include_directories : 'at',
install : true,
sources : [
'atrun/atrun.c',
'atrun/gloadavg.c',
]
)
install_man('atrun/atrun.8')
executable(
'chkpasswd',
c_args : [ '-DUSE_PAM' ],
dependencies : [ core_foundation, open_directory, pam ],
install : true,
sources : [
'chkpasswd/file_passwd.c',
'chkpasswd/nis_passwd.c',
'chkpasswd/od_passwd.c',
'chkpasswd/pam_passwd.c',
'chkpasswd/passwd.c',
'chkpasswd/stringops.c'
],
)
install_man('chkpasswd/chkpasswd.8')
executable(
'chpass',
dependencies : [ core_foundation, cfopen_directory, open_directory ],
install : true,
sources : [
'chpass/chpass.c',
'chpass/edit.c',
'chpass/field.c',
'chpass/open_directory.c',
'chpass/table.c',
'chpass/util.c',
]
)
install_man('chpass/chpass.1')
executable(
'cpuctl',
install : true,
sources : 'cpuctl/cpuctl.c'
)
install_man('cpuctl/cpuctl.8')
executable(
'dmesg',
install : true,
sources : 'dmesg/dmesg.c',
)
install_man('dmesg/dmesg.8')
executable(
'dynamic_pager',
c_args : '-DNO_DIRECT_RPC',
install : true,
sources : 'dynamic_pager/dynamic_pager.c',
)
install_man('dynamic_pager/dynamic_pager.8')
executable(
'fs_usage',
# Requires 'ktrace/session.h'
build_by_default : false,
c_args : [
'-DTARGET_OS_EXCLAVECORE=0',
'-DTARGET_OS_EXCLAVEKIT=0',
],
# dependencies : [ libutil ],
install : false,
sources : 'fs_usage/fs_usage.c',
)
install_man('fs_usage/fs_usage.1')
executable(
'gcore',
# Requires XPC private APIs
build_by_default : false,
install : false,
sources : [
'gcore/convert.c',
'gcore/corefile.c',
'gcore/dyld.c',
'gcore/dyld_shared_cache.c',
'gcore/gcore_framework.m',
'gcore/main.c',
'gcore/notes.c',
'gcore/sparse.c',
'gcore/threads.c',
'gcore/utils.c',
'gcore/vanilla.c',
'gcore/vm.c',
]
)
# install_man('gcore/gcore-internal.1', 'gcore/gcore.1')
executable(
'getconf',
c_args : '-DAPPLE_GETCONF_UNDERSCORE',
include_directories : 'getconf',
install : true,
sources : [
'getconf/getconf.c',
pgperf.process(
[
'getconf/confstr.gperf',
'getconf/limits.gperf',
'getconf/unsigned_limits.gperf',
'getconf/progenv.gperf',
'getconf/sysconf.gperf',
'getconf/pathconf.gperf',
]
),
]
)
install_man('getconf/getconf.1')
executable(
'getty',
install : true,
sources : [
'getty/chat.c',
'getty/init.c',
'getty/main.c',
'getty/subr.c',
]
)
install_man(
'getty/getty.8',
'getty/gettytab.5',
'getty/ttys.5',
)
executable(
'hostinfo',
install : true,
sources : 'hostinfo/hostinfo.c',
)
install_man('hostinfo/hostinfo.8')
executable(
'iosim',
dependencies : [ core_foundation, iokit ],
include_directories : 'at',
install : true,
sources : 'iosim/iosim.c',
)
install_man('iosim/iosim.1')
executable(
'iostat',
dependencies : [ core_foundation, iokit ],
install : true,
sources : 'iostat/iostat.c',
)
install_man('iostat/iostat.8')
executable(
'kpgo',
install : true,
sources : 'kpgo/kpgo.c',
)
# No man pages for `kpgo`
executable(
'latency',
build_by_default : sdk_version.version_compare('>=12'),
dependencies : [ ncurses ],
install : sdk_version.version_compare('>=12'),
sources : 'latency/latency.c',
)
if sdk_version.version_compare('>=12')
install_man('latency/latency.1')
endif
executable(
'login',
# Requires SoftLinking/WeakLinking.h and end-point security entitlements
build_by_default : false,
c_args : '-DUSE_BSM_AUDIT=1',
dependencies : [ openbsm ],
install : false,
sources : [
'login/login.c',
'login/login_audit.c',
]
)
# install_man('login/login.1')
executable(
'lskq',
build_by_default : sdk_version.version_compare('>=12'),
install : sdk_version.version_compare('>=12'),
sources : 'lskq/lskq.c',
)
if sdk_version.version_compare('>=12')
install_man('lskq/lskq.1')
endif
executable(
'lsmp',
build_by_default : sdk_version.version_compare('>=12'),
install : sdk_version.version_compare('>=12'),
sources : [
'lsmp/lsmp.c',
'lsmp/port_details.c',
'lsmp/task_details.c'
]
)
if sdk_version.version_compare('>=12')
install_man('lsmp/lsmp.1')
endif
executable(
'ltop',
install : true,
sources : 'ltop/ltop.c',
)
install_man('ltop/ltop.1')
executable(
'mean',
install : true,
sources : 'mean/mean.c',
)
# No man pages for `mean`.
executable(
'memory_pressure',
c_args : ['-include', 'stdint.h'],
install : true,
sources : 'memory_pressure/memory_pressure.c',
)
install_man('memory_pressure/memory_pressure.1')
executable(
'mkfile',
install : true,
sources : 'mkfile/mkfile.c',
)
install_man('mkfile/mkfile.8')
executable(
'mslutil',
install : true,
sources : 'mslutil/mslutil.c',
)
install_man('mslutil/mslutil.1')
executable(
'newgrp',
install : true,
sources : 'newgrp/newgrp.c',
)
install_man('newgrp/newgrp.1')
executable(
'nologin',
install : true,
sources : 'nologin/nologin.c',
)
install_man(
'nologin/nologin.5',
'nologin/nologin.8',
)
executable(
'nvram',
c_args : [
'-DTARGET_OS_BRIDGE=0',
'-DkIONVRAMDeletePropertyKeyWRet="IONVRAM-DELETEWRET-PROPERTY"',
],
dependencies : [ core_foundation, iokit ],
install : true,
sources : 'nvram/nvram.c',
)
install_man('nvram/nvram.8')
custom_target(
'pagesize',
command : [ 'cp', '@INPUT@', '@OUTPUT@' ],
install : true,
install_dir : get_option('bindir'),
install_mode : 'r-xr-xr-x',
input : 'pagesize/pagesize.sh',
output : 'pagesize',
)
install_man('pagesize/pagesize.1')
executable(
'passwd',
dependencies : [ core_foundation, cfopen_directory, open_directory, pam ],
install : true,
sources : [
'passwd/file_passwd.c',
'passwd/nis_passwd.c',
'passwd/od_passwd.c',
'passwd/pam_passwd.c',
'passwd/passwd.c',
]
)
install_man('passwd/passwd.1')
executable(
'proc_uuid_policy',
install : true,
sources : 'proc_uuid_policy/proc_uuid_policy.c',
)
install_man('proc_uuid_policy/proc_uuid_policy.1')
executable(
'purge',
install : true,
sources : 'purge/purge.c',
)
install_man('purge/purge.8')
executable(
'pwd_mkdb',
c_args : [
'-D_PW_NAME_LEN=MAXLOGNAME',
'-D_PW_YPTOKEN="__YP!"',
],
dependencies : [ dbm ],
install : true,
sources : [
'pwd_mkdb/pw_scan.c',
'pwd_mkdb/pwd_mkdb.c',
]
)
install_man('pwd_mkdb/pwd_mkdb.8')
executable(
'reboot',
# Requires IOKitUser kext APIs
build_by_default : false,
install : false,
sources : 'reboot/reboot.c',
)
# install_man('reboot/reboot.8')
executable(
'sa',
c_args : '-DAHZV1',
dependencies : [ dbm ],
install : true,
sources : [
'sa/db.c',
'sa/main.c',
'sa/pdb.c',
'sa/usrdb.c',
]
)
install_man('sa/sa.8')
executable(
'sc_usage',
build_by_default : sdk_version.version_compare('>=12'),
dependencies : ncurses,
install : sdk_version.version_compare('>=12'),
sources : 'sc_usage/sc_usage.c',
)
if sdk_version.version_compare('>=12')
install_man('sc_usage/sc_usage.1')
endif
executable('shutdown',
# Requires IOKitUser kext APIs
build_by_default : false,
install : false,
sources : 'shutdown/shutdown.c',
)
# install_man('shutdown/shutdown.8')
executable(
'stackshot',
# Requires private entitlements
build_by_default : false,
install : false,
sources : 'stackshot/stackshot.c',
)
# No man pages for `stackshot`.
executable(
'sync',
install : true,
sources : 'sync/sync.c',
)
# No man pages for `sync`.
executable(
'sysctl',
install : true,
sources : 'sysctl/sysctl.c',
)
install_man(
'sysctl/sysctl.8',
'sysctl/sysctl.conf.5',
)
executable(
'taskpolicy',
install : true,
sources : 'taskpolicy/taskpolicy.c',
)
install_man('taskpolicy/taskpolicy.8')
executable(
'vifs',
install : true,
sources : 'vifs/vifs.c',
)
install_man('vifs/vifs.8')
executable(
'vipw',
install : true,
sources : [
'vipw/pw_util.c',
'vipw/vipw.c',
],
)
install_man('vipw/vipw.8')
executable('vm_purgeable_stat',
install : true,
sources : 'vm_purgeable_stat/vm_purgeable_stat.c',
)
install_man('vm_purgeable_stat/vm_purgeable_stat.1')
executable(
'vm_stat',
install : true,
sources : 'vm_stat/vm_stat.c',
)
install_man('vm_stat/vm_stat.1')
executable(
'wait4path',
install : true,
sources : 'wait4path/wait4path.c',
)
install_man('wait4path/wait4path.1')
executable(
'wordexp-helper',
install : true,
sources : 'wordexp-helper/wordexp-helper.c',
)
# No man pages for `wordexp-helper`.
executable(
'zdump',
c_args : [ '-DHAVE_LOCALTIME_RZ=0' ],
include_directories : 'zic',
install : true,
sources : 'zdump/zdump.c',
)
install_man('zdump/zdump.8')
executable(
'zic',
install : true,
sources : 'zic/zic.c',
)
install_man('zic/zic.8')
executable(
'zlog',
c_args : '-DKERN_NOT_FOUND=56',
dependencies : [ core_foundation, core_symbolication ],
install : true,
sources : [
'zlog/SymbolicationHelper.c',
'zlog/zlog.c',
],
)
install_man('zlog/zlog.1')
executable(
'zprint',
# Requires IOKitUser kext APIs
build_by_default : false,
install : false,
sources : 'zprint/zprint.c',
)
# install_man('zprint/zprint.1')

View File

@@ -0,0 +1 @@
option('sdk_version', type : 'string')

View File

@@ -0,0 +1,116 @@
{
lib,
apple-sdk,
apple-sdk_12,
mkAppleDerivation,
ncurses,
openpam,
pkg-config,
stdenv,
stdenvNoCC,
}:
let
libdispatch = apple-sdk.sourceRelease "libdispatch"; # Has to match the version of the SDK
Libc = apple-sdk_12.sourceRelease "Libc";
libmalloc = apple-sdk_12.sourceRelease "libmalloc";
OpenDirectory = apple-sdk_12.sourceRelease "OpenDirectory";
libplatform = apple-sdk_12.sourceRelease "libplatform";
xnu = apple-sdk_12.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "system_cmds-deps-private-headers";
buildCommand = ''
install -D -t "$out/include/CFOpenDirectory" \
'${OpenDirectory}/Core/CFOpenDirectoryPriv.h' \
'${OpenDirectory}/Core/CFODTrigger.h'
touch "$out/include/CFOpenDirectory/CFOpenDirectoryConstantsPriv.h"
install -D -t "$out/include/IOKit" \
'${xnu}/iokit/IOKit/IOKitKeysPrivate.h'
install -D -t "$out/include/OpenDirectory" \
'${OpenDirectory}/Framework/OpenDirectoryPriv.h' \
'${OpenDirectory}/Framework/NSOpenDirectoryPriv.h'
install -D -t "$out/include/System/sys" \
'${xnu}/bsd/sys/proc.h' \
'${xnu}/bsd/sys/proc_uuid_policy.h'
install -D -t "$out/include" \
'${libmalloc}/private/stack_logging.h' \
'${libplatform}/private/_simple.h' \
'${xnu}/libsyscall/wrappers/spawn/spawn_private.h'
touch "$out/include/btm.h"
cp -r '${libdispatch}/private' "$out/include/dispatch"
# Work around availability headers compatibility issue when building with an unprocessed SDK.
chmod -R u+w "$out/include/dispatch"
find "$out/include/dispatch" -name '*.h' -exec sed -i {} -e 's/, bridgeos([^)]*)//g' \;
install -D -t "$out/include/System/i386" \
'${xnu}/osfmk/i386/cpu_capabilities.h'
install -D -t "$out/include/kern" \
'${xnu}/osfmk/kern/debug.h'
install -D -t "$out/include/mach" \
'${xnu}/osfmk/mach/coalition.h'
install -D -t "$out/include/os" \
'${Libc}/os/assumes.h' \
'${Libc}/os/variant_private.h' \
'${xnu}/libkern/os/base_private.h'
substituteInPlace "$out/include/os/variant_private.h" \
--replace-fail ', bridgeos(4.0)' "" \
--replace-fail ', bridgeos' ""
touch "$out/include/os/feature_private.h"
install -D -t "$out/include/sys" \
'${xnu}/bsd/sys/csr.h' \
'${xnu}/bsd/sys/pgo.h' \
'${xnu}/bsd/sys/kern_memorystatus.h' \
'${xnu}/bsd/sys/reason.h' \
'${xnu}/bsd/sys/resource.h' \
'${xnu}/bsd/sys/spawn_internal.h' \
'${xnu}/bsd/sys/stackshot.h'
# Older source releases depend on CrashReporterClient.h, but its not publicly available.
touch "$out/include/CrashReporterClient.h"
'';
};
in
mkAppleDerivation {
releaseName = "system_cmds";
xcodeHash = "sha256-gdtn3zNIneZKy6+X0mQ51CFVLNM6JQYLbd/lotG5/Tw=";
postPatch = ''
# Replace hard-coded, impure system paths with the output path in the store.
sed -e "s|PATH=[^;]*|PATH='$out/bin'|" -i "pagesize/pagesize.sh"
# Requires BackgroundTaskManagement.framework headers.
sed -e '/ if (os_feature_enabled(cronBTMToggle, cronBTMCheck))/,/ }/d' -i atrun/atrun.c
'';
preConfigure = ''
export NIX_CFLAGS_COMPILE+=" -iframework $SDKROOT/System/Library/Frameworks/OpenDirectory.framework/Frameworks"
'';
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
buildInputs = [
apple-sdk.privateFrameworksHook
ncurses
openpam
];
nativeBuildInputs = [ pkg-config ];
mesonFlags = [ (lib.mesonOption "sdk_version" stdenv.hostPlatform.darwinSdkVersion) ];
meta.description = "System commands for Darwin";
}

View File

@@ -0,0 +1,396 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/text_cmds/blob/main/text_cmds.xcodeproj/project.pbxproj
# Project settings
project('text_cmds', 'c', version : '@version@')
add_global_arguments(
# Many programs use old prototypes
'-Wno-deprecated-non-prototype',
# Needed to build errx functions from Libc
'-include', 'crt_externs.h',
'-D_getprogname()=(*_NSGetProgname())',
language : 'c',
)
fs = import('fs')
# Dependencies
cc = meson.get_compiler('c')
bzip2 = dependency('bzip2')
libmd = dependency('libmd')
libresolv = cc.find_library('resolv')
libutil = cc.find_library('util')
libxo = dependency('libxo')
ncurses = dependency('ncurses')
xz = dependency('liblzma')
zlib = dependency('zlib')
# Binaries
executable(
'banner',
install : true,
sources : [ 'banner/banner.c' ],
)
install_man('banner/banner.6')
executable(
'bintrans',
dependencies : [ libresolv ],
install : true,
sources : [
'bintrans/apple_base64.c',
'bintrans/bintrans.c',
'bintrans/qp.c',
'bintrans/uudecode.c',
'bintrans/uuencode.c',
fs.exists('err-libc.c') ? 'err-libc.c' : [ ],
],
)
install_man(
'bintrans/base64.1',
'bintrans/bintrans.1',
'bintrans/uuencode.format.5',
)
install_symlink(
'base64',
install_dir : get_option('bindir'),
pointing_to : 'bintrans',
)
foreach cmd : [ 'b64decode', 'b64encode', 'uudecode', 'uuencode' ]
install_symlink(
cmd,
install_dir : get_option('bindir'),
pointing_to : 'bintrans',
)
install_symlink(
f'@cmd@.1',
install_dir : get_option('mandir') + '/man1',
pointing_to : 'bintrans.1',
)
endforeach
executable(
'cat',
install : true,
sources : [ 'cat/cat.c' ],
)
install_man('cat/cat.1')
executable(
'col',
install : true,
sources : [
'col/col.c',
fs.exists('err-libc.c') ? 'err-libc.c' : [ ],
],
)
install_man('col/col.1')
executable(
'colrm',
install : true,
sources : [
'colrm/colrm.c',
fs.exists('err-libc.c') ? 'err-libc.c' : [ ],
],
)
install_man('colrm/colrm.1')
executable(
'column',
install : true,
sources : [ 'column/column.c' ],
)
install_man('column/column.1')
executable(
'comm',
install : true,
sources : [
'comm/comm.c',
fs.exists('err-libc.c') ? 'err-libc.c' : [ ],
],
)
install_man('comm/comm.1')
executable(
'csplit',
install : true,
sources : [
'csplit/csplit.c',
fs.exists('err-libc.c') ? 'err-libc.c' : [ ],
],
)
install_man('csplit/csplit.1')
executable(
'cut',
install : true,
sources : [ 'cut/cut.c' ],
)
install_man('cut/cut.1')
executable(
'ed',
install : true,
sources : [
'ed/buf.c',
'ed/glbl.c',
'ed/io.c',
'ed/main.c',
'ed/re.c',
'ed/sub.c',
'ed/undo.c',
],
)
install_man(
'ed/ed.1',
'ed/red.1',
)
executable(
'expand',
install : true,
sources : [ 'expand/expand.c' ],
)
install_man('expand/expand.1')
executable(
'fmt',
install : true,
sources : [ 'fmt/fmt.c' ],
)
install_man('fmt/fmt.1')
executable(
'fold',
install : true,
sources : [ 'fold/fold.c' ],
)
install_man('fold/fold.1')
executable(
'grep',
dependencies : [ bzip2, xz, zlib ],
install : true,
sources : [
'grep/file.c',
'grep/grep.c',
'grep/queue.c',
'grep/util.c',
],
)
install_man('grep/grep.1')
install_data(
'grep/zgrep.sh',
install_dir : get_option('bindir'),
install_mode : 'r-xr-xr-x',
rename : 'zgrep',
)
install_man('grep/zgrep.1')
executable(
'head',
install : true,
sources : [ 'head/head.c' ],
)
install_man('head/head.1')
executable(
'join',
install : true,
sources : [ 'join/join.c' ],
)
install_man('join/join.1')
executable(
'lam',
install : true,
sources : [ 'lam/lam.c' ],
)
install_man('lam/lam.1')
executable(
'look',
install : true,
sources : [ 'look/look.c' ],
)
install_man('look/look.1')
executable(
'md5',
dependencies : [ libmd ],
install : true,
sources : [ 'md5/md5.c' ],
)
install_man('md5/md5.1')
foreach cmd : [ 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512' ]
foreach suffix : [ '', 'sum' ]
cmd += suffix
if cmd != 'md5'
install_symlink(
cmd,
install_dir : get_option('bindir'),
pointing_to : 'md5',
)
install_symlink(
f'@cmd@.1',
install_dir : get_option('mandir') + '/man1',
pointing_to : 'md5.1',
)
endif
endforeach
endforeach
executable(
'nl',
install : true,
sources : [ 'nl/nl.c' ],
)
install_man('nl/nl.1')
executable(
'paste',
install : true,
sources : [ 'paste/paste.c' ],
)
install_man('paste/paste.1')
executable(
'pr',
install : true,
sources : [
'pr/egetopt.c',
'pr/pr.c',
],
)
install_man('pr/pr.1')
executable(
'rev',
install : true,
sources : [
'rev/rev.c',
],
)
install_man('rev/rev.1')
executable(
'rs',
install : true,
sources : [ 'rs/rs.c' ],
)
install_man('rs/rs.1')
executable(
'sed',
install : true,
sources : [
'sed/compile.c',
'sed/main.c',
'sed/misc.c',
'sed/process.c',
],
)
install_man('sed/sed.1')
executable(
'sort',
c_args : [ '-DSORT_VERSION="@version@"' ],
install : true,
sources : [
'sort/bwstring.c',
'sort/coll.c',
'sort/file.c',
'sort/mem.c',
'sort/radixsort.c',
'sort/sort.c',
'sort/vsort.c',
],
)
executable(
'split',
dependencies : [ libutil ],
install : true,
sources : [ 'split/split.c' ],
)
install_man('split/split.1')
executable(
'tail',
dependencies : [ libutil ],
install : true,
sources : [
'tail/forward.c',
'tail/misc.c',
'tail/read.c',
'tail/reverse.c',
'tail/tail.c',
],
)
install_man('tail/tail.1')
executable(
'tr',
install : true,
link_args : [ '-Wl,-undefined,dynamic_lookup' ],
sources : [
'tr/cmap.c',
'tr/cset.c',
'tr/str.c',
'tr/tr.c',
fs.exists('tr/collate-libc.c') ? 'tr/collate-libc.c' : [ ]
],
)
install_man('tr/tr.1')
executable(
'ul',
dependencies : [ ncurses ],
install : true,
sources : [ 'ul/ul.c' ],
)
install_man('ul/ul.1')
executable(
'unexpand',
install : true,
sources : [ 'unexpand/unexpand.c' ],
)
executable(
'uniq',
install : true,
sources : [ 'uniq/uniq.c' ],
)
install_man('uniq/uniq.1')
executable(
'unvis',
install : true,
sources : [ 'unvis/unvis.c' ],
)
install_man('unvis/unvis.1')
executable(
'vis',
install : true,
sources : [
'vis/foldit.c',
'vis/vis.c',
fs.exists('vis/vis-libc.c') ? 'vis/vis-libc.c' : [ ],
],
)
install_man('vis/vis.1')
executable(
'wc',
dependencies : [ libxo ],
install : true,
sources : [ 'wc/wc.c' ],
)
install_man('wc/wc.1')

View File

@@ -0,0 +1,100 @@
{
lib,
apple-sdk,
apple-sdk_13,
bzip2,
libmd,
libresolv,
libutil,
libxo,
mkAppleDerivation,
ncurses,
pkg-config,
shell_cmds,
stdenvNoCC,
xz,
zlib,
}:
let
Libc = apple-sdk.sourceRelease "Libc";
Libc_13 = apple-sdk_13.sourceRelease "Libc";
CommonCrypto = apple-sdk.sourceRelease "CommonCrypto";
libplatform = apple-sdk.sourceRelease "libplatform";
xnu = apple-sdk.sourceRelease "xnu";
privateHeaders = stdenvNoCC.mkDerivation {
name = "text_cmds-deps-private-headers";
buildCommand = ''
install -D -t "$out/include" \
'${libplatform}/private/_simple.h' \
'${Libc_13}/include/vis.h'
install -D -t "$out/include/os" \
'${Libc}/os/assumes.h' \
'${xnu}/libkern/os/base_private.h'
install -D -t "$out/include/CommonCrypto" \
'${CommonCrypto}/include/Private/CommonDigestSPI.h'
'';
};
in
mkAppleDerivation {
releaseName = "text_cmds";
outputs = [
"out"
"man"
];
xcodeHash = "sha256-dZ+yJyfflhmUyx3gitRXC115QxS87SGC4/HjMa199Ts=";
postPatch = ''
# Improve compatiblity with libmd in nixpkgs.
substituteInPlace md5/md5.c \
--replace-fail '<sha224.h>' '<sha2.h>' \
--replace-fail SHA224_Init SHA224Init \
--replace-fail SHA224_Update SHA224Update \
--replace-fail SHA224_End SHA224End \
--replace-fail SHA224_Data SHA224Data \
--replace-fail SHA224_CTX SHA2_CTX \
--replace-fail '<sha384.h>' '<sha512.h>' \
--replace-fail 'const void *, unsigned int, char *' 'const uint8_t *, size_t, char *'
''
+ lib.optionalString (lib.versionOlder (lib.getVersion apple-sdk) "13.0") ''
# Backport vis APIs from the 13.3 SDK (needed by vis).
cp '${Libc_13}/gen/FreeBSD/vis.c' vis/vis-libc.c
# Backport errx APIs from the 13.3 SDK (needed by lots of things).
mkdir sys
cp '${Libc_13}/gen/FreeBSD/err.c' err-libc.c
cp '${Libc_13}/include/err.h' err.h
cp '${Libc_13}/fbsdcompat/sys/cdefs.h' sys/cdefs.h
substituteInPlace err.h \
--replace-fail '__cold' ""
touch namespace.h un-namespace.h libc_private.h
'';
env.NIX_CFLAGS_COMPILE = "-I${privateHeaders}/include";
nativeBuildInputs = [ pkg-config ];
buildInputs = [
bzip2
libmd
libresolv
libutil
libxo
ncurses
xz
zlib
];
postInstall = ''
# Patch the shebangs to use `sh` from shell_cmds.
HOST_PATH='${lib.getBin shell_cmds}/bin' patchShebangs --host "$out/bin"
'';
meta = {
description = "Text commands for Darwin";
};
}

View File

@@ -0,0 +1,80 @@
# Build settings based on the upstream Xcode project.
# See: https://github.com/apple-oss-distributions/top/blob/main/top.xcodeproj/project.pbxproj
# Project settings
project('top', 'c', version : '@version@')
# Dependencies
cc = meson.get_compiler('c')
libutil = cc.find_library('util', has_headers : 'libutil.h')
ncurses = [
dependency('ncurses'),
dependency('form'),
dependency('panel'),
]
sdk_frameworks = dependency('appleframeworks', modules : ['CoreFoundation', 'IOKit'])
# Libraries
libtop = static_library(
'top',
sources : [
'libtop.c',
],
)
install_headers(
'libtop.h',
)
# Binaries
top = executable(
'top',
dependencies : [libutil, ncurses, sdk_frameworks],
install : true,
link_with : libtop,
sources : [
'command.c',
'cpu.c',
'csw.c',
'faults.c',
'generic.c',
'globalstats.c',
'layout.c',
'log.c',
'logging.c',
'main.c',
'memstats.c',
'messages.c',
'options.c',
'pgrp.c',
'pid.c',
'ports.c',
'power.c',
'ppid.c',
'preferences.c',
'pstate.c',
'sig.c',
'statistic.c',
'syscalls.c',
'threads.c',
'timestat.c',
'top.c',
'uid.c',
'uinteger.c',
'user.c',
'userinput.c',
'userinput_help.c',
'userinput_mode.c',
'userinput_order.c',
'userinput_secondary_order.c',
'userinput_signal.c',
'userinput_sleep.c',
'userinput_user.c',
'workqueue.c',
],
)
install_man(
'top.1',
)

View File

@@ -0,0 +1,42 @@
{
apple-sdk,
libutil,
mkAppleDerivation,
ncurses,
pkg-config,
}:
let
xnu = apple-sdk.sourceRelease "xnu";
in
mkAppleDerivation {
releaseName = "top";
xcodeHash = "sha256-YeBhEstvPh8IX8ArVc7U8IRU6vqPoOE6kBTqcqZonGc=";
patches = [
# Upstream removed aarch64 support from the 137 source release, but the removal can be reverted.
# Otherwise, top will fail to run on aarch64-darwin.
# Based on https://github.com/apple-oss-distributions/top/commit/a989bd5d18246e330e5feadd80958b913351f8ae.diff
./patches/0001-Revert-change-that-dropped-aarch64-support.patch
];
postPatch = ''
# Fix duplicate symbol error. `tsamp` is unused in `main.c`.
substituteInPlace main.c \
--replace-fail 'const libtop_tsamp_t *tsamp;' ""
# Adding the whole sys folder causes header conflicts, so copy only the private headers that are needed.
mkdir sys
cp ${xnu}/bsd/sys/{kern_memorystatus.h,reason.h} sys/
'';
buildInputs = [
libutil
ncurses
];
nativeBuildInputs = [ pkg-config ];
meta.description = "Display information about processes";
}

View File

@@ -0,0 +1,68 @@
diff --git a/libtop.c b/libtop.c
index 5afeaf3f90..755a584073 100644
--- a/libtop.c
+++ b/libtop.c
@@ -703,11 +703,20 @@
mach_vm_address_t base = 0, size = 0;
switch (type) {
+ case CPU_TYPE_ARM64_32:
+ base = SHARED_REGION_BASE_ARM64_32;
+ size = SHARED_REGION_SIZE_ARM64_32;
+ break;
+
case CPU_TYPE_ARM:
base = SHARED_REGION_BASE_ARM;
size = SHARED_REGION_SIZE_ARM;
break;
+ case CPU_TYPE_ARM64:
+ base = SHARED_REGION_BASE_ARM64;
+ size = SHARED_REGION_SIZE_ARM64;
+ break;
case CPU_TYPE_X86_64:
base = SHARED_REGION_BASE_X86_64;
@@ -816,6 +825,8 @@
#if defined(__arm__)
libtop_p_fw_scan(mach_task_self(), SHARED_REGION_BASE_ARM, SHARED_REGION_SIZE_ARM);
+#elif defined(__arm64__) && !defined(__LP64__)
+ libtop_p_fw_scan(mach_task_self(), SHARED_REGION_BASE_ARM64_32, SHARED_REGION_SIZE_ARM64_32);
#elif defined(__arm64__)
libtop_p_fw_scan(mach_task_self(), SHARED_REGION_BASE_ARM64, SHARED_REGION_SIZE_ARM64);
#elif defined(__x86_64__) || defined(__i386__)
@@ -1329,6 +1340,14 @@
switch (type) {
case CPU_TYPE_ARM:
return SHARED_REGION_SIZE_ARM;
+#if defined(CPU_TYPE_ARM64)
+ case CPU_TYPE_ARM64:
+ return SHARED_REGION_SIZE_ARM64;
+#endif
+#if defined(CPU_TYPE_ARM64_32)
+ case CPU_TYPE_ARM64_32:
+ return SHARED_REGION_SIZE_ARM64_32;
+#endif
case CPU_TYPE_POWERPC:
return SHARED_REGION_SIZE_PPC;
case CPU_TYPE_POWERPC64:
diff --git a/pid.c b/pid.c
index 0d9a77460a..54d532d51b 100644
--- a/pid.c
+++ b/pid.c
@@ -54,8 +54,13 @@
proc_is_foreign = true;
#endif
break;
+#if defined(CPU_TYPE_ARM64)
+ case CPU_TYPE_ARM64:
+ proc_is_64 = true;
+ // FALLTHROUGH
+#endif
case CPU_TYPE_ARM:
-#if !defined(__arm__)
+#if !defined(__arm__) && !defined(__arm64__)
proc_is_foreign = true;
#endif
break;

View File

@@ -0,0 +1,80 @@
#!/usr/bin/env nix-shell
#!nix-shell -i bash -p coreutils curl git gnutar jq moreutils nix
set -eu -o pipefail
if [ ! -v 1 ]; then
echo "usage: lock-sdk-deps.sh <macOS version> <Packages>" >&2
echo " <macOS version> Decimal-separated version number." >&2
echo " Must correspond to a tag in https://github.com/apple-oss-distributions/distribution-macOS" >&2
exit 1
fi
pkgdir=$(dirname "$(realpath "$0")")
lockfile=$pkgdir/versions.json
if [ -e "$lockfile" ]; then
echo '{}' > "$lockfile"
fi
workdir=$(mktemp -d)
trap 'rm -rf -- "$workdir"' EXIT
sdkVersion=$1; shift
tag="macos-${sdkVersion//.}"
declare -A ignoredPackages=(
[libsbuf]=1
[locale]=1
[mkAppleDerivation]=1
[update-source-releases.sh]=1
[versions.json]=1
)
readarray -t packages < <(
for file in "$pkgdir"/*; do
pkg=$(basename "$file" ".nix")
test ! "${ignoredPackages[$pkg]-}" && echo "$pkg"
done
)
echo "Locking versions for macOS $sdkVersion using tag '$tag'..."
pushd "$workdir" > /dev/null
git clone --branch "$tag" https://github.com/apple-oss-distributions/distribution-macOS.git &> /dev/null
cd distribution-macOS
for package in "${packages[@]}"; do
# If the tag exists in `release.json`, use that as an optimization to avoid downloading unnecessarily from Github.
packageTag=$(jq -r --arg package "$package" '.projects[] | select(.project == $package) | .tag' release.json)
packageCommit=$(git ls-tree -d HEAD "$package" | awk '{print $3}')
if [ ! -d "$package" ]; then
packageCommit=HEAD
fi
# However, sometimes it doesnt exist. In that case, fall back to cloning the repo and check manually
# which tag corresponds to the commit from the submodule.
if [ -z "$packageTag" ]; then
git clone --no-checkout "https://github.com/apple-oss-distributions/$package.git" ../source &> /dev/null
pushd ../source > /dev/null
packageTag=$(git tag --points-at "$packageCommit")
popd > /dev/null
rm -rf ../source
fi
packageVersion=${packageTag##"$package"-}
curl -OL "https://github.com/apple-oss-distributions/$package/archive/$packageTag.tar.gz" &> /dev/null
tar axf "$packageTag.tar.gz"
packageHash=$(nix --extra-experimental-features nix-command hash path "$package-$packageTag")
pkgsjson="{\"$package\": {\"version\": \"$packageVersion\", \"hash\": \"$packageHash\"}}"
echo " - Locking $package to version $packageVersion with hash '$packageHash'"
jq --argjson pkg "$pkgsjson" -S '. * $pkg' "$lockfile" | sponge "$lockfile"
done
popd > /dev/null

View File

@@ -0,0 +1,118 @@
{
"AvailabilityVersions": {
"hash": "sha256-PT54BPSRkQiIHrpxZCdjo6XvNuWxESabLndCBYjulfs=",
"version": "143.6"
},
"Csu": {
"hash": "sha256-l8RI8aiin7ovZuoDh54thDmd/b502w+dtjN5ZoISZBg=",
"version": "88"
},
"ICU": {
"hash": "sha256-7ImBX4SlrFaLnHdQ4bm4F8q9IpHhQMaeVOO6pnnhyzQ=",
"version": "74222.203"
},
"IOKitTools": {
"hash": "sha256-Oknsvzn4nv77WU7f0WPS446iwR2BM2q4iw46r/qctAE=",
"version": "125"
},
"PowerManagement": {
"hash": "sha256-APkvbp0FhNrypQcDUuREUYOnNLOZGOKhsj5JLcDgvAU=",
"version": "1740.60.27"
},
"adv_cmds": {
"hash": "sha256-alJOcKeHmIh67ZmN7/YdIouCP/qzakkhimsuZaOkr+c=",
"version": "231"
},
"basic_cmds": {
"hash": "sha256-RQve2GqS9ke9hd8kupRMgoOKalTS229asi5tBGrBmS8=",
"version": "70"
},
"bootstrap_cmds": {
"hash": "sha256-6JG0sysgqLlgcpIOXfN+F0/gxpIIHZZ5et3gmDBoBGQ=",
"version": "136"
},
"copyfile": {
"hash": "sha256-Vz1fo4p2b6S8xfyDPu1FNgMkH1aX0tkpXCZkdzkRdq0=",
"version": "213.40.2"
},
"developer_cmds": {
"hash": "sha256-jgQUjN9zmqi0/7XpqzbRsJjZIYeMrxXT1Zf3qi7+o+8=",
"version": "83"
},
"diskdev_cmds": {
"hash": "sha256-v3TFHLUlumt/sHxkOTyxDA4iG8ci5ZmMn7HCb4+9Uo0=",
"version": "737.60.1"
},
"doc_cmds": {
"hash": "sha256-/Mf+RhaTU9O5i95gddZ2h9eDjLezwj3nP6FvryMF54E=",
"version": "66"
},
"dyld": {
"hash": "sha256-DDhV7X81nhd3oeJuICEvF8FU43yE/afQ/LYgDNtXswA=",
"version": "1241.17"
},
"file_cmds": {
"hash": "sha256-/79jS//IBZiQBumGA60lKDmddQCzl/r8QnviD6lGXNg=",
"version": "448.0.3"
},
"libffi": {
"hash": "sha256-YjRMS3H3hIEfQm5MVSxGNTBtFc/9al7iQGDeZy6m/0U=",
"version": "39"
},
"libiconv": {
"hash": "sha256-eaUp0z7HqX0AW2C90gDVFeiJnmGRxPDuzyb1Jlm1pNc=",
"version": "109"
},
"libpcap": {
"hash": "sha256-RViIXv5zP2Bcive5qrcfb9vNWwhSe6fGCaToSgDYNxU=",
"version": "137"
},
"libresolv": {
"hash": "sha256-ndGcicbHizPazTCB0P3aioDOv7IJPmTOgLnioFHH2+o=",
"version": "83"
},
"libutil": {
"hash": "sha256-tUsl22Z0HUVSkSoohFXkhicNFCW+RARvpTS0q6yaQFk=",
"version": "72"
},
"mail_cmds": {
"hash": "sha256-ET1nga9nwgBtN7fuvsPs1yqe5OhQ62PVl7LxqbsAPqU=",
"version": "38.0.1"
},
"misc_cmds": {
"hash": "sha256-qPqcV9d4mKeu9ZD3rt3p5m1p/NyLy6np19ULC6FmnMI=",
"version": "44"
},
"network_cmds": {
"hash": "sha256-aGBsxdYW21QjTILxcR8tHufQKvkvmai9MKOCxBNZvmI=",
"version": "698.60.4"
},
"patch_cmds": {
"hash": "sha256-foIoIMe+zgPISFmE10q4cwEUBhiah4nbD7UtjBumZYU=",
"version": "66"
},
"remote_cmds": {
"hash": "sha256-a5ELSGJSTlyCb3bPdJqYSX320UzIkS2FiHxSpELIgls=",
"version": "303.0.2"
},
"removefile": {
"hash": "sha256-h1jb4DcgDHwi9eiUguc2e5OLP8ZHxCN3B4Myp/DFDBg=",
"version": "75"
},
"shell_cmds": {
"hash": "sha256-bcu9NNS7NW5oc5yrOk+GxZcQo0AP0+mOnph9HhLdRts=",
"version": "319.0.1"
},
"system_cmds": {
"hash": "sha256-9nNJeVJo4XwGSHh+SJydhVt+I8+Rb5hCsPiFYKQ8/28=",
"version": "1012.60.2"
},
"text_cmds": {
"hash": "sha256-76dagwRcAf5fpoyH5FDR5kdCldv6Mgre6aFBzxaCRkg=",
"version": "190.0.1"
},
"top": {
"hash": "sha256-e+k/jE49BMZZ24ge9JCa2ct5f1og6ewWb6U5ZMWdIEc=",
"version": "139.40.2"
}
}

View File

@@ -0,0 +1,126 @@
{
lib,
stdenvNoCC,
cctools,
clang-unwrapped,
ld64,
llvm,
llvm-manpages,
makeWrapper,
enableManpages ? stdenvNoCC.targetPlatform == stdenvNoCC.hostPlatform,
}:
let
inherit (stdenvNoCC) targetPlatform hostPlatform;
targetPrefix = lib.optionalString (targetPlatform != hostPlatform) "${targetPlatform.config}-";
llvm_cmds = [
"addr2line"
"ar"
"c++filt"
"dwarfdump"
"dsymutil"
"nm"
"objcopy"
"objdump"
"otool"
"size"
"strings"
"strip"
];
cctools_cmds = [
"codesign_allocate"
"gprof"
"ranlib"
# Use the cctools versions because the LLVM ones can crash or fail when the cctools ones dont.
# Revisit when LLVM is updated to LLVM 18 on Darwin.
"lipo"
"install_name_tool"
];
linkManPages =
pkg: source: target:
lib.optionalString enableManpages ''
sourcePath=${pkg}/share/man/man1/${source}.1.gz
targetPath=''${!outputMan}/share/man/man1/${target}.1.gz
if [ -f "$sourcePath" ]; then
mkdir -p "$(dirname "$targetPath")"
ln -s "$sourcePath" "$targetPath"
fi
'';
in
stdenvNoCC.mkDerivation {
pname = "${targetPrefix}cctools-binutils-darwin";
inherit (cctools) version;
outputs = [ "out" ] ++ lib.optional enableManpages "man";
strictDeps = true;
nativeBuildInputs = [ makeWrapper ];
buildCommand = ''
mkdir -p $out/bin $out/include
for tool in ${toString llvm_cmds}; do
# Translate between LLVM and traditional tool names (e.g., `c++filt` versus `cxxfilt`).
cctoolsTool=''${tool//-/_}
llvmTool=''${tool//++/xx}
# Some tools arent prefixed (like `dsymutil`).
llvmPath="${lib.getBin llvm}/bin"
if [ -e "$llvmPath/llvm-$llvmTool" ]; then
llvmTool=llvm-$llvmTool
elif [ -e "$llvmPath/${targetPrefix}$llvmTool" ]; then
llvmTool=${targetPrefix}$llvmTool
fi
# Not all tools are included in the bootstrap tools. Dont link them if they dont exist.
if [ -e "$llvmPath/$llvmTool" ]; then
ln -s "$llvmPath/$llvmTool" "$out/bin/${targetPrefix}$cctoolsTool"
fi
${linkManPages llvm-manpages "$llvmTool" "$cctoolsTool"}
done
for tool in ${toString cctools_cmds}; do
toolsrc="${lib.getBin cctools}/bin/${targetPrefix}$tool"
if [ -e "$toolsrc" ]; then
ln -s "${lib.getBin cctools}/bin/${targetPrefix}$tool" "$out/bin/${targetPrefix}$tool"
fi
${linkManPages (lib.getMan cctools) "$tool" "$tool"}
done
${
# These are unprefixed because some tools expect to invoke them without it when cross-compiling to Darwin:
# - clang needs `dsymutil` when building with debug information;
# - meson needs `lipo` when cross-compiling to Darwin; and
# - meson also needs `install_name_tool` and `otool` when performing rpath cleanup on installation.
lib.optionalString (targetPrefix != "") ''
for bintool in dsymutil install_name_tool lipo otool; do
ln -s "$out/bin/${targetPrefix}$bintool" "$out/bin/$bintool"
done
''
}
# Use the clang-integrated assembler. `as` in cctools is deprecated upstream and no longer built in nixpkgs.
makeWrapper "${lib.getBin clang-unwrapped}/bin/clang" "$out/bin/${targetPrefix}as" \
--add-flags "-x assembler -integrated-as -c"
ln -s '${lib.getBin ld64}/bin/ld' "$out/bin/${targetPrefix}ld"
${linkManPages (lib.getMan ld64) "ld" "ld"}
${linkManPages (lib.getMan ld64) "ld-classic" "ld-classic"}
${linkManPages (lib.getMan ld64) "ld64" "ld64"}
'';
__structuredAttrs = true;
passthru = {
inherit cctools_cmds llvm_cmds targetPrefix;
isCCTools = true; # The fact ld64 is used instead of lld is why this isnt `isLLVM`.
};
meta = {
maintainers = with lib.maintainers; [ reckenrode ];
priority = 10;
};
}

View File

@@ -0,0 +1,26 @@
local role_post
getHostRole
# Compare the requested deployment target to the existing one. The deployment target has to be a version number,
# and this hook tries to do the right thing with deployment targets set outside of it, so it has to parse
# the version numbers for the comparison manually.
local darwinMinVersion=@deploymentTarget@
local darwinMinVersionVar=@darwinMinVersionVariable@${role_post}
local currentDeploymentTargetArr
IFS=. read -a currentDeploymentTargetArr <<< "${!darwinMinVersionVar-0.0.0}"
local darwinMinVersionArr
IFS=. read -a darwinMinVersionArr <<< "$darwinMinVersion"
local currentDeploymentTarget
currentDeploymentTarget=$(printf "%02d%02d%02d" "${currentDeploymentTargetArr[0]-0}" "${currentDeploymentTargetArr[1]-0}" "${currentDeploymentTargetArr[2]-0}")
darwinMinVersion=$(printf "%02d%02d%02d" "${darwinMinVersionArr[0]-0}" "${darwinMinVersionArr[1]-0}" "${darwinMinVersionArr[2]-0}")
if [ "$darwinMinVersion" -gt "$currentDeploymentTarget" ]; then
export "$darwinMinVersionVar"=@deploymentTarget@
fi
unset -v role_post currentDeploymentTarget currentDeploymentTargetArr darwinMinVersion darwinMinVersionArr darwinMinVersionVar

View File

@@ -0,0 +1,27 @@
{ runCommand, cctools }:
{
haskellPackages,
src,
deps ? p: [ ],
name,
}:
let
inherit (haskellPackages) ghc ghcWithPackages;
with-env = ghcWithPackages deps;
ghcName = "${ghc.targetPrefix}ghc";
in
runCommand name
{
buildInputs = [
with-env
cctools
];
}
''
mkdir -p $out/lib
mkdir -p $out/include
${ghcName} ${src} -staticlib -outputdir . -o $out/lib/${name}.a -stubdir $out/include
for file in ${ghc}/lib/${ghcName}-${ghc.version}/include/*; do
ln -sv $file $out/include
done
''

View File

@@ -0,0 +1,38 @@
{ lib, runCommandLocal }:
# On darwin, there are some commands neither opensource nor able to build in nixpkgs.
# We have no choice but to use those system-shipped impure ones.
let
commands = {
ditto = "/usr/bin/ditto"; # ditto is not opensource
sudo = "/usr/bin/sudo"; # sudo must be owned by uid 0 and have the setuid bit set
};
mkImpureDrv =
name: path:
runCommandLocal "${name}-impure-darwin"
{
__impureHostDeps = [ path ];
meta = {
platforms = lib.platforms.darwin;
};
}
''
if ! [ -x ${path} ]; then
echo Cannot find command ${path}
exit 1
fi
mkdir -p $out/bin
ln -s ${path} $out/bin
manpage="/usr/share/man/man1/${name}.1"
if [ -f $manpage ]; then
mkdir -p $out/share/man/man1
ln -s $manpage $out/share/man/man1
fi
'';
in
lib.mapAttrs mkImpureDrv commands

View File

@@ -0,0 +1,13 @@
{ stdenvNoCC }:
# Darwin dynamically determines the `libSystem` to use based on the SDK found at `DEVELOPER_DIR`.
# By default, this will be `apple-sdk` or one of the versioned variants.
stdenvNoCC.mkDerivation {
pname = "libSystem";
version = "B";
# Silence linker warnings due a missing `lib` (which is added by cc-wrapper).
buildCommand = ''
mkdir -p "$out/include" "$out/lib"
'';
}

View File

@@ -0,0 +1,28 @@
{
# Use the text-based stubs and headers from the latest SDK (currently 15.x). This is safe because
# using features that are not available on an older deployment target is a hard error.
apple-sdk_15,
stdenvNoCC,
}:
stdenvNoCC.mkDerivation (finalAttrs: {
pname = "libcxx";
# Keep this in sync with the corresponding LLVM libc++ version
# defined as `_LIBCPP_VERSION` in `usr/include/c++/v1/__config`.
version = "19.1.2+apple-sdk-${apple-sdk_15.version}";
inherit (apple-sdk_15) src;
dontConfigure = true;
dontBuild = true;
installPhase = ''
runHook preInstall
mkdir -p "$out/include" "$out/lib"
cp -v usr/lib/libc++abi.tbd usr/lib/libc++.1.tbd "$out/lib"
ln -s libc++.1.tbd "$out/lib/libc++.tbd"
cp -rv usr/include/c++ "$out/include"
runHook postInstall
'';
passthru.isLLVM = true;
})

View File

@@ -0,0 +1,28 @@
{
lib,
apple-sdk,
stdenvNoCC,
}:
stdenvNoCC.mkDerivation (finalAttrs: {
pname = "libunwind";
inherit (apple-sdk) version;
# No `-lunwind` is provided because you get it automatically from linking with libSystem.
# Its also not possible to link libunwind directly, otherwise. Darwin requires going through libSystem.
buildCommand = ''
mkdir -p "$out/lib/pkgconfig"
cat <<EOF > "$out/lib/pkgconfig/libunwind.pc"
Name: libunwind
Description: An implementation of the HP libunwind interface
Version: ${finalAttrs.version}
EOF
'';
meta = {
description = "Compatibility package for libunwind on Darwin";
teams = [ lib.teams.darwin ];
platforms = lib.platforms.darwin;
pkgConfigModules = [ "libunwind" ];
};
})

View File

@@ -0,0 +1,32 @@
{
lib,
stdenv,
fetchFromGitHub,
}:
stdenv.mkDerivation {
version = "1.0";
pname = "lsusb";
src = fetchFromGitHub {
owner = "jlhonora";
repo = "lsusb";
rev = "8a6bd7084a55a58ade6584af5075c1db16afadd1";
sha256 = "0p8pkcgvsx44dd56wgipa8pzi3298qk9h4rl9pwsw1939hjx6h0g";
};
installPhase = ''
mkdir -p $out/bin
mkdir -p $out/share/man/man8
install -m 0755 lsusb $out/bin
install -m 0444 man/lsusb.8 $out/share/man/man8
'';
meta = {
homepage = "https://github.com/jlhonora/lsusb";
description = "Lsusb command for Mac OS X";
platforms = lib.platforms.darwin;
license = lib.licenses.mit;
maintainers = [ lib.maintainers.varunpatro ];
};
}

View File

@@ -0,0 +1,42 @@
{
lib,
swiftPackages,
fetchFromGitHub,
}:
let
inherit (swiftPackages) stdenv swift;
arch = if stdenv.hostPlatform.isAarch64 then "arm64" else "x86_64";
in
stdenv.mkDerivation {
pname = "openwith";
version = "unstable-2022-10-28";
src = fetchFromGitHub {
owner = "jdek";
repo = "openwith";
rev = "a8a99ba0d1cabee7cb470994a1e2507385c30b6e";
hash = "sha256-lysleg3qM2MndXeKjNk+Y9Tkk40urXA2ZdxY5KZNANo=";
};
nativeBuildInputs = [ swift ];
makeFlags = [ "openwith_${arch}" ];
installPhase = ''
runHook preInstall
install openwith_${arch} -D $out/bin/openwith
runHook postInstall
'';
meta = with lib; {
description = "Utility to specify which application bundle should open specific file extensions";
homepage = "https://github.com/jdek/openwith";
license = licenses.unlicense;
maintainers = with maintainers; [ zowoq ];
platforms = [
"aarch64-darwin"
"x86_64-darwin"
];
};
}

View File

@@ -0,0 +1,37 @@
{
lib,
stdenv,
fetchFromGitHub,
}:
stdenv.mkDerivation rec {
pname = "reattach-to-user-namespace";
version = "2.9";
src = fetchFromGitHub {
owner = "ChrisJohnsen";
repo = "tmux-MacOSX-pasteboard";
rev = "v${version}";
sha256 = "1qgimh58hcx5f646gj2kpd36ayvrdkw616ad8cb3lcm11kg0ag79";
};
buildFlags =
if stdenv.hostPlatform.system == "x86_64-darwin" then
[ "ARCHES=x86_64" ]
else if stdenv.hostPlatform.system == "aarch64-darwin" then
[ "ARCHES=arm64" ]
else
throw "reattach-to-user-namespace isn't being built for ${stdenv.hostPlatform.system} yet.";
installPhase = ''
mkdir -p $out/bin
cp reattach-to-user-namespace $out/bin/
'';
meta = with lib; {
description = "Wrapper that provides access to the Mac OS X pasteboard service";
license = licenses.bsd2;
maintainers = with maintainers; [ lnl7 ];
platforms = platforms.darwin;
};
}

View File

@@ -0,0 +1,31 @@
postFixupHooks+=(signDarwinBinariesInAllOutputs)
# Uses signingUtils, see definition of autoSignDarwinBinariesHook in
# darwin-packages.nix
signDarwinBinariesIn() {
local dir="$1"
if [ ! -d "$dir" ]; then
return 0
fi
if [ "${darwinDontCodeSign:-}" ]; then
return 0
fi
echo "signing $dir"
while IFS= read -r -d $'\0' f; do
signIfRequired "$f"
done < <(find "$dir" -type f -print0)
}
# Apply fixup to each output.
signDarwinBinariesInAllOutputs() {
local output
for output in $(getAllOutputNames); do
signDarwinBinariesIn "${!output}"
done
}

View File

@@ -0,0 +1,27 @@
{
stdenvNoCC,
sigtool,
cctools,
}:
let
stdenv = stdenvNoCC;
in
stdenv.mkDerivation {
name = "signing-utils";
dontUnpack = true;
dontConfigure = true;
dontBuild = true;
installPhase = ''
substituteAll ${./utils.sh} $out
'';
# Substituted variables
env = {
inherit sigtool;
codesignAllocate = "${cctools}/bin/${cctools.targetPrefix}codesign_allocate";
};
}

View File

@@ -0,0 +1,43 @@
# Work around for some odd behaviour where we can't codesign a file
# in-place if it has been called before. This happens for example if
# you try to fix-up a binary using strip/install_name_tool, after it
# had been used previous. The solution is to copy the binary (with
# the corrupted signature from strip/install_name_tool) to some
# location, sign it there and move it back into place.
#
# This does not appear to happen with the codesign tool that ships
# with recent macOS BigSur installs on M1 arm64 machines. However it
# had also been happening with the tools that shipped with the DTKs.
sign() {
local tmpdir
tmpdir=$(mktemp -d)
# $1 is the file
cp "$1" "$tmpdir"
CODESIGN_ALLOCATE=@codesignAllocate@ \
@sigtool@/bin/codesign -f -s - "$tmpdir/$(basename "$1")"
mv "$tmpdir/$(basename "$1")" "$1"
rmdir "$tmpdir"
}
checkRequiresSignature() {
local file=$1
local rc=0
@sigtool@/bin/sigtool --file "$file" check-requires-signature || rc=$?
if [ "$rc" -eq 0 ] || [ "$rc" -eq 1 ]; then
return "$rc"
fi
echo "Unexpected exit status from sigtool: $rc"
exit 1
}
signIfRequired() {
local file=$1
if checkRequiresSignature "$file"; then
sign "$file"
fi
}

Some files were not shown because too many files have changed in this diff Show More