diff --git a/.github/workflows/clippy.yml b/.github/workflows/clippy.yml index a9f2ba2834..8af27305b2 100644 --- a/.github/workflows/clippy.yml +++ b/.github/workflows/clippy.yml @@ -118,6 +118,7 @@ jobs: cargo clippy -p test_not_dll && cargo clippy -p test_query_signature && cargo clippy -p test_readme && + cargo clippy -p test_registry && cargo clippy -p test_reserved && cargo clippy -p test_resources && cargo clippy -p test_result && @@ -154,6 +155,7 @@ jobs: cargo clippy -p windows-implement && cargo clippy -p windows-interface && cargo clippy -p windows-metadata && + cargo clippy -p windows-registry && cargo clippy -p windows-result && cargo clippy -p windows-sys && cargo clippy -p windows-targets && diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 67fc454d48..4c82b41f82 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -106,8 +106,8 @@ jobs: cargo test -p test_deprecated && cargo test -p test_dispatch && cargo test -p test_does_not_return && - cargo clean && cargo test -p test_enums && + cargo clean && cargo test -p test_error && cargo test -p test_event && cargo test -p test_extensions && @@ -126,6 +126,7 @@ jobs: cargo test -p test_not_dll && cargo test -p test_query_signature && cargo test -p test_readme && + cargo test -p test_registry && cargo test -p test_reserved && cargo test -p test_resources && cargo test -p test_result && @@ -162,6 +163,7 @@ jobs: cargo test -p windows-implement && cargo test -p windows-interface && cargo test -p windows-metadata && + cargo test -p windows-registry && cargo test -p windows-result && cargo test -p windows-sys && cargo test -p windows-targets && diff --git a/crates/libs/registry/Cargo.toml b/crates/libs/registry/Cargo.toml new file mode 100644 index 0000000000..6421738942 --- /dev/null +++ b/crates/libs/registry/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "windows-registry" +version = "0.1.0" +authors = ["Microsoft"] +edition = "2021" +rust-version = "1.60" +license = "MIT OR Apache-2.0" +description = "Windows registry" +repository = "https://github.com/microsoft/windows-rs" +readme = "readme.md" +categories = ["os::windows-apis"] +exclude = ["tests"] + +[lints] +workspace = true + +[package.metadata.docs.rs] +default-target = "x86_64-pc-windows-msvc" +targets = [] + +[dependencies.windows-targets] +version = "0.52.0" +path = "../targets" + +[dependencies.windows-result] +version = "0.1.0" +path = "../result" + +[dev-dependencies.windows-bindgen] +version = "0.52.0" +path = "../bindgen" diff --git a/crates/libs/registry/license-apache-2.0 b/crates/libs/registry/license-apache-2.0 new file mode 100644 index 0000000000..b5ed4ecec2 --- /dev/null +++ b/crates/libs/registry/license-apache-2.0 @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) Microsoft Corporation. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/crates/libs/registry/license-mit b/crates/libs/registry/license-mit new file mode 100644 index 0000000000..9e841e7a26 --- /dev/null +++ b/crates/libs/registry/license-mit @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/crates/libs/registry/readme.md b/crates/libs/registry/readme.md new file mode 100644 index 0000000000..851e681d06 --- /dev/null +++ b/crates/libs/registry/readme.md @@ -0,0 +1,32 @@ +## Windows registry + +The [windows-registry](https://crates.io/crates/windows-registry) crate provides simple, safe, and efficient access to the Windows registry. + +* [Getting started](https://kennykerr.ca/rust-getting-started/) +* [Samples](https://github.com/microsoft/windows-rs/tree/0.52.0/crates/samples) +* [Releases](https://github.com/microsoft/windows-rs/releases) + +Start by adding the following to your Cargo.toml file: + +```toml +[dependencies.windows-registry] +version = "0.1" +``` + +Read and write registry keys and values as needed: + +```rust,no_run +use windows_registry::*; + +fn main() -> Result<()> { + let key = CURRENT_USER.create(r#"software\\windows-rs"#)?; + + key.set_u32("number", 123)?; + key.set_string("name", "Rust")?; + + println!("{}", key.get_u32("number")?); + println!("{}", key.get_string("name")?); + + Ok(()) +} +``` diff --git a/crates/libs/registry/rustfmt.toml b/crates/libs/registry/rustfmt.toml new file mode 100644 index 0000000000..43d4840c79 --- /dev/null +++ b/crates/libs/registry/rustfmt.toml @@ -0,0 +1 @@ +newline_style = "Unix" diff --git a/crates/libs/registry/src/bindings.rs b/crates/libs/registry/src/bindings.rs new file mode 100644 index 0000000000..e210042d7f --- /dev/null +++ b/crates/libs/registry/src/bindings.rs @@ -0,0 +1,67 @@ +// Bindings generated by `windows-bindgen` 0.52.0 + +#![allow( + non_snake_case, + non_upper_case_globals, + non_camel_case_types, + dead_code, + clippy::all +)] +::windows_targets::link!("advapi32.dll" "system" fn RegCloseKey(hkey : HKEY) -> WIN32_ERROR); +::windows_targets::link!("advapi32.dll" "system" fn RegCreateKeyExW(hkey : HKEY, lpsubkey : PCWSTR, reserved : u32, lpclass : PCWSTR, dwoptions : REG_OPEN_CREATE_OPTIONS, samdesired : REG_SAM_FLAGS, lpsecurityattributes : *const SECURITY_ATTRIBUTES, phkresult : *mut HKEY, lpdwdisposition : *mut REG_CREATE_KEY_DISPOSITION) -> WIN32_ERROR); +::windows_targets::link!("advapi32.dll" "system" fn RegDeleteTreeW(hkey : HKEY, lpsubkey : PCWSTR) -> WIN32_ERROR); +::windows_targets::link!("advapi32.dll" "system" fn RegDeleteValueW(hkey : HKEY, lpvaluename : PCWSTR) -> WIN32_ERROR); +::windows_targets::link!("advapi32.dll" "system" fn RegEnumKeyExW(hkey : HKEY, dwindex : u32, lpname : PWSTR, lpcchname : *mut u32, lpreserved : *const u32, lpclass : PWSTR, lpcchclass : *mut u32, lpftlastwritetime : *mut FILETIME) -> WIN32_ERROR); +::windows_targets::link!("advapi32.dll" "system" fn RegEnumValueW(hkey : HKEY, dwindex : u32, lpvaluename : PWSTR, lpcchvaluename : *mut u32, lpreserved : *const u32, lptype : *mut u32, lpdata : *mut u8, lpcbdata : *mut u32) -> WIN32_ERROR); +::windows_targets::link!("advapi32.dll" "system" fn RegOpenKeyExW(hkey : HKEY, lpsubkey : PCWSTR, uloptions : u32, samdesired : REG_SAM_FLAGS, phkresult : *mut HKEY) -> WIN32_ERROR); +::windows_targets::link!("advapi32.dll" "system" fn RegQueryInfoKeyW(hkey : HKEY, lpclass : PWSTR, lpcchclass : *mut u32, lpreserved : *const u32, lpcsubkeys : *mut u32, lpcbmaxsubkeylen : *mut u32, lpcbmaxclasslen : *mut u32, lpcvalues : *mut u32, lpcbmaxvaluenamelen : *mut u32, lpcbmaxvaluelen : *mut u32, lpcbsecuritydescriptor : *mut u32, lpftlastwritetime : *mut FILETIME) -> WIN32_ERROR); +::windows_targets::link!("advapi32.dll" "system" fn RegQueryValueExW(hkey : HKEY, lpvaluename : PCWSTR, lpreserved : *const u32, lptype : *mut REG_VALUE_TYPE, lpdata : *mut u8, lpcbdata : *mut u32) -> WIN32_ERROR); +::windows_targets::link!("advapi32.dll" "system" fn RegSetValueExW(hkey : HKEY, lpvaluename : PCWSTR, reserved : u32, dwtype : REG_VALUE_TYPE, lpdata : *const u8, cbdata : u32) -> WIN32_ERROR); +pub type BOOL = i32; +pub const ERROR_INVALID_DATA: WIN32_ERROR = 13u32; +pub const ERROR_NO_MORE_ITEMS: WIN32_ERROR = 259u32; +#[repr(C)] +pub struct FILETIME { + pub dwLowDateTime: u32, + pub dwHighDateTime: u32, +} +impl ::core::marker::Copy for FILETIME {} +impl ::core::clone::Clone for FILETIME { + fn clone(&self) -> Self { + *self + } +} +pub type HKEY = isize; +pub const HKEY_CLASSES_ROOT: HKEY = -2147483648i32 as _; +pub const HKEY_CURRENT_CONFIG: HKEY = -2147483643i32 as _; +pub const HKEY_CURRENT_USER: HKEY = -2147483647i32 as _; +pub const HKEY_LOCAL_MACHINE: HKEY = -2147483646i32 as _; +pub const HKEY_USERS: HKEY = -2147483645i32 as _; +pub const KEY_READ: REG_SAM_FLAGS = 131097u32; +pub const KEY_WRITE: REG_SAM_FLAGS = 131078u32; +pub type PCWSTR = *const u16; +pub type PWSTR = *mut u16; +pub const REG_BINARY: REG_VALUE_TYPE = 3u32; +pub type REG_CREATE_KEY_DISPOSITION = u32; +pub const REG_DWORD: REG_VALUE_TYPE = 4u32; +pub const REG_EXPAND_SZ: REG_VALUE_TYPE = 2u32; +pub const REG_MULTI_SZ: REG_VALUE_TYPE = 7u32; +pub type REG_OPEN_CREATE_OPTIONS = u32; +pub const REG_OPTION_NON_VOLATILE: REG_OPEN_CREATE_OPTIONS = 0u32; +pub const REG_QWORD: REG_VALUE_TYPE = 11u32; +pub type REG_SAM_FLAGS = u32; +pub const REG_SZ: REG_VALUE_TYPE = 1u32; +pub type REG_VALUE_TYPE = u32; +#[repr(C)] +pub struct SECURITY_ATTRIBUTES { + pub nLength: u32, + pub lpSecurityDescriptor: *mut ::core::ffi::c_void, + pub bInheritHandle: BOOL, +} +impl ::core::marker::Copy for SECURITY_ATTRIBUTES {} +impl ::core::clone::Clone for SECURITY_ATTRIBUTES { + fn clone(&self) -> Self { + *self + } +} +pub type WIN32_ERROR = u32; diff --git a/crates/libs/registry/src/key.rs b/crates/libs/registry/src/key.rs new file mode 100644 index 0000000000..eb1d4919f7 --- /dev/null +++ b/crates/libs/registry/src/key.rs @@ -0,0 +1,276 @@ +use super::*; + +/// A registry key. +#[repr(transparent)] +#[derive(Default, Debug)] +pub struct Key(pub(crate) HKEY); + +impl Key { + /// Creates a registry key. If the key already exists, the function opens it. + pub fn create>(&self, path: T) -> Result { + let mut handle = 0; + + let result = unsafe { + RegCreateKeyExW( + self.0, + pcwstr(path).as_ptr(), + 0, + std::ptr::null(), + REG_OPTION_NON_VOLATILE, + KEY_READ | KEY_WRITE, + std::ptr::null(), + &mut handle, + std::ptr::null_mut(), + ) + }; + + win32_error(result).map(|_| Self(handle)) + } + + /// Opens a registry key. + pub fn open>(&self, path: T) -> Result { + let mut handle = 0; + + let result = + unsafe { RegOpenKeyExW(self.0, pcwstr(path).as_ptr(), 0, KEY_READ, &mut handle) }; + + win32_error(result).map(|_| Self(handle)) + } + + /// Removes the registry keys and values of the specified key recursively. + pub fn remove_tree>(&self, path: T) -> Result<()> { + let result = unsafe { RegDeleteTreeW(self.0, pcwstr(path).as_ptr()) }; + win32_error(result) + } + + /// Removes the registry value. + pub fn remove_value>(&self, name: T) -> Result<()> { + let result = unsafe { RegDeleteValueW(self.0, pcwstr(name).as_ptr()) }; + win32_error(result) + } + + /// Creates an iterator of registry key names. + pub fn keys(&self) -> Result> { + KeyIterator::new(self) + } + + /// Creates an iterator of registry values. + pub fn values(&self) -> Result> { + ValueIterator::new(self) + } + + /// Sets the name and value in the registry key. + pub fn set_u32>(&self, name: T, value: u32) -> Result<()> { + unsafe { self.set_value(name, REG_DWORD, &value as *const _ as _, 4) } + } + + /// Sets the name and value in the registry key. + pub fn set_u64>(&self, name: T, value: u64) -> Result<()> { + unsafe { self.set_value(name, REG_QWORD, &value as *const _ as _, 8) } + } + + /// Sets the name and value in the registry key. + pub fn set_string>(&self, name: T, value: T) -> Result<()> { + let value = pcwstr(value); + + unsafe { self.set_value(name, REG_SZ, value.as_ptr() as _, value.len() * 2) } + } + + /// Sets the name and value in the registry key. + pub fn set_multi_string>(&self, name: T, value: &[T]) -> Result<()> { + let mut packed = value.iter().fold(vec![0u16; 0], |mut packed, value| { + packed.append(&mut pcwstr(value)); + packed + }); + + packed.push(0); + + unsafe { self.set_value(name, REG_MULTI_SZ, packed.as_ptr() as _, packed.len() * 2) } + } + + /// Sets the name and value in the registry key. + pub fn set_bytes>(&self, name: T, value: &[u8]) -> Result<()> { + unsafe { self.set_value(name, REG_BINARY, value.as_ptr() as _, value.len()) } + } + + /// Gets the value for the name in the registry key. + pub fn get_value>(&self, name: T) -> Result { + let name = pcwstr(name); + let mut ty = 0; + let mut len = 0; + + let result = unsafe { + RegQueryValueExW( + self.0, + name.as_ptr(), + std::ptr::null(), + &mut ty, + std::ptr::null_mut(), + &mut len, + ) + }; + + win32_error(result)?; + + match ty { + REG_DWORD if len == 4 => { + let mut value = 0u32; + + let result = unsafe { + RegQueryValueExW( + self.0, + name.as_ptr(), + std::ptr::null(), + std::ptr::null_mut(), + &mut value as *mut _ as _, + &mut len, + ) + }; + + win32_error(result)?; + Ok(Value::U32(value)) + } + REG_QWORD if len == 8 => { + let mut value = 0u64; + + let result = unsafe { + RegQueryValueExW( + self.0, + name.as_ptr(), + std::ptr::null(), + std::ptr::null_mut(), + &mut value as *mut _ as _, + &mut len, + ) + }; + + win32_error(result)?; + Ok(Value::U64(value)) + } + REG_SZ | REG_EXPAND_SZ => { + let mut value = vec![0u16; len as usize / 2]; + + let result = unsafe { + RegQueryValueExW( + self.0, + name.as_ptr(), + std::ptr::null(), + std::ptr::null_mut(), + value.as_mut_ptr() as _, + &mut len, + ) + }; + + win32_error(result)?; + Ok(Value::String(String::from_utf16_lossy(trim(&value)))) + } + REG_MULTI_SZ => { + let mut value = vec![0u16; len as usize / 2]; + + let result = unsafe { + RegQueryValueExW( + self.0, + name.as_ptr(), + std::ptr::null(), + std::ptr::null_mut(), + value.as_mut_ptr() as _, + &mut len, + ) + }; + + win32_error(result)?; + + Ok(Value::MultiString( + trim(&value) + .split(|c| *c == 0) + .map(String::from_utf16_lossy) + .collect(), + )) + } + REG_BINARY => { + let mut value = vec![0u8; len as usize]; + + let result = unsafe { + RegQueryValueExW( + self.0, + name.as_ptr(), + std::ptr::null(), + std::ptr::null_mut(), + value.as_mut_ptr() as _, + &mut len, + ) + }; + + win32_error(result)?; + Ok(Value::Bytes(value)) + } + _ => Err(invalid_data()), + } + } + + /// Gets the value for the name in the registry key. + pub fn get_u32>(&self, name: T) -> Result { + if let Value::U32(value) = self.get_value(name)? { + Ok(value) + } else { + Err(invalid_data()) + } + } + + /// Gets the value for the name in the registry key. + pub fn get_u64>(&self, name: T) -> Result { + if let Value::U64(value) = self.get_value(name)? { + Ok(value) + } else { + Err(invalid_data()) + } + } + + /// Gets the value for the name in the registry key. + pub fn get_string>(&self, name: T) -> Result { + if let Value::String(value) = self.get_value(name)? { + Ok(value) + } else { + Err(invalid_data()) + } + } + + /// Gets the value for the name in the registry key. + pub fn get_bytes>(&self, name: T) -> Result> { + if let Value::Bytes(value) = self.get_value(name)? { + Ok(value) + } else { + Err(invalid_data()) + } + } + + /// Gets the value for the name in the registry key. + pub fn get_multi_string>(&self, name: T) -> Result> { + if let Value::MultiString(value) = self.get_value(name)? { + Ok(value) + } else { + Err(invalid_data()) + } + } + + unsafe fn set_value>( + &self, + name: T, + ty: REG_VALUE_TYPE, + ptr: *const u8, + len: usize, + ) -> Result<()> { + let result = + unsafe { RegSetValueExW(self.0, pcwstr(name).as_ptr(), 0, ty, ptr, len.try_into()?) }; + + win32_error(result) + } +} + +impl Drop for Key { + fn drop(&mut self) { + unsafe { + RegCloseKey(self.0); + } + } +} diff --git a/crates/libs/registry/src/key_iterator.rs b/crates/libs/registry/src/key_iterator.rs new file mode 100644 index 0000000000..367218da87 --- /dev/null +++ b/crates/libs/registry/src/key_iterator.rs @@ -0,0 +1,68 @@ +use super::*; + +/// An iterator of registry key names. +pub struct KeyIterator<'a> { + key: &'a Key, + range: std::ops::Range, + name: Vec, +} + +impl<'a> KeyIterator<'a> { + pub(crate) fn new(key: &'a Key) -> Result { + let mut count = 0; + let mut max_len = 0; + + let result = unsafe { + RegQueryInfoKeyW( + key.0, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut count, + &mut max_len, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + + win32_error(result).map(|_| Self { + key, + range: 0..count as usize, + name: vec![0; max_len as usize + 1], + }) + } +} + +impl<'a> Iterator for KeyIterator<'a> { + type Item = String; + + fn next(&mut self) -> Option { + self.range.next().and_then(|index| { + let mut len = self.name.len() as u32; + + let result = unsafe { + RegEnumKeyExW( + self.key.0, + index as u32, + self.name.as_mut_ptr(), + &mut len, + std::ptr::null(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + + if result != 0 { + debug_assert_eq!(result, ERROR_NO_MORE_ITEMS); + None + } else { + Some(String::from_utf16_lossy(&self.name[0..len as usize])) + } + }) + } +} diff --git a/crates/libs/registry/src/lib.rs b/crates/libs/registry/src/lib.rs new file mode 100644 index 0000000000..af9059d15c --- /dev/null +++ b/crates/libs/registry/src/lib.rs @@ -0,0 +1,63 @@ +/*! +Learn more about Rust for Windows here: +*/ + +mod bindings; +use bindings::*; + +mod key; +pub use key::Key; + +mod value; +pub use value::Value; + +mod key_iterator; +pub use key_iterator::KeyIterator; + +mod value_iterator; +pub use value_iterator::ValueIterator; + +pub use windows_result::Result; +use windows_result::*; + +/// The predefined `HKEY_CLASSES_ROOT` registry key. +pub const CLASSES_ROOT: &Key = &Key(HKEY_CLASSES_ROOT); + +/// The predefined `HKEY_CURRENT_CONFIG` registry key. +pub const CURRENT_CONFIG: &Key = &Key(HKEY_CURRENT_CONFIG); + +/// The predefined `HKEY_CURRENT_USER` registry key. +pub const CURRENT_USER: &Key = &Key(HKEY_CURRENT_USER); + +/// The predefined `HKEY_LOCAL_MACHINE` registry key. +pub const LOCAL_MACHINE: &Key = &Key(HKEY_LOCAL_MACHINE); + +/// The predefined `HKEY_USERS` registry key. +pub const USERS: &Key = &Key(HKEY_USERS); + +fn pcwstr>(value: T) -> Vec { + value + .as_ref() + .encode_utf16() + .chain(std::iter::once(0)) + .collect() +} + +fn trim(mut value: &[u16]) -> &[u16] { + while value.last() == Some(&0) { + value = &value[..value.len() - 1]; + } + value +} + +fn win32_error(result: u32) -> Result<()> { + if result == 0 { + Ok(()) + } else { + Err(Error::from_hresult(HRESULT::from_win32(result))) + } +} + +fn invalid_data() -> Error { + Error::from_hresult(HRESULT::from_win32(ERROR_INVALID_DATA)) +} diff --git a/crates/libs/registry/src/value.rs b/crates/libs/registry/src/value.rs new file mode 100644 index 0000000000..ba25e0cccf --- /dev/null +++ b/crates/libs/registry/src/value.rs @@ -0,0 +1,21 @@ +/// A registry value. +#[derive(Clone, PartialEq, Eq, Debug)] +pub enum Value { + /// A 32-bit unsigned integer value. + U32(u32), + + /// A 64-bit unsigned integer value. + U64(u64), + + /// A string value. + String(String), + + /// An array u8 bytes. + Bytes(Vec), + + /// An array of string values. + MultiString(Vec), + + /// An unknown or unsupported type. + Unknown(u32), +} diff --git a/crates/libs/registry/src/value_iterator.rs b/crates/libs/registry/src/value_iterator.rs new file mode 100644 index 0000000000..1f4b25f5b3 --- /dev/null +++ b/crates/libs/registry/src/value_iterator.rs @@ -0,0 +1,118 @@ +use super::*; + +/// An iterator of registry values. +pub struct ValueIterator<'a> { + key: &'a Key, + range: std::ops::Range, + name: Vec, + value: Vec, +} + +impl<'a> ValueIterator<'a> { + pub(crate) fn new(key: &'a Key) -> Result { + let mut count = 0; + let mut name_max_len = 0; + let mut value_max_len = 0; + + let result = unsafe { + RegQueryInfoKeyW( + key.0, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut count, + &mut name_max_len, + &mut value_max_len, + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + + win32_error(result).map(|_| Self { + key, + range: 0..count as usize, + name: vec![0; name_max_len as usize + 1], + value: vec![0; value_max_len as usize], + }) + } +} + +impl<'a> Iterator for ValueIterator<'a> { + type Item = (String, Value); + + fn next(&mut self) -> Option { + self.range.next().and_then(|index| { + let mut ty = 0; + let mut name_len = self.name.len() as u32; + let mut value_len = self.value.len() as u32; + + let result = unsafe { + RegEnumValueW( + self.key.0, + index as u32, + self.name.as_mut_ptr(), + &mut name_len, + std::ptr::null(), + &mut ty, + self.value.as_mut_ptr(), + &mut value_len, + ) + }; + + if result != 0 { + debug_assert_eq!(result, ERROR_NO_MORE_ITEMS); + None + } else { + let value = match ty { + REG_DWORD if value_len == 4 => { + Value::U32(u32::from_le_bytes(self.value[0..4].try_into().unwrap())) + } + REG_QWORD if value_len == 8 => { + Value::U64(u64::from_le_bytes(self.value[0..8].try_into().unwrap())) + } + REG_BINARY => Value::Bytes(self.value[0..value_len as usize].to_vec()), + REG_SZ | REG_EXPAND_SZ => { + if value_len == 0 { + Value::String(String::new()) + } else { + let value = unsafe { + std::slice::from_raw_parts( + self.value.as_ptr() as *const u16, + value_len as usize / 2, + ) + }; + + Value::String(String::from_utf16_lossy(trim(value))) + } + } + REG_MULTI_SZ => { + if value_len == 0 { + Value::MultiString(vec![]) + } else { + let value = unsafe { + std::slice::from_raw_parts( + self.value.as_ptr() as *const u16, + value_len as usize / 2, + ) + }; + + Value::MultiString( + trim(value) + .split(|c| *c == 0) + .map(String::from_utf16_lossy) + .collect(), + ) + } + } + rest => Value::Unknown(rest), + }; + + let name = String::from_utf16_lossy(&self.name[0..name_len as usize]); + Some((name, value)) + } + }) + } +} diff --git a/crates/libs/registry/tests/bindings.rs b/crates/libs/registry/tests/bindings.rs new file mode 100644 index 0000000000..803ee2f2c8 --- /dev/null +++ b/crates/libs/registry/tests/bindings.rs @@ -0,0 +1,4 @@ +#[test] +fn bindings() { + windows_bindgen::bindgen(["--etc", "tests/bindings.txt"]).unwrap(); +} diff --git a/crates/libs/registry/tests/bindings.txt b/crates/libs/registry/tests/bindings.txt new file mode 100644 index 0000000000..221a53d704 --- /dev/null +++ b/crates/libs/registry/tests/bindings.txt @@ -0,0 +1,30 @@ +--out src/bindings.rs +--config flatten sys minimal + +--filter + Windows.Win32.Foundation.ERROR_INVALID_DATA + Windows.Win32.Foundation.ERROR_NO_MORE_ITEMS + Windows.Win32.System.Registry.HKEY_CLASSES_ROOT + Windows.Win32.System.Registry.HKEY_CURRENT_CONFIG + Windows.Win32.System.Registry.HKEY_CURRENT_USER + Windows.Win32.System.Registry.HKEY_LOCAL_MACHINE + Windows.Win32.System.Registry.HKEY_USERS + Windows.Win32.System.Registry.KEY_READ + Windows.Win32.System.Registry.KEY_WRITE + Windows.Win32.System.Registry.REG_BINARY + Windows.Win32.System.Registry.REG_DWORD + Windows.Win32.System.Registry.REG_EXPAND_SZ + Windows.Win32.System.Registry.REG_MULTI_SZ + Windows.Win32.System.Registry.REG_OPTION_NON_VOLATILE + Windows.Win32.System.Registry.REG_QWORD + Windows.Win32.System.Registry.REG_SZ + Windows.Win32.System.Registry.RegCloseKey + Windows.Win32.System.Registry.RegCreateKeyExW + Windows.Win32.System.Registry.RegDeleteTreeW + Windows.Win32.System.Registry.RegDeleteValueW + Windows.Win32.System.Registry.RegEnumKeyExW + Windows.Win32.System.Registry.RegEnumValueW + Windows.Win32.System.Registry.RegOpenKeyExW + Windows.Win32.System.Registry.RegQueryInfoKeyW + Windows.Win32.System.Registry.RegQueryValueExW + Windows.Win32.System.Registry.RegSetValueExW diff --git a/crates/tests/registry/Cargo.toml b/crates/tests/registry/Cargo.toml new file mode 100644 index 0000000000..9c9243c783 --- /dev/null +++ b/crates/tests/registry/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "test_registry" +version = "0.0.0" +edition = "2021" +publish = false + +[dependencies.windows-registry] +path = "../../libs/registry" + +[dependencies.windows-result] +path = "../../libs/result" diff --git a/crates/tests/registry/src/lib.rs b/crates/tests/registry/src/lib.rs new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/crates/tests/registry/src/lib.rs @@ -0,0 +1 @@ + diff --git a/crates/tests/registry/tests/keys.rs b/crates/tests/registry/tests/keys.rs new file mode 100644 index 0000000000..4a8114bf33 --- /dev/null +++ b/crates/tests/registry/tests/keys.rs @@ -0,0 +1,27 @@ +use windows_registry::*; +use windows_result::*; + +#[test] +fn keys() -> Result<()> { + let test_key = "software\\windows-rs\\tests\\keys"; + _ = CURRENT_USER.remove_tree(test_key); + + let key = CURRENT_USER.create(test_key)?; + key.create("one")?; + key.create("two")?; + key.create("three")?; + + let names: Vec = key.keys()?.collect(); + assert_eq!(names, ["one", "three", "two"]); + + let err = key.open("missing").unwrap_err(); + assert_eq!(err.code(), HRESULT(0x80070002u32 as i32)); // HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) + assert_eq!(err.message(), "The system cannot find the file specified."); + + let key = key.open("one")?; + let err = key.set_u32("name", 123).unwrap_err(); + assert_eq!(err.code(), HRESULT(0x80070005u32 as i32)); // E_ACCESSDENIED + assert_eq!(err.message(), "Access is denied."); + + Ok(()) +} diff --git a/crates/tests/registry/tests/values.rs b/crates/tests/registry/tests/values.rs new file mode 100644 index 0000000000..d78256d3b4 --- /dev/null +++ b/crates/tests/registry/tests/values.rs @@ -0,0 +1,68 @@ +use windows_registry::*; +use windows_result::*; + +#[test] +fn values() -> Result<()> { + let test_key = "software\\windows-rs\\tests\\values"; + _ = CURRENT_USER.remove_tree(test_key); + + let key = CURRENT_USER.create(test_key)?; + key.set_u32("u32", 123)?; + key.set_u64("u64", 456)?; + key.set_string("string", "hello")?; + key.set_bytes("bytes", &[1u8, 2u8, 2u8])?; + key.set_multi_string("multi", &["hello", "world"])?; + + assert_eq!(key.get_u32("u32")?, 123u32); + assert_eq!(key.get_u64("u64")?, 456u64); + assert_eq!(key.get_string("string")?, "hello".to_string()); + assert_eq!(key.get_bytes("bytes")?, vec![1u8, 2u8, 2u8]); + assert_eq!( + key.get_multi_string("multi")?, + vec!["hello".to_string(), "world".to_string()] + ); + + let err = key.get_u32("string").unwrap_err(); + assert_eq!(err.code(), HRESULT(0x8007000Du32 as i32)); // HRESULT_FROM_WIN32(ERROR_INVALID_DATA) + assert_eq!(err.message(), "The data is invalid."); + + assert_eq!(key.get_value("u32")?, Value::U32(123)); + assert_eq!(key.get_value("u64")?, Value::U64(456)); + assert_eq!(key.get_value("string")?, Value::String("hello".to_string())); + assert_eq!(key.get_value("bytes")?, Value::Bytes(vec![1u8, 2u8, 2u8])); + assert_eq!( + key.get_value("multi")?, + Value::MultiString(vec!["hello".to_string(), "world".to_string()]) + ); + + let names: Vec<(String, Value)> = key.values()?.collect(); + + assert_eq!( + names, + [ + ("u32".to_string(), Value::U32(123)), + ("u64".to_string(), Value::U64(456)), + ("string".to_string(), Value::String("hello".to_string())), + ("bytes".to_string(), Value::Bytes(vec![1u8, 2u8, 2u8])), + ( + "multi".to_string(), + Value::MultiString(vec!["hello".to_string(), "world".to_string()]) + ), + ] + ); + + key.remove_value("string")?; + key.remove_value("multi")?; + let names: Vec<_> = key.values()?.collect(); + + assert_eq!( + names, + [ + ("u32".to_string(), Value::U32(123)), + ("u64".to_string(), Value::U64(456)), + ("bytes".to_string(), Value::Bytes(vec![1u8, 2u8, 2u8])), + ] + ); + + Ok(()) +}