libdoltlite-sys 0.38.21

Native bindings to the DoltLite SQLite-compatible library
Documentation
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
use std::env;
use std::path::Path;

#[cfg(all(feature = "loadable_extension", feature = "preupdate_hook"))]
compile_error!("feature \"loadable_extension\" and feature \"preupdate_hook\" cannot be enabled at the same time");

/// Tells whether we're building for Windows. This is more suitable than a plain
/// `cfg!(windows)`, since the latter does not properly handle cross-compilation
///
/// Note that there is no way to know at compile-time which system we'll be
/// targeting, and this test must be made at run-time (of the build script) See
/// <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts>
fn win_target() -> bool {
    env::var("CARGO_CFG_WINDOWS").is_ok()
}

/// Tells whether we're building for Android.
/// See [`win_target`]
#[cfg(any(feature = "bundled", feature = "bundled-windows"))]
fn android_target() -> bool {
    env::var("CARGO_CFG_TARGET_OS").is_ok_and(|v| v == "android")
}

/// Tells whether a given compiler will be used `compiler_name` is compared to
/// the content of `CARGO_CFG_TARGET_ENV` (and is always lowercase)
///
/// See [`win_target`]
fn is_compiler(compiler_name: &str) -> bool {
    env::var("CARGO_CFG_TARGET_ENV").is_ok_and(|v| v == compiler_name)
}

/// Copy bindgen file from `dir` to `out_path`.
fn copy_bindings<T: AsRef<Path>>(dir: &str, bindgen_name: &str, out_path: T) {
    let from = if cfg!(feature = "loadable_extension") {
        format!("{dir}/{bindgen_name}_ext.rs")
    } else {
        format!("{dir}/{bindgen_name}.rs")
    };
    std::fs::copy(from, out_path).expect("Could not copy bindings to output directory");
}

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let out_path = Path::new(&out_dir).join("bindgen.rs");
    if cfg!(feature = "in_gecko") {
        // When inside mozilla-central, we are included into the build with
        // sqlite3.o directly, so we don't want to provide any linker arguments.
        copy_bindings("doltlite", "bindgen_bundled_version", out_path);
        return;
    }

    println!("cargo:rerun-if-env-changed=LIBSQLITE3_SYS_USE_PKG_CONFIG");
    if env::var_os("LIBSQLITE3_SYS_USE_PKG_CONFIG").is_some_and(|s| s != "0")
        || cfg!(feature = "loadable_extension")
    {
        build_linked::main(&out_dir, &out_path);
    } else if cfg!(feature = "bundled") || (win_target() && cfg!(feature = "bundled-windows")) {
        #[cfg(any(feature = "bundled", feature = "bundled-windows"))]
        build_bundled::main(&out_dir, &out_path);
        #[cfg(not(any(feature = "bundled", feature = "bundled-windows")))]
        panic!("The runtime test should not run this branch, which has not compiled any logic.")
    } else {
        build_linked::main(&out_dir, &out_path);
    }
}

#[cfg(any(feature = "bundled", feature = "bundled-windows"))]
mod build_bundled {
    use std::env;
    use std::io::Write;
    use std::path::{Path, PathBuf};
    use std::process::Command;

    use super::{is_compiler, win_target};

    pub fn main(out_dir: &str, out_path: &Path) {
        let lib_name = super::lib_name();

        // This is just a sanity check, the top level `main` should ensure this.
        assert!(!(cfg!(feature = "bundled-windows") && !cfg!(feature = "bundled") && !win_target()),
            "This module should not be used: we're not on Windows and the bundled feature has not been enabled");

        cfg_select! {
            feature = "buildtime_bindgen" => {
                use super::{bindings, HeaderLocation};
                let header = HeaderLocation::FromPath(lib_name.to_owned());
                bindings::write_to_out_dir(header, out_path);
            }
            _ => {
                super::copy_bindings(lib_name, "bindgen_bundled_version", out_path);
            }
        }
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        println!("cargo:include={}/{lib_name}", manifest_dir.display());
        let source_file = "doltlite.c";
        println!("cargo:rerun-if-changed={lib_name}/{source_file}");
        println!("cargo:rerun-if-changed=patches");
        let upstream_source = manifest_dir.join(lib_name).join(source_file);
        let patched_source = apply_local_patches(
            &upstream_source,
            &manifest_dir.join("patches"),
            &Path::new(out_dir).join("patched-doltlite"),
        );
        // Remote-auth server uses pthreads, unported to Windows/MSVC.
        let remote_supported = cfg!(feature = "remote")
            && !env::var("TARGET").is_ok_and(|target| target.starts_with("wasm32"))
            && !win_target();
        let remote_dir = Path::new(lib_name).join("remote");
        let auth_is_in_amalgamation = if remote_supported {
            append_remote_server_if_missing(
                &patched_source,
                &manifest_dir.join(&remote_dir).join("doltlite_remotesrv.c"),
            )
        } else {
            false
        };
        let mut cfg = cc::Build::new();
        cfg.file(&patched_source);

        #[cfg(feature = "blockcachevfs")]
        add_blockcachevfs(&mut cfg, manifest_dir, out_dir);

        // DoltLite's amalgamation includes both Windows headers used by
        // SQLite and Winsock2 headers used by the remote implementation.
        // Without this, <windows.h> may include legacy <winsock.h>, which
        // conflicts with <winsock2.h> on current Windows SDKs.
        if win_target() {
            cfg.define("WIN32_LEAN_AND_MEAN", None);
        }

        if remote_supported {
            let ed25519_dir = remote_dir.join("ed25519");
            let mbedtls_dir = remote_dir.join("mbedtls");
            let mut mbedtls_sources = std::fs::read_dir(mbedtls_dir.join("library"))
                .expect("could not read bundled mbedTLS sources")
                .map(|entry| entry.expect("could not read bundled mbedTLS source").path())
                .filter(|path| path.extension().is_some_and(|ext| ext == "c"))
                .collect::<Vec<_>>();
            mbedtls_sources.sort();

            println!("cargo:rerun-if-changed={}", remote_dir.display());
            cfg.define("DOLTLITE_HAVE_AUTH", None)
                .include(&remote_dir)
                .include(&ed25519_dir)
                .include(mbedtls_dir.join("include"))
                .include(mbedtls_dir.join("library"));
            if !auth_is_in_amalgamation {
                cfg.file(remote_dir.join("doltlite_creds.c"))
                    .file(remote_dir.join("doltlite_tls.c"))
                    .files(
                        [
                            "fe.c",
                            "ge.c",
                            "sc.c",
                            "sha512.c",
                            "keypair.c",
                            "sign.c",
                            "verify.c",
                        ]
                        .map(|name| ed25519_dir.join(name)),
                    )
                    .files(mbedtls_sources);
            }
        }

        cfg.flag("-DSQLITE_CORE")
            .flag("-DSQLITE_DEFAULT_FOREIGN_KEYS=1")
            .flag("-DSQLITE_ENABLE_API_ARMOR")
            .flag("-DSQLITE_ENABLE_COLUMN_METADATA")
            .flag("-DSQLITE_ENABLE_DBSTAT_VTAB")
            .flag("-DSQLITE_ENABLE_FTS3")
            .flag("-DSQLITE_ENABLE_FTS3_PARENTHESIS")
            .flag("-DSQLITE_ENABLE_FTS5")
            .flag("-DSQLITE_ENABLE_JSON1")
            .flag("-DSQLITE_ENABLE_LOAD_EXTENSION=1")
            .flag("-DSQLITE_ENABLE_MEMORY_MANAGEMENT")
            .flag("-DSQLITE_ENABLE_RTREE")
            .flag("-DSQLITE_ENABLE_STAT4")
            .flag("-DSQLITE_SOUNDEX")
            .flag("-DSQLITE_THREADSAFE=1")
            .flag("-DSQLITE_USE_URI")
            .flag("-DHAVE_USLEEP=1")
            .flag("-DHAVE_ISNAN")
            .flag("-D_POSIX_THREAD_SAFE_FUNCTIONS") // cross compile with MinGW
            .warnings(false);

        // on android sqlite can't figure out where to put the temp files.
        // the bundled sqlite on android also uses `SQLITE_TEMP_STORE=3`.
        // https://android.googlesource.com/platform/external/sqlite/+/2c8c9ae3b7e6f340a19a0001c2a889a211c9d8b2/dist/Android.mk
        if super::android_target() {
            cfg.flag("-DSQLITE_TEMP_STORE=3");
        }

        if cfg!(feature = "with-asan") {
            cfg.flag("-fsanitize=address");
        }

        // If explicitly requested: enable static linking against the Microsoft Visual
        // C++ Runtime to avoid dependencies on vcruntime140.dll and similar libraries.
        if env::var("CARGO_CFG_TARGET_FEATURE")
            .is_ok_and(|v| v.split(',').any(|tf| tf == "crt-static"))
            && is_compiler("msvc")
        {
            cfg.static_crt(true);
        }

        if !win_target() {
            cfg.flag("-DHAVE_LOCALTIME_R");
        }
        if env::var("TARGET").is_ok_and(|v| v.starts_with("wasm32-wasi")) {
            cfg.flag("-USQLITE_THREADSAFE")
                .flag("-DSQLITE_THREADSAFE=0")
                // https://github.com/rust-lang/rust/issues/74393
                .flag("-DLONGDOUBLE_TYPE=double")
                .flag("-D_WASI_EMULATED_MMAN")
                .flag("-D_WASI_EMULATED_GETPID")
                .flag("-D_WASI_EMULATED_SIGNAL")
                .flag("-D_WASI_EMULATED_PROCESS_CLOCKS");

            if cfg!(feature = "wasm32-wasi-vfs") {
                panic!("wasm32-wasi-vfs is not available with the bundled DoltLite backend");
            }
        }
        if env::var("TARGET").is_ok_and(|v| v.contains("emscripten")) {
            // The amalgamation's unix VFS section has `<fcntl.h>` commented out
            // unconditionally ("standard include files", ahead of unixOpen/
            // unixFileLock and the syscall table). glibc/BSD libc headers leak
            // open()/fcntl()/O_CREAT/struct flock declarations transitively
            // through other includes, masking this on macOS/Linux, but
            // Emscripten's musl libc does not, so the same code fails to compile
            // there with a string of "undeclared identifier" errors. Force-
            // including the header (rather than patching the amalgamation) fixes
            // it with no behavior change on other targets, where it's a no-op.
            cfg.flag("-include").flag("fcntl.h");
        }
        if cfg!(feature = "unlock_notify") {
            cfg.flag("-DSQLITE_ENABLE_UNLOCK_NOTIFY");
        }
        if cfg!(feature = "column_metadata") {
            cfg.flag("-DSQLITE_ENABLE_COLUMN_METADATA");
        }
        if cfg!(feature = "preupdate_hook") {
            cfg.flag("-DSQLITE_ENABLE_PREUPDATE_HOOK");
        }
        if cfg!(feature = "session") {
            cfg.flag("-DSQLITE_ENABLE_SESSION");
        }

        if let Ok(limit) = env::var("SQLITE_MAX_VARIABLE_NUMBER") {
            cfg.flag(format!("-DSQLITE_MAX_VARIABLE_NUMBER={limit}"));
        }
        println!("cargo:rerun-if-env-changed=SQLITE_MAX_VARIABLE_NUMBER");

        if let Ok(limit) = env::var("SQLITE_MAX_EXPR_DEPTH") {
            cfg.flag(format!("-DSQLITE_MAX_EXPR_DEPTH={limit}"));
        }
        println!("cargo:rerun-if-env-changed=SQLITE_MAX_EXPR_DEPTH");

        if let Ok(limit) = env::var("SQLITE_MAX_COLUMN") {
            cfg.flag(format!("-DSQLITE_MAX_COLUMN={limit}"));
        }
        println!("cargo:rerun-if-env-changed=SQLITE_MAX_COLUMN");

        if let Ok(extras) = env::var("LIBSQLITE3_FLAGS") {
            for extra in extras.split_whitespace() {
                if extra.starts_with("-D") || extra.starts_with("-U") {
                    cfg.flag(extra);
                } else if extra.starts_with("SQLITE_") {
                    cfg.flag(format!("-D{extra}"));
                } else {
                    panic!("Don't understand {extra} in LIBSQLITE3_FLAGS");
                }
            }
        }
        println!("cargo:rerun-if-env-changed=LIBSQLITE3_FLAGS");

        cfg.compile(lib_name);
        #[cfg(feature = "blockcachevfs")]
        link_blockcachevfs();
        if win_target() {
            // The DoltLite amalgamation always includes its remote client and
            // auth implementation, even when the Rust `remote` feature (which
            // exposes the in-process server) is disabled. Emit these after the
            // static archive because GNU linkers resolve libraries in order.
            println!("cargo:rustc-link-lib=ws2_32");
            println!("cargo:rustc-link-lib=bcrypt");
            println!("cargo:rustc-link-lib=crypt32");
        }
        if remote_supported && auth_is_in_amalgamation {
            compile_server_tls(&remote_dir);
        }

        println!("cargo:lib_dir={out_dir}");
    }

    #[cfg(feature = "blockcachevfs")]
    fn add_blockcachevfs(cfg: &mut cc::Build, manifest_dir: &Path, out_dir: &str) {
        use std::fs;

        let source_dir = manifest_dir.join("cloudsqlite/src");
        if !source_dir.is_dir() {
            panic!(
                "vendored Cloud Backed SQLite source directory is missing: {}",
                source_dir.display()
            );
        }
        println!(
            "cargo:rerun-if-changed={}",
            manifest_dir.join("cloudsqlite").display()
        );

        // CBS ships a sqlite3.h next to its sources.  Its quoted includes
        // would win over -I paths and silently compile against a second
        // SQLite ABI.  Compile from an OUT_DIR staging directory containing
        // only CBS's VFS files and the bundled DoltLite public header under
        // the name expected by CBS instead.
        let stage = Path::new(out_dir).join("blockcachevfs-src");
        fs::create_dir_all(&stage).expect("could not create CBS source staging directory");
        let sources = [
            "blockcachevfs.c",
            "simplexml.c",
            "bcvutil.c",
            "bcvmodule.c",
            "bcvlog.c",
            "bcvencrypt.c",
        ];
        let headers = [
            "blockcachevfs.h",
            "bcv_int.h",
            "bcvutil.h",
            "bcvmodule.h",
            "bcvencrypt.h",
            "simplexml.h",
        ];
        for name in sources.iter().chain(headers.iter()).copied() {
            let from = source_dir.join(name);
            if !from.is_file() {
                panic!("CBS source directory is missing {}", from.display());
            }
            fs::copy(&from, stage.join(name)).unwrap_or_else(|error| {
                panic!("could not stage CBS source {}: {error}", from.display())
            });
            println!("cargo:rerun-if-changed={}", from.display());
        }
        fs::copy(
            manifest_dir.join("doltlite/doltlite.h"),
            stage.join("sqlite3.h"),
        )
        .expect("could not stage bundled DoltLite header for CBS");
        apply_blockcache_patches(&stage, &manifest_dir.join("patches/blockcachevfs"));

        cfg.files(sources.iter().map(|name| stage.join(name)))
            .include(&stage)
            .flag("-DSQLITE_CORE")
            .flag("-DSQLITE_THREADSAFE=1")
            .define("BCV_DOLTLITE_INTEGRATION", None)
            .warnings(false);

        // CBS uses libcurl and OpenSSL directly.  Prefer pkg-config when the
        // target supplies it, but retain the conventional linker names for
        // systems where the development packages do not ship .pc files.
        let curl = pkg_config::Config::new()
            .cargo_metadata(false)
            .probe("libcurl")
            .or_else(|_| {
                pkg_config::Config::new()
                    .cargo_metadata(false)
                    .probe("curl")
            });
        let openssl = pkg_config::Config::new()
            .cargo_metadata(false)
            .probe("openssl");
        if let Ok(ref lib) = curl {
            cfg.includes(&lib.include_paths);
        } else if let Ok(path) = env::var("BLOCKCACHEVFS_CURL_INCLUDE_DIR") {
            cfg.include(path);
        } else {
            panic!(
                "could not find libcurl with pkg-config; set BLOCKCACHEVFS_CURL_INCLUDE_DIR to its headers"
            );
        }
        if let Ok(ref lib) = openssl {
            cfg.includes(&lib.include_paths);
        } else if let Ok(path) = env::var("BLOCKCACHEVFS_OPENSSL_INCLUDE_DIR") {
            cfg.include(path);
        } else {
            panic!(
                "could not find OpenSSL with pkg-config; set BLOCKCACHEVFS_OPENSSL_INCLUDE_DIR to its headers"
            );
        }
        println!("cargo:rerun-if-env-changed=BLOCKCACHEVFS_CURL_INCLUDE_DIR");
        println!("cargo:rerun-if-env-changed=BLOCKCACHEVFS_OPENSSL_INCLUDE_DIR");
    }

    #[cfg(feature = "blockcachevfs")]
    fn apply_blockcache_patches(stage: &Path, patch_dir: &Path) {
        use std::process::Command;

        println!("cargo:rerun-if-changed={}", patch_dir.display());
        let mut patches = std::fs::read_dir(patch_dir)
            .unwrap_or_else(|error| {
                panic!(
                    "could not read CBS patch directory {}: {error}",
                    patch_dir.display()
                )
            })
            .map(|entry| {
                entry
                    .unwrap_or_else(|error| panic!("could not read CBS patch: {error}"))
                    .path()
            })
            .filter(|path| path.extension().is_some_and(|ext| ext == "patch"))
            .collect::<Vec<_>>();
        patches.sort();
        for patch in &patches {
            println!("cargo:rerun-if-changed={}", patch.display());
        }
        if patches.is_empty() {
            panic!("the CBS patch set is empty");
        }
        let ceiling = stage.parent().unwrap_or(stage);
        let output = Command::new("git")
            .arg("apply")
            .args(&patches)
            .current_dir(stage)
            .env("GIT_CEILING_DIRECTORIES", ceiling)
            .env_remove("GIT_DIR")
            .env_remove("GIT_WORK_TREE")
            .env_remove("GIT_INDEX_FILE")
            .output()
            .unwrap_or_else(|error| {
                panic!(
                    "could not apply CBS patches: {error}. Git is required to build blockcachevfs"
                )
            });
        if !output.status.success() {
            panic!(
                "could not apply CBS patches to {}:\n{}",
                stage.display(),
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }

    #[cfg(feature = "blockcachevfs")]
    fn link_blockcachevfs() {
        let curl = pkg_config::Config::new()
            .cargo_metadata(false)
            .probe("libcurl")
            .or_else(|_| {
                pkg_config::Config::new()
                    .cargo_metadata(false)
                    .probe("curl")
            });
        let openssl = pkg_config::Config::new()
            .cargo_metadata(false)
            .probe("openssl");
        let curl_found = curl.is_ok();
        let openssl_found = openssl.is_ok();
        for lib in [curl, openssl].into_iter().flatten() {
            for path in lib.link_paths {
                println!("cargo:rustc-link-search=native={}", path.display());
            }
            for name in lib.libs {
                println!("cargo:rustc-link-lib={name}");
            }
            for name in lib.frameworks {
                println!("cargo:rustc-link-lib=framework={name}");
            }
        }
        // Development environments without pkg-config commonly still expose
        // the conventional shared-library names.
        if !curl_found {
            println!("cargo:rustc-link-lib=curl");
        }
        if !openssl_found {
            println!("cargo:rustc-link-lib=ssl");
            println!("cargo:rustc-link-lib=crypto");
        }
    }

    fn append_remote_server_if_missing(amalgamation: &Path, server_source: &Path) -> bool {
        let current = std::fs::read_to_string(amalgamation).unwrap_or_else(|error| {
            panic!(
                "could not inspect DoltLite amalgamation {}: {error}",
                amalgamation.display()
            )
        });
        let auth_is_in_amalgamation = current.contains("DOLTLITE_AMALGAMATION_AUTH");
        if current.contains("Begin file doltlite_remotesrv.c") {
            return auth_is_in_amalgamation;
        }

        let source = std::fs::read_to_string(server_source).unwrap_or_else(|error| {
            panic!(
                "could not read DoltLite remote-server source {}: {error}",
                server_source.display()
            )
        });
        let amalgamated_headers = [
            "#include \"sqliteInt.h\"",
            "#include \"chunk_store.h\"",
            "#include \"prolly_hash.h\"",
            "#include \"doltlite_remote.h\"",
            "#include \"doltlite_commit.h\"",
        ];
        let mut appended = String::with_capacity(source.len() + 256);
        appended.push_str(
            "\n/* Cargo-bundled upstream remote server sidecar. */\n\
             #undef DOLTLITE_AUTH_CLIENT_ONLY\n\
             #undef DOLTLITE_TLS_H\n",
        );
        for line in source.lines() {
            let trimmed = line.trim();
            if amalgamated_headers.contains(&trimmed) {
                continue;
            }
            if trimmed == "#include \"doltlite_tls.h\"" {
                // The sidecar must re-include this header after disabling
                // DOLTLITE_AUTH_CLIENT_ONLY to expose its server declarations.
                // DoltLite v0.50.7 also defines doltliteConnOpen inline there,
                // so give that redundant definition a private name.
                appended.push_str("#define doltliteConnOpen doltliteBundledServerHeaderConnOpen\n");
                appended.push_str(line);
                appended.push('\n');
                appended.push_str("#undef doltliteConnOpen\n");
                continue;
            }
            appended.push_str(line);
            appended.push('\n');
        }

        let mut output = std::fs::OpenOptions::new()
            .append(true)
            .open(amalgamation)
            .unwrap_or_else(|error| {
                panic!(
                    "could not open patched DoltLite amalgamation {}: {error}",
                    amalgamation.display()
                )
            });
        output
            .write_all(appended.as_bytes())
            .unwrap_or_else(|error| {
                panic!(
                    "could not append DoltLite remote-server source to {}: {error}",
                    amalgamation.display()
                )
            });
        auth_is_in_amalgamation
    }

    fn compile_server_tls(remote_dir: &Path) {
        let mbedtls_dir = remote_dir.join("mbedtls");
        let mut cfg = cc::Build::new();
        cfg.file(remote_dir.join("doltlite_tls.c"))
            .define(
                "doltliteConnOpenTimeout",
                "doltliteBundledClientConnOpenTimeout",
            )
            .define("doltliteConnOpen", "doltliteBundledClientConnOpen")
            .define("doltliteConnWriteAll", "doltliteBundledClientConnWriteAll")
            .define("doltliteConnRead", "doltliteBundledClientConnRead")
            .define("doltliteConnClose", "doltliteBundledClientConnClose")
            .include(remote_dir)
            .include(mbedtls_dir.join("include"))
            .include(mbedtls_dir.join("library"))
            .warnings(false);
        if win_target() {
            cfg.define("WIN32_LEAN_AND_MEAN", None);
        }
        cfg.compile("doltlite_server_tls");
    }

    fn apply_local_patches(upstream_source: &Path, patch_dir: &Path, output_dir: &Path) -> PathBuf {
        std::fs::create_dir_all(output_dir).unwrap_or_else(|error| {
            panic!(
                "could not create DoltLite patch directory {}: {error}",
                output_dir.display()
            )
        });
        let patched_source = output_dir.join("doltlite.c");
        std::fs::copy(upstream_source, &patched_source).unwrap_or_else(|error| {
            panic!(
                "could not copy pristine DoltLite source to {}: {error}",
                patched_source.display()
            )
        });

        let mut patches = std::fs::read_dir(patch_dir)
            .unwrap_or_else(|error| {
                panic!(
                    "could not read DoltLite patch directory {}: {error}",
                    patch_dir.display()
                )
            })
            .map(|entry| {
                entry
                    .unwrap_or_else(|error| panic!("could not read DoltLite patch: {error}"))
                    .path()
            })
            .filter(|path| {
                path.extension()
                    .is_some_and(|extension| extension == "patch")
            })
            .collect::<Vec<_>>();
        patches.sort();
        assert!(!patches.is_empty(), "the local DoltLite patch set is empty");

        let ceiling = output_dir
            .parent()
            .expect("DoltLite patch output directory must have a parent");
        let output = Command::new("git")
            .arg("apply")
            .args(&patches)
            .current_dir(output_dir)
            .env("GIT_CEILING_DIRECTORIES", ceiling)
            .env_remove("GIT_DIR")
            .env_remove("GIT_WORK_TREE")
            .env_remove("GIT_INDEX_FILE")
            .output()
            .unwrap_or_else(|error| {
                panic!(
                    "could not run `git apply` for local DoltLite patches: {error}. \
                     Git is required to build the bundled DoltLite source"
                )
            });
        if !output.status.success() {
            panic!(
                "`git apply` could not apply local DoltLite patches to {}:\n{}\
                 The upstream source may have changed or incorporated a local fix. \
                 Update the standard Git patches; do not edit the vendored amalgamation.",
                upstream_source.display(),
                String::from_utf8_lossy(&output.stderr)
            );
        }

        patched_source
    }
}

fn env_prefix() -> &'static str {
    "DOLTLITE"
}

fn lib_name() -> &'static str {
    "doltlite"
}

pub enum HeaderLocation {
    FromEnvironment,
    Wrapper,
    FromPath(String),
}

impl From<HeaderLocation> for String {
    fn from(header: HeaderLocation) -> Self {
        match header {
            HeaderLocation::FromEnvironment => {
                let prefix = env_prefix();
                let mut header = env::var(format!("{prefix}_INCLUDE_DIR")).unwrap_or_else(|_| {
                    panic!("{prefix}_INCLUDE_DIR must be set if {prefix}_LIB_DIR is set")
                });
                header.push_str(if cfg!(feature = "loadable_extension") {
                    "/sqlite3ext.h"
                } else {
                    "/doltlite.h"
                });
                header
            }
            HeaderLocation::Wrapper => if cfg!(feature = "loadable_extension") {
                "wrapper_ext.h"
            } else {
                "wrapper.h"
            }
            .into(),
            HeaderLocation::FromPath(path) => format!(
                "{}/{}",
                path,
                if cfg!(feature = "loadable_extension") {
                    "sqlite3ext.h"
                } else if path == "doltlite" {
                    "doltlite.h"
                } else {
                    "sqlite3.h"
                }
            ),
        }
    }
}

mod build_linked {
    #[cfg(feature = "vcpkg")]
    extern crate vcpkg;

    use super::{bindings, env_prefix, is_compiler, lib_name, win_target, HeaderLocation};
    use std::env;
    use std::path::Path;

    pub fn main(_out_dir: &str, out_path: &Path) {
        let header = find_sqlite();
        if (cfg!(any(feature = "bundled_bindings", feature = "bundled",))
            || (win_target() && cfg!(feature = "bundled-windows")))
            && !cfg!(feature = "buildtime_bindgen")
        {
            // Generally means the `bundled_bindings` feature is enabled.
            // Most users are better off with turning
            // on buildtime_bindgen instead, but this is still supported as we
            // have runtime version checks and there are good reasons to not
            // want to run bindgen.
            super::copy_bindings(lib_name(), "bindgen_bundled_version", out_path);
        } else {
            bindings::write_to_out_dir(header, out_path);
        }
    }

    #[cfg(not(feature = "loadable_extension"))]
    fn find_link_mode() -> &'static str {
        // If the user specifies DOLTLITE_STATIC, do static linking unless it is
        // explicitly set to 0.
        match &env::var(format!("{}_STATIC", env_prefix())) {
            Ok(v) if v != "0" => "static",
            _ => "dylib",
        }
    }
    // Prints the necessary cargo link commands and returns the path to the header.
    fn find_sqlite() -> HeaderLocation {
        let link_lib = lib_name();

        println!("cargo:rerun-if-env-changed={}_INCLUDE_DIR", env_prefix());
        println!("cargo:rerun-if-env-changed={}_LIB_DIR", env_prefix());
        println!("cargo:rerun-if-env-changed={}_STATIC", env_prefix());
        if cfg!(feature = "vcpkg") && is_compiler("msvc") {
            println!("cargo:rerun-if-env-changed=VCPKGRS_DYNAMIC");
        }

        // Dependents can access DEP_DOLTLITE_LINK_TARGET to get this value.
        // This is useful for checking whether the backend is doltlite or
        // another SQLite-compatible library.
        #[cfg(not(feature = "loadable_extension"))]
        println!("cargo:link-target={link_lib}");

        // Allow users to specify where to find SQLite.
        if let Ok(dir) = env::var(format!("{}_LIB_DIR", env_prefix())) {
            // Try to use pkg-config to determine link commands
            let pkgconfig_path = Path::new(&dir).join("pkgconfig");
            env::set_var("PKG_CONFIG_PATH", pkgconfig_path);
            #[cfg(not(feature = "loadable_extension"))]
            if pkg_config::Config::new()
                .atleast_version("3.34.1")
                .probe(link_lib)
                .is_err()
            {
                // Otherwise just emit the bare minimum link commands.
                println!("cargo:rustc-link-lib={}={link_lib}", find_link_mode());
                println!("cargo:rustc-link-search={dir}");
            }
            return HeaderLocation::FromEnvironment;
        }

        if let Some(header) = try_vcpkg() {
            return header;
        }

        // See if pkg-config can do everything for us.
        if let Ok(mut lib) = pkg_config::Config::new()
            .atleast_version("3.34.1")
            .print_system_libs(false)
            .probe(link_lib)
        {
            if let Some(header) = lib.include_paths.pop() {
                HeaderLocation::FromPath(header.to_string_lossy().into())
            } else {
                HeaderLocation::Wrapper
            }
        } else {
            // No env var set and pkg-config couldn't help; just output the link-lib
            // request and hope that the library exists on the system paths. We used to
            // output /usr/lib explicitly, but that can introduce other linking problems;
            // see https://github.com/rusqlite/rusqlite/issues/207.
            #[cfg(not(feature = "loadable_extension"))]
            println!("cargo:rustc-link-lib={}={link_lib}", find_link_mode());
            HeaderLocation::Wrapper
        }
    }

    fn try_vcpkg() -> Option<HeaderLocation> {
        if cfg!(feature = "vcpkg") && is_compiler("msvc") {
            // See if vcpkg can find it.
            if let Ok(mut lib) = vcpkg::Config::new().probe(lib_name()) {
                if let Some(header) = lib.include_paths.pop() {
                    return Some(HeaderLocation::FromPath(header.to_string_lossy().into()));
                }
            }
            None
        } else {
            None
        }
    }
}

#[cfg(not(feature = "buildtime_bindgen"))]
#[allow(dead_code)]
mod bindings {
    use super::HeaderLocation;

    use std::path::Path;

    static PREBUILT_BINDGENS: &[&str] = &["bindgen_3.34.1"];

    pub fn write_to_out_dir(_header: HeaderLocation, out_path: &Path) {
        let name = PREBUILT_BINDGENS[PREBUILT_BINDGENS.len() - 1];
        super::copy_bindings("bindgen-bindings", name, out_path);
    }
}

#[cfg(feature = "buildtime_bindgen")]
mod bindings {
    use super::HeaderLocation;
    use bindgen::callbacks::{IntKind, ParseCallbacks};

    use std::path::Path;
    #[derive(Debug)]
    struct SqliteTypeChooser;

    impl ParseCallbacks for SqliteTypeChooser {
        fn int_macro(&self, name: &str, _value: i64) -> Option<IntKind> {
            if name == "SQLITE_SERIALIZE_NOCOPY"
                || name.starts_with("SQLITE_DESERIALIZE_")
                || name.starts_with("SQLITE_PREPARE_")
                || name.starts_with("SQLITE_TRACE_")
            {
                Some(IntKind::UInt)
            } else {
                None
            }
        }
    }

    // Are we generating the bundled bindings? Used to avoid emitting things
    // that would be problematic in bundled builds. This env var is set by
    // `upgrade_git.sh`.
    fn generating_bundled_bindings() -> bool {
        // Hacky way to know if we're generating the bundled bindings
        println!("cargo:rerun-if-env-changed=LIBDOLTLITE_SYS_BUNDLING");
        println!("cargo:rerun-if-env-changed=LIBSQLITE3_SYS_BUNDLING");
        std::env::var("LIBDOLTLITE_SYS_BUNDLING")
            .or_else(|_| std::env::var("LIBSQLITE3_SYS_BUNDLING"))
            .is_ok_and(|v| v != "0")
    }

    pub fn write_to_out_dir(header: HeaderLocation, out_path: &Path) {
        let header: String = header.into();
        let mut bindings = bindgen::builder()
            .default_macro_constant_type(bindgen::MacroTypeVariation::Signed)
            .disable_nested_struct_naming()
            .generate_cstr(true)
            .use_core()
            .trust_clang_mangling(false)
            .header(header.clone())
            .parse_callbacks(Box::new(SqliteTypeChooser));
        if cfg!(feature = "loadable_extension") {
            bindings = bindings.ignore_functions(); // see generate_functions
        } else {
            bindings = bindings
                .blocklist_function("sqlite3_auto_extension")
                .raw_line(
                    r#"extern "C" {
    pub fn sqlite3_auto_extension(
        xEntryPoint: ::core::option::Option<
            unsafe extern "C" fn(
                db: *mut sqlite3,
                pzErrMsg: *mut *mut ::core::ffi::c_char,
                _: *const sqlite3_api_routines,
            ) -> ::core::ffi::c_int,
        >,
    ) -> ::core::ffi::c_int;
}"#,
                )
                .blocklist_function("sqlite3_cancel_auto_extension")
                .raw_line(
                    r#"extern "C" {
    pub fn sqlite3_cancel_auto_extension(
        xEntryPoint: ::core::option::Option<
            unsafe extern "C" fn(
                db: *mut sqlite3,
                pzErrMsg: *mut *mut ::core::ffi::c_char,
                _: *const sqlite3_api_routines,
            ) -> ::core::ffi::c_int,
        >,
    ) -> ::core::ffi::c_int;
}"#,
                )
                .blocklist_function(".*16.*")
                .blocklist_function("sqlite3_close_v2")
                .blocklist_function("sqlite3_create_collation")
                .blocklist_function("sqlite3_create_function")
                .blocklist_function("sqlite3_create_module")
                .blocklist_function("sqlite3_prepare");
        }

        if cfg!(feature = "unlock_notify") {
            bindings = bindings.clang_arg("-DSQLITE_ENABLE_UNLOCK_NOTIFY");
        }
        if cfg!(feature = "preupdate_hook") {
            bindings = bindings.clang_arg("-DSQLITE_ENABLE_PREUPDATE_HOOK");
        }
        if cfg!(feature = "session") {
            bindings = bindings.clang_arg("-DSQLITE_ENABLE_SESSION");
        }

        // When cross compiling unless effort is taken to fix the issue, bindgen
        // will find the wrong headers. There's only one header included by the
        // amalgamated `sqlite.h`: `stdarg.h`.
        //
        // Thankfully, there's almost no case where rust code needs to use
        // functions taking `va_list` (It's nearly impossible to get a `va_list`
        // in Rust unless you get passed it by C code for some reason).
        //
        // Arguably, we should never be including these, but we include them for
        // the cases where they aren't totally broken...
        let target_arch = std::env::var("TARGET").unwrap();
        let host_arch = std::env::var("HOST").unwrap();
        let is_cross_compiling = target_arch != host_arch;

        // Note that when generating the bundled file, we're essentially always
        // cross compiling.
        if generating_bundled_bindings() || is_cross_compiling {
            // Get rid of va_list, as it's not
            bindings = bindings
                .blocklist_function("sqlite3_vmprintf")
                .blocklist_function("sqlite3_vsnprintf")
                .blocklist_function("sqlite3_str_vappendf")
                .blocklist_type("va_list")
                .blocklist_item("__.*");
        }

        let bindings = bindings
            .layout_tests(false)
            .generate()
            .unwrap_or_else(|_| panic!("could not run bindgen on header {header}"));

        cfg_select! {
            feature = "loadable_extension" => {
                let mut output = Vec::new();
                bindings
                    .write(Box::new(&mut output))
                    .expect("could not write output of bindgen");
                let mut output = String::from_utf8(output).expect("bindgen output was not UTF-8?!");
                super::loadable_extension::generate_functions(&mut output);
                std::fs::write(out_path, output.as_bytes())
                    .unwrap_or_else(|_| panic!("Could not write to {out_path:?}"));
            }
            _ => bindings
                .write_to_file(out_path)
                .unwrap_or_else(|_| panic!("Could not write to {out_path:?}"))
        }
    }
}

#[cfg(all(feature = "buildtime_bindgen", feature = "loadable_extension"))]
mod loadable_extension {
    /// try to generate similar rust code for all `#define sqlite3_xyz
    /// sqlite3_api->abc` macros` in sqlite3ext.h
    pub fn generate_functions(output: &mut String) {
        // (1) parse sqlite3_api_routines fields from bindgen output
        let ast: syn::File = syn::parse_str(output).expect("could not parse bindgen output");
        let sqlite3_api_routines: syn::ItemStruct = ast
            .items
            .into_iter()
            .find_map(|i| {
                if let syn::Item::Struct(s) = i {
                    if s.ident == "sqlite3_api_routines" {
                        Some(s)
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
            .expect("could not find sqlite3_api_routines");
        let sqlite3_api_routines_ident = sqlite3_api_routines.ident;
        let p_api = quote::format_ident!("p_api");
        let mut stores = Vec::new();
        let mut malloc = Vec::new();
        // (2) `#define sqlite3_xyz sqlite3_api->abc` => `pub unsafe fn
        // sqlite3_xyz(args) -> ty {...}` for each `abc` field:
        for field in sqlite3_api_routines.fields {
            let ident = field.ident.expect("unnamed field");
            let span = ident.span();
            let name = ident.to_string();
            if name.contains("16") {
                continue; // skip UTF-16 api as rust uses UTF-8
            } else if name == "vmprintf" || name == "xvsnprintf" || name == "str_vappendf" {
                continue; // skip va_list
            } else if name == "aggregate_count"
                || name == "expired"
                || name == "global_recover"
                || name == "thread_cleanup"
                || name == "transfer_bindings"
                || name == "create_collation"
                || name == "create_function"
                || name == "create_module"
                || name == "prepare"
                || name == "close_v2"
            {
                continue; // omit deprecated
            }
            let sqlite3_name = match name.as_ref() {
                "xthreadsafe" => "sqlite3_threadsafe".to_owned(),
                "interruptx" => "sqlite3_interrupt".to_owned(),
                _ => {
                    format!("sqlite3_{name}")
                }
            };
            let ptr_name =
                syn::Ident::new(format!("__{}", sqlite3_name.to_uppercase()).as_ref(), span);
            let sqlite3_fn_name = syn::Ident::new(&sqlite3_name, span);
            let method =
                extract_method(&field.ty).unwrap_or_else(|| panic!("unexpected type for {name}"));
            let arg_names: syn::punctuated::Punctuated<&syn::Ident, syn::token::Comma> = method
                .inputs
                .iter()
                .map(|i| &i.name.as_ref().unwrap().0)
                .collect();
            let args = &method.inputs;
            // vtab_config/sqlite3_vtab_config: ok
            let varargs = &method.variadic;
            if varargs.is_some() && "db_config" != name && "log" != name && "vtab_config" != name {
                continue; // skip ...
            }
            let ty = &method.output;
            let tokens = if "db_config" == name {
                quote::quote! {
                    static #ptr_name: ::core::sync::atomic::AtomicPtr<()> = ::core::sync::atomic::AtomicPtr::new(::core::ptr::null_mut());
                    pub unsafe fn #sqlite3_fn_name(#args arg3: ::core::ffi::c_int, arg4: *mut ::core::ffi::c_int) #ty {
                        let ptr = #ptr_name.load(::core::sync::atomic::Ordering::Acquire);
                        assert!(!ptr.is_null(), "SQLite API not initialized");
                        let fun: unsafe extern "C" fn(#args #varargs) #ty = ::core::mem::transmute(ptr);
                        (fun)(#arg_names, arg3, arg4)
                    }
                }
            } else if "log" == name {
                quote::quote! {
                    static #ptr_name: ::core::sync::atomic::AtomicPtr<()> = ::core::sync::atomic::AtomicPtr::new(::core::ptr::null_mut());
                    pub unsafe fn #sqlite3_fn_name(#args arg3: *const ::core::ffi::c_char) #ty {
                        let ptr = #ptr_name.load(::core::sync::atomic::Ordering::Acquire);
                        assert!(!ptr.is_null(), "SQLite API not initialized");
                        let fun: unsafe extern "C" fn(#args #varargs) #ty = ::core::mem::transmute(ptr);
                        (fun)(#arg_names, arg3)
                    }
                }
            } else {
                quote::quote! {
                    static #ptr_name: ::core::sync::atomic::AtomicPtr<()> = ::core::sync::atomic::AtomicPtr::new(::core::ptr::null_mut());
                    pub unsafe fn #sqlite3_fn_name(#args) #ty {
                        let ptr = #ptr_name.load(::core::sync::atomic::Ordering::Acquire);
                        assert!(!ptr.is_null(), "SQLite API not initialized or SQLite feature omitted");
                        let fun: unsafe extern "C" fn(#args #varargs) #ty = ::core::mem::transmute(ptr);
                        (fun)(#arg_names)
                    }
                }
            };
            output.push_str(&prettyplease::unparse(
                &syn::parse2(tokens).expect("could not parse quote output"),
            ));
            output.push('\n');
            if name == "malloc" {
                &mut malloc
            } else {
                &mut stores
            }
            .push(quote::quote! {
                if let Some(fun) = (*#p_api).#ident {
                    #ptr_name.store(
                        fun as usize as *mut (),
                        ::core::sync::atomic::Ordering::Release,
                    );
                }
            });
        }
        // (3) generate rust code similar to SQLITE_EXTENSION_INIT2 macro
        let tokens = quote::quote! {
            /// Like SQLITE_EXTENSION_INIT2 macro
            pub unsafe fn rusqlite_extension_init2(#p_api: *mut #sqlite3_api_routines_ident) -> ::core::result::Result<(), crate::InitError> {
                #(#malloc)* // sqlite3_malloc needed by to_sqlite_error
                if let Some(fun) = (*#p_api).libversion_number {
                    let version = fun();
                    if SQLITE_VERSION_NUMBER > version {
                        return Err(crate::InitError::VersionMismatch{compile_time: SQLITE_VERSION_NUMBER, runtime: version});
                    }
                } else {
                    return Err(crate::InitError::NullFunctionPointer);
                }
                #(#stores)*
                Ok(())
            }
        };
        output.push_str(&prettyplease::unparse(
            &syn::parse2(tokens).expect("could not parse quote output"),
        ));
        output.push('\n');
    }

    fn extract_method(ty: &syn::Type) -> Option<&syn::TypeBareFn> {
        match ty {
            syn::Type::Path(tp) => tp.path.segments.last(),
            _ => None,
        }
        .map(|seg| match &seg.arguments {
            syn::PathArguments::AngleBracketed(args) => args.args.first(),
            _ => None,
        })?
        .map(|arg| match arg {
            syn::GenericArgument::Type(t) => Some(t),
            _ => None,
        })?
        .map(|ty| match ty {
            syn::Type::BareFn(r) => Some(r),
            _ => None,
        })?
    }
}