-
Notifications
You must be signed in to change notification settings - Fork 23
/
build.rs
466 lines (411 loc) · 16.1 KB
/
build.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Build
#[macro_use]
extern crate error_chain;
error_chain! {
foreign_links {
Io(::std::io::Error);
EnvVar(::std::env::VarError);
StringFromUtf8(::std::string::FromUtf8Error);
}
}
use glob::glob;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Instant;
use std::borrow::Borrow;
use std::ffi::OsStr;
fn run_command_or_fail<P, S>(dir: &str, cmd: P, args: &[S])
where
P: AsRef<Path>,
S: Borrow<str> + AsRef<OsStr>,
{
let cmd = cmd.as_ref();
let cmd = if cmd.components().count() > 1 && cmd.is_relative() {
// If `cmd` is a relative path (and not a bare command that should be
// looked up in PATH), absolutize it relative to `dir`, as otherwise the
// behavior of std::process::Command is undefined.
// https://github.com/rust-lang/rust/issues/37868
PathBuf::from(dir)
.join(cmd)
.canonicalize()
.expect("canonicalization failed")
} else {
PathBuf::from(cmd)
};
eprintln!(
"Running command: \"{} {}\" in dir: {}",
cmd.display(),
args.join(" "),
dir
);
let ret = Command::new(cmd).current_dir(dir).args(args).status();
match ret.map(|status| (status.success(), status.code())) {
Ok((true, _)) => {}
Ok((false, Some(c))) => panic!("Command failed with error code {}", c),
Ok((false, None)) => panic!("Command got killed"),
Err(e) => panic!("Command failed with error: {}", e),
}
}
fn check_submodules_or_checkout_from_git() {
if !Path::new("submodules/tensorflow/LICENSE").exists() {
eprintln!("Setting up submodules");
run_command_or_fail(".", "git", &["submodule", "update", "--init"]);
}
if !Path::new("submodules/tensorflow/tensorflow/lite/micro/tools/make/downloads/flatbuffers/CONTRIBUTING.md").exists() {
eprintln!("Building tensorflow micro example to fetch Tensorflow dependencies");
run_command_or_fail("submodules/tensorflow", "make", &["-f", "tensorflow/lite/micro/tools/make/Makefile", "test_micro_speech_test"]);
}
}
fn manifest_dir() -> PathBuf {
PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap())
}
fn submodules() -> PathBuf {
manifest_dir().join("submodules")
}
fn flatbuffers_include_dir() -> PathBuf {
submodules().join("tensorflow/tensorflow/lite/micro/tools/make/downloads/flatbuffers/include")
}
fn is_cross_compiling() -> Result<bool> {
Ok(env::var("TARGET")? != env::var("HOST")?)
}
fn get_command_result(command: &mut Command) -> Result<String> {
command
.output()
.chain_err(|| "Couldn't find target GCC executable.")
.and_then(|output| {
if output.status.success() {
Ok(String::from_utf8(output.stdout)?)
} else {
panic!("Couldn't read output from GCC.")
}
})
}
/// Move tensorflow source to $OUT_DIR
fn prepare_tensorflow_source() -> PathBuf {
println!("Moving tensorflow micro source");
let start = Instant::now();
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let tf_src_dir = out_dir.join("tensorflow/tensorflow");
let submodules = submodules();
let copy_dir = fs_extra::dir::CopyOptions {
content_only: false,
overwrite: true,
skip_exist: false,
buffer_size: 65536,
copy_inside: false,
depth: 0,
};
if !tf_src_dir.exists() || cfg!(feature = "build") {
// Copy directory
println!("Copying TF from {:?}", submodules.join("tensorflow"));
println!("Copying TF to {:?}", out_dir);
fs_extra::dir::copy(submodules.join("tensorflow"), &out_dir, ©_dir)
.expect("Unable to copy tensorflow");
}
println!("Moving source took {:?}", start.elapsed());
tf_src_dir
}
/// Return a Vec of all *.cc files in `path`, excluding those that have a
/// name containing 'test.cc'
fn get_files_glob(path: PathBuf) -> Vec<String> {
let mut paths: Vec<String> = vec![];
for entry in glob(&path.to_string_lossy()).unwrap() {
let p: PathBuf = entry.unwrap();
paths.push(p.to_string_lossy().to_string());
}
paths
.into_iter()
.filter(|p| !p.contains("test.cc"))
.filter(|p| !p.contains("debug_log.cc"))
.filter(|p| !p.contains("frontend_memmap"))
.filter(|p| !p.contains("frontend_main"))
.collect()
}
trait CompilationBuilder {
fn flag(&mut self, s: &str) -> &mut Self;
fn define(&mut self, var: &str, val: Option<&str>) -> &mut Self;
/// Build flags for tensorflow micro sources
fn tensorflow_build_setup(&mut self) -> &mut Self {
let target = env::var("TARGET").unwrap_or_else(|_| "".to_string());
let build = self
.flag("-fno-rtti") // No Runtime type information
.flag("-fmessage-length=0")
.flag("-fno-exceptions")
.flag("-fno-unwind-tables")
.flag("-ffunction-sections")
.flag("-fdata-sections")
.flag("-funsigned-char")
.flag("-MMD")
.flag("-std=c++11")
.flag("-fno-delete-null-pointer-checks")
.flag("-fomit-frame-pointer")
.flag("-fpermissive")
.flag("-fno-use-cxa-atexit")
// use a full word for enums, this should match clang's behaviour
.flag("-fno-short-enums")
.define("TF_LITE_STATIC_MEMORY", None)
.define("TF_LITE_MCU_DEBUG_LOG", None)
.define("GEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK", None);
// warnings on by default
let build = if cfg!(feature = "no-c-warnings") {
build.flag("-w")
} else {
build
.flag("-Wvla")
.flag("-Wall")
.flag("-Wextra")
.flag("-Wno-unused-parameter")
.flag("-Wno-missing-field-initializers")
.flag("-Wno-write-strings")
.flag("-Wno-sign-compare")
.flag("-Wunused-function")
};
if target.starts_with("thumb") {
// unaligned accesses are usually a poor idea on ARM cortex-m
build.flag("-mno-unaligned-access")
} else {
build
}
}
}
impl CompilationBuilder for cpp_build::Config {
fn flag(&mut self, s: &str) -> &mut Self {
self.flag(s)
}
fn define(&mut self, var: &str, val: Option<&str>) -> &mut Self {
self.define(var, val)
}
}
impl CompilationBuilder for cc::Build {
fn flag(&mut self, s: &str) -> &mut Self {
self.flag(s)
}
fn define(&mut self, var: &str, val: Option<&str>) -> &mut Self {
self.define(var, val)
}
}
fn cc_tensorflow_library() {
let tflite = prepare_tensorflow_source();
let out_dir = env::var("OUT_DIR").unwrap();
let tf_lib_name =
Path::new(&out_dir).join("libtensorflow-microlite.a".to_string());
if is_cross_compiling().unwrap() {
// Find include directory used by the crosscompiler for libm
let mut gcc = cc::Build::new().get_compiler().to_command();
let libm_location = PathBuf::from(
get_command_result(gcc.arg("--print-file-name=libm.a"))
.expect("Error querying gcc for libm location"),
);
let libm_path = libm_location.parent().unwrap();
// Pass this to the linker
println!(
"cargo:rustc-link-search=native={}",
libm_path.to_string_lossy()
);
println!("cargo:rustc-link-lib=static=m");
}
if !tf_lib_name.exists() || cfg!(feature = "build") {
println!("Building tensorflow micro");
let target = env::var("TARGET").unwrap_or_else(|_| "".to_string());
let tfmicro_mdir = tflite.join("lite/micro/tools/make/");
let start = Instant::now();
let mut builder = cc::Build::new();
let builder_ref = builder
.cpp(true)
.tensorflow_build_setup()
.cpp_link_stdlib(None)
//
.include(tflite.parent().unwrap())
.include(tfmicro_mdir.join("downloads"))
.include(tfmicro_mdir.join("downloads/gemmlowp"))
.include(tfmicro_mdir.join("downloads/flatbuffers/include"))
.include(tfmicro_mdir.join("downloads/ruy"))
//
.files(get_files_glob(tflite.join("lite/micro/*.cc")))
.files(get_files_glob(tflite.join("lite/micro/kernels/*.cc")))
.files(get_files_glob(
tflite.join("lite/micro/memory_planner/*.cc"),
))
.files(get_files_glob(
tflite.join("lite/experimental/microfrontend/lib/*.c"),
))
.file(tflite.join("lite/c/common.c"))
.file(tflite.join("lite/core/api/error_reporter.cc"))
.file(tflite.join("lite/core/api/flatbuffer_conversions.cc"))
.file(tflite.join("lite/core/api/op_resolver.cc"))
.file(tflite.join("lite/core/api/tensor_utils.cc"))
.file(tflite.join("lite/kernels/internal/quantization_util.cc"))
.file(tflite.join("lite/kernels/kernel_util.cc"));
// CMSIS-NN for ARM Cortex-M targets
if target.starts_with("thumb")
&& target.contains("m-none-")
&& cfg!(feature = "cmsis-nn")
{
println!("Build includes CMSIS-NN.");
let cmsis = tflite.join("lite/micro/tools/make/downloads/cmsis");
builder_ref
.files(get_files_glob(cmsis.join("CMSIS/NN/Source/*.c")))
.include(cmsis.join("CMSIS/NN/Include"))
.include(cmsis.join("CMSIS/DSP/Include"))
.include(cmsis.join("CMSIS/Core/Include"));
}
// micro frontend
builder_ref
.include(tfmicro_mdir.join("downloads/kissfft"))
.include(tfmicro_mdir.join("downloads/kissfft/tools"))
.include(tflite.join("lite/experimental/microfrontend/lib"))
.files(get_files_glob(
tflite.join("lite/experimental/microfrontend/lib/*.cc"),
))
.file(tfmicro_mdir.join("downloads/kissfft/kiss_fft.c"))
.file(tfmicro_mdir.join("downloads/kissfft/tools/kiss_fftr.c"));
// Compile
builder_ref.compile("tensorflow-microlite");
println!(
"Building tensorflow micro from source took {:?}",
start.elapsed()
);
} else {
println!("Didn't rebuild tensorflow micro, using {:?}", tf_lib_name);
println!("cargo:rustc-link-lib=static=tensorflow-microlite");
println!("cargo:rustc-link-search=native={}", out_dir);
}
}
/// Configure bindgen for cross-compiling
fn bindgen_cross_builder() -> Result<bindgen::Builder> {
let builder = bindgen::Builder::default().clang_arg("--verbose");
if is_cross_compiling()? {
// Setup target triple
let target = env::var("TARGET")?;
let builder = builder.clang_arg(format!("--target={}", target));
println!("Setting bindgen to cross compile to {}", target);
// Find the sysroot used by the crosscompiler, and pass this to clang
let mut gcc = cc::Build::new().get_compiler().to_command();
let path = get_command_result(gcc.arg("--print-sysroot"))?;
let builder = builder.clang_arg(format!("--sysroot={}", path.trim()));
// Add a path to the system headers for the target
// compiler. Possibly we end up using a gcc header with clang
// frontend, which is sketchy.
let search_paths = cc::Build::new()
.cpp(true)
.get_compiler()
.to_command()
.arg("-E")
.arg("-Wp,-v")
.arg("-xc++")
.arg(".")
.output()
.chain_err(|| "Couldn't find target GCC executable.")
.and_then(|output| {
// We have to scrape the gcc console output to find where
// the c++ headers are. If we only needed the c headers we
// could use `--print-file-name=include` but that's not
// possible.
let gcc_out = String::from_utf8(output.stderr)?;
// Scrape the search paths
let search_start = gcc_out.find("search starts here").unwrap();
let search_paths: Vec<PathBuf> = gcc_out[search_start..]
.split('\n')
.map(|p| PathBuf::from(p.trim()))
.filter(|path| path.exists())
.collect();
Ok(search_paths)
})?;
// Add scraped paths to builder
let mut builder = builder.detect_include_paths(false);
for path in search_paths {
builder =
builder.clang_arg(format!("-I{}", path.to_string_lossy()));
}
Ok(builder)
} else {
Ok(builder)
}
}
/// This generates "tflite_types.rs" containing structs and enums which are
/// inter-operable with rust
fn bindgen_tflite_types() {
use bindgen::*;
let submodules = submodules();
let submodules_str = submodules.to_string_lossy();
let out_dir = env::var("OUT_DIR").unwrap();
let tflite_types_name = Path::new(&out_dir).join("tflite_types.rs");
if !tflite_types_name.exists() || cfg!(feature = "build") {
println!("Running bindgen");
let start = Instant::now();
let bindings = bindgen_cross_builder()
.expect("Error setting up bindgen for cross compiling")
.whitelist_recursively(true)
.prepend_enum_name(false)
.impl_debug(true)
.with_codegen_config(CodegenConfig::TYPES)
.layout_tests(false)
.enable_cxx_namespaces()
.derive_default(true)
.size_t_is_usize(true)
.use_core()
.ctypes_prefix("cty")
// Types
.whitelist_type("tflite::MicroErrorReporter")
.opaque_type("tflite::MicroErrorReporter")
.whitelist_type("tflite::Model")
.opaque_type("tflite::Model")
.whitelist_type("tflite::MicroInterpreter")
.opaque_type("tflite::MicroInterpreter")
.whitelist_type("tflite::ops::micro::AllOpsResolver")
.opaque_type("tflite::ops::micro::AllOpsResolver")
.whitelist_type("TfLiteTensor")
.whitelist_type("FrontendState")
.whitelist_type("FrontendConfig")
.whitelist_type("FrontendOutput")
// Types - blacklist
.blacklist_type("std")
.blacklist_type("tflite::Interpreter_TfLiteDelegatePtr")
.blacklist_type("tflite::Interpreter_State")
.default_enum_style(EnumVariation::Rust {
non_exhaustive: false,
})
.derive_partialeq(true)
.derive_eq(true)
.header("csrc/tflite_wrapper.hpp")
.clang_arg(format!("-I{}/tensorflow", submodules_str))
.clang_arg(format!(
// -> flatbuffers/flatbuffers.h
"-I{}",
flatbuffers_include_dir().to_string_lossy()
))
.clang_arg("-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK")
.clang_arg("-xc++")
.clang_arg("-std=c++11");
let bindings =
bindings.generate().expect("Unable to generate bindings");
// Write the bindings to $OUT_DIR/tflite_types.rs
let out_path = PathBuf::from(out_dir).join("tflite_types.rs");
bindings
.write_to_file(out_path)
.expect("Couldn't write bindings!");
println!("Running bindgen took {:?}", start.elapsed());
} else {
println!("Didn't regenerate bindings");
}
}
fn build_inline_cpp() {
let submodules = submodules();
println!("Building inline cpp");
let start = Instant::now();
cpp_build::Config::new()
.include(submodules.join("tensorflow"))
.include(flatbuffers_include_dir())
.tensorflow_build_setup()
.cpp_link_stdlib(None)
//.flag("-std=c++14")
.build("src/lib.rs");
println!("Building inline cpp took {:?}", start.elapsed());
}
fn main() {
check_submodules_or_checkout_from_git();
bindgen_tflite_types();
build_inline_cpp();
cc_tensorflow_library();
}