blob: b10989bbf8cc3eaf507746a2d9b7041036e54883 [file] [log] [blame]
Joel Galenson610a7512020-07-28 13:41:38 -07001use std::env;
2use std::path::Path;
3
4fn main() {
5 let out_dir = env::var("OUT_DIR").unwrap();
6 let out_path = Path::new(&out_dir).join("bindgen.rs");
7 if cfg!(feature = "in_gecko") {
8 // When inside mozilla-central, we are included into the build with
9 // sqlite3.o directly, so we don't want to provide any linker arguments.
10 std::fs::copy("sqlite3/bindgen_bundled_version.rs", out_path)
11 .expect("Could not copy bindings to output directory");
12 return;
13 }
14 if cfg!(feature = "sqlcipher") {
15 if cfg!(any(
16 feature = "bundled",
17 all(windows, feature = "bundled-windows")
18 )) {
19 println!(
20 "cargo:warning=Builds with bundled SQLCipher are not supported. Searching for SQLCipher to link against. \
21 This can lead to issues if your version of SQLCipher is not up to date!");
22 }
23 build_linked::main(&out_dir, &out_path)
24 } else {
25 // This can't be `cfg!` without always requiring our `mod build_bundled` (and
26 // thus `cc`)
27 #[cfg(any(feature = "bundled", all(windows, feature = "bundled-windows")))]
28 {
29 build_bundled::main(&out_dir, &out_path)
30 }
31 #[cfg(not(any(feature = "bundled", all(windows, feature = "bundled-windows"))))]
32 {
33 build_linked::main(&out_dir, &out_path)
34 }
35 }
36}
37
38#[cfg(any(feature = "bundled", all(windows, feature = "bundled-windows")))]
39mod build_bundled {
40 use std::env;
41 use std::path::Path;
42
43 pub fn main(out_dir: &str, out_path: &Path) {
44 if cfg!(feature = "sqlcipher") {
45 // This is just a sanity check, the top level `main` should ensure this.
46 panic!("Builds with bundled SQLCipher are not supported");
47 }
48
49 #[cfg(feature = "buildtime_bindgen")]
50 {
51 use super::{bindings, HeaderLocation};
52 let header = HeaderLocation::FromPath("sqlite3/sqlite3.h".to_owned());
53 bindings::write_to_out_dir(header, out_path);
54 }
55 #[cfg(not(feature = "buildtime_bindgen"))]
56 {
57 use std::fs;
58 fs::copy("sqlite3/bindgen_bundled_version.rs", out_path)
59 .expect("Could not copy bindings to output directory");
60 }
61
62 let mut cfg = cc::Build::new();
63 cfg.file("sqlite3/sqlite3.c")
64 .flag("-DSQLITE_CORE")
65 .flag("-DSQLITE_DEFAULT_FOREIGN_KEYS=1")
66 .flag("-DSQLITE_ENABLE_API_ARMOR")
67 .flag("-DSQLITE_ENABLE_COLUMN_METADATA")
68 .flag("-DSQLITE_ENABLE_DBSTAT_VTAB")
69 .flag("-DSQLITE_ENABLE_FTS3")
70 .flag("-DSQLITE_ENABLE_FTS3_PARENTHESIS")
71 .flag("-DSQLITE_ENABLE_FTS5")
72 .flag("-DSQLITE_ENABLE_JSON1")
73 .flag("-DSQLITE_ENABLE_LOAD_EXTENSION=1")
74 .flag("-DSQLITE_ENABLE_MEMORY_MANAGEMENT")
75 .flag("-DSQLITE_ENABLE_RTREE")
76 .flag("-DSQLITE_ENABLE_STAT2")
77 .flag("-DSQLITE_ENABLE_STAT4")
78 .flag("-DSQLITE_SOUNDEX")
79 .flag("-DSQLITE_THREADSAFE=1")
80 .flag("-DSQLITE_USE_URI")
81 .flag("-DHAVE_USLEEP=1")
82 .warnings(false);
83
84 if cfg!(feature = "with-asan") {
85 cfg.flag("-fsanitize=address");
86 }
87
88 // Older versions of visual studio don't support c99 (including isnan), which
89 // causes a build failure when the linker fails to find the `isnan`
90 // function. `sqlite` provides its own implmentation, using the fact
91 // that x != x when x is NaN.
92 //
93 // There may be other platforms that don't support `isnan`, they should be
94 // tested for here.
95 if cfg!(target_env = "msvc") {
96 use cc::windows_registry::{find_vs_version, VsVers};
97 let vs_has_nan = match find_vs_version() {
98 Ok(ver) => ver != VsVers::Vs12,
99 Err(_msg) => false,
100 };
101 if vs_has_nan {
102 cfg.flag("-DSQLITE_HAVE_ISNAN");
103 }
104 } else {
105 cfg.flag("-DSQLITE_HAVE_ISNAN");
106 }
107 if cfg!(feature = "unlock_notify") {
108 cfg.flag("-DSQLITE_ENABLE_UNLOCK_NOTIFY");
109 }
110 if cfg!(feature = "preupdate_hook") {
111 cfg.flag("-DSQLITE_ENABLE_PREUPDATE_HOOK");
112 }
113 if cfg!(feature = "session") {
114 cfg.flag("-DSQLITE_ENABLE_SESSION");
115 }
116
117 if let Ok(limit) = env::var("SQLITE_MAX_VARIABLE_NUMBER") {
118 cfg.flag(&format!("-DSQLITE_MAX_VARIABLE_NUMBER={}", limit));
119 }
120 println!("cargo:rerun-if-env-changed=SQLITE_MAX_VARIABLE_NUMBER");
121
122 if let Ok(limit) = env::var("SQLITE_MAX_EXPR_DEPTH") {
123 cfg.flag(&format!("-DSQLITE_MAX_EXPR_DEPTH={}", limit));
124 }
125 println!("cargo:rerun-if-env-changed=SQLITE_MAX_EXPR_DEPTH");
126
127 cfg.compile("libsqlite3.a");
128
129 println!("cargo:lib_dir={}", out_dir);
130 }
131}
132
133fn env_prefix() -> &'static str {
134 if cfg!(feature = "sqlcipher") {
135 "SQLCIPHER"
136 } else {
137 "SQLITE3"
138 }
139}
140
141pub enum HeaderLocation {
142 FromEnvironment,
143 Wrapper,
144 FromPath(String),
145}
146
147impl From<HeaderLocation> for String {
148 fn from(header: HeaderLocation) -> String {
149 match header {
150 HeaderLocation::FromEnvironment => {
151 let prefix = env_prefix();
152 let mut header = env::var(format!("{}_INCLUDE_DIR", prefix)).unwrap_or_else(|_| {
153 panic!(
154 "{}_INCLUDE_DIR must be set if {}_LIB_DIR is set",
155 prefix, prefix
156 )
157 });
158 header.push_str("/sqlite3.h");
159 header
160 }
161 HeaderLocation::Wrapper => "wrapper.h".into(),
162 HeaderLocation::FromPath(path) => path,
163 }
164 }
165}
166
167mod build_linked {
168 #[cfg(all(feature = "vcpkg", target_env = "msvc"))]
169 extern crate vcpkg;
170
171 use super::{bindings, env_prefix, HeaderLocation};
172 use std::env;
173 use std::path::Path;
174
175 pub fn main(_out_dir: &str, out_path: &Path) {
176 let header = find_sqlite();
177 if cfg!(any(
178 feature = "bundled_bindings",
179 feature = "bundled",
180 all(windows, feature = "bundled-windows")
181 )) && !cfg!(feature = "buildtime_bindgen")
182 {
183 // Generally means the `bundled_bindings` feature is enabled
184 // (there's also an edge case where we get here involving
185 // sqlcipher). In either case most users are better off with turning
186 // on buildtime_bindgen instead, but this is still supported as we
187 // have runtime version checks and there are good reasons to not
188 // want to run bindgen.
189 std::fs::copy("sqlite3/bindgen_bundled_version.rs", out_path)
190 .expect("Could not copy bindings to output directory");
191 } else {
192 bindings::write_to_out_dir(header, out_path);
193 }
194 }
195
196 fn find_link_mode() -> &'static str {
197 // If the user specifies SQLITE_STATIC (or SQLCIPHER_STATIC), do static
198 // linking, unless it's explicitly set to 0.
199 match &env::var(format!("{}_STATIC", env_prefix())) {
200 Ok(v) if v != "0" => "static",
201 _ => "dylib",
202 }
203 }
204 // Prints the necessary cargo link commands and returns the path to the header.
205 fn find_sqlite() -> HeaderLocation {
206 let link_lib = link_lib();
207
208 println!("cargo:rerun-if-env-changed={}_INCLUDE_DIR", env_prefix());
209 println!("cargo:rerun-if-env-changed={}_LIB_DIR", env_prefix());
210 println!("cargo:rerun-if-env-changed={}_STATIC", env_prefix());
211 if cfg!(all(feature = "vcpkg", target_env = "msvc")) {
212 println!("cargo:rerun-if-env-changed=VCPKGRS_DYNAMIC");
213 }
214
215 // dependents can access `DEP_SQLITE3_LINK_TARGET` (`sqlite3` being the
216 // `links=` value in our Cargo.toml) to get this value. This might be
217 // useful if you need to ensure whatever crypto library sqlcipher relies
218 // on is available, for example.
219 println!("cargo:link-target={}", link_lib);
220
221 // Allow users to specify where to find SQLite.
222 if let Ok(dir) = env::var(format!("{}_LIB_DIR", env_prefix())) {
223 // Try to use pkg-config to determine link commands
224 let pkgconfig_path = Path::new(&dir).join("pkgconfig");
225 env::set_var("PKG_CONFIG_PATH", pkgconfig_path);
226 if pkg_config::Config::new().probe(link_lib).is_err() {
227 // Otherwise just emit the bare minimum link commands.
228 println!("cargo:rustc-link-lib={}={}", find_link_mode(), link_lib);
229 println!("cargo:rustc-link-search={}", dir);
230 }
231 return HeaderLocation::FromEnvironment;
232 }
233
234 if let Some(header) = try_vcpkg() {
235 return header;
236 }
237
238 // See if pkg-config can do everything for us.
239 match pkg_config::Config::new()
240 .print_system_libs(false)
241 .probe(link_lib)
242 {
243 Ok(mut lib) => {
244 if let Some(mut header) = lib.include_paths.pop() {
245 header.push("sqlite3.h");
246 HeaderLocation::FromPath(header.to_string_lossy().into())
247 } else {
248 HeaderLocation::Wrapper
249 }
250 }
251 Err(_) => {
252 // No env var set and pkg-config couldn't help; just output the link-lib
253 // request and hope that the library exists on the system paths. We used to
254 // output /usr/lib explicitly, but that can introduce other linking problems;
255 // see https://github.com/rusqlite/rusqlite/issues/207.
256 println!("cargo:rustc-link-lib={}={}", find_link_mode(), link_lib);
257 HeaderLocation::Wrapper
258 }
259 }
260 }
261
262 #[cfg(all(feature = "vcpkg", target_env = "msvc"))]
263 fn try_vcpkg() -> Option<HeaderLocation> {
264 // See if vcpkg can find it.
265 if let Ok(mut lib) = vcpkg::Config::new().probe(link_lib()) {
266 if let Some(mut header) = lib.include_paths.pop() {
267 header.push("sqlite3.h");
268 return Some(HeaderLocation::FromPath(header.to_string_lossy().into()));
269 }
270 }
271 None
272 }
273
274 #[cfg(not(all(feature = "vcpkg", target_env = "msvc")))]
275 fn try_vcpkg() -> Option<HeaderLocation> {
276 None
277 }
278
279 fn link_lib() -> &'static str {
280 if cfg!(feature = "sqlcipher") {
281 "sqlcipher"
282 } else {
283 "sqlite3"
284 }
285 }
286}
287
288#[cfg(not(feature = "buildtime_bindgen"))]
289mod bindings {
290 use super::HeaderLocation;
291
292 use std::fs;
293 use std::path::Path;
294
295 static PREBUILT_BINDGEN_PATHS: &[&str] = &[
296 "bindgen-bindings/bindgen_3.6.8.rs",
297 #[cfg(feature = "min_sqlite_version_3_6_23")]
298 "bindgen-bindings/bindgen_3.6.23.rs",
299 #[cfg(feature = "min_sqlite_version_3_7_7")]
300 "bindgen-bindings/bindgen_3.7.7.rs",
301 #[cfg(feature = "min_sqlite_version_3_7_16")]
302 "bindgen-bindings/bindgen_3.7.16.rs",
303 ];
304
305 pub fn write_to_out_dir(_header: HeaderLocation, out_path: &Path) {
306 let in_path = PREBUILT_BINDGEN_PATHS[PREBUILT_BINDGEN_PATHS.len() - 1];
307 fs::copy(in_path, out_path).expect("Could not copy bindings to output directory");
308 }
309}
310
311#[cfg(feature = "buildtime_bindgen")]
312mod bindings {
313 use super::HeaderLocation;
314 use bindgen::callbacks::{IntKind, ParseCallbacks};
315
316 use std::fs::OpenOptions;
317 use std::io::Write;
318 use std::path::Path;
319
320 #[derive(Debug)]
321 struct SqliteTypeChooser;
322
323 impl ParseCallbacks for SqliteTypeChooser {
324 fn int_macro(&self, _name: &str, value: i64) -> Option<IntKind> {
325 if value >= i32::min_value() as i64 && value <= i32::max_value() as i64 {
326 Some(IntKind::I32)
327 } else {
328 None
329 }
330 }
331 }
332
333 // Are we generating the bundled bindings? Used to avoid emitting things
334 // that would be problematic in bundled builds. This env var is set by
335 // `upgrade.sh`.
336 fn generating_bundled_bindings() -> bool {
337 // Hacky way to know if we're generating the bundled bindings
338 println!("cargo:rerun-if-env-changed=LIBSQLITE3_SYS_BUNDLING");
339 match std::env::var("LIBSQLITE3_SYS_BUNDLING") {
340 Ok(v) if v != "0" => true,
341 _ => false,
342 }
343 }
344
345 pub fn write_to_out_dir(header: HeaderLocation, out_path: &Path) {
346 let header: String = header.into();
347 let mut output = Vec::new();
348 let mut bindings = bindgen::builder()
349 .header(header.clone())
350 .parse_callbacks(Box::new(SqliteTypeChooser))
351 .rustfmt_bindings(true);
352
353 if cfg!(feature = "unlock_notify") {
354 bindings = bindings.clang_arg("-DSQLITE_ENABLE_UNLOCK_NOTIFY");
355 }
356 if cfg!(feature = "preupdate_hook") {
357 bindings = bindings.clang_arg("-DSQLITE_ENABLE_PREUPDATE_HOOK");
358 }
359 if cfg!(feature = "session") {
360 bindings = bindings.clang_arg("-DSQLITE_ENABLE_SESSION");
361 }
362
363 // When cross compiling unless effort is taken to fix the issue, bindgen
364 // will find the wrong headers. There's only one header included by the
365 // amalgamated `sqlite.h`: `stdarg.h`.
366 //
367 // Thankfully, there's almost no case where rust code needs to use
368 // functions taking `va_list` (It's nearly impossible to get a `va_list`
369 // in Rust unless you get passed it by C code for some reason).
370 //
371 // Arguably, we should never be including these, but we include them for
372 // the cases where they aren't totally broken...
373 let target_arch = std::env::var("TARGET").unwrap();
374 let host_arch = std::env::var("HOST").unwrap();
375 let is_cross_compiling = target_arch != host_arch;
376
377 // Note that when generating the bundled file, we're essentially always
378 // cross compiling.
379 if generating_bundled_bindings() || is_cross_compiling {
380 // Get rid of va_list, as it's not
381 bindings = bindings
382 .blacklist_function("sqlite3_vmprintf")
383 .blacklist_function("sqlite3_vsnprintf")
384 .blacklist_function("sqlite3_str_vappendf")
385 .blacklist_type("va_list")
386 .blacklist_type("__builtin_va_list")
387 .blacklist_type("__gnuc_va_list")
388 .blacklist_type("__va_list_tag")
389 .blacklist_item("__GNUC_VA_LIST");
390 }
391
392 bindings
393 .generate()
394 .unwrap_or_else(|_| panic!("could not run bindgen on header {}", header))
395 .write(Box::new(&mut output))
396 .expect("could not write output of bindgen");
397 let mut output = String::from_utf8(output).expect("bindgen output was not UTF-8?!");
398
399 // rusqlite's functions feature ors in the SQLITE_DETERMINISTIC flag when it
400 // can. This flag was added in SQLite 3.8.3, but oring it in in prior
401 // versions of SQLite is harmless. We don't want to not build just
402 // because this flag is missing (e.g., if we're linking against
403 // SQLite 3.7.x), so append the flag manually if it isn't present in bindgen's
404 // output.
405 if !output.contains("pub const SQLITE_DETERMINISTIC") {
406 output.push_str("\npub const SQLITE_DETERMINISTIC: i32 = 2048;\n");
407 }
408
409 let mut file = OpenOptions::new()
410 .write(true)
411 .truncate(true)
412 .create(true)
413 .open(out_path)
414 .unwrap_or_else(|_| panic!("Could not write to {:?}", out_path));
415
416 file.write_all(output.as_bytes())
417 .unwrap_or_else(|_| panic!("Could not write to {:?}", out_path));
418 }
419}