4207a012b44f98954d19359b8e87a4f1ed72b3e8
[nit.git] / src / interpreter / dynamic_loading_ffi / on_demand_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Compiles extern code within a module to a static library, as needed
16 module on_demand_compiler
17
18 import modelbuilder
19 import c_tools
20 import nitni
21 import ffi
22 import naive_interpreter
23 import pkgconfig
24 import debugger_socket # To linearize `ToolContext::init`
25
26 redef class ToolContext
27
28 # --compile-dir
29 var opt_compile_dir = new OptionString("Directory used to generate temporary files", "--compile-dir")
30
31 init do option_context.add_option opt_compile_dir
32 end
33
34 redef class AMethPropdef
35 # Does this method definition use the FFI and is it supported by the interpreter?
36 #
37 # * Must use the nested foreign code block of the FFI.
38 # * Must not have callbacks.
39 # * Must be implemented in C.
40 # * Must not have a parameter or return typed with a Nit standard class.
41 fun supported_by_dynamic_ffi: Bool
42 do
43 # If the user specfied `is light_ffi`, it must be supported
44 var nats = get_annotations("light_ffi")
45 if nats.not_empty then return true
46
47 var n_extern_code_block = n_extern_code_block
48 if not (n_extern_calls == null and n_extern_code_block != null and
49 n_extern_code_block.is_c) then return false
50
51 for mparam in mpropdef.msignature.mparameters do
52 if not mparam.mtype.is_cprimitive then
53 return false
54 end
55 end
56
57 var return_mtype = mpropdef.msignature.return_mtype
58 if return_mtype != null and not return_mtype.is_cprimitive then
59 return false
60 end
61
62 return true
63 end
64 end
65
66 redef class NaiveInterpreter
67 redef fun start(mainmodule)
68 do
69 super
70
71 # Delete temporary files
72 var compile_dir = compile_dir
73 if compile_dir.file_exists then compile_dir.rmdir
74 end
75
76 # Where to store generated C and extracted code
77 private var compile_dir: String is lazy do
78 # Prioritize the user supplied directory
79 var opt = modelbuilder.toolcontext.opt_compile_dir.value
80 if opt != null then return opt
81 return "/tmp/niti_ffi_{process_id}"
82 end
83
84 # Identifier for this process, unique between running interpreters
85 private fun process_id: Int `{ return getpid(); `}
86
87 # Path of the compiled foreign code library
88 #
89 # TODO change the ".so" extension per platform.
90 fun foreign_code_lib_path(mmodule: MModule): String
91 do
92 return compile_dir / mmodule.c_name + ".so"
93 end
94
95 # External compiler used to generate the foreign code library
96 private var c_compiler = "cc"
97 end
98
99 redef class AModule
100
101 # Compile user FFI code and a standardized API into a `.so` file
102 #
103 # Returns `true` on success.
104 fun compile_foreign_lib(v: NaiveInterpreter): Bool
105 do
106 var mmodule = mmodule
107 assert mmodule != null
108
109 var compile_dir = v.compile_dir
110 var foreign_code_lib_path = v.foreign_code_lib_path(mmodule)
111
112 if not compile_dir.file_exists then compile_dir.mkdir(0o700)
113
114 # Compile the common FFI part
115 ensure_compile_ffi_wrapper
116 for mclassdef in mmodule.mclassdefs do for mpropdef in mclassdef.mpropdefs do
117 var anode = v.modelbuilder.mpropdef2node(mpropdef)
118 if mpropdef isa MMethodDef and anode isa AMethPropdef and anode.supported_by_dynamic_ffi then
119 anode.compile_ffi_method(mmodule)
120 end
121 end
122 mmodule.finalize_ffi_wrapper(compile_dir, mmodule)
123
124 # Compile the standard API and its implementation for the .so file
125 var ccu = compile_foreign_lib_api(compile_dir)
126
127 var srcs = [for file in ccu.files do new ExternCFile(file, ""): ExternFile]
128 srcs.add_all mmodule.ffi_files
129
130 # Compiler options specific to this module
131 var ldflags = mmodule.ldflags[""].join(" ")
132
133 # Protect pkg-config
134 var pkgconfigs = mmodule.pkgconfigs
135 var pkg_cflags = ""
136 if not pkgconfigs.is_empty then
137 var cmd = "which pkg-config >/dev/null"
138 if system(cmd) != 0 then
139 v.fatal "FFI Error: Command `pkg-config` not found. Please install it"
140 return false
141 end
142
143 for p in pkgconfigs do
144 cmd = "pkg-config --exists '{p}'"
145 if system(cmd) != 0 then
146 v.fatal "FFI Error: package {p} is not found by `pkg-config`. Please install it."
147 return false
148 end
149 end
150
151 pkg_cflags = "`pkg-config --cflags {pkgconfigs.join(" ")}`"
152 ldflags += " `pkg-config --libs {pkgconfigs.join(" ")}`"
153 end
154
155 # Compile each source file to an object file (or equivalent)
156 var object_files = new Array[String]
157 for f in srcs do
158 f.compile(v, mmodule, object_files, pkg_cflags)
159 end
160
161 # Link everything in a shared library
162 var cmd = "{v.c_compiler} -Wall -shared -o {foreign_code_lib_path} {object_files.join(" ")} {ldflags}"
163 if system(cmd) != 0 then
164 v.fatal "FFI Error: Failed to link native code using `{cmd}`"
165 return false
166 end
167
168 return true
169 end
170
171 # Compile the standard API of the `.so` file
172 #
173 # * The shared structure `nit_call_arg`.
174 # * Standardized implementation functions entrypoints that relay calls
175 # to the FFI implementation functions.
176 private fun compile_foreign_lib_api(compdir: String): CCompilationUnit
177 do
178 var mmodule = mmodule
179 assert mmodule != null
180
181 # ready extern code compiler
182 var ecc = new CCompilationUnit
183
184 ecc.body_decl.add """
185
186 #include <string.h>
187 #include <stdio.h>
188 #include <inttypes.h>
189
190 // C structure behind `CallArg` from the interpreter
191 typedef union nit_call_arg {
192 long value_Int;
193 int value_Bool;
194 uint32_t value_Char;
195 uint8_t value_Byte;
196 int8_t value_Int8;
197 int16_t value_Int16;
198 uint16_t value_UInt16;
199 int32_t value_Int32;
200 uint32_t value_UInt32;
201 double value_Float;
202 void* value_Pointer;
203 } nit_call_arg;
204
205 """
206
207 # types
208 var used_types = collect_mtypes
209 for t in used_types do
210 if not t.is_cprimitive then
211 ecc.header_c_types.add "typedef void* {t.cname};\n"
212 end
213 end
214
215 # TODO callbacks & casts
216
217 for nclassdef in n_classdefs do for npropdef in nclassdef.n_propdefs do
218 if npropdef isa AMethPropdef and npropdef.supported_by_dynamic_ffi then
219 npropdef.mpropdef.compile_foreign_code_entry ecc
220 end
221 end
222
223 ecc.write_as_foreign_lib_api(mmodule, compdir)
224
225 return ecc
226 end
227
228 # Collect all `MType` use in extern methods within this module
229 private fun collect_mtypes: Set[MType]
230 do
231 var used_types = new HashSet[MType]
232
233 # collect callbacks
234 for nclassdef in n_classdefs do for npropdef in nclassdef.n_propdefs do
235 if npropdef isa AMethPropdef and npropdef.supported_by_dynamic_ffi then
236 var fcs = npropdef.foreign_callbacks
237 used_types.add_all fcs.types
238 end
239 end
240
241 return used_types
242 end
243 end
244
245 redef class CCompilationUnit
246 # Write this compilation unit as the API of a foreign code library
247 private fun write_as_foreign_lib_api(mmodule: MModule, compdir: String)
248 do
249 # The FFI expects the support header to end with `._nitni.h`
250 var base_name = mmodule.c_name + "._nitni"
251 var guard = mmodule.c_name.to_s.to_upper + "_API_H"
252 var header_comment = """
253 /*
254 Public API to foreign code of the Nit module {{{mmodule.name}}}
255 */
256 """
257
258 # Header file
259 var h_file = base_name+".h"
260 var stream = new FileWriter.open(compdir/h_file)
261 stream.write header_comment
262 stream.write """
263 #ifndef {{{guard}}}
264 #define {{{guard}}}
265 """
266 compile_header_core stream
267 stream.write """
268
269 #endif
270 """
271 stream.close
272
273 # Body file
274 var c_file = base_name+".c"
275 stream = new FileWriter.open(compdir/c_file)
276 stream.write header_comment
277 stream.write """
278 #include "{{{h_file}}}"
279 """
280 compile_body_core stream
281 stream.close
282
283 # Only the C files needs compiling
284 files.add compdir / c_file
285 end
286 end
287
288 redef class MMethodDef
289 # Name of the entry point to the implementation function in the foreign lib
290 fun foreign_lib_entry_cname: String do return "entry__{cname}"
291
292 # Compile the standardized entry point as part of the foreign lib API
293 private fun compile_foreign_code_entry(ecc: CCompilationUnit)
294 do
295 var msignature = msignature
296 if msignature == null then return
297
298 # Return type
299 var return_mtype = msignature.return_mtype
300 if mproperty.is_init then return_mtype = mclassdef.mclass.mclass_type
301
302 var c_return_type
303 if return_mtype != null then
304 c_return_type = return_mtype.cname_blind
305 else c_return_type = "void"
306
307 var is_init = mproperty.is_init
308
309 # Params
310 var params = new Array[String]
311 if not is_init then params.add mclassdef.mclass.mclass_type.cname_blind
312 for param in msignature.mparameters do params.add param.mtype.cname_blind
313
314 # Declare the implementation function as extern
315 var impl_cname = mproperty.build_cname(mclassdef.bound_mtype,
316 mclassdef.mmodule, "___impl", long_signature)
317 ecc.body_decl.add "extern {c_return_type} {impl_cname}({params.join(", ")});\n"
318
319 # Declare the entry function
320 var foreign_lib_entry_cname = "int {foreign_lib_entry_cname}(int argc, nit_call_arg *argv, nit_call_arg *result)"
321 var fc = new CFunction(foreign_lib_entry_cname)
322
323 # Check argument count on the library side
324 #
325 # This may detect inconsistencies between the interpreter and the generated code.
326 var expected_argc = msignature.arity
327 if not is_init then expected_argc += 1
328
329 fc.exprs.add """
330 if (argc != {{{expected_argc}}}) {
331 printf("Invalid argument count in `{{{mproperty.full_name}}}`, expected %d, got %d.\\n",
332 argc, {{{expected_argc}}});
333 return 1;
334 }
335 """
336
337 # Unpack and prepare args for the user code
338 var k = 0
339 var args_for_call = new Array[String]
340 if not is_init then
341 var mtype = mclassdef.mclass.mclass_type
342 var arg_name = "arg___self"
343
344 fc.decls.add " {mtype.cname_blind} {arg_name};\n"
345 fc.exprs.add " {arg_name} = argv[{k}].{mtype.call_arg_field};\n"
346 args_for_call.add arg_name
347
348 k += 1
349 end
350 for param in msignature.mparameters do
351 var mtype = param.mtype
352 var arg_name = "arg__"+param.name
353
354 fc.decls.add " {mtype.cname_blind} {arg_name};\n"
355 fc.exprs.add " {arg_name} = argv[{k}].{mtype.call_arg_field};\n"
356 args_for_call.add arg_name
357
358 k += 1
359 end
360
361 # Call implementation function
362 var args_compressed = args_for_call.join(", ")
363 var method_call = "{impl_cname}({args_compressed})"
364 if return_mtype != null then
365 fc.decls.add """
366 {{{return_mtype.cname_blind}}} return_value;
367 """
368 fc.exprs.add """
369 return_value = {{{method_call}}};
370 result->{{{return_mtype.call_arg_field}}} = return_value;
371 """
372 else
373 fc.exprs.add " {method_call};\n"
374 end
375
376 fc.exprs.add " return 0;\n"
377
378 ecc.add_exported_function fc
379 end
380 end
381
382 redef class MType
383 # The interpreter FFI use `void*` to represent intern data types
384 redef fun cname_blind do return "void*"
385
386 # Field to store this type in the C structure `nit_call_arg`
387 private fun call_arg_field: String do return "value_Pointer"
388 end
389
390 redef class MClassType
391 redef fun call_arg_field
392 do
393 if is_cprimitive and mclass.kind != extern_kind then
394 return "value_{name}"
395 else return super
396 end
397 end
398
399 redef class ExternFile
400 # Compile this source file
401 private fun compile(v: NaiveInterpreter, mmodule: MModule,
402 object_files: Array[String], pkg_cflags: String): Bool is abstract
403 end
404
405 redef class ExternCFile
406 redef fun compile(v, mmodule, object_files, pkg_cflags)
407 do
408 var compile_dir = v.compile_dir
409 var cflags = mmodule.cflags[""].join(" ") + " " + pkg_cflags
410 var obj = compile_dir / filename.basename(".c") + ".o"
411
412 var cmd = "{v.c_compiler} -Wall -c -fPIC -I {compile_dir} -g -o {obj} {filename} {cflags}"
413 if sys.system(cmd) != 0 then
414 v.fatal "FFI Error: Failed to compile C code using `{cmd}`"
415 return false
416 end
417
418 object_files.add obj
419 return true
420 end
421 end