-
Notifications
You must be signed in to change notification settings - Fork 779
/
impl_.rs
2099 lines (1884 loc) · 71.9 KB
/
impl_.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
collections::{HashMap, HashSet},
convert::AsRef,
env,
ffi::{OsStr, OsString},
fmt::Display,
fs::{self, DirEntry},
io::{BufRead, BufReader, Read, Write},
path::{Path, PathBuf},
process::{Command, Stdio},
str,
str::FromStr,
};
use crate::{
bail, ensure,
errors::{Context, Error, Result},
warn,
};
/// Minimum Python version PyO3 supports.
const MINIMUM_SUPPORTED_VERSION: PythonVersion = PythonVersion { major: 3, minor: 7 };
/// Maximum Python version that can be used as minimum required Python version with abi3.
const ABI3_MAX_MINOR: u8 = 10;
/// Gets an environment variable owned by cargo.
///
/// Environment variables set by cargo are expected to be valid UTF8.
pub fn cargo_env_var(var: &str) -> Option<String> {
env::var_os(var).map(|os_string| os_string.to_str().unwrap().into())
}
/// Gets an external environment variable, and registers the build script to rerun if
/// the variable changes.
pub fn env_var(var: &str) -> Option<OsString> {
if cfg!(feature = "resolve-config") {
println!("cargo:rerun-if-env-changed={}", var);
}
env::var_os(var)
}
/// Configuration needed by PyO3 to build for the correct Python implementation.
///
/// Usually this is queried directly from the Python interpreter, or overridden using the
/// `PYO3_CONFIG_FILE` environment variable.
///
/// When the `PYO3_NO_PYTHON` variable is set, or during cross compile situations, then alternative
/// strategies are used to populate this type.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct InterpreterConfig {
/// The Python implementation flavor.
///
/// Serialized to `implementation`.
pub implementation: PythonImplementation,
/// Python `X.Y` version. e.g. `3.9`.
///
/// Serialized to `version`.
pub version: PythonVersion,
/// Whether link library is shared.
///
/// Serialized to `shared`.
pub shared: bool,
/// Whether linking against the stable/limited Python 3 API.
///
/// Serialized to `abi3`.
pub abi3: bool,
/// The name of the link library defining Python.
///
/// This effectively controls the `cargo:rustc-link-lib=<name>` value to
/// control how libpython is linked. Values should not contain the `lib`
/// prefix.
///
/// Serialized to `lib_name`.
pub lib_name: Option<String>,
/// The directory containing the Python library to link against.
///
/// The effectively controls the `cargo:rustc-link-search=native=<path>` value
/// to add an additional library search path for the linker.
///
/// Serialized to `lib_dir`.
pub lib_dir: Option<String>,
/// Path of host `python` executable.
///
/// This is a valid executable capable of running on the host/building machine.
/// For configurations derived by invoking a Python interpreter, it was the
/// executable invoked.
///
/// Serialized to `executable`.
pub executable: Option<String>,
/// Width in bits of pointers on the target machine.
///
/// Serialized to `pointer_width`.
pub pointer_width: Option<u32>,
/// Additional relevant Python build flags / configuration settings.
///
/// Serialized to `build_flags`.
pub build_flags: BuildFlags,
/// Whether to suppress emitting of `cargo:rustc-link-*` lines from the build script.
///
/// Typically, `pyo3`'s build script will emit `cargo:rustc-link-lib=` and
/// `cargo:rustc-link-search=` lines derived from other fields in this struct. In
/// advanced building configurations, the default logic to derive these lines may not
/// be sufficient. This field can be set to `Some(true)` to suppress the emission
/// of these lines.
///
/// If suppression is enabled, `extra_build_script_lines` should contain equivalent
/// functionality or else a build failure is likely.
pub suppress_build_script_link_lines: bool,
/// Additional lines to `println!()` from Cargo build scripts.
///
/// This field can be populated to enable the `pyo3` crate to emit additional lines from its
/// its Cargo build script.
///
/// This crate doesn't populate this field itself. Rather, it is intended to be used with
/// externally provided config files to give them significant control over how the crate
/// is build/configured.
///
/// Serialized to multiple `extra_build_script_line` values.
pub extra_build_script_lines: Vec<String>,
}
impl InterpreterConfig {
#[doc(hidden)]
pub fn emit_pyo3_cfgs(&self) {
// This should have been checked during pyo3-build-config build time.
assert!(self.version >= MINIMUM_SUPPORTED_VERSION);
// pyo3-build-config was released when Python 3.6 was supported, so minimum flag to emit is
// Py_3_6 (to avoid silently breaking users who depend on this cfg).
for i in 6..=self.version.minor {
println!("cargo:rustc-cfg=Py_3_{}", i);
}
if self.implementation.is_pypy() {
println!("cargo:rustc-cfg=PyPy");
if self.abi3 {
warn!(
"PyPy does not yet support abi3 so the build artifacts will be version-specific. \
See https://foss.heptapod.net/pypy/pypy/-/issues/3397 for more information."
);
}
} else if self.abi3 {
println!("cargo:rustc-cfg=Py_LIMITED_API");
}
for flag in &self.build_flags.0 {
println!("cargo:rustc-cfg=py_sys_config=\"{}\"", flag);
}
}
#[doc(hidden)]
pub fn from_interpreter(interpreter: impl AsRef<Path>) -> Result<Self> {
const SCRIPT: &str = r#"
# Allow the script to run on Python 2, so that nicer error can be printed later.
from __future__ import print_function
import os.path
import platform
import struct
import sys
from sysconfig import get_config_var, get_platform
PYPY = platform.python_implementation() == "PyPy"
# sys.base_prefix is missing on Python versions older than 3.3; this allows the script to continue
# so that the version mismatch can be reported in a nicer way later.
base_prefix = getattr(sys, "base_prefix", None)
if base_prefix:
# Anaconda based python distributions have a static python executable, but include
# the shared library. Use the shared library for embedding to avoid rust trying to
# LTO the static library (and failing with newer gcc's, because it is old).
ANACONDA = os.path.exists(os.path.join(base_prefix, "conda-meta"))
else:
ANACONDA = False
def print_if_set(varname, value):
if value is not None:
print(varname, value)
# Windows always uses shared linking
WINDOWS = platform.system() == "Windows"
# macOS framework packages use shared linking
FRAMEWORK = bool(get_config_var("PYTHONFRAMEWORK"))
# unix-style shared library enabled
SHARED = bool(get_config_var("Py_ENABLE_SHARED"))
print("implementation", platform.python_implementation())
print("version_major", sys.version_info[0])
print("version_minor", sys.version_info[1])
print("shared", PYPY or ANACONDA or WINDOWS or FRAMEWORK or SHARED)
print_if_set("ld_version", get_config_var("LDVERSION"))
print_if_set("libdir", get_config_var("LIBDIR"))
print_if_set("base_prefix", base_prefix)
print("executable", sys.executable)
print("calcsize_pointer", struct.calcsize("P"))
print("mingw", get_platform().startswith("mingw"))
"#;
let output = run_python_script(interpreter.as_ref(), SCRIPT)?;
let map: HashMap<String, String> = parse_script_output(&output);
let shared = map["shared"].as_str() == "True";
let version = PythonVersion {
major: map["version_major"]
.parse()
.context("failed to parse major version")?,
minor: map["version_minor"]
.parse()
.context("failed to parse minor version")?,
};
let abi3 = is_abi3();
let implementation = map["implementation"].parse()?;
let lib_name = if cfg!(windows) {
default_lib_name_windows(
version,
implementation,
abi3,
map["mingw"].as_str() == "True",
)
} else {
default_lib_name_unix(
version,
implementation,
map.get("ld_version").map(String::as_str),
)
};
let lib_dir = if cfg!(windows) {
map.get("base_prefix")
.map(|base_prefix| format!("{}\\libs", base_prefix))
} else {
map.get("libdir").cloned()
};
// The reason we don't use platform.architecture() here is that it's not
// reliable on macOS. See https://stackoverflow.com/a/1405971/823869.
// Similarly, sys.maxsize is not reliable on Windows. See
// https://stackoverflow.com/questions/1405913/how-do-i-determine-if-my-python-shell-is-executing-in-32bit-or-64bit-mode-on-os/1405971#comment6209952_1405971
// and https://stackoverflow.com/a/3411134/823869.
let calcsize_pointer: u32 = map["calcsize_pointer"]
.parse()
.context("failed to parse calcsize_pointer")?;
Ok(InterpreterConfig {
version,
implementation,
shared,
abi3,
lib_name: Some(lib_name),
lib_dir,
executable: map.get("executable").cloned(),
pointer_width: Some(calcsize_pointer * 8),
build_flags: BuildFlags::from_interpreter(interpreter)?.fixup(version),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
})
}
/// Generate from parsed sysconfigdata file
///
/// Use [`parse_sysconfigdata`] to generate a hash map of configuration values which may be
/// used to build an [`InterpreterConfig`].
pub fn from_sysconfigdata(sysconfigdata: &Sysconfigdata) -> Result<Self> {
macro_rules! get_key {
($sysconfigdata:expr, $key:literal) => {
$sysconfigdata
.get_value($key)
.ok_or(concat!($key, " not found in sysconfigdata file"))
};
}
macro_rules! parse_key {
($sysconfigdata:expr, $key:literal) => {
get_key!($sysconfigdata, $key)?
.parse()
.context(concat!("could not parse value of ", $key))
};
}
let soabi = get_key!(sysconfigdata, "SOABI")?;
let implementation = PythonImplementation::from_soabi(soabi)?;
let version = parse_key!(sysconfigdata, "VERSION")?;
let shared = match sysconfigdata.get_value("Py_ENABLE_SHARED") {
Some("1") | Some("true") | Some("True") => true,
Some("0") | Some("false") | Some("False") => false,
_ => bail!("expected a bool (1/true/True or 0/false/False) for Py_ENABLE_SHARED"),
};
// macOS framework packages use shared linking (PYTHONFRAMEWORK is the framework name, hence the empty check)
let framework = match sysconfigdata.get_value("PYTHONFRAMEWORK") {
Some(s) => !s.is_empty(),
_ => false,
};
let lib_dir = get_key!(sysconfigdata, "LIBDIR").ok().map(str::to_string);
let lib_name = Some(default_lib_name_unix(
version,
implementation,
sysconfigdata.get_value("LDVERSION"),
));
let pointer_width = parse_key!(sysconfigdata, "SIZEOF_VOID_P")
.map(|bytes_width: u32| bytes_width * 8)
.ok();
let build_flags = BuildFlags::from_sysconfigdata(sysconfigdata).fixup(version);
Ok(InterpreterConfig {
implementation,
version,
shared: shared || framework,
abi3: is_abi3(),
lib_dir,
lib_name,
executable: None,
pointer_width,
build_flags,
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
})
}
#[doc(hidden)]
pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
let config_file = std::fs::File::open(path)
.with_context(|| format!("failed to open PyO3 config file at {}", path.display()))?;
let reader = std::io::BufReader::new(config_file);
InterpreterConfig::from_reader(reader)
}
#[doc(hidden)]
pub fn from_cargo_dep_env() -> Option<Result<Self>> {
cargo_env_var("DEP_PYTHON_PYO3_CONFIG")
.map(|buf| InterpreterConfig::from_reader(buf.replace("\\n", "\n").as_bytes()))
}
#[doc(hidden)]
pub fn from_reader(reader: impl Read) -> Result<Self> {
let reader = BufReader::new(reader);
let lines = reader.lines();
macro_rules! parse_value {
($variable:ident, $value:ident) => {
$variable = Some($value.trim().parse().context(format!(
concat!(
"failed to parse ",
stringify!($variable),
" from config value '{}'"
),
$value
))?)
};
}
let mut implementation = None;
let mut version = None;
let mut shared = None;
let mut abi3 = None;
let mut lib_name = None;
let mut lib_dir = None;
let mut executable = None;
let mut pointer_width = None;
let mut build_flags = None;
let mut suppress_build_script_link_lines = None;
let mut extra_build_script_lines = vec![];
for (i, line) in lines.enumerate() {
let line = line.context("failed to read line from config")?;
let mut split = line.splitn(2, '=');
let (key, value) = (
split
.next()
.expect("first splitn value should always be present"),
split
.next()
.ok_or_else(|| format!("expected key=value pair on line {}", i + 1))?,
);
match key {
"implementation" => parse_value!(implementation, value),
"version" => parse_value!(version, value),
"shared" => parse_value!(shared, value),
"abi3" => parse_value!(abi3, value),
"lib_name" => parse_value!(lib_name, value),
"lib_dir" => parse_value!(lib_dir, value),
"executable" => parse_value!(executable, value),
"pointer_width" => parse_value!(pointer_width, value),
"build_flags" => parse_value!(build_flags, value),
"suppress_build_script_link_lines" => {
parse_value!(suppress_build_script_link_lines, value)
}
"extra_build_script_line" => {
extra_build_script_lines.push(value.to_string());
}
unknown => bail!("unknown config key `{}`", unknown),
}
}
let version = version.ok_or("missing value for version")?;
let implementation = implementation.unwrap_or(PythonImplementation::CPython);
let abi3 = abi3.unwrap_or(false);
Ok(InterpreterConfig {
implementation,
version,
shared: shared.unwrap_or(true),
abi3,
lib_name,
lib_dir,
executable,
pointer_width,
build_flags: build_flags.unwrap_or_default(),
suppress_build_script_link_lines: suppress_build_script_link_lines.unwrap_or(false),
extra_build_script_lines,
})
}
#[doc(hidden)]
/// Serialize the `InterpreterConfig` and print it to the environment for Cargo to pass along
/// to dependent packages during build time.
///
/// NB: writing to the cargo environment requires the
/// [`links`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#the-links-manifest-key)
/// manifest key to be set. In this case that means this is called by the `pyo3-ffi` crate and
/// available for dependent package build scripts in `DEP_PYTHON_PYO3_CONFIG`. See
/// documentation for the
/// [`DEP_<name>_<key>`](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts)
/// environment variable.
pub fn to_cargo_dep_env(&self) -> Result<()> {
let mut buf = Vec::new();
self.to_writer(&mut buf)?;
// escape newlines in env var
if let Ok(config) = str::from_utf8(&buf) {
println!("cargo:PYO3_CONFIG={}", config.replace('\n', "\\n"));
} else {
bail!("unable to emit interpreter config to link env for downstream use");
}
Ok(())
}
#[doc(hidden)]
pub fn to_writer(&self, mut writer: impl Write) -> Result<()> {
macro_rules! write_line {
($value:ident) => {
writeln!(writer, "{}={}", stringify!($value), self.$value).context(concat!(
"failed to write ",
stringify!($value),
" to config"
))
};
}
macro_rules! write_option_line {
($value:ident) => {
if let Some(value) = &self.$value {
writeln!(writer, "{}={}", stringify!($value), value).context(concat!(
"failed to write ",
stringify!($value),
" to config"
))
} else {
Ok(())
}
};
}
write_line!(implementation)?;
write_line!(version)?;
write_line!(shared)?;
write_line!(abi3)?;
write_option_line!(lib_name)?;
write_option_line!(lib_dir)?;
write_option_line!(executable)?;
write_option_line!(pointer_width)?;
write_line!(build_flags)?;
write_line!(suppress_build_script_link_lines)?;
for line in &self.extra_build_script_lines {
writeln!(writer, "extra_build_script_line={}", line)
.context("failed to write extra_build_script_line")?;
}
Ok(())
}
/// Run a python script using the [`InterpreterConfig::executable`].
///
/// # Panics
///
/// This function will panic if the [`executable`](InterpreterConfig::executable) is `None`.
pub fn run_python_script(&self, script: &str) -> Result<String> {
run_python_script_with_envs(
Path::new(self.executable.as_ref().expect("no interpreter executable")),
script,
std::iter::empty::<(&str, &str)>(),
)
}
/// Run a python script using the [`InterpreterConfig::executable`] with additional
/// environment variables (e.g. PYTHONPATH) set.
///
/// # Panics
///
/// This function will panic if the [`executable`](InterpreterConfig::executable) is `None`.
pub fn run_python_script_with_envs<I, K, V>(&self, script: &str, envs: I) -> Result<String>
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
run_python_script_with_envs(
Path::new(self.executable.as_ref().expect("no interpreter executable")),
script,
envs,
)
}
/// Lowers the configured version to the abi3 version, if set.
fn fixup_for_abi3_version(&mut self, abi3_version: Option<PythonVersion>) -> Result<()> {
// PyPy doesn't support abi3; don't adjust the version
if self.implementation.is_pypy() {
return Ok(());
}
if let Some(version) = abi3_version {
ensure!(
version <= self.version,
"cannot set a minimum Python version {} higher than the interpreter version {} \
(the minimum Python version is implied by the abi3-py3{} feature)",
version,
self.version,
version.minor,
);
self.version = version;
}
Ok(())
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PythonVersion {
pub major: u8,
pub minor: u8,
}
impl PythonVersion {
const PY37: Self = PythonVersion { major: 3, minor: 7 };
}
impl Display for PythonVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}", self.major, self.minor)
}
}
impl FromStr for PythonVersion {
type Err = crate::errors::Error;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let mut split = value.splitn(2, '.');
let (major, minor) = (
split
.next()
.expect("first splitn value should always be present"),
split.next().ok_or("expected major.minor version")?,
);
Ok(Self {
major: major.parse().context("failed to parse major version")?,
minor: minor.parse().context("failed to parse minor version")?,
})
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum PythonImplementation {
CPython,
PyPy,
}
impl PythonImplementation {
#[doc(hidden)]
pub fn is_pypy(self) -> bool {
self == PythonImplementation::PyPy
}
#[doc(hidden)]
pub fn from_soabi(soabi: &str) -> Result<Self> {
if soabi.starts_with("pypy") {
Ok(PythonImplementation::PyPy)
} else if soabi.starts_with("cpython") {
Ok(PythonImplementation::CPython)
} else {
bail!("unsupported Python interpreter");
}
}
}
impl Display for PythonImplementation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PythonImplementation::CPython => write!(f, "CPython"),
PythonImplementation::PyPy => write!(f, "PyPy"),
}
}
}
impl FromStr for PythonImplementation {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"CPython" => Ok(PythonImplementation::CPython),
"PyPy" => Ok(PythonImplementation::PyPy),
_ => bail!("unknown interpreter: {}", s),
}
}
}
/// Checks if the `abi3` feature is enabled for the PyO3 crate.
///
/// Must be called from a PyO3 crate build script.
pub fn is_abi3() -> bool {
cargo_env_var("CARGO_FEATURE_ABI3").is_some()
}
/// Gets the minimum supported Python version from PyO3 `abi3-py*` features.
///
/// Must be called from a PyO3 crate build script.
pub fn get_abi3_version() -> Option<PythonVersion> {
let minor_version = (MINIMUM_SUPPORTED_VERSION.minor..=ABI3_MAX_MINOR)
.find(|i| cargo_env_var(&format!("CARGO_FEATURE_ABI3_PY3{}", i)).is_some());
minor_version.map(|minor| PythonVersion { major: 3, minor })
}
/// Checks if the `extension-module` feature is enabled for the PyO3 crate.
///
/// Must be called from a PyO3 crate build script.
pub fn is_extension_module() -> bool {
cargo_env_var("CARGO_FEATURE_EXTENSION_MODULE").is_some()
}
/// Checks if we need to link to `libpython` for the current build target.
///
/// Must be called from a crate PyO3 build script.
pub fn is_linking_libpython() -> bool {
let target = TargetInfo::from_cargo_env().expect("must be called from a build script");
target.os == "windows" || target.os == "android" || !is_extension_module()
}
#[derive(Debug, PartialEq)]
struct TargetInfo {
/// The `arch` component of the compilation target triple.
///
/// e.g. x86_64, aarch64, x86, arm, thumb, mips, etc.
arch: String,
/// The `vendor` component of the compilation target triple.
///
/// e.g. apple, pc, unknown, etc.
vendor: String,
/// The `os` component of the compilation target triple.
///
/// e.g. darwin, freebsd, linux, windows, etc.
os: String,
/// The optional `env` component of the compilation target triple.
///
/// e.g. gnu, musl, msvc, etc.
env: Option<String>,
}
impl TargetInfo {
fn from_triple(arch: &str, vendor: &str, os: &str, env: Option<&str>) -> Self {
TargetInfo {
arch: arch.to_owned(),
vendor: vendor.to_owned(),
os: os.to_owned(),
env: env.map(|s| s.to_owned()),
}
}
/// Gets the compile target from the Cargo environment.
///
/// Must be called from a build script.
fn from_cargo_env() -> Result<Self> {
Ok(Self {
arch: cargo_env_var("CARGO_CFG_TARGET_ARCH")
.ok_or("expected CARGO_CFG_TARGET_ARCH env var")?,
vendor: cargo_env_var("CARGO_CFG_TARGET_VENDOR")
.ok_or("expected CARGO_CFG_TARGET_VENDOR env var")?,
os: cargo_env_var("CARGO_CFG_TARGET_OS")
.ok_or("expected CARGO_CFG_TARGET_OS env var")?,
env: cargo_env_var("CARGO_CFG_TARGET_ENV"),
})
}
fn to_target_triple(&self) -> String {
format!(
"{}-{}-{}",
if self.arch == "x86" {
"i686"
} else {
&self.arch
},
self.vendor,
if self.os == "macos" {
"darwin"
} else {
&self.os
}
)
}
fn is_cross_compiling_from(&self, host: &str) -> bool {
let target_triple = self.to_target_triple();
// Not cross-compiling if arch-vendor-os is all the same
// e.g. x86_64-unknown-linux-musl on x86_64-unknown-linux-gnu host
// x86_64-pc-windows-gnu on x86_64-pc-windows-msvc host
let host_target_compatible = host.starts_with(&target_triple)
// Not cross-compiling to compile for 32-bit Python from windows 64-bit
|| (target_triple == "i686-pc-windows" && host.starts_with("x86_64-pc-windows"))
// Not cross-compiling to compile for x86-64 Python from macOS arm64
|| (target_triple == "x86_64-apple-darwin" && host == "aarch64-apple-darwin")
// Not cross-compiling to compile for arm64 Python from macOS x86_64
|| (target_triple == "aarch64-apple-darwin" && host == "x86_64-apple-darwin");
// Cross compiling if not compiler compatible
!host_target_compatible
}
fn is_windows(&self) -> bool {
self.os == "windows"
}
fn is_windows_mingw(&self) -> bool {
self.is_windows() && self.env.as_ref().map_or(false, |env| env == "gnu")
}
}
/// Configuration needed by PyO3 to cross-compile for a target platform.
///
/// Usually this is collected from the environment (i.e. `PYO3_CROSS_*` and `CARGO_CFG_TARGET_*`)
/// when a cross-compilation configuration is detected.
#[derive(Debug, PartialEq)]
pub struct CrossCompileConfig {
/// The directory containing the Python library to link against.
pub lib_dir: Option<PathBuf>,
/// The version of the Python library to link against.
version: Option<PythonVersion>,
/// The target information
target_info: TargetInfo,
}
impl CrossCompileConfig {
/// Creates a new cross compile config struct from PyO3 environment variables
/// and the build environment when cross compilation mode is detected.
///
/// Returns `None` when not cross compiling.
fn try_from_env_vars(
env_vars: CrossCompileEnvVars,
host: &str,
target_info: TargetInfo,
) -> Result<Option<Self>> {
let maybe_config = if env_vars.any() || target_info.is_cross_compiling_from(host) {
let lib_dir = env_vars.lib_dir_path()?;
let version = env_vars.parse_version()?;
Some(CrossCompileConfig {
lib_dir,
target_info,
version,
})
} else {
None
};
Ok(maybe_config)
}
/// Converts `lib_dir` member field to an UTF-8 string.
///
/// The conversion can not fail because `PYO3_CROSS_LIB_DIR` variable
/// is ensured to be valid UTF-8 bytes.
fn lib_dir_string(&self) -> Option<String> {
self.lib_dir
.as_ref()
.map(|s| s.to_str().unwrap().to_owned())
}
}
pub(crate) struct CrossCompileEnvVars {
pyo3_cross: Option<OsString>,
pyo3_cross_lib_dir: Option<OsString>,
pyo3_cross_python_version: Option<OsString>,
}
impl CrossCompileEnvVars {
pub fn any(&self) -> bool {
self.pyo3_cross.is_some()
|| self.pyo3_cross_lib_dir.is_some()
|| self.pyo3_cross_python_version.is_some()
}
/// Converts the stored `PYO3_CROSS_LIB_DIR` variable value (if any)
/// into a `PathBuf` instance.
///
/// Ensures that the path is a valid UTF-8 string.
fn lib_dir_path(&self) -> Result<Option<PathBuf>> {
let lib_dir = self.pyo3_cross_lib_dir.as_ref().map(PathBuf::from);
if let Some(dir) = lib_dir.as_ref() {
if dir.to_str().is_none() {
bail!("PYO3_CROSS_LIB_DIR is not valid UTF-8");
}
}
Ok(lib_dir)
}
fn parse_version(&self) -> Result<Option<PythonVersion>> {
let version = self
.pyo3_cross_python_version
.as_ref()
.map(|os_string| {
let utf8_str = os_string
.to_str()
.ok_or("PYO3_CROSS_PYTHON_VERSION is not valid UTF-8")?;
utf8_str
.parse()
.context("failed to parse PYO3_CROSS_PYTHON_VERSION")
})
.transpose()?;
Ok(version)
}
}
pub(crate) fn cross_compile_env_vars() -> CrossCompileEnvVars {
CrossCompileEnvVars {
pyo3_cross: env::var_os("PYO3_CROSS"),
pyo3_cross_lib_dir: env::var_os("PYO3_CROSS_LIB_DIR"),
pyo3_cross_python_version: env::var_os("PYO3_CROSS_PYTHON_VERSION"),
}
}
/// Detect whether we are cross compiling and return an assembled CrossCompileConfig if so.
///
/// This function relies on PyO3 cross-compiling environment variables:
///
/// * `PYO3_CROSS`: If present, forces PyO3 to configure as a cross-compilation.
/// * `PYO3_CROSS_LIB_DIR`: If present, must be set to the directory containing
/// the target's libpython DSO and the associated `_sysconfigdata*.py` file for
/// Unix-like targets, or the Python DLL import libraries for the Windows target.
/// * `PYO3_CROSS_PYTHON_VERSION`: Major and minor version (e.g. 3.9) of the target Python
/// installation. This variable is only needed if PyO3 cannnot determine the version to target
/// from `abi3-py3*` features, or if there are multiple versions of Python present in
/// `PYO3_CROSS_LIB_DIR`.
///
/// See the [PyO3 User Guide](https://pyo3.rs/) for more info on cross-compiling.
pub fn cross_compiling(
host: &str,
target_arch: &str,
target_vendor: &str,
target_os: &str,
) -> Result<Option<CrossCompileConfig>> {
let env_vars = cross_compile_env_vars();
let target_info = TargetInfo::from_triple(target_arch, target_vendor, target_os, None);
CrossCompileConfig::try_from_env_vars(env_vars, host, target_info)
}
/// Detect whether we are cross compiling from Cargo and `PYO3_CROSS_*` environment
/// variables and return an assembled `CrossCompileConfig` if so.
///
/// This must be called from PyO3's build script, because it relies on environment
/// variables such as `CARGO_CFG_TARGET_OS` which aren't available at any other time.
pub fn cross_compiling_from_cargo_env() -> Result<Option<CrossCompileConfig>> {
let env_vars = cross_compile_env_vars();
let host = cargo_env_var("HOST").ok_or("expected HOST env var")?;
let target_info = TargetInfo::from_cargo_env()?;
CrossCompileConfig::try_from_env_vars(env_vars, &host, target_info)
}
#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum BuildFlag {
Py_DEBUG,
Py_REF_DEBUG,
Py_TRACE_REFS,
COUNT_ALLOCS,
Other(String),
}
impl Display for BuildFlag {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BuildFlag::Other(flag) => write!(f, "{}", flag),
_ => write!(f, "{:?}", self),
}
}
}
impl FromStr for BuildFlag {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Py_DEBUG" => Ok(BuildFlag::Py_DEBUG),
"Py_REF_DEBUG" => Ok(BuildFlag::Py_REF_DEBUG),
"Py_TRACE_REFS" => Ok(BuildFlag::Py_TRACE_REFS),
"COUNT_ALLOCS" => Ok(BuildFlag::COUNT_ALLOCS),
other => Ok(BuildFlag::Other(other.to_owned())),
}
}
}
/// A list of python interpreter compile-time preprocessor defines that
/// we will pick up and pass to rustc via `--cfg=py_sys_config={varname}`;
/// this allows using them conditional cfg attributes in the .rs files, so
///
/// ```rust
/// #[cfg(py_sys_config="{varname}")]
/// # struct Foo;
/// ```
///
/// is the equivalent of `#ifdef {varname}` in C.
///
/// see Misc/SpecialBuilds.txt in the python source for what these mean.
#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Clone, Default)]
pub struct BuildFlags(pub HashSet<BuildFlag>);
impl BuildFlags {
const ALL: [BuildFlag; 4] = [
BuildFlag::Py_DEBUG,
BuildFlag::Py_REF_DEBUG,
BuildFlag::Py_TRACE_REFS,
BuildFlag::COUNT_ALLOCS,
];
pub fn new() -> Self {
BuildFlags(HashSet::new())
}
fn from_sysconfigdata(config_map: &Sysconfigdata) -> Self {
Self(
BuildFlags::ALL
.iter()
.cloned()
.filter(|flag| {
config_map
.get_value(&flag.to_string())
.map_or(false, |value| value == "1")
})
.collect(),
)
}
/// Examine python's compile flags to pass to cfg by launching
/// the interpreter and printing variables of interest from
/// sysconfig.get_config_vars.
fn from_interpreter(interpreter: impl AsRef<Path>) -> Result<Self> {
// sysconfig is missing all the flags on windows, so we can't actually
// query the interpreter directly for its build flags.
if cfg!(windows) {
return Ok(Self::new());
}
let mut script = String::from("import sysconfig\n");
script.push_str("config = sysconfig.get_config_vars()\n");
for k in &BuildFlags::ALL {
script.push_str(&format!("print(config.get('{}', '0'))\n", k));
}
let stdout = run_python_script(interpreter.as_ref(), &script)?;
let split_stdout: Vec<&str> = stdout.trim_end().lines().collect();
ensure!(
split_stdout.len() == BuildFlags::ALL.len(),
"Python stdout len didn't return expected number of lines: {}",
split_stdout.len()
);
let flags = BuildFlags::ALL
.iter()