about summary refs log tree commit diff
path: root/src/libstd/sys/sgx/args.rs
blob: 8fb35d7ef98bd30974b43341488ecdcf4c72853a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use ffi::OsString;
use super::abi::usercalls::{copy_user_buffer, alloc, ByteBuffer};
use sync::atomic::{AtomicUsize, Ordering};
use sys::os_str::Buf;
use sys_common::FromInner;
use slice;

static ARGS: AtomicUsize = AtomicUsize::new(0);
type ArgsStore = Vec<OsString>;

pub unsafe fn init(argc: isize, argv: *const *const u8) {
    if argc != 0 {
        let args = alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _);
        let args = args.iter()
            .map( |a| OsString::from_inner(Buf { inner: copy_user_buffer(a) }) )
            .collect::<ArgsStore>();
        ARGS.store(Box::into_raw(Box::new(args)) as _, Ordering::Relaxed);
    }
}

pub unsafe fn cleanup() {
    let args = ARGS.swap(0, Ordering::Relaxed);
    if args != 0 {
        drop(Box::<ArgsStore>::from_raw(args as _))
    }
}

pub fn args() -> Args {
    let args = unsafe { (ARGS.load(Ordering::Relaxed) as *const ArgsStore).as_ref() };
    if let Some(args) = args {
        Args(args.iter())
    } else {
        Args([].iter())
    }
}

pub struct Args(slice::Iter<'static, OsString>);

impl Args {
    pub fn inner_debug(&self) -> &[OsString] {
        self.0.as_slice()
    }
}

impl Iterator for Args {
    type Item = OsString;
    fn next(&mut self) -> Option<OsString> {
        self.0.next().cloned()
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl ExactSizeIterator for Args {
    fn len(&self) -> usize {
        self.0.len()
    }
}

impl DoubleEndedIterator for Args {
    fn next_back(&mut self) -> Option<OsString> {
        self.0.next_back().cloned()
    }
}