[
  {
    "path": ".cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-uefi\""
  },
  {
    "path": ".gitignore",
    "content": "/target\n/.idea\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"setup_var\"\nversion = \"0.3.1\"\nedition = \"2024\"\nlicense = \"MIT OR Apache-2.0\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\nuefi = { version = \"0.34.1\", features = [\"alloc\", \"global_allocator\", \"panic_handler\"] }\nnum_enum = { version = \"0.7.3\", default-features = false }\nstrum = { version = \"0.27.1\", default-features = false, features = [\"derive\"] }"
  },
  {
    "path": "LICENSE-APACHE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "LICENSE-MIT",
    "content": "MIT License\n\nCopyright (c) 2022 datasone\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# UEFI Command Line Tool for Reading/Writing UEFI Variables\nThis tool is a rewritten version of the [modded grub with setup_var commands](https://github.com/datasone/grub-mod-setup_var), enhanced with much cleaner code, aarch64 support and ability to be automated. The tool is able to read/write UEFI variables, and is usually used for changing BIOS settings which are hidden from UI.\n\n⚠ Use this tool with extreme caution as accessing wrong varstore or variable may completely brick your computer!\n\n---\n**The new usage document is for 0.3.0 version and later with the new syntax for specifying variables. For 0.2.x releases with the old syntax (0.2.x will still be maintained so you can continue to use that), refer to [document of that version](https://github.com/datasone/setup_var.efi/blob/0.2.x/README.md).**\n\n---\nNote: If you have been using the modded grub tool, you may want to refer to [the cheatsheet](#grub-cheatsheet).\n\n## Term definitions\nThe legacy names used in grub version of the tool and some other related tools (e.g. IFR extractor) used *varstore* and *variable*. The former word is not used in UEFI specification, and is actually the **variable** in UEFI runtime services (sometimes referred to as \"variable store\", which is possibly where \"varstore\" came from). So to clarify this, this project uses \"variable\" and \"value\":\n- **Variable** is the former *varstore*, which means a named storage with varying size from several to several thousands of bytes. Maybe used for storing many values of many BIOS setting items.\n- **Value** is the former *variable*, which represents a value in the variable with few (often one to two) bytes, referred with variable and offset. While changing BIOS settings, this means the value of *one* BIOS setting item.\n\n## Usage\nRun `setup_var.efi -h` in UEFI shell to get this help:\n```\nsetup_var.efi [-h/--help] [-r/--reboot(=auto)] [--write_on_demand] VALUE_ARG...\n\n-r or --reboot: Reboot (warm reset) the computer after the program successfully finishes.\n--reboot=auto: Reboot only if any value was actually written. This option automatically enables --write_on_demand.\n--write_on_demand: If the value desired to be written is the same with storage, skip the unnecessary write.\n\nVALUE_ARG represents the value needs to be read/written, and can be specified multiple times.\nThe format of VALUE_ARG is: <VAR_NAME>[(VAR_ID)]:<OFFSET>[(VALUE_SIZE)][=VALUE]\n\nVAR_NAME: The name of UEFI variable to be altered, defaults to \"Setup\".\nVAR_ID: Unique id for distinguishing variables with same name, which will be provided by setup_var.efi (when required).\nOFFSET: The offset of value to be altered in the UEFI variable.\nVALUE: The new value to write, capped at 64-bit. If not specified, the value at OFFSET will be read and shown.\nVALUE_SIZE: Bytes of value to write, must be equal or larger than the size of <VALUE>, defaults to 1.\n\nOFFSET, VALUE, VALUE_SIZE and VAR_ID are numbers, and can be specified in hexadecimal with prefix \"0x\", or decimal with no prefixes.\n\nThe program defaults to little endian for values ONLY while operating UEFI variables,\nthough it's recommended to only operate on one byte if you are not sure what this is or means.\n\nExample: .\\setup_var.efi -r CpuSetup:0x10E=0x1A\n```\n\n---\n\n### Examples for `VALUE_ARG`\n- `CpuSetup:0x10E=0x1A`: write one byte `0x1A` to offset `0x10E` in `CpuSetup`.\n- `CpuSetup:0x10E(2)`: read one word (2 bytes) from offset `0x10E` in `CpuSetup`.\n- `Setup(1):0x100(2)=0x1000`: write one word `0x1000` to offset `0x100` in `Setup` with variable id `1`.\n\n---\n\nFor changing BIOS settings, you may use those following steps to obtain the variable name and value offset:\n1. Obtain (raw) BIOS image, some motherboard OEMs provides BIOS image that can be directly opened but it's not commonly the case for branded PCs. For Intel CPU-based systems, you may use **Flash Programming Tool** from CSME System Tools to directly extract raw BIOS image.\n2. Use [UEFITool](https://github.com/LongSoft/UEFITool) to open the BIOS image, and find `Setup` as string, there would be image sections named \"Setup/*\", navigate to that and extract body of the `Setup` folder to a file.\n3. Use [IFR-Extractor](https://github.com/LongSoft/Universal-IFR-Extractor) to export setup info to a text file.\n4. Find your desired setting in the text file, note the offset after `VarStoreInfo (VarOffset/VarName):` and the id after `VarStore:`.\n5. Search for `VarStoreId: {id}`, where `{id}` is the id found earlier. And note the `Name` after it.\n6. Change the value using noted variable(varstore) name, offset, and size.\n\n## Input File\n`setup_var.efi` now supports specifying with a input file (by UEFI shell redirection). All options that can be specified with arguments are available in input file.\n\nNote: The text should be in UTF-16LE encoding, see [pinned issue #25](https://github.com/datasone/setup_var.efi/issues/25) for details.\n\nThe input file consists of three parts:\n- Named arguments which are specified with a leading `@`.\n- Defining a value address reference (to make the input file more readable) with `:=`.\n- Specifying value arguments as how they are specified in progrm arguments.\n\nComments starting with `#` can be specified in the input file.\n\n### Input File Example\n```\n# Named arguments\n# @reboot # Reboot after executing setup_var.efi\n@write_on_demand # Only write values when necessary\n\n# Address Definition\nADLImonSlope:=CpuSetup:0x016E\nADLImonPrefix:=CpuSetup:0x0182\n\n# Value Args\n# Address can be referenced with leading '$'\n$ADLImonSlope=0x14\n$ADLImonPrefix=0x01\n\n# Normal value argument also works\nCpuSetup:0x0178(2)=0x4E20\n```\n\nThe output of `setup.var.efi` has also be altered to match the format of the input file. So you can save your configurations with\n```shell\nsetup_var.efi CpuSetup:0x10E=0x1A > vars.txt\n```\nand load them afterwards with\n```shell\nsetup_var.efi < vars.txt\n```\n\n## GRUB Cheatsheet\nThe legacy grub commands can be mapped to these usages of this tool:\n- `setup_var offset [value]`: `setup_var.efi Setup:offset[=value]`.\n- `setup_var2 offset [value]`: This command searches for named `Custom`, so `setup_var.efi Custom:offset[=value]`.\n- `setup_var_3 offset [value]`: This command discards variables that are too small, `setup_var.efi` has the `VAR_ID` argument to handle this. Though it's not tested as the problemed firmware used to test this command has been updated and the issue was solved.\n- `setup_var_vs offset [value_size] [value]`: This command processes variable-sized values, and is mapped to `setup_var.efi Setup:offset(value_size)[=value]`.\n- `setup_var_cv name offset [value_size] [value]`: This was the full-featured command, to use full features, use `setup_var.efi name:offset(value_size)[=value]`, in which the `(value_size)` can be omitted for 1-byte value.\n\n## Build\n```shell\ncargo build [--release]\n```\n\nThe default and tested target for this project is `x86_64-unknown-uefi`, it can also target `aarch64-unknown-uefi` for AArch64 UEFI and `i686-unknown-uefi` for 32-bit x86 EFI, though they are not tested and may contain glitches.\n"
  },
  {
    "path": "rust-toolchain.toml",
    "content": "[toolchain]\ntargets = [\"aarch64-unknown-uefi\", \"i686-unknown-uefi\", \"x86_64-unknown-uefi\"]\n"
  },
  {
    "path": "src/args.rs",
    "content": "use alloc::{\n    borrow::{Cow, ToOwned},\n    format,\n    string::{String, ToString},\n    vec,\n    vec::Vec,\n};\nuse core::fmt::{Display, Formatter};\n\nuse uefi::{\n    CStr16, CString16, Char16,\n    data_types::EqStrUntilNul,\n    println,\n    proto::loaded_image::{LoadOptionsError, LoadedImage},\n};\n\nuse crate::utils::{CStr16Ext, UEFIValue};\n\n#[derive(Debug)]\npub enum ParseError {\n    LoadedImageProtocolError,\n    LoadOptionsError(LoadOptionsError),\n    InvalidValue(String),\n    NumberTooLarge(String),\n    InvalidArgs(ArgsError),\n    NoArgs,\n    NoInput,\n    LoadStdInError,\n    AddrDefWrite(String),\n}\n\nimpl Display for ParseError {\n    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {\n        match self {\n            Self::LoadedImageProtocolError => {\n                write!(f, \"Error while initializing UEFI LoadedImage protocol\")\n            }\n            Self::LoadOptionsError(e) => {\n                write!(f, \"Error loading options: {e:?}\")\n            }\n            Self::InvalidValue(s) => {\n                write!(f, \"Unexpected value: {s}\")\n            }\n            Self::NumberTooLarge(s) => {\n                write!(f, \"Specified number {s} is too large (larger than 64-bit)\")\n            }\n            Self::InvalidArgs(e) => {\n                write!(f, \"{e}\")\n            }\n            Self::NoArgs => {\n                // This error is not meant to be returned to user\n                write!(f, \"\")\n            }\n            Self::NoInput => {\n                // This error is not meant to be returned to user as well\n                write!(f, \"\")\n            }\n            Self::LoadStdInError => {\n                write!(f, \"Error while reading from standard input\")\n            }\n            Self::AddrDefWrite(s) => {\n                write!(f, \"Address definition in {s} cannot contain value write\")\n            }\n        }\n    }\n}\n\n#[derive(Debug, Default, Clone)]\npub struct ValueAddr {\n    pub var_name: CString16,\n    pub var_id:   Option<usize>,\n    pub offset:   usize,\n    pub val_size: usize,\n}\n\n#[derive(Debug, Default, Copy, Clone)]\npub enum ValueOperation {\n    #[default]\n    Read,\n    Write(usize),\n}\n\n#[derive(Debug, Default, Clone)]\npub struct ValueArg {\n    pub addr:      ValueAddr,\n    pub operation: ValueOperation,\n}\n\nimpl ValueArg {\n    pub fn validate(&self) -> Result<(), ArgsError> {\n        if let ValueOperation::Write(val) = self.operation {\n            if val > (1 << (self.addr.val_size * 8)) {\n                Err(ArgsError::ValLargerThanSize(val, self.addr.val_size))\n            } else {\n                Ok(())\n            }\n        } else {\n            Ok(())\n        }\n    }\n\n    pub fn to_string_with_val(&self, value: &UEFIValue) -> String {\n        let var_name = &self.addr.var_name;\n        let var_id_str = match self.addr.var_id {\n            None => \"\".to_owned(),\n            Some(id) => format!(\"({id})\"),\n        };\n\n        let var_offset = self.addr.offset;\n        let val_size_str = if self.addr.val_size == 1 {\n            \"\".to_owned()\n        } else {\n            format!(\"({})\", self.addr.val_size)\n        };\n\n        let value_str = value.to_string_with_size(self.addr.val_size);\n\n        format!(\"{var_name}{var_id_str}:0x{var_offset:X}{val_size_str}={value_str}\")\n    }\n}\n\n#[derive(Debug, PartialEq, Copy, Clone)]\npub enum RebootMode {\n    Never,\n    Always,\n    Auto,\n}\n\nimpl Default for RebootMode {\n    fn default() -> Self {\n        Self::Never\n    }\n}\n\n#[derive(Debug)]\npub enum NamedArg {\n    Help,\n    Reboot(RebootMode),\n    WriteOnDemand,\n}\n\n#[derive(Debug)]\nenum Arg {\n    Named(NamedArg),\n    Value(ValueArg),\n}\n\n#[derive(Debug, Default)]\npub struct Args {\n    pub value_args:      Vec<ValueArg>,\n    pub help_msg:        bool,\n    pub write_on_demand: bool,\n    pub reboot:          RebootMode,\n}\n\nimpl Args {\n    fn validate(&self) -> Result<(), ArgsError> {\n        if self.help_msg {\n            Ok(())\n        } else {\n            self.value_args.iter().try_for_each(|va| va.validate())\n        }\n    }\n}\n\n#[derive(Debug)]\npub enum ArgsError {\n    ValLargerThanSize(usize, usize),\n}\n\nimpl Display for ArgsError {\n    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {\n        match self {\n            Self::ValLargerThanSize(value, size) => {\n                write!(\n                    f,\n                    \"Specified value to write (0x{:0width$X}) is larger than specified size \\\n                     {size} bytes\",\n                    value,\n                    width = size * 2,\n                )\n            }\n        }\n    }\n}\n\nimpl From<ArgsError> for ParseError {\n    fn from(value: ArgsError) -> Self {\n        Self::InvalidArgs(value)\n    }\n}\n\npub const HELP_MSG: &str = r#\"Usage:\nsetup_var.efi [-h/--help] [-r/--reboot(=auto)] [--write_on_demand] VALUE_ARG...\n\n-r or --reboot: Reboot (warm reset) the computer after the program successfully finishes.\n--reboot=auto: Reboot only if any value was actually written. This option automatically enables --write_on_demand.\n--write_on_demand: If the value desired to be written is the same with storage, skip the unnecessary write.\n\nVALUE_ARG represents the value needs to be read/written, and can be specified multiple times.\nThe format of VALUE_ARG is: <VAR_NAME>[(VAR_ID)]:<OFFSET>[(VALUE_SIZE)][=VALUE]\n\nVAR_NAME: The name of UEFI variable to be altered, defaults to \"Setup\".\nVAR_ID: Unique id for distinguishing variables with same name, which will be provided by setup_var.efi (when required).\nOFFSET: The offset of value to be altered in the UEFI variable.\nVALUE: The new value to write, capped at 64-bit. If not specified, the value at OFFSET will be read and shown.\nVALUE_SIZE: Bytes of value to write, must be equal or larger than the size of <VALUE>, defaults to 1.\n\nOFFSET, VALUE, VALUE_SIZE and VAR_ID are numbers, and can be specified in hexadecimal with prefix \"0x\", or decimal with no prefixes.\n\nThe program defaults to little endian for values ONLY while operating UEFI variables,\nthough it's recommended to only operate on one byte if you are not sure what this is or means.\n\nExample: .\\setup_var.efi -r CpuSetup:0x10E=0x1A\"#;\n\npub fn parse_args() -> Result<Args, ParseError> {\n    let loaded_image =\n        uefi::boot::open_protocol_exclusive::<LoadedImage>(uefi::boot::image_handle())\n            .map_err(|_| ParseError::LoadedImageProtocolError)?;\n\n    let options = loaded_image\n        .load_options_as_cstr16()\n        .map_err(ParseError::LoadOptionsError)?;\n\n    parse_args_from_str(options)\n}\n\nfn drop_first_arg(arg: &CStr16) -> bool {\n    let rev_efi_ext: [Char16; 5] = [\n        '.'.try_into().unwrap(),\n        'e'.try_into().unwrap(),\n        'f'.try_into().unwrap(),\n        'i'.try_into().unwrap(),\n        '\\0'.try_into().unwrap(),\n    ];\n    let arg_chars = arg.as_slice_with_nul();\n    let has_efi_ext = if arg_chars.len() < 5 {\n        false\n    } else {\n        let arg_last_chars = &arg_chars[arg_chars.len() - 5..arg_chars.len()];\n        arg_last_chars == rev_efi_ext\n    };\n\n    #[allow(clippy::needless_bool)]\n    #[allow(clippy::if_same_then_else)]\n    if has_efi_ext {\n        true // efi extension, treated as the name of the executable file\n    } else if starts_with(arg, '-') {\n        false // Highly probably an option\n    } else {\n        // Now that we can't decide what is the first arg as they starts with the var\n        // name, defaults to keep it\n        false\n    }\n}\n\nmacro_rules! try_parsers {\n    ($input:expr, $parser:expr) => {{\n        $parser($input)\n    }};\n\n    ($input:expr, $parser:expr, $( $parsers:expr ),* $(,)? ) => {{\n        if let Ok(val) = $parser($input) {\n            Ok(val)\n        } else {\n            crate::args::try_parsers!($input, $($parsers),*)\n        }\n    }};\n}\n\npub(crate) use try_parsers;\n\nfn parse_args_from_str(options: &CStr16) -> Result<Args, ParseError> {\n    let options = options.split_to_cstring(' '.try_into().unwrap());\n    let opt_len = options.len();\n\n    if opt_len == 0 {\n        return Err(ParseError::NoArgs);\n    }\n\n    let first_arg = options[0].clone();\n    let mut option_iter = options.into_iter();\n    if drop_first_arg(&first_arg) {\n        if opt_len == 1 {\n            return Err(ParseError::NoArgs);\n        }\n        option_iter.next(); // Skips executable argv\n    }\n\n    let args = option_iter\n        .filter(|s| s.as_slice_with_nul().len() != 1)\n        .map(|s| {\n            try_parsers!(&s, parse_named_arg, parse_value_arg_wrapped)\n                .map_err(|e| ParseError::InvalidValue(format!(\"{s}: {e}\")))\n        })\n        .collect::<Result<Vec<_>, _>>()?;\n\n    let named_args = args\n        .iter()\n        .filter(|arg| matches!(arg, Arg::Named(_)))\n        .map(|arg| {\n            if let Arg::Named(arg) = arg {\n                arg\n            } else {\n                unreachable!()\n            }\n        })\n        .collect::<Vec<_>>();\n    let value_args = args\n        .iter()\n        .filter(|arg| matches!(arg, Arg::Value(_)))\n        .map(|arg| {\n            if let Arg::Value(arg) = arg {\n                arg.clone()\n            } else {\n                unreachable!()\n            }\n        })\n        .collect::<Vec<_>>();\n\n    let mut args = Args::default();\n    for named_arg in named_args {\n        match named_arg {\n            NamedArg::Help => args.help_msg = true,\n            NamedArg::Reboot(mode) => {\n                args.reboot = *mode;\n                if *mode == RebootMode::Auto {\n                    args.write_on_demand = true;\n                }\n            }\n            NamedArg::WriteOnDemand => args.write_on_demand = true,\n        }\n    }\n\n    args.value_args = value_args;\n\n    args.validate()?;\n    Ok(args)\n}\n\nfn starts_with(s: &CStr16, c: char) -> bool {\n    match s.as_slice_with_nul().first() {\n        None => false,\n        Some(&c_h) => c_h == Char16::try_from(c).unwrap(),\n    }\n}\n\nfn try_next_char(iter: &mut impl Iterator<Item = char>, str: &CStr16) -> Result<char, ParseError> {\n    iter.next()\n        .ok_or_else(|| ParseError::InvalidValue(str.to_string()))\n}\n\nfn parse_hex_number(num_str: &CStr16) -> Result<usize, ParseError> {\n    let mut str_iter = num_str.iter().map(|&c| char::from(c));\n\n    // Prefix 0x(0X)\n    let c_h = try_next_char(&mut str_iter, num_str)?;\n    let c2_h = try_next_char(&mut str_iter, num_str)?;\n\n    match (c_h, c2_h) {\n        ('0', 'x') => {}\n        ('0', 'X') => {}\n        _ => return Err(ParseError::InvalidValue(num_str.to_string())),\n    }\n\n    if num_str.num_bytes() > 2 * (18 + 1) {\n        return Err(ParseError::NumberTooLarge(num_str.to_string()));\n    }\n\n    let value = str_iter\n        .map(|c| c.to_digit(16).map(|n| n as u8))\n        .collect::<Option<Vec<u8>>>()\n        .ok_or_else(|| ParseError::InvalidValue(num_str.to_string()))?;\n    let value_len = value.len();\n    let value = value.iter().enumerate().fold(0usize, |acc, (i, &n)| {\n        acc + ((n as usize) << (4 * (value_len - i - 1)))\n    });\n\n    Ok(value)\n}\n\nfn parse_number(num_str: &CStr16) -> Result<usize, ParseError> {\n    let chars = num_str.iter().map(|&c| char::from(c)).collect::<Vec<_>>();\n    if chars.iter().any(|c| !c.is_ascii_digit()) {\n        Err(ParseError::InvalidValue(num_str.to_string()))?\n    }\n\n    let value = chars\n        .into_iter()\n        .fold(0usize, |acc, n| acc * 10 + (n as u8 - b'0') as usize);\n\n    Ok(value)\n}\n\nfn parse_named_arg(key: &CStr16) -> Result<Arg, ParseError> {\n    if key.eq_str_until_nul(&\"-h\") || key.eq_str_until_nul(&\"--help\") {\n        Ok(Arg::Named(NamedArg::Help))\n    } else if key.eq_str_until_nul(&\"-r=auto\") || key.eq_str_until_nul(&\"--reboot=auto\") {\n        Ok(Arg::Named(NamedArg::Reboot(RebootMode::Auto)))\n    } else if key.eq_str_until_nul(&\"-r\") || key.eq_str_until_nul(&\"--reboot\") {\n        Ok(Arg::Named(NamedArg::Reboot(RebootMode::Always)))\n    } else if key.eq_str_until_nul(&\"--write_on_demand\") {\n        Ok(Arg::Named(NamedArg::WriteOnDemand))\n    } else {\n        Err(ParseError::InvalidValue(key.to_string()))\n    }\n}\n\nfn parse_value_arg_wrapped(arg: &CStr16) -> Result<Arg, ParseError> {\n    Ok(Arg::Value(parse_value_arg(arg)?))\n}\n\npub fn parse_value_wrapped(arg: &CStr16) -> Result<ValueOperation, ParseError> {\n    Ok(parse_value(arg)?.1)\n}\n\nfn parse_value(arg: &CStr16) -> Result<(Cow<CStr16>, ValueOperation), ParseError> {\n    if arg.contains('='.try_into().unwrap()) {\n        let mut arg_split = arg.split_to_cstring('='.try_into().unwrap());\n        if arg_split.len() != 2 {\n            Err(ParseError::InvalidValue(arg.to_string()))?\n        }\n        let value = try_parsers!(&arg_split[1], parse_hex_number, parse_number)?;\n\n        Ok((\n            Cow::Owned(arg_split.swap_remove(0)),\n            ValueOperation::Write(value),\n        ))\n    } else {\n        Ok((Cow::Borrowed(arg), ValueOperation::Read))\n    }\n}\n\npub fn parse_value_arg(arg: &CStr16) -> Result<ValueArg, ParseError> {\n    let mut arg_split = arg.split_to_cstring(':'.try_into().unwrap());\n    if arg_split.len() != 2 {\n        Err(ParseError::InvalidValue(arg.to_string()))?\n    }\n\n    let mut var_name = arg_split.swap_remove(0);\n    let mut var_id = None;\n\n    if var_name.contains('('.try_into().unwrap()) {\n        let mut arg_split = var_name.split_to_cstring('('.try_into().unwrap());\n        if arg_split.len() != 2 {\n            Err(ParseError::InvalidValue(var_name.to_string()))?\n        }\n        let var_id_str = arg_split[1]\n            .strip_suffix(')'.try_into().unwrap())\n            .ok_or(ParseError::InvalidValue(var_name.to_string()))?;\n\n        var_id = Some(try_parsers!(&var_id_str, parse_number, parse_hex_number)?);\n        var_name = arg_split.swap_remove(0);\n    }\n\n    let var_offset = arg_split.swap_remove(0);\n    let mut val_size = 1;\n\n    let (mut var_offset, op_type) = parse_value(&var_offset)?;\n\n    if var_offset.contains('('.try_into().unwrap()) {\n        let mut arg_split = var_offset.split_to_cstring('('.try_into().unwrap());\n        if arg_split.len() != 2 {\n            Err(ParseError::InvalidValue(var_offset.to_string()))?\n        }\n        let val_size_str = arg_split[1]\n            .strip_suffix(')'.try_into().unwrap())\n            .ok_or(ParseError::InvalidValue(var_offset.to_string()))?;\n\n        val_size = try_parsers!(&val_size_str, parse_number, parse_hex_number)?;\n        var_offset = Cow::Owned(arg_split.swap_remove(0));\n    }\n\n    let offset = try_parsers!(&var_offset, parse_hex_number, parse_number)?;\n\n    Ok(ValueArg {\n        addr:      ValueAddr {\n            var_name,\n            var_id,\n            offset,\n            val_size,\n        },\n        operation: op_type,\n    })\n}\n\n#[allow(dead_code)]\npub fn test_functions() {\n    println!(\"Testing parse_hex_number\");\n    println!(\n        r#\"parse_hex_number(\"0x1\"), should be Ok({}), result is {:?}\"#,\n        0x1,\n        parse_hex_number(&CString16::try_from(\"0x1\").unwrap())\n    );\n    println!(\n        r#\"parse_hex_number(\"0x01\"), should be Ok({}), result is {:?}\"#,\n        0x1,\n        parse_hex_number(&CString16::try_from(\"0x01\").unwrap())\n    );\n    println!(\n        r#\"parse_hex_number(\"0X12e\"), should be Ok({}), result is {:?}\"#,\n        0x12E,\n        parse_hex_number(&CString16::try_from(\"0X12e\").unwrap())\n    );\n    println!(\n        r#\"parse_hex_number(\"0x12eFAb\"), should be Ok({}), result is {:?}\"#,\n        0x12EFAB,\n        parse_hex_number(&CString16::try_from(\"0x12eFAb\").unwrap())\n    );\n    println!(\n        r#\"parse_hex_number(\"0xDEADBEEFDEADBEEF01\"), should be Err({}), result is {:?}\"#,\n        ParseError::NumberTooLarge(\"0xDEADBEEFDEADBEEF01\".to_owned()),\n        parse_hex_number(&CString16::try_from(\"0xDEADBEEFDEADBEEF01\").unwrap())\n    );\n    println!(\n        r#\"parse_hex_number(\"0x12eFAs\"), should be Err({:?}), result is {:?}\"#,\n        ParseError::InvalidValue(\"0x12eFAs\".to_owned()),\n        parse_hex_number(&CString16::try_from(\"0x12eFAs\").unwrap())\n    );\n    println!(\n        r#\"parse_hex_number(\"abc\"), should be Err({:?}), result is {:?}\"#,\n        ParseError::InvalidValue(\"abc\".to_owned()),\n        parse_hex_number(&CString16::try_from(\"abc\").unwrap())\n    );\n\n    println!(\"Testing parse_named_arg\");\n    println!(\n        r#\"parse_named_arg(\"-h\", None), should be Ok({:?}), result is {:?}\"#,\n        NamedArg::Help,\n        parse_named_arg(&CString16::try_from(\"-h\").unwrap())\n    );\n    println!(\n        r#\"parse_named_arg(\"-r\", None), should be Ok({:?}), result is {:?}\"#,\n        NamedArg::Reboot(RebootMode::Always),\n        parse_named_arg(&CString16::try_from(\"-r\").unwrap())\n    );\n    println!(\n        r#\"parse_named_arg(\"--reboot\", None), should be Ok({:?}), result is {:?}\"#,\n        NamedArg::Reboot(RebootMode::Always),\n        parse_named_arg(&CString16::try_from(\"--reboot\").unwrap())\n    );\n    println!(\n        r#\"parse_named_arg(\"--write_on_demand\", None), should be Ok({:?}), result is {:?}\"#,\n        NamedArg::WriteOnDemand,\n        parse_named_arg(&CString16::try_from(\"--write_on_demand\").unwrap())\n    );\n    println!(\n        r#\"parse_named_arg(\"--help\", Some(\"abc\")), should be Ok({:?}), result is {:?}\"#,\n        NamedArg::Help,\n        parse_named_arg(&CString16::try_from(\"--help\").unwrap())\n    );\n    println!(\n        r#\"parse_named_arg(\"0x13\", Some(\"CpuSetup\")), should be Err({:?}), result is {:?}\"#,\n        ParseError::InvalidValue(\"0x13\".to_owned()),\n        parse_named_arg(&CString16::try_from(\"0x13\").unwrap())\n    );\n\n    println!(\"Testing parse_value_arg\");\n    println!(\n        r#\"parse_value_arg(\"CpuSetup(2):0x19E\"), should be Ok({:?}), result is {:?}\"#,\n        ValueArg {\n            addr:      ValueAddr {\n                var_name: CString16::try_from(\"CpuSetup\").unwrap(),\n                var_id:   Some(2),\n                offset:   0x19E,\n                val_size: 1,\n            },\n            operation: ValueOperation::Read,\n        },\n        parse_value_arg(&CString16::try_from(\"CpuSetup(2):0x19E\").unwrap())\n    );\n    println!(\n        r#\"parse_value_arg(\"CpuSetup:0x19E(3)=0x02\"), should be Ok({:?}), result is {:?}\"#,\n        ValueArg {\n            addr:      ValueAddr {\n                var_name: CString16::try_from(\"CpuSetup\").unwrap(),\n                var_id:   None,\n                offset:   0x19E,\n                val_size: 3,\n            },\n            operation: ValueOperation::Write(0x02),\n        },\n        parse_value_arg(&CString16::try_from(\"CpuSetup:0x19E(3)=0x02\").unwrap())\n    );\n\n    println!(\"Testing parse_args_from_str\");\n    println!(\n        r#\"parse_args_from_str(\".\\setup_var.efi\"), should be Ok({:?}), result is {:?}\"#,\n        Args {\n            help_msg: true,\n            ..Default::default()\n        },\n        parse_args_from_str(&CString16::try_from(\".\\\\setup_var.efi\").unwrap())\n    );\n    println!(\n        r#\"parse_args_from_str(\".\\setup_var.efi -h\"), should be Ok({:?}), result is {:?}\"#,\n        Args {\n            help_msg: true,\n            ..Default::default()\n        },\n        parse_args_from_str(&CString16::try_from(\".\\\\setup_var.efi -h\").unwrap())\n    );\n    println!(\n        r#\"parse_args_from_str(\".\\setup_var.efi VAR:0x12 -h\"), should be Ok({:?}), result is {:?}\"#,\n        Args {\n            help_msg: true,\n            value_args: vec![ValueArg {\n                addr:      ValueAddr {\n                    var_name: CString16::try_from(\"VAR\").unwrap(),\n                    var_id:   None,\n                    offset:   0x12,\n                    val_size: 1,\n                },\n                operation: ValueOperation::Read,\n            },],\n            ..Default::default()\n        },\n        parse_args_from_str(&CString16::try_from(\".\\\\setup_var.efi VAR:0x12 -h\").unwrap())\n    );\n    println!(\n        r#\"parse_args_from_str(\".\\setup_var.efi VAR:0x12=0x12 --write_on_demand -h\"), should be Ok({:?}), result is {:?}\"#,\n        Args {\n            help_msg: true,\n            write_on_demand: true,\n            value_args: vec![ValueArg {\n                addr:      ValueAddr {\n                    var_name: CString16::try_from(\"VAR\").unwrap(),\n                    var_id:   None,\n                    offset:   0x12,\n                    val_size: 1,\n                },\n                operation: ValueOperation::Write(0x12),\n            },],\n            ..Default::default()\n        },\n        parse_args_from_str(\n            &CString16::try_from(\".\\\\setup_var.efi VAR:0x12=0x12 --write_on_demand -h\").unwrap()\n        )\n    );\n    println!(\n        r#\"parse_args_from_str(\".\\setup_var.efi VAR:0x12=0x12e\"), should be Err({:?}), result is {:?}\"#,\n        ParseError::InvalidArgs(ArgsError::ValLargerThanSize(0x12e, 1)),\n        parse_args_from_str(&CString16::try_from(\".\\\\setup_var.efi VAR:0x12=0x12e\").unwrap())\n    );\n    println!(\n        r#\"parse_args_from_str(\".\\setup_var.efi VAR:0x01(3) VAR2(2):0x03=0x05\"), should be Ok({:?}), result is {:?}\"#,\n        Args {\n            value_args: vec![\n                ValueArg {\n                    addr:      ValueAddr {\n                        var_name: CString16::try_from(\"VAR\").unwrap(),\n                        var_id:   None,\n                        offset:   0x01,\n                        val_size: 3,\n                    },\n                    operation: ValueOperation::Read,\n                },\n                ValueArg {\n                    addr:      ValueAddr {\n                        var_name: CString16::try_from(\"VAR2\").unwrap(),\n                        var_id:   Some(2),\n                        offset:   0x03,\n                        val_size: 1,\n                    },\n                    operation: ValueOperation::Write(0x05),\n                }\n            ],\n            ..Default::default()\n        },\n        parse_args_from_str(\n            &CString16::try_from(\".\\\\setup_var.efi VAR:0x01(3) VAR2(2):0x03=0x05\").unwrap()\n        )\n    );\n\n    // Add new test for auto reboot mode\n    println!(\n        r#\"parse_args_from_str(\".\\setup_var.efi --reboot=auto VAR:0x12=0x12\"), should be Ok({:?}), result is {:?}\"#,\n        Args {\n            help_msg:        false,\n            write_on_demand: true, // auto reboot enables write_on_demand\n            reboot:          RebootMode::Auto,\n            value_args:      vec![ValueArg {\n                addr:      ValueAddr {\n                    var_name: CString16::try_from(\"VAR\").unwrap(),\n                    var_id:   None,\n                    offset:   0x12,\n                    val_size: 1,\n                },\n                operation: ValueOperation::Write(0x12),\n            },],\n        },\n        parse_args_from_str(\n            &CString16::try_from(\".\\\\setup_var.efi --reboot=auto VAR:0x12=0x12\").unwrap()\n        )\n    );\n}\n"
  },
  {
    "path": "src/input.rs",
    "content": "use alloc::{\n    borrow::{Cow, ToOwned},\n    string::ToString,\n    vec::Vec,\n};\n\nuse uefi::{\n    CStr16, CString16,\n    data_types::EqStrUntilNul,\n    proto::console::text::{Input, Key},\n    system::with_stdin,\n};\n\nuse crate::{\n    args::{Args, NamedArg, ParseError, RebootMode, ValueAddr, ValueArg, ValueOperation},\n    utils::CStr16Ext,\n};\n\nfn read_to_string(stdin: &mut Input) -> uefi::Result<CString16> {\n    let mut str = CString16::new();\n\n    while let Some(key) = stdin.read_key()? {\n        if let Key::Printable(char) = key {\n            str.push(char)\n        }\n    }\n\n    Ok(str)\n}\n\npub fn parse_input() -> Result<Args, ParseError> {\n    let content = with_stdin(read_to_string).map_err(|_| ParseError::LoadStdInError)?;\n    if content.is_empty() {\n        return Err(ParseError::NoInput);\n    }\n    let content = content\n        .strip_prefix('\\u{feff}'.try_into().unwrap())\n        .unwrap_or(&content);\n\n    let lines = content.split_to_cstring('\\n'.try_into().unwrap());\n    let lines = lines.into_iter().filter_map(|s| {\n        let s = s.trim();\n        if s.starts_with('#'.try_into().unwrap()) {\n            return None;\n        }\n\n        let res = s.strip_suffix('\\r'.try_into().unwrap()).unwrap_or(s);\n        if res.is_empty() { None } else { Some(res) }\n    });\n\n    let entries = lines\n        .map(|s| {\n            crate::args::try_parsers!(\n                &s,\n                parser_with_comment(parse_named_arg),\n                parser_with_comment(parse_address_def),\n                parser_with_comment(parse_value_arg_wrapped),\n                parser_with_comment(parse_address_ref),\n            )\n        })\n        .collect::<Result<Vec<_>, _>>()?;\n\n    let address_defs = entries\n        .iter()\n        .filter(|e| matches!(e, FileInputEntry::AddressDef { .. }))\n        .map(|e| e.as_address_def())\n        .collect::<Vec<_>>();\n    let mut val_args = entries\n        .iter()\n        .filter(|e| matches!(e, FileInputEntry::ValueArg(_)))\n        .map(|e| e.as_value_arg())\n        .cloned()\n        .collect::<Vec<_>>();\n\n    let address_refs = entries\n        .iter()\n        .filter(|e| matches!(e, FileInputEntry::AddressRef { .. }));\n    let mut address_ref_args = address_refs\n        .map(|e| match e {\n            FileInputEntry::AddressRef { name, operation } => {\n                let (_, addr) = address_defs\n                    .iter()\n                    .find(|(def_name, _)| name == *def_name)\n                    .ok_or_else(|| ParseError::InvalidValue(name.to_string()))?;\n                Ok(ValueArg {\n                    addr:      (*addr).clone(),\n                    operation: *operation,\n                })\n            }\n            _ => unreachable!(),\n        })\n        .collect::<Result<Vec<_>, ParseError>>()?;\n\n    val_args.append(&mut address_ref_args);\n\n    // Here we choose to let the last occurred setting override previous ones\n    let reboot_entry = entries\n        .iter()\n        .filter(|e| matches!(e, FileInputEntry::NamedArg(NamedArg::Reboot(_))))\n        .next_back();\n    let reboot = match reboot_entry {\n        Some(FileInputEntry::NamedArg(NamedArg::Reboot(mode))) => *mode,\n        _ => RebootMode::Never,\n    };\n\n    let write_on_demand = entries\n        .iter()\n        .any(|e| matches!(e, FileInputEntry::NamedArg(NamedArg::WriteOnDemand)));\n\n    Ok(Args {\n        value_args: val_args,\n        help_msg: false,\n        write_on_demand,\n        reboot,\n    })\n}\n\nenum FileInputEntry {\n    AddressDef {\n        name: CString16,\n        addr: ValueAddr,\n    },\n    ValueArg(ValueArg),\n    AddressRef {\n        name:      CString16,\n        operation: ValueOperation,\n    },\n    NamedArg(NamedArg),\n}\n\nimpl FileInputEntry {\n    fn as_address_def(&self) -> (&CString16, &ValueAddr) {\n        match self {\n            Self::AddressDef { name, addr } => (name, addr),\n            _ => panic!(\"Invalid variant used on into_address_def\"),\n        }\n    }\n\n    fn as_value_arg(&self) -> &ValueArg {\n        match self {\n            Self::ValueArg(val_arg) => val_arg,\n            _ => panic!(\"Invalid variant used on into_value_arg\"),\n        }\n    }\n}\n\nfn parser_with_comment<T>(parser: T) -> impl Fn(&CStr16) -> Result<FileInputEntry, ParseError>\nwhere\n    T: Fn(&CStr16) -> Result<FileInputEntry, ParseError>,\n{\n    move |arg| {\n        let arg = if let Some((arg, _comment)) = arg.split_only_first('#'.try_into().unwrap()) {\n            Cow::Owned(arg.trim())\n        } else {\n            Cow::Borrowed(arg)\n        };\n\n        parser(&arg)\n    }\n}\n\nfn parse_named_arg(arg: &CStr16) -> Result<FileInputEntry, ParseError> {\n    let named_arg = arg\n        .strip_prefix('@'.try_into().unwrap())\n        .ok_or_else(|| ParseError::InvalidValue(arg.to_string()))?;\n\n    if named_arg.eq_str_until_nul(\"reboot=auto\") {\n        Ok(FileInputEntry::NamedArg(NamedArg::Reboot(RebootMode::Auto)))\n    } else if named_arg.eq_str_until_nul(\"reboot\") {\n        Ok(FileInputEntry::NamedArg(NamedArg::Reboot(\n            RebootMode::Always,\n        )))\n    } else if named_arg.eq_str_until_nul(\"write_on_demand\") {\n        Ok(FileInputEntry::NamedArg(NamedArg::WriteOnDemand))\n    } else {\n        Err(ParseError::InvalidValue(arg.to_string()))\n    }\n}\n\nfn parse_address_def(arg: &CStr16) -> Result<FileInputEntry, ParseError> {\n    let (addr_name, addr_def) = arg\n        .split_only_first('='.try_into().unwrap())\n        .ok_or_else(|| ParseError::InvalidValue(arg.to_string()))?;\n\n    let addr_name = addr_name\n        .strip_suffix(':'.try_into().unwrap())\n        .ok_or_else(|| ParseError::InvalidValue(arg.to_string()))?;\n    let val_arg = crate::args::parse_value_arg(&addr_def)?;\n\n    if let ValueOperation::Write(_) = val_arg.operation {\n        Err(ParseError::AddrDefWrite(addr_def.to_string()))\n    } else {\n        Ok(FileInputEntry::AddressDef {\n            name: addr_name,\n            addr: val_arg.addr,\n        })\n    }\n}\n\nfn parse_value_arg_wrapped(arg: &CStr16) -> Result<FileInputEntry, ParseError> {\n    Ok(FileInputEntry::ValueArg(crate::args::parse_value_arg(arg)?))\n}\n\nfn parse_address_ref(arg: &CStr16) -> Result<FileInputEntry, ParseError> {\n    let (addr_name, _value_str) = arg\n        .split_only_first('='.try_into().unwrap())\n        .ok_or_else(|| ParseError::InvalidValue(arg.to_string()))?;\n\n    let addr_name = if addr_name.starts_with('$'.try_into().unwrap()) {\n        addr_name\n            .strip_prefix('$'.try_into().unwrap())\n            .ok_or_else(|| ParseError::InvalidValue(arg.to_string()))?\n    } else {\n        Err(ParseError::InvalidValue(addr_name.to_string()))?\n    };\n\n    let value_op = crate::args::parse_value_wrapped(arg)?;\n\n    Ok(FileInputEntry::AddressRef {\n        name:      addr_name.to_owned(),\n        operation: value_op,\n    })\n}\n"
  },
  {
    "path": "src/main.rs",
    "content": "#![no_main]\n#![no_std]\n\nextern crate alloc;\n\nmod args;\nmod input;\nmod utils;\n\nuse args::{HELP_MSG, ParseError, RebootMode, ValueArg, ValueOperation};\nuse uefi::{prelude::*, println, runtime::ResetType};\nuse utils::{UEFIValue, WriteStatus};\n\nuse crate::input::parse_input;\n\n#[entry]\nfn main() -> Status {\n    uefi::helpers::init().expect(\"Unexpected error while initializing UEFI services\");\n\n    let args = match args::parse_args() {\n        Ok(args) => {\n            if args.help_msg {\n                println!(\"{}\", HELP_MSG);\n                return Status::INVALID_PARAMETER;\n            }\n\n            args\n        }\n        Err(ParseError::NoArgs) => match parse_input() {\n            Ok(args) => args,\n            Err(ParseError::NoInput) => {\n                println!(\"{}\", HELP_MSG);\n                return Status::INVALID_PARAMETER;\n            }\n            Err(e) => {\n                println!(\"Error parsing input file:\\n{e}\");\n                return Status::INVALID_PARAMETER;\n            }\n        },\n        Err(e) => {\n            println!(\"Error parsing arguments:\\n{e}\");\n            return Status::INVALID_PARAMETER;\n        }\n    };\n\n    let mut arg_process_state = ArgProcessState::default();\n    for val_arg in args.value_args {\n        let (status, state) = process_arg(args.write_on_demand, &val_arg);\n\n        if status != Status::SUCCESS {\n            return status;\n        }\n        arg_process_state.bind(&state);\n    }\n\n    let reboot_required = matches!(arg_process_state.write_status, WriteStatus::Normal);\n    if args.reboot == RebootMode::Always || (args.reboot == RebootMode::Auto && reboot_required) {\n        runtime::reset(ResetType::WARM, Status::SUCCESS, None);\n    }\n\n    Status::SUCCESS\n}\n\nstruct ArgProcessState {\n    write_status: WriteStatus,\n}\n\nimpl ArgProcessState {\n    fn bind(&mut self, other: &Self) {\n        if let WriteStatus::Skipped = self.write_status {\n            if let WriteStatus::Normal = other.write_status {\n                self.write_status = WriteStatus::Normal;\n            }\n        }\n    }\n\n    fn nothing_written() -> Self {\n        Self {\n            write_status: WriteStatus::Skipped,\n        }\n    }\n}\n\nimpl Default for ArgProcessState {\n    fn default() -> Self {\n        Self::nothing_written()\n    }\n}\n\nfn process_arg(write_on_demand: bool, val_arg: &ValueArg) -> (Status, ArgProcessState) {\n    let var_name = &val_arg.addr.var_name;\n    let val_size = val_arg.addr.val_size;\n    let offset = val_arg.addr.offset;\n\n    match val_arg.operation {\n        ValueOperation::Read => {\n            match utils::read_val(var_name, val_arg.addr.var_id, offset, val_size) {\n                Ok(value) => {\n                    println!(\"{}\", val_arg.to_string_with_val(&value));\n                    (Status::SUCCESS, ArgProcessState::nothing_written())\n                }\n                Err(e) => {\n                    println!(\"Error reading variable:\\n{e}\");\n                    (Status::ABORTED, ArgProcessState::nothing_written())\n                }\n            }\n        }\n        ValueOperation::Write(value) => {\n            let value = UEFIValue::from_usize(value, val_size);\n\n            match utils::write_val(\n                var_name,\n                val_arg.addr.var_id,\n                offset,\n                &value,\n                val_size,\n                write_on_demand,\n            ) {\n                Err(e) => {\n                    println!(\"Error writing variable:\\n{e}\");\n                    (Status::ABORTED, ArgProcessState::nothing_written())\n                }\n                Ok(write_status) => {\n                    let skipped_msg = match write_status {\n                        WriteStatus::Skipped => \" # Writing skipped\",\n                        WriteStatus::Normal => \"\",\n                    };\n\n                    println!(\"{}{}\", val_arg.to_string_with_val(&value), skipped_msg);\n                    (Status::SUCCESS, ArgProcessState { write_status })\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/utils.rs",
    "content": "use alloc::{\n    borrow::ToOwned,\n    format,\n    string::{String, ToString},\n    vec,\n    vec::Vec,\n};\nuse core::fmt::{Display, Formatter};\n\nuse num_enum::TryFromPrimitive;\nuse strum::EnumMessage;\nuse uefi::{\n    CStr16, CString16, Char16, ResultExt, Status,\n    data_types::{FromSliceWithNulError, chars::NUL_16},\n    print, println,\n    runtime::{VariableAttributes, VariableKey, VariableVendor},\n};\n\n#[allow(non_camel_case_types, clippy::upper_case_acronyms)]\n#[derive(TryFromPrimitive, EnumMessage, strum::Display)]\n#[repr(u8)]\npub enum UEFIStatusErrorCode {\n    /// The image failed to load.\n    LOAD_ERROR           = 1,\n    /// A parameter was incorrect.\n    INVALID_PARAMETER    = 2,\n    /// The operation is not supported.\n    UNSUPPORTED          = 3,\n    /// The buffer was not the proper size for the request.\n    BAD_BUFFER_SIZE      = 4,\n    /// The buffer is not large enough to hold the requested data.\n    /// The required buffer size is returned in the appropriate parameter.\n    BUFFER_TOO_SMALL     = 5,\n    /// There is no data pending upon return.\n    NOT_READY            = 6,\n    /// The physical device reported an error while attempting the operation.\n    DEVICE_ERROR         = 7,\n    /// The device cannot be written to.\n    WRITE_PROTECTED      = 8,\n    /// A resource has run out.\n    OUT_OF_RESOURCES     = 9,\n    /// An inconstency was detected on the file system.\n    VOLUME_CORRUPTED     = 10,\n    /// There is no more space on the file system.\n    VOLUME_FULL          = 11,\n    /// The device does not contain any medium to perform the operation.\n    NO_MEDIA             = 12,\n    /// The medium in the device has changed since the last access.\n    MEDIA_CHANGED        = 13,\n    /// The item was not found.\n    NOT_FOUND            = 14,\n    /// Access was denied.\n    ACCESS_DENIED        = 15,\n    /// The server was not found or did not respond to the request.\n    NO_RESPONSE          = 16,\n    /// A mapping to a device does not exist.\n    NO_MAPPING           = 17,\n    /// The timeout time expired.\n    TIMEOUT              = 18,\n    /// The protocol has not been started.\n    NOT_STARTED          = 19,\n    /// The protocol has already been started.\n    ALREADY_STARTED      = 20,\n    /// The operation was aborted.\n    ABORTED              = 21,\n    /// An ICMP error occurred during the network operation.\n    ICMP_ERROR           = 22,\n    /// A TFTP error occurred during the network operation.\n    TFTP_ERROR           = 23,\n    /// A protocol error occurred during the network operation.\n    PROTOCOL_ERROR       = 24,\n    /// The function encountered an internal version that was\n    /// incompatible with a version requested by the caller.\n    INCOMPATIBLE_VERSION = 25,\n    /// The function was not performed due to a security violation.\n    SECURITY_VIOLATION   = 26,\n    /// A CRC error was detected.\n    CRC_ERROR            = 27,\n    /// Beginning or end of media was reached\n    END_OF_MEDIA         = 28,\n    /// The end of the file was reached.\n    END_OF_FILE          = 31,\n    /// The language specified was invalid.\n    INVALID_LANGUAGE     = 32,\n    /// The security status of the data is unknown or compromised and\n    /// the data must be updated or replaced to restore a valid security status.\n    COMPROMISED_DATA     = 33,\n    /// There is an address conflict address allocation\n    IP_ADDRESS_CONFLICT  = 34,\n    /// A HTTP error occurred during the network operation.\n    HTTP_ERROR           = 35,\n}\n\npub enum UEFIStatusError {\n    Success,\n    Error(UEFIStatusErrorCode),\n    UnknownError(usize),\n}\n\nimpl From<Status> for UEFIStatusError {\n    fn from(value: Status) -> Self {\n        if !value.is_error() {\n            Self::Success\n        } else {\n            match UEFIStatusErrorCode::try_from(value.0 as u8) {\n                Ok(error_code) => UEFIStatusError::Error(error_code),\n                Err(_) => UEFIStatusError::UnknownError(value.0),\n            }\n        }\n    }\n}\n\nimpl Display for UEFIStatusError {\n    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {\n        match self {\n            UEFIStatusError::Success => write!(f, \"Success\"),\n            UEFIStatusError::Error(error_code) => {\n                write!(\n                    f,\n                    \"{} ({})\",\n                    error_code,\n                    error_code.get_documentation().unwrap_or_default()\n                )\n            }\n            UEFIStatusError::UnknownError(code) => write!(f, \"Unknown error with code {}\", code),\n        }\n    }\n}\n\npub enum UEFIVarError {\n    NoCorrespondingVar,\n    MultipleVarNoId,\n    InvalidVarName(FromSliceWithNulError),\n    GetVariableSize(String, UEFIStatusError),\n    GetVariable(String, UEFIStatusError),\n    OffsetOverflow((usize, usize), usize), // ((offset, val_size), var_size)\n    SetVariable(String, UEFIStatusError),\n}\n\nimpl Display for UEFIVarError {\n    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {\n        match self {\n            Self::NoCorrespondingVar => {\n                write!(f, \"No variable with specified name found\")\n            }\n            Self::MultipleVarNoId => {\n                write!(\n                    f,\n                    \"Please re-run with variable id as shown in the above table\"\n                )\n            }\n            Self::InvalidVarName(e) => {\n                write!(f, \"Unexpected invalid UEFI variable name obtained: {e:?}\")\n            }\n            Self::GetVariableSize(s, st) => {\n                write!(f, \"Error while getting size of variable {s}: {st}\")\n            }\n            Self::GetVariable(s, st) => {\n                write!(f, \"Error while getting content of variable {s}: {st}\",)\n            }\n            Self::OffsetOverflow((offset, val_size), size) => {\n                write!(\n                    f,\n                    \"Specified offset 0x{offset:X} and value size 0x{val_size:X} exceeds variable \\\n                     size 0x{size:X}\"\n                )\n            }\n            Self::SetVariable(s, st) => {\n                write!(f, \"Error while setting content of variable {s}: {st}\")\n            }\n        }\n    }\n}\n\nimpl From<FromSliceWithNulError> for UEFIVarError {\n    fn from(value: FromSliceWithNulError) -> Self {\n        Self::InvalidVarName(value)\n    }\n}\n\nstruct UEFIVariable {\n    name:       CString16,\n    vendor:     VariableVendor,\n    attributes: VariableAttributes,\n    content:    Vec<u8>,\n}\n\npub struct UEFIValue(pub Vec<u8>);\n\nimpl UEFIValue {\n    pub fn from_usize(value: usize, val_size: usize) -> Self {\n        let value = value & ((1 << (val_size * 8)) - 1);\n        Self(value.to_le_bytes()[0..val_size].to_vec())\n    }\n\n    pub fn to_string_with_size(&self, val_size: usize) -> String {\n        let mut bytes = [0; 8];\n        bytes[0..self.0.len()].copy_from_slice(&self.0);\n\n        format!(\n            \"0x{:0width$X}\",\n            usize::from_ne_bytes(bytes),\n            width = val_size * 2\n        )\n    }\n}\n\nimpl Display for UEFIValue {\n    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {\n        let mut bytes = [0; 8];\n        bytes[0..self.0.len()].copy_from_slice(&self.0);\n\n        write!(f, \"0x{:X}\", usize::from_ne_bytes(bytes))\n    }\n}\n\npub fn read_val(\n    var_name: &CStr16,\n    var_id: Option<usize>,\n    offset: usize,\n    val_size: usize,\n) -> Result<UEFIValue, UEFIVarError> {\n    let var = read_var(var_name, var_id)?;\n    if offset + val_size > var.content.len() {\n        return Err(UEFIVarError::OffsetOverflow(\n            (offset, val_size),\n            var.content.len(),\n        ));\n    }\n\n    let slice = &var.content[offset..offset + val_size];\n    Ok(UEFIValue(slice.to_vec()))\n}\n\npub enum WriteStatus {\n    Normal,\n    Skipped,\n}\n\npub fn write_val(\n    var_name: &CStr16,\n    var_id: Option<usize>,\n    offset: usize,\n    value: &UEFIValue,\n    val_size: usize,\n    write_on_demand: bool,\n) -> Result<WriteStatus, UEFIVarError> {\n    let mut var = read_var(var_name, var_id)?;\n    if offset + val_size > var.content.len() {\n        return Err(UEFIVarError::OffsetOverflow(\n            (offset, val_size),\n            var.content.len(),\n        ));\n    }\n\n    let slice = &mut var.content[offset..offset + val_size];\n\n    if write_on_demand && slice == value.0 {\n        Ok(WriteStatus::Skipped)\n    } else {\n        slice.copy_from_slice(&value.0);\n\n        uefi::runtime::set_variable(&var.name, &var.vendor, var.attributes, &var.content)\n            .map_err(|e| UEFIVarError::SetVariable(var.name.to_string(), e.status().into()))?;\n\n        Ok(WriteStatus::Normal)\n    }\n}\n\nfn read_var(var_name: &CStr16, var_id: Option<usize>) -> Result<UEFIVariable, UEFIVarError> {\n    let keys = uefi::runtime::variable_keys();\n    let mut keys = keys\n        .into_iter()\n        .filter_map(|k| k.ok())\n        .filter(|k| k.name == var_name)\n        .collect::<Vec<_>>();\n    keys.sort_by_key(|k| k.vendor.0);\n\n    if keys.is_empty() {\n        return Err(UEFIVarError::NoCorrespondingVar);\n    }\n\n    if keys.len() > 1 && var_id.is_none() {\n        print_keys(keys)?;\n        return Err(UEFIVarError::MultipleVarNoId);\n    }\n\n    let var_key = if keys.len() == 1 {\n        &keys[0]\n    } else {\n        &keys[var_id.unwrap()] // if keys.len() == 1, then branch above; if keys.len() > 1 && var_id is None, then above if\n    };\n    let var_name = &var_key.name;\n\n    let size = get_variable_size(var_name, &var_key.vendor)\n        .map_err(|e| UEFIVarError::GetVariableSize(var_name.to_string(), e.status().into()))?;\n    let mut buf = vec![0; size];\n    let (_, var_attr) = uefi::runtime::get_variable(var_name, &var_key.vendor, &mut buf)\n        .map_err(|e| UEFIVarError::GetVariable(var_name.to_string(), e.status().into()))?;\n\n    Ok(UEFIVariable {\n        name:       var_name.to_owned(),\n        vendor:     var_key.vendor,\n        attributes: var_attr,\n        content:    buf,\n    })\n}\n\nfn print_keys(keys: Vec<VariableKey>) -> Result<(), UEFIVarError> {\n    println!(\"Multiple variables with same name detected:\");\n    println!(\"ID\\tVarName\\t\\t\\t\\tSize\\t\");\n    println!();\n\n    for (i, key) in keys.into_iter().enumerate() {\n        let id = i;\n        let name = &key.name;\n        let size = get_variable_size(name, &key.vendor)\n            .map_err(|e| UEFIVarError::GetVariableSize(name.to_string(), e.status().into()))?;\n        print!(\"0x{:X}\\t\", id);\n        print!(\"{name}\");\n        match (name.num_bytes() / 2 - 1) / 8 {\n            0 => {\n                print!(\"\\t\\t\\t\\t\")\n            }\n            1 => {\n                print!(\"\\t\\t\\t\")\n            }\n            2 => {\n                print!(\"\\t\\t\")\n            }\n            _ => {\n                print!(\"\\t\")\n            }\n        }\n        println!(\"0x{:X}\\t\", size)\n    }\n\n    Ok(())\n}\n\nfn get_variable_size(name: &CStr16, vendor: &VariableVendor) -> uefi::Result<usize> {\n    let res = uefi::runtime::get_variable(name, vendor, &mut []);\n    if res.status() == Status::BUFFER_TOO_SMALL {\n        let err = res.unwrap_err();\n        Ok(err.data().unwrap_or_default())\n    } else {\n        Err(res.discard_errdata().unwrap_err())\n    }\n}\n\npub trait CStr16Ext {\n    fn contains(&self, char: Char16) -> bool;\n    fn strip_prefix(&self, prefix: Char16) -> Option<&CStr16>;\n    fn strip_suffix(&self, suffix: Char16) -> Option<CString16>;\n    /// The CStr16 requires a NUL terminator, so we can only collect them back\n    /// into CString16\n    fn split_to_cstring(&self, split: Char16) -> Vec<CString16>;\n    fn split_only_first(&self, split: Char16) -> Option<(CString16, CString16)>;\n    fn trim(&self) -> CString16;\n    fn starts_with(&self, char: Char16) -> bool;\n}\n\nimpl CStr16Ext for CStr16 {\n    fn contains(&self, char: Char16) -> bool {\n        self.iter().any(|&c| c == char)\n    }\n\n    fn strip_prefix(&self, prefix: Char16) -> Option<&CStr16> {\n        if *self.iter().next()? == prefix {\n            let str_ref = unsafe {\n                CStr16::from_u16_with_nul_unchecked(\n                    &*(&self.as_slice_with_nul()[1..] as *const [Char16] as *const [u16]),\n                )\n            };\n            Some(str_ref)\n        } else {\n            None\n        }\n    }\n\n    fn strip_suffix(&self, suffix: Char16) -> Option<CString16> {\n        let str = self.to_u16_slice();\n        if *str.last()? == u16::from(suffix) {\n            let mut buf = self\n                .as_slice()\n                .iter()\n                .map(|&c| u16::from(c))\n                .collect::<Vec<_>>();\n            *buf.last_mut()? = 0;\n            Some(CString16::try_from(buf).unwrap())\n        } else {\n            None\n        }\n    }\n\n    fn split_to_cstring(&self, split: Char16) -> Vec<CString16> {\n        let mut split_strings = Vec::new();\n        let mut current_string = Vec::new();\n\n        for c in self.iter() {\n            if *c != split {\n                current_string.push(u16::from(*c))\n            } else {\n                current_string.push(0u16);\n                split_strings.push(\n                    current_string\n                        .try_into()\n                        .expect(\"Invalid bytes in arguments\"),\n                );\n                current_string = Vec::new()\n            }\n        }\n\n        if !current_string.is_empty() {\n            current_string.push(0u16);\n            split_strings.push(\n                current_string\n                    .try_into()\n                    .expect(\"Invalid bytes in arguments\"),\n            )\n        }\n\n        split_strings\n    }\n\n    fn split_only_first(&self, split: Char16) -> Option<(CString16, CString16)> {\n        let index = self.iter().position(|&c| c == split)?;\n\n        // We have to copy twice and check validity again???\n        let mut first_str = self.as_slice()[..index].to_vec();\n        first_str.push(NUL_16);\n\n        let mut second_str = self.as_slice()[index + 1..].to_vec();\n        second_str.push(NUL_16);\n\n        let first_str = char16_vec_to_cstring16(first_str);\n        let second_str = char16_vec_to_cstring16(second_str);\n\n        Some((first_str, second_str))\n    }\n\n    fn trim(&self) -> CString16 {\n        let is_space =\n            |&c| c == Char16::try_from(' ').unwrap() || c == Char16::try_from('\\t').unwrap();\n\n        let mut start = 0;\n        for (i, c) in self.iter().enumerate() {\n            if !is_space(c) {\n                start = i;\n                break;\n            }\n        }\n\n        let mut end = self.num_chars() - 1;\n        for (i, c) in self.as_slice().iter().rev().enumerate() {\n            if !is_space(c) {\n                end -= i;\n                break;\n            }\n        }\n\n        let mut str = self.as_slice()[start..=end].to_vec();\n        str.push(NUL_16);\n\n        char16_vec_to_cstring16(str)\n    }\n\n    fn starts_with(&self, char: Char16) -> bool {\n        *self.iter().next().unwrap_or(&NUL_16) == char\n    }\n}\n\n/// We have no way to directly construct CString16, and as it does NOT use\n/// repr(transparent). We even cannot construct it with unsafe operations. A\n/// copy and char validity check is required in this function.\nfn char16_vec_to_cstring16(s: Vec<Char16>) -> CString16 {\n    CString16::try_from(s.into_iter().map(u16::from).collect::<Vec<_>>()).unwrap()\n}\n"
  }
]