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#[derive(bon::Builder)]
80#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
81pub(crate) struct Linker<'a> {
82    cc_build: &'a cc::Build,
83    lua: &'a lua::Installation,
84    external_dependencies: &'a HashMap<String, ExternalDependencyInfo>,
85    target_file_name: &'a str,
86    libdir_args: Vec<String>,
87    library_args: Vec<String>,
88    target_module: &'a rockspec::build::backend::Module,
89    target_parent_dir: &'a Path,
90    objects: Vec<PathBuf>,
91    config: &'a Config,
92}
93
94impl<'a, State> LinkerBuilder<'a, State>
95where
96    State: linker_builder::State + linker_builder::IsComplete,
97{
98    pub(crate) async fn link(self) -> Result<(), Error> {
99        let linker = self._build();
100        let output_path =
101            std::path::absolute(linker.target_parent_dir.join(linker.target_file_name))
102                .map_err(Error::Io)?;
103        let compiler = linker.cc_build.try_get_compiler()?;
104        // Linking from within a temp directory makes sure the linker doesn't create any build artifacts in
105        // the current working directory.
106        // See https://github.com/lumen-oss/lux/issues/1106
107        let temp_work_dir = fs::tempfile::tempdir()?;
108        let is_msvc = compiler.is_like_msvc();
109        let cmd = linker.cc_build.try_get_compiler()?.to_command();
110        let mut cmd: tokio::process::Command = cmd.into();
111        cmd.current_dir(temp_work_dir.path());
112        let output = if is_msvc {
113            let def_file = mk_def_file(
114                temp_work_dir.path(),
115                linker.target_file_name,
116                linker.target_module,
117            )?;
118            cmd.args(&linker.objects).arg("/LD");
119            add_variable_if_set(linker.config, "LDFLAGS", &mut cmd);
120            cmd.arg("/link")
121                .arg("/NOIMPLIB")
122                .arg("/NOEXP")
123                .arg(format!("/DEF:{}", def_file.display()))
124                .arg(format!("/OUT:{}", output_path.display()))
125                .args(lua_lib_link_args(linker.lua, &compiler))
126                .args(
127                    linker
128                        .external_dependencies
129                        .values()
130                        .flat_map(|dep| dep.lib_link_args(&compiler)),
131                )
132                .args(&linker.libdir_args)
133                .args(&linker.library_args)
134                .output()
135                .await?
136        } else {
137            add_variable_if_set(linker.config, "LIBFLAG", &mut cmd);
138            add_variable_if_set(linker.config, "LDFLAGS", &mut cmd);
139            cmd.args(vec!["-o".into(), output_path.to_string_lossy().to_string()])
140                .args(lua_lib_link_args(
141                    linker.lua,
142                    &linker.cc_build.try_get_compiler()?,
143                ))
144                .args(
145                    linker
146                        .external_dependencies
147                        .values()
148                        .flat_map(|dep| dep.lib_link_args(&compiler)),
149                )
150                .args(&linker.objects)
151                .args(&linker.libdir_args)
152                .args(&linker.library_args)
153                .output()
154                .await?
155        };
156        crate::build::command::trace_output(&output);
157        validate_output(&output)?;
158
159        if output_path.exists() {
160            Ok(())
161        } else {
162            Err(Error::LibOutputNotCreated(
163                output_path.to_slash_lossy().to_string(),
164            ))
165        }
166    }
167}
168
169/// NOTE: In luarocks, these are behind a link_lua_explicity config option
170fn lua_lib_link_args(lua: &lua::Installation, compiler: &cc::Tool) -> Vec<String> {
171    if cfg!(target_os = "macos") {
172        // On macos, linking Lua can lead to duplicate symbol errors
173        Vec::new()
174    } else {
175        lua.lib_link_args(compiler)
176    }
177}
178
179/// Lookup a variable in the `Config` and if set and non-empty,
180/// split it into multiple arguments and add them to the `Command`.
181fn add_variable_if_set(config: &Config, name: &str, cmd: &mut Command) {
182    let variables = config.variables();
183    if let Some(var_str) = variables.get(name) {
184        if !var_str.is_empty() {
185            let vars = var_str.split_whitespace().collect_vec();
186            cmd.args(vars);
187        }
188    }
189}