Debian Codegraph @

.cargo/vendor/cc/src/windows/registry.rs

raw
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use crate::windows::windows_sys::{
12 RegCloseKey, RegEnumKeyExW, RegOpenKeyExW, RegQueryValueExW, ERROR_NO_MORE_ITEMS,
13 ERROR_SUCCESS, HKEY, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, REG_SZ,
14 };
15 use std::{
16 ffi::{OsStr, OsString},
17 io,
18 ops::RangeFrom,
19 os::windows::prelude::*,
20 ptr::null_mut,
21 };
22
23 /// Must never be `HKEY_PERFORMANCE_DATA`.
24 pub(crate) struct RegistryKey(Repr);
25
26 #[allow(clippy::upper_case_acronyms)]
27 type DWORD = u32;
28
29 struct OwnedKey(HKEY);
30
31 /// Note: must not encode `HKEY_PERFORMANCE_DATA` or one of its subkeys.
32 enum Repr {
33 /// `HKEY_LOCAL_MACHINE`.
34 LocalMachine,
35 /// A subkey of `HKEY_LOCAL_MACHINE`.
36 Owned(OwnedKey),
37 }
38
39 pub struct Iter<'a> {
40 idx: RangeFrom<DWORD>,
41 key: &'a RegistryKey,
42 }
43
44 unsafe impl Sync for Repr {}
45 unsafe impl Send for Repr {}
46
47 pub(crate) const LOCAL_MACHINE: RegistryKey = RegistryKey(Repr::LocalMachine);
48
49 impl RegistryKey {
50 fn raw(&self) -> HKEY {
51 match self.0 {
52 Repr::LocalMachine => HKEY_LOCAL_MACHINE,
53 Repr::Owned(ref val) => val.0,
54 }
55 }
56
57 /// Open a sub-key of `self`.
58 pub fn open(&self, key: &OsStr) -> io::Result<RegistryKey> {
59 let key = key.encode_wide().chain(Some(0)).collect::<Vec<_>>();
60 let mut ret = null_mut();
61 let err = unsafe {
62 RegOpenKeyExW(
63 self.raw(),
64 key.as_ptr(),
65 0,
66 KEY_READ | KEY_WOW64_32KEY,
67 &mut ret,
68 )
69 };
70 if err == ERROR_SUCCESS {
71 Ok(RegistryKey(Repr::Owned(OwnedKey(ret))))
72 } else {
73 Err(io::Error::from_raw_os_error(err as i32))
74 }
75 }
76
77 pub fn iter(&self) -> Iter {
78 Iter {
79 idx: 0..,
80 key: self,
81 }
82 }
83
84 pub fn query_str(&self, name: &str) -> io::Result<OsString> {
85 let name: &OsStr = name.as_ref();
86 let name = name.encode_wide().chain(Some(0)).collect::<Vec<_>>();
87 let mut len = 0;
88 let mut kind = 0;
89 unsafe {
90 let err = RegQueryValueExW(
91 self.raw(),
92 name.as_ptr(),
93 null_mut(),
94 &mut kind,
95 null_mut(),
96 &mut len,
97 );
98 if err != ERROR_SUCCESS {
99 return Err(io::Error::from_raw_os_error(err as i32));
100 }
101 if kind != REG_SZ {
102 return Err(io::Error::new(
103 io::ErrorKind::Other,
104 "registry key wasn't a string",
105 ));
106 }
107
108 // The length here is the length in bytes, but we're using wide
109 // characters so we need to be sure to halve it for the length
110 // passed in.
111 assert!(len % 2 == 0, "impossible wide string size: {} bytes", len);
112 let vlen = len as usize / 2;
113 // Defensively initialized, see comment about
114 // `HKEY_PERFORMANCE_DATA` below.
115 let mut v = vec![0u16; vlen];
116 let err = RegQueryValueExW(
117 self.raw(),
118 name.as_ptr(),
119 null_mut(),
120 null_mut(),
121 v.as_mut_ptr() as *mut _,
122 &mut len,
123 );
124 // We don't check for `ERROR_MORE_DATA` (which would if the value
125 // grew between the first and second call to `RegQueryValueExW`),
126 // both because it's extremely unlikely, and this is a bit more
127 // defensive more defensive against weird types of registry keys.
128 if err != ERROR_SUCCESS {
129 return Err(io::Error::from_raw_os_error(err as i32));
130 }
131 // The length is allowed to change, but should still be even, as
132 // well as smaller.
133 assert!(len % 2 == 0, "impossible wide string size: {} bytes", len);
134 // If the length grew but returned a success code, it *probably*
135 // indicates we're `HKEY_PERFORMANCE_DATA` or a subkey(?). We
136 // consider this UB, since those keys write "undefined" or
137 // "unpredictable" values to len, and need to use a completely
138 // different loop structure. This should be impossible (and enforce
139 // it in the API to the best of our ability), but to mitigate the
140 // damage we do some smoke-checks on the len, and ensure `v` has
141 // been fully initialized (rather than trusting the result of
142 // `RegQueryValueExW`).
143 let actual_len = len as usize / 2;
144 assert!(actual_len <= v.len());
145 v.truncate(actual_len);
146 // Some registry keys may have a terminating nul character, but
147 // we're not interested in that, so chop it off if it's there.
148 if !v.is_empty() && v[v.len() - 1] == 0 {
149 v.pop();
150 }
151 Ok(OsString::from_wide(&v))
152 }
153 }
154 }
155
156 impl Drop for OwnedKey {
157 fn drop(&mut self) {
158 unsafe {
159 RegCloseKey(self.0);
160 }
161 }
162 }
163
164 impl<'a> Iterator for Iter<'a> {
165 type Item = io::Result<OsString>;
166
167 fn next(&mut self) -> Option<io::Result<OsString>> {
168 self.idx.next().and_then(|i| unsafe {
169 let mut v = Vec::with_capacity(256);
170 let mut len = v.capacity() as DWORD;
171 let ret = RegEnumKeyExW(
172 self.key.raw(),
173 i,
174 v.as_mut_ptr(),
175 &mut len,
176 null_mut(),
177 null_mut(),
178 null_mut(),
179 null_mut(),
180 );
181 if ret == ERROR_NO_MORE_ITEMS {
182 None
183 } else if ret != ERROR_SUCCESS {
184 Some(Err(io::Error::from_raw_os_error(ret as i32)))
185 } else {
186 v.set_len(len as usize);
187 Some(Ok(OsString::from_wide(&v)))
188 }
189 })
190 }
191 }