forked from danielpclark/rutie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.rs
304 lines (254 loc) · 9.78 KB
/
build.rs
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
extern crate pkg_config;
use std::ffi::{OsStr, OsString};
use std::process::Command;
use std::path::Path;
use std::env;
#[cfg(target_os = "windows")]
use std::fs;
macro_rules! ci_stderr_log {
() => (eprint!("\n"));
($($arg:tt)*) => ({
if env::var_os("CI_STDERR_LOG").is_some() { eprintln!($($arg)*) }
})
}
fn rbconfig(key: &str) -> String {
let ruby = match env::var_os("RUBY") {
Some(val) => val.to_os_string(),
None => OsStr::new("ruby").to_os_string(),
};
let config = Command::new(ruby)
.arg("-e")
.arg(format!("print RbConfig::CONFIG['{}']", key))
.output()
.unwrap_or_else(|e| panic!("ruby not found: {}", e));
String::from_utf8(config.stdout).expect("RbConfig value not UTF-8!")
}
fn ruby_name() -> OsString {
match env::var_os("LIBRUBY_NAME") {
Some(name) => name,
None => OsString::from("ruby"),
}
}
fn set_env_pkg_config() {
if env::var_os("PKG_CONFIG_PATH").is_none() {
let key = "PKG_CONFIG_PATH";
let value = Path::new(&rbconfig("libdir")).join("pkgconfig");
std::env::set_var(key, &value);
ci_stderr_log!("Set PKG_CONFIG_PATH to {:?}", value);
}
}
fn trim_teeny(version: &str) -> &str {
version.rsplitn(2, '.').collect::<Vec<&str>>().last().unwrap()
}
fn ruby_version() -> String {
rbconfig("RUBY_PROGRAM_VERSION")
}
fn transform_lib_args(rbconfig_key: &str, replacement: &str) -> String {
rbconfig(rbconfig_key).replace("-l", replacement)
}
// returns a list of the current systems executable paths
#[cfg(not(target_os = "windows"))]
fn path() -> Vec<String> {
env::var_os("PATH").unwrap_or(OsString::new()).
to_string_lossy().split(':').map(|s| s.into()).collect()
}
#[cfg(not(target_os = "windows"))]
fn rvm_path() -> Option<String> {
for p in path() {
if p.contains("rvm/bin") {
return Some(p[0..p.len()-4].to_string())
}
}
return None;
}
#[cfg(not(target_os = "windows"))]
fn rvm_libruby_static_path() -> Option<String> {
let pth = rvm_path();
if pth.is_none() { return None; }
let path = format!("{}/src/ruby-{}", pth.unwrap(), rbconfig("RUBY_PROGRAM_VERSION"));
if !Path::new(&path).exists() { return None; }
if !Path::new(&path).join("libruby-static.a").exists() { return None; }
Some(path)
}
#[cfg(not(target_os = "windows"))]
fn static_ruby_file_name() -> String {
"libruby-static.a".to_string()
}
#[cfg(target_os = "windows")]
fn static_ruby_file_name() -> String {
let libruby_so = rbconfig("LIBRUBY_SO");
let ruby_dll = Path::new(&libruby_so);
let name = ruby_dll.file_stem().unwrap();
format!("{}.lib", name.to_string_lossy())
}
#[cfg(not(target_os = "windows"))]
fn static_ruby_location() -> String {
let location: Option<String> = env::var_os("RUBY_STATIC_PATH").map(|s|s.to_string_lossy().to_string());
let location: String = location.unwrap_or(rvm_libruby_static_path().unwrap_or(rbconfig("libdir")));
if !Path::new(&location).join(static_ruby_file_name()).exists() {
panic!("{} was not found in path but static build was chosen.\n\
Please use environment variable RUBY_STATIC_PATH to define where {} is located.",
static_ruby_file_name(), static_ruby_file_name());
}
location
}
#[cfg(target_os = "windows")]
fn static_ruby_location() -> String {
let location: Option<String> = env::var_os("RUBY_STATIC_PATH").map(|s|s.to_string_lossy().to_string());
let location: String = location.unwrap_or(
Path::new("target").join(env::var_os("PROFILE").unwrap()).join("deps").to_string_lossy().to_string()
);
location
}
#[cfg(not(target_os = "windows"))]
fn windows_static_ruby_dep() {}
// Windows needs ligmp-10.dll as gmp.lib
#[cfg(target_os = "windows")]
fn windows_static_ruby_dep() {
Command::new("build/windows/vcbuild.cmd")
.arg("-arch=x64")
.arg("-host_arch=x64")
.arg("&&")
.arg("dumpbin")
.arg("/exports")
.arg("/out:exports.txt")
.arg(format!("{}/ruby_builtin_dlls/libgmp-10.dll", rbconfig("bindir")))
.output()
.unwrap();
Command::new("build/windows/exports.bat").output().unwrap();
let deps_dir = Path::new("target").join(env::var_os("PROFILE").unwrap()).join("deps");
Command::new("build/windows/vcbuild.cmd")
.arg("-arch=x64")
.arg("-host_arch=x64")
.arg("&&")
.arg("lib")
.arg("/def:exports.def")
.arg("/name:gmp")
.arg(format!("/libpath:{}/ruby_builtin_dlls", rbconfig("bindir")))
.arg("/machine:x64")
.arg(format!("/out:{}/gmp.lib", deps_dir.to_string_lossy()))
.output()
.unwrap();
fs::remove_file("exports.def").expect("couldn't remove exports.def");
fs::remove_file("exports.txt").expect("couldn't remove exports.txt");
}
fn use_static() {
// Ruby removed libruby-static.a by default in https://bugs.ruby-lang.org/issues/12845
// so we'll have to check known locations based on which ruby version manager
// is in use or default install.
println!("cargo:rustc-link-search={}", static_ruby_location());
let static_name = static_ruby_file_name();
let static_name = Path::new(&static_name).file_stem().unwrap().to_string_lossy();
println!("cargo:rustc-link-lib={}", static_name);
// If Windows
windows_static_ruby_dep();
// Ruby gives back the libs in the form: `-lpthread -lgmp`
// Cargo wants them as: `-l pthread -l gmp`
// **Flags must be last in order for linking!**
println!("cargo:rustc-flags={}", transform_lib_args("LIBS", "-l "));
ci_stderr_log!("Using static linker flags");
}
fn use_dylib() {
println!("cargo:rustc-link-search={}", rbconfig("libdir"));
println!("cargo:rustc-link-lib=dylib={}", rbconfig("RUBY_SO_NAME"));
ci_stderr_log!("Using dynamic linker flags");
}
#[cfg(target_os = "windows")]
fn delete<'a>(s: &'a str, from: &'a str) -> String {
let mut result = String::new();
let mut last_end = 0;
for (start, part) in s.match_indices(from) {
result.push_str(unsafe { s.get_unchecked(last_end..start) });
last_end = start + part.len();
}
result.push_str(unsafe { s.get_unchecked(last_end..s.len()) });
result
}
#[cfg(target_os = "windows")]
fn purge_refptr_text() {
let buffer = fs::read_to_string("exports.def")
.expect("Failed to read 'exports.def'");
fs::write("exports.def", delete(&buffer, ".refptr."))
.expect("Failed to write update to 'exports.def'");
}
#[cfg(target_os = "windows")]
fn windows_support() {
println!("cargo:rustc-link-search={}", rbconfig("bindir"));
let mingw_libs: OsString = env::var_os("MINGW_LIBS").unwrap_or(
OsString::from(format!("{}/ruby_builtin_dlls", rbconfig("bindir")))
);
println!("cargo:rustc-link-search={}", mingw_libs.to_string_lossy());
let deps_dir = Path::new("target").join(env::var_os("PROFILE").unwrap()).join("deps");
let libruby_so = rbconfig("LIBRUBY_SO");
let ruby_dll = Path::new(&libruby_so);
let name = ruby_dll.file_stem().unwrap();
let target = deps_dir.join(format!("{}.lib", name.to_string_lossy()));
Command::new("build/windows/vcbuild.cmd")
.arg("-arch=x64")
.arg("-host_arch=x64")
.arg("&&")
.arg("dumpbin")
.arg("/exports")
.arg("/out:exports.txt")
.arg(Path::new(&rbconfig("bindir")).join(&libruby_so))
.output()
.unwrap();
Command::new("build/windows/exports.bat").output().unwrap();
purge_refptr_text();
Command::new("build/windows/vcbuild.cmd")
.arg("-arch=x64")
.arg("-host_arch=x64")
.arg("&&")
.arg("lib")
.arg("/def:exports.def")
.arg(format!("/name:{}", name.to_string_lossy()))
.arg(format!("/libpath:{}", rbconfig("bindir")))
.arg("/machine:x64")
.arg(format!("/out:{}", target.to_string_lossy()))
.output()
.unwrap();
fs::remove_file("exports.def").expect("couldn't remove exports.def");
fs::remove_file("exports.txt").expect("couldn't remove exports.txt");
}
#[cfg(not(target_os = "windows"))]
fn windows_support() {}
fn main() {
// Ruby programs calling Rust doesn't need cc linking
if let None = std::env::var_os("NO_LINK_RUTIE") {
// If windows OS do windows stuff
windows_support();
if env::var_os("RUTIE_NO_PKG_CONFIG").is_none() && env::var_os("RUBY_STATIC").is_none() {
// Ruby often includes pkgconfig under their lib dir
set_env_pkg_config();
let ruby_version = ruby_version();
let version = trim_teeny(&ruby_version);
let ruby_name = ruby_name();
let name = ruby_name.to_str().unwrap_or("ruby");
// To disable the use of pkg-config set the environment variable `RUTIE_NO_PKG_CONFIG`
match pkg_config::Config::new().atleast_version(version).probe(name) {
Ok(_) => {
ci_stderr_log!("pkg-config is being used");
return;
},
Err(err) => ci_stderr_log!("{:?}", err),
}
}
if env::var_os("RUBY_STATIC").is_some() {
ci_stderr_log!("RUBY_STATIC is set");
use_static()
} else {
match rbconfig("ENABLE_SHARED").as_str() {
"no" => use_static(),
"yes" => use_dylib(),
_ => {
let msg = "Error! Couldn't find a valid value for \
RbConfig::CONFIG['ENABLE_SHARED']. \
This may mean that your ruby's build config is corrupted. \
Possible solution: build a new Ruby with the `--enable-shared` configure opt.";
ci_stderr_log!("{}", &msg);
panic!(msg)
}
}
}
}
}