1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 use std::collections::HashMap;
15 use std::mem::MaybeUninit;
16 use std::sync::Once;
17 
18 use libc::c_int;
19 
20 use crate::common::{SigAction, Signal};
21 use crate::spin_rwlock::SpinningRwLock;
22 
23 pub(crate) struct SigMap {
24     pub(crate) data: SpinningRwLock<HashMap<c_int, Signal>>,
25     pub(crate) race_old: SpinningRwLock<Option<SigAction>>,
26 }
27 
28 impl SigMap {
29     // This function will be called inside a signal handler.
30     // Although a mutex Once is used, but the mutex will only be locked for once
31     // when initializing the SignalManager, which is outside of the signal
32     // handler.
get_instance() -> &'static SigMap33     pub(crate) fn get_instance() -> &'static SigMap {
34         static ONCE: Once = Once::new();
35         static mut GLOBAL_SIG_MAP: MaybeUninit<SigMap> = MaybeUninit::uninit();
36 
37         unsafe {
38             ONCE.call_once(|| {
39                 GLOBAL_SIG_MAP = MaybeUninit::new(SigMap {
40                     data: SpinningRwLock::new(HashMap::new()),
41                     race_old: SpinningRwLock::new(None),
42                 });
43             });
44             GLOBAL_SIG_MAP.assume_init_ref()
45         }
46     }
47 }
48