cgo 0.3.0

A library for build scripts to compile custom Go code
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! A library for build scripts to compile custom Go code, inspired by the
//! excellent [cc](https://docs.rs/cc/latest/cc) crate.
//!
//! It is intended that you use this library from within your `build.rs` file by
//! adding the cgo crate to your [`build-dependencies`](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#build-dependencies):
//!
//! ```toml
//! [build-dependencies]
//! cgo = "*"
//! ```
//!
//! # Examples
//!
//! The following example will statically compile the Go package and instruct
//! cargo to link the resulting library (`libexample`).
//!
//! ```no_run
//! fn main() {
//!     cgo::Build::new()
//!         .package("pkg/example/main.go")
//!         .build("example");
//! }
//! ```

#![forbid(unsafe_code)]
#![allow(clippy::needless_doctest_main)]

use std::{
    env,
    ffi::{OsStr, OsString},
    fmt::Write,
    path::{Path, PathBuf},
    process,
};

/// A builder for the compilation of a Go library.
#[derive(Clone, Debug)]
pub struct Build {
    build_mode: BuildMode,
    cargo_metadata: bool,
    change_dir: Option<PathBuf>,
    goarch: Option<String>,
    goos: Option<String>,
    ldflags: Option<OsString>,
    module_mode: Option<ModuleMode>,
    out_dir: Option<PathBuf>,
    packages: Vec<PathBuf>,
    trimpath: bool,
}

impl Default for Build {
    fn default() -> Self {
        Self::new()
    }
}

impl Build {
    /// Returns a new instance of `Build` with the default configuration.
    pub fn new() -> Self {
        Build {
            build_mode: BuildMode::default(),
            cargo_metadata: true,
            change_dir: None,
            goarch: None,
            goos: None,
            ldflags: None,
            module_mode: None,
            out_dir: None,
            packages: Vec::default(),
            trimpath: false,
        }
    }

    /// Instruct the builder to use the provided build mode.
    ///
    /// For more information, see https://pkg.go.dev/cmd/go#hdr-Build_modes
    ///
    /// By default, 'CArchive' is used.
    pub fn build_mode(&mut self, build_mode: BuildMode) -> &mut Self {
        self.build_mode = build_mode;
        self
    }

    /// Instruct the builder to automatically output cargo metadata or not.
    ///
    /// By default, cargo metadata is enabled.
    pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Self {
        self.cargo_metadata = cargo_metadata;
        self
    }

    /// Instruct the builder to change to `dir` before running the `go build`
    /// command. All other paths are interpreted after changing directories.
    pub fn change_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
        self.change_dir = Some(dir.as_ref().to_owned());
        self
    }

    /// Instruct the builder to set the GOARCH to the provided value.
    ///
    /// By default, this value is set from the CARGO_CFG_TARGET_ARCH env var.
    pub fn goarch(&mut self, goarch: &str) -> &mut Self {
        self.goarch = Some(goarch.to_owned());
        self
    }

    /// Instruct the builder to set the GOOS to the provided value.
    ///
    /// By default, this value is set from the CARGO_CFG_TARGET_OS env var.
    pub fn goos(&mut self, goos: &str) -> &mut Self {
        self.goos = Some(goos.to_owned());
        self
    }

    /// Instruct the builder to pass in the provided ldflags during compilation.
    pub fn ldflags<P: AsRef<OsStr>>(&mut self, ldflags: P) -> &mut Self {
        self.ldflags = Some(ldflags.as_ref().to_os_string());
        self
    }

    /// Instruct the builder to use the provided module mode.
    ///
    /// For more information, see https://go.dev/ref/mod#build-commands
    pub fn module_mode(&mut self, module_mode: ModuleMode) -> &mut Self {
        self.module_mode = Some(module_mode);
        self
    }

    /// Instruct the builder to use the provided directory for output.
    ///
    /// By default, the cargo-provided `OUT_DIR` env var is used.
    pub fn out_dir<P: AsRef<Path>>(&mut self, out_dir: P) -> &mut Self {
        self.out_dir = Some(out_dir.as_ref().to_owned());
        self
    }

    /// Instruct the builder to compile the provided Go package.
    ///
    /// Note: The `go build` command can be passed multiple packages and this
    /// method may be called more than once.
    pub fn package<P: AsRef<Path>>(&mut self, package: P) -> &mut Self {
        self.packages.push(package.as_ref().to_owned());
        self
    }

    /// Instruct the builder to enable the `-trimpath` flag during compilation.
    pub fn trimpath(&mut self, trimpath: bool) -> &mut Self {
        self.trimpath = trimpath;
        self
    }

    /// Builds the Go package, generating the file `output`.
    ///
    /// # Panics
    ///
    /// Panics if any error occurs during compilation.
    pub fn build(&self, output: &str) {
        if let Err(err) = self.try_build(output) {
            eprintln!("\n\nerror occurred: {}\n", err);
            process::exit(1);
        }
    }

    /// Builds the Go package, generating the file `output`.
    pub fn try_build(&self, output: &str) -> Result<(), Error> {
        // Use the provided values for GOARCH and GOOS, otherwise fetch the
        // values from the cargo build environnment variables.
        let goarch = match &self.goarch {
            None => goarch_from_env()?,
            Some(goarch) => goarch.to_owned(),
        };
        let goos = match &self.goos {
            None => goos_from_env()?,
            Some(goos) => goos.to_owned(),
        };

        let lib_name = self.format_lib_name(output);
        let out_dir = match &self.out_dir {
            Some(out_dir) => out_dir.clone(),
            None => get_env_var("OUT_DIR")?.into(),
        };
        let out_path = out_dir.join(lib_name);

        let mut cmd = process::Command::new("go");
        cmd.env("CGO_ENABLED", "1")
            .env("GOOS", goos)
            .env("GOARCH", goarch)
            .env("CC", get_cc())
            .env("CXX", get_cxx())
            .arg("build");
        if let Some(change_dir) = &self.change_dir {
            // This flag is required to be the first flag used in the command as
            // of Go v1.21: https://tip.golang.org/doc/go1.21#go-command
            cmd.args([&"-C".into(), change_dir]);
        }
        if let Some(ldflags) = &self.ldflags {
            cmd.args([&"-ldflags".into(), ldflags]);
        }
        if let Some(module_mode) = &self.module_mode {
            cmd.args(["-mod", &module_mode.to_string()]);
        }
        if self.trimpath {
            cmd.arg("-trimpath");
        }
        cmd.args(["-buildmode", &self.build_mode.to_string()]);
        cmd.args(["-o".into(), out_path]);
        for package in &self.packages {
            cmd.arg(package);
        }

        let build_output = match cmd.output() {
            Ok(build_output) => build_output,
            Err(err) => {
                return Err(Error::new(
                    ErrorKind::ToolExecError,
                    &format!("failed to execute go command: {}", err),
                ));
            }
        };

        if self.cargo_metadata {
            let link_kind = match self.build_mode {
                BuildMode::CArchive => "static",
                BuildMode::CShared => "dylib",
            };
            println!("cargo:rustc-link-lib={}={}", link_kind, output);
            println!("cargo:rustc-link-search=native={}", out_dir.display());
        }

        if build_output.status.success() {
            return Ok(());
        }

        let mut message = format!(
            "failed to build Go library ({}). Build output:",
            build_output.status
        );

        let mut push_output = |stream_name, bytes| {
            let string = String::from_utf8_lossy(bytes);
            let string = string.trim();

            if string.is_empty() {
                return;
            }

            write!(&mut message, "\n=== {stream_name}:\n{string}").unwrap();
        };

        push_output("stdout", &build_output.stdout);
        push_output("stderr", &build_output.stderr);

        Err(Error::new(ErrorKind::ToolExecError, &message))
    }

    fn format_lib_name(&self, output: &str) -> PathBuf {
        let mut lib = String::with_capacity(output.len() + 7);
        lib.push_str("lib");
        lib.push_str(output);
        lib.push_str(match self.build_mode {
            BuildMode::CArchive => {
                if cfg!(windows) {
                    ".lib"
                } else {
                    ".a"
                }
            }
            BuildMode::CShared => {
                if cfg!(windows) {
                    ".dll"
                } else {
                    ".so"
                }
            }
        });
        lib.into()
    }
}

/// BuildMode to be used during compilation.
///
/// Refer to the [Go docs](https://pkg.go.dev/cmd/go#hdr-Build_modes)
/// for more information.
#[derive(Clone, Debug, Default)]
pub enum BuildMode {
    /// Build the listed main package, plus all packages it imports,
    /// into a C archive file. The only callable symbols will be those
    /// functions exported using a cgo //export comment. Requires
    /// exactly one main package to be listed.
    #[default]
    CArchive,
    /// Build the listed main package, plus all packages it imports,
    /// into a C shared library. The only callable symbols will
    /// be those functions exported using a cgo //export comment.
    /// Requires exactly one main package to be listed.
    CShared,
}

impl std::fmt::Display for BuildMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::CArchive => "c-archive",
            Self::CShared => "c-shared",
        })
    }
}

/// ModuleMode to be used during compilation.
///
/// By default, if the go version in go.mod is 1.14 or higher and a vendor
/// directory is present, the go command acts as if -mod=vendor were used.
/// Otherwise, the go command acts as if -mod=readonly were used.
///
/// Refer to the [Go docs](https://go.dev/ref/mod#build-commands)
/// for more information.
#[derive(Clone, Debug)]
pub enum ModuleMode {
    /// Tells the go command to ignore the vendor directory and to automatically
    /// update go.mod, for example, when an imported package is not provided by
    /// any known module.
    Mod,
    /// Tells the go command to ignore the vendor directory and to report an
    /// error if go.mod needs to be updated.
    ReadOnly,
    /// Tells the go command to use the vendor directory. In this mode, the go
    /// command will not use the network or the module cache.
    Vendor,
}

impl std::fmt::Display for ModuleMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Mod => "mod",
            Self::ReadOnly => "readonly",
            Self::Vendor => "vendor",
        })
    }
}

/// Kind of error that was encountered.
#[derive(Clone, Debug)]
enum ErrorKind {
    EnvVarNotFound,
    InvalidGOARCH,
    InvalidGOOS,
    ToolExecError,
}

/// Represents an internal error that occurred, including an explanation.
#[derive(Clone, Debug)]
pub struct Error {
    kind: ErrorKind,
    message: String,
}

impl Error {
    fn new(kind: ErrorKind, message: &str) -> Self {
        Error {
            kind,
            message: message.to_owned(),
        }
    }
}

impl std::error::Error for Error {}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}: {}", self.kind, self.message)
    }
}

fn get_cc() -> PathBuf {
    cc::Build::new().get_compiler().path().to_path_buf()
}

fn get_cxx() -> PathBuf {
    cc::Build::new()
        .cpp(true)
        .get_compiler()
        .path()
        .to_path_buf()
}

fn goarch_from_env() -> Result<String, Error> {
    let target_arch = get_env_var("CARGO_CFG_TARGET_ARCH")?;

    // From the following references:
    // https://doc.rust-lang.org/reference/conditional-compilation.html#target_arch
    // https://go.dev/doc/install/source#environment
    let goarch = match target_arch.as_str() {
        "x86" => "386",
        "x86_64" => "amd64",
        "powerpc64" => "ppc64",
        "aarch64" => "arm64",
        "mips" | "mips64" | "arm" => &target_arch,
        _ => {
            return Err(Error::new(
                ErrorKind::InvalidGOARCH,
                &format!("unexpected target arch {}", target_arch),
            ))
        }
    };
    Ok(goarch.to_string())
}

fn goos_from_env() -> Result<String, Error> {
    let target_os = get_env_var("CARGO_CFG_TARGET_OS")?;

    // From the following references:
    // https://doc.rust-lang.org/reference/conditional-compilation.html#target_os
    // https://go.dev/doc/install/source#environment
    let goos = match target_os.as_str() {
        "macos" => "darwin",
        "windows" | "ios" | "linux" | "android" | "freebsd" | "dragonfly" | "openbsd"
        | "netbsd" => &target_os,
        _ => {
            return Err(Error::new(
                ErrorKind::InvalidGOOS,
                &format!("unexpected target os {}", target_os),
            ))
        }
    };
    Ok(goos.to_string())
}

fn get_env_var(key: &str) -> Result<String, Error> {
    env::var(key).map_err(|_| {
        Error::new(
            ErrorKind::EnvVarNotFound,
            &format!("could not find environment variable {}", key),
        )
    })
}