<commit_before>#![allow(dead_code)]
use num::Float;
use typenum::*;
use generic_array::*;
use std::ops;
use std::ops::{Index, IndexMut, Mul};
use std::mem;

use vector::*;

#[derive(PartialEq, Eq, Debug, Clone)]
pub struct Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T>,
          M: ArrayLength<Vector<T, N>>,
          N::ArrayType: Copy,
          M::ArrayType: Copy
{
    data: GenericArray<Vector<T, N>, M>,
}

impl<T, N, M> Mul<T> for Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T>,
          M: ArrayLength<Vector<T, N>>,
          N::ArrayType: Copy,
          M::ArrayType: Copy,
          Vector<T, N>: Copy
{
    type Output = Matrix<T, N, M>;
    fn mul(self, scalar: T) -> Self::Output {
        let mut m = Self::zero();
        for (index, new_val) in self.data.into_iter().map(|v| v * scalar).enumerate() {
            m.data[index] = new_val;
        }
        m
    }
}
impl<T, N, M> Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T>,
          M: ArrayLength<Vector<T, N>>,
          N::ArrayType: Copy,
          M::ArrayType: Copy,
          Vector<T, N>: Copy
{
    pub fn new(slice: &[Vector<T, N>]) -> Matrix<T, N, M> {
        Matrix::<T, N, M> { data: GenericArray::from_slice(slice) }
    }

    pub fn zero() -> Matrix<T, N, M> {
        unsafe {
            let mut mat: Matrix<T, N, M> = mem::uninitialized();
            for j in 0..M::to_usize() {
                mat.data[j] = Vector::<T, N>::zero();
            }
            mat
        }
    }
}
impl<T, N> Matrix<T, N, N>
    where T: Float,
          N: ArrayLength<T> + ArrayLength<Vector<T, N>>,
          <N as ArrayLength<T>>::ArrayType: Copy,
          <N as ArrayLength<Vector<T, N>>>::ArrayType: Copy,
          Vector<T, N>: Copy
{
    fn identity() -> Matrix<T, N, N> {
        let mut mat = Matrix::<T, N, N>::zero();
        for index in 0..N::to_usize() {
            mat.data[index].data[index] = T::one();
        }
        mat
    }
}

impl<T, N, M> Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T> + ArrayLength<Vector<T, M>>,
          M: ArrayLength<T> + ArrayLength<Vector<T, N>>,
          <N as ArrayLength<Vector<T, M>>>::ArrayType: Copy,
          <M as ArrayLength<Vector<T, N>>>::ArrayType: Copy,
          <N as ArrayLength<T>>::ArrayType: Copy,
          <M as ArrayLength<T>>::ArrayType: Copy
{
    fn transpose(&self) -> Matrix<T, M, N> {
        unsafe {
            let mut data: GenericArray<Vector<T, M>, N> = mem::uninitialized();
            for j in 0..N::to_usize() {
                for i in 0..M::to_usize() {
                    data[j].data[i] = self.data[i].data[j];
                }
            }
            Matrix::<T, M, N> { data: data }
        }
    }
}
// funny stuff is happening here
impl<T, N, M> Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T> + ArrayLength<Vector<T, M>>,
          M: ArrayLength<T> + ArrayLength<Vector<T, N>>,
          <N as ArrayLength<Vector<T, M>>>::ArrayType: Copy,
          <M as ArrayLength<Vector<T, N>>>::ArrayType: Copy,
          <N as ArrayLength<T>>::ArrayType: Copy,
          <M as ArrayLength<T>>::ArrayType: Copy
{
    pub fn mul_v(&self, other: Vector<T, N>) -> Vector<T, N>
        where Vector<T, N>: Copy
    {
        let mut v = Vector::<T, N>::zero();
        for index in 0..N::to_usize() {
            v.data[index] = self.data[index].dot(other);
        }
        v
    }
    pub fn mul<N1>(&self, other: &Matrix<T, N1, N>) -> Matrix<T, M, N1>
        where N1: ArrayLength<T> + ArrayLength<Vector<T, M>> + ArrayLength<Vector<T, N>>,
              <N1 as ArrayLength<T>>::ArrayType: Copy,
              <N1 as ArrayLength<Vector<T, M>>>::ArrayType: Copy,
              <N1 as ArrayLength<Vector<T, N>>>::ArrayType: Copy,
              N: ArrayLength<Vector<T, N1>>,
              <N as ArrayLength<Vector<T, N1>>>::ArrayType: Copy,
              Vector<T, N>: Copy
    {
        unsafe {
            let mut new_matrix: Matrix<T, M, N1> = mem::uninitialized();
            let other_transposed: Matrix<T, N, N1> = other.transpose();
            for j in 0..N1::to_usize() {
                for i in 0..M::to_usize() {
                    new_matrix.data[j].data[i] = self.data[j].dot(other_transposed.data[i]);
                }
            }
            new_matrix
        }
    }
}

impl<T, N, M> Index<usize> for Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T>,
          M: ArrayLength<Vector<T, N>>,
          N::ArrayType: Copy,
          M::ArrayType: Copy
{
    type Output = Vector<T, N>;

    fn index(&self, idx: usize) -> &Vector<T, N> {
        &self.data[idx]
    }
}
impl<T, N, M> IndexMut<usize> for Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T>,
          M: ArrayLength<Vector<T, N>>,
          N::ArrayType: Copy,
          M::ArrayType: Copy
{
    fn index_mut(&mut self, idx: usize) -> &mut Vector<T, N> {
        &mut self.data[idx]
    }
}

impl<T> Matrix<T, U4, U4>
    where T: Float
{
    pub fn translate(v: Vec3<T>) -> Self {
        let mut m = Self::identity();
        *m.data[0].w_m() = v.x();
        *m.data[1].w_m() = v.y();
        *m.data[2].w_m() = v.z();
        m
    }

    pub fn scale(s: Vec3<T>) -> Self {
        let mut identity = Self::identity();
        for index in 0..s.dim() {
            identity.data[index].data[index] = s.data[index];
        }
        identity
    }

    #[cfg_attr(rustfmt, rustfmt_skip)]
    pub fn rotation_x(angle: T) -> Self {
        let s = angle.sin();
        let c = angle.cos();
        Self::new(&[Vec4::<T>::new(T::one(),  T::zero(),  T::zero(), T::zero()),
                    Vec4::<T>::new(T::zero(), c,         -s,         T::zero()),
                    Vec4::<T>::new(T::zero(), s,          c,         T::zero()),
                    Vec4::<T>::new(T::zero(), T::zero(),  T::zero(), T::one())])
    }

    #[cfg_attr(rustfmt, rustfmt_skip)]
    pub fn rotation_y(angle: T) -> Self {
        let s = angle.sin();
        let c = angle.cos();
        Self::new(&[Vec4::<T>::new(c,         T::zero(), s,         T::zero()),
                    Vec4::<T>::new(T::zero(), T::one(),  T::zero(), T::zero()),
                    Vec4::<T>::new(-s,        T::zero(), c,         T::zero()),
                    Vec4::<T>::new(T::zero(), T::zero(), T::zero(), T::one())])
    }

    #[cfg_attr(rustfmt, rustfmt_skip)]
    pub fn rotation_z(angle: T) -> Self {
        let s = angle.sin();
        let c = angle.cos();
        Self::new(&[Vec4::<T>::new(c,        -s,         T::zero(), T::zero()),
                    Vec4::<T>::new(s,         c,         T::zero(), T::zero()),
                    Vec4::<T>::new(T::zero(), T::zero(), T::one(),  T::zero()),
                    Vec4::<T>::new(T::zero(), T::zero(), T::zero(), T::one())])
    }

    pub fn inverse(&self) -> Self {
        let mut inv = self.clone();
        let coef00 = self[2][2] * self[3][3] - self[3][2] * self[2][3];
        let coef02 = self[1][2] * self[3][3] - self[3][2] * self[1][3];
        let coef03 = self[1][2] * self[2][3] - self[2][2] * self[1][3];

        let coef04 = self[2][1] * self[3][3] - self[3][1] * self[2][3];
        let coef06 = self[1][1] * self[3][3] - self[3][1] * self[1][3];
        let coef07 = self[1][1] * self[2][3] - self[2][1] * self[1][3];

        let coef08 = self[2][1] * self[3][2] - self[3][1] * self[2][2];
        let coef10 = self[1][1] * self[3][2] - self[3][1] * self[1][2];
        let coef11 = self[1][1] * self[2][2] - self[2][1] * self[1][2];

        let coef12 = self[2][0] * self[3][3] - self[3][0] * self[2][3];
        let coef14 = self[1][0] * self[3][3] - self[3][0] * self[1][3];
        let coef15 = self[1][0] * self[2][3] - self[2][0] * self[1][3];

        let coef16 = self[2][0] * self[3][2] - self[3][0] * self[2][2];
        let coef18 = self[1][0] * self[3][2] - self[3][0] * self[1][2];
        let coef19 = self[1][0] * self[2][2] - self[2][0] * self[1][2];

        let coef20 = self[2][0] * self[3][1] - self[3][0] * self[2][1];
        let coef22 = self[1][0] * self[3][1] - self[3][0] * self[1][1];
        let coef23 = self[1][0] * self[2][1] - self[2][0] * self[1][1];

        let fac0 = Vec4::new(coef00, coef00, coef02, coef03);
        let fac1 = Vec4::new(coef04, coef04, coef06, coef07);
        let fac2 = Vec4::new(coef08, coef08, coef10, coef11);
        let fac3 = Vec4::new(coef12, coef12, coef14, coef15);
        let fac4 = Vec4::new(coef16, coef16, coef18, coef19);
        let fac5 = Vec4::new(coef20, coef20, coef22, coef23);

        let vec0 = Vec4::new(self[1][0], self[0][0], self[0][0], self[0][0]);
        let vec1 = Vec4::new(self[1][1], self[0][1], self[0][1], self[0][1]);
        let vec2 = Vec4::new(self[1][2], self[0][2], self[0][2], self[0][2]);
        let vec3 = Vec4::new(self[1][3], self[0][3], self[0][3], self[0][3]);

        let inv0 = vec1 * fac0 - vec2 * fac1 + vec3 * fac2;
        let inv1 = vec0 * fac0 - vec2 * fac3 + vec3 * fac4;
        let inv2 = vec0 * fac1 - vec1 * fac3 + vec3 * fac5;
        let inv3 = vec0 * fac2 - vec1 * fac4 + vec2 * fac5;

        let sign_a = Vec4::new(T::one(), -T::one(), T::one(), -T::one());
        let sign_b = Vec4::new(-T::one(), T::one(), -T::one(), T::one());

        let inverse = Self::new(&[inv0 * sign_a, inv1 * sign_b, inv2 * sign_a, inv3 * sign_b]);

        let row0 = Vec4::new(inverse[0][0], inverse[1][0], inverse[2][0], inverse[3][0]);

        let dot0 = self[0] * row0;
        let dot1 = (dot0.x() + dot0.y()) + (dot0.z() + dot0.w());

        let one_over_det = T::one() / dot1;
        inv * one_over_det
    }
}

#[cfg(test)]
mod test {
    use vector::*;
    use matrix::*;
    #[test]
    fn rot_x() {
        use std::f32;
        let v = Vec4f::new(0., 0., 1., 0.);
        let pi = f32::consts::PI;
        let m = Mat4x4f::rotation_x(pi / 2.0);
        let v2 = m.mul_v(v);
        println!("{:?}", v2);
    }
}
#[test]
fn mul() {
    // use vector::*;
    // let v2 = Vec2f::new(1., 2.);
    // let v3 = Vec3f::new(1., 2., 3.);
    // let m1 = Mat3x2f::new(&[v3, v3]);
    // let m2 = Mat2x3f::new(&[v2, v2, v2]);

    // let m3: Mat2x2f = m1.mul(&m2);
    // let m4 = m3.mul(&m3);
    // println!("{:?}", m3);
}
#[test]
fn matrix_identity() {
    // use vector::*;
    // let m = Mat2x2f::identity();
}

pub type Mat4x4<T> = Matrix<T, U4, U4>;
pub type Mat3x3<T> = Matrix<T, U3, U3>;
pub type Mat3x2<T> = Matrix<T, U3, U2>;
pub type Mat2x3<T> = Matrix<T, U2, U3>;
pub type Mat2x2<T> = Matrix<T, U2, U2>;
pub type Mat4x1<T> = Matrix<T, U4, U2>;

pub type Mat4x4f = Mat4x4<f32>;
pub type Mat4x1f = Mat4x1<f32>;
pub type Mat3x2f = Mat3x2<f32>;
pub type Mat2x3f = Mat2x3<f32>;
pub type Mat2x2f = Mat2x2<f32>;
<commit_msg>Wrong inverse fixed<commit_after>#![allow(dead_code)]
use num::Float;
use typenum::*;
use generic_array::*;
use std::ops;
use std::ops::{Index, IndexMut, Mul};
use std::mem;

use vector::*;

#[derive(PartialEq, Eq, Debug, Clone)]
pub struct Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T>,
          M: ArrayLength<Vector<T, N>>,
          N::ArrayType: Copy,
          M::ArrayType: Copy
{
    data: GenericArray<Vector<T, N>, M>,
}

impl<T, N, M> Mul<T> for Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T>,
          M: ArrayLength<Vector<T, N>>,
          N::ArrayType: Copy,
          M::ArrayType: Copy,
          Vector<T, N>: Copy
{
    type Output = Matrix<T, N, M>;
    fn mul(self, scalar: T) -> Self::Output {
        let mut m = Self::zero();
        for (index, new_val) in self.data.into_iter().map(|v| v * scalar).enumerate() {
            m.data[index] = new_val;
        }
        m
    }
}
impl<T, N, M> Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T>,
          M: ArrayLength<Vector<T, N>>,
          N::ArrayType: Copy,
          M::ArrayType: Copy,
          Vector<T, N>: Copy
{
    pub fn new(slice: &[Vector<T, N>]) -> Matrix<T, N, M> {
        Matrix::<T, N, M> { data: GenericArray::from_slice(slice) }
    }

    pub fn zero() -> Matrix<T, N, M> {
        unsafe {
            let mut mat: Matrix<T, N, M> = mem::uninitialized();
            for j in 0..M::to_usize() {
                mat.data[j] = Vector::<T, N>::zero();
            }
            mat
        }
    }
}
impl<T, N> Matrix<T, N, N>
    where T: Float,
          N: ArrayLength<T> + ArrayLength<Vector<T, N>>,
          <N as ArrayLength<T>>::ArrayType: Copy,
          <N as ArrayLength<Vector<T, N>>>::ArrayType: Copy,
          Vector<T, N>: Copy
{
    fn identity() -> Matrix<T, N, N> {
        let mut mat = Matrix::<T, N, N>::zero();
        for index in 0..N::to_usize() {
            mat.data[index].data[index] = T::one();
        }
        mat
    }
}

impl<T, N, M> Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T> + ArrayLength<Vector<T, M>>,
          M: ArrayLength<T> + ArrayLength<Vector<T, N>>,
          <N as ArrayLength<Vector<T, M>>>::ArrayType: Copy,
          <M as ArrayLength<Vector<T, N>>>::ArrayType: Copy,
          <N as ArrayLength<T>>::ArrayType: Copy,
          <M as ArrayLength<T>>::ArrayType: Copy
{
    fn transpose(&self) -> Matrix<T, M, N> {
        unsafe {
            let mut data: GenericArray<Vector<T, M>, N> = mem::uninitialized();
            for j in 0..N::to_usize() {
                for i in 0..M::to_usize() {
                    data[j].data[i] = self.data[i].data[j];
                }
            }
            Matrix::<T, M, N> { data: data }
        }
    }
}
// funny stuff is happening here
impl<T, N, M> Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T> + ArrayLength<Vector<T, M>>,
          M: ArrayLength<T> + ArrayLength<Vector<T, N>>,
          <N as ArrayLength<Vector<T, M>>>::ArrayType: Copy,
          <M as ArrayLength<Vector<T, N>>>::ArrayType: Copy,
          <N as ArrayLength<T>>::ArrayType: Copy,
          <M as ArrayLength<T>>::ArrayType: Copy
{
    pub fn mul_v(&self, other: Vector<T, N>) -> Vector<T, N>
        where Vector<T, N>: Copy
    {
        let mut v = Vector::<T, N>::zero();
        for index in 0..N::to_usize() {
            v.data[index] = self.data[index].dot(other);
        }
        v
    }
    pub fn mul<N1>(&self, other: &Matrix<T, N1, N>) -> Matrix<T, M, N1>
        where N1: ArrayLength<T> + ArrayLength<Vector<T, M>> + ArrayLength<Vector<T, N>>,
              <N1 as ArrayLength<T>>::ArrayType: Copy,
              <N1 as ArrayLength<Vector<T, M>>>::ArrayType: Copy,
              <N1 as ArrayLength<Vector<T, N>>>::ArrayType: Copy,
              N: ArrayLength<Vector<T, N1>>,
              <N as ArrayLength<Vector<T, N1>>>::ArrayType: Copy,
              Vector<T, N>: Copy
    {
        unsafe {
            let mut new_matrix: Matrix<T, M, N1> = mem::uninitialized();
            let other_transposed: Matrix<T, N, N1> = other.transpose();
            for j in 0..N1::to_usize() {
                for i in 0..M::to_usize() {
                    new_matrix.data[j].data[i] = self.data[j].dot(other_transposed.data[i]);
                }
            }
            new_matrix
        }
    }
}

impl<T, N, M> Index<usize> for Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T>,
          M: ArrayLength<Vector<T, N>>,
          N::ArrayType: Copy,
          M::ArrayType: Copy
{
    type Output = Vector<T, N>;

    fn index(&self, idx: usize) -> &Vector<T, N> {
        &self.data[idx]
    }
}
impl<T, N, M> IndexMut<usize> for Matrix<T, N, M>
    where T: Float,
          N: ArrayLength<T>,
          M: ArrayLength<Vector<T, N>>,
          N::ArrayType: Copy,
          M::ArrayType: Copy
{
    fn index_mut(&mut self, idx: usize) -> &mut Vector<T, N> {
        &mut self.data[idx]
    }
}

impl<T> Matrix<T, U4, U4>
    where T: Float
{
    pub fn translate(v: Vec3<T>) -> Self {
        let mut m = Self::identity();
        *m.data[0].w_m() = v.x();
        *m.data[1].w_m() = v.y();
        *m.data[2].w_m() = v.z();
        m
    }

    pub fn scale(s: Vec3<T>) -> Self {
        let mut identity = Self::identity();
        for index in 0..s.dim() {
            identity.data[index].data[index] = s.data[index];
        }
        identity
    }

    #[cfg_attr(rustfmt, rustfmt_skip)]
    pub fn rotation_x(angle: T) -> Self {
        let s = angle.sin();
        let c = angle.cos();
        Self::new(&[Vec4::<T>::new(T::one(),  T::zero(),  T::zero(), T::zero()),
                    Vec4::<T>::new(T::zero(), c,         -s,         T::zero()),
                    Vec4::<T>::new(T::zero(), s,          c,         T::zero()),
                    Vec4::<T>::new(T::zero(), T::zero(),  T::zero(), T::one())])
    }

    #[cfg_attr(rustfmt, rustfmt_skip)]
    pub fn rotation_y(angle: T) -> Self {
        let s = angle.sin();
        let c = angle.cos();
        Self::new(&[Vec4::<T>::new(c,         T::zero(), s,         T::zero()),
                    Vec4::<T>::new(T::zero(), T::one(),  T::zero(), T::zero()),
                    Vec4::<T>::new(-s,        T::zero(), c,         T::zero()),
                    Vec4::<T>::new(T::zero(), T::zero(), T::zero(), T::one())])
    }

    #[cfg_attr(rustfmt, rustfmt_skip)]
    pub fn rotation_z(angle: T) -> Self {
        let s = angle.sin();
        let c = angle.cos();
        Self::new(&[Vec4::<T>::new(c,        -s,         T::zero(), T::zero()),
                    Vec4::<T>::new(s,         c,         T::zero(), T::zero()),
                    Vec4::<T>::new(T::zero(), T::zero(), T::one(),  T::zero()),
                    Vec4::<T>::new(T::zero(), T::zero(), T::zero(), T::one())])
    }

    pub fn inverse(&self) -> Self {
        let coef00 = self[2][2] * self[3][3] - self[3][2] * self[2][3];
        let coef02 = self[1][2] * self[3][3] - self[3][2] * self[1][3];
        let coef03 = self[1][2] * self[2][3] - self[2][2] * self[1][3];

        let coef04 = self[2][1] * self[3][3] - self[3][1] * self[2][3];
        let coef06 = self[1][1] * self[3][3] - self[3][1] * self[1][3];
        let coef07 = self[1][1] * self[2][3] - self[2][1] * self[1][3];

        let coef08 = self[2][1] * self[3][2] - self[3][1] * self[2][2];
        let coef10 = self[1][1] * self[3][2] - self[3][1] * self[1][2];
        let coef11 = self[1][1] * self[2][2] - self[2][1] * self[1][2];

        let coef12 = self[2][0] * self[3][3] - self[3][0] * self[2][3];
        let coef14 = self[1][0] * self[3][3] - self[3][0] * self[1][3];
        let coef15 = self[1][0] * self[2][3] - self[2][0] * self[1][3];

        let coef16 = self[2][0] * self[3][2] - self[3][0] * self[2][2];
        let coef18 = self[1][0] * self[3][2] - self[3][0] * self[1][2];
        let coef19 = self[1][0] * self[2][2] - self[2][0] * self[1][2];

        let coef20 = self[2][0] * self[3][1] - self[3][0] * self[2][1];
        let coef22 = self[1][0] * self[3][1] - self[3][0] * self[1][1];
        let coef23 = self[1][0] * self[2][1] - self[2][0] * self[1][1];

        let fac0 = Vec4::new(coef00, coef00, coef02, coef03);
        let fac1 = Vec4::new(coef04, coef04, coef06, coef07);
        let fac2 = Vec4::new(coef08, coef08, coef10, coef11);
        let fac3 = Vec4::new(coef12, coef12, coef14, coef15);
        let fac4 = Vec4::new(coef16, coef16, coef18, coef19);
        let fac5 = Vec4::new(coef20, coef20, coef22, coef23);

        let vec0 = Vec4::new(self[1][0], self[0][0], self[0][0], self[0][0]);
        let vec1 = Vec4::new(self[1][1], self[0][1], self[0][1], self[0][1]);
        let vec2 = Vec4::new(self[1][2], self[0][2], self[0][2], self[0][2]);
        let vec3 = Vec4::new(self[1][3], self[0][3], self[0][3], self[0][3]);

        let inv0 = vec1 * fac0 - vec2 * fac1 + vec3 * fac2;
        let inv1 = vec0 * fac0 - vec2 * fac3 + vec3 * fac4;
        let inv2 = vec0 * fac1 - vec1 * fac3 + vec3 * fac5;
        let inv3 = vec0 * fac2 - vec1 * fac4 + vec2 * fac5;

        let sign_a = Vec4::new(T::one(), -T::one(), T::one(), -T::one());
        let sign_b = Vec4::new(-T::one(), T::one(), -T::one(), T::one());

        let inverse = Self::new(&[inv0 * sign_a, inv1 * sign_b, inv2 * sign_a, inv3 * sign_b]);

        let row0 = Vec4::new(inverse[0][0], inverse[1][0], inverse[2][0], inverse[3][0]);

        let dot0 = self[0] * row0;
        let dot1 = (dot0.x() + dot0.y()) + (dot0.z() + dot0.w());

        let one_over_det = T::one() / dot1;
        inverse * one_over_det
    }
}

#[cfg(test)]
mod test {
    use vector::*;
    use matrix::*;
    #[test]
    fn rot_x() {
        use std::f32;
        let v = Vec4f::new(0., 0., 1., 0.);
        let pi = f32::consts::PI;
        let m = Mat4x4f::rotation_x(pi / 2.0);
        let v2 = m.mul_v(v);
        println!("{:?}", v2);
    }
}
#[test]
fn mul() {
    // use vector::*;
    // let v2 = Vec2f::new(1., 2.);
    // let v3 = Vec3f::new(1., 2., 3.);
    // let m1 = Mat3x2f::new(&[v3, v3]);
    // let m2 = Mat2x3f::new(&[v2, v2, v2]);

    // let m3: Mat2x2f = m1.mul(&m2);
    // let m4 = m3.mul(&m3);
    // println!("{:?}", m3);
}
#[test]
fn matrix_identity() {
    // use vector::*;
    // let m = Mat2x2f::identity();
}

pub type Mat4x4<T> = Matrix<T, U4, U4>;
pub type Mat3x3<T> = Matrix<T, U3, U3>;
pub type Mat3x2<T> = Matrix<T, U3, U2>;
pub type Mat2x3<T> = Matrix<T, U2, U3>;
pub type Mat2x2<T> = Matrix<T, U2, U2>;
pub type Mat4x1<T> = Matrix<T, U4, U2>;

pub type Mat4x4f = Mat4x4<f32>;
pub type Mat4x1f = Mat4x1<f32>;
pub type Mat3x2f = Mat3x2<f32>;
pub type Mat2x3f = Mat2x3<f32>;
pub type Mat2x2f = Mat2x2<f32>;
<|endoftext|>


<commit_before>// ignore-windows: File handling is not implemented yet
// compile-flags: -Zmiri-disable-isolation

#![feature(rustc_private)]

use std::fs::{
    File, create_dir, OpenOptions, read_dir, remove_dir, remove_dir_all, remove_file, rename,
};
use std::ffi::CString;
use std::io::{Read, Write, Error, ErrorKind, Result, Seek, SeekFrom};
use std::path::{PathBuf, Path};

extern crate libc;

fn main() {
    test_file();
    test_file_clone();
    test_file_create_new();
    test_seek();
    test_metadata();
    test_file_set_len();
    test_file_sync();
    test_symlink();
    test_errors();
    test_rename();
    test_directory();
    test_dup_stdout_stderr();
}

fn tmp() -> PathBuf {
    std::env::var("MIRI_TEMP").map(PathBuf::from).unwrap_or_else(|_| std::env::temp_dir())
}

/// Prepare: compute filename and make sure the file does not exist.
fn prepare(filename: &str) -> PathBuf {
    let path = tmp().join(filename);
    // Clean the paths for robustness.
    remove_file(&path).ok();
    path
}

/// Prepare directory: compute directory name and make sure it does not exist.
fn prepare_dir(dirname: &str) -> PathBuf {
    let path = tmp().join(&dirname);
    // Clean the directory for robustness.
    remove_dir_all(&path).ok();
    path
}

/// Prepare like above, and also write some initial content to the file.
fn prepare_with_content(filename: &str, content: &[u8]) -> PathBuf {
    let path = prepare(filename);
    let mut file = File::create(&path).unwrap();
    file.write(content).unwrap();
    path
}

fn test_file() {
    let bytes = b"Hello, World!\n";
    let path = prepare("miri_test_fs_file.txt");

    // Test creating, writing and closing a file (closing is tested when `file` is dropped).
    let mut file = File::create(&path).unwrap();
    // Writing 0 bytes should not change the file contents.
    file.write(&mut []).unwrap();
    assert_eq!(file.metadata().unwrap().len(), 0);

    file.write(bytes).unwrap();
    assert_eq!(file.metadata().unwrap().len(), bytes.len() as u64);
    // Test opening, reading and closing a file.
    let mut file = File::open(&path).unwrap();
    let mut contents = Vec::new();
    // Reading 0 bytes should not move the file pointer.
    file.read(&mut []).unwrap();
    // Reading until EOF should get the whole text.
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes, contents.as_slice());

    // Removing file should succeed.
    remove_file(&path).unwrap();
}

fn test_file_clone() {
    let bytes = b"Hello, World!\n";
    let path = prepare_with_content("miri_test_fs_file_clone.txt", bytes);

    // Cloning a file should be successful.
    let file = File::open(&path).unwrap();
    let mut cloned = file.try_clone().unwrap();
    // Reading from a cloned file should get the same text.
    let mut contents = Vec::new();
    cloned.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes, contents.as_slice());

    // Removing file should succeed.
    remove_file(&path).unwrap();
}

fn test_file_create_new() {
    let path = prepare("miri_test_fs_file_create_new.txt");

    // Creating a new file that doesn't yet exist should succeed.
    OpenOptions::new().write(true).create_new(true).open(&path).unwrap();
    // Creating a new file that already exists should fail.
    assert_eq!(ErrorKind::AlreadyExists, OpenOptions::new().write(true).create_new(true).open(&path).unwrap_err().kind());
    // Optionally creating a new file that already exists should succeed.
    OpenOptions::new().write(true).create(true).open(&path).unwrap();

    // Clean up
    remove_file(&path).unwrap();
}

fn test_seek() {
    let bytes = b"Hello, entire World!\n";
    let path = prepare_with_content("miri_test_fs_seek.txt", bytes);

    let mut file = File::open(&path).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes, contents.as_slice());
    // Test that seeking to the beginning and reading until EOF gets the text again.
    file.seek(SeekFrom::Start(0)).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes, contents.as_slice());
    // Test seeking relative to the end of the file.
    file.seek(SeekFrom::End(-1)).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(&bytes[bytes.len() - 1..], contents.as_slice());
    // Test seeking relative to the current position.
    file.seek(SeekFrom::Start(5)).unwrap();
    file.seek(SeekFrom::Current(-3)).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(&bytes[2..], contents.as_slice());

    // Removing file should succeed.
    remove_file(&path).unwrap();
}

fn check_metadata(bytes: &[u8], path: &Path) -> Result<()> {
    // Test that the file metadata is correct.
    let metadata = path.metadata()?;
    // `path` should point to a file.
    assert!(metadata.is_file());
    // The size of the file must be equal to the number of written bytes.
    assert_eq!(bytes.len() as u64, metadata.len());
    Ok(())
}

fn test_metadata() {
    let bytes = b"Hello, meta-World!\n";
    let path = prepare_with_content("miri_test_fs_metadata.txt", bytes);

    // Test that metadata of an absolute path is correct.
    check_metadata(bytes, &path).unwrap();
    // Test that metadata of a relative path is correct.
    std::env::set_current_dir(path.parent().unwrap()).unwrap();
    check_metadata(bytes, Path::new(path.file_name().unwrap())).unwrap();

    // Removing file should succeed.
    remove_file(&path).unwrap();
}

fn test_file_set_len() {
    let bytes = b"Hello, World!\n";
    let path = prepare_with_content("miri_test_fs_set_len.txt", bytes);

    // Test extending the file
    let mut file = OpenOptions::new().read(true).write(true).open(&path).unwrap();
    let bytes_extended = b"Hello, World!\n\x00\x00\x00\x00\x00\x00";
    file.set_len(20).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes_extended, contents.as_slice());

    // Test truncating the file
    file.seek(SeekFrom::Start(0)).unwrap();
    file.set_len(10).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(&bytes[..10], contents.as_slice());

    // Can't use set_len on a file not opened for writing
    let file = OpenOptions::new().read(true).open(&path).unwrap();
    assert_eq!(ErrorKind::InvalidInput, file.set_len(14).unwrap_err().kind());

    remove_file(&path).unwrap();
}

fn test_file_sync() {
    let bytes = b"Hello, World!\n";
    let path = prepare_with_content("miri_test_fs_sync.txt", bytes);

    // Test that we can call sync_data and sync_all (can't readily test effects of this operation)
    let file = OpenOptions::new().write(true).open(&path).unwrap();
    file.sync_data().unwrap();
    file.sync_all().unwrap();

    // Test that we can call sync_data and sync_all on a file opened for reading.
    let file = File::open(&path).unwrap();
    file.sync_data().unwrap();
    file.sync_all().unwrap();

    remove_file(&path).unwrap();
}

fn test_symlink() {
    let bytes = b"Hello, World!\n";
    let path = prepare_with_content("miri_test_fs_link_target.txt", bytes);
    let symlink_path = prepare("miri_test_fs_symlink.txt");

    // Creating a symbolic link should succeed.
    #[cfg(unix)]
    std::os::unix::fs::symlink(&path, &symlink_path).unwrap();
    #[cfg(windows)]
    std::os::windows::fs::symlink_file(&path, &symlink_path).unwrap();
    // Test that the symbolic link has the same contents as the file.
    let mut symlink_file = File::open(&symlink_path).unwrap();
    let mut contents = Vec::new();
    symlink_file.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes, contents.as_slice());

    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;

        let expected_path = path.as_os_str().as_bytes();

        // Test that the expected string gets written to a buffer of proper
        // length, and that a trailing null byte is not written.
        let symlink_c_str = CString::new(symlink_path.as_os_str().as_bytes()).unwrap();
        let symlink_c_ptr = symlink_c_str.as_ptr();

        // Make the buf one byte larger than it needs to be,
        // and check that the last byte is not overwritten.
        let mut large_buf = vec![0xFF; expected_path.len() + 1];
        let res = unsafe { libc::readlink(symlink_c_ptr, large_buf.as_mut_ptr().cast(), large_buf.len()) };
        // Check that the resovled path was properly written into the buf.
        assert_eq!(&large_buf[..(large_buf.len() - 1)], expected_path);
        assert_eq!(large_buf.last(), Some(&0xFF));
        assert_eq!(res, large_buf.len() as isize - 1);

        // Test that the resolved path is truncated if the provided buffer
        // is too small.
        let mut small_buf = [0u8; 2];
        let res = unsafe { libc::readlink(symlink_c_ptr, small_buf.as_mut_ptr().cast(), small_buf.len()) };
        assert_eq!(small_buf, &expected_path[..small_buf.len()]);
        assert_eq!(res, small_buf.len() as isize);

        // Test that we report a proper error for a missing path.
        let bad_path = CString::new("MIRI_MISSING_FILE_NAME").unwrap();
        let res = unsafe { libc::readlink(bad_path.as_ptr(), small_buf.as_mut_ptr().cast(), small_buf.len()) };
        assert_eq!(res, -1);
        assert_eq!(Error::last_os_error().kind(), ErrorKind::NotFound);
    }

    // Test that metadata of a symbolic link is correct.
    check_metadata(bytes, &symlink_path).unwrap();
    // Test that the metadata of a symbolic link is correct when not following it.
    assert!(symlink_path.symlink_metadata().unwrap().file_type().is_symlink());
    // Removing symbolic link should succeed.
    remove_file(&symlink_path).unwrap();

    // Removing file should succeed.
    remove_file(&path).unwrap();
}

fn test_errors() {
    let bytes = b"Hello, World!\n";
    let path = prepare("miri_test_fs_errors.txt");

    // The following tests also check that the `__errno_location()` shim is working properly.
    // Opening a non-existing file should fail with a "not found" error.
    assert_eq!(ErrorKind::NotFound, File::open(&path).unwrap_err().kind());
    // Removing a non-existing file should fail with a "not found" error.
    assert_eq!(ErrorKind::NotFound, remove_file(&path).unwrap_err().kind());
    // Reading the metadata of a non-existing file should fail with a "not found" error.
    assert_eq!(ErrorKind::NotFound, check_metadata(bytes, &path).unwrap_err().kind());
}

fn test_rename() {
    // Renaming a file should succeed.
    let path1 = prepare("miri_test_fs_rename_source.txt");
    let path2 = prepare("miri_test_fs_rename_destination.txt");

    let file = File::create(&path1).unwrap();
    drop(file);

    // Renaming should succeed
    rename(&path1, &path2).unwrap();
    // Check that the old file path isn't present
    assert_eq!(ErrorKind::NotFound, path1.metadata().unwrap_err().kind());
    // Check that the file has moved successfully
    assert!(path2.metadata().unwrap().is_file());

    // Renaming a nonexistent file should fail
    assert_eq!(ErrorKind::NotFound, rename(&path1, &path2).unwrap_err().kind());

    remove_file(&path2).unwrap();
}

fn test_directory() {
    let dir_path = prepare_dir("miri_test_fs_dir");
    // Creating a directory should succeed.
    create_dir(&dir_path).unwrap();
    // Test that the metadata of a directory is correct.
    assert!(dir_path.metadata().unwrap().is_dir());
    // Creating a directory when it already exists should fail.
    assert_eq!(ErrorKind::AlreadyExists, create_dir(&dir_path).unwrap_err().kind());

    // Create some files inside the directory
    let path_1 = dir_path.join("test_file_1");
    drop(File::create(&path_1).unwrap());
    let path_2 = dir_path.join("test_file_2");
    drop(File::create(&path_2).unwrap());
    // Test that the files are present inside the directory
    let dir_iter = read_dir(&dir_path).unwrap();
    let mut file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
    file_names.sort_unstable();
    assert_eq!(file_names, vec!["test_file_1", "test_file_2"]);
    // Clean up the files in the directory
    remove_file(&path_1).unwrap();
    remove_file(&path_2).unwrap();
    // Now there should be nothing left in the directory.
    let dir_iter = read_dir(&dir_path).unwrap();
    let file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
    assert!(file_names.is_empty());

    // Deleting the directory should succeed.
    remove_dir(&dir_path).unwrap();
    // Reading the metadata of a non-existent directory should fail with a "not found" error.
    assert_eq!(ErrorKind::NotFound, check_metadata(&[], &dir_path).unwrap_err().kind());
}

fn test_dup_stdout_stderr() {
    let bytes = b"hello dup fd\n";
    unsafe {
        let new_stdout = libc::fcntl(1, libc::F_DUPFD, 0);
        let new_stderr = libc::fcntl(2, libc::F_DUPFD, 0);
        libc::write(new_stdout, bytes.as_ptr() as *const libc::c_void, bytes.len());
        libc::write(new_stderr, bytes.as_ptr() as *const libc::c_void, bytes.len());
    }
}
<commit_msg>Normalize MIRI_TEMP before using it<commit_after>// ignore-windows: File handling is not implemented yet
// compile-flags: -Zmiri-disable-isolation

#![feature(rustc_private)]

use std::fs::{
    File, create_dir, OpenOptions, read_dir, remove_dir, remove_dir_all, remove_file, rename,
};
use std::ffi::CString;
use std::io::{Read, Write, Error, ErrorKind, Result, Seek, SeekFrom};
use std::path::{PathBuf, Path};

extern crate libc;

fn main() {
    test_file();
    test_file_clone();
    test_file_create_new();
    test_seek();
    test_metadata();
    test_file_set_len();
    test_file_sync();
    test_symlink();
    test_errors();
    test_rename();
    test_directory();
    test_dup_stdout_stderr();
}

fn tmp() -> PathBuf {
    std::env::var("MIRI_TEMP")
        .map(|tmp| {
            // MIRI_TEMP is set outside of our emulated
            // program, so it may have path separators that don't
            // correspond to our target platform. We normalize them here
            // before constructing a `PathBuf`

            #[cfg(windows)]
            return PathBuf::from(tmp.replace("/", "\\"));

            #[cfg(not(windows))]
            return PathBuf::from(tmp.replace("\\", "/"));
        }).unwrap_or_else(|_| std::env::temp_dir())
}

/// Prepare: compute filename and make sure the file does not exist.
fn prepare(filename: &str) -> PathBuf {
    let path = tmp().join(filename);
    // Clean the paths for robustness.
    remove_file(&path).ok();
    path
}

/// Prepare directory: compute directory name and make sure it does not exist.
fn prepare_dir(dirname: &str) -> PathBuf {
    let path = tmp().join(&dirname);
    // Clean the directory for robustness.
    remove_dir_all(&path).ok();
    path
}

/// Prepare like above, and also write some initial content to the file.
fn prepare_with_content(filename: &str, content: &[u8]) -> PathBuf {
    let path = prepare(filename);
    let mut file = File::create(&path).unwrap();
    file.write(content).unwrap();
    path
}

fn test_file() {
    let bytes = b"Hello, World!\n";
    let path = prepare("miri_test_fs_file.txt");

    // Test creating, writing and closing a file (closing is tested when `file` is dropped).
    let mut file = File::create(&path).unwrap();
    // Writing 0 bytes should not change the file contents.
    file.write(&mut []).unwrap();
    assert_eq!(file.metadata().unwrap().len(), 0);

    file.write(bytes).unwrap();
    assert_eq!(file.metadata().unwrap().len(), bytes.len() as u64);
    // Test opening, reading and closing a file.
    let mut file = File::open(&path).unwrap();
    let mut contents = Vec::new();
    // Reading 0 bytes should not move the file pointer.
    file.read(&mut []).unwrap();
    // Reading until EOF should get the whole text.
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes, contents.as_slice());

    // Removing file should succeed.
    remove_file(&path).unwrap();
}

fn test_file_clone() {
    let bytes = b"Hello, World!\n";
    let path = prepare_with_content("miri_test_fs_file_clone.txt", bytes);

    // Cloning a file should be successful.
    let file = File::open(&path).unwrap();
    let mut cloned = file.try_clone().unwrap();
    // Reading from a cloned file should get the same text.
    let mut contents = Vec::new();
    cloned.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes, contents.as_slice());

    // Removing file should succeed.
    remove_file(&path).unwrap();
}

fn test_file_create_new() {
    let path = prepare("miri_test_fs_file_create_new.txt");

    // Creating a new file that doesn't yet exist should succeed.
    OpenOptions::new().write(true).create_new(true).open(&path).unwrap();
    // Creating a new file that already exists should fail.
    assert_eq!(ErrorKind::AlreadyExists, OpenOptions::new().write(true).create_new(true).open(&path).unwrap_err().kind());
    // Optionally creating a new file that already exists should succeed.
    OpenOptions::new().write(true).create(true).open(&path).unwrap();

    // Clean up
    remove_file(&path).unwrap();
}

fn test_seek() {
    let bytes = b"Hello, entire World!\n";
    let path = prepare_with_content("miri_test_fs_seek.txt", bytes);

    let mut file = File::open(&path).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes, contents.as_slice());
    // Test that seeking to the beginning and reading until EOF gets the text again.
    file.seek(SeekFrom::Start(0)).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes, contents.as_slice());
    // Test seeking relative to the end of the file.
    file.seek(SeekFrom::End(-1)).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(&bytes[bytes.len() - 1..], contents.as_slice());
    // Test seeking relative to the current position.
    file.seek(SeekFrom::Start(5)).unwrap();
    file.seek(SeekFrom::Current(-3)).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(&bytes[2..], contents.as_slice());

    // Removing file should succeed.
    remove_file(&path).unwrap();
}

fn check_metadata(bytes: &[u8], path: &Path) -> Result<()> {
    // Test that the file metadata is correct.
    let metadata = path.metadata()?;
    // `path` should point to a file.
    assert!(metadata.is_file());
    // The size of the file must be equal to the number of written bytes.
    assert_eq!(bytes.len() as u64, metadata.len());
    Ok(())
}

fn test_metadata() {
    let bytes = b"Hello, meta-World!\n";
    let path = prepare_with_content("miri_test_fs_metadata.txt", bytes);

    // Test that metadata of an absolute path is correct.
    check_metadata(bytes, &path).unwrap();
    // Test that metadata of a relative path is correct.
    std::env::set_current_dir(path.parent().unwrap()).unwrap();
    check_metadata(bytes, Path::new(path.file_name().unwrap())).unwrap();

    // Removing file should succeed.
    remove_file(&path).unwrap();
}

fn test_file_set_len() {
    let bytes = b"Hello, World!\n";
    let path = prepare_with_content("miri_test_fs_set_len.txt", bytes);

    // Test extending the file
    let mut file = OpenOptions::new().read(true).write(true).open(&path).unwrap();
    let bytes_extended = b"Hello, World!\n\x00\x00\x00\x00\x00\x00";
    file.set_len(20).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes_extended, contents.as_slice());

    // Test truncating the file
    file.seek(SeekFrom::Start(0)).unwrap();
    file.set_len(10).unwrap();
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).unwrap();
    assert_eq!(&bytes[..10], contents.as_slice());

    // Can't use set_len on a file not opened for writing
    let file = OpenOptions::new().read(true).open(&path).unwrap();
    assert_eq!(ErrorKind::InvalidInput, file.set_len(14).unwrap_err().kind());

    remove_file(&path).unwrap();
}

fn test_file_sync() {
    let bytes = b"Hello, World!\n";
    let path = prepare_with_content("miri_test_fs_sync.txt", bytes);

    // Test that we can call sync_data and sync_all (can't readily test effects of this operation)
    let file = OpenOptions::new().write(true).open(&path).unwrap();
    file.sync_data().unwrap();
    file.sync_all().unwrap();

    // Test that we can call sync_data and sync_all on a file opened for reading.
    let file = File::open(&path).unwrap();
    file.sync_data().unwrap();
    file.sync_all().unwrap();

    remove_file(&path).unwrap();
}

fn test_symlink() {
    let bytes = b"Hello, World!\n";
    let path = prepare_with_content("miri_test_fs_link_target.txt", bytes);
    let symlink_path = prepare("miri_test_fs_symlink.txt");

    // Creating a symbolic link should succeed.
    #[cfg(unix)]
    std::os::unix::fs::symlink(&path, &symlink_path).unwrap();
    #[cfg(windows)]
    std::os::windows::fs::symlink_file(&path, &symlink_path).unwrap();
    // Test that the symbolic link has the same contents as the file.
    let mut symlink_file = File::open(&symlink_path).unwrap();
    let mut contents = Vec::new();
    symlink_file.read_to_end(&mut contents).unwrap();
    assert_eq!(bytes, contents.as_slice());

    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;

        let expected_path = path.as_os_str().as_bytes();

        // Test that the expected string gets written to a buffer of proper
        // length, and that a trailing null byte is not written.
        let symlink_c_str = CString::new(symlink_path.as_os_str().as_bytes()).unwrap();
        let symlink_c_ptr = symlink_c_str.as_ptr();

        // Make the buf one byte larger than it needs to be,
        // and check that the last byte is not overwritten.
        let mut large_buf = vec![0xFF; expected_path.len() + 1];
        let res = unsafe { libc::readlink(symlink_c_ptr, large_buf.as_mut_ptr().cast(), large_buf.len()) };
        // Check that the resovled path was properly written into the buf.
        assert_eq!(&large_buf[..(large_buf.len() - 1)], expected_path);
        assert_eq!(large_buf.last(), Some(&0xFF));
        assert_eq!(res, large_buf.len() as isize - 1);

        // Test that the resolved path is truncated if the provided buffer
        // is too small.
        let mut small_buf = [0u8; 2];
        let res = unsafe { libc::readlink(symlink_c_ptr, small_buf.as_mut_ptr().cast(), small_buf.len()) };
        assert_eq!(small_buf, &expected_path[..small_buf.len()]);
        assert_eq!(res, small_buf.len() as isize);

        // Test that we report a proper error for a missing path.
        let bad_path = CString::new("MIRI_MISSING_FILE_NAME").unwrap();
        let res = unsafe { libc::readlink(bad_path.as_ptr(), small_buf.as_mut_ptr().cast(), small_buf.len()) };
        assert_eq!(res, -1);
        assert_eq!(Error::last_os_error().kind(), ErrorKind::NotFound);
    }

    // Test that metadata of a symbolic link is correct.
    check_metadata(bytes, &symlink_path).unwrap();
    // Test that the metadata of a symbolic link is correct when not following it.
    assert!(symlink_path.symlink_metadata().unwrap().file_type().is_symlink());
    // Removing symbolic link should succeed.
    remove_file(&symlink_path).unwrap();

    // Removing file should succeed.
    remove_file(&path).unwrap();
}

fn test_errors() {
    let bytes = b"Hello, World!\n";
    let path = prepare("miri_test_fs_errors.txt");

    // The following tests also check that the `__errno_location()` shim is working properly.
    // Opening a non-existing file should fail with a "not found" error.
    assert_eq!(ErrorKind::NotFound, File::open(&path).unwrap_err().kind());
    // Removing a non-existing file should fail with a "not found" error.
    assert_eq!(ErrorKind::NotFound, remove_file(&path).unwrap_err().kind());
    // Reading the metadata of a non-existing file should fail with a "not found" error.
    assert_eq!(ErrorKind::NotFound, check_metadata(bytes, &path).unwrap_err().kind());
}

fn test_rename() {
    // Renaming a file should succeed.
    let path1 = prepare("miri_test_fs_rename_source.txt");
    let path2 = prepare("miri_test_fs_rename_destination.txt");

    let file = File::create(&path1).unwrap();
    drop(file);

    // Renaming should succeed
    rename(&path1, &path2).unwrap();
    // Check that the old file path isn't present
    assert_eq!(ErrorKind::NotFound, path1.metadata().unwrap_err().kind());
    // Check that the file has moved successfully
    assert!(path2.metadata().unwrap().is_file());

    // Renaming a nonexistent file should fail
    assert_eq!(ErrorKind::NotFound, rename(&path1, &path2).unwrap_err().kind());

    remove_file(&path2).unwrap();
}

fn test_directory() {
    let dir_path = prepare_dir("miri_test_fs_dir");
    // Creating a directory should succeed.
    create_dir(&dir_path).unwrap();
    // Test that the metadata of a directory is correct.
    assert!(dir_path.metadata().unwrap().is_dir());
    // Creating a directory when it already exists should fail.
    assert_eq!(ErrorKind::AlreadyExists, create_dir(&dir_path).unwrap_err().kind());

    // Create some files inside the directory
    let path_1 = dir_path.join("test_file_1");
    drop(File::create(&path_1).unwrap());
    let path_2 = dir_path.join("test_file_2");
    drop(File::create(&path_2).unwrap());
    // Test that the files are present inside the directory
    let dir_iter = read_dir(&dir_path).unwrap();
    let mut file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
    file_names.sort_unstable();
    assert_eq!(file_names, vec!["test_file_1", "test_file_2"]);
    // Clean up the files in the directory
    remove_file(&path_1).unwrap();
    remove_file(&path_2).unwrap();
    // Now there should be nothing left in the directory.
    let dir_iter = read_dir(&dir_path).unwrap();
    let file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
    assert!(file_names.is_empty());

    // Deleting the directory should succeed.
    remove_dir(&dir_path).unwrap();
    // Reading the metadata of a non-existent directory should fail with a "not found" error.
    assert_eq!(ErrorKind::NotFound, check_metadata(&[], &dir_path).unwrap_err().kind());
}

fn test_dup_stdout_stderr() {
    let bytes = b"hello dup fd\n";
    unsafe {
        let new_stdout = libc::fcntl(1, libc::F_DUPFD, 0);
        let new_stderr = libc::fcntl(2, libc::F_DUPFD, 0);
        libc::write(new_stdout, bytes.as_ptr() as *const libc::c_void, bytes.len());
        libc::write(new_stderr, bytes.as_ptr() as *const libc::c_void, bytes.len());
    }
}
<|endoftext|>


<commit_before>#![allow(dead_code)]

use std::fmt;
use std::sync::Arc;
use std::thread;

use futures::{Future, IntoFuture, Async, Poll};
use futures::future::FutureResult;
use futures::stream::Stream;
use futures::executor::{self, NotifyHandle, Notify};
use futures::task;

pub mod local_executor;

pub fn f_ok(a: i32) -> FutureResult<i32, u32> { Ok(a).into_future() }
pub fn f_err(a: u32) -> FutureResult<i32, u32> { Err(a).into_future() }
pub fn r_ok(a: i32) -> Result<i32, u32> { Ok(a) }
pub fn r_err(a: u32) -> Result<i32, u32> { Err(a) }

pub fn assert_done<T, F>(f: F, result: Result<T::Item, T::Error>)
    where T: Future,
          T::Item: Eq + fmt::Debug,
          T::Error: Eq + fmt::Debug,
          F: FnOnce() -> T,
{
    assert_eq!(f().wait(), result);
}

pub fn assert_empty<T: Future, F: FnMut() -> T>(mut f: F) {
    assert!(executor::spawn(f()).poll_future_notify(&notify_panic(), 0).ok().unwrap().is_not_ready());
}

pub fn sassert_done<S: Stream>(s: &mut S) {
    match executor::spawn(s).poll_stream_notify(&notify_panic(), 0) {
        Ok(Async::Ready(None)) => {}
        Ok(Async::Ready(Some(_))) => panic!("stream had more elements"),
        Ok(Async::NotReady) => panic!("stream wasn't ready"),
        Err(_) => panic!("stream had an error"),
    }
}

pub fn sassert_empty<S: Stream>(s: &mut S) {
    match executor::spawn(s).poll_stream_notify(&notify_noop(), 0) {
        Ok(Async::Ready(None)) => panic!("stream is at its end"),
        Ok(Async::Ready(Some(_))) => panic!("stream had more elements"),
        Ok(Async::NotReady) => {}
        Err(_) => panic!("stream had an error"),
    }
}

pub fn sassert_next<S: Stream>(s: &mut S, item: S::Item)
    where S::Item: Eq + fmt::Debug
{
    match executor::spawn(s).poll_stream_notify(&notify_panic(), 0) {
        Ok(Async::Ready(None)) => panic!("stream is at its end"),
        Ok(Async::Ready(Some(e))) => assert_eq!(e, item),
        Ok(Async::NotReady) => panic!("stream wasn't ready"),
        Err(_) => panic!("stream had an error"),
    }
}

pub fn sassert_err<S: Stream>(s: &mut S, err: S::Error)
    where S::Error: Eq + fmt::Debug
{
    match executor::spawn(s).poll_stream_notify(&notify_panic(), 0) {
        Ok(Async::Ready(None)) => panic!("stream is at its end"),
        Ok(Async::Ready(Some(_))) => panic!("stream had more elements"),
        Ok(Async::NotReady) => panic!("stream wasn't ready"),
        Err(e) => assert_eq!(e, err),
    }
}

pub fn notify_panic() -> NotifyHandle {
    struct Foo;

    impl Notify for Foo {
        fn notify(&self, _id: usize) {
            panic!("should not be notified");
        }
    }

    NotifyHandle::from(Arc::new(Foo))
}

pub fn notify_noop() -> NotifyHandle {
    struct Noop;

    impl Notify for Noop {
        fn notify(&self, _id: usize) {}
    }

    const NOOP : &'static Noop = &Noop;

    NotifyHandle::from(NOOP)
}

pub trait ForgetExt {
    fn forget(self);
}

impl<F> ForgetExt for F
    where F: Future + Sized + Send + 'static,
          F::Item: Send,
          F::Error: Send
{
    fn forget(self) {
        thread::spawn(|| self.wait());
    }
}

pub struct DelayFuture<F>(F,bool);

impl<F: Future> Future for DelayFuture<F> {
    type Item = F::Item;
    type Error = F::Error;

    fn poll(&mut self) -> Poll<F::Item,F::Error> {
        if self.1 {
            self.0.poll()
        } else {
            self.1 = true;
            task::current().notify();
            Ok(Async::NotReady)
        }
    }
}

/// Introduces one `Ok(Async::NotReady)` before polling the given future
pub fn delay_future<F>(f: F) -> DelayFuture<F::Future>
    where F: IntoFuture,
{
    DelayFuture(f.into_future(), false)
}

<commit_msg>chmod -x tests/support/mod.rs<commit_after>#![allow(dead_code)]

use std::fmt;
use std::sync::Arc;
use std::thread;

use futures::{Future, IntoFuture, Async, Poll};
use futures::future::FutureResult;
use futures::stream::Stream;
use futures::executor::{self, NotifyHandle, Notify};
use futures::task;

pub mod local_executor;

pub fn f_ok(a: i32) -> FutureResult<i32, u32> { Ok(a).into_future() }
pub fn f_err(a: u32) -> FutureResult<i32, u32> { Err(a).into_future() }
pub fn r_ok(a: i32) -> Result<i32, u32> { Ok(a) }
pub fn r_err(a: u32) -> Result<i32, u32> { Err(a) }

pub fn assert_done<T, F>(f: F, result: Result<T::Item, T::Error>)
    where T: Future,
          T::Item: Eq + fmt::Debug,
          T::Error: Eq + fmt::Debug,
          F: FnOnce() -> T,
{
    assert_eq!(f().wait(), result);
}

pub fn assert_empty<T: Future, F: FnMut() -> T>(mut f: F) {
    assert!(executor::spawn(f()).poll_future_notify(&notify_panic(), 0).ok().unwrap().is_not_ready());
}

pub fn sassert_done<S: Stream>(s: &mut S) {
    match executor::spawn(s).poll_stream_notify(&notify_panic(), 0) {
        Ok(Async::Ready(None)) => {}
        Ok(Async::Ready(Some(_))) => panic!("stream had more elements"),
        Ok(Async::NotReady) => panic!("stream wasn't ready"),
        Err(_) => panic!("stream had an error"),
    }
}

pub fn sassert_empty<S: Stream>(s: &mut S) {
    match executor::spawn(s).poll_stream_notify(&notify_noop(), 0) {
        Ok(Async::Ready(None)) => panic!("stream is at its end"),
        Ok(Async::Ready(Some(_))) => panic!("stream had more elements"),
        Ok(Async::NotReady) => {}
        Err(_) => panic!("stream had an error"),
    }
}

pub fn sassert_next<S: Stream>(s: &mut S, item: S::Item)
    where S::Item: Eq + fmt::Debug
{
    match executor::spawn(s).poll_stream_notify(&notify_panic(), 0) {
        Ok(Async::Ready(None)) => panic!("stream is at its end"),
        Ok(Async::Ready(Some(e))) => assert_eq!(e, item),
        Ok(Async::NotReady) => panic!("stream wasn't ready"),
        Err(_) => panic!("stream had an error"),
    }
}

pub fn sassert_err<S: Stream>(s: &mut S, err: S::Error)
    where S::Error: Eq + fmt::Debug
{
    match executor::spawn(s).poll_stream_notify(&notify_panic(), 0) {
        Ok(Async::Ready(None)) => panic!("stream is at its end"),
        Ok(Async::Ready(Some(_))) => panic!("stream had more elements"),
        Ok(Async::NotReady) => panic!("stream wasn't ready"),
        Err(e) => assert_eq!(e, err),
    }
}

pub fn notify_panic() -> NotifyHandle {
    struct Foo;

    impl Notify for Foo {
        fn notify(&self, _id: usize) {
            panic!("should not be notified");
        }
    }

    NotifyHandle::from(Arc::new(Foo))
}

pub fn notify_noop() -> NotifyHandle {
    struct Noop;

    impl Notify for Noop {
        fn notify(&self, _id: usize) {}
    }

    const NOOP : &'static Noop = &Noop;

    NotifyHandle::from(NOOP)
}

pub trait ForgetExt {
    fn forget(self);
}

impl<F> ForgetExt for F
    where F: Future + Sized + Send + 'static,
          F::Item: Send,
          F::Error: Send
{
    fn forget(self) {
        thread::spawn(|| self.wait());
    }
}

pub struct DelayFuture<F>(F,bool);

impl<F: Future> Future for DelayFuture<F> {
    type Item = F::Item;
    type Error = F::Error;

    fn poll(&mut self) -> Poll<F::Item,F::Error> {
        if self.1 {
            self.0.poll()
        } else {
            self.1 = true;
            task::current().notify();
            Ok(Async::NotReady)
        }
    }
}

/// Introduces one `Ok(Async::NotReady)` before polling the given future
pub fn delay_future<F>(f: F) -> DelayFuture<F::Future>
    where F: IntoFuture,
{
    DelayFuture(f.into_future(), false)
}

<|endoftext|>


<commit_before>use backend::graphics::egl::{EGLGraphicsBackend, SwapBuffersError};
use glium::SwapBuffersError as GliumSwapBuffersError;
use glium::backend::Backend;

use std::os::raw::c_void;

impl From<SwapBuffersError> for GliumSwapBuffersError {
    fn from(error: SwapBuffersError) -> Self {
        match error {
            SwapBuffersError::ContextLost => GliumSwapBuffersError::ContextLost,
            SwapBuffersError::AlreadySwapped => GliumSwapBuffersError::AlreadySwapped,
        }
    }
}

pub struct GliumGraphicBackend<T: EGLGraphicsBackend>(T);

pub trait IntoGlium: EGLGraphicsBackend + Sized {
    fn into_glium(self) -> GliumGraphicBackend<Self>;
}

impl<T: EGLGraphicsBackend> IntoGlium for T {
    fn into_glium(self) -> GliumGraphicBackend<Self> {
        GliumGraphicBackend(self)
    }
}

unsafe impl<T: EGLGraphicsBackend> Backend for GliumGraphicBackend<T> {
    fn swap_buffers(&self) -> Result<(), GliumSwapBuffersError> {
        self.0.swap_buffers().map_err(Into::into)
    }

    unsafe fn get_proc_address(&self, symbol: &str) -> *const c_void {
        self.0.get_proc_address(symbol) as *const c_void
    }

    fn get_framebuffer_dimensions(&self) -> (u32, u32) {
        self.0.get_framebuffer_dimensions()
    }

    fn is_current(&self) -> bool {
        self.0.is_current()
    }

    unsafe fn make_current(&self) {
        self.0.make_current().expect("Context was lost")
    }
}
<commit_msg>Flesh out glium compatibility<commit_after>//! Glium compatibility module

use backend::graphics::egl::{EGLGraphicsBackend, SwapBuffersError};
use glium::Frame;
use glium::SwapBuffersError as GliumSwapBuffersError;
use glium::backend::{Backend, Context};
use glium::debug::DebugCallbackBehavior;
use std::ops::Deref;
use std::os::raw::c_void;

use std::rc::Rc;

impl From<SwapBuffersError> for GliumSwapBuffersError {
    fn from(error: SwapBuffersError) -> Self {
        match error {
            SwapBuffersError::ContextLost => GliumSwapBuffersError::ContextLost,
            SwapBuffersError::AlreadySwapped => GliumSwapBuffersError::AlreadySwapped,
        }
    }
}

/// Wrapper to expose `glium` compatibility
pub struct GliumGraphicsBackend<T: EGLGraphicsBackend> {
    context: Rc<Context>,
    backend: Rc<InternalBackend<T>>,
}

struct InternalBackend<T: EGLGraphicsBackend>(T);

impl<T: EGLGraphicsBackend + 'static> GliumGraphicsBackend<T> {
    fn new(backend: T) -> GliumGraphicsBackend<T> {
        let internal = Rc::new(InternalBackend(backend));

        GliumGraphicsBackend {
            // cannot fail
            context: unsafe {
                Context::new::<_, ()>(internal.clone(), false, DebugCallbackBehavior::default()).unwrap()
            },
            backend: internal,
        }
    }

    /// Start drawing on the backbuffer.
    ///
    /// This function returns a `Frame`, which can be used to draw on it. When the `Frame` is
    /// destroyed, the buffers are swapped.
    ///
    /// Note that destroying a `Frame` is immediate, even if vsync is enabled.
    #[inline]
    pub fn draw(&self) -> Frame {
        Frame::new(self.context.clone(),
                   self.backend.get_framebuffer_dimensions())
    }
}

impl<T: EGLGraphicsBackend> Deref for GliumGraphicsBackend<T> {
    type Target = Context;

    fn deref(&self) -> &Context {
        &self.context
    }
}

/// Converter trait to expose `glium` compatibility for all `EGLGraphicsBackend`s
pub trait IntoGlium: EGLGraphicsBackend + Sized {
    /// Wrap the given `EGLGraphicsBackend` to a `GliumGraphicBackend`
    fn into_glium(self) -> GliumGraphicsBackend<Self>;
}

impl<T: EGLGraphicsBackend + 'static> IntoGlium for T {
    fn into_glium(self) -> GliumGraphicsBackend<Self> {
        GliumGraphicsBackend::new(self)
    }
}

unsafe impl<T: EGLGraphicsBackend> Backend for InternalBackend<T> {
    fn swap_buffers(&self) -> Result<(), GliumSwapBuffersError> {
        self.0.swap_buffers().map_err(Into::into)
    }

    unsafe fn get_proc_address(&self, symbol: &str) -> *const c_void {
        self.0.get_proc_address(symbol) as *const c_void
    }

    fn get_framebuffer_dimensions(&self) -> (u32, u32) {
        self.0.get_framebuffer_dimensions()
    }

    fn is_current(&self) -> bool {
        self.0.is_current()
    }

    unsafe fn make_current(&self) {
        self.0.make_current().expect("Context was lost")
    }
}
<|endoftext|>


<commit_before>use clap::crate_version;

use std::env;
use std::ffi::OsStr;
use std::io;
use std::process::{self, Command, ExitStatus};
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};

#[path = "../common.rs"]
mod common;

fn main() {
    if !common::archive_file_path().exists() {
        let version = common::afl_rustc_version();
        eprintln!(
            "AFL LLVM runtime is not built with Rust {}, run `cargo \
             install --force afl` to build it.",
            version
        );
        process::exit(1);
    }

    let app_matches = clap_app().get_matches();
    let afl_matches = app_matches.subcommand_matches("afl").unwrap();

    match afl_matches.subcommand() {
        ("analyze", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-analyze args")
                .unwrap_or_default();
            run_afl(args, "afl-analyze");
        }
        ("cmin", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-cmin args")
                .unwrap_or_default();
            run_afl(args, "afl-cmin");
        }
        ("fuzz", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-fuzz args")
                .unwrap_or_default();
            run_afl(args, "afl-fuzz");
        }
        ("gotcpu", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-gotcpu args")
                .unwrap_or_default();
            run_afl(args, "afl-gotcpu");
        }
        ("plot", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-plot args")
                .unwrap_or_default();
            run_afl(args, "afl-plot");
        }
        ("showmap", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-showmap args")
                .unwrap_or_default();
            run_afl(args, "afl-showmap");
        }
        ("tmin", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-tmin args")
                .unwrap_or_default();
            run_afl(args, "afl-tmin");
        }
        ("whatsup", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-whatsup args")
                .unwrap_or_default();
            run_afl(args, "afl-whatsup");
        }
        (subcommand, Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("")
                .unwrap_or_default();
            run_cargo(subcommand, args);
        }
        (_, None) => unreachable!(),
    }
}

fn clap_app() -> clap::App<'static, 'static> {
    use clap::{App, AppSettings::{
        AllowExternalSubcommands,
        AllowLeadingHyphen,
        ArgRequiredElseHelp,
        DisableHelpSubcommand,
        DisableVersion,
        SubcommandRequiredElseHelp,
        TrailingVarArg,
    }, Arg, SubCommand};

    App::new("cargo afl").bin_name("cargo").setting(SubcommandRequiredElseHelp).subcommand(
        SubCommand::with_name("afl")
            .version(crate_version!())
            .setting(ArgRequiredElseHelp)
            .setting(SubcommandRequiredElseHelp)
            .setting(TrailingVarArg)
            .setting(AllowExternalSubcommands)
            .usage("cargo afl [SUBCOMMAND or Cargo SUBCOMMAND]")
            .after_help(
                "In addition to the subcommands above, Cargo subcommands are also \
                 supported (see `cargo help` for a list of all Cargo subcommands).",
            )
            .subcommand(
                SubCommand::with_name("analyze")
                    .about("Invoke afl-analyze")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-analyze args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("cmin")
                    .about("Invoke afl-cmin")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-cmin args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("fuzz")
                    .about("Invoke afl-fuzz")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-fuzz args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("gotcpu")
                    .about("Invoke afl-gotcpu")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-gotcpu args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("plot")
                    .about("Invoke afl-plot")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-plot args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("showmap")
                    .about("Invoke afl-showmap")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-showmap args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("tmin")
                    .about("Invoke afl-tmin")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-tmin args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("whatsup")
                    .about("Invoke afl-whatsup")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-whatsup args").multiple(true)),
            ),
    )
}

fn run_timeout_terminate(mut cmd: Command, timeout: Option<u64>) -> Result<ExitStatus, io::Error> {
    let timeout = match timeout {
        Some(timeout) => Duration::from_secs(timeout),
        None => return cmd.status(),
    };
    let start_time = Instant::now();

    let mut child = cmd.spawn()?;
    let pid = child.id();

    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let (stop_mutex, condvar) = &*pair;
    let thread_handle = {
        let pair = pair.clone();
        thread::spawn(move || -> Result<(), io::Error> {
            // This thread will wait until the child process has exited, or the
            // timeout has elapsed, whichever comes first. If the timeout
            // elapses, and the process is still running, it will send SIGTERM
            // to the child process.

            let (stop_mutex, condvar) = &*pair;
            let mut stop = stop_mutex.lock().unwrap();
            loop {
                let elapsed = Instant::now() - start_time;
                if elapsed >= timeout {
                    break;
                }

                let dur = timeout - elapsed;
                let results = condvar.wait_timeout(stop, dur).unwrap();
                stop = results.0;
                if *stop {
                    // Blocking waitid call on the main thread has returned,
                    // thus the child process has terminated
                    return Ok(());
                }
                if results.1.timed_out() {
                    break;
                }
            }

            // Since the waitid call on the main thread is using WNOWAIT, the
            // child process won't be cleaned up (until after this thread
            // exits and the main thread calls wait) and thus its PID won't be
            // reused by another, unrelated process.
            unsafe {
                let ret = libc::kill(pid as i32, libc::SIGTERM);
                if ret == -1 {
                    Err(io::Error::last_os_error())?
                }
            }

            Ok(())
        })
    };

    unsafe {
        // Block until the child process terminates, but leave it in a waitable
        // state still
        let ret = libc::waitid(libc::P_PID, pid, std::ptr::null_mut(), libc::WEXITED | libc::WNOWAIT);
        if ret == -1 {
            Err(io::Error::last_os_error())?
        }
    }
    {
        let mut stop = stop_mutex.lock().unwrap();
        *stop = true;
    }
    // Tell the timeout thread to stop, wake it, and wait for it to exit
    condvar.notify_one();
    thread_handle.join().unwrap()?;

    // Clean up zombie and get exit status (this won't block, because the child
    // process has terminated and is still waitable)
    child.wait()
}

fn run_afl<I, S>(args: I, cmd: &str)
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let cmd_path = common::afl_dir().join("bin").join(cmd);
    let status = Command::new(cmd_path)
        .args(args)
        .status()
        .unwrap();
    process::exit(status.code().unwrap_or(1));
}

fn run_cargo<I, S>(subcommand: &str, args: I)
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let cargo_path = env!("CARGO");

    // add some flags to sanitizers to make them work with Rust code
    let asan_options = env::var("ASAN_OPTIONS").unwrap_or_default();
    let asan_options = format!("detect_odr_violation=0:{}", asan_options);

    let tsan_options = env::var("TSAN_OPTIONS").unwrap_or_default();
    let tsan_options = format!("report_signal_unsafe=0:{}", tsan_options);

    let mut rustflags = format!(
        "--cfg fuzzing \
         -C debug-assertions \
         -C overflow_checks \
         -C passes=sancov \
         -C llvm-args=-sanitizer-coverage-level=3 \
         -C llvm-args=-sanitizer-coverage-trace-pc-guard \
         -C llvm-args=-sanitizer-coverage-prune-blocks=0 \
         -C opt-level=3 \
         -C target-cpu=native \
         -C debuginfo=0 \
         -l afl-llvm-rt \
         -L {} ",
        common::afl_llvm_rt_dir().display()
    );

    // RUSTFLAGS are not used by rustdoc, instead RUSTDOCFLAGS are used. Since
    // doctests will try to link against afl-llvm-rt, set up RUSTDOCFLAGS to
    // have doctests built the same as other code to avoid issues with doctests.
    let mut rustdocflags = format!(
        "--cfg fuzzing \
         -C debug-assertions \
         -C overflow_checks \
         -C passes=sancov \
         -C llvm-args=-sanitizer-coverage-level=3 \
         -C llvm-args=-sanitizer-coverage-trace-pc-guard \
         -C llvm-args=-sanitizer-coverage-prune-blocks=0 \
         -C opt-level=3 \
         -C target-cpu=native \
         -C debuginfo=0 \
         -L {} ",
        common::afl_llvm_rt_dir().display()
    );

    if cfg!(target_os = "linux") {
        // work around https://github.com/rust-fuzz/afl.rs/issues/141 /
        // https://github.com/rust-lang/rust/issues/53945, can be removed once
        // those are fixed.
        rustflags.push_str("-Clink-arg=-fuse-ld=gold ");
        rustdocflags.push_str("-Clink-arg=-fuse-ld=gold ");
    }

    // add user provided flags
    rustflags.push_str(&env::var("RUSTFLAGS").unwrap_or_default());
    rustdocflags.push_str(&env::var("RUSTDOCFLAGS").unwrap_or_default());

    let status = Command::new(cargo_path)
        .arg(subcommand)
        .args(args)
        .env("RUSTFLAGS", &rustflags)
        .env("RUSTDOCFLAGS", &rustdocflags)
        .env("ASAN_OPTIONS", asan_options)
        .env("TSAN_OPTIONS", tsan_options)
        .status()
        .unwrap();
    process::exit(status.code().unwrap_or(1));
}
<commit_msg>Add time limit option for cargo afl fuzz<commit_after>use clap::crate_version;

use std::env;
use std::ffi::OsStr;
use std::io;
use std::process::{self, Command, ExitStatus};
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};

#[path = "../common.rs"]
mod common;

fn main() {
    if !common::archive_file_path().exists() {
        let version = common::afl_rustc_version();
        eprintln!(
            "AFL LLVM runtime is not built with Rust {}, run `cargo \
             install --force afl` to build it.",
            version
        );
        process::exit(1);
    }

    let app_matches = clap_app().get_matches();
    let afl_matches = app_matches.subcommand_matches("afl").unwrap();

    match afl_matches.subcommand() {
        ("analyze", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-analyze args")
                .unwrap_or_default();
            run_afl(args, "afl-analyze", None);
        }
        ("cmin", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-cmin args")
                .unwrap_or_default();
            run_afl(args, "afl-cmin", None);
        }
        ("fuzz", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-fuzz args")
                .unwrap_or_default();
            let timeout = sub_matches
                .value_of("max_total_time")
                .map(str::parse::<u64>)
                .map(Result::unwrap);
            run_afl(args, "afl-fuzz", timeout);
        }
        ("gotcpu", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-gotcpu args")
                .unwrap_or_default();
            run_afl(args, "afl-gotcpu", None);
        }
        ("plot", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-plot args")
                .unwrap_or_default();
            run_afl(args, "afl-plot", None);
        }
        ("showmap", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-showmap args")
                .unwrap_or_default();
            run_afl(args, "afl-showmap", None);
        }
        ("tmin", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-tmin args")
                .unwrap_or_default();
            run_afl(args, "afl-tmin", None);
        }
        ("whatsup", Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("afl-whatsup args")
                .unwrap_or_default();
            run_afl(args, "afl-whatsup", None);
        }
        (subcommand, Some(sub_matches)) => {
            let args = sub_matches
                .values_of_os("")
                .unwrap_or_default();
            run_cargo(subcommand, args);
        }
        (_, None) => unreachable!(),
    }
}

fn clap_app() -> clap::App<'static, 'static> {
    use clap::{App, AppSettings::{
        AllowExternalSubcommands,
        AllowLeadingHyphen,
        ArgRequiredElseHelp,
        DisableHelpSubcommand,
        DisableVersion,
        SubcommandRequiredElseHelp,
        TrailingVarArg,
    }, Arg, SubCommand};

    App::new("cargo afl").bin_name("cargo").setting(SubcommandRequiredElseHelp).subcommand(
        SubCommand::with_name("afl")
            .version(crate_version!())
            .setting(ArgRequiredElseHelp)
            .setting(SubcommandRequiredElseHelp)
            .setting(TrailingVarArg)
            .setting(AllowExternalSubcommands)
            .usage("cargo afl [SUBCOMMAND or Cargo SUBCOMMAND]")
            .after_help(
                "In addition to the subcommands above, Cargo subcommands are also \
                 supported (see `cargo help` for a list of all Cargo subcommands).",
            )
            .subcommand(
                SubCommand::with_name("analyze")
                    .about("Invoke afl-analyze")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-analyze args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("cmin")
                    .about("Invoke afl-cmin")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-cmin args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("fuzz")
                    .about("Invoke afl-fuzz")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("max_total_time").long("max_total_time").takes_value(true).help("Maximum amount of time to run the fuzzer"))
                    .arg(Arg::with_name("afl-fuzz args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("gotcpu")
                    .about("Invoke afl-gotcpu")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-gotcpu args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("plot")
                    .about("Invoke afl-plot")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-plot args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("showmap")
                    .about("Invoke afl-showmap")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-showmap args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("tmin")
                    .about("Invoke afl-tmin")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-tmin args").multiple(true)),
            )
            .subcommand(
                SubCommand::with_name("whatsup")
                    .about("Invoke afl-whatsup")
                    .setting(AllowLeadingHyphen)
                    .setting(DisableHelpSubcommand)
                    .setting(DisableVersion)
                    .arg(Arg::with_name("h").short("h").hidden(true))
                    .arg(Arg::with_name("help").long("help").hidden(true))
                    .arg(Arg::with_name("afl-whatsup args").multiple(true)),
            ),
    )
}

fn run_timeout_terminate(mut cmd: Command, timeout: Option<u64>) -> Result<ExitStatus, io::Error> {
    let timeout = match timeout {
        Some(timeout) => Duration::from_secs(timeout),
        None => return cmd.status(),
    };
    let start_time = Instant::now();

    let mut child = cmd.spawn()?;
    let pid = child.id();

    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let (stop_mutex, condvar) = &*pair;
    let thread_handle = {
        let pair = pair.clone();
        thread::spawn(move || -> Result<(), io::Error> {
            // This thread will wait until the child process has exited, or the
            // timeout has elapsed, whichever comes first. If the timeout
            // elapses, and the process is still running, it will send SIGTERM
            // to the child process.

            let (stop_mutex, condvar) = &*pair;
            let mut stop = stop_mutex.lock().unwrap();
            loop {
                let elapsed = Instant::now() - start_time;
                if elapsed >= timeout {
                    break;
                }

                let dur = timeout - elapsed;
                let results = condvar.wait_timeout(stop, dur).unwrap();
                stop = results.0;
                if *stop {
                    // Blocking waitid call on the main thread has returned,
                    // thus the child process has terminated
                    return Ok(());
                }
                if results.1.timed_out() {
                    break;
                }
            }

            // Since the waitid call on the main thread is using WNOWAIT, the
            // child process won't be cleaned up (until after this thread
            // exits and the main thread calls wait) and thus its PID won't be
            // reused by another, unrelated process.
            unsafe {
                let ret = libc::kill(pid as i32, libc::SIGTERM);
                if ret == -1 {
                    Err(io::Error::last_os_error())?
                }
            }

            Ok(())
        })
    };

    unsafe {
        // Block until the child process terminates, but leave it in a waitable
        // state still
        let ret = libc::waitid(libc::P_PID, pid, std::ptr::null_mut(), libc::WEXITED | libc::WNOWAIT);
        if ret == -1 {
            Err(io::Error::last_os_error())?
        }
    }
    {
        let mut stop = stop_mutex.lock().unwrap();
        *stop = true;
    }
    // Tell the timeout thread to stop, wake it, and wait for it to exit
    condvar.notify_one();
    thread_handle.join().unwrap()?;

    // Clean up zombie and get exit status (this won't block, because the child
    // process has terminated and is still waitable)
    child.wait()
}

fn run_afl<I, S>(args: I, cmd: &str, timeout: Option<u64>)
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let cmd_path = common::afl_dir().join("bin").join(cmd);
    let mut cmd = Command::new(cmd_path);
    cmd.args(args);
    let status = run_timeout_terminate(cmd, timeout).unwrap();
    process::exit(status.code().unwrap_or(1));
}

fn run_cargo<I, S>(subcommand: &str, args: I)
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let cargo_path = env!("CARGO");

    // add some flags to sanitizers to make them work with Rust code
    let asan_options = env::var("ASAN_OPTIONS").unwrap_or_default();
    let asan_options = format!("detect_odr_violation=0:{}", asan_options);

    let tsan_options = env::var("TSAN_OPTIONS").unwrap_or_default();
    let tsan_options = format!("report_signal_unsafe=0:{}", tsan_options);

    let mut rustflags = format!(
        "--cfg fuzzing \
         -C debug-assertions \
         -C overflow_checks \
         -C passes=sancov \
         -C llvm-args=-sanitizer-coverage-level=3 \
         -C llvm-args=-sanitizer-coverage-trace-pc-guard \
         -C llvm-args=-sanitizer-coverage-prune-blocks=0 \
         -C opt-level=3 \
         -C target-cpu=native \
         -C debuginfo=0 \
         -l afl-llvm-rt \
         -L {} ",
        common::afl_llvm_rt_dir().display()
    );

    // RUSTFLAGS are not used by rustdoc, instead RUSTDOCFLAGS are used. Since
    // doctests will try to link against afl-llvm-rt, set up RUSTDOCFLAGS to
    // have doctests built the same as other code to avoid issues with doctests.
    let mut rustdocflags = format!(
        "--cfg fuzzing \
         -C debug-assertions \
         -C overflow_checks \
         -C passes=sancov \
         -C llvm-args=-sanitizer-coverage-level=3 \
         -C llvm-args=-sanitizer-coverage-trace-pc-guard \
         -C llvm-args=-sanitizer-coverage-prune-blocks=0 \
         -C opt-level=3 \
         -C target-cpu=native \
         -C debuginfo=0 \
         -L {} ",
        common::afl_llvm_rt_dir().display()
    );

    if cfg!(target_os = "linux") {
        // work around https://github.com/rust-fuzz/afl.rs/issues/141 /
        // https://github.com/rust-lang/rust/issues/53945, can be removed once
        // those are fixed.
        rustflags.push_str("-Clink-arg=-fuse-ld=gold ");
        rustdocflags.push_str("-Clink-arg=-fuse-ld=gold ");
    }

    // add user provided flags
    rustflags.push_str(&env::var("RUSTFLAGS").unwrap_or_default());
    rustdocflags.push_str(&env::var("RUSTDOCFLAGS").unwrap_or_default());

    let status = Command::new(cargo_path)
        .arg(subcommand)
        .args(args)
        .env("RUSTFLAGS", &rustflags)
        .env("RUSTDOCFLAGS", &rustdocflags)
        .env("ASAN_OPTIONS", asan_options)
        .env("TSAN_OPTIONS", tsan_options)
        .status()
        .unwrap();
    process::exit(status.code().unwrap_or(1));
}
<|endoftext|>