uniffi-bindgen-java 0.5.2

a java bindings generator for uniffi rust
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
/* This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use anyhow::{Context, Result, bail};
use camino::{Utf8Path, Utf8PathBuf};
use cargo_metadata::{CrateType, MetadataCommand, Package, Target};
use std::io::{Read, Write};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{env, fs};
use uniffi_bindgen::{BindgenLoader, BindgenPaths, BindgenPathsLayer, GlobalConfig};
use uniffi_bindgen_java::{GenerateOptions, generate};
use uniffi_testing::UniFFITestHelper;

/// Points every crate at one merged `uniffi.toml`, so a fixture's config plus its test's
/// `uniffi-extras.toml` apply across all the namespaces the fixture pulls in.
struct ConfigOverrideLayer {
    path: Utf8PathBuf,
}

impl BindgenPathsLayer for ConfigOverrideLayer {
    fn get_config_path(&self, _crate_name: &str) -> Option<Utf8PathBuf> {
        Some(self.path.clone())
    }
}

/// Run the test fixtures from UniFFI
fn run_test(fixture_name: &str, test_file: &str) -> Result<()> {
    let test_path = Utf8Path::new(".").join("tests").join(test_file);
    let test_helper = UniFFITestHelper::new(fixture_name)?;
    let out_dir = test_helper.create_out_dir(env!("CARGO_TARGET_TMPDIR"), &test_path)?;
    let cdylib_path = test_helper.cdylib_path()?;

    // This whole block in designed to create a new TOML file if there is one in the fixture or a uniffi-extras.toml as a sibling of the test. The extras
    // will be concatenated to the end of the base with extra if available.
    let maybe_new_uniffi_toml_filename = {
        let maybe_base_uniffi_toml_string =
            find_uniffi_toml(fixture_name)?.and_then(read_file_contents);
        let maybe_extra_uniffi_toml_string =
            read_file_contents(test_path.with_file_name("uniffi-extras.toml"));

        // final_string will be "" if there aren't any toml files to read.
        let final_string: String = itertools::Itertools::intersperse(
            vec![
                maybe_base_uniffi_toml_string,
                maybe_extra_uniffi_toml_string,
            ]
            .into_iter()
            .flatten(),
            "\n".to_string(),
        )
        .collect();

        // If there wasn't anything read from the files, just return none so the default config file can be used.
        if final_string.is_empty() {
            None
        } else {
            //Create a unique(ish) filename for the fixture. We'll just accept that nanosecond uniqueness is good enough per fixture_name.
            let current_time = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("Time went backwards")
                .as_nanos();
            let new_filename =
                out_dir.with_file_name(format!("{}-{}.toml", fixture_name, current_time));
            write_file_contents(&new_filename, &final_string)?;
            Some(new_filename)
        }
    };

    // Create BindgenPaths with cargo metadata layer and optional config override
    let mut paths = BindgenPaths::default();
    if let Some(config_path) = &maybe_new_uniffi_toml_filename {
        paths.add_layer(ConfigOverrideLayer {
            path: config_path.clone(),
        });
    }
    paths.add_cargo_metadata_layer(false)?;
    let loader = BindgenLoader::new(paths, GlobalConfig::default());

    // generate the fixture bindings
    generate(
        &loader,
        &GenerateOptions {
            source: cdylib_path.clone(),
            out_dir: out_dir.clone(),
            format: true,
            crate_filter: None,
        },
    )?;

    // Copy the cdylib to a flat directory for java.library.path.
    // System.loadLibrary expects "lib<name>.dylib" (macOS) or "lib<name>.so" (Linux).
    // The cdylib from cargo has a hash suffix, so we create a symlink with the
    // expected name that System.loadLibrary will find.
    let native_lib_dir = out_dir.join("native");
    fs::create_dir_all(&native_lib_dir)?;
    let cdylib_filename = cdylib_path.file_name().unwrap();
    let cdylib_dest = native_lib_dir.join(cdylib_filename);
    fs::copy(&cdylib_path, &cdylib_dest)?;

    let extension = cdylib_path.extension().unwrap(); // "dylib" or "so"
    let lib_base_name = cdylib_filename
        .strip_prefix("lib")
        .unwrap_or(cdylib_filename)
        .split('-')
        .next()
        .unwrap_or(cdylib_filename);
    let expected_lib_name = format!("lib{}.{}", lib_base_name, extension);
    let symlink_path = native_lib_dir.join(&expected_lib_name);
    if !symlink_path.exists() {
        std::os::unix::fs::symlink(cdylib_dest.file_name().unwrap(), &symlink_path)?;
    }

    // compile generated bindings and form jar
    let jar_file = build_jar(fixture_name, &out_dir)?;

    // compile test
    // Helper sources in a package directory beside the test compile from here, e.g. to reach
    // package-private generated helpers.
    let test_dir = test_path.parent().unwrap().to_path_buf();
    let status = Command::new("javac")
        .arg("-classpath")
        .arg(calc_classpath(vec![&out_dir, &jar_file, &test_dir]))
        // Our tests should not produce any warnings.
        .arg("-Werror")
        .arg(&test_path)
        .spawn()
        .context("Failed to spawn `javac` to compile Java test")?
        .wait()
        .context("Failed to wait for `javac` when compiling Java test")?;
    if !status.success() {
        anyhow::bail!("running `javac` failed when compiling the Java test")
    }

    // run resulting test
    let compiled_path = test_path.file_stem().unwrap();
    let run_status = java_command()
        // allow for runtime assertions
        .arg("-ea")
        // Enable FFM native access
        .arg("--enable-native-access=ALL-UNNAMED")
        // Set native library path so System.loadLibrary can find the cdylib
        .arg(format!("-Djava.library.path={}", native_lib_dir))
        .arg("-classpath")
        .arg(calc_classpath(vec![&out_dir, &jar_file, &test_dir]))
        .arg(compiled_path)
        .spawn()
        .context("Failed to spawn `java` to run Java test")?
        .wait()
        .context("Failed to wait for `java` when running Java test")?;
    if !run_status.success() {
        anyhow::bail!("Running the `java` test failed.")
    }

    Ok(())
}

/// Run a test using an absolute path library override instead of java.library.path.
/// This validates that the generated loadLibrary() code uses System.load() for absolute paths.
fn run_test_with_library_override(
    fixture_name: &str,
    test_file: &str,
    namespace: &str,
) -> Result<()> {
    let test_path = Utf8Path::new(".").join("tests").join(test_file);
    let test_helper = UniFFITestHelper::new(fixture_name)?;
    // Use a synthetic path for out_dir so it doesn't collide with run_test's out_dir
    // (create_out_dir is deterministic based on the path).
    let out_dir_key = Utf8Path::new(".")
        .join("tests")
        .join("library_override")
        .join(test_file);
    let out_dir = test_helper.create_out_dir(env!("CARGO_TARGET_TMPDIR"), &out_dir_key)?;
    let cdylib_path = test_helper.cdylib_path()?;

    let mut paths = BindgenPaths::default();
    paths.add_cargo_metadata_layer(false)?;
    let loader = BindgenLoader::new(paths, GlobalConfig::default());

    generate(
        &loader,
        &GenerateOptions {
            source: cdylib_path.clone(),
            out_dir: out_dir.clone(),
            format: true,
            crate_filter: None,
        },
    )?;

    // Copy the cdylib to a known absolute path (no symlink needed since we pass the full path)
    let native_lib_dir = out_dir.join("native");
    fs::create_dir_all(&native_lib_dir)?;
    let cdylib_filename = cdylib_path.file_name().unwrap();
    let extension = cdylib_path.extension().unwrap();
    let lib_base_name = cdylib_filename
        .strip_prefix("lib")
        .unwrap_or(cdylib_filename)
        .split('-')
        .next()
        .unwrap_or(cdylib_filename);
    let canonical_lib_name = format!("lib{}.{}", lib_base_name, extension);
    let lib_absolute_path = native_lib_dir.join(&canonical_lib_name);
    fs::copy(&cdylib_path, &lib_absolute_path)?;

    let jar_file = build_jar(fixture_name, &out_dir)?;

    let status = Command::new("javac")
        .arg("-classpath")
        .arg(calc_classpath(vec![&out_dir, &jar_file]))
        .arg("-Werror")
        .arg(&test_path)
        .spawn()
        .context("Failed to spawn `javac` to compile Java test")?
        .wait()
        .context("Failed to wait for `javac` when compiling Java test")?;
    if !status.success() {
        anyhow::bail!("running `javac` failed when compiling the Java test")
    }

    // Run with library override set to an absolute path and NO java.library.path,
    // so this can only work if the generated code uses System.load() for absolute paths.
    let compiled_path = test_path.file_stem().unwrap();
    let run_status = java_command()
        .arg("-ea")
        .arg("--enable-native-access=ALL-UNNAMED")
        .arg(format!(
            "-Duniffi.component.{}.libraryOverride={}",
            namespace, lib_absolute_path
        ))
        // Deliberately NOT setting -Djava.library.path
        .arg("-classpath")
        .arg(calc_classpath(vec![
            &out_dir,
            &jar_file,
            &test_path.parent().unwrap().to_path_buf(),
        ]))
        .arg(compiled_path)
        .spawn()
        .context("Failed to spawn `java` to run Java test")?
        .wait()
        .context("Failed to wait for `java` when running Java test")?;
    if !run_status.success() {
        anyhow::bail!("Running the `java` test with library override failed.")
    }

    Ok(())
}

/// `java` with allocator poisoning, so a use-after-free of native memory reads a fill pattern
/// instead of plausible data. Each platform ignores the other's variables.
fn java_command() -> Command {
    let mut cmd = Command::new("java");
    // glibc: fill allocated and freed memory with 0xa5 and its complement.
    cmd.env("GLIBC_TUNABLES", "glibc.malloc.perturb=165");
    // macOS libmalloc: fill freed memory, and abort on access past a guarded large allocation.
    cmd.env("MallocScribble", "1");
    cmd.env("MallocGuardEdges", "1");
    cmd
}

/// Get the uniffi_toml of the fixture if it exists.
/// It looks for it in the root directory of the project `name`.
fn find_uniffi_toml(name: &str) -> Result<Option<Utf8PathBuf>> {
    let metadata = MetadataCommand::new()
        .exec()
        .expect("error running cargo metadata");
    let matching: Vec<&Package> = metadata
        .packages
        .iter()
        .filter(|p| p.name == name)
        .collect();
    let package = match matching.len() {
        1 => matching[0].clone(),
        n => bail!("cargo metadata return {n} packages named {name}"),
    };
    let cdylib_targets: Vec<&Target> = package
        .targets
        .iter()
        .filter(|t| t.crate_types.iter().any(|t| t == &CrateType::CDyLib))
        .collect();
    let target = match cdylib_targets.len() {
        1 => cdylib_targets[0],
        n => bail!("Found {n} cdylib targets for {}", package.name),
    };
    let maybe_uniffi_toml = target
        .src_path
        .parent()
        .map(|uniffi_toml_dir| uniffi_toml_dir.with_file_name("uniffi.toml"));
    Ok(maybe_uniffi_toml)
}

/// Generate java bindings for the given namespace, then use the Java
/// command-line tools to compile them into a .jar file.
fn build_jar(fixture_name: &str, out_dir: &Utf8PathBuf) -> Result<Utf8PathBuf> {
    let mut jar_file = Utf8PathBuf::from(out_dir);
    jar_file.push(format!("{}.jar", fixture_name));
    let staging_dir = out_dir.join("staging");

    let status = Command::new("javac")
        // Our generated bindings should not produce any warnings; fail tests if they do.
        .arg("-Werror")
        .arg("-d")
        .arg(&staging_dir)
        .arg("-classpath")
        .arg(calc_classpath(vec![]))
        .args(
            glob::glob(&out_dir.join("**/*.java").into_string())?
                .flatten()
                .map(|p| String::from(p.to_string_lossy())),
        )
        .spawn()
        .context("Failed to spawn `javac` to compile the bindings")?
        .wait()
        .context("Failed to wait for `javac` when compiling the bindings")?;
    if !status.success() {
        bail!("running `javac` failed when compiling the bindings")
    }

    let jar_status = Command::new("jar")
        .current_dir(out_dir)
        .arg("cf")
        .arg(jar_file.file_name().unwrap())
        .arg("-C")
        .arg(&staging_dir)
        .arg(".")
        .spawn()
        .context("Failed to spawn `jar` to package the bindings")?
        .wait()
        .context("Failed to wait for `jar` when packaging the bindings")?;
    if !jar_status.success() {
        bail!("running `jar` failed")
    }

    Ok(jar_file)
}

fn calc_classpath(extra_paths: Vec<&Utf8PathBuf>) -> String {
    extra_paths
        .into_iter()
        .map(|p| p.to_string())
        // Add the system classpath as a component, using the fact that env::var returns an Option,
        // which implement Iterator
        .chain(env::var("CLASSPATH"))
        .collect::<Vec<String>>()
        .join(":")
}

/// Read the contents of the file. Any errors will be turned into None.
fn read_file_contents(path: Utf8PathBuf) -> Option<String> {
    if let Ok(metadata) = fs::metadata(&path) {
        if metadata.is_file() {
            let mut content = String::new();
            std::fs::File::open(path)
                .ok()?
                .read_to_string(&mut content)
                .ok()?;
            Some(content)
        } else {
            None
        }
    } else {
        None
    }
}

fn write_file_contents(path: &Utf8PathBuf, contents: &str) -> Result<()> {
    std::fs::File::create(path)?.write_all(contents.as_bytes())?;
    Ok(())
}

macro_rules! fixture_tests {
    {
        $(($test_name:ident, $fixture_name:expr, $test_script:expr),)*
    } => {
    $(
        #[test]
        fn $test_name() -> Result<()> {
            run_test($fixture_name, $test_script)
        }
    )*
    }
}

fixture_tests! {
    (test_arithmetic, "uniffi-example-arithmetic", "scripts/TestArithmetic.java"),
    (test_geometry, "uniffi-example-geometry", "scripts/TestGeometry.java"),
    (test_rondpoint, "uniffi-example-rondpoint", "scripts/TestRondpoint.java"),
    // todolist: namespace class `Todolist` and object class `TodoList` produce filenames that
    // collide on case-insensitive filesystems (macOS).
    // (test_todolist, "uniffi-example-todolist", "scripts/TestTodolist.java"),
    (test_sprites, "uniffi-example-sprites", "scripts/TestSprites.java"),
    (test_coverall, "uniffi-fixture-coverall", "scripts/TestFixtureCoverall.java"),
    (test_enum_types, "uniffi-fixture-enum-types", "scripts/TestEnumTypes.java"),
    (test_chronological, "uniffi-fixture-time", "scripts/TestChronological.java"),
    (test_custom_types, "uniffi-example-custom-types", "scripts/TestCustomTypes/TestCustomTypes.java"),
    (test_external_types, "uniffi-fixture-ext-types", "scripts/TestImportedTypes/TestImportedTypes.java"),
    (test_futures, "uniffi-example-futures", "scripts/TestFutures.java"),
    (test_futures_fixtures, "uniffi-fixture-futures", "scripts/TestFixtureFutures/TestFixtureFutures.java"),
    (test_trait_methods, "uniffi-fixture-trait-methods", "scripts/TestTraitMethods.java"),
    (test_omit_checksums, "uniffi-example-arithmetic", "scripts/TestOmitChecksums/TestOmitChecksums.java"),
    (test_proc_macro, "uniffi-fixture-proc-macro", "scripts/TestProcMacro.java"),
    (test_rename, "uniffi-fixture-rename", "scripts/TestRename/TestRename.java"),
    (test_primitive_arrays, "uniffi-fixture-primitive-arrays", "scripts/TestPrimitiveArrays.java"),
    (test_async_lifecycle, "uniffi-fixture-async-lifecycle", "scripts/TestAsyncLifecycle/TestAsyncLifecycle.java"),
    (test_zero_copy, "uniffi-fixture-zero-copy", "scripts/TestZeroCopy.java"),
    (test_name_collisions, "uniffi-fixture-name-collisions", "scripts/TestNameCollisions.java"),
}

#[test]
fn test_library_override_absolute_path() -> Result<()> {
    run_test_with_library_override(
        "uniffi-example-arithmetic",
        "scripts/TestArithmetic.java",
        "arithmetic",
    )
}