-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathbuild.rs
More file actions
2732 lines (2521 loc) · 112 KB
/
Copy pathbuild.rs
File metadata and controls
2732 lines (2521 loc) · 112 KB
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
use cmake::Config;
use glob::glob;
use patch_apply::{Line, Patch};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::{env, fs};
#[cfg(feature = "prebuilt")]
mod prebuilt_download;
macro_rules! debug_log {
($($arg:tt)*) => {
if std::env::var("BUILD_DEBUG").is_ok() {
println!("cargo:warning=[DEBUG] {}", format!($($arg)*));
}
};
}
fn get_cargo_target_dir() -> Result<std::path::PathBuf, Box<dyn std::error::Error>> {
let profile = std::env::var("PROFILE")?;
// Cargo includes the active target/profile directory in the build
// script's runtime-library search path. Prefer that authoritative path:
// with unstable `build.build-dir`, OUT_DIR intentionally lives somewhere
// else and cannot identify where Cargo will look for shared libraries
// while running tests and binaries.
let runtime_path_variables: &[&str] = if cfg!(target_os = "windows") {
&["PATH"]
} else if cfg!(target_os = "macos") {
&["DYLD_FALLBACK_LIBRARY_PATH", "DYLD_LIBRARY_PATH"]
} else {
&["LD_LIBRARY_PATH"]
};
for variable in runtime_path_variables {
let Some(paths) = std::env::var_os(variable) else {
continue;
};
for path in std::env::split_paths(&paths) {
if path
.file_name()
.is_some_and(|name| name == std::ffi::OsStr::new(&profile))
{
return Ok(path);
}
if path.file_name().is_some_and(|name| name == "deps") {
if let Some(parent) = path.parent() {
if parent
.file_name()
.is_some_and(|name| name == std::ffi::OsStr::new(&profile))
{
return Ok(parent.to_path_buf());
}
}
}
}
}
let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?);
let mut target_dir = None;
let mut sub_path = out_dir.as_path();
while let Some(parent) = sub_path.parent() {
if parent.ends_with(&profile) {
target_dir = Some(parent);
break;
}
sub_path = parent;
}
let target_dir = target_dir.ok_or("not found")?;
Ok(target_dir.to_path_buf())
}
/// Compute a short hash over the contents of all `*.patch` files in `patches_dir`.
/// Returns an empty string when the directory does not exist or contains no patches.
fn patches_hash(patches_dir: &Path) -> String {
if !patches_dir.is_dir() {
return String::new();
}
let mut entries: Vec<_> = std::fs::read_dir(patches_dir)
.map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.path()).collect())
.unwrap_or_default();
entries.sort();
let mut hasher_val: u64 = 0xcbf29ce484222325; // FNV-1a offset basis
for path in &entries {
if path.extension().map(|e| e == "patch").unwrap_or(false) {
if let Ok(bytes) = std::fs::read(path) {
for &b in &bytes {
hasher_val ^= b as u64;
hasher_val = hasher_val.wrapping_mul(0x100000001b3);
}
}
}
}
format!("{:016x}", hasher_val)
}
/// Resolve the patch binary.
///
/// Search order:
/// 1. Explicit env override (`LLAMA_PATCH`, then `PATCH`).
/// 2. `patch` already available on PATH.
/// 3. Windows-only fallback probes for Git-for-Windows installations,
/// including deriving `..\\usr\\bin\\patch.exe` from `where git`.
fn resolve_patch_cmd() -> PathBuf {
// 1) Explicit override for fully custom installations.
for var in ["LLAMA_PATCH", "PATCH"] {
if let Ok(raw) = env::var(var) {
let trimmed = raw.trim();
if !trimmed.is_empty() {
let candidate = PathBuf::from(trimmed.trim_matches('"'));
if candidate.exists() {
println!(
"cargo:warning=Using patch binary from {var}: {}",
candidate.display()
);
return candidate;
}
println!(
"cargo:warning={var} was set to '{}' but that path does not exist",
candidate.display()
);
}
}
}
// 2) Already on PATH.
if command_exists("patch") {
return PathBuf::from("patch");
}
// 3) Windows fallback search.
if cfg!(windows) {
let mut candidates: Vec<PathBuf> = Vec::new();
let mut push_unique = |p: PathBuf| {
if !candidates.iter().any(|c| c == &p) {
candidates.push(p);
}
};
// If git is on PATH (typically from Git\\cmd), infer sibling
// Git\\usr\\bin\\patch.exe from each discovered git.exe.
if let Ok(output) = Command::new("where").arg("git").output() {
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
for line in stdout.lines() {
let git = PathBuf::from(line.trim());
if let Some(git_dir) = git.parent() {
if let Some(git_root) = git_dir.parent() {
push_unique(git_root.join("usr").join("bin").join("patch.exe"));
}
}
}
}
}
if let Some(program_files) = env::var_os("ProgramFiles") {
push_unique(PathBuf::from(&program_files).join("Git\\usr\\bin\\patch.exe"));
}
if let Some(program_files_x86) = env::var_os("ProgramFiles(x86)") {
push_unique(PathBuf::from(&program_files_x86).join("Git\\usr\\bin\\patch.exe"));
}
if let Some(local_app_data) = env::var_os("LOCALAPPDATA") {
push_unique(PathBuf::from(&local_app_data).join("Programs\\Git\\usr\\bin\\patch.exe"));
}
push_unique(PathBuf::from("C:\\Program Files\\Git\\usr\\bin\\patch.exe"));
if let Some(found) = candidates.iter().find(|p| p.exists()).cloned() {
println!("cargo:warning=Using patch binary at {}", found.display());
return found;
}
let searched = candidates
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ");
panic!(
"could not locate `patch.exe` on PATH or common Git-for-Windows locations. \
Set LLAMA_PATCH (or PATCH) to the full path to patch.exe, or add Git\\usr\\bin to PATH. \
Searched: [{searched}]"
);
}
panic!(
"could not locate `patch` on PATH. Install patch, or set LLAMA_PATCH (or PATCH) to the full path to the patch binary"
)
}
fn find_sequence(lines: &[&str], pattern: &[&str], start_at: usize) -> Option<usize> {
if pattern.is_empty() {
return Some(start_at.min(lines.len()));
}
if pattern.len() > lines.len() {
return None;
}
(start_at..=lines.len() - pattern.len()).find(|&i| lines[i..i + pattern.len()] == *pattern)
}
fn hunk_side_pattern<'a>(hunk: &'a patch_apply::Hunk<'a>, new_side: bool) -> Vec<&'a str> {
let mut out = Vec::new();
for line in &hunk.lines {
match line {
Line::Context(s) => out.push(*s),
Line::Remove(s) if !new_side => out.push(*s),
Line::Add(s) if new_side => out.push(*s),
_ => {}
}
}
out
}
fn patch_matches_side(lines: &[&str], patch: &Patch<'_>, new_side: bool) -> bool {
let mut cursor = 0usize;
for hunk in &patch.hunks {
let pattern = hunk_side_pattern(hunk, new_side);
let Some(pos) = find_sequence(lines, &pattern, cursor) else {
return false;
};
let consumed = if new_side {
hunk.new_range.count as usize
} else {
hunk.old_range.count as usize
};
cursor = pos.saturating_add(consumed);
}
true
}
fn reanchor_patch_to_old_side(lines: &[&str], patch: &mut Patch<'_>) -> bool {
let mut cursor = 0usize;
for hunk in &mut patch.hunks {
let pattern = hunk_side_pattern(hunk, false);
let Some(pos) = find_sequence(lines, &pattern, cursor) else {
return false;
};
hunk.old_range.start = pos as u64 + 1;
cursor = pos.saturating_add(hunk.old_range.count as usize);
}
true
}
fn strip_patch_path(path: &str, strip_components: usize) -> Option<PathBuf> {
let parts: Vec<&str> = path.split('/').collect();
if parts.len() <= strip_components {
return None;
}
let rel = PathBuf::from(parts[strip_components..].join("/"));
if rel.is_absolute() {
return None;
}
if rel.components().any(|c| {
matches!(
c,
std::path::Component::ParentDir
| std::path::Component::RootDir
| std::path::Component::Prefix(_)
)
}) {
return None;
}
Some(rel)
}
fn patch_target_path(dst: &Path, patch: &Patch<'_>) -> Result<PathBuf, String> {
let raw = if patch.new.path.as_ref() != "/dev/null" {
patch.new.path.as_ref()
} else {
patch.old.path.as_ref()
};
let rel = strip_patch_path(raw, 1)
.ok_or_else(|| format!("unsupported patch path after -p1 stripping: '{raw}'"))?;
Ok(dst.join(rel))
}
fn patch_entries(patches_dir: &Path) -> Vec<PathBuf> {
if !patches_dir.is_dir() {
return Vec::new();
}
let mut entries: Vec<_> = std::fs::read_dir(patches_dir)
.expect("failed to read patches dir")
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| {
path.extension()
.is_some_and(|extension| extension == "patch")
})
.collect();
entries.sort();
entries
}
fn patches_match_new_side(patches_dir: &Path, dst: &Path) -> Result<bool, String> {
for patch_path in patch_entries(patches_dir) {
let patch_text = fs::read_to_string(&patch_path)
.map_err(|error| format!("failed to read patch {}: {error}", patch_path.display()))?;
let patches = Patch::from_multiple(&patch_text)
.map_err(|error| format!("failed to parse patch {}: {error}", patch_path.display()))?;
for patch in patches {
let file_path = patch_target_path(dst, &patch)?;
let creates_file = patch.old.path.as_ref() == "/dev/null";
let deletes_file = patch.new.path.as_ref() == "/dev/null";
let current = match fs::read_to_string(&file_path) {
Ok(contents) => contents,
Err(error) if error.kind() == std::io::ErrorKind::NotFound && deletes_file => {
continue;
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound && creates_file => {
return Ok(false);
}
Err(error) => {
return Err(format!(
"failed to read patched target {}: {error}",
file_path.display()
));
}
};
let current_lines: Vec<&str> = current.lines().collect();
if !patch_matches_side(¤t_lines, &patch, true) {
return Ok(false);
}
}
}
Ok(true)
}
fn apply_patches_via_rust(entries: &[PathBuf], dst: &Path) -> Result<(), String> {
for patch_path in entries {
println!(
"cargo:warning=Applying patch (rust): {}",
patch_path.display()
);
let patch_text = fs::read_to_string(patch_path)
.map_err(|e| format!("failed to read patch {}: {e}", patch_path.display()))?;
let patches = Patch::from_multiple(&patch_text)
.map_err(|e| format!("failed to parse patch {}: {e}", patch_path.display()))?;
for patch in patches {
let file_path = patch_target_path(dst, &patch)?;
let creates_file = patch.old.path.as_ref() == "/dev/null";
let deletes_file = patch.new.path.as_ref() == "/dev/null";
let current = match fs::read_to_string(&file_path) {
Ok(s) => s,
Err(_e) if creates_file => String::new(),
Err(e) => {
return Err(format!(
"failed to read target file {}: {e}",
file_path.display()
));
}
};
let current_lines: Vec<&str> = current.lines().collect();
if patch_matches_side(¤t_lines, &patch, true) {
println!(
"cargo:warning=Patch already applied (rust): {}",
file_path.display()
);
continue;
}
let mut anchored_patch = patch.clone();
if reanchor_patch_to_old_side(¤t_lines, &mut anchored_patch) {
let updated = patch_apply::apply(current.clone(), anchored_patch);
if updated != current {
if deletes_file {
if let Err(e) = fs::remove_file(&file_path) {
return Err(format!(
"failed to delete patched file {}: {e}",
file_path.display()
));
}
} else {
if let Some(parent) = file_path.parent() {
fs::create_dir_all(parent).map_err(|e| {
format!(
"failed to create parent dir for {}: {e}",
file_path.display()
)
})?;
}
fs::write(&file_path, updated).map_err(|e| {
format!("failed to write patched file {}: {e}", file_path.display())
})?;
}
}
continue;
}
return Err(format!(
"patch hunk mismatch for {} while applying {}",
file_path.display(),
patch_path.display()
));
}
}
Ok(())
}
fn apply_patches_via_cli(entries: &[PathBuf], dst: &Path) -> Result<(), String> {
let patch_cmd = resolve_patch_cmd();
for patch in entries {
println!("cargo:warning=Applying patch (cli): {}", patch.display());
let status = Command::new(&patch_cmd)
.arg("-p1")
.arg("--forward")
.arg("--directory")
.arg(dst)
.arg("--input")
.arg(patch)
.status()
.map_err(|e| {
format!(
"failed to run '{}' for {}: {e}",
patch_cmd.display(),
patch.display()
)
})?;
if !status.success() {
return Err(format!(
"patch command failed for {} with status {}",
patch.display(),
status
));
}
}
Ok(())
}
/// Apply all `*.patch` files in `patches_dir` (sorted alphabetically) to `dst`.
/// Uses the `patch -p1` command.
/// Skips the patches directory entirely when it does not exist or is empty.
fn apply_patches(patches_dir: &Path, dst: &Path) {
let entries = patch_entries(patches_dir);
if entries.is_empty() {
return;
}
let engine = env::var("LLAMA_PATCH_ENGINE")
.map(|v| v.to_ascii_lowercase())
.unwrap_or_else(|_| "rust".to_string());
let res = match engine.as_str() {
"cli" => apply_patches_via_cli(&entries, dst),
"rust" => apply_patches_via_rust(&entries, dst),
other => Err(format!(
"unsupported LLAMA_PATCH_ENGINE='{other}', expected 'rust' or 'cli'"
)),
};
if let Err(err) = res {
panic!(
"Patch application failed using engine '{engine}': {err}. \
The patch may need rebasing against the current llama.cpp submodule commit."
);
}
}
fn stage_active_patches(patches_dir: &Path, staged_dir: &Path) -> bool {
if staged_dir.exists() {
std::fs::remove_dir_all(staged_dir).expect("failed to clear staged llama.cpp patches");
}
std::fs::create_dir_all(staged_dir).expect("failed to create staged llama.cpp patches");
let always_active = [
"0003-exact-speculative-state.patch",
"0004-exact-decode-lifecycle-hooks.patch",
"0005-fail-closed-eagle3-process.patch",
];
for name in always_active {
let source = patches_dir.join(name);
assert!(
source.is_file(),
"required llama.cpp patch is absent: {}",
source.display()
);
std::fs::copy(&source, staged_dir.join(name))
.unwrap_or_else(|error| panic!("failed to stage {name}: {error}"));
}
if cfg!(feature = "q1") {
let name = "0001-q1-quantization.patch";
let source = patches_dir.join(name);
if source.exists() {
std::fs::copy(&source, staged_dir.join(name))
.unwrap_or_else(|error| panic!("failed to stage {name}: {error}"));
}
}
// DFlash2 speculative decoding, vendored from the (still unmerged) upstream
// PR #27342. Opt-in because it is a pre-merge feature carrying new GGUF KV
// keys and tensors: with it applied the build recognises DFlash2 checkpoints
// that stock llama.cpp releases do not. Staged last so it lands on top of
// the exact-state patches, which also touch common/speculative.cpp.
if cfg!(feature = "dflash2") {
let name = "0006-dflash2.patch";
let source = patches_dir.join(name);
assert!(
source.is_file(),
"the `dflash2` feature is enabled but its patch is absent: {}",
source.display()
);
std::fs::copy(&source, staged_dir.join(name))
.unwrap_or_else(|error| panic!("failed to stage {name}: {error}"));
}
true
}
/// Return a string that uniquely identifies the current state of the llama.cpp
/// submodule so we know when a re-copy is needed.
///
/// Priority:
/// 1. The commit hash from the submodule's git HEAD (most precise).
/// 2. The mtime of `CMakeLists.txt` (fallback for non-git trees).
fn llama_src_version(src: &Path, patches_dir: &Path) -> String {
const PATCH_STAGING_VERSION: &str = "2";
let ph = patches_hash(patches_dir);
// In a git submodule the `.git` entry is a *file* whose content is:
// gitdir: ../../.git/modules/llama-cpp-sys-4/llama.cpp
let git_file = src.join(".git");
if git_file.is_file() {
if let Ok(text) = std::fs::read_to_string(&git_file) {
if let Some(rel) = text.strip_prefix("gitdir:").map(str::trim) {
let head_path = git_file.parent().unwrap().join(rel).join("HEAD");
if let Ok(head) = std::fs::read_to_string(&head_path) {
// HEAD is either a commit hash or "ref: refs/heads/…"
let head = head.trim();
if head.starts_with("ref:") {
// Resolve the ref to the actual commit hash.
let ref_path = head.strip_prefix("ref:").map(str::trim).unwrap_or(head);
let commit_path = git_file.parent().unwrap().join(rel).join(ref_path);
if let Ok(hash) = std::fs::read_to_string(commit_path) {
return format!("{}:{}:{PATCH_STAGING_VERSION}", hash.trim(), ph);
}
}
return format!("{}:{}:{PATCH_STAGING_VERSION}", head, ph);
}
}
}
}
// Fallback: modification time of the top-level CMakeLists.txt.
let base = src
.join("CMakeLists.txt")
.metadata()
.and_then(|m| m.modified())
.map(|t| format!("{t:?}"))
.unwrap_or_else(|_| "unknown".to_owned());
// Mix in patch contents so that updating patches forces a re-copy+re-patch.
format!(
"{}:{}:{PATCH_STAGING_VERSION}",
base,
patches_hash(patches_dir)
)
}
/// Copy a directory tree. This runs on the *host*, so cfg!(unix/windows) is correct here.
/// Always perform a real copy. Using hardlinks is unsafe here because
/// build-time patch application mutates files in the copied tree.
fn copy_folder(src: &Path, dst: &Path) {
std::fs::create_dir_all(dst).expect("Failed to create dst directory");
if cfg!(unix) {
std::process::Command::new("cp")
.arg("-rf")
.arg(src)
.arg(dst.parent().unwrap())
.status()
.expect("Failed to execute cp command");
} else if cfg!(windows) {
std::process::Command::new("robocopy.exe")
.arg("/e")
.arg(src)
.arg(dst)
.status()
.expect("Failed to execute robocopy command");
}
}
/// Extract library names from the build output directory.
///
/// `target` is the Rust target triple of the *cross-compilation target* so
/// that the correct file extensions are chosen even when cross-compiling.
fn extract_lib_names(out_dir: &Path, build_shared_libs: bool, target: &str) -> Vec<String> {
// MSVC produces `.lib` for both static archives and import libraries.
// MinGW/GCC (windows-gnu / windows-gnullvm) produces `.a` for static
// archives and `.dll.a` for import libraries — both end in `.a`, so the
// single pattern covers both cases.
let lib_pattern = if target.contains("windows-msvc") {
"*.lib"
} else if target.contains("windows") {
// MinGW / GCC-based Windows toolchain (cross or native).
// Static libs: libfoo.a | Shared import libs: libfoo.dll.a
"*.a"
} else if target.contains("apple") {
if build_shared_libs {
"*.dylib"
} else {
"*.a"
}
} else if build_shared_libs {
"*.so"
} else {
"*.a"
};
let libs_dir = out_dir.join("lib*");
let pattern = libs_dir.join(lib_pattern);
debug_log!("Extract libs {}", pattern.display());
let mut lib_names: Vec<String> = Vec::new();
// Process the libraries based on the pattern
for entry in glob(pattern.to_str().unwrap()).unwrap() {
match entry {
Ok(path) => {
let stem = path.file_stem().unwrap();
let stem_str = stem.to_str().unwrap();
// For MinGW import libraries the file is named `libfoo.dll.a`.
// `file_stem()` strips the final `.a` extension, leaving
// `libfoo.dll`. We additionally need to strip the trailing
// `.dll` so that the link name becomes `foo` rather than
// `foo.dll`.
let stem_str = if target.contains("windows")
&& !target.contains("msvc")
&& stem_str.ends_with(".dll")
{
&stem_str[..stem_str.len() - 4]
} else {
stem_str
};
// Remove the "lib" prefix if present (Unix/MinGW convention).
let lib_name = if stem_str.starts_with("lib") {
stem_str.strip_prefix("lib").unwrap_or(stem_str)
} else {
stem_str
};
lib_names.push(lib_name.to_string());
}
Err(e) => println!("cargo:warning=error={}", e),
}
}
lib_names
}
/// Make the built shared libraries loadable from the directory they sit in.
///
/// CMake stamps every dylib with an `@rpath/…` install name, and rustc records
/// that name in whatever links against it. Cargo never adds an `LC_RPATH` to the
/// binaries it builds, so a *directly executed* binary dies with:
///
/// ```text
/// dyld: Library not loaded: @rpath/libggml-base.0.dylib
/// Reason: no LC_RPATH's found
/// ```
///
/// This is easy to miss because `cargo run` / `cargo test` set
/// `DYLD_FALLBACK_LIBRARY_PATH` to the target directory, so the failure only
/// shows up once someone runs the binary themselves.
///
/// Rewriting the install names (and the inter-library references) to
/// `@loader_path/…` removes the need for an rpath at all: dyld resolves them
/// relative to whichever binary or dylib did the loading, and the copy step
/// below places every dylib next to the binaries.
///
/// Only meaningful on Apple targets. Windows resolves DLLs next to the `.exe`
/// already; ELF needs `-Wl,-rpath,$ORIGIN` on the final executable, which a
/// dependency's build script cannot inject — see `.cargo/config.toml`.
fn make_shared_libs_loader_relative(lib_dirs: &[PathBuf], target: &str) {
if !target.contains("apple") {
return;
}
for dir in lib_dirs {
let Ok(entries) = std::fs::read_dir(dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
// Skip the symlinks in the versioned chain; retargeting the real
// file is enough, and install_name_tool cannot rewrite a symlink.
if !path.is_file() || path.symlink_metadata().is_ok_and(|m| m.is_symlink()) {
continue;
}
if path.extension().is_none_or(|e| e != "dylib") {
continue;
}
let Some(filename) = path.file_name().and_then(|f| f.to_str()) else {
continue;
};
// 1. The library's own identity, which is what dependents record.
run_install_name_tool(&["-id", &format!("@loader_path/{filename}")], &path);
// 2. Its references to sibling libraries.
for dep in otool_rpath_dependencies(&path) {
let Some(base) = dep.strip_prefix("@rpath/") else {
continue;
};
run_install_name_tool(&["-change", &dep, &format!("@loader_path/{base}")], &path);
}
}
}
}
/// `@rpath/…` entries this Mach-O file depends on.
fn otool_rpath_dependencies(path: &Path) -> Vec<String> {
let Ok(output) = std::process::Command::new("otool")
.arg("-L")
.arg(path)
.output()
else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
String::from_utf8_lossy(&output.stdout)
.lines()
.skip(1) // first line is the file being inspected
.filter_map(|line| line.split_whitespace().next())
.filter(|dep| dep.starts_with("@rpath/"))
.map(ToOwned::to_owned)
.collect()
}
fn run_install_name_tool(args: &[&str], path: &Path) {
match std::process::Command::new("install_name_tool")
.args(args)
.arg(path)
.output()
{
Ok(output) if output.status.success() => {}
Ok(output) => {
// Non-fatal: a library that was already rewritten by an earlier
// build reports "no such dependency", and the build still links.
debug_log!(
"install_name_tool {:?} on {} failed: {}",
args,
path.display(),
String::from_utf8_lossy(&output.stderr).trim()
);
}
Err(error) => {
println!(
"cargo:warning=install_name_tool not runnable ({error}); \
directly executed binaries may fail to find the llama.cpp dylibs"
);
}
}
}
/// Extract shared-library asset paths from the build output directory.
///
/// `target` is the Rust target triple of the *cross-compilation target*.
fn extract_lib_assets(out_dir: &Path, target: &str) -> Vec<PathBuf> {
let shared_lib_pattern = if target.contains("windows") {
"*.dll"
} else if target.contains("apple") {
"*.dylib"
} else {
// Match versioned sonames too (e.g. `libggml-base.so.0`), not just the
// bare `.so` developer symlink. At runtime the dynamic loader requests
// the SONAME (`libggml-base.so.0`), so that file — not just
// `libggml-base.so` — must be placed next to the test/example
// binaries. Globbing only `*.so` copies the symlink but misses the
// versioned target, causing `cargo test` to fail at load time with
// "libggml-base.so.0: cannot open shared object file".
"*.so*"
};
let shared_libs_dir = if target.contains("windows") {
"bin"
} else {
"lib"
};
let libs_dir = out_dir.join(shared_libs_dir);
let pattern = libs_dir.join(shared_lib_pattern);
debug_log!("Extract lib assets {}", pattern.display());
let mut files = Vec::new();
for entry in glob(pattern.to_str().unwrap()).unwrap() {
match entry {
Ok(path) => {
files.push(path);
}
Err(e) => eprintln!("cargo:warning=error={}", e),
}
}
files
}
fn extract_prebuilt_lib_names(
prebuilt_root: &Path,
use_shared_libs: bool,
target: &str,
) -> Vec<String> {
let lib_pattern = if target.contains("windows-msvc") {
"*.lib"
} else if target.contains("windows") {
"*.a"
} else if target.contains("apple") {
if use_shared_libs {
"*.dylib"
} else {
"*.a"
}
} else if use_shared_libs {
"*.so"
} else {
"*.a"
};
let mut lib_names = Vec::new();
for dir in [
prebuilt_root.to_path_buf(),
prebuilt_root.join("lib"),
prebuilt_root.join("lib64"),
prebuilt_root.join("bin"),
] {
if !dir.exists() {
continue;
}
let pattern = dir.join(lib_pattern);
let pattern_s = match pattern.to_str() {
Some(v) => v,
None => continue,
};
for entry in glob(pattern_s).unwrap() {
match entry {
Ok(path) => {
let stem = match path.file_stem().and_then(|s| s.to_str()) {
Some(v) => v,
None => continue,
};
let stem = if target.contains("windows")
&& !target.contains("msvc")
&& stem.ends_with(".dll")
{
&stem[..stem.len() - 4]
} else {
stem
};
let lib_name = if let Some(stripped) = stem.strip_prefix("lib") {
stripped
} else {
stem
};
if !lib_names.iter().any(|n| n == lib_name) {
lib_names.push(lib_name.to_string());
}
}
Err(e) => eprintln!("cargo:warning=error={}", e),
}
}
}
lib_names
}
fn extract_prebuilt_shared_assets(prebuilt_root: &Path, target: &str) -> Vec<PathBuf> {
let shared_pattern = if target.contains("windows") {
"*.dll"
} else if target.contains("apple") {
"*.dylib"
} else {
// Include versioned sonames (e.g. `libggml-base.so.0`) — the runtime
// loader requests the SONAME, not the bare `.so` symlink. See the note
// in `extract_lib_assets`.
"*.so*"
};
let mut files = Vec::new();
for dir in [
prebuilt_root.to_path_buf(),
prebuilt_root.join("lib"),
prebuilt_root.join("lib64"),
prebuilt_root.join("bin"),
] {
if !dir.exists() {
continue;
}
let pattern = dir.join(shared_pattern);
let pattern_s = match pattern.to_str() {
Some(v) => v,
None => continue,
};
for entry in glob(pattern_s).unwrap() {
match entry {
Ok(path) => {
if !files.iter().any(|p| p == &path) {
files.push(path);
}
}
Err(e) => eprintln!("cargo:warning=error={}", e),
}
}
}
files
}
/// Ask a clang binary for its library search path (macOS link helper).
///
/// `clang_binary` should be the bare name or full path of the clang binary to
/// query — e.g. `"clang"` for native builds or `"aarch64-apple-darwin-clang"`
/// for a cross-compiler.
fn macos_link_search_path(clang_binary: &str) -> Option<String> {
let output = Command::new(clang_binary)
.arg("--print-search-dirs")
.output()
.ok()?;
if !output.status.success() {
println!(
"failed to run '{clang_binary} --print-search-dirs', continuing without a link search path"
);
return None;
}
let stdout = String::from_utf8_lossy(&output.stdout);
for line in stdout.lines() {
if line.contains("libraries: =") {
let path = line.split('=').nth(1)?;
return Some(format!("{}/lib/darwin", path));
}
}
println!("failed to determine link search path, continuing without it");
None
}
/// Map a Rust target triple to the CMake `CMAKE_SYSTEM_NAME` value.
fn cmake_system_name(target: &str) -> &'static str {
if target.contains("-android") || target.contains("android-") {
"Android"
} else if target.contains("-apple-ios") {
"iOS"
} else if target.contains("-apple-") {
"Darwin"
} else if target.contains("-windows") {
"Windows"
} else if target.contains("-linux") {
"Linux"
} else {
// Generic UNIX-like fallback
"Linux"
}
}
/// Derive a MinGW cross-compiler binary name from a Rust `windows-gnu` target triple.
///
/// Rust uses `x86_64-pc-windows-gnu` / `x86_64-pc-windows-gnullvm` while the
/// MinGW toolchain conventionally uses `x86_64-w64-mingw32`. The `gnullvm`
/// variant uses Clang instead of GCC.
///
/// Returns `None` for `windows-msvc` targets — MSVC cannot cross-compile from
/// a non-Windows host and users must supply `CC`/`CXX` themselves.
fn mingw_compiler(target: &str, cxx: bool) -> Option<String> {
if !target.contains("windows-gnu") {
return None;
}
let arch = if target.contains("x86_64") {
"x86_64"
} else if target.contains("i686") || target.contains("i586") {
"i686"
} else if target.contains("aarch64") {
"aarch64"
} else {
target.split('-').next()?
};
// `gnullvm` targets use LLVM/Clang; plain `gnu` targets use GCC.
let compiler = if target.contains("gnullvm") {
if cxx {
"clang++"
} else {
"clang"
}
} else {
if cxx {
"g++"
} else {
"gcc"
}
};
Some(format!("{}-w64-mingw32-{}", arch, compiler))
}
fn command_exists(cmd: &str) -> bool {
Command::new(cmd)
.arg("--version")
.output()