Skip to main content

lux_lib/build/compile/
c_link.rs

1use std::{
2    collections::HashMap,
3    io,
4    path::{Path, PathBuf},
5    process::{ExitStatus, Output},
6};
7
8use itertools::Itertools;
9use miette::Diagnostic;
10use path_slash::PathExt;
11use thiserror::Error;
12use tokio::process::Command;
13
14use crate::{
15    build::external_dependency::ExternalDependencyInfo, config::Config, fs, lua, rockspec,
16};
17
18#[derive(Error, Debug, Diagnostic)]
19#[non_exhaustive]
20pub enum Error {
21    #[error("IO operation failed while linking C modules")]
22    Io(#[from] io::Error),
23    #[error(transparent)]
24    #[diagnostic(transparent)]
25    Fs(#[from] fs::Error),
26    #[error(transparent)]
27    CC(#[from] cc::Error),
28    #[error("compilation failed.\nstatus: {status}\nstdout: {stdout}\nstderr: {stderr}")]
29    #[diagnostic(help(
30        r#"check the compiler output above for details.
31rerun with `--verbose` for more information."#
32    ))]
33    CommandFailure {
34        status: ExitStatus,
35        stdout: String,
36        stderr: String,
37    },
38    #[error("compiling C modules succeeded, but the expected library {0} was not created")]
39    #[diagnostic(help(
40        "check the rockspec or lux.toml `modules` and `lib_modules` tables for correct paths."
41    ))]
42    LibOutputNotCreated(String),
43}
44
45fn validate_output(output: &Output) -> Result<(), Error> {
46    if !output.status.success() {
47        return Err(Error::CommandFailure {
48            status: output.status,
49            stdout: String::from_utf8_lossy(&output.stdout).into(),
50            stderr: String::from_utf8_lossy(&output.stderr).into(),
51        });
52    }
53    Ok(())
54}
55
56/// On MSVC, we need to create Lua definitions manually
57#[tracing::instrument(level = "trace")]
58fn mk_def_file(
59    dir: &Path,
60    output_file_name: &str,
61    target_module: &rockspec::build::backend::Module,
62) -> Result<PathBuf, fs::Error> {
63    let mut def_file: PathBuf = dir.join(output_file_name);
64    def_file.set_extension(".def");
65    let exported_name = target_module.to_string().replace(".", "_");
66    let exported_name = exported_name
67        .split_once('-')
68        .map(|(_, after_hyphen)| after_hyphen.to_string())
69        .unwrap_or_else(|| exported_name.clone());
70    let content = format!(
71        r#"EXPORTS
72luaopen_{exported_name}
73"#,
74    );
75    fs::sync::write(&def_file, content)?;
76    Ok(def_file)
77}
78
79#[allow(clippy::too_many_arguments)]
80pub(crate) async fn artifacts(
81    build: &mut cc::Build,
82    lua: &lua::Installation,
83    external_dependencies: &HashMap<String, ExternalDependencyInfo>,
84    target_file_name: &str,
85    libdir_args: Vec<String>,
86    library_args: Vec<String>,
87    target_module: &rockspec::build::backend::Module,
88    target_parent_dir: &Path,
89    objects: Vec<PathBuf>,
90    config: &Config,
91) -> Result<(), Error> {
92    let output_path =
93        std::path::absolute(target_parent_dir.join(target_file_name)).map_err(Error::Io)?;
94    let compiler = build.try_get_compiler()?;
95    // Linking from within a temp directory makes sure the linker doesn't create any build artifacts in
96    // the current working directory.
97    // See https://github.com/lumen-oss/lux/issues/1106
98    let temp_work_dir = fs::tempfile::tempdir()?;
99    let is_msvc = compiler.is_like_msvc();
100    let cmd = build.try_get_compiler()?.to_command();
101    let mut cmd: tokio::process::Command = cmd.into();
102    cmd.current_dir(temp_work_dir.path());
103    let output = if is_msvc {
104        let def_file = mk_def_file(temp_work_dir.path(), target_file_name, target_module)?;
105        cmd.args(&objects).arg("/LD");
106        add_variable_if_set(config, "LDFLAGS", &mut cmd);
107        cmd.arg("/link")
108            .arg("/NOIMPLIB")
109            .arg("/NOEXP")
110            .arg(format!("/DEF:{}", def_file.display()))
111            .arg(format!("/OUT:{}", output_path.display()))
112            .args(lua_lib_link_args(lua, &compiler))
113            .args(
114                external_dependencies
115                    .values()
116                    .flat_map(|dep| dep.lib_link_args(&compiler)),
117            )
118            .args(libdir_args)
119            .args(library_args)
120            .output()
121            .await?
122    } else {
123        add_variable_if_set(config, "LIBFLAG", &mut cmd);
124        add_variable_if_set(config, "LDFLAGS", &mut cmd);
125        cmd.args(vec!["-o".into(), output_path.to_string_lossy().to_string()])
126            .args(lua_lib_link_args(lua, &build.try_get_compiler()?))
127            .args(
128                external_dependencies
129                    .values()
130                    .flat_map(|dep| dep.lib_link_args(&compiler)),
131            )
132            .args(&objects)
133            .args(libdir_args)
134            .args(library_args)
135            .output()
136            .await?
137    };
138    crate::build::command::trace_output(&output);
139    validate_output(&output)?;
140
141    if output_path.exists() {
142        Ok(())
143    } else {
144        Err(Error::LibOutputNotCreated(
145            output_path.to_slash_lossy().to_string(),
146        ))
147    }
148}
149
150/// NOTE: In luarocks, these are behind a link_lua_explicity config option
151fn lua_lib_link_args(lua: &lua::Installation, compiler: &cc::Tool) -> Vec<String> {
152    if cfg!(target_os = "macos") {
153        // On macos, linking Lua can lead to duplicate symbol errors
154        Vec::new()
155    } else {
156        lua.lib_link_args(compiler)
157    }
158}
159
160/// Lookup a variable in the `Config` and if set and non-empty,
161/// split it into multiple arguments and add them to the `Command`.
162fn add_variable_if_set(config: &Config, name: &str, cmd: &mut Command) {
163    let variables = config.variables();
164    if let Some(var_str) = variables.get(name) {
165        if !var_str.is_empty() {
166            let vars = var_str.split_whitespace().collect_vec();
167            cmd.args(vars);
168        }
169    }
170}