vile / scheme / native_cache_d_vile_native.c.v
176 lines · 163 sloc · 6.92 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import crypto.sha256
4import dl
5import os
6
7struct NativeLibrary {
8 handle voidptr
9 entry voidptr
10}
11
12fn native_library(path string) ?NativeLibrary {
13 handle := dl.open_opt(path, dl.rtld_now) or { return none }
14 entry := dl.sym_opt(handle, 'native_entry') or {
15 dl.close(handle)
16 return none
17 }
18 return NativeLibrary{handle: handle, entry: entry}
19}
20
21fn native_private_directory(path string) bool {
22 info := os.lstat(path) or { return false }
23 return info.get_filetype() == .directory && info.uid == u32(os.geteuid())
24 && (info.mode & 0o077) == 0
25}
26
27fn native_cache_root() string {
28 requested := os.getenv('VILE_NATIVE_CACHE')
29 if requested == 'off' { return '' }
30 // Generated code needs only the platform integer ABI. Custom header roots
31 // can change those definitions without changing the generated text.
32 for key in ['CPATH', 'C_INCLUDE_PATH', 'CPLUS_INCLUDE_PATH', 'OBJC_INCLUDE_PATH', 'SDKROOT'] {
33 if os.getenv(key) != '' { return '' }
34 }
35 mut path := requested
36 if path == '' {
37 base := os.getenv('XDG_CACHE_HOME')
38 path = os.join_path(if base != '' { base } else { os.join_path(os.home_dir(), '.cache') }, 'vile', 'native-v1')
39 }
40 path = os.abs_path(path)
41 os.mkdir_all(path, mode: 0o700) or { return '' }
42 if !native_private_directory(path) { return '' }
43 return path
44}
45
46fn native_build_flags() []string {
47 mut flags := ['-std=c11', '-O3', '-ffp-contract=off', '-dynamiclib']
48 $if vile_native_sanitize ? {
49 flags << ['-fsanitize=address,undefined', '-fno-sanitize-recover=all', '-fno-omit-frame-pointer']
50 }
51 return flags
52}
53
54fn native_cache_frame(value string) string {
55 return '${value.len}:' + value
56}
57
58fn native_prepare_compiler(mut scope NativeScope) bool {
59 compiler := os.find_abs_path_of_executable('clang') or { return false }
60 info := os.stat(compiler) or { return false }
61 mut context := native_cache_frame(compiler) + native_cache_frame('${info.dev}:${info.inode}:${info.size}:${info.mtime}')
62 context += native_cache_frame(os.getwd())
63 for key in ['PATH', 'VILE_NATIVE_CACHE', 'XDG_CACHE_HOME', 'SDKROOT',
64 'MACOSX_DEPLOYMENT_TARGET', 'DEVELOPER_DIR', 'CPATH', 'C_INCLUDE_PATH',
65 'CPLUS_INCLUDE_PATH', 'OBJC_INCLUDE_PATH', 'LIBRARY_PATH'] {
66 context += native_cache_frame(key) + native_cache_frame(os.getenv(key))
67 }
68 if scope.compiler != '' && scope.compiler_context == context { return true }
69 mut cache := native_cache_root()
70 mut identity := ''
71 if cache != '' {
72 version := os.exec([compiler, '--version'])
73 // os.uname explicitly frees its temporary buffer and cannot run under
74 // the compiler scratch arena. os.exec keeps transient storage in scope.
75 platform := os.exec(['/usr/bin/uname', '-mr'])
76 if version.exit_code == 0 && platform.exit_code == 0 {
77 identity = context + native_cache_frame(version.output) + native_cache_frame(platform.output)
78 } else { cache = '' }
79 }
80 scope.metadata.push()
81 defer { scope.metadata.pop() }
82 scope.compiler = compiler.clone()
83 scope.compiler_context = context.clone()
84 scope.compiler_identity = identity.clone()
85 scope.cache_root = cache.clone()
86 return true
87}
88
89fn native_cache_key(code string, identity string, flags []string) string {
90 mut key := 'vile-native-code-v1\n${identity.len}:' + identity + '${flags.len}:'
91 for flag in flags { key += '${flag.len}:' + flag }
92 key += '${code.len}:' + code
93 return sha256.hexhash(key)
94}
95
96fn native_cache_load(root string, key string) ?NativeLibrary {
97 entry := os.join_path(root, key)
98 if !native_private_directory(root) || !native_private_directory(entry) { return none }
99 manifest_path := os.join_path(entry, 'current')
100 manifest_info := os.lstat(manifest_path) or { return none }
101 if manifest_info.get_filetype() != .regular || manifest_info.size > 130 { return none }
102 manifest := os.read_file(manifest_path) or { return none }
103 lines := manifest.split_into_lines()
104 if lines.len != 2 || lines[0] != key || lines[1].len != 64 { return none }
105 for c in lines[1].bytes() { if !((c >= `0` && c <= `9`) || (c >= `a` && c <= `f`)) { return none } }
106 path := os.join_path(entry, lines[1] + '.dylib')
107 info := os.lstat(path) or { return none }
108 if info.get_filetype() != .regular || info.uid != u32(os.geteuid())
109 || (info.mode & 0o022) != 0 || info.size == 0 || info.size > 16 * 1024 * 1024 { return none }
110 bytes := os.read_bytes(path) or { return none }
111 if sha256.sum256(bytes).hex() != lines[1] { return none }
112 return native_library(path)
113}
114
115fn native_cache_store(root string, key string, library string) {
116 if !native_private_directory(root) { return }
117 entry := os.join_path(root, key)
118 os.mkdir_all(entry, mode: 0o700) or { return }
119 if !native_private_directory(entry) { return }
120 info := os.stat(library) or { return }
121 if info.size == 0 || info.size > 16 * 1024 * 1024 { return }
122 bytes := os.read_bytes(library) or { return }
123 digest := sha256.sum256(bytes).hex()
124 mut pattern := os.join_path(entry, '.publish.${os.getpid()}.XXXXXX').bytes()
125 pattern << u8(0)
126 if isnil(unsafe { C.mkdtemp(&char(pattern.data)) }) { return }
127 directory := pattern[..pattern.len - 1].bytestr()
128 defer { os.rmdir_all(directory) or {} }
129 binary := os.join_path(directory, 'library')
130 manifest := os.join_path(directory, 'current')
131 os.write_file_array(binary, bytes) or { return }
132 os.chmod(binary, 0o500) or { return }
133 os.write_file(manifest, key + '\n' + digest + '\n') or { return }
134 // POSIX rename publishes complete files; unlike os.rename, this raw form
135 // never moves a file inside an existing destination directory.
136 os.rename_dir(binary, os.join_path(entry, digest + '.dylib')) or { return }
137 os.rename_dir(manifest, os.join_path(entry, 'current')) or { return }
138}
139
140fn native_build_library(mut scope NativeScope, code string) ?NativeLibrary {
141 if !native_prepare_compiler(mut scope) { return none }
142 flags := native_build_flags()
143 key := if scope.cache_root != '' { native_cache_key(code, scope.compiler_identity, flags) } else { '' }
144 if key != '' {
145 if library := native_cache_load(scope.cache_root, key) {
146 scope.cache_hits++
147 return library
148 }
149 }
150 if scope.directory == '' {
151 mut pattern := os.join_path(os.temp_dir(), 'vile-native.${os.getpid()}.XXXXXX').bytes()
152 pattern << u8(0)
153 if isnil(unsafe { C.mkdtemp(&char(pattern.data)) }) { return none }
154 directory := pattern[..pattern.len - 1].bytestr()
155 scope.metadata.push()
156 scope.directory = directory.clone()
157 scope.metadata.pop()
158 }
159 path := os.join_path(scope.directory, scope.plans.len.str())
160 os.write_file(path + '.c', code) or { return none }
161 mut build := [scope.compiler]
162 build << flags
163 build << [path + '.c', '-o', path + '.dylib']
164 scope.compilations++
165 if os.exec(build).exit_code != 0 { return none }
166 library := native_library(path + '.dylib') or { return none }
167 if key != '' { native_cache_store(scope.cache_root, key, path + '.dylib') }
168 return library
169}
170
171// Returns verified disk-cache hits and source compilation attempts in this scope.
172pub fn (vm &VM) native_compilation_stats() (u64, u64) {
173 if isnil(vm.native_execution_scope) { return 0, 0 }
174 scope := unsafe { &NativeScope(vm.native_execution_scope) }
175 return scope.cache_hits, scope.compilations
176}
177