1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
use crate::util::constants::DEFAULT_STRESS_FACTOR;
use std::cell::UnsafeCell;
use std::default::Default;
use std::ops::Deref;

custom_derive! {
    #[derive(Copy, Clone, EnumFromStr)]
    pub enum NurseryZeroingOptions {
        Temporal,
        Nontemporal,
        Concurrent,
        Adaptive,
    }
}

custom_derive! {
    #[derive(Copy, Clone, EnumFromStr, Debug)]
    pub enum PlanSelector {
        NoGC,
        SemiSpace,
        GenCopy,
        MarkSweep
    }
}

pub struct UnsafeOptionsWrapper(UnsafeCell<Options>);
unsafe impl Sync for UnsafeOptionsWrapper {}

impl UnsafeOptionsWrapper {
    pub const fn new(o: Options) -> UnsafeOptionsWrapper {
        UnsafeOptionsWrapper(UnsafeCell::new(o))
    }
    /// # Safety
    /// This method is not thread safe, as internally it acquires a mutable reference to self.
    /// It is supposed to be used by one thread during boot time.
    pub unsafe fn process(&self, name: &str, value: &str) -> bool {
        (&mut *self.0.get()).set_from_camelcase_str(name, value)
    }
}
impl Deref for UnsafeOptionsWrapper {
    type Target = Options;
    fn deref(&self) -> &Options {
        unsafe { &*self.0.get() }
    }
}

fn always_valid<T>(_: T) -> bool {
    true
}
macro_rules! options {
    ($($name:ident: $type:ty[$validator:expr] = $default:expr),*,) => [
        options!($($name: $type[$validator] = $default),*);
    ];
    ($($name:ident: $type:ty[$validator:expr] = $default:expr),*) => [
        pub struct Options {
            $(pub $name: $type),*
        }
        impl Options {
            pub fn set_from_str(&mut self, s: &str, val: &str)->bool {
                match s {
                    $(stringify!($name) => if let Ok(val) = val.parse() {
                        self.$name = val;
                        let validate_fn = $validator;
                        validate_fn(val)
                    } else {
                        eprintln!("Warn: unable to set {}={}. Default value will be used.", s, val);
                        false
                    })*
                    _ => panic!("Invalid Options key")
                }
            }
        }
        impl Default for Options {
            fn default() -> Self {
                let mut options = Options {
                    $($name: $default),*
                };

                // If we have env vars that start with MMTK_ and match any option (such as MMTK_STRESS_FACTOR),
                // we set the option to its value (if it is a valid value). Otherwise, use the default value.
                const PREFIX: &str = "MMTK_";
                for (key, val) in std::env::vars() {
                    // strip the prefix, and get the lower case string
                    if let Some(rest_of_key) = key.strip_prefix(PREFIX) {
                        let lowercase: &str = &rest_of_key.to_lowercase();
                        match lowercase {
                            $(stringify!($name) => { options.set_from_str(lowercase, &val); },)*
                            _ => {}
                        }
                    }
                }
                return options;
            }
        }
    ]
}
options! {
    plan:                  PlanSelector         [always_valid] = PlanSelector::NoGC,
    threads:               usize                [|v| v > 0]    = num_cpus::get(),
    use_short_stack_scans: bool                 [always_valid] = false,
    use_return_barrier:    bool                 [always_valid] = false,
    eager_complete_sweep:  bool                 [always_valid] = false,
    ignore_system_g_c:     bool                 [always_valid] = false,
    // Note: Not used. To workaround cmd args passed by the running script
    variable_size_heap:    bool                 [always_valid] = true,
    no_finalizer:          bool                 [always_valid] = false,
    no_reference_types:    bool                 [always_valid] = false,
    nursery_zeroing:       NurseryZeroingOptions[always_valid] = NurseryZeroingOptions::Temporal,
    // Note: This gets ignored. Use RUST_LOG to specify log level.
    // TODO: Delete this option.
    verbose:               usize                [always_valid] = 0,
    stress_factor:         usize                [always_valid] = DEFAULT_STRESS_FACTOR,
    analysis_factor:       usize                [always_valid] = DEFAULT_STRESS_FACTOR,
    // vmspace
    // FIXME: These options are set for JikesRVM. We need a proper way to set options.
    //   We need to set these values programmatically in VM specific code.
    vm_space:              bool                 [always_valid] = true,
    vm_space_size:         usize                [|v| v > 0]    = 0x7cc_cccc,
}

impl Options {
    fn set_from_camelcase_str(&mut self, s: &str, val: &str) -> bool {
        trace!("Trying to process option pair: ({}, {})", s, val);

        let mut sr = String::with_capacity(s.len());
        for c in s.chars() {
            if c.is_uppercase() {
                sr.push('_');
                for c in c.to_lowercase() {
                    sr.push(c);
                }
            } else {
                sr.push(c)
            }
        }

        let result = self.set_from_str(sr.as_str(), val);

        trace!("Trying to process option pair: ({})", sr);

        if result {
            trace!("Validation passed");
        } else {
            trace!("Validation failed")
        }
        result
    }
}

#[cfg(test)]
mod tests {
    use crate::util::constants::DEFAULT_STRESS_FACTOR;
    use crate::util::options::Options;
    use crate::util::test_util::serial_test;

    #[test]
    fn no_env_var() {
        serial_test(|| {
            let options = Options::default();
            assert_eq!(options.stress_factor, DEFAULT_STRESS_FACTOR);
        })
    }

    #[test]
    fn with_valid_env_var() {
        serial_test(|| {
            std::env::set_var("MMTK_STRESS_FACTOR", "4096");

            let res = std::panic::catch_unwind(|| {
                let options = Options::default();
                assert_eq!(options.stress_factor, 4096);
            });
            assert!(res.is_ok());

            std::env::remove_var("MMTK_STRESS_FACTOR");
        })
    }

    #[test]
    fn with_multiple_valid_env_vars() {
        serial_test(|| {
            std::env::set_var("MMTK_STRESS_FACTOR", "4096");
            std::env::set_var("MMTK_VM_SPACE", "false");

            let res = std::panic::catch_unwind(|| {
                let options = Options::default();
                assert_eq!(options.stress_factor, 4096);
                assert_eq!(options.vm_space, false);
            });
            assert!(res.is_ok());

            std::env::remove_var("MMTK_STRESS_FACTOR");
            std::env::remove_var("MMTK_VM_SPACE");
        })
    }

    #[test]
    fn with_invalid_env_var_value() {
        serial_test(|| {
            // invalid value, we cannot parse the value, so use the default value
            std::env::set_var("MMTK_STRESS_FACTOR", "abc");

            let res = std::panic::catch_unwind(|| {
                let options = Options::default();
                assert_eq!(options.stress_factor, DEFAULT_STRESS_FACTOR);
            });
            assert!(res.is_ok());

            std::env::remove_var("MMTK_STRESS_FACTOR");
        })
    }

    #[test]
    fn with_invalid_env_var_key() {
        serial_test(|| {
            // invalid value, we cannot parse the value, so use the default value
            std::env::set_var("MMTK_ABC", "42");

            let res = std::panic::catch_unwind(|| {
                let options = Options::default();
                assert_eq!(options.stress_factor, DEFAULT_STRESS_FACTOR);
            });
            assert!(res.is_ok());

            std::env::remove_var("MMTK_ABC");
        })
    }
}