vendor: Add vendored dependencies

We use cargo vendor to generate a .cargo/config file and the vendor
directory. Vendoring allows us to lock our dependencies and to modify
them easily from the top level Cargo.toml.

We vendor all dependencies, including the crates.io ones, which allows
for network isolated builds.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
This commit is contained in:
Samuel Ortiz
2019-06-03 16:40:09 +02:00
parent e3f7bc2e9d
commit d5f5648b37
4062 changed files with 442206 additions and 2 deletions

View File

@@ -0,0 +1,5 @@
#!/bin/bash
wget http://mirror.centos.org/centos/7/os/x86_64/Packages/kernel-3.10.0-957.el7.x86_64.rpm
rpm2cpio kernel-3.10.0-957.el7.x86_64.rpm | cpio -idmv ./boot/vmlinuz-3.10.0-957.el7.x86_64

View File

@@ -0,0 +1,109 @@
steps:
- label: "build-gnu-x86"
commands:
- cargo build --release
retry:
automatic: false
agents:
platform: x86_64.metal
plugins:
- docker#v3.0.1:
image: "fandree/rust-vmm-dev"
always-pull: true
- label: "style"
command: cargo fmt --all -- --check
retry:
automatic: false
agents:
platform: x86_64.metal
plugins:
- docker#v3.0.1:
image: "fandree/rust-vmm-dev"
always-pull: true
- label: "unittests-gnu-x86"
commands:
- cargo test
retry:
automatic: false
agents:
platform: x86_64.metal
plugins:
- docker#v3.0.1:
privileged: true
image: "fandree/rust-vmm-dev"
always-pull: true
- label: "build-gnu-x86-elf"
commands:
- cargo build --release --features elf
retry:
automatic: false
agents:
platform: x86_64.metal
plugins:
- docker#v3.0.1:
image: "fandree/rust-vmm-dev"
always-pull: true
- label: "unittests-gnu-x86-elf"
commands:
- cargo test --features elf
retry:
automatic: false
agents:
platform: x86_64.metal
plugins:
- docker#v3.0.1:
privileged: true
image: "fandree/rust-vmm-dev"
- label: "build-gnu-x86-bzImage"
commands:
- cargo build --release --features bzImage
retry:
automatic: false
agents:
platform: x86_64.metal
plugins:
- docker#v3.0.1:
image: "fandree/rust-vmm-dev"
always-pull: true
- label: "unittests-gnu-x86-bzImage"
commands:
- cargo test --features bzImage
retry:
automatic: false
agents:
platform: x86_64.metal
plugins:
- docker#v3.0.1:
privileged: true
image: "fandree/rust-vmm-dev"
- label: "clippy-x86"
commands:
- cargo clippy --all -- -D warnings
retry:
automatic: false
agents:
platform: x86_64.metal
plugins:
- docker#v3.0.1:
image: "fandree/rust-vmm-dev"
always-pull: true
- label: "coverage-x86"
commands:
- pytest tests/test_coverage.py
retry:
automatic: false
agents:
platform: x86_64.metal
plugins:
- docker#v3.0.1:
privileged: true
image: "fandree/rust-vmm-dev"
always-pull: true

View File

@@ -0,0 +1 @@
{"files":{".buildkite/hooks/post-checkout":"4433e2001686837e6bd1a6baef67daacd07434817a04fcb7df8332ee16c51740",".buildkite/pipeline.yml":"8d0550f4a793c4b056189e0612afc50d6d8a686535ee81262318ae33d72611e3",".gitignore/.gitignore":"6b937008e0a58a438c32574627db6961a4d2aff4bf5c703d4e45cb56ef3b168a","Cargo.toml":"f2754a32f2dacc0f8695ee9780193badc85995954ed452d0df4ca1ef8517d089","DESIGN.md":"d877f3093cf94402528a54a97e833fc79d4cbc07934031035f60a2d8d0a542d4","LICENSE-APACHE":"000b4962e6b27176a0ff89cce4be555b16472cafb5671eb2804a8fdac6854793","LICENSE-BSD-3-Clause":"a6d3ebd1c2f37d4fd83d0676621f695fc0cc2d8c6e646cdbb831b46e0650c208","README.md":"3e585f0ceb915bf4734075d2f0a91b626ff2363079baebcf7592a8d51d2c7931","src/cmdline/mod.rs":"30f57b492618155be6129311d0182688e5d1ecd9a3b5fdc9b742cd0c0e1f85da","src/lib.rs":"67d3e4a9ed48495c00fe6698fc606693b15a006fb0599cb18b946ea3929cd0f6","src/loader/bootparam.rs":"054b5a196873965cb48b9e9fa99c2505f523f9c71ca8ca0fad3af02491811fe6","src/loader/elf.rs":"f4e4eb6ffcb114bbf3242a9c72ea7e99631487d63bbbfbcf641bea42b3aba2e1","src/loader/mod.rs":"6bc6b4f5e90cbf15f554c3c0e4752226794053fc4c0781a7a7828124de1b1ec7","src/loader/struct_util.rs":"a98c2854ebd3a0c0ed11e01e474f2da15fb9200754129223710d62cc88ab253a","src/loader/test_elf.bin":"dda390f7546c7ba36bab412a93add96533806154824b77aafc8c153231f3f161","tests/conftest.py":"ee2baacd9da7ac04ffbfd580a7d4fe8a8b166a16e1eeed2d488f7b820abab433","tests/coverage":"69eaa47e0089d5a3e2844fe7ca823b67ff712e382f6c34b0300797a415b7f3e9","tests/test_coverage.py":"2f4bbb571bf52ad796f9f47a3aaace61ee92ab9788980496bb1652826f224150"},"package":null}

View File

@@ -0,0 +1,3 @@
/target
**/*.rs.bk
Cargo.lock

View File

@@ -0,0 +1,16 @@
[package]
name = "linux-loader"
version = "0.1.0"
authors = ["cathy <cathy.zhang@intel.com>"]
edition = "2018"
license = "Apache-2.0 AND BSD-3-Clause"
[features]
default = ["elf"]
elf = []
bzImage = []
[dependencies.vm-memory]
git = "https://github.com/rust-vmm/vm-memory"
features = ["backend-mmap"]

View File

@@ -0,0 +1,64 @@
# ELF Image parsing and loading
The boot process is explained from the following two sides.
## Loader side
It follows ELF standard which is specified in elf.rs. The entry header and program headers will be inerpreted, and PT_LOAD segments will be loaded into guest memory.
### Where kernel is loaded
There are two ways on deciding where the program segments will be loaded.
- One way is to provide an option and allow vmm to specify where to load the image, considering its memory layout.
- The other way is to load image into phdr.p_paddr by default.
## Vmm side
### Construct zero page
According to the 64-bit boot protocol, the boot parameters (traditionally known as "zero page") should be setup, including setup_header, e820 table and other stuff. However, ELF has no setup_header, nothing returned from ELF loader could be used to fill boot parameters, vmm is totally responsible for the construction.
### Configure vcpu
- RIP, the start offset of guest memory where kernel is loaded, which is returned from loader
- 64 bit mode with paging enabled
- GDT must be configured and loaded
# bzImage
The boot process is also explained from the following two sides.
## Loader side
### What will be returned from loader
bzImage includes two parts, the setup and the compressed kernel. The compressed kernel part will be loaded into guest memory, and the following three parts will returned to vmm by loader.
- The start address of loaded kernel
- The offset of memory where kernel is end of loading
- The setup header begin at the offset 0x01f1 of bzImage, this one is an extra compared to the return of ELF loader.
### Where kernel is loaded
The same as ELF image loader, there are two ways for deciding where the compressed kernel will be loaded.
- Vmm specify where to load kernel image.
- Load into code32_start (Boot load address) by default.
### Additional checking
As what the boot protocol said, the kernel is a bzImage kernel if the protocol >= 2.00 and the 0x01 bit(LOAD_HIGH) is the loadflags field is set. Add this checking to validate the bzImage.
## Vmm side
### Construct zero page
While vmm build "zero page" with e820 table and other stuff, bzImage loader will return the setup header to fill the boot parameters. Meanwhile, setup_header.init_size is a must to be filled into zero page, which will be used during head_64.S boot process.
### Configure vcpu
- RIP, the start address of loaded 64-bit kernel returned from loader + 0x200. Regarding to the 64-bit boot protocol, kernel is started by jumping to the 64-bit kernel entry point, which is the start address of loaded 64-bit kernel plus 0x200.
- 64 bit mode with paging enabled
- GDT must be configured and loaded

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,27 @@
// Copyright 2017 The Chromium OS Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,105 @@
# Linux-loader
## Short-description
* Parsing and loading vmlinux (raw ELF image) and bzImage images
* Linux command line parsing and generation
* Definitions and helpers for the Linux boot protocol
## How to build
```
cd linux-loader
cargo build
```
## Tests
Our Continuous Integration (CI) pipeline is implemented on top of
[Buildkite](https://buildkite.com/).
For the complete list of tests, check our
[CI pipeline](https://buildkite.com/rust-vmm/vm-virtio-ci).
Each individual test runs in a container. To reproduce a test locally, you can
use the dev-container on both x86 and arm64.
```bash
docker run -it \
--security-opt seccomp=unconfined \
--volume $(pwd):/linux-loader \
fandree/rust-vmm-dev
cd linux-loader/
cargo test
```
### Test Profiles
The integration tests support two test profiles:
- **devel**: this is the recommended profile for running the integration tests
on a local development machine.
- **ci** (default option): this is the profile used when running the
integration tests as part of the the Continuous Integration (CI).
The test profiles are applicable to tests that run using pytest. Currently only
the [coverage test](tests/test_coverage.py) follows this model as all the other
integration tests are run using the
[Buildkite pipeline](https://buildkite.com/rust-vmm/vm-virtio-ci).
The difference between is declaring tests as passed or failed:
- with the **devel** profile the coverage test passes if the current coverage
is equal or higher than the upstream coverage value. In case the current
coverage is higher, the coverage file is updated to the new coverage value.
- with the **ci** profile the coverage test passes only if the current coverage
is equal to the upstream coverage value.
Further details about the coverage test can be found in the
[Adaptive Coverage](#adaptive-coverage) section.
### Adaptive Coverage
The line coverage is saved in [tests/coverage](tests/coverage). To update the
coverage before submitting a PR, run the coverage test:
```bash
docker run -it \
--security-opt seccomp=unconfined \
--volume $(pwd):/linux-loader \
fandree/rust-vmm-dev
cd linux-loader/
pytest --profile=devel tests/test_coverage.py
```
If the PR coverage is higher than the upstream coverage, the coverage file
needs to be manually added to the commit before submitting the PR:
```bash
git add tests/coverage
```
Failing to do so will generate a fail on the CI pipeline when publishing the
PR.
**NOTE:** The coverage file is only updated in the `devel` test profile. In
the `ci` profile the coverage test will fail if the current coverage is higher
than the coverage reported in [tests/coverage](tests/coverage).
### bzImage test
As we don't want to distribute an entire kernel bzImage, the `load_bzImage` test is ignored by
default. In order to test the bzImage support, one needs to locally build a bzImage, copy it
to the `src/loader` directory and run the ignored test:
```shell
# Assuming your linux-loader and linux-stable are both under $LINUX_LOADER
$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git $LINUX_LOADER/linux-stable
$ cd linux-stable
$ make bzImage
$ cp linux-stable/arch/x86/boot/bzImage $LINUX_LOADER/linux-loader/src/loader/
$ cd $LINUX_LOADER/linux-loader
$ docker run -it \
--security-opt seccomp=unconfined \
--volume $(pwd):/linux-loader \
fandree/rust-vmm-dev
$ cd linux-loader/
$ cargo test -- --ignored
```

View File

@@ -0,0 +1,235 @@
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
//
//! Helper for creating valid kernel command line strings.
use std::fmt;
use std::result;
/// The error type for command line building operations.
#[derive(PartialEq, Debug)]
pub enum Error {
/// Operation would have resulted in a non-printable ASCII character.
InvalidAscii,
/// Key/Value Operation would have had a space in it.
HasSpace,
/// Key/Value Operation would have had an equals sign in it.
HasEquals,
/// Operation would have made the command line too large.
TooLarge,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match *self {
Error::InvalidAscii => "string contains non-printable ASCII character",
Error::HasSpace => "string contains a space",
Error::HasEquals => "string contains an equals sign",
Error::TooLarge => "inserting string would make command line too long",
}
)
}
}
/// Specialized Result type for command line operations.
pub type Result<T> = result::Result<T, Error>;
fn valid_char(c: char) -> bool {
match c {
' '...'~' => true,
_ => false,
}
}
fn valid_str(s: &str) -> Result<()> {
if s.chars().all(valid_char) {
Ok(())
} else {
Err(Error::InvalidAscii)
}
}
fn valid_element(s: &str) -> Result<()> {
if !s.chars().all(valid_char) {
Err(Error::InvalidAscii)
} else if s.contains(' ') {
Err(Error::HasSpace)
} else if s.contains('=') {
Err(Error::HasEquals)
} else {
Ok(())
}
}
/// A builder for a kernel command line string that validates the string as its being built. A
/// `CString` can be constructed from this directly using `CString::new`.
#[derive(Clone)]
pub struct Cmdline {
line: String,
capacity: usize,
}
impl Cmdline {
/// Constructs an empty Cmdline with the given capacity, which includes the nul terminator.
/// Capacity must be greater than 0.
pub fn new(capacity: usize) -> Cmdline {
assert_ne!(capacity, 0);
Cmdline {
line: String::with_capacity(capacity),
capacity,
}
}
fn has_capacity(&self, more: usize) -> Result<()> {
let needs_space = if self.line.is_empty() { 0 } else { 1 };
if self.line.len() + more + needs_space < self.capacity {
Ok(())
} else {
Err(Error::TooLarge)
}
}
fn start_push(&mut self) {
if !self.line.is_empty() {
self.line.push(' ');
}
}
fn end_push(&mut self) {
// This assert is always true because of the `has_capacity` check that each insert method
// uses.
assert!(self.line.len() < self.capacity);
}
/// Validates and inserts a key value pair into this command line
pub fn insert<T: AsRef<str>>(&mut self, key: T, val: T) -> Result<()> {
let k = key.as_ref();
let v = val.as_ref();
valid_element(k)?;
valid_element(v)?;
self.has_capacity(k.len() + v.len() + 1)?;
self.start_push();
self.line.push_str(k);
self.line.push('=');
self.line.push_str(v);
self.end_push();
Ok(())
}
/// Validates and inserts a string to the end of the current command line
pub fn insert_str<T: AsRef<str>>(&mut self, slug: T) -> Result<()> {
let s = slug.as_ref();
valid_str(s)?;
self.has_capacity(s.len())?;
self.start_push();
self.line.push_str(s);
self.end_push();
Ok(())
}
/// Returns the cmdline in progress without nul termination
pub fn as_str(&self) -> &str {
self.line.as_str()
}
}
impl Into<Vec<u8>> for Cmdline {
fn into(self) -> Vec<u8> {
self.line.into_bytes()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CString;
#[test]
fn insert_hello_world() {
let mut cl = Cmdline::new(100);
assert_eq!(cl.as_str(), "");
assert!(cl.insert("hello", "world").is_ok());
assert_eq!(cl.as_str(), "hello=world");
let s = CString::new(cl).expect("failed to create CString from Cmdline");
assert_eq!(s, CString::new("hello=world").unwrap());
}
#[test]
fn insert_multi() {
let mut cl = Cmdline::new(100);
assert!(cl.insert("hello", "world").is_ok());
assert!(cl.insert("foo", "bar").is_ok());
assert_eq!(cl.as_str(), "hello=world foo=bar");
}
#[test]
fn insert_space() {
let mut cl = Cmdline::new(100);
assert_eq!(cl.insert("a ", "b"), Err(Error::HasSpace));
assert_eq!(cl.insert("a", "b "), Err(Error::HasSpace));
assert_eq!(cl.insert("a ", "b "), Err(Error::HasSpace));
assert_eq!(cl.insert(" a", "b"), Err(Error::HasSpace));
assert_eq!(cl.as_str(), "");
}
#[test]
fn insert_equals() {
let mut cl = Cmdline::new(100);
assert_eq!(cl.insert("a=", "b"), Err(Error::HasEquals));
assert_eq!(cl.insert("a", "b="), Err(Error::HasEquals));
assert_eq!(cl.insert("a=", "b "), Err(Error::HasEquals));
assert_eq!(cl.insert("=a", "b"), Err(Error::HasEquals));
assert_eq!(cl.insert("a", "=b"), Err(Error::HasEquals));
assert_eq!(cl.as_str(), "");
}
#[test]
fn insert_emoji() {
let mut cl = Cmdline::new(100);
assert_eq!(cl.insert("heart", "💖"), Err(Error::InvalidAscii));
assert_eq!(cl.insert("💖", "love"), Err(Error::InvalidAscii));
assert_eq!(cl.as_str(), "");
}
#[test]
fn insert_string() {
let mut cl = Cmdline::new(13);
assert_eq!(cl.as_str(), "");
assert!(cl.insert_str("noapic").is_ok());
assert_eq!(cl.as_str(), "noapic");
assert!(cl.insert_str("nopci").is_ok());
assert_eq!(cl.as_str(), "noapic nopci");
}
#[test]
fn insert_too_large() {
let mut cl = Cmdline::new(4);
assert_eq!(cl.insert("hello", "world"), Err(Error::TooLarge));
assert_eq!(cl.insert("a", "world"), Err(Error::TooLarge));
assert_eq!(cl.insert("hello", "b"), Err(Error::TooLarge));
assert!(cl.insert("a", "b").is_ok());
assert_eq!(cl.insert("a", "b"), Err(Error::TooLarge));
assert_eq!(cl.insert_str("a"), Err(Error::TooLarge));
assert_eq!(cl.as_str(), "a=b");
let mut cl = Cmdline::new(10);
assert!(cl.insert("ab", "ba").is_ok()); // adds 5 length
assert_eq!(cl.insert("c", "da"), Err(Error::TooLarge)); // adds 5 (including space) length
assert!(cl.insert("c", "d").is_ok()); // adds 4 (including space) length
}
}

View File

@@ -0,0 +1,13 @@
// Copyright (c) 2019 Intel Corporation. All rights reserved.
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
pub mod cmdline;
pub mod loader;
extern crate vm_memory;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,340 @@
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
/*
* automatically generated by rust-bindgen
* From upstream linux include/uapi/linux/elf.h at commit:
* 806276b7f07a39a1cc3f38bb1ef5c573d4594a38
*/
pub const EI_MAG0: ::std::os::raw::c_uint = 0;
pub const EI_MAG1: ::std::os::raw::c_uint = 1;
pub const EI_MAG2: ::std::os::raw::c_uint = 2;
pub const EI_MAG3: ::std::os::raw::c_uint = 3;
pub const EI_DATA: ::std::os::raw::c_uint = 5;
pub const ELFMAG0: ::std::os::raw::c_uint = 127;
pub const ELFDATA2LSB: ::std::os::raw::c_uint = 1;
pub const PT_LOAD: ::std::os::raw::c_uint = 1;
pub const ELFMAG1: u8 = b'E';
pub const ELFMAG2: u8 = b'L';
pub const ELFMAG3: u8 = b'F';
type Elf64_Addr = __u64;
type Elf64_Half = __u16;
type Elf64_Off = __u64;
type Elf64_Word = __u32;
type Elf64_Xword = __u64;
type __s8 = ::std::os::raw::c_schar;
type __u8 = ::std::os::raw::c_uchar;
type __s16 = ::std::os::raw::c_short;
type __u16 = ::std::os::raw::c_ushort;
type __s32 = ::std::os::raw::c_int;
type __u32 = ::std::os::raw::c_uint;
type __s64 = ::std::os::raw::c_longlong;
type __u64 = ::std::os::raw::c_ulonglong;
#[repr(C)]
#[derive(Debug, Default, Copy)]
pub struct elf64_hdr {
pub e_ident: [::std::os::raw::c_uchar; 16usize],
pub e_type: Elf64_Half,
pub e_machine: Elf64_Half,
pub e_version: Elf64_Word,
pub e_entry: Elf64_Addr,
pub e_phoff: Elf64_Off,
pub e_shoff: Elf64_Off,
pub e_flags: Elf64_Word,
pub e_ehsize: Elf64_Half,
pub e_phentsize: Elf64_Half,
pub e_phnum: Elf64_Half,
pub e_shentsize: Elf64_Half,
pub e_shnum: Elf64_Half,
pub e_shstrndx: Elf64_Half,
}
impl Clone for elf64_hdr {
fn clone(&self) -> Self {
*self
}
}
pub type Elf64_Ehdr = elf64_hdr;
#[repr(C)]
#[derive(Debug, Default, Copy)]
pub struct elf64_phdr {
pub p_type: Elf64_Word,
pub p_flags: Elf64_Word,
pub p_offset: Elf64_Off,
pub p_vaddr: Elf64_Addr,
pub p_paddr: Elf64_Addr,
pub p_filesz: Elf64_Xword,
pub p_memsz: Elf64_Xword,
pub p_align: Elf64_Xword,
}
impl Clone for elf64_phdr {
fn clone(&self) -> Self {
*self
}
}
pub type Elf64_Phdr = elf64_phdr;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bindgen_test_layout_elf64_phdr() {
assert_eq!(
::std::mem::size_of::<elf64_phdr>(),
56usize,
concat!("Size of: ", stringify!(elf64_phdr))
);
assert_eq!(
::std::mem::align_of::<elf64_phdr>(),
8usize,
concat!("Alignment of ", stringify!(elf64_phdr))
);
assert_eq!(
unsafe { &(*(0 as *const elf64_phdr)).p_type as *const _ as usize },
0usize,
concat!(
"Alignment of field: ",
stringify!(elf64_phdr),
"::",
stringify!(p_type)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_phdr)).p_flags as *const _ as usize },
4usize,
concat!(
"Alignment of field: ",
stringify!(elf64_phdr),
"::",
stringify!(p_flags)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_phdr)).p_offset as *const _ as usize },
8usize,
concat!(
"Alignment of field: ",
stringify!(elf64_phdr),
"::",
stringify!(p_offset)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_phdr)).p_vaddr as *const _ as usize },
16usize,
concat!(
"Alignment of field: ",
stringify!(elf64_phdr),
"::",
stringify!(p_vaddr)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_phdr)).p_paddr as *const _ as usize },
24usize,
concat!(
"Alignment of field: ",
stringify!(elf64_phdr),
"::",
stringify!(p_paddr)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_phdr)).p_filesz as *const _ as usize },
32usize,
concat!(
"Alignment of field: ",
stringify!(elf64_phdr),
"::",
stringify!(p_filesz)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_phdr)).p_memsz as *const _ as usize },
40usize,
concat!(
"Alignment of field: ",
stringify!(elf64_phdr),
"::",
stringify!(p_memsz)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_phdr)).p_align as *const _ as usize },
48usize,
concat!(
"Alignment of field: ",
stringify!(elf64_phdr),
"::",
stringify!(p_align)
)
);
}
#[test]
fn bindgen_test_layout_elf64_hdr() {
assert_eq!(
::std::mem::size_of::<elf64_hdr>(),
64usize,
concat!("Size of: ", stringify!(elf64_hdr))
);
assert_eq!(
::std::mem::align_of::<elf64_hdr>(),
8usize,
concat!("Alignment of ", stringify!(elf64_hdr))
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_ident as *const _ as usize },
0usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_ident)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_type as *const _ as usize },
16usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_type)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_machine as *const _ as usize },
18usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_machine)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_version as *const _ as usize },
20usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_version)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_entry as *const _ as usize },
24usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_entry)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_phoff as *const _ as usize },
32usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_phoff)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_shoff as *const _ as usize },
40usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_shoff)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_flags as *const _ as usize },
48usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_flags)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_ehsize as *const _ as usize },
52usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_ehsize)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_phentsize as *const _ as usize },
54usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_phentsize)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_phnum as *const _ as usize },
56usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_phnum)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_shentsize as *const _ as usize },
58usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_shentsize)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_shnum as *const _ as usize },
60usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_shnum)
)
);
assert_eq!(
unsafe { &(*(0 as *const elf64_hdr)).e_shstrndx as *const _ as usize },
62usize,
concat!(
"Alignment of field: ",
stringify!(elf64_hdr),
"::",
stringify!(e_shstrndx)
)
);
}
}

View File

@@ -0,0 +1,596 @@
// Copyright (c) 2019 Intel Corporation. All rights reserved.
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
//! Traits and Structs
//! - [KernelLoader](trait.KernelLoader.html): load kernel image into guest memory
//! - [KernelLoaderResult](struct.KernelLoaderResult.html): the structure which loader
//! returns to VMM to assist zero page construction and boot environment setup
//! - [Elf](struct.Elf.html): elf image loader
//! - [BzImage](struct.BzImage.html): bzImage loader
extern crate vm_memory;
use std::error::{self, Error as KernelLoaderError};
use std::ffi::CStr;
use std::fmt::{self, Display};
use std::io::{Read, Seek, SeekFrom};
use std::mem;
use vm_memory::{Address, Bytes, GuestAddress, GuestMemory, GuestUsize};
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[allow(non_upper_case_globals)]
#[cfg_attr(feature = "cargo-clippy", allow(clippy::all))]
pub mod bootparam;
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[allow(non_upper_case_globals)]
#[cfg_attr(feature = "cargo-clippy", allow(clippy::all))]
mod elf;
mod struct_util;
#[derive(Debug, PartialEq)]
pub enum Error {
BigEndianElfOnLittle,
CommandLineCopy,
CommandLineOverflow,
InvalidElfMagicNumber,
InvalidProgramHeaderSize,
InvalidProgramHeaderOffset,
InvalidProgramHeaderAddress,
InvalidEntryAddress,
InvalidBzImage,
InvalidKernelStartAddress,
InitrdImageSizeTooLarge,
MemoryOverflow,
ReadElfHeader,
ReadKernelImage,
ReadProgramHeader,
ReadBzImageHeader,
ReadBzImageCompressedKernel,
ReadInitrdImage,
SeekKernelStart,
SeekElfStart,
SeekProgramHeader,
SeekBzImageEnd,
SeekBzImageHeader,
SeekBzImageCompressedKernel,
SeekInitrdImage,
}
pub type Result<T> = std::result::Result<T, Error>;
impl error::Error for Error {
fn description(&self) -> &str {
match self {
Error::BigEndianElfOnLittle => {
"Trying to load big-endian binary on little-endian machine"
}
Error::CommandLineCopy => "Failed writing command line to guest memory",
Error::CommandLineOverflow => "Command line overflowed guest memory",
Error::InvalidElfMagicNumber => "Invalid Elf magic number",
Error::InvalidProgramHeaderSize => "Invalid program header size",
Error::InvalidProgramHeaderOffset => "Invalid program header offset",
Error::InvalidProgramHeaderAddress => "Invalid Program Header Address",
Error::InvalidEntryAddress => "Invalid entry address",
Error::InvalidBzImage => "Invalid bzImage",
Error::InvalidKernelStartAddress => "Invalid kernel start address",
Error::InitrdImageSizeTooLarge => "Initrd image size too large",
Error::MemoryOverflow => "Memory to load kernel image is not enough",
Error::ReadElfHeader => "Unable to read elf header",
Error::ReadKernelImage => "Unable to read kernel image",
Error::ReadProgramHeader => "Unable to read program header",
Error::ReadBzImageHeader => "Unable to read bzImage header",
Error::ReadBzImageCompressedKernel => "Unable to read bzImage compressed kernel",
Error::ReadInitrdImage => "Unable to read initrd image",
Error::SeekKernelStart => "Unable to seek to kernel start",
Error::SeekElfStart => "Unable to seek to elf start",
Error::SeekProgramHeader => "Unable to seek to program header",
Error::SeekBzImageEnd => "Unable to seek bzImage end",
Error::SeekBzImageHeader => "Unable to seek bzImage header",
Error::SeekBzImageCompressedKernel => "Unable to seek bzImage compressed kernel",
Error::SeekInitrdImage => "Unable to seek initrd image",
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Kernel Loader Error: {}", Error::description(self))
}
}
#[derive(Debug, Default, Copy, Clone, PartialEq)]
pub struct KernelLoaderResult {
// Address in the guest memory where the kernel image starts to be loaded
pub kernel_load: GuestAddress,
// Offset in guest memory corresponding to the end of kernel image, in case that
// device tree blob and initrd will be loaded adjacent to kernel image.
pub kernel_end: GuestUsize,
// This field is only for bzImage following https://www.kernel.org/doc/Documentation/x86/boot.txt
// VMM should make use of it to fill zero page for bzImage direct boot.
pub setup_header: Option<bootparam::setup_header>,
}
pub trait KernelLoader {
fn load<F, M: GuestMemory>(
guest_mem: &M,
kernel_start: Option<GuestAddress>,
kernel_image: &mut F,
highmem_start_address: Option<GuestAddress>,
) -> Result<KernelLoaderResult>
where
F: Read + Seek;
}
#[cfg(feature = "elf")]
pub struct Elf;
#[cfg(feature = "elf")]
impl KernelLoader for Elf {
/// Loads a kernel from a vmlinux elf image to a slice
///
/// kernel is loaded into guest memory at offset phdr.p_paddr specified by elf image.
///
/// # Arguments
///
/// * `guest_mem` - The guest memory region the kernel is written to.
/// * `kernel_start` - The offset into 'guest_mem' at which to load the kernel.
/// * `kernel_image` - Input vmlinux image.
/// * `highmem_start_address` - This is the start of the high memory, kernel should above it.
///
/// # Returns
/// * KernelLoaderResult
fn load<F, M: GuestMemory>(
guest_mem: &M,
kernel_start: Option<GuestAddress>,
kernel_image: &mut F,
highmem_start_address: Option<GuestAddress>,
) -> Result<KernelLoaderResult>
where
F: Read + Seek,
{
let mut ehdr: elf::Elf64_Ehdr = Default::default();
kernel_image
.seek(SeekFrom::Start(0))
.map_err(|_| Error::SeekElfStart)?;
unsafe {
// read_struct is safe when reading a POD struct. It can be used and dropped without issue.
struct_util::read_struct(kernel_image, &mut ehdr).map_err(|_| Error::ReadElfHeader)?;
}
// Sanity checks
if ehdr.e_ident[elf::EI_MAG0 as usize] != elf::ELFMAG0 as u8
|| ehdr.e_ident[elf::EI_MAG1 as usize] != elf::ELFMAG1
|| ehdr.e_ident[elf::EI_MAG2 as usize] != elf::ELFMAG2
|| ehdr.e_ident[elf::EI_MAG3 as usize] != elf::ELFMAG3
{
return Err(Error::InvalidElfMagicNumber);
}
if ehdr.e_ident[elf::EI_DATA as usize] != elf::ELFDATA2LSB as u8 {
return Err(Error::BigEndianElfOnLittle);
}
if ehdr.e_phentsize as usize != mem::size_of::<elf::Elf64_Phdr>() {
return Err(Error::InvalidProgramHeaderSize);
}
if (ehdr.e_phoff as usize) < mem::size_of::<elf::Elf64_Ehdr>() {
return Err(Error::InvalidProgramHeaderOffset);
}
if (highmem_start_address.is_some())
&& ((ehdr.e_entry as u64) < highmem_start_address.unwrap().raw_value())
{
return Err(Error::InvalidEntryAddress);
}
let mut loader_result: KernelLoaderResult = Default::default();
// where the kernel will be start loaded.
loader_result.kernel_load = match kernel_start {
Some(start) => GuestAddress(start.raw_value() + (ehdr.e_entry as u64)),
None => GuestAddress(ehdr.e_entry as u64),
};
kernel_image
.seek(SeekFrom::Start(ehdr.e_phoff))
.map_err(|_| Error::SeekProgramHeader)?;
let phdrs: Vec<elf::Elf64_Phdr> = unsafe {
// Reading the structs is safe for a slice of POD structs.
struct_util::read_struct_slice(kernel_image, ehdr.e_phnum as usize)
.map_err(|_| Error::ReadProgramHeader)?
};
// Read in each section pointed to by the program headers.
for phdr in &phdrs {
if phdr.p_type != elf::PT_LOAD || phdr.p_filesz == 0 {
continue;
}
kernel_image
.seek(SeekFrom::Start(phdr.p_offset))
.map_err(|_| Error::SeekKernelStart)?;
// if the vmm does not specify where the kernel should be loaded, just
// load it to the physical address p_paddr for each segment.
let mem_offset = match kernel_start {
Some(start) => start
.checked_add(phdr.p_paddr as u64)
.ok_or(Error::InvalidProgramHeaderAddress)?,
None => GuestAddress(phdr.p_paddr as u64),
};
guest_mem
.read_exact_from(mem_offset, kernel_image, phdr.p_filesz as usize)
.map_err(|_| Error::ReadKernelImage)?;
loader_result.kernel_end = mem_offset.raw_value()
.checked_add(phdr.p_memsz as GuestUsize)
.ok_or(Error::MemoryOverflow)?;
}
// elf image has no setup_header which is defined for bzImage
loader_result.setup_header = None;
Ok(loader_result)
}
}
#[cfg(feature = "bzImage")]
pub struct BzImage;
#[cfg(feature = "bzImage")]
impl KernelLoader for BzImage {
/// Loads a bzImage
///
/// kernel is loaded into guest memory at code32_start the default load address
/// stored in bzImage setup header.
///
/// # Arguments
///
/// * `guest_mem` - The guest memory where the kernel image is loaded.
/// * `kernel_start` - The offset into 'guest_mem' at which to load the kernel.
/// * `kernel_image` - Input bzImage image.
/// * `highmem_start_address` - This is the start of the high memory, kernel should above it.
///
/// # Returns
/// * KernelLoaderResult
fn load<F, M: GuestMemory>(
guest_mem: &M,
kernel_start: Option<GuestAddress>,
kernel_image: &mut F,
highmem_start_address: Option<GuestAddress>,
) -> Result<KernelLoaderResult>
where
F: Read + Seek,
{
let mut kernel_size = kernel_image
.seek(SeekFrom::End(0))
.map_err(|_| Error::SeekBzImageEnd)? as usize;
let mut boot_header: bootparam::setup_header = Default::default();
kernel_image
.seek(SeekFrom::Start(0x1F1))
.map_err(|_| Error::SeekBzImageHeader)?;
unsafe {
// read_struct is safe when reading a POD struct. It can be used and dropped without issue.
struct_util::read_struct(kernel_image, &mut boot_header)
.map_err(|_| Error::ReadBzImageHeader)?;
}
// if the HdrS magic number is not found at offset 0x202, the boot protocol version is "old",
// the image type is assumed as zImage, not bzImage.
if boot_header.header != 0x5372_6448 {
return Err(Error::InvalidBzImage);
}
// follow section of loading the rest of the kernel in linux boot protocol
if (boot_header.version < 0x0200) || ((boot_header.loadflags & 0x1) == 0x0) {
return Err(Error::InvalidBzImage);
}
let mut setup_size = boot_header.setup_sects as usize;
if setup_size == 0 {
setup_size = 4;
}
setup_size = (setup_size + 1) * 512;
kernel_size -= setup_size;
// verify bzImage validation by checking if code32_start, the defaults to the address of
// the kernel is not lower than high memory.
if (highmem_start_address.is_some())
&& (u64::from(boot_header.code32_start) < highmem_start_address.unwrap().raw_value())
{
return Err(Error::InvalidKernelStartAddress);
}
let mem_offset = match kernel_start {
Some(start) => start,
None => GuestAddress(u64::from(boot_header.code32_start)),
};
boot_header.code32_start = mem_offset.raw_value() as u32;
let mut loader_result: KernelLoaderResult = Default::default();
loader_result.setup_header = Some(boot_header);
loader_result.kernel_load = mem_offset;
//seek the compressed vmlinux.bin and read to memory
kernel_image
.seek(SeekFrom::Start(setup_size as u64))
.map_err(|_| Error::SeekBzImageCompressedKernel)?;
guest_mem
.read_exact_from(mem_offset, kernel_image, kernel_size)
.map_err(|_| Error::ReadBzImageCompressedKernel)?;
loader_result.kernel_end = mem_offset.raw_value()
.checked_add(kernel_size as GuestUsize)
.ok_or(Error::MemoryOverflow)?;
Ok(loader_result)
}
}
/// Writes the command line string to the given memory slice.
///
/// # Arguments
///
/// * `guest_mem` - A u8 slice that will be partially overwritten by the command line.
/// * `guest_addr` - The address in `guest_mem` at which to load the command line.
/// * `cmdline` - The kernel command line.
pub fn load_cmdline<M: GuestMemory>(
guest_mem: &M,
guest_addr: GuestAddress,
cmdline: &CStr,
) -> Result<()> {
let len = cmdline.to_bytes().len();
if len == 0 {
return Ok(());
}
let end = guest_addr
.checked_add(len as u64 + 1)
.ok_or(Error::CommandLineOverflow)?; // Extra for null termination.
if end > guest_mem.end_addr() {
return Err(Error::CommandLineOverflow)?;
}
guest_mem
.write_slice(cmdline.to_bytes_with_nul(), guest_addr)
.map_err(|_| Error::CommandLineCopy)?;
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
use std::io::Cursor;
use vm_memory::{Address, GuestAddress, GuestMemoryMmap};
const MEM_SIZE: u64 = 0x1000000;
fn create_guest_mem() -> GuestMemoryMmap {
GuestMemoryMmap::new(&[(GuestAddress(0x0), (MEM_SIZE as usize))]).unwrap()
}
#[allow(non_snake_case)]
#[cfg(feature = "bzImage")]
fn make_bzImage() -> Vec<u8> {
let mut v = Vec::new();
v.extend_from_slice(include_bytes!("../../.buildkite/hooks/boot/vmlinuz-3.10.0-957.el7.x86_64"));
v
}
// Elf64 image that prints hello world on x86_64.
fn make_elf_bin() -> Vec<u8> {
let mut v = Vec::new();
v.extend_from_slice(include_bytes!("test_elf.bin"));
v
}
#[allow(safe_packed_borrows)]
#[allow(non_snake_case)]
#[test]
#[cfg(feature = "bzImage")]
fn load_bzImage() {
let gm = create_guest_mem();
let image = make_bzImage();
let mut kernel_start = GuestAddress(0x200000);
let mut highmem_start_address = GuestAddress(0x0);
// load bzImage with good kernel_start and himem_start setting
let mut loader_result = BzImage::load(
&gm,
Some(kernel_start),
&mut Cursor::new(&image),
Some(highmem_start_address),
)
.unwrap();
assert_eq!(0x53726448, loader_result.setup_header.unwrap().header);
println!(
"bzImage is loaded at {:8x} \n",
loader_result.kernel_load.raw_value()
);
println!(
"bzImage version is {:2x} \n",
loader_result.setup_header.unwrap().version
);
println!(
"bzImage loadflags is {:x} \n",
loader_result.setup_header.unwrap().loadflags
);
println!(
"bzImage kernel size is {:4x} \n",
(loader_result.kernel_end as u32)
);
// load bzImage without kernel_start
loader_result = BzImage::load(
&gm,
None,
&mut Cursor::new(&image),
Some(highmem_start_address),
)
.unwrap();
assert_eq!(0x53726448, loader_result.setup_header.unwrap().header);
println!(
"bzImage is loaded at {:8x} \n",
loader_result.kernel_load.raw_value()
);
// load bzImage withouth himem_start
loader_result = BzImage::load(&gm, None, &mut Cursor::new(&image), None).unwrap();
assert_eq!(0x53726448, loader_result.setup_header.unwrap().header);
println!(
"bzImage is loaded at {:8x} \n",
loader_result.kernel_load.raw_value()
);
// load bzImage with a bad himem setting
kernel_start = GuestAddress(0x1000);
highmem_start_address = GuestAddress(0x200000);
let x = BzImage::load(
&gm,
Some(kernel_start),
&mut Cursor::new(&image),
Some(highmem_start_address),
);
assert_eq!(x.is_ok(), false);
println!("load bzImage with bad himem setting \n");
}
#[test]
#[cfg(feature = "elf")]
fn load_elf() {
let gm = create_guest_mem();
let image = make_elf_bin();
let kernel_addr = GuestAddress(0x200000);
let mut highmem_start_address = GuestAddress(0x0);
let mut loader_result = Elf::load(
&gm,
Some(kernel_addr),
&mut Cursor::new(&image),
Some(highmem_start_address),
)
.unwrap();
println!(
"load elf at address {:8x} \n",
loader_result.kernel_load.raw_value()
);
loader_result = Elf::load(&gm, Some(kernel_addr), &mut Cursor::new(&image), None).unwrap();
println!(
"load elf at address {:8x} \n",
loader_result.kernel_load.raw_value()
);
loader_result = Elf::load(
&gm,
None,
&mut Cursor::new(&image),
Some(highmem_start_address),
)
.unwrap();
println!(
"load elf at address {:8x} \n",
loader_result.kernel_load.raw_value()
);
highmem_start_address = GuestAddress(0xa00000);
assert_eq!(
Err(Error::InvalidEntryAddress),
Elf::load(
&gm,
None,
&mut Cursor::new(&image),
Some(highmem_start_address)
)
);
}
#[test]
fn cmdline_overflow() {
let gm = create_guest_mem();
let cmdline_address = GuestAddress(MEM_SIZE - 5);
assert_eq!(
Err(Error::CommandLineOverflow),
load_cmdline(
&gm,
cmdline_address,
CStr::from_bytes_with_nul(b"12345\0").unwrap()
)
);
}
#[test]
fn cmdline_write_end() {
let gm = create_guest_mem();
let mut cmdline_address = GuestAddress(45);
assert_eq!(
Ok(()),
load_cmdline(
&gm,
cmdline_address,
CStr::from_bytes_with_nul(b"1234\0").unwrap()
)
);
let val: u8 = gm.read_obj(cmdline_address).unwrap();
assert_eq!(val, '1' as u8);
cmdline_address = cmdline_address.unchecked_add(1);
let val: u8 = gm.read_obj(cmdline_address).unwrap();
assert_eq!(val, '2' as u8);
cmdline_address = cmdline_address.unchecked_add(1);
let val: u8 = gm.read_obj(cmdline_address).unwrap();
assert_eq!(val, '3' as u8);
cmdline_address = cmdline_address.unchecked_add(1);
let val: u8 = gm.read_obj(cmdline_address).unwrap();
assert_eq!(val, '4' as u8);
cmdline_address = cmdline_address.unchecked_add(1);
let val: u8 = gm.read_obj(cmdline_address).unwrap();
assert_eq!(val, '\0' as u8);
}
#[test]
fn bad_magic() {
let gm = create_guest_mem();
let kernel_addr = GuestAddress(0x0);
let mut bad_image = make_elf_bin();
bad_image[0x1] = 0x33;
assert_eq!(
Err(Error::InvalidElfMagicNumber),
Elf::load(&gm, Some(kernel_addr), &mut Cursor::new(&bad_image), None)
);
}
#[test]
fn bad_endian() {
// Only little endian is supported
let gm = create_guest_mem();
let kernel_addr = GuestAddress(0x0);
let mut bad_image = make_elf_bin();
bad_image[0x5] = 2;
assert_eq!(
Err(Error::BigEndianElfOnLittle),
Elf::load(&gm, Some(kernel_addr), &mut Cursor::new(&bad_image), None)
);
}
#[test]
fn bad_phoff() {
// program header has to be past the end of the elf header
let gm = create_guest_mem();
let kernel_addr = GuestAddress(0x0);
let mut bad_image = make_elf_bin();
bad_image[0x20] = 0x10;
assert_eq!(
Err(Error::InvalidProgramHeaderOffset),
Elf::load(&gm, Some(kernel_addr), &mut Cursor::new(&bad_image), None)
);
}
}

View File

@@ -0,0 +1,152 @@
// Copyright (c) 2019 Intel Corporation. All rights reserved.
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
use std;
use std::io::Read;
use std::mem;
#[derive(Debug)]
pub enum Error {
ReadStruct,
}
pub type Result<T> = std::result::Result<T, Error>;
/// Reads a struct from an input buffer.
/// This is unsafe because the struct is initialized to unverified data read from the input.
/// `read_struct` should only be called to fill plain old data structs. It is not endian safe.
///
/// # Arguments
///
/// * `f` - The input to read from. Often this is a file.
/// * `out` - The struct to fill with data read from `f`.
pub unsafe fn read_struct<T: Copy, F: Read>(f: &mut F, out: &mut T) -> Result<()> {
let out_slice = std::slice::from_raw_parts_mut(out as *mut T as *mut u8, mem::size_of::<T>());
f.read_exact(out_slice).map_err(|_| Error::ReadStruct)?;
Ok(())
}
/// Reads an array of structs from an input buffer. Returns a Vec of structs initialized with data
/// from the specified input.
/// This is unsafe because the structs are initialized to unverified data read from the input.
/// `read_struct_slice` should only be called for plain old data structs. It is not endian safe.
///
/// # Arguments
///
/// * `f` - The input to read from. Often this is a file.
/// * `len` - The number of structs to fill with data read from `f`.
pub unsafe fn read_struct_slice<T: Copy, F: Read>(f: &mut F, len: usize) -> Result<Vec<T>> {
let mut out: Vec<T> = Vec::with_capacity(len);
out.set_len(len);
let out_slice = std::slice::from_raw_parts_mut(
out.as_ptr() as *mut T as *mut u8,
mem::size_of::<T>() * len,
);
f.read_exact(out_slice).map_err(|_| Error::ReadStruct)?;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
use std::mem;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct TestRead {
a: u64,
b: u8,
c: u8,
d: u8,
e: u8,
}
#[test]
fn struct_basic_read() {
let orig = TestRead {
a: 0x7766554433221100,
b: 0x88,
c: 0x99,
d: 0xaa,
e: 0xbb,
};
let source = unsafe {
// Don't worry it's a test
std::slice::from_raw_parts(
&orig as *const _ as *const u8,
std::mem::size_of::<TestRead>(),
)
};
assert_eq!(mem::size_of::<TestRead>(), mem::size_of_val(&source));
let mut tr: TestRead = Default::default();
unsafe {
read_struct(&mut Cursor::new(source), &mut tr).unwrap();
}
assert_eq!(orig, tr);
}
#[test]
fn struct_read_past_end() {
let orig = TestRead {
a: 0x7766554433221100,
b: 0x88,
c: 0x99,
d: 0xaa,
e: 0xbb,
};
let source = unsafe {
// Don't worry it's a test
std::slice::from_raw_parts(
&orig as *const _ as *const u8,
std::mem::size_of::<TestRead>() - 1,
)
};
let mut tr: TestRead = Default::default();
unsafe {
assert!(read_struct(&mut Cursor::new(source), &mut tr).is_err());
format!("{:?}", read_struct(&mut Cursor::new(source), &mut tr));
}
}
#[test]
fn struct_slice_read() {
let orig = vec![
TestRead {
a: 0x7766554433221100,
b: 0x88,
c: 0x99,
d: 0xaa,
e: 0xbb,
},
TestRead {
a: 0x7867564534231201,
b: 0x02,
c: 0x13,
d: 0x24,
e: 0x35,
},
TestRead {
a: 0x7a69584736251403,
b: 0x04,
c: 0x15,
d: 0x26,
e: 0x37,
},
];
let source = unsafe {
// Don't worry it's a test
std::slice::from_raw_parts(
orig.as_ptr() as *const u8,
std::mem::size_of::<TestRead>() * 3,
)
};
let tr: Vec<TestRead> = unsafe { read_struct_slice(&mut Cursor::new(source), 3).unwrap() };
assert_eq!(orig, tr);
}
}

Binary file not shown.

View File

@@ -0,0 +1,28 @@
import pytest
PROFILE_CI="ci"
PROFILE_DEVEL="devel"
def pytest_addoption(parser):
parser.addoption(
"--profile",
default=PROFILE_CI,
choices=[PROFILE_CI, PROFILE_DEVEL],
help="Profile for running the test: {} or {}".format(
PROFILE_CI,
PROFILE_DEVEL
)
)
@pytest.fixture
def profile(request):
return request.config.getoption("--profile")
# This is used for defining global variables in pytest.
def pytest_configure():
pytest.profile_ci = PROFILE_CI
pytest.profile_devel = PROFILE_DEVEL

View File

@@ -0,0 +1 @@
67.0

View File

@@ -0,0 +1,108 @@
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
"""Test the coverage and update the threshold when coverage is increased."""
import os, re, shutil, subprocess
import pytest
def _get_current_coverage():
"""Helper function that returns the coverage computed with kcov."""
kcov_ouput_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"kcov_output"
)
# By default the build output for kcov and unit tests are both in the debug
# directory. This causes some linker errors that I haven't investigated.
# Error: error: linking with `cc` failed: exit code: 1
# An easy fix is to have separate build directories for kcov & unit tests.
kcov_build_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"kcov_build"
)
# Remove kcov output and build directory to be sure we are always working
# on a clean environment.
shutil.rmtree(kcov_ouput_dir, ignore_errors=True)
shutil.rmtree(kcov_build_dir, ignore_errors=True)
exclude_pattern = (
'${CARGO_HOME:-$HOME/.cargo/},'
'usr/lib/,'
'lib/'
)
exclude_region = "'mod tests {'"
kcov_cmd = "CARGO_TARGET_DIR={} cargo kcov --all " \
"--output {} -- " \
"--exclude-region={} " \
"--exclude-pattern={} " \
"--verify".format(
kcov_build_dir,
kcov_ouput_dir,
exclude_region,
exclude_pattern
)
subprocess.run(kcov_cmd, shell=True, check=True)
# Read the coverage reported by kcov.
coverage_file = os.path.join(kcov_ouput_dir, 'index.js')
with open(coverage_file) as cov_output:
coverage = float(re.findall(
r'"covered":"(\d+\.\d)"',
cov_output.read()
)[0])
# Remove coverage related directories.
shutil.rmtree(kcov_ouput_dir, ignore_errors=True)
shutil.rmtree(kcov_build_dir, ignore_errors=True)
return coverage
def _get_previous_coverage():
"""Helper function that returns the last reported coverage."""
coverage_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'coverage'
)
# The first and only line of the file contains the coverage.
with open(coverage_path) as f:
coverage = f.readline()
return float(coverage.strip())
def _update_coverage(cov_value):
"""Updates the coverage in the coverage file."""
coverage_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'coverage'
)
with open(coverage_path, "w") as f:
f.write(str(cov_value))
def test_coverage(profile):
current_coverage = _get_current_coverage()
previous_coverage = _get_previous_coverage()
if previous_coverage < current_coverage:
if profile == pytest.profile_ci:
# In the CI Profile we expect the coverage to be manually updated.
assert False, "Coverage is increased from {} to {}. " \
"Please update the coverage in " \
"tests/coverage.".format(
previous_coverage,
current_coverage
)
elif profile == pytest.profile_devel:
_update_coverage(current_coverage)
else:
# This should never happen because pytest should only accept
# the valid test profiles specified with `choices` in
# `pytest_addoption`.
assert False, "Invalid test profile."
elif previous_coverage > current_coverage:
diff = float(previous_coverage - current_coverage)
assert False, "Coverage drops by {:.2f}%. Please add unit tests for" \
"the uncovered lines.".format(diff)