diff --git a/guest/bundle/Makefile b/guest/bundle/Makefile index 8e9babba8..f1e14e068 100644 --- a/guest/bundle/Makefile +++ b/guest/bundle/Makefile @@ -234,6 +234,10 @@ $(STITCH_CONSTANTS): tests/stitch_constants.metal Makefile -o $(BUILD)/stitch_constants.air xcrun -sdk macosx metallib $(BUILD)/stitch_constants.air -o $@ +# A committed .metallib of our own (tests/shaders), which the shell tests read at URLs of each form +# as the device's newLibraryWithURL:error: reads them. +LIBRARY_FILE = ../../tests/shaders/compute_add.metallib + # The post-tessellation vertex functions of tests/patch.metal, for the shell tests' patch answers. PATCH_LIB = $(BUILD)/patch.metallib @@ -373,7 +377,7 @@ test: $(SER_TESTBIN) $(AIR_TESTBIN) $(AIR_LIB) $(AIR_OLD_LIB) $(AIR_11_LIB) $(AI RGFX_AIR_ARGUMENTS_11=$(AIR_11_LIB) RGFX_ORACLE_REFLECTION=$(ORACLE_REFLECTION_LIB) \ RGFX_COMMITTED_METALLIBS=$(COMMITTED_METALLIBS) arch -$(ARCH) $(AIR_TESTBIN) RGFX_CI_KERNEL=$(CI_KERNEL) RGFX_STITCHABLE=$(STITCHABLE) RGFX_STITCH_CONSTANTS=$(STITCH_CONSTANTS) \ - RGFX_AIR_ARGUMENTS=$(AIR_LIB) RGFX_AIR_ARGUMENTS_11=$(AIR_11_LIB) \ + RGFX_AIR_ARGUMENTS=$(AIR_LIB) RGFX_AIR_ARGUMENTS_11=$(AIR_11_LIB) RGFX_LIBRARY_FILE=$(LIBRARY_FILE) \ RGFX_AIR_REFLECTED=$(AIR_REFLECTED) RGFX_ORACLE_REFLECTION=$(ORACLE_REFLECTION_LIB) \ RGFX_PATCH=$(PATCH_LIB) $(SHELL_TESTBIN) arch -$(ARCH) $(INHERIT_TESTBIN) $(BUNDLEBIN) diff --git a/guest/bundle/src/RgfxLibraryFile.h b/guest/bundle/src/RgfxLibraryFile.h new file mode 100644 index 000000000..7f1b725d4 --- /dev/null +++ b/guest/bundle/src/RgfxLibraryFile.h @@ -0,0 +1,41 @@ +/* + * RgfxLibraryFile: the bytes of the library file a URL names, read as Metal's + * newLibraryWithURL:error: reads them, for the device's newLibraryWithURL:error: (and + * newLibraryWithFile:error:, which makes a file URL of its path). + * + * Metal opens the file at the URL's path, whatever the URL's scheme: a URL of no scheme is a path, + * relative to the current directory where it is relative, its percent escapes decoded; a URL of + * another scheme (http, one of no meaning) is the file at its path too. It answers nil and an + * error of MTLLibraryErrorDomain for a file it cannot read (measured: macOS 26.7.1, the AMD Radeon + * Pro 5300M and the Intel UHD 630, and macOS 27.0.1, the M3 Max, all alike, a .metallib of our own + * at each URL form): + * - a URL of no path (data:): MTLLibraryErrorFileNotFound (6), "Invalid file url"; + * - no file at the path: MTLLibraryErrorFileNotFound (6), "library not found"; + * - a file it may not open: MTLLibraryErrorUnsupported (1), "metal library file PATH failed to + * open with error: Permission denied", strerror's words for EACCES, the one error of an open + * measured besides ENOENT; another error is answered in the same form, with its own words; + * - a directory, or an empty file: MTLLibraryErrorUnsupported (1), "Invalid library file + * (unexpected end of file)". + * Each error's userInfo holds its description alone. Bytes that are not a library are the + * library's to refuse, as newLibraryWithData:error: refuses them. + * + * Our own ObjC++; no Apple private SPI. + */ + +#ifndef RGFX_LIBRARY_FILE_H_ +#define RGFX_LIBRARY_FILE_H_ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// The path Metal opens for `url`: its path, whatever its scheme; nil where it has none. +NSString *_Nullable RgfxLibraryFilePath(NSURL *url); + +/// The bytes of the file at `path` (RgfxLibraryFilePath's), mapped where that is safe; nil, with +/// Metal's error in `*error`, where it cannot be read. +NSData *_Nullable RgfxLibraryFileData(NSString *_Nullable path, NSError *_Nullable __autoreleasing *_Nullable error); + +NS_ASSUME_NONNULL_END + +#endif // RGFX_LIBRARY_FILE_H_ diff --git a/guest/bundle/src/RgfxLibraryFile.mm b/guest/bundle/src/RgfxLibraryFile.mm new file mode 100644 index 000000000..d16de111e --- /dev/null +++ b/guest/bundle/src/RgfxLibraryFile.mm @@ -0,0 +1,92 @@ +/* + * RgfxLibraryFile: see the header. Our own ObjC++. + */ + +#import "RgfxLibraryFile.h" + +#import + +#include +#include +#include + +namespace { + +NSError *libraryError(MTLLibraryError code, NSString *description) +{ + return [NSError errorWithDomain:MTLLibraryErrorDomain + code:code + userInfo:@{NSLocalizedDescriptionKey : description}]; +} + +NSError *notFound() +{ + return libraryError(MTLLibraryErrorFileNotFound, @"library not found"); +} + +NSError *endOfFile() +{ + return libraryError(MTLLibraryErrorUnsupported, @"Invalid library file (unexpected end of file)"); +} + +// Metal's error for a file it could not open, `reason` strerror's words for the open's error. +NSError *notOpened(NSString *path, NSString *reason) +{ + return libraryError(MTLLibraryErrorUnsupported, + [NSString stringWithFormat:@"metal library file %@ failed to open with error: %@", path, + reason]); +} + +NSString *reasonOf(int code) +{ + return @(strerror(code)); +} + +// The POSIX error under Foundation's error of a read, 0 where it names none. +int posixCodeOf(NSError *error) +{ + for (NSError *e = error; e != nil; e = e.userInfo[NSUnderlyingErrorKey]) { + if ([e.domain isEqualToString:NSPOSIXErrorDomain]) + return static_cast(e.code); + } + return 0; +} + +} // namespace + +NSString *RgfxLibraryFilePath(NSURL *url) +{ + NSString *path = url.path; + return path.length != 0 ? path : nil; +} + +NSData *RgfxLibraryFileData(NSString *path, NSError *__autoreleasing *error) +{ + NSError *answer = nil; + NSData *data = nil; + struct stat st = {}; + if (path == nil) { + answer = libraryError(MTLLibraryErrorFileNotFound, @"Invalid file url"); + } else if (stat(path.fileSystemRepresentation, &st) != 0) { + const int code = errno; + answer = code == ENOENT ? notFound() : notOpened(path, reasonOf(code)); + } else if (S_ISDIR(st.st_mode)) { + answer = endOfFile(); + } else { + NSError *readError = nil; + data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:&readError]; + if (data == nil) { + // Foundation's error names the read's POSIX error; where it names none, its own words + // stand for strerror's. + const int code = posixCodeOf(readError); + answer = code == ENOENT ? notFound() + : notOpened(path, code != 0 ? reasonOf(code) : readError.localizedDescription); + } else if (data.length == 0) { + data = nil; + answer = endOfFile(); + } + } + if (data == nil && error != nullptr) + *error = answer; + return data; +} diff --git a/guest/bundle/src/RgfxMetalDevice+Pipelines.mm b/guest/bundle/src/RgfxMetalDevice+Pipelines.mm index 4e08f089f..01d438f49 100644 --- a/guest/bundle/src/RgfxMetalDevice+Pipelines.mm +++ b/guest/bundle/src/RgfxMetalDevice+Pipelines.mm @@ -11,6 +11,7 @@ #import "RgfxBlockCall.h" #import "RgfxComputePipelineState.h" #import "RgfxLibrary.h" +#import "RgfxLibraryFile.h" #import "RgfxMetalError.h" #import "RgfxPipelineReflection.h" #import "RgfxRenderPipelineState.h" @@ -370,23 +371,25 @@ bool fileIdentity(const char *path, RgfxFileIdentity &out) return [super newLibraryWithDAG:dag functions:shadows error:error]; } -// A file's library is keyed by the file's identity where it is the same before and after the -// read (rgfxLibraryKeyOfFile), so a framework's library loaded again is not hashed again. +// The library of the file at the URL's path, whatever its scheme, as Metal reads it, with Metal's +// errors for a file it cannot read (RgfxLibraryFile.h): Espresso names its kernels' libraries by +// URLs of no scheme. A file's library is keyed by the file's identity where it is the same before +// and after the read (rgfxLibraryKeyOfFile), so a framework's library loaded again is not hashed +// again. - (id)newLibraryWithURL:(NSURL *)url error:(__autoreleasing NSError **)error { - const char *path = url.isFileURL ? url.fileSystemRepresentation : nullptr; - RgfxFileIdentity before = {}, after = {}; - const bool identified = fileIdentity(path, before); - NSError *readError = nil; - NSData *data = url ? [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe - error:&readError] - : nil; - if (data == nil) { + if (url == nil) { if (error) - *error = readError ?: RgfxMakeError(RgfxMetalErrorInvalidDescriptor, - @"newLibraryWithURL: could not read URL"); + *error = RgfxMakeError(RgfxMetalErrorInvalidDescriptor, @"newLibraryWithURL: nil URL"); return nil; } + NSString *filePath = RgfxLibraryFilePath(url); + const char *path = filePath.fileSystemRepresentation; + RgfxFileIdentity before = {}, after = {}; + const bool identified = fileIdentity(path, before); + NSData *data = RgfxLibraryFileData(filePath, error); + if (data == nil) + return nil; const bool same = identified && fileIdentity(path, after) && after == before && after.size == data.length; id lib = [self rgfxLibraryWithBytes:data.bytes diff --git a/guest/bundle/tests/shell_tests.mm b/guest/bundle/tests/shell_tests.mm index 8b8f12596..f75d4f265 100644 --- a/guest/bundle/tests/shell_tests.mm +++ b/guest/bundle/tests/shell_tests.mm @@ -45,6 +45,7 @@ #import "RgfxFunction.h" #import "RgfxGLFunction.h" #import "RgfxLibrary.h" +#import "RgfxLibraryFile.h" #import "RgfxMetalError.h" #import "RgfxPipelineReflection.h" #import "RgfxRenderPipelineState.h" @@ -70,6 +71,9 @@ #include #include #include +#include +#include +#include #include #include @@ -4462,6 +4466,96 @@ void test_function_array_library_holds_the_functions() // through as Metal gave it, the public device's words and code (both x86 Macs: MTLLibraryErrorDomain // 1 "Invalid metal package", and 6 "failed to open MPSGraph package"), and nothing reaches the // maker or the ring. +// A library file's URL, read as Metal's newLibraryWithURL:error: reads it (RgfxLibraryFile.h), over +// a .metallib of our own (RGFX_LIBRARY_FILE): the file at the URL's path, whatever its scheme, a +// URL of no scheme among them (as Espresso names its kernels' libraries), and Metal's errors for a +// file it cannot read. Each form's answer is also this Mac's Metal's, which the x86 Macs give alike +// (measured: macOS 26.7.1, the AMD 5300M and the Intel 630, and macOS 27.0.1, the M3 Max). +void test_library_file_urls_as_metal() +{ + Fixture fx; + const char *given = getenv("RGFX_LIBRARY_FILE"); + char resolved[PATH_MAX]; + CHECK(given != nullptr && realpath(given, resolved) != nullptr); + if (given == nullptr || realpath(given, resolved) == nullptr) + return; + NSString *lib = @(resolved), *dir = lib.stringByDeletingLastPathComponent, *name = lib.lastPathComponent; + NSData *bytes = [NSData dataWithContentsOfFile:lib]; + NSString *scratch = [NSTemporaryDirectory() stringByAppendingPathComponent: + [NSString stringWithFormat:@"rgfx-library-file-%d", getpid()]]; + NSFileManager *fm = [NSFileManager defaultManager]; + NSString *spaced = [scratch stringByAppendingPathComponent:@"with space"]; + CHECK([fm createDirectoryAtPath:spaced withIntermediateDirectories:YES attributes:nil error:nil]); + NSString *copy = [spaced stringByAppendingPathComponent:@"lib.metallib"]; + NSString *empty = [scratch stringByAppendingPathComponent:@"empty.metallib"]; + NSString *locked = [scratch stringByAppendingPathComponent:@"locked.metallib"]; + CHECK([bytes writeToFile:copy atomically:NO] && [[NSData data] writeToFile:empty atomically:NO] && + [bytes writeToFile:locked atomically:NO] && chmod(locked.fileSystemRepresentation, 0) == 0); + char cwd[PATH_MAX]; + CHECK(getcwd(cwd, sizeof cwd) != nullptr && chdir(dir.fileSystemRepresentation) == 0); + NSString *escaped = [copy stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet]; + const struct { + const char *what; + NSURL *url; + bool reads; + } cases[] = { + {"no scheme, absolute", [NSURL URLWithString:lib], true}, + {"a file URL", [NSURL fileURLWithPath:lib], true}, + {"relative to a file URL", [NSURL URLWithString:name relativeToURL:[NSURL fileURLWithPath:dir isDirectory:YES]], true}, + {"no scheme, relative to the current directory", [NSURL URLWithString:name], true}, + {"no scheme, escaped", [NSURL URLWithString:escaped], true}, + {"another scheme", [NSURL URLWithString:[@"rgfxtest://" stringByAppendingString:lib]], true}, + {"no scheme, missing", [NSURL URLWithString:[dir stringByAppendingPathComponent:@"no-such.metallib"]], false}, + {"no scheme, missing, relative", [NSURL URLWithString:@"no-such.metallib"], false}, + {"a file URL, missing", [NSURL fileURLWithPath:[dir stringByAppendingPathComponent:@"no-such.metallib"]], false}, + {"another scheme, missing", [NSURL URLWithString:@"rgfxtest:///no/such/lib.metallib"], false}, + {"of no path", [NSURL URLWithString:@"data:application/octet-stream;base64,AAAA"], false}, + {"a directory", [NSURL fileURLWithPath:dir isDirectory:YES], false}, + {"an empty file", [NSURL fileURLWithPath:empty], false}, + {"a file it may not open", [NSURL URLWithString:locked], false}, + }; + id metal = MTLCreateSystemDefaultDevice(); + for (const auto &c : cases) { + NSError *err = nil; + NSData *read = RgfxLibraryFileData(RgfxLibraryFilePath(c.url), &err); + NSError *metalError = nil; + id metals = [metal newLibraryWithURL:c.url error:&metalError]; + const bool sameError = err == nil ? metalError == nil + : metalError != nil && [err.domain isEqual:metalError.domain] && + err.code == metalError.code && + [err.localizedDescription isEqualToString:metalError.localizedDescription] && + [err.userInfo.allKeys isEqualToArray:metalError.userInfo.allKeys]; + const bool same = (read != nil) == (metals != nil) && sameError; + if ((read != nil) != c.reads || !same) + fprintf(stderr, "shell_tests: a library file URL, %s (%s): read %d, error %s; Metal's library %d, error %s\n", + c.what, c.url.absoluteString.UTF8String, read != nil, err.description.UTF8String, metals != nil, + metalError.description.UTF8String); + CHECK((read != nil) == c.reads && same); + if (c.reads) + CHECK([read isEqualToData:bytes]); + } + // The bytes read from a URL of no scheme make the library, as the file's own do. + NSData *read = RgfxLibraryFileData(RgfxLibraryFilePath([NSURL URLWithString:lib]), nullptr); + uint32_t status = 0; + RgfxLibrary *made = [RgfxLibrary libraryWithData:read.bytes + length:read.length + key:nullptr + device:nil + serializer:&fx.ser + status:&status]; + CHECK(made != nil && [made.functionNames containsObject:@"add_one"]); + // A missing file of no scheme: MTLLibraryErrorDomain 6, as Espresso's absent libraries answer. + NSError *err = nil; + CHECK(RgfxLibraryFileData(RgfxLibraryFilePath([NSURL URLWithString:@"/no/such/dir/espresso.metallib"]), &err) == + nil && + [err.domain isEqualToString:MTLLibraryErrorDomain] && err.code == MTLLibraryErrorFileNotFound && + [err.localizedDescription isEqualToString:@"library not found"]); + CHECK(chdir(cwd) == 0); + chmod(locked.fileSystemRepresentation, 0644); + [fm removeItemAtPath:scratch error:nil]; + drainRing(fx.ring); +} + void test_package_libraries_answer_metals_refusals() { Fixture fx; @@ -16878,6 +16972,7 @@ int main(int argc, char **argv) test_libraries_over_equal_bytes_share_their_air_reads(); test_source_compiles_through_metals_frontend(); test_function_array_library_holds_the_functions(); + test_library_file_urls_as_metal(); test_package_libraries_answer_metals_refusals(); test_stitched_libraries_in_archives(); test_function_members_from_shadow();