llama-cpp-bindings-build 0.33.0

Build scripts of llama-cpp-native, which builds llama.cpp with CMake, and llama-cpp-bindings-sys, which generates the bindings and compiles the C++ wrapper
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
use std::env::VarError;
use std::fs;
use std::fs::DirEntry;
use std::io;
use std::path::Path;
use std::path::PathBuf;

use crate::android_architecture::AndroidArchitecture;
use crate::build_environment::BuildEnvironment;
use crate::build_error::BuildError;
use crate::host_os::HostOs;

const DEFAULT_ANDROID_API_LEVEL: &str = "28";

fn detect_ndk_path(
    environment: &BuildEnvironment,
    target_triple: &str,
) -> Result<String, BuildError> {
    environment
        .var("ANDROID_NDK_HOME")
        .map_err(|source| BuildError::AndroidNdkRootNotConfigured {
            target_triple: target_triple.to_owned(),
            source,
        })
}

fn validate_ndk_installation(ndk_path: &str) -> Result<(), BuildError> {
    let ndk_path = Path::new(ndk_path);

    if !ndk_path.exists() {
        return Err(BuildError::AndroidNdkRootMissing {
            path: ndk_path.to_path_buf(),
        });
    }

    let toolchain_file = ndk_path.join("build/cmake/android.toolchain.cmake");

    if !toolchain_file.exists() {
        return Err(BuildError::AndroidNdkToolchainFileMissing {
            path: toolchain_file,
        });
    }

    Ok(())
}

fn detect_api_level(environment: &BuildEnvironment) -> Result<String, BuildError> {
    match environment.var("ANDROID_PLATFORM") {
        Ok(platform) => Ok(platform
            .strip_prefix("android-")
            .unwrap_or(&platform)
            .to_owned()),
        Err(VarError::NotPresent) => Ok(DEFAULT_ANDROID_API_LEVEL.to_owned()),
        Err(source) => Err(BuildError::AndroidPlatformUnreadable { source }),
    }
}

/// The NDK toolchain keeps the built-in headers of its clang in the single version directory
/// under `lib/clang`.
fn find_clang_builtin_includes(toolchain_path: &str) -> Result<String, BuildError> {
    let clang_lib_path = PathBuf::from(toolchain_path).join("lib/clang");
    let mut version_dirs = fs::read_dir(&clang_lib_path)
        .and_then(Iterator::collect::<Result<Vec<DirEntry>, io::Error>>)
        .map_err(|source| BuildError::AndroidNdkClangDirectoryUnreadable {
            path: clang_lib_path.clone(),
            source,
        })?
        .into_iter()
        .map(|entry| entry.path())
        .filter(|path| path.is_dir())
        .collect::<Vec<PathBuf>>();

    version_dirs.sort();

    let [version_dir] = <[PathBuf; 1]>::try_from(version_dirs).map_err(|candidates| {
        if candidates.is_empty() {
            BuildError::AndroidNdkClangVersionDirectoryMissing {
                path: clang_lib_path.clone(),
            }
        } else {
            BuildError::AndroidNdkClangVersionDirectoryAmbiguous {
                path: clang_lib_path.clone(),
                candidates,
            }
        }
    })?;
    let include_path = version_dir.join("include");

    if !include_path.is_dir() {
        return Err(BuildError::AndroidNdkClangBuiltinIncludesMissing { path: include_path });
    }

    Ok(include_path.to_string_lossy().into_owned())
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AndroidNdk {
    pub ndk_path: String,
    pub api_level: String,
    pub abi: &'static str,
    pub sysroot: String,
    pub target_prefix: &'static str,
    pub clang_builtin_includes: String,
}

impl AndroidNdk {
    /// # Errors
    ///
    /// Returns the [`BuildError`] describing why the NDK installation cannot be located, an
    /// environment variable is missing or malformed, the target architecture is unsupported, or
    /// the host platform is not supported by the NDK.
    pub fn detect(
        environment: &BuildEnvironment,
        target_triple: &str,
        cargo_cfg_target_arch: &str,
        host_os: HostOs,
    ) -> Result<Self, BuildError> {
        let ndk_path = detect_ndk_path(environment, target_triple)?;

        validate_ndk_installation(&ndk_path)?;

        let architecture = AndroidArchitecture::from_cargo_cfg(cargo_cfg_target_arch)?;
        let api_level = detect_api_level(environment)?;
        let host_tag = host_os.android_ndk_tag()?;
        let toolchain_path = format!("{ndk_path}/toolchains/llvm/prebuilt/{host_tag}");

        if !Path::new(&toolchain_path).exists() {
            return Err(BuildError::AndroidNdkToolchainDirectoryMissing {
                path: PathBuf::from(toolchain_path),
            });
        }

        let clang_builtin_includes = find_clang_builtin_includes(&toolchain_path)?;

        Ok(Self {
            ndk_path,
            api_level,
            abi: architecture.abi(),
            sysroot: format!("{toolchain_path}/sysroot"),
            target_prefix: architecture.ndk_prefix(),
            clang_builtin_includes,
        })
    }

    #[must_use]
    pub fn android_platform(&self) -> String {
        format!("android-{}", self.api_level)
    }

    /// The clang arguments that parse headers the way the NDK compiles them for `target_triple`.
    #[must_use]
    pub fn clang_args(&self, target_triple: &str) -> Vec<String> {
        vec![
            format!("--sysroot={}", self.sysroot),
            format!("-D__ANDROID_API__={}", self.api_level),
            "-D__ANDROID__".to_owned(),
            "-isystem".to_owned(),
            self.clang_builtin_includes.clone(),
            "-isystem".to_owned(),
            format!("{}/usr/include/{}", self.sysroot, self.target_prefix),
            "-isystem".to_owned(),
            format!("{}/usr/include", self.sysroot),
            "-include".to_owned(),
            "stdbool.h".to_owned(),
            "-include".to_owned(),
            "stdint.h".to_owned(),
            format!("--target={target_triple}"),
        ]
    }

    #[must_use]
    pub fn cmake_toolchain_file(&self) -> String {
        format!("{}/build/cmake/android.toolchain.cmake", self.ndk_path)
    }
}

#[cfg(test)]
pub mod tests {
    use std::env;
    use std::ffi::OsString;
    use std::fs;
    use std::os::unix::ffi::OsStringExt;
    use std::path::Path;
    use std::path::PathBuf;
    use std::process;
    use std::sync::atomic::AtomicUsize;
    use std::sync::atomic::Ordering;

    use llama_cpp_error_chain::error_chain::error_chain;

    use super::AndroidNdk;
    use super::find_clang_builtin_includes;
    use super::validate_ndk_installation;
    use crate::build_environment::BuildEnvironment;
    use crate::build_environment::tests::environment_of;
    use crate::build_environment::tests::variable;
    use crate::host_os::HostOs;

    const FIXTURE_TOOLCHAIN: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/fixtures/android_ndk/toolchains/llvm/prebuilt/linux-x86_64"
    );

    static NEXT_DIRECTORY_ID: AtomicUsize = AtomicUsize::new(0);

    fn temporary_directory(name: &str) -> PathBuf {
        let id = NEXT_DIRECTORY_ID.fetch_add(1, Ordering::Relaxed);

        env::temp_dir().join(format!("llama-cpp-bindings-{name}-{}-{id}", process::id()))
    }

    fn ndk_at(root: &Path) -> BuildEnvironment {
        environment_of(&[], &[variable("ANDROID_NDK_HOME", OsString::from(root))])
    }

    fn detection_failure(
        environment: &BuildEnvironment,
        cargo_cfg_target_arch: &str,
        host_os: HostOs,
    ) -> Option<String> {
        AndroidNdk::detect(
            environment,
            "aarch64-linux-android",
            cargo_cfg_target_arch,
            host_os,
        )
        .err()
        .map(|error| error_chain(&error))
    }

    pub const FIXTURE_ANDROID_NDK: &str =
        concat!(env!("CARGO_MANIFEST_DIR"), "/fixtures/android_ndk");

    #[test]
    fn an_installed_ndk_is_detected_with_the_platform_api_level() {
        let detected = AndroidNdk::detect(
            &environment_of(
                &[],
                &[
                    variable("ANDROID_NDK_HOME", OsString::from(FIXTURE_ANDROID_NDK)),
                    variable("ANDROID_PLATFORM", OsString::from("android-30")),
                ],
            ),
            "aarch64-linux-android",
            "aarch64",
            HostOs::Linux,
        )
        .unwrap();

        assert_eq!(
            detected,
            AndroidNdk {
                ndk_path: FIXTURE_ANDROID_NDK.to_owned(),
                api_level: "30".to_owned(),
                abi: "arm64-v8a",
                sysroot: format!("{FIXTURE_TOOLCHAIN}/sysroot"),
                target_prefix: "aarch64-linux-android",
                clang_builtin_includes: format!("{FIXTURE_TOOLCHAIN}/lib/clang/20/include"),
            }
        );
    }

    #[test]
    fn the_cmake_platform_and_toolchain_file_derive_from_the_api_level_and_ndk_path() {
        let android_ndk = AndroidNdk {
            ndk_path: "/ndk".to_owned(),
            api_level: "30".to_owned(),
            abi: "arm64-v8a",
            sysroot: "/ndk/sysroot".to_owned(),
            target_prefix: "aarch64-linux-android",
            clang_builtin_includes: "/ndk/lib/clang/20/include".to_owned(),
        };

        assert_eq!(
            [
                android_ndk.android_platform(),
                android_ndk.cmake_toolchain_file()
            ],
            [
                "android-30".to_owned(),
                "/ndk/build/cmake/android.toolchain.cmake".to_owned(),
            ]
        );
    }

    #[test]
    fn an_unprefixed_api_level_is_read_as_is_and_a_missing_one_defaults_to_28() {
        let api_level_of = |environment: &BuildEnvironment| {
            AndroidNdk::detect(
                environment,
                "aarch64-linux-android",
                "aarch64",
                HostOs::Linux,
            )
            .map(|AndroidNdk { api_level, .. }| api_level)
            .ok()
        };

        assert_eq!(
            [
                api_level_of(&environment_of(
                    &[],
                    &[
                        variable("ANDROID_NDK_HOME", OsString::from(FIXTURE_ANDROID_NDK)),
                        variable("ANDROID_PLATFORM", OsString::from("33")),
                    ]
                )),
                api_level_of(&ndk_at(Path::new(FIXTURE_ANDROID_NDK))),
            ],
            [Some("33".to_owned()), Some("28".to_owned())]
        );
    }

    #[test]
    fn detection_names_the_ndk_input_that_is_missing_unreadable_or_unsupported() {
        let fixture_ndk = Path::new(FIXTURE_ANDROID_NDK);
        let missing_root = temporary_directory("missing-ndk-root");

        assert_eq!(
            [
                detection_failure(
                    &environment_of(&[], &[]),
                    "aarch64",
                    HostOs::Linux
                ),
                detection_failure(&ndk_at(&missing_root), "aarch64", HostOs::Linux),
                detection_failure(&ndk_at(fixture_ndk), "riscv64", HostOs::Linux),
                detection_failure(
                    &environment_of(
                        &[],
                        &[
                            variable("ANDROID_NDK_HOME", OsString::from(FIXTURE_ANDROID_NDK)),
                            variable("ANDROID_PLATFORM", OsString::from_vec(vec![0xff])),
                        ]
                    ),
                    "aarch64",
                    HostOs::Linux
                ),
                detection_failure(&ndk_at(fixture_ndk), "aarch64", HostOs::Unsupported),
                detection_failure(&ndk_at(fixture_ndk), "aarch64", HostOs::MacOs),
            ],
            [
                Some(
                    "Android NDK not found for target aarch64-linux-android. Set ANDROID_NDK_HOME.: \
                     environment variable not found"
                        .to_owned()
                ),
                Some(format!(
                    "Android NDK path does not exist: {}",
                    missing_root.display()
                )),
                Some("Unsupported Android target architecture: riscv64".to_owned()),
                Some(
                    "ANDROID_PLATFORM is set but could not be read: environment variable was not \
                     valid unicode: \"\\xFF\""
                        .to_owned()
                ),
                Some("Unsupported host platform for Android NDK".to_owned()),
                Some(format!(
                    "Android NDK toolchain not found at: \
                     {FIXTURE_ANDROID_NDK}/toolchains/llvm/prebuilt/darwin-x86_64"
                )),
            ]
        );
    }

    #[test]
    fn ndk_validation_rejects_a_root_without_a_cmake_toolchain() {
        let root = temporary_directory("ndk-without-toolchain");
        fs::create_dir_all(&root).unwrap();

        assert_eq!(
            validate_ndk_installation(root.to_str().unwrap())
                .err()
                .map(|error| error_chain(&error)),
            Some(format!(
                "Android NDK toolchain file not found: {}",
                root.join("build/cmake/android.toolchain.cmake").display()
            ))
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn detection_rejects_a_toolchain_without_a_clang_directory() {
        let root = temporary_directory("ndk-without-clang");
        let toolchain = root.join("toolchains/llvm/prebuilt/linux-x86_64");
        fs::create_dir_all(root.join("build/cmake")).unwrap();
        fs::write(root.join("build/cmake/android.toolchain.cmake"), "").unwrap();
        fs::create_dir_all(&toolchain).unwrap();

        assert_eq!(
            detection_failure(&ndk_at(&root), "aarch64", HostOs::Linux),
            Some(format!(
                "Android NDK Clang directory could not be listed at {}: No such file or directory \
                 (os error 2)",
                toolchain.join("lib/clang").display()
            ))
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn clang_builtin_include_resolution_requires_a_version_directory() {
        let toolchain = temporary_directory("clang-without-version");
        fs::create_dir_all(toolchain.join("lib/clang")).unwrap();
        fs::write(toolchain.join("lib/clang/21"), "").unwrap();

        assert_eq!(
            find_clang_builtin_includes(toolchain.to_str().unwrap())
                .err()
                .map(|error| error_chain(&error)),
            Some(format!(
                "Android NDK Clang version directory was not found at {}",
                toolchain.join("lib/clang").display()
            ))
        );
        fs::remove_dir_all(toolchain).unwrap();
    }

    #[test]
    fn clang_builtin_include_resolution_refuses_to_choose_between_version_directories() {
        let toolchain = temporary_directory("clang-with-two-versions");
        fs::create_dir_all(toolchain.join("lib/clang/18/include")).unwrap();
        fs::create_dir_all(toolchain.join("lib/clang/17/include")).unwrap();

        assert_eq!(
            find_clang_builtin_includes(toolchain.to_str().unwrap())
                .err()
                .map(|error| error_chain(&error)),
            Some(format!(
                "Android NDK Clang directory {} holds more than one version directory: {:?}",
                toolchain.join("lib/clang").display(),
                [
                    toolchain.join("lib/clang/17"),
                    toolchain.join("lib/clang/18")
                ]
            ))
        );
        fs::remove_dir_all(toolchain).unwrap();
    }

    #[test]
    fn clang_builtin_include_resolution_requires_an_include_directory() {
        let toolchain = temporary_directory("clang-without-includes");
        fs::create_dir_all(toolchain.join("lib/clang/20")).unwrap();

        assert_eq!(
            find_clang_builtin_includes(toolchain.to_str().unwrap())
                .err()
                .map(|error| error_chain(&error)),
            Some(format!(
                "Android NDK Clang built-in include directory was not found at {}",
                toolchain.join("lib/clang/20/include").display()
            ))
        );
        fs::remove_dir_all(toolchain).unwrap();
    }
}