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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use secgate::{util::Descriptor, Crossing};
use twizzler_runtime_api::{
    AddrRange, DlPhdrInfo, LibraryId, MapError, ObjID, SpawnError, ThreadSpawnArgs,
};

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_spawn_thread(
    info: &secgate::GateCallInfo,
    args: ThreadSpawnArgs,
    thread_pointer: usize,
    stack_pointer: usize,
) -> Result<ObjID, SpawnError> {
    let monitor = crate::mon::get_monitor();
    monitor.spawn_compartment_thread(
        info.source_context().unwrap_or(0.into()),
        args,
        stack_pointer,
        thread_pointer,
    )
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_get_comp_config(info: &secgate::GateCallInfo) -> usize {
    use crate::api::MONITOR_INSTANCE_ID;
    let monitor = crate::mon::get_monitor();
    monitor
        .get_comp_config(info.source_context().unwrap_or(MONITOR_INSTANCE_ID))
        .map(|ptr| ptr as usize)
        .unwrap_or(0)
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_get_library_info(
    info: &secgate::GateCallInfo,
    desc: Descriptor,
) -> Option<LibraryInfo> {
    use crate::api::MONITOR_INSTANCE_ID;
    let monitor = crate::mon::get_monitor();
    let instance = info.source_context().unwrap_or(MONITOR_INSTANCE_ID);
    let thread = info.thread_id();
    monitor.get_library_info(instance, thread, desc)
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_get_library_handle(
    info: &secgate::GateCallInfo,
    compartment: Option<Descriptor>,
    lib_n: usize,
) -> Option<Descriptor> {
    use crate::api::MONITOR_INSTANCE_ID;
    let monitor = crate::mon::get_monitor();
    let caller = info.source_context().unwrap_or(MONITOR_INSTANCE_ID);
    monitor.get_library_handle(caller, compartment, lib_n)
}

#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct LibraryInfo {
    pub name_len: usize,
    pub compartment_id: ObjID,
    pub objid: ObjID,
    pub slot: usize,
    pub range: AddrRange,
    pub dl_info: DlPhdrInfo,
    pub desc: Descriptor,
}

#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct CompartmentInfo {
    pub name_len: usize,
    pub id: ObjID,
    pub sctx: ObjID,
    pub flags: u64,
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_get_compartment_handle(
    info: &secgate::GateCallInfo,
    compartment: ObjID,
) -> Option<Descriptor> {
    use crate::api::MONITOR_INSTANCE_ID;
    let monitor = crate::mon::get_monitor();
    let caller = info.source_context().unwrap_or(MONITOR_INSTANCE_ID);
    let compartment = if compartment.as_u128() == 0 {
        caller
    } else {
        compartment
    };
    monitor.get_compartment_handle(caller, compartment)
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_get_compartment_info(
    info: &secgate::GateCallInfo,
    desc: Option<Descriptor>,
) -> Option<CompartmentInfo> {
    use crate::api::MONITOR_INSTANCE_ID;
    let monitor = crate::mon::get_monitor();
    let caller = info.source_context().unwrap_or(MONITOR_INSTANCE_ID);
    monitor.get_compartment_info(caller, info.thread_id(), desc)
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_get_compartment_deps(
    info: &secgate::GateCallInfo,
    desc: Option<Descriptor>,
    dep_n: usize,
) -> Option<Descriptor> {
    use crate::api::MONITOR_INSTANCE_ID;
    let monitor = crate::mon::get_monitor();
    let caller = info.source_context().unwrap_or(MONITOR_INSTANCE_ID);
    monitor.get_compartment_deps(caller, desc, dep_n)
}

// Safety: the broken part is just DlPhdrInfo. We ensure that any pointers in there are
// intra-compartment.
unsafe impl Crossing for LibraryInfo {}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_load_compartment(
    info: &secgate::GateCallInfo,
    root_id: ObjID,
) -> Result<Descriptor, LoadCompartmentError> {
    use crate::api::MONITOR_INSTANCE_ID;
    let monitor = crate::mon::get_monitor();
    let caller = info.source_context().unwrap_or(MONITOR_INSTANCE_ID);
    monitor.load_compartment(caller, root_id)
}

#[derive(Clone, Copy, Debug)]
pub enum LoadCompartmentError {
    Unknown,
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_drop_compartment_handle(info: &secgate::GateCallInfo, desc: Descriptor) {
    use crate::api::MONITOR_INSTANCE_ID;
    let monitor = crate::mon::get_monitor();
    let caller = info.source_context().unwrap_or(MONITOR_INSTANCE_ID);
    monitor.drop_compartment_handle(caller, desc)
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_load_library(
    info: &secgate::GateCallInfo,
    compartment: Option<Descriptor>,
    id: ObjID,
) -> Result<Descriptor, LoadLibraryError> {
    use crate::api::MONITOR_INSTANCE_ID;
    let monitor = crate::mon::get_monitor();
    let caller = info.source_context().unwrap_or(MONITOR_INSTANCE_ID);
    monitor.load_library(caller, id, compartment)
}

#[derive(Clone, Copy, Debug)]
pub enum LoadLibraryError {
    Unknown,
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_drop_library_handle(info: &secgate::GateCallInfo, desc: Descriptor) {
    use crate::api::MONITOR_INSTANCE_ID;
    let monitor = crate::mon::get_monitor();
    let caller = info.source_context().unwrap_or(MONITOR_INSTANCE_ID);
    monitor.drop_library_handle(caller, desc)
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_object_map(
    info: &secgate::GateCallInfo,
    id: ObjID,
    flags: twizzler_runtime_api::MapFlags,
) -> Result<crate::MappedObjectAddrs, MapError> {
    use twz_rt::{RuntimeState, OUR_RUNTIME};

    use crate::{api::MONITOR_INSTANCE_ID, mon::space::MapInfo};
    if OUR_RUNTIME.state().contains(RuntimeState::READY) {
        // Are we recursing from the monitor, with a lock held? In that case, use early_object_map
        // to map the object. This will leak this mapping, but this is both rare, and then
        // since the mapping is leaked, it can be used as an allocator object indefinitely
        // (not currently implemented). Make sure the ThreadKey drops.
        let is_monitor_recursed =
            { happylock::ThreadKey::get().is_none() && info.source_context().is_none() };
        if is_monitor_recursed {
            tracing::debug!(
                "performing early object mapping (recursed), {} {:?}",
                id,
                flags
            );
            return Ok(crate::mon::early_object_map(MapInfo { id, flags }));
        }
        let monitor = crate::mon::get_monitor();
        monitor
            .map_object(
                info.source_context().unwrap_or(MONITOR_INSTANCE_ID),
                MapInfo { id, flags },
            )
            .map(|handle| handle.addrs())
    } else {
        // We need to use early_object_map, since the monitor hasn't finished initializing, but
        // still needs to allocate (which may involve mapping an object).
        tracing::debug!("performing early object mapping, {} {:?}", id, flags);
        Ok(crate::mon::early_object_map(MapInfo { id, flags }))
    }
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_object_unmap(
    info: &secgate::GateCallInfo,
    _slot: usize,
    id: ObjID,
    flags: twizzler_runtime_api::MapFlags,
) {
    use twz_rt::{RuntimeState, OUR_RUNTIME};
    if OUR_RUNTIME.state().contains(RuntimeState::READY) {
        let monitor = crate::mon::get_monitor();
        let key = happylock::ThreadKey::get().unwrap();
        monitor
            .comp_mgr
            .write(key)
            .get_mut(
                info.source_context()
                    .unwrap_or(crate::api::MONITOR_INSTANCE_ID),
            )
            .unwrap()
            .unmap_object(crate::mon::space::MapInfo { id, flags })
    }
}

#[cfg_attr(feature = "secgate-impl", secgate::secure_gate(options(info)))]
#[cfg_attr(
    not(feature = "secgate-impl"),
    secgate::secure_gate(options(info, api))
)]
pub fn monitor_rt_get_thread_simple_buffer(info: &secgate::GateCallInfo) -> Option<ObjID> {
    use crate::api::MONITOR_INSTANCE_ID;
    let monitor = crate::mon::get_monitor();
    let caller = info.source_context().unwrap_or(MONITOR_INSTANCE_ID);
    monitor.get_thread_simple_buffer(caller, info.thread_id())
}