module scheme import crypto.sha256 import dl import os struct NativeLibrary { handle voidptr entry voidptr } fn native_library(path string) ?NativeLibrary { handle := dl.open_opt(path, dl.rtld_now) or { return none } entry := dl.sym_opt(handle, 'native_entry') or { dl.close(handle) return none } return NativeLibrary{handle: handle, entry: entry} } fn native_private_directory(path string) bool { info := os.lstat(path) or { return false } return info.get_filetype() == .directory && info.uid == u32(os.geteuid()) && (info.mode & 0o077) == 0 } fn native_cache_root() string { requested := os.getenv('VILE_NATIVE_CACHE') if requested == 'off' { return '' } // Generated code needs only the platform integer ABI. Custom header roots // can change those definitions without changing the generated text. for key in ['CPATH', 'C_INCLUDE_PATH', 'CPLUS_INCLUDE_PATH', 'OBJC_INCLUDE_PATH', 'SDKROOT'] { if os.getenv(key) != '' { return '' } } mut path := requested if path == '' { base := os.getenv('XDG_CACHE_HOME') path = os.join_path(if base != '' { base } else { os.join_path(os.home_dir(), '.cache') }, 'vile', 'native-v1') } path = os.abs_path(path) os.mkdir_all(path, mode: 0o700) or { return '' } if !native_private_directory(path) { return '' } return path } fn native_build_flags() []string { mut flags := ['-std=c11', '-O3', '-ffp-contract=off', '-dynamiclib'] $if vile_native_sanitize ? { flags << ['-fsanitize=address,undefined', '-fno-sanitize-recover=all', '-fno-omit-frame-pointer'] } return flags } fn native_cache_frame(value string) string { return '${value.len}:' + value } fn native_prepare_compiler(mut scope NativeScope) bool { compiler := os.find_abs_path_of_executable('clang') or { return false } info := os.stat(compiler) or { return false } mut context := native_cache_frame(compiler) + native_cache_frame('${info.dev}:${info.inode}:${info.size}:${info.mtime}') context += native_cache_frame(os.getwd()) for key in ['PATH', 'VILE_NATIVE_CACHE', 'XDG_CACHE_HOME', 'SDKROOT', 'MACOSX_DEPLOYMENT_TARGET', 'DEVELOPER_DIR', 'CPATH', 'C_INCLUDE_PATH', 'CPLUS_INCLUDE_PATH', 'OBJC_INCLUDE_PATH', 'LIBRARY_PATH'] { context += native_cache_frame(key) + native_cache_frame(os.getenv(key)) } if scope.compiler != '' && scope.compiler_context == context { return true } mut cache := native_cache_root() mut identity := '' if cache != '' { version := os.exec([compiler, '--version']) // os.uname explicitly frees its temporary buffer and cannot run under // the compiler scratch arena. os.exec keeps transient storage in scope. platform := os.exec(['/usr/bin/uname', '-mr']) if version.exit_code == 0 && platform.exit_code == 0 { identity = context + native_cache_frame(version.output) + native_cache_frame(platform.output) } else { cache = '' } } scope.metadata.push() defer { scope.metadata.pop() } scope.compiler = compiler.clone() scope.compiler_context = context.clone() scope.compiler_identity = identity.clone() scope.cache_root = cache.clone() return true } fn native_cache_key(code string, identity string, flags []string) string { mut key := 'vile-native-code-v1\n${identity.len}:' + identity + '${flags.len}:' for flag in flags { key += '${flag.len}:' + flag } key += '${code.len}:' + code return sha256.hexhash(key) } fn native_cache_load(root string, key string) ?NativeLibrary { entry := os.join_path(root, key) if !native_private_directory(root) || !native_private_directory(entry) { return none } manifest_path := os.join_path(entry, 'current') manifest_info := os.lstat(manifest_path) or { return none } if manifest_info.get_filetype() != .regular || manifest_info.size > 130 { return none } manifest := os.read_file(manifest_path) or { return none } lines := manifest.split_into_lines() if lines.len != 2 || lines[0] != key || lines[1].len != 64 { return none } for c in lines[1].bytes() { if !((c >= `0` && c <= `9`) || (c >= `a` && c <= `f`)) { return none } } path := os.join_path(entry, lines[1] + '.dylib') info := os.lstat(path) or { return none } if info.get_filetype() != .regular || info.uid != u32(os.geteuid()) || (info.mode & 0o022) != 0 || info.size == 0 || info.size > 16 * 1024 * 1024 { return none } bytes := os.read_bytes(path) or { return none } if sha256.sum256(bytes).hex() != lines[1] { return none } return native_library(path) } fn native_cache_store(root string, key string, library string) { if !native_private_directory(root) { return } entry := os.join_path(root, key) os.mkdir_all(entry, mode: 0o700) or { return } if !native_private_directory(entry) { return } info := os.stat(library) or { return } if info.size == 0 || info.size > 16 * 1024 * 1024 { return } bytes := os.read_bytes(library) or { return } digest := sha256.sum256(bytes).hex() mut pattern := os.join_path(entry, '.publish.${os.getpid()}.XXXXXX').bytes() pattern << u8(0) if isnil(unsafe { C.mkdtemp(&char(pattern.data)) }) { return } directory := pattern[..pattern.len - 1].bytestr() defer { os.rmdir_all(directory) or {} } binary := os.join_path(directory, 'library') manifest := os.join_path(directory, 'current') os.write_file_array(binary, bytes) or { return } os.chmod(binary, 0o500) or { return } os.write_file(manifest, key + '\n' + digest + '\n') or { return } // POSIX rename publishes complete files; unlike os.rename, this raw form // never moves a file inside an existing destination directory. os.rename_dir(binary, os.join_path(entry, digest + '.dylib')) or { return } os.rename_dir(manifest, os.join_path(entry, 'current')) or { return } } fn native_build_library(mut scope NativeScope, code string) ?NativeLibrary { if !native_prepare_compiler(mut scope) { return none } flags := native_build_flags() key := if scope.cache_root != '' { native_cache_key(code, scope.compiler_identity, flags) } else { '' } if key != '' { if library := native_cache_load(scope.cache_root, key) { scope.cache_hits++ return library } } if scope.directory == '' { mut pattern := os.join_path(os.temp_dir(), 'vile-native.${os.getpid()}.XXXXXX').bytes() pattern << u8(0) if isnil(unsafe { C.mkdtemp(&char(pattern.data)) }) { return none } directory := pattern[..pattern.len - 1].bytestr() scope.metadata.push() scope.directory = directory.clone() scope.metadata.pop() } path := os.join_path(scope.directory, scope.plans.len.str()) os.write_file(path + '.c', code) or { return none } mut build := [scope.compiler] build << flags build << [path + '.c', '-o', path + '.dylib'] scope.compilations++ if os.exec(build).exit_code != 0 { return none } library := native_library(path + '.dylib') or { return none } if key != '' { native_cache_store(scope.cache_root, key, path + '.dylib') } return library } // Returns verified disk-cache hits and source compilation attempts in this scope. pub fn (vm &VM) native_compilation_stats() (u64, u64) { if isnil(vm.native_execution_scope) { return 0, 0 } scope := unsafe { &NativeScope(vm.native_execution_scope) } return scope.cache_hits, scope.compilations }