forked from model-checking/kani
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup.rs
209 lines (172 loc) · 7.4 KB
/
setup.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
// Copyright Kani Contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! This module contains all first-time setup code done as part of `cargo kani setup`.
use std::env;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{bail, Context, Result};
use crate::cmd::AutoRun;
use crate::os_hacks;
/// Comes from our Cargo.toml manifest file. Must correspond to our release verion.
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// Set by our `build.rs`, reflects the Rust target triple we're building for
const TARGET: &str = env!("TARGET");
/// The directory where Kani is installed, either:
/// * (custom) `${KANI_HOME}/kani-<VERSION>` if the environment variable
/// `KANI_HOME` is set.
/// * (default) `${HOME}/.kani/kani-<VERSION>` where `HOME` is the canonical
/// definition of home directory used by Cargo and rustup.
pub fn kani_dir() -> Result<PathBuf> {
let kani_dir = match env::var("KANI_HOME") {
Ok(val) => custom_kani_dir(val),
Err(_) => default_kani_dir()?,
};
let kani_dir = kani_dir.join(format!("kani-{VERSION}"));
Ok(kani_dir)
}
/// Returns the custom Kani home directory: `${KANI_HOME}`
fn custom_kani_dir(path: String) -> PathBuf {
// We don't check if it doesn't exist since we create it later
PathBuf::from(path)
}
/// Returns the default Kani home directory: `${HOME}/.kani`
fn default_kani_dir() -> Result<PathBuf> {
let home_dir = home::home_dir().expect("couldn't find home directory");
if !home_dir.is_dir() {
bail!("got home directory `{}` which isn't a directory", home_dir.display());
}
let kani_dir = home_dir.join(".kani");
Ok(kani_dir)
}
/// Fast check to see if we look setup already
pub fn appears_setup() -> bool {
kani_dir().expect("couldn't find kani directory").exists()
}
// Ensure that the tar file does not exist, essentially using its presence
// to detect setup completion as if it were a lock file.
pub fn appears_incomplete() -> Option<PathBuf> {
let kani_dir = kani_dir().expect("couldn't find kani directory");
let kani_dir_parent = kani_dir.parent().unwrap();
for entry in std::fs::read_dir(kani_dir_parent).ok()?.flatten() {
if let Some(file_name) = entry.file_name().to_str() {
if file_name.ends_with(".tar.gz") {
return Some(kani_dir_parent.join(file_name));
}
}
}
None
}
/// Sets up Kani by unpacking/installing to `~/.kani/kani-VERSION`
pub fn setup(use_local_bundle: Option<OsString>) -> Result<()> {
let kani_dir = kani_dir()?;
let os = os_info::get();
println!("[0/5] Running Kani first-time setup...");
println!("[1/5] Ensuring the existence of: {}", kani_dir.display());
std::fs::create_dir_all(&kani_dir)?;
setup_kani_bundle(&kani_dir, use_local_bundle)?;
setup_rust_toolchain(&kani_dir)?;
setup_python_deps(&kani_dir)?;
os_hacks::setup_os_hacks(&kani_dir, &os)?;
println!("[5/5] Successfully completed Kani first-time setup.");
Ok(())
}
/// Download and unpack the Kani release bundle
fn setup_kani_bundle(kani_dir: &Path, use_local_bundle: Option<OsString>) -> Result<()> {
// e.g. `~/.kani/`
let base_dir = kani_dir.parent().expect("No base directory?");
if let Some(pathstr) = use_local_bundle {
println!("[2/5] Installing local Kani bundle: {}", pathstr.to_string_lossy());
let path = Path::new(&pathstr).canonicalize()?;
// When given a local bundle, it's often "-latest" but we expect "-1.0" or something.
// tar supports "stripping" the first directory from the bundle, so do that and
// extract it directly into the expected (kani_dir) directory (instead of base_dir).
Command::new("tar")
.arg("--strip-components=1")
.arg("-zxf")
.arg(&path)
.current_dir(kani_dir)
.run()
.context(
"Failed to extract tar file, try removing Kani setup located in .kani in your home directory and restarting",
)?;
} else {
let filename = download_filename();
println!("[2/5] Downloading Kani release bundle: {}", &filename);
fail_if_unsupported_target()?;
let bundle = base_dir.join(filename);
Command::new("curl")
.args(["-sSLf", "-o"])
.arg(&bundle)
.arg(download_url())
.run()
.context("Failed to download Kani release bundle")?;
Command::new("tar").arg("zxf").arg(&bundle).current_dir(base_dir).run()?;
std::fs::remove_file(bundle)?;
}
Ok(())
}
/// Reads the Rust toolchain version that Kani was built against from the file in
/// the Kani release bundle (unpacked in `kani_dir`).
pub(crate) fn get_rust_toolchain_version(kani_dir: &Path) -> Result<String> {
std::fs::read_to_string(kani_dir.join("rust-toolchain-version"))
.context("Reading release bundle rust-toolchain-version")
}
/// Install the Rust toolchain version we require
fn setup_rust_toolchain(kani_dir: &Path) -> Result<String> {
// Currently this means we require the bundle to have been unpacked first!
let toolchain_version = get_rust_toolchain_version(kani_dir)?;
println!("[3/5] Installing rust toolchain version: {}", &toolchain_version);
Command::new("rustup").args(["toolchain", "install", &toolchain_version]).run()?;
let toolchain = home::rustup_home()?.join("toolchains").join(&toolchain_version);
symlink_rust_toolchain(&toolchain, kani_dir)?;
Ok(toolchain_version)
}
/// Install into the pyroot the python dependencies we need
fn setup_python_deps(kani_dir: &Path) -> Result<()> {
println!("[4/5] Installing Kani python dependencies...");
let pyroot = kani_dir.join("pyroot");
// TODO: this is a repetition of versions from kani/kani-dependencies
let pkg_versions = &["cbmc-viewer==3.8"];
Command::new("python3")
.args(["-m", "pip", "install", "--target"])
.arg(&pyroot)
.args(pkg_versions)
.run()?;
Ok(())
}
// This ends the setup steps above.
//
// Just putting a bit of space between that and the helper functions below.
/// The filename of the release bundle
fn download_filename() -> String {
format!("kani-{VERSION}-{TARGET}.tar.gz")
}
/// The download URL for this version of Kani
fn download_url() -> String {
let tag: &str = &format!("kani-{VERSION}");
let file: &str = &download_filename();
format!("https://github.com/model-checking/kani/releases/download/{tag}/{file}")
}
/// Give users a better error message than "404" if we're on an unsupported platform.
/// This is called just before we try to download the release bundle.
fn fail_if_unsupported_target() -> Result<()> {
// This is basically going to be reduced to a compile-time constant
match TARGET {
"x86_64-unknown-linux-gnu"
| "x86_64-apple-darwin"
| "aarch64-unknown-linux-gnu"
| "aarch64-apple-darwin" => Ok(()),
_ => bail!("Kani does not support this platform (Rust target {})", TARGET),
}
}
/// Creates a `kani_dir/toolchain` symlink pointing to `toolchain`.
fn symlink_rust_toolchain(toolchain: &Path, kani_dir: &Path) -> Result<()> {
let path = kani_dir.join("toolchain");
// We want setup to be idempotent, so if the symlink already exists, delete instead of failing
if path.exists() && path.is_symlink() {
std::fs::remove_file(&path)?;
}
std::os::unix::fs::symlink(toolchain, path)?;
Ok(())
}