kern/xen: Add Xen command line parsing
v3 cover kern/xen: Add Xen command line parsing
The purpose of this patch is to allow the Xen hypervisor to pass extra data to GRUB in the form of a kernel command line, allowing the host to customize the boot process of the guest. The command line from Xen is parsed, and any variables within that start with the string xen_grub_env_ are exposed as environment variables. The grub.cfg script can then use those environment variables as it sees fit.
The main reason for doing this is to allow implementing boot modes in Qubes OS while also using in-VM kernels. For more context on Qubes boot modes, see [1]. In order for this to work with in-VM kernels, it is necessary for dom0 to pass kernel parameters to the guest without modifying the guest's grub.cfg manually. This patch allows this to be done, by allowing dom0 to pass kernel parameters to GRUB, which then provides them to grub.cfg as an environment variable. The grub.cfg script within the VM can then append those variables to the kernel command line.
The patch's code is unchanged from the last time I sent it [2], I've simply rebased it on top of the latest commit at the time of this writing (0e36779). I have not run it through the full test suite used previously, but I have ensured that both PV and PVH bootloaders build successfully and can boot an Arch Linux virtual machine on an Arch Linux host.
Changes from the version 2 of the patch:
* Added documentation for the future to the GRUB manual.
* Fixed error checking when allocating memory.
* Enhanced coding style, code efficiency, and comments based on Daniel Kiper's previous review and my own re-review.
* Added an explicit null termination check on the Xen-provided kernel command line before parsing.
* Fixed some memory management issues that could result in unnecessary memory consumption (one memory leak and a couple of places where an extra byte was allocated that didn't need to be).
[1] https://github.com/QubesOS/qubes-linux-pvgrub2/pull/16
[2] https://lists.gnu.org/archive/html/grub-devel/2025-06/msg00011.html
Aaron Rainbolt (1):
kern/xen: Add Xen command line parsing
docs/grub.texi | 50 +++++ grub-core/Makefile.core.def | 2 + grub-core/kern/i386/xen/pvh.c | 14 ++ grub-core/kern/main.c | 12 ++ grub-core/kern/xen/cmdline.c | 343 ++++++++++++++++++++++++++++++++++ include/grub/xen.h | 2 + 6 files changed, 423 insertions(+) create mode 100644 grub-core/kern/xen/cmdline.c
Signature · 1 line
2.50.1
PATCH RESEND v3 1/1 kern/xen: Add Xen command line parsing
Xen traditionally allows customizing guest behavior by passing arguments to the VM kernel via the kernel command line. This is no longer possible when using GRUB with Xen, as the kernel command line is decided by the GRUB configuration file within the guest, not data passed to the guest by Xen.
To work around this limitation, enable GRUB to parse a command line passed to it by Xen, and expose data from the command line to the GRUB configuration as environment variables. These variables can be used in the GRUB configuration for any desired purpose, such as extending the kernel command line passed to the guest. The command line format is inspired by the Linux kernel's command line format.
To reduce the risk of misuse, abuse, or accidents in production, the command line will only be parsed if it consists entirely of 7-bit ASCII characters, only alphabetical characters and underscores are permitted in variable names, and all variable names must start with the string "xen_grub_env_". This also allows room for expanding the command line arguments accepted by GRUB in the future, should other arguments end up becoming desirable in the future.
--- docs/grub.texi | 50 +++++ grub-core/Makefile.core.def | 2 + grub-core/kern/i386/xen/pvh.c | 14 ++ grub-core/kern/main.c | 12 ++ grub-core/kern/xen/cmdline.c | 343 ++++++++++++++++++++++++++++++++++ include/grub/xen.h | 2 + 6 files changed, 423 insertions(+) create mode 100644 grub-core/kern/xen/cmdline.c
docs/grub.texi +50 -0
@@ -3271,6 +3271,7 @@ GRUB. Others may be used freely in GRUB configuration files. @menu * Special environment variables:: * Environment block:: +* Passing environment variables through Xen:: @end menu
@@ -3871,6 +3872,55 @@ using BIOS or EFI functions (no ATA, USB or IEEE1275). @command{grub-mkconfig} uses this facility to implement @samp{GRUB_SAVEDEFAULT} (@pxref{Simple configuration}). +@node Passing environment variables through Xen +@section Passing environment variables through Xen + +If you are using a GRUB image as the kernel for a PV or PVH Xen virtual +machine, you can pass environment variables from Xen's dom0 to the VM through +the Xen-provided kernel command line. When combined with a properly configured +guest, this can be used to customize the guest's behavior on bootup via the +VM's Xen configuration file. + +GRUB will parse the kernel command line passed to it by Xen during bootup. +The command line will be split into space-delimited words. Single and +double quotes may be used to quote words or portions of words that contain +spaces. Arbitrary characters may be backslash-escaped to make them a literal +component of a word rather than being parsed as quotes or word separators. The +command line must consist entirely of printable 7-bit ASCII characters and +spaces. If a non-printing ASCII character is found anywhere in the command +line, the entire command line will be ignored by GRUB. + +Each word should be a variable assignment in the format ``variable'' or +``variable=value''. Variable names must contain only the characters A-Z, a-z, +and underscore (``_''). Variable names must begin with the string +``xen_grub_env_''. Variable values can contain arbitrary printable 7-bit +ASCII characters and space. If any variable contains an illegal name, that +variable will be ignored. + +If a variable name and value are both specified, the variable will be set to +the specified value. If only a variable name is specified, the variable's +value will be set to ``1''. + +The following is a simple example of how to use this functionality to append +arbitrary variables to a guest's kernel command line: + +@example +# In the Xen configuration file for the guest +name = "linux_vm" +type = "pvh" +kernel = "/path/to/grub-i386-xen_pvh.bin" +extra = "xen_grub_env_kernelappend='loglevel=3'" +memory = 1024 +disk = [ "file:/srv/vms/linux_vm.img,sda,w" ] + +# In the guest's GRUB configuration file +menuentry "Linux VM with dom0-specified kernel parameters" @{ + search --set=root --label linux_vm --hint hd0,msdos1 + linux /boot/vmlinuz root=LABEL=linux_vm $@{xen_grub_env_kernelappend@} + initrd /boot/initrd.img +@} +@end example + @node Modules @chapter Modules
grub-core/Makefile.core.def +2 -0
@@ -248,6 +248,7 @@ kernel = { xen = term/xen/console.c; xen = disk/xen/xendisk.c; xen = commands/boot.c; + xen = kern/xen/cmdline.c; i386_xen_pvh = commands/boot.c; i386_xen_pvh = disk/xen/xendisk.c;
@@ -255,6 +256,7 @@ kernel = { i386_xen_pvh = kern/i386/xen/tsc.c; i386_xen_pvh = kern/i386/xen/pvh.c; i386_xen_pvh = kern/xen/init.c; + i386_xen_pvh = kern/xen/cmdline.c; i386_xen_pvh = term/xen/console.c; ia64_efi = kern/ia64/efi/startup.S;
grub-core/kern/i386/xen/pvh.c +14 -0
@@ -321,6 +321,8 @@ voidgrub_xen_setup_pvh (void) {grub_addr_t par; +const char *xen_cmdline; +int i;grub_xen_cpuid_base ();grub_xen_setup_hypercall_page ();
@@ -352,6 +354,18 @@ grub_xen_setup_pvh (void)grub_xen_mm_init_regions (); grub_rsdp_addr = pvh_start_info->rsdp_paddr; + + xen_cmdline = (const char *) pvh_start_info->cmdline_paddr; +for (i =0 ; i <MAX_GUEST_CMDLINE ; i++) + { +if (xen_cmdline[i] =='\0' ) + { +grub_strncpy ((char *) grub_xen_start_page_addr->cmd_line, + (char *) pvh_start_info->cmdline_paddr, +MAX_GUEST_CMDLINE ); +break ; + } + } } grub_err_t
grub-core/kern/main.c +12 -0
@@ -37,6 +37,10 @@#include <grub/machine/memory.h> #endif +#if defined (GRUB_MACHINE_XEN ) || defined (GRUB_MACHINE_XEN_PVH ) +#include <grub/xen.h> +#endif +static bool cli_disabled = false;static bool cli_need_auth = false;
@@ -351,6 +355,14 @@ grub_main (void)grub_env_export ("root" );grub_env_export ("prefix" ); +/* +* Parse command line parameters from Xen and export them as environment +* variables +*/ +#if defined (GRUB_MACHINE_XEN ) || defined (GRUB_MACHINE_XEN_PVH ) +grub_parse_xen_cmdline (); +#endif +/* Reclaim space used for modules. */ reclaim_module_space ();
grub-core/kern/xen/cmdline.c new file +343 -0
343 lines not on this page · raw message
include/grub/xen.h +2 -0
@@ -89,6 +89,8 @@ void grub_console_init (void);void grub_xendisk_fini (void );void grub_xendisk_init (void ); +void grub_parse_xen_cmdline (void ); +#ifdef __x86_64__typedef grub_uint64_t grub_xen_mfn_t ;#else
Signature · 1 line
2.50.1
Quoted 76 lines · Aaron Rainbolt
Xen traditionally allows customizing guest behavior by passing arguments to the VM kernel via the kernel command line. This is no longer possible when using GRUB with Xen, as the kernel command line is decided by the GRUB configuration file within the guest, not data passed to the guest by Xen.
To work around this limitation, enable GRUB to parse a command line passed to it by Xen, and expose data from the command line to the GRUB configuration as environment variables. These variables can be used in the GRUB configuration for any desired purpose, such as extending the kernel command line passed to the guest. The command line format is inspired by the Linux kernel's command line format.
To reduce the risk of misuse, abuse, or accidents in production, the command line will only be parsed if it consists entirely of 7-bit ASCII characters, only alphabetical characters and underscores are permitted in variable names, and all variable names must start with the string "
xen_grub_env_". This also allows room for expanding the command line arguments accepted by GRUB in the future, should other arguments end up becoming desirable in the future.Signed-off-by Aaron Rainbolt <[email protected]>--- docs/grub.texi | 50 +++++ grub-core/Makefile.core.def | 2 + grub-core/kern/i386/xen/pvh.c | 14 ++ grub-core/kern/main.c | 12 ++ grub-core/kern/xen/cmdline.c | 343 ++++++++++++++++++++++++++++++++++ include/grub/xen.h | 2 + 6 files changed, 423 insertions(+) create mode 100644 grub-core/kern/xen/cmdline.cdocs/grub.texi +29
-0@@ -3271,6 +3271,7 @@ GRUB. Others may be used freely in GRUB configuration files. @menu * Special environment variables:: * Environment block:: +* Passing environment variables through Xen:: @end menu@@ -3871,6 +3872,55 @@ using BIOS or EFI functions (no ATA, USB or IEEE1275). @command{grub-mkconfig} uses this facility to implement @samp{GRUB_SAVEDEFAULT} (@pxref{Simple configuration}). +@node Passing environment variables through Xen +@section Passing environment variables through Xen + +If you are using a GRUB image as the kernel for a PV or PVH Xen virtual +machine, you can pass environment variables from Xen's dom0 to the VM through +the Xen-provided kernel command line. When combined with a properly configured +guest, this can be used to customize the guest's behavior on bootup via the +VM's Xen configuration file. + +GRUB will parse the kernel command line passed to it by Xen during bootup. +The command line will be split into space-delimited words. Single and +double quotes may be used to quote words or portions of words that contain +spaces. Arbitrary characters may be backslash-escaped to make them a literal +component of a word rather than being parsed as quotes or word separators. The +command line must consist entirely of printable 7-bit ASCII characters and +spaces. If a non-printing ASCII character is found anywhere in the command +line, the entire command line will be ignored by GRUB. + +Each word should be a variable assignment in the format ``variable'' or +``variable=value''. Variable names must contain only the characters A-Z, a-z, +and underscore (``_''). Variable names must begin with the string +``xen_grub_env_''. Variable values can contain arbitrary printable 7-bit +ASCII characters and space. If any variable contains an illegal name, that +variable will be ignored. + +If a variable name and value are both specified, the variable will be set to +the specified value. If only a variable name is specified, the variable's +value will be set to ``1''.
docs/grub.texi using BIOS or EFI functions (no ATA, USB or IEEE1275). · line 3912
Quoted 10 lines
docs/grub.texi +10
-0+ +The following is a simple example of how to use this functionality to append +arbitrary variables to a guest's kernel command line: + +@example +# In the Xen configuration file for the guest +name = "linux_vm" +type = "pvh" +kernel = "/path/to/grub-i386-xen_pvh.bin" +extra = "xen_grub_env_kernelappend='loglevel=3'"
s/kernelappend/kernel_append/
or maybe even
s/kernelappend/linux_append/
to make it clear it is appended to the "linux" command line...
docs/grub.texi using BIOS or EFI functions (no ATA, USB or IEEE1275). · line 3919
Quoted 7 lines
docs/grub.texi +7
-0+memory = 1024 +disk = [ "file:/srv/vms/linux_vm.img,sda,w" ] + +# In the guest's GRUB configuration file +menuentry "Linux VM with dom0-specified kernel parameters" @{ + search --set=root --label linux_vm --hint hd0,msdos1 + linux /boot/vmlinuz root=LABEL=linux_vm $@{xen_grub_env_kernelappend@}
Ditto...
Quoted 41 lines
docs/grub.texi +4
-0+ initrd /boot/initrd.img +@} +@end example + @node Modules @chapter Modulesgrub-core/Makefile.core.def +2
-0@@ -248,6 +248,7 @@ kernel = { xen = term/xen/console.c; xen = disk/xen/xendisk.c; xen = commands/boot.c; + xen = kern/xen/cmdline.c; i386_xen_pvh = commands/boot.c; i386_xen_pvh = disk/xen/xendisk.c;@@ -255,6 +256,7 @@ kernel = { i386_xen_pvh = kern/i386/xen/tsc.c; i386_xen_pvh = kern/i386/xen/pvh.c; i386_xen_pvh = kern/xen/init.c; + i386_xen_pvh = kern/xen/cmdline.c; i386_xen_pvh = term/xen/console.c; ia64_efi = kern/ia64/efi/startup.S;grub-core/kern/i386/xen/pvh.c +2
-0@@ -321,6 +321,8 @@ voidgrub_xen_setup_pvh (void) {grub_addr_t par; +const char *xen_cmdline; +int i;grub_xen_cpuid_base ();grub_xen_setup_hypercall_page ();
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 359
Quoted 6 lines
grub-core/kern/i386/xen/pvh.c +3
-0@@ -352,6 +354,18 @@ grub_xen_setup_pvh (void)grub_xen_mm_init_regions (); grub_rsdp_addr = pvh_start_info->rsdp_paddr; + + xen_cmdline = (const char *) pvh_start_info->cmdline_paddr; +for (i =0 ; i <MAX_GUEST_CMDLINE ; i++)
Oh, MAX_GUEST_CMDLINE is a too generic. May I ask you to rename it to GRUB_XEN_MAX_GUEST_CMDLINE? This should be done in separate patch preceding this one.
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 361
Quoted 2 lines
grub-core/kern/i386/xen/pvh.c +2
-0+ { +if (xen_cmdline[i] =='\0' )
I cannot see much sense in this check. Please look below...
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 364
Quoted 3 lines
grub-core/kern/i386/xen/pvh.c +3
-0+ { + grub_strncpy ((char *) grub_xen_start_page_addr->cmd_line, + (char *) pvh_start_info->cmdline_paddr,
s/char */const char */
Is it always guaranteed that pvh_start_info->cmdline_paddr have MAX_GUEST_CMDLINE size? If yes then...
grub_memset ((void *) pvh_start_info->cmdline_paddr, 0, MAX_GUEST_CMDLINE); grub_strncpy ((char *) grub_xen_start_page_addr->cmd_line,
(const char *) pvh_start_info->cmdline_paddr, MAX_GUEST_CMDLINE - 1);
... and you are done...
Quoted 23 lines
grub-core/kern/i386/xen/pvh.c +4
-0+ MAX_GUEST_CMDLINE); +break ; + } + } } grub_err_tgrub-core/kern/main.c +4
-0@@ -37,6 +37,10 @@#include <grub/machine/memory.h> #endif +#if defined (GRUB_MACHINE_XEN ) || defined (GRUB_MACHINE_XEN_PVH ) +#include <grub/xen.h> +#endif +static bool cli_disabled = false;static bool cli_need_auth = false;
grub-core/kern/main.c grub_main (void) · line 363
Quoted 9 lines
grub-core/kern/main.c +6
-0@@ -351,6 +355,14 @@ grub_main (void)grub_env_export ("root" );grub_env_export ("prefix" ); +/* +* Parse command line parameters from Xen and export them as environment +* variables +*/ +#if defined (GRUB_MACHINE_XEN ) || defined (GRUB_MACHINE_XEN_PVH ) +grub_parse_xen_cmdline ();
Please move this call to the grub-core/kern/xen/init.c:grub_machine_init().
Quoted 30 lines
grub-core/kern/main.c +2
-0+#endif +/* Reclaim space used for modules. */ reclaim_module_space ();grub-core/kern/xen/cmdline.c new file +19
-0@@ -0,0 +1,343 @@ +/* +* GRUB -- GRand Unified Bootloader +* Copyright (C) 2025 Free Software Foundation, Inc. +* +* GRUB is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* GRUB is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with GRUB. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <grub/env.h>
grub-core/kern/xen/cmdline.c line 29
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+#include <grub/misc.h> +#include <grub/mm.h> +#include <grub/xen.h> + +enum parse_flags +{ +PARSER_HIT_BACKSLASH =0x1 , +PARSER_IN_SINGLE_QUOTES =0x2 , +PARSER_IN_DOUBLE_QUOTES =0x4 , +};
typedef parse_flags parse_flags_t;
... and use parse_flags_t instead below...
And probably this should be a local variable...
grub-core/kern/xen/cmdline.c line 31
Quoted 2 lines
grub-core/kern/xen/cmdline.c new file +2
-0+ +#define PARSER_BASE_WORD_LEN 16
This constant begs for a few words of comment...
grub-core/kern/xen/cmdline.c line 38
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +6
-0+static grub_size_t word_list_len; +static char **word_list; +static grub_size_t current_word_len; +static grub_size_t current_word_pos; +static char *current_word; +static char current_char;
I have a feeling that most if not all of this variables should be local in a given function...
grub-core/kern/xen/cmdline.c line 45
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +6
-0+static bool +append_char_to_word (bool allow_null) +{ +/* +* Fail if the current char is outside of the range 0x20 to 0x7E. If +* allow_null is true, make an exception for 0x00. This is a safeguard
Could you elaborate here when allow_null == true is useful?
grub-core/kern/xen/cmdline.c line 48
Quoted 3 lines
grub-core/kern/xen/cmdline.c new file +3
-0+* against likely-invalid data. +*/ + if ( (!(current_char >= 0x20) || !(current_char <= 0x7E) )
grub_isprint()?
grub-core/kern/xen/cmdline.c line 49
Quoted 1 line
grub-core/kern/xen/cmdline.c new file +1
-0+ && (current_char != '\0' || allow_null == false))
I would drop redundant spaces between "(" and ")" and move "&&" to the end of first line of "if".
grub-core/kern/xen/cmdline.c line 54
Quoted 5 lines
grub-core/kern/xen/cmdline.c new file +5
-0+return false; + +if (current_word_pos == current_word_len) + { + current_word_len *=2 ;
You can do this in the argument of the function below...
grub-core/kern/xen/cmdline.c line 64
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+ current_word =grub_realloc (current_word, current_word_len); +if (current_word ==NULL ) + { + current_word_len /=2 ; +return false; + } + } + + current_word[current_word_pos] = current_char; + current_word_pos++;
Again, you can do this operation in the "[]" above...
grub-core/kern/xen/cmdline.c line 72
Quoted 8 lines
grub-core/kern/xen/cmdline.c new file +8
-0+return true; +} + +static bool +append_word_to_list (void ) +{ +/* No-op on empty words. */ +if (current_word_pos ==0 )
This should be probably an argument for the function...
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +6
-0+return true; + + current_char ='\0' ; +if (append_char_to_word (true) == false) + { + grub_error (GRUB_ERR_BUG,
grub-core/kern/xen/cmdline.c line 88
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+ "couldn't append null terminator to word during Xen cmdline parsing"); +grub_print_error (); +grub_exit (); + } + + current_word_len =grub_strlen (current_word) +1 ; + current_word =grub_realloc (current_word, current_word_len); +if (current_word ==NULL ) +return false; + word_list_len++;
Again this, OK ++word_list_len to be precise, can be done in a function argument below...
Quoted 16 lines
grub-core/kern/xen/cmdline.c new file +16
-0+ word_list =grub_realloc (word_list, word_list_len *sizeof (char *)); +if (word_list ==NULL ) +return false; + word_list[word_list_len -1 ] = current_word; + + current_word_len =PARSER_BASE_WORD_LEN ; + current_word_pos =0 ; + current_word =grub_malloc (current_word_len); +if (current_word ==NULL ) +return false; + +return true; +} + +static bool +check_key_is_safe (char *key,grub_size_t len)
grub-core/kern/xen/cmdline.c line 114
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+{ +grub_size_t i; + +for (i =0 ; i < len; i++) + { +/* +* Ensure only a-z, A-Z, and _ are allowed. +*/ + if (! ( (key[i] >= 'A' && key[i] <= 'Z') + || (key[i] >= 'a' && key[i] <= 'z')
You have whole family of grub_isalpha() functions. Could not use them here and there?
Quoted 32 lines
grub-core/kern/xen/cmdline.c new file +32
-0+ || (key[i] == '_') ) ) +return false; + } +return true; +} + +void +grub_parse_xen_cmdline (void ) +{ +const char *cmdline = (const char *) grub_xen_start_page_addr->cmd_line; +grub_size_t cmdline_len; +bool cmdline_valid = false; +char **param_keys =NULL ; +char **param_vals =NULL ; +grub_size_t param_dict_len =0 ; +grub_size_t param_dict_pos =0 ; +enum parse_flags parse_flags =0 ; +grub_size_t i =0 ; + +/* +* The following algorithm is used to parse the Xen command line: +* +* - The command line is split into space-separated words. +* - Single and double quotes may be used to suppress the splitting +* behavior of spaces. +* - Double quotes are appended to the current word verbatim if they +* appear within a single-quoted string portion, and vice versa. +* - Backslashes may be used to cause the next character to be +* appended to the current word verbatim. This is only useful when +* used to escape quotes, spaces, and backslashes, but for simplicity +* we allow backslash-escaping anything. +* - After splitting the command line into words, each word is checked to
grub-core/kern/xen/cmdline.c line 156
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+* see if it contains an equals sign. +* - If it does, it is split on the equals sign into a key-value pair. The +* key is then treated as an variable name, and the value is treated as +* the variable's value. +* - If it does not, the entire word is treated as a variable name. The +* variable's value is implicitly considered to be `1`. +* - All variables detected on the command line are checked to see if their +* names begin with the string `xen_grub_env_`. Variables that do not pass +* this check are discarded, variables that do pass this check are +* exported so they are available to the GRUB configuration.
I think not all from this valuable comment landed in the documentation. Please fix it...
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+*/ + + current_word_len =PARSER_BASE_WORD_LEN ; + current_word =grub_malloc (current_word_len); +if (current_word ==NULL ) + goto cleanup; + +for (i =0 ; i <MAX_GUEST_CMDLINE ; i++) + { +if (cmdline[i] =='\0' )
grub-core/kern/xen/cmdline.c line 176
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+ { + cmdline_valid = true; +break ; + } + } + +if (cmdline_valid == false) + { +grub_error (GRUB_ERR_BAD_ARGUMENT , +"Command line from Xen is not NUL-terminated" );
GRUB errors usually start with lowercase...
Quoted 4 lines
grub-core/kern/xen/cmdline.c new file +4
-0+grub_print_error (); + goto cleanup; + } +
grub-core/kern/xen/cmdline.c line 190
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+ cmdline_len =grub_strlen (cmdline); +for (i =0 ; i < cmdline_len; i++) + { + current_char = cmdline[i]; + +/* +* If the previous character was a backslash, append the current +* character to the word verbatim +*/ +if (parse_flags &PARSER_HIT_BACKSLASH )
s/parse_flags/parser_state/
Quoted 38 lines
grub-core/kern/xen/cmdline.c new file +38
-0+ { + parse_flags &= ~PARSER_HIT_BACKSLASH ; +if (append_char_to_word (false) == false) + goto cleanup; +continue ; + } + +switch (current_char) + { +case '\\' : +/* Backslashes escape arbitrary characters. */ + parse_flags |=PARSER_HIT_BACKSLASH ; +continue ; + +case '\'' : +/* +* Single quotes suppress word splitting and double quoting until +* the next single quote is encountered. +*/ +if (parse_flags &PARSER_IN_DOUBLE_QUOTES ) + { +if (append_char_to_word (false) == false) + goto cleanup; +continue ; + } + + parse_flags ^=PARSER_IN_SINGLE_QUOTES ; +continue ; + +case '"' : +/* +* Double quotes suppress word splitting and single quoting until +* the next double quote is encountered. +*/ +if (parse_flags &PARSER_IN_SINGLE_QUOTES ) + { +if (append_char_to_word (false) == false) + goto cleanup;
grub-core/kern/xen/cmdline.c line 238
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+continue ; + } + + parse_flags ^=PARSER_IN_DOUBLE_QUOTES ; +continue ; + +case ' ' : +/* Spaces separate words in the command line from each other. */ +if (parse_flags &PARSER_IN_SINGLE_QUOTES + || parse_flags &PARSER_IN_DOUBLE_QUOTES )
I prefer "||" and "&&" at the end of the lines...
grub-core/kern/xen/cmdline.c line 245
Quoted 7 lines
grub-core/kern/xen/cmdline.c new file +7
-0+ { +if (append_char_to_word (false) == false) + goto cleanup; +continue ; + } + +if (append_word_to_list () == false)
This shows nicely that the function misses arguments...
grub-core/kern/xen/cmdline.c line 212
Quoted 5 lines
grub-core/kern/xen/cmdline.c new file +5
-0+ goto cleanup; +continue ; + } + +if (append_char_to_word (false) == false)
Ditto...
grub-core/kern/xen/cmdline.c line 245
Quoted 4 lines
grub-core/kern/xen/cmdline.c new file +4
-0+ goto cleanup; + } + +if (append_word_to_list () == false)
Ditto...
Quoted 8 lines
grub-core/kern/xen/cmdline.c new file +8
-0+ goto cleanup; + + param_keys =grub_malloc (word_list_len *sizeof (char *)); +if (param_keys ==NULL ) + goto cleanup; + param_vals =grub_malloc (word_list_len *sizeof (char *)); +if (param_vals ==NULL ) + goto cleanup;
grub-core/kern/xen/cmdline.c line 272
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+ +for (i =0 ; i < word_list_len; i++) + { +char *current_word_eq_ptr; + + current_word = word_list[i]; + current_word_len =grub_strlen (current_word) +1 ; + current_word_eq_ptr =grub_strchr (current_word,'=' ); + +if (current_word_eq_ptr)
current_word_eq_ptr != NULL
grub-core/kern/xen/cmdline.c line 272
Quoted 2 lines
grub-core/kern/xen/cmdline.c new file +2
-0+ { +grub_size_t eq_idx = (grub_size_t)(current_word_eq_ptr - current_word);
Missing space after "(grub_size_t)"...
grub-core/kern/xen/cmdline.c line 275
Quoted 1 line
grub-core/kern/xen/cmdline.c new file +1
-0+grub_size_t post_eq_len = current_word_len - (eq_idx);
You can drop "()" from eq_idx
grub-core/kern/xen/cmdline.c line 277
Quoted 2 lines
grub-core/kern/xen/cmdline.c new file +2
-0+ +if (check_key_is_safe (current_word, eq_idx))
check_key_is_safe() == true
s/check_key_is_safe/is_key_safe/
grub-core/kern/xen/cmdline.c line 289
Quoted 12 lines
grub-core/kern/xen/cmdline.c new file +12
-0+ { + param_dict_pos = param_dict_len; + param_dict_len++; + param_keys[param_dict_pos] =grub_malloc (eq_idx +1 ); +if (param_keys ==NULL ) + goto cleanup; + param_vals[param_dict_pos] =grub_malloc (post_eq_len +1 ); +if (param_vals ==NULL ) + goto cleanup; + +grub_strncpy (param_keys[param_dict_pos], current_word, + eq_idx);
Please do not wrap line here...
grub-core/kern/xen/cmdline.c line 291
Quoted 2 lines
grub-core/kern/xen/cmdline.c new file +2
-0+grub_strncpy (param_vals[param_dict_pos], + current_word + eq_idx +1 , post_eq_len);
Please remember that grub_strncpy() may return non-NUL terminated strings... You should check this everywhere...
grub-core/kern/xen/cmdline.c line 298
Quoted 7 lines
grub-core/kern/xen/cmdline.c new file +7
-0+ param_keys[param_dict_pos][eq_idx] ='\0' ; + param_vals[param_dict_pos][post_eq_len] ='\0' ; + } + } +else + { +if (check_key_is_safe (current_word, current_word_len -1 ))
check_key_is_safe() == true
Quoted 19 lines
grub-core/kern/xen/cmdline.c new file +19
-0+ { + param_dict_pos = param_dict_len; + param_dict_len++; + param_keys[param_dict_pos] =grub_malloc (current_word_len); +if (param_keys ==NULL ) + goto cleanup; + param_vals[param_dict_pos] =grub_malloc (2 ); +if (param_vals ==NULL ) + goto cleanup; + +grub_strncpy (param_keys[param_dict_pos], current_word, + current_word_len); +grub_strcpy (param_vals[param_dict_pos],"1" ); + } + } + } + +for (i =0 ; i < param_dict_len; i++) + {
grub-core/kern/xen/cmdline.c line 327
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+/* +* Find keys that start with "xen_grub_env_" and export them +* as environment variables. +*/ +if (grub_strncmp (param_keys[i], +"xen_grub_env_" , +sizeof ("xen_grub_env_" ) -1 ) !=0 ) +continue ; +grub_env_set (param_keys[i], param_vals[i]); +grub_env_export (param_keys[i]);
Both functions may fail. Don't we care about that? Should not we print a warning?
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +6
-0+ } + + cleanup: +for (i =0 ; i < word_list_len; i++) +grub_free (word_list[i]); +
grub-core/kern/xen/cmdline.c line 343
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+for (i =0 ; i < param_dict_len; i++) + { +grub_free (param_keys[i]); +grub_free (param_vals[i]); + } + +grub_free (param_keys); +grub_free (param_vals); +grub_free (word_list); +}
Daniel
Quoted 90 lines · On Fri, 1 Aug 2025 14:55:36 +0200 Daniel Kiper <[email protected]> wrote:
Quoted 79 lines · Aaron Rainbolt
Xen traditionally allows customizing guest behavior by passing arguments to the VM kernel via the kernel command line. This is no longer possible when using GRUB with Xen, as the kernel command line is decided by the GRUB configuration file within the guest, not data passed to the guest by Xen.
To work around this limitation, enable GRUB to parse a command line passed to it by Xen, and expose data from the command line to the GRUB configuration as environment variables. These variables can be used in the GRUB configuration for any desired purpose, such as extending the kernel command line passed to the guest. The command line format is inspired by the Linux kernel's command line format.
To reduce the risk of misuse, abuse, or accidents in production, the command line will only be parsed if it consists entirely of 7-bit ASCII characters, only alphabetical characters and underscores are permitted in variable names, and all variable names must start with the string "
xen_grub_env_". This also allows room for expanding the command line arguments accepted by GRUB in the future, should other arguments end up becoming desirable in the future.Signed-off-by Aaron Rainbolt <[email protected]>--- docs/grub.texi | 50 +++++ grub-core/Makefile.core.def | 2 + grub-core/kern/i386/xen/pvh.c | 14 ++ grub-core/kern/main.c | 12 ++ grub-core/kern/xen/cmdline.c | 343 ++++++++++++++++++++++++++++++++++ include/grub/xen.h | 2 + 6 files changed, 423 insertions(+) create mode 100644 grub-core/kern/xen/cmdline.cdocs/grub.texi +0
-0@@ -3271,6 +3271,7 @@ GRUB. Others may be used freely in GRUBconfiguration files. @menu
* Special environment variables::
* Environment block::docs/grub.texi +1
-0+* Passing environment variables through Xen:: @end menu@@ -3871,6 +3872,55 @@ using BIOS or EFI functions (no ATA, USB orIEEE1275). @command{grub-mkconfig} uses this facility to implement
@samp{GRUB_SAVEDEFAULT} (@pxref{Simple configuration}).+@node Passing environment variables through Xen +@section Passing environment variables through Xen
docs/grub.texi +2
-0+ +If you are using a GRUB image as the kernel for a PV or PVH Xenvirtual +machine, you can pass environment variables from Xen's dom0 to the VM through +the Xen-provided kernel command line. When combined with a properly configured +guest, this can be used to customize the guest's behavior on bootup via the +VM's Xen configuration file. +
+GRUB will parse the kernel command line passed to it by Xen during bootup. +The command line will be split into space-delimited words. Single and +double quotes may be used to quote words or portions of words that contain +spaces. Arbitrary characters may be backslash-escaped to make them a literal +component of a word rather than being parsed as quotes or word separators. The +command line must consist entirely of printable 7-bit ASCII characters and +spaces. If a non-printing ASCII character is found anywhere in the command +line, the entire command line will be ignored by GRUB. + +Each word should be a variable assignment in the format ``variable'' or +``variable=value''. Variable names must contain only the characters A-Z, a-z, +and underscore (``_''). Variable names must begin with the string +``xen_grub_env_''. Variable values can contain arbitrary printable 7-bit +ASCII characters and space. If any variable contains an illegal name, that +variable will be ignored. +
+If a variable name and value are both specified, the variable will be set to +the specified value. If only a variable name is specified, the variable's +value will be set to ``1''.docs/grub.texi +2
-0+ +The following is a simple example of how to use this functionalityto append +arbitrary variables to a guest's kernel command line:
docs/grub.texi using BIOS or EFI functions (no ATA, USB or IEEE1275). · line 3912
Quoted 7 lines
docs/grub.texi +7
-0+ +@example +# In the Xen configuration file for the guest +name = "linux_vm" +type = "pvh" +kernel = "/path/to/grub-i386-xen_pvh.bin" +extra = "xen_grub_env_kernelappend='loglevel=3'"s/kernelappend/kernel_append/
Quoted 5 lines
or maybe even
s/kernelappend/linux_append/
to make it clear it is appended to the "linux" command line...
Will do.
Quoted 10 lines
Quoted 8 lines
docs/grub.texi +7
-0+memory = 1024 +disk = [ "file:/srv/vms/linux_vm.img,sda,w" ] + +# In the guest's GRUB configuration file +menuentry "Linux VM with dom0-specified kernel parameters" @{ + search --set=root --label linux_vm --hint hd0,msdos1 + linux /boot/vmlinuz root=LABEL=linux_vm$@{xen_grub_env_kernelappend@}
Ditto...
Will do.
Quoted 43 lines
Quoted 43 lines
docs/grub.texi +4
-0+ initrd /boot/initrd.img +@} +@end example + @node Modules @chapter Modules(quoted diff) +0
-0b/grub-core/Makefile.core.def index b3f7119..df0f266 100644
grub-core/Makefile.core.def +2
-0@@ -248,6 +248,7 @@ kernel = { xen = term/xen/console.c; xen = disk/xen/xendisk.c; xen = commands/boot.c; + xen = kern/xen/cmdline.c; i386_xen_pvh = commands/boot.c; i386_xen_pvh = disk/xen/xendisk.c;@@ -255,6 +256,7 @@ kernel = { i386_xen_pvh = kern/i386/xen/tsc.c; i386_xen_pvh = kern/i386/xen/pvh.c; i386_xen_pvh = kern/xen/init.c; + i386_xen_pvh = kern/xen/cmdline.c; i386_xen_pvh = term/xen/console.c; ia64_efi = kern/ia64/efi/startup.S;(quoted diff) +0
-0
b/grub-core/kern/i386/xen/pvh.cindex 91fbca8..12df2d8 100644grub-core/kern/i386/xen/pvh.c +2
-0@@ -321,6 +321,8 @@ voidgrub_xen_setup_pvh (void) {grub_addr_t par; +const char *xen_cmdline; +int i;grub_xen_cpuid_base ();grub_xen_setup_hypercall_page ();@@ -352,6 +354,18 @@ grub_xen_setup_pvh (void)grub_xen_mm_init_regions ();
Quoted 8 lines
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 359
Quoted 4 lines
grub-core/kern/i386/xen/pvh.c +3
-0grub_rsdp_addr = pvh_start_info->rsdp_paddr; + + xen_cmdline = (const char *) pvh_start_info->cmdline_paddr; +for (i =0 ; i <MAX_GUEST_CMDLINE ; i++)Oh,
MAX_GUEST_CMDLINEis a too generic. May I ask you to rename it toGRUB_XEN_MAX_GUEST_CMDLINE? This should be done in separate patch preceding this one.
Sure.
Quoted 12 lines
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 361
Quoted 2 lines
grub-core/kern/i386/xen/pvh.c +2
-0+ { +if (xen_cmdline[i] =='\0' )I cannot see much sense in this check. Please look below...
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 364
Quoted 4 lines
grub-core/kern/i386/xen/pvh.c +3
-0+ { + grub_strncpy ((char *) grub_xen_start_page_addr->cmd_line, + (char *) pvh_start_info->cmdline_paddr,s/char */const char */
Quoted 2 lines
Is it always guaranteed that
pvh_start_info->cmdline_paddrhaveMAX_GUEST_CMDLINEsize? If yes then...
It is not guaranteed. I tested this under Qubes OS, and it is unfortunately very possible to pass a guest command line longer than MAX_GUEST_CMDLINE via pvh_start_info->cmdline_paddr. I do not know of any documentation specifying what the "real" maximum length is in this instance (if any), but in any event the string ultimately has to be crammed into an array that is only MAX_GUEST_CMDLINE long. Originally I wrote this to truncate the command line in this situation, but later decided that discarding the command line would be safer than truncation.
(When booting a VM in PV mode, Xen does guarantee the command line will not be longer than MAX_GUEST_CMDLINE and will simply return a truncated command line. There is no way to detect this condition to my awareness, so in PV mode, we simply live with the truncation since we aren't given another option.)
Quoted 6 lines
grub_memset((void *)pvh_start_info->cmdline_paddr, 0,MAX_GUEST_CMDLINE);grub_strncpy((char *)grub_xen_start_page_addr->cmd_line, (const char *)pvh_start_info->cmdline_paddr,MAX_GUEST_CMDLINE- 1);... and you are done...
This would truncate the command line rather than discarding it. If the goal is consistency with Xen's PV mode, then I can switch to this, but I don't like the idea of booting a guest with corrupted data inserted randomly into the grub.cfg file. (Like mentioned above, there isn't any other option when using PV mode, but just because PV mode does things dangerously doesn't mean we have to when running in PVH mode.)
Quoted 26 lines
Quoted 26 lines
grub-core/kern/i386/xen/pvh.c +4
-0+ MAX_GUEST_CMDLINE); +break ; + } + } }
grub_err_tgrub-core/kern/main.c +4
-0@@ -37,6 +37,10 @@#include <grub/machine/memory.h> #endif +#if defined (GRUB_MACHINE_XEN ) || defined (GRUB_MACHINE_XEN_PVH ) +#include <grub/xen.h> +#endif +static bool cli_disabled = false;static bool cli_need_auth = false;@@ -351,6 +355,14 @@ grub_main (void)grub_env_export ("root" );grub_env_export ("prefix" );
Quoted 10 lines
grub-core/kern/main.c grub_main (void) · line 363
Quoted 7 lines
grub-core/kern/main.c +2
-0+/* +* Parse command line parameters from Xen and export them as environment
grub-core/kern/main.c +4
-0+* variables +*/ +#if defined (GRUB_MACHINE_XEN ) || defined (GRUB_MACHINE_XEN_PVH ) +grub_parse_xen_cmdline ();Please move this call to the
grub-core/kern/xen/init.c:grub_machine_init().
Will do.
Quoted 45 lines
Quoted 33 lines
grub-core/kern/main.c +2
-0+#endif +/* Reclaim space used for modules. */ reclaim_module_space ();(quoted diff) +0
-0
b/grub-core/kern/xen/cmdline.cnew file mode 100644 index 0000000..03dd88fgrub-core/kern/xen/cmdline.c new file +6
-0@@ -0,0 +1,343 @@ +/* +* GRUB -- GRand Unified Bootloader +* Copyright (C) 2025 Free Software Foundation, Inc. +* +* GRUB is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *+ * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details.+ *
+ * You should have received a copy of the GNU General Public License
+ * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
+ */grub-core/kern/xen/cmdline.c new file +2
-0+ +#include <grub/env.h> grub-core/kern/xen/cmdline.c line 29
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+#include <grub/misc.h> +#include <grub/mm.h> +#include <grub/xen.h> + +enum parse_flags +{ +PARSER_HIT_BACKSLASH =0x1 , +PARSER_IN_SINGLE_QUOTES =0x2 , +PARSER_IN_DOUBLE_QUOTES =0x4 , +};typedef
parse_flagsparse_flags_t;
Quoted 1 line
... and use
parse_flags_tinstead below...
Will do.
Quoted 1 line
And probably this should be a local variable...
See below for comments on globals in the parser.
Quoted 4 lines
grub-core/kern/xen/cmdline.c
Quoted 2 lines
grub-core/kern/xen/cmdline.c new file +2
-0+ +#define PARSER_BASE_WORD_LEN 16This constant begs for a few words of comment...
Will add. This is just the initial length of the dynamically allocated buffer for storing each "word" of the command line, but it is confusing as written. Perhaps it should be renamed to PARSER_WORD_BUF_START_LEN or similar, to make it clear this isn't a string length, but a buffer length?
Quoted 9 lines
grub-core/kern/xen/cmdline.c line 38
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +6
-0+static grub_size_t word_list_len; +static char **word_list; +static grub_size_t current_word_len; +static grub_size_t current_word_pos; +static char *current_word; +static char current_char;I have a feeling that most if not all of this variables should be local in a given function...
I made them globals because making them local would have required an awful lot of parameter "shuttling" that I believed made the code less readable. For instance, the append_word_to_list function right now has no parameters and can be called very simply by the parser whenever it is needed. If all variables used were local, the function would have to have a signature akin to:
static bool append_word_to_list(grub_size_t *current_word_pos_ref,
grub_size_t *current_word_len_ref, char *current_word, grub_size_t *word_list_len_ref, char **word_list)
IMO this is difficult to read and frustrating to call (possibly even error-prone). Ultimately the variables are "local" to the parser, and the functions are just there to split up the parser's algorithm to avoid repetition. They all ultimately operate on the same state, so having the state variables static but global within the file fits the current parser design well.
Quoted 10 lines
Quoted 8 lines
grub-core/kern/xen/cmdline.c new file +5
-0+static bool +append_char_to_word (bool allow_null) +{ +/* +* Fail if the current char is outside of the range 0x20 to
0x7E. If
+ *allow_nullis true, make an exception for0x00. This is a
safeguardCould you elaborate here when
allow_null== true is useful?
Usually when appending characters to a word, you aren't going to be appending null characters, thus append_char_to_word usually rejects those so as to make it harder to mess things up. However, the string does need to be null-terminated, and thus once a command line word is fully loaded into current_word, it is necessary to add the null terminator on the end. In this instance the parser sets current_char to '\0' and then calls the append_char_to_word function with allow_null set to true, so that the function knows that the addition of a null is intentional here.
(In retrospect, if allow_null is set to true, the only thing append_char_to_word should append is a null character, it should reject anything else in that instance. Otherwise someone could accidentally append something other than a null when they meant to append a null.)
Quoted 5 lines
grub-core/kern/xen/cmdline.c line 48
Quoted 3 lines
grub-core/kern/xen/cmdline.c new file +3
-0+* against likely-invalid data. +*/ + if ( (!(current_char >= 0x20) || !(current_char <= 0x7E) )
grub_isprint()?
That would work, I wasn't aware that existed. Maybe a mention of some valuable GRUB internal API functions that are likely to remain stable could be added to the GRUB development manual? (Or just a reference to header files where useful things like this are defined.)
Quoted 4 lines
Quoted 1 line
+ && (
current_char!= '\0' ||allow_null== false))I would drop redundant spaces between "(" and ")" and move "&&" to the end of first line of "if".
Will do, though I'm likely to rewrite this conditional anyway so that anything other than '\0' will be rejected when allow_null == true.
Quoted 7 lines
grub-core/kern/xen/cmdline.c line 54
Quoted 5 lines
grub-core/kern/xen/cmdline.c new file +5
-0+return false; + +if (current_word_pos == current_word_len) + { + current_word_len *=2 ;You can do this in the argument of the function below...
I mean, yes, technically I can, but that's a lot less readable to me. I can't find anywhere else in GRUB that uses that style (using grep -ri '\*=' to search), and can find a few spots that use a style similar to the one I've used here:
* util/grub-install.c in function device_map_check_duplicates
* grub-core/osdep/windows/platform.c in function get_efi_variable
* grub-core/osdep/unix/platform.c in function get_ofpathname
Quoted 11 lines
grub-core/kern/xen/cmdline.c line 64
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+ current_word =grub_realloc (current_word, current_word_len); +if (current_word ==NULL ) + { + current_word_len /=2 ; +return false; + } + } + + current_word[current_word_pos] = current_char; + current_word_pos++;
Quoted 1 line
Again, you can do this operation in the "[]" above...
Will do. (This does seem to be a much more common way to write things in GRUB than what I've done.)
Quoted 10 lines
grub-core/kern/xen/cmdline.c line 72
Quoted 8 lines
grub-core/kern/xen/cmdline.c new file +8
-0+return true; +} + +static bool +append_word_to_list (void ) +{ +/* No-op on empty words. */ +if (current_word_pos ==0 )This should be probably an argument for the function...
See above for parser state and global variables rationale.
Quoted 12 lines
Quoted 12 lines
grub-core/kern/xen/cmdline.c new file +7
-0+return true; + + current_char ='\0' ; +if (append_char_to_word (true) == false) + { + grub_error (GRUB_ERR_BUG, + "couldn't append null terminator to word duringXen cmdline parsing");
grub-core/kern/xen/cmdline.c new file +4
-0+grub_print_error (); +grub_exit (); + } +
Quoted 8 lines
grub-core/kern/xen/cmdline.c line 88
Quoted 5 lines
grub-core/kern/xen/cmdline.c new file +5
-0+ current_word_len =grub_strlen (current_word) +1 ; + current_word =grub_realloc (current_word, current_word_len); +if (current_word ==NULL ) +return false; + word_list_len++;Again this, OK ++word_list_len to be precise, can be done in a function argument below...
grep -ri 'alloc.*++' doesn't show me any instance of this style anywhere else in the GRUB codebase, and I find it much more difficult to read since now I have to think about incrementing word_list_len's value and returning it and multiplying the returned value all at the same time. grub-core/osdep/unix/platform.c uses the style I've used here.
Quoted 22 lines
Quoted 22 lines
+
word_list=grub_realloc(word_list,word_list_len* sizeof (char *));grub-core/kern/xen/cmdline.c new file +20
-0+if (word_list ==NULL ) +return false; + word_list[word_list_len -1 ] = current_word; + + current_word_len =PARSER_BASE_WORD_LEN ; + current_word_pos =0 ; + current_word =grub_malloc (current_word_len); +if (current_word ==NULL ) +return false; + +return true; +} + +static bool +check_key_is_safe (char *key,grub_size_t len) +{ +grub_size_t i; + +for (i =0 ; i < len; i++) + {
Quoted 8 lines
grub-core/kern/xen/cmdline.c line 114
Quoted 5 lines
grub-core/kern/xen/cmdline.c new file +5
-0+/* +* Ensure only a-z, A-Z, and _ are allowed. +*/ + if (! ( (key[i] >= 'A' && key[i] <= 'Z') + || (key[i] >= 'a' && key[i] <= 'z')You have whole family of
grub_isalpha()functions. Could not use them here and there?
Those would almost certainly work here, I'll switch to using those where possible (including here).
Quoted 50 lines
Quoted 50 lines
grub-core/kern/xen/cmdline.c new file +10
-0+ || (key[i] == '_') ) ) +return false; + } +return true; +} + +void +grub_parse_xen_cmdline (void ) +{ + const char *cmdline = (const char *)
grub_xen_start_page_addr->cmd_line;grub-core/kern/xen/cmdline.c new file +14
-0+grub_size_t cmdline_len; +bool cmdline_valid = false; +char **param_keys =NULL ; +char **param_vals =NULL ; +grub_size_t param_dict_len =0 ; +grub_size_t param_dict_pos =0 ; +enum parse_flags parse_flags =0 ; +grub_size_t i =0 ; + +/* +* The following algorithm is used to parse the Xen command line: +* +* - The command line is split into space-separated words. +* - Single and double quotes may be used to suppress the splitting
grub-core/kern/xen/cmdline.c new file +2
-0+* behavior of spaces. +* - Double quotes are appended to the current word verbatim if they
+ * appear within a single-quoted string portion, and vice
versa.grub-core/kern/xen/cmdline.c new file +2
-0+* - Backslashes may be used to cause the next character to be +* appended to the current word verbatim. This is only useful when
+ * used to escape quotes, spaces, and backslashes, but for
simplicitygrub-core/kern/xen/cmdline.c new file +2
-0+* we allow backslash-escaping anything. +* - After splitting the command line into words, each word is checked to
grub-core/kern/xen/cmdline.c new file +2
-0+* see if it contains an equals sign. +* - If it does, it is split on the equals sign into a key-value pair. The
+ * key is then treated as an variable name, and the value is
treated asgrub-core/kern/xen/cmdline.c new file +2
-0+* the variable's value. +* - If it does not, the entire word is treated as a variable name. The
grub-core/kern/xen/cmdline.c new file +2
-0+* variable's value is implicitly considered to be `1`. +* - All variables detected on the command line are checked to see if their
Quoted 8 lines
Quoted 5 lines
+ * names begin with the string
xen_grub_env_. Variables that
do not pass
+ * this check are discarded, variables that do pass this check
are
+ * exported so they are available to the GRUB configuration.I think not all from this valuable comment landed in the documentation. Please fix it...
Comparing the two side-by-side:
+----------------------------------+----------------------------------+ | Documentation | Comment | +==================================+==================================+ | The command line will be split | The command line is split into | | into space-delimited words. | space-separated words. Single | | Single and double quotes may be | and double quotes may be used to | | used to quote words or portions | suppress the splitting behavior | | of words that contain spaces. | of spaces. | +----------------------------------+----------------------------------+ | (Self-evident, any other | Double quotes are appended to | | behavior involving quotes would | the current word verbatim if | | be extremely unexpected.) | they appear within a single- | | | quoted string, and vice versa. | +----------------------------------+----------------------------------+ | Arbitrary characters may be | Backslashes may be used to cause | | backslash-escaped to make them a | the next character to be | | literal component of a word | appended to the current word | | rather than being parsed as | verbatim. This is only useful | | quotes or word separators. | when used to escape quotes, | | | spaces, and backslashes, but for | | | simplicity we allow backslash- | | | escaping anything. | +----------------------------------+----------------------------------+ | Each word should be a variable | After splitting the command line | | assignment in the format | into words, each word is checked | | ``variable'' or | to see if it contains an equals | | ``variable=value''. | sign. | +----------------------------------+----------------------------------+ | If a variable name and value are | If it does, it is split on the | | both specified, the variable | equals sign into a key-value | | will be set to the specified | pair. The key is then treated as | | value. | a variable name, and the value | | | treated as the variable's value. | +----------------------------------+----------------------------------+ | If only a variable name is | If it does not, the entire word | | specified, the variable's value | is treated as a variable name. | | will be set to ``1''. | The variable's value is | | | implicitly considered to be '1'. | +----------------------------------+----------------------------------+ | Variable names must begin with | All variables detected on the | | the string ``xen_grub_env_''... | command line are checked to see | | If any variable contains an | if their names begin with the | | illegal name, that variable will | string `xen_grub_env_`. | | be ignored. | Variables that do not pass this | | | check are discarded, | +----------------------------------+----------------------------------+ | ...you can pass environment | variables that do pass this | | variables from Xen's dom0 to the | check are exported so they are | | VM through the Xen-provided | available to the GRUB | | kernel command line. | configuration. | +----------------------------------+----------------------------------+
The only missing detail I see is that single quotes are legal in double-quoted strings and vice versa, though I guess I can make it more explicit that the variables passed on the command line are exported before getting to the example that shows this. Is there anything else you see that's missing?
Quoted 14 lines
Quoted 14 lines
grub-core/kern/xen/cmdline.c new file +14
-0+*/ + + current_word_len =PARSER_BASE_WORD_LEN ; + current_word =grub_malloc (current_word_len); +if (current_word ==NULL ) + goto cleanup; + +for (i =0 ; i <MAX_GUEST_CMDLINE ; i++) + { +if (cmdline[i] =='\0' ) + { + cmdline_valid = true; +break ; + }
Quoted 8 lines
grub-core/kern/xen/cmdline.c line 176
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +6
-0+ } + +if (cmdline_valid == false) + { +grub_error (GRUB_ERR_BAD_ARGUMENT , +"Command line from Xen is not NUL-terminated" );GRUB errors usually start with lowercase...
Will fix.
Quoted 9 lines
Quoted 9 lines
grub-core/kern/xen/cmdline.c new file +9
-0+grub_print_error (); + goto cleanup; + } + + cmdline_len =grub_strlen (cmdline); +for (i =0 ; i < cmdline_len; i++) + { + current_char = cmdline[i]; +
Quoted 8 lines
grub-core/kern/xen/cmdline.c line 190
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +2
-0+/* +* If the previous character was a backslash, append the current
grub-core/kern/xen/cmdline.c new file +3
-0+* character to the word verbatim +*/ +if (parse_flags &PARSER_HIT_BACKSLASH )s/parse_flags/parser_state/
Hmm, I don't like 'parser_state' as a name because the parser's "state" is the global variables in grub-core/kern/xen/cmdline.. Maybe 'splitter_state' instead, since this is just the bit of state that the word splitter is concerned with?
Quoted 45 lines
Quoted 45 lines
grub-core/kern/xen/cmdline.c new file +17
-0+ { + parse_flags &= ~PARSER_HIT_BACKSLASH ; +if (append_char_to_word (false) == false) + goto cleanup; +continue ; + } + +switch (current_char) + { +case '\\' : +/* Backslashes escape arbitrary characters. */ + parse_flags |=PARSER_HIT_BACKSLASH ; +continue ; + +case '\'' : +/* +* Single quotes suppress word splitting and double quoting until
grub-core/kern/xen/cmdline.c new file +15
-0+* the next single quote is encountered. +*/ +if (parse_flags &PARSER_IN_DOUBLE_QUOTES ) + { +if (append_char_to_word (false) == false) + goto cleanup; +continue ; + } + + parse_flags ^=PARSER_IN_SINGLE_QUOTES ; +continue ; + +case '"' : +/* +* Double quotes suppress word splitting and single quoting until
grub-core/kern/xen/cmdline.c new file +11
-0+* the next double quote is encountered. +*/ +if (parse_flags &PARSER_IN_SINGLE_QUOTES ) + { +if (append_char_to_word (false) == false) + goto cleanup; +continue ; + } + + parse_flags ^=PARSER_IN_DOUBLE_QUOTES ; +continue ;
Quoted 8 lines
grub-core/kern/xen/cmdline.c line 238
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +3
-0+ +case ' ' : +/* Spaces separate words in the command line from each other. */
grub-core/kern/xen/cmdline.c new file +2
-0+if (parse_flags &PARSER_IN_SINGLE_QUOTES + || parse_flags &PARSER_IN_DOUBLE_QUOTES )I prefer "||" and "&&" at the end of the lines...
Will fix. This is another thing that might be good to put in the GRUB coding style docs. (My boss insists that I always put && and || at the beginning of lines, so I've been instinctively doing that.)
Quoted 10 lines
grub-core/kern/xen/cmdline.c line 245
Quoted 8 lines
grub-core/kern/xen/cmdline.c new file +7
-0+ { +if (append_char_to_word (false) == false) + goto cleanup; +continue ; + } + +if (append_word_to_list () == false)This shows nicely that the function misses arguments...
Will fix, and will also check my compiler warnings more closely (I assume this generated a warning that I missed).
Quoted 27 lines
grub-core/kern/xen/cmdline.c line 212
Quoted 5 lines
grub-core/kern/xen/cmdline.c new file +5
-0+ goto cleanup; +continue ; + } + +if (append_char_to_word (false) == false)Ditto...
grub-core/kern/xen/cmdline.c line 245
Quoted 4 lines
grub-core/kern/xen/cmdline.c new file +4
-0+ goto cleanup; + } + +if (append_word_to_list () == false)Ditto...
Quoted 12 lines
grub-core/kern/xen/cmdline.c new file +12
-0+ goto cleanup; + + param_keys =grub_malloc (word_list_len *sizeof (char *)); +if (param_keys ==NULL ) + goto cleanup; + param_vals =grub_malloc (word_list_len *sizeof (char *)); +if (param_vals ==NULL ) + goto cleanup; + +for (i =0 ; i < word_list_len; i++) + { +char *current_word_eq_ptr;
Quoted 8 lines
grub-core/kern/xen/cmdline.c line 272
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +6
-0+ + current_word = word_list[i]; + current_word_len =grub_strlen (current_word) +1 ; + current_word_eq_ptr =grub_strchr (current_word,'=' ); + +if (current_word_eq_ptr)
current_word_eq_ptr!= NULL
Will change.
Quoted 5 lines
Quoted 3 lines
grub-core/kern/xen/cmdline.c new file +2
-0+ { + grub_size_t eq_idx = (grub_size_t)(current_word_eq_ptr -
current_word);Missing space after "(
grub_size_t)"...
Will fix.
Quoted 3 lines
Quoted 1 line
+
grub_size_tpost_eq_len=current_word_len- (eq_idx);You can drop "()" from
eq_idx
Will fix.
Quoted 6 lines
grub-core/kern/xen/cmdline.c line 277
Quoted 2 lines
grub-core/kern/xen/cmdline.c new file +2
-0+ +if (check_key_is_safe (current_word, eq_idx))
check_key_is_safe()== trues/check_key_is_safe/is_key_safe/
Will fix and rename.
Quoted 9 lines
Quoted 9 lines
grub-core/kern/xen/cmdline.c new file +4
-0+ { + param_dict_pos = param_dict_len; + param_dict_len++; + param_keys[param_dict_pos] = grub_malloc (eq_idx +1);
grub-core/kern/xen/cmdline.c new file +3
-0+if (param_keys ==NULL ) + goto cleanup; + param_vals[param_dict_pos] = grub_malloc(
post_eq_len+ 1);
Quoted 8 lines
grub-core/kern/xen/cmdline.c line 289
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +4
-0+if (param_vals ==NULL ) + goto cleanup; + + grub_strncpy (param_keys[param_dict_pos],
current_word,grub-core/kern/xen/cmdline.c new file +1
-0+ eq_idx);Please do not wrap line here...
Will fix.
Quoted 6 lines
Quoted 3 lines
grub-core/kern/xen/cmdline.c new file +2
-0+ grub_strncpy (param_vals[param_dict_pos], + current_word + eq_idx + 1,
post_eq_len);Please remember that
grub_strncpy()may return non-NUL terminated strings... You should check this everywhere...
The next two lines of the patch append the null terminators here.
Quoted 2 lines
grub-core/kern/xen/cmdline.c line 293
Quoted 2 lines
grub-core/kern/xen/cmdline.c new file +2
-0+ param_keys[param_dict_pos][eq_idx] ='\0' ; + param_vals[param_dict_pos][post_eq_len] ='\0' ;
Making a note for myself here, I believe I'm unintentionally double-null-terminating param_vals[param_dict_pos], since post_eq_len is the length of everything after the equals sign including the null terminator. Thus post_eq_len - 2 is the index of the last character of the string, post_eq_len - 1 is the index of the null terminator, and then this is a second null terminator. I should skip appending the null here and also should allocate a buffer one character smaller for param_vals[param_dict_pos]. This will need comments to explain.
Quoted 8 lines
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +5
-0+ } + } +else + { + if (check_key_is_safe (current_word, current_word_len -1))
check_key_is_safe()== true
Will fix (and also rename as requested earlier).
Quoted 26 lines
Quoted 26 lines
grub-core/kern/xen/cmdline.c new file +4
-0+ { + param_dict_pos = param_dict_len; + param_dict_len++; + param_keys[param_dict_pos] = grub_malloc(
current_word_len);grub-core/kern/xen/cmdline.c new file +7
-0+if (param_keys ==NULL ) + goto cleanup; + param_vals[param_dict_pos] =grub_malloc (2 ); +if (param_vals ==NULL ) + goto cleanup; + + grub_strncpy (param_keys[param_dict_pos],
current_word,grub-core/kern/xen/cmdline.c new file +13
-0+ current_word_len); +grub_strcpy (param_vals[param_dict_pos],"1" ); + } + } + } + +for (i =0 ; i < param_dict_len; i++) + { +/* +* Find keys that start with "xen_grub_env_" and export them +* as environment variables. +*/ + if (grub_strncmp (param_keys[i],
Quoted 8 lines
grub-core/kern/xen/cmdline.c line 327
Quoted 5 lines
grub-core/kern/xen/cmdline.c new file +5
-0+"xen_grub_env_" , + sizeof ("xen_grub_env_") - 1) != 0) + continue; +grub_env_set (param_keys[i], param_vals[i]); +grub_env_export (param_keys[i]);Both functions may fail. Don't we care about that? Should not we print a warning?
No other places in this file do so, but I'm happy to add warnings here anyway.
--
Aaron
Quoted 18 lines
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +6
-0+ } + + cleanup: +for (i =0 ; i < word_list_len; i++) +grub_free (word_list[i]); +grub-core/kern/xen/cmdline.c line 343
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+for (i =0 ; i < param_dict_len; i++) + { +grub_free (param_keys[i]); +grub_free (param_vals[i]); + } + +grub_free (param_keys); +grub_free (param_vals); +grub_free (word_list); +}Daniel
Quoted 181 lines · Aaron Rainbolt
Quoted 90 lines · On Fri, 1 Aug 2025 14:55:36 +0200 Daniel Kiper <[email protected]> wrote:
Quoted 79 lines · Aaron Rainbolt
Xen traditionally allows customizing guest behavior by passing arguments to the VM kernel via the kernel command line. This is no longer possible when using GRUB with Xen, as the kernel command line is decided by the GRUB configuration file within the guest, not data passed to the guest by Xen.
To work around this limitation, enable GRUB to parse a command line passed to it by Xen, and expose data from the command line to the GRUB configuration as environment variables. These variables can be used in the GRUB configuration for any desired purpose, such as extending the kernel command line passed to the guest. The command line format is inspired by the Linux kernel's command line format.
To reduce the risk of misuse, abuse, or accidents in production, the command line will only be parsed if it consists entirely of 7-bit ASCII characters, only alphabetical characters and underscores are permitted in variable names, and all variable names must start with the string "
xen_grub_env_". This also allows room for expanding the command line arguments accepted by GRUB in the future, should other arguments end up becoming desirable in the future.Signed-off-by Aaron Rainbolt <[email protected]>--- docs/grub.texi | 50 +++++ grub-core/Makefile.core.def | 2 + grub-core/kern/i386/xen/pvh.c | 14 ++ grub-core/kern/main.c | 12 ++ grub-core/kern/xen/cmdline.c | 343 ++++++++++++++++++++++++++++++++++ include/grub/xen.h | 2 + 6 files changed, 423 insertions(+) create mode 100644 grub-core/kern/xen/cmdline.cdocs/grub.texi +0
-0@@ -3271,6 +3271,7 @@ GRUB. Others may be used freely in GRUBconfiguration files. @menu
* Special environment variables::
* Environment block::docs/grub.texi +1
-0+* Passing environment variables through Xen:: @end menu@@ -3871,6 +3872,55 @@ using BIOS or EFI functions (no ATA, USB orIEEE1275). @command{grub-mkconfig} uses this facility to implement
@samp{GRUB_SAVEDEFAULT} (@pxref{Simple configuration}).+@node Passing environment variables through Xen +@section Passing environment variables through Xen
docs/grub.texi +2
-0+ +If you are using a GRUB image as the kernel for a PV or PVH Xenvirtual +machine, you can pass environment variables from Xen's dom0 to the VM through +the Xen-provided kernel command line. When combined with a properly configured +guest, this can be used to customize the guest's behavior on bootup via the +VM's Xen configuration file. +
+GRUB will parse the kernel command line passed to it by Xen during bootup. +The command line will be split into space-delimited words. Single and +double quotes may be used to quote words or portions of words that contain +spaces. Arbitrary characters may be backslash-escaped to make them a literal +component of a word rather than being parsed as quotes or word separators. The +command line must consist entirely of printable 7-bit ASCII characters and +spaces. If a non-printing ASCII character is found anywhere in the command +line, the entire command line will be ignored by GRUB. + +Each word should be a variable assignment in the format ``variable'' or +``variable=value''. Variable names must contain only the characters A-Z, a-z, +and underscore (``_''). Variable names must begin with the string +``xen_grub_env_''. Variable values can contain arbitrary printable 7-bit +ASCII characters and space. If any variable contains an illegal name, that +variable will be ignored. +
+If a variable name and value are both specified, the variable will be set to +the specified value. If only a variable name is specified, the variable's +value will be set to ``1''.docs/grub.texi +2
-0+ +The following is a simple example of how to use this functionalityto append +arbitrary variables to a guest's kernel command line:
docs/grub.texi using BIOS or EFI functions (no ATA, USB or IEEE1275). · line 3912
Quoted 7 lines
docs/grub.texi +7
-0+ +@example +# In the Xen configuration file for the guest +name = "linux_vm" +type = "pvh" +kernel = "/path/to/grub-i386-xen_pvh.bin" +extra = "xen_grub_env_kernelappend='loglevel=3'"s/kernelappend/kernel_append/
Quoted 5 lines
or maybe even
s/kernelappend/linux_append/
to make it clear it is appended to the "linux" command line...
Will do.
Quoted 10 lines
Quoted 8 lines
docs/grub.texi +7
-0+memory = 1024 +disk = [ "file:/srv/vms/linux_vm.img,sda,w" ] + +# In the guest's GRUB configuration file +menuentry "Linux VM with dom0-specified kernel parameters" @{ + search --set=root --label linux_vm --hint hd0,msdos1 + linux /boot/vmlinuz root=LABEL=linux_vm$@{xen_grub_env_kernelappend@}
Ditto...
Will do.
Quoted 43 lines
Quoted 43 lines
docs/grub.texi +4
-0+ initrd /boot/initrd.img +@} +@end example + @node Modules @chapter Modules(quoted diff) +0
-0b/grub-core/Makefile.core.def index b3f7119..df0f266 100644
grub-core/Makefile.core.def +2
-0@@ -248,6 +248,7 @@ kernel = { xen = term/xen/console.c; xen = disk/xen/xendisk.c; xen = commands/boot.c; + xen = kern/xen/cmdline.c; i386_xen_pvh = commands/boot.c; i386_xen_pvh = disk/xen/xendisk.c;@@ -255,6 +256,7 @@ kernel = { i386_xen_pvh = kern/i386/xen/tsc.c; i386_xen_pvh = kern/i386/xen/pvh.c; i386_xen_pvh = kern/xen/init.c; + i386_xen_pvh = kern/xen/cmdline.c; i386_xen_pvh = term/xen/console.c; ia64_efi = kern/ia64/efi/startup.S;(quoted diff) +0
-0
b/grub-core/kern/i386/xen/pvh.cindex 91fbca8..12df2d8 100644grub-core/kern/i386/xen/pvh.c +2
-0@@ -321,6 +321,8 @@ voidgrub_xen_setup_pvh (void) {grub_addr_t par; +const char *xen_cmdline; +int i;grub_xen_cpuid_base ();grub_xen_setup_hypercall_page ();@@ -352,6 +354,18 @@ grub_xen_setup_pvh (void)grub_xen_mm_init_regions ();Quoted 8 lines
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 359
Quoted 4 lines
grub-core/kern/i386/xen/pvh.c +3
-0grub_rsdp_addr = pvh_start_info->rsdp_paddr; + + xen_cmdline = (const char *) pvh_start_info->cmdline_paddr; +for (i =0 ; i <MAX_GUEST_CMDLINE ; i++)Oh,
MAX_GUEST_CMDLINEis a too generic. May I ask you to rename it toGRUB_XEN_MAX_GUEST_CMDLINE? This should be done in separate patch preceding this one.Sure.
Quoted 12 lines
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 361
Quoted 2 lines
grub-core/kern/i386/xen/pvh.c +2
-0+ { +if (xen_cmdline[i] =='\0' )I cannot see much sense in this check. Please look below...
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 364
Quoted 4 lines
grub-core/kern/i386/xen/pvh.c +3
-0+ { + grub_strncpy ((char *) grub_xen_start_page_addr->cmd_line, + (char *) pvh_start_info->cmdline_paddr,s/char */const char */
Quoted 2 lines
Is it always guaranteed that
pvh_start_info->cmdline_paddrhaveMAX_GUEST_CMDLINEsize? If yes then...
Quoted 8 lines
It is not guaranteed. I tested this under Qubes OS, and it is unfortunately very possible to pass a guest command line longer than
MAX_GUEST_CMDLINEviapvh_start_info->cmdline_paddr. I do not know of any documentation specifying what the "real" maximum length is in this instance (if any), but in any event the string ultimately has to be crammed into an array that is onlyMAX_GUEST_CMDLINElong. Originally I wrote this to truncate the command line in this situation, but later decided that discarding the command line would be safer than truncation.
I think you are confusing source, grub_xen_start_page_addr->cmd_line, and destination, pvh_start_info->cmdline_paddr. I am asking about the destination...
Quoted 5 lines
(When booting a VM in PV mode, Xen does guarantee the command line will not be longer than
MAX_GUEST_CMDLINEand will simply return a truncated command line. There is no way to detect this condition to my awareness, so in PV mode, we simply live with the truncation since we aren't given another option.)
OK...
Quoted 5 lines
Quoted 5 lines
grub_memset((void *)pvh_start_info->cmdline_paddr, 0,MAX_GUEST_CMDLINE);grub_strncpy((char *)grub_xen_start_page_addr->cmd_line, (const char *)pvh_start_info->cmdline_paddr,MAX_GUEST_CMDLINE- 1);
Quoted 8 lines
Quoted 1 line
... and you are done...
This would truncate the command line rather than discarding it. If the goal is consistency with Xen's PV mode, then I can switch to this, but I don't like the idea of booting a guest with corrupted data inserted randomly into the grub.cfg file. (Like mentioned above, there isn't any other option when using PV mode, but just because PV mode does things dangerously doesn't mean we have to when running in PVH mode.)
OK, but please remember you have to ensure the string is NUL-terminated after grub_strncpy(). Potentially you could also use grub_strlen() to make a check and add NUL in proper place...
Quoted 97 lines
Quoted 26 lines
Quoted 26 lines
grub-core/kern/i386/xen/pvh.c +4
-0+ MAX_GUEST_CMDLINE); +break ; + } + } }
grub_err_tgrub-core/kern/main.c +4
-0@@ -37,6 +37,10 @@#include <grub/machine/memory.h> #endif +#if defined (GRUB_MACHINE_XEN ) || defined (GRUB_MACHINE_XEN_PVH ) +#include <grub/xen.h> +#endif +static bool cli_disabled = false;static bool cli_need_auth = false;@@ -351,6 +355,14 @@ grub_main (void)grub_env_export ("root" );grub_env_export ("prefix" );Quoted 10 lines
grub-core/kern/main.c grub_main (void) · line 363
Quoted 7 lines
grub-core/kern/main.c +2
-0+/* +* Parse command line parameters from Xen and export them as environment
grub-core/kern/main.c +4
-0+* variables +*/ +#if defined (GRUB_MACHINE_XEN ) || defined (GRUB_MACHINE_XEN_PVH ) +grub_parse_xen_cmdline ();Please move this call to the
grub-core/kern/xen/init.c:grub_machine_init().Will do.
Quoted 45 lines
Quoted 33 lines
grub-core/kern/main.c +2
-0+#endif +/* Reclaim space used for modules. */ reclaim_module_space ();(quoted diff) +0
-0
b/grub-core/kern/xen/cmdline.cnew file mode 100644 index 0000000..03dd88fgrub-core/kern/xen/cmdline.c new file +6
-0@@ -0,0 +1,343 @@ +/* +* GRUB -- GRand Unified Bootloader +* Copyright (C) 2025 Free Software Foundation, Inc. +* +* GRUB is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *+ * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details.+ *
+ * You should have received a copy of the GNU General Public License
+ * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
+ */grub-core/kern/xen/cmdline.c new file +2
-0+ +#include <grub/env.h> grub-core/kern/xen/cmdline.c line 29
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+#include <grub/misc.h> +#include <grub/mm.h> +#include <grub/xen.h> + +enum parse_flags +{ +PARSER_HIT_BACKSLASH =0x1 , +PARSER_IN_SINGLE_QUOTES =0x2 , +PARSER_IN_DOUBLE_QUOTES =0x4 , +};typedef
parse_flagsparse_flags_t;Quoted 1 line
... and use
parse_flags_tinstead below...Will do.
Quoted 1 line
And probably this should be a local variable...
See below for comments on globals in the parser.
Quoted 4 lines
grub-core/kern/xen/cmdline.c
Quoted 2 lines
grub-core/kern/xen/cmdline.c new file +2
-0+ +#define PARSER_BASE_WORD_LEN 16This constant begs for a few words of comment...
Quoted 5 lines
Will add. This is just the initial length of the dynamically allocated buffer for storing each "word" of the command line, but it is confusing as written. Perhaps it should be renamed to
PARSER_WORD_BUF_START_LENor similar, to make it clear this isn't a string length, but a buffer length?
s/length/size/ then... However, then why 16 not, e.g., 32?
Quoted 21 lines
Quoted 9 lines
grub-core/kern/xen/cmdline.c line 38
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +6
-0+static grub_size_t word_list_len; +static char **word_list; +static grub_size_t current_word_len; +static grub_size_t current_word_pos; +static char *current_word; +static char current_char;I have a feeling that most if not all of this variables should be local in a given function...
I made them globals because making them local would have required an awful lot of parameter "shuttling" that I believed made the code less readable. For instance, the
append_word_to_listfunction right now has no parameters and can be called very simply by the parser whenever it is needed. If all variables used were local, the function would have to have a signature akin to:static bool append_word_to_list(grub_size_t
*current_word_pos_ref,
grub_size_t*current_word_len_ref, char*current_word,grub_size_t*word_list_len_ref, char **word_list)
Quoted 6 lines
IMO this is difficult to read and frustrating to call (possibly even error-prone). Ultimately the variables are "local" to the parser, and the functions are just there to split up the parser's algorithm to avoid repetition. They all ultimately operate on the same state, so having the state variables static but global within the file fits the current parser design well.
First of all, think about the design. If you are sure it is optimal then please use struct and a pointer to pass as many argument as you need...
Quoted 11 lines
Quoted 10 lines
Quoted 8 lines
grub-core/kern/xen/cmdline.c new file +5
-0+static bool +append_char_to_word (bool allow_null) +{ +/* +* Fail if the current char is outside of the range 0x20 to
0x7E. If
+ *allow_nullis true, make an exception for0x00. This is a
safeguardCould you elaborate here when
allow_null== true is useful?
Quoted 2 lines
Usually when appending characters to a word, you aren't going to be appending null characters, thus
append_char_to_wordusually rejects
s/null/NUL/...
Quoted 2 lines
those so as to make it harder to mess things up. However, the string does need to be null-terminated, and thus once a command line word is
Ditto... In general, even it is correct, I prefer to use NUL instead of null/NULL to avoid confusion...
Quoted 11 lines
fully loaded into
current_word, it is necessary to add the null terminator on the end. In this instance the parser setscurrent_charto '\0' and then calls theappend_char_to_wordfunction withallow_nullset to true, so that the function knows that the addition of a null is intentional here.(In retrospect, if
allow_nullis set to true, the only thingappend_char_to_wordshould append is a null character, it should reject anything else in that instance. Otherwise someone could accidentally append something other than a null when they meant to append a null.)
Is not it simpler to open code this instead of complicating this function?
Quoted 10 lines
Quoted 5 lines
grub-core/kern/xen/cmdline.c line 48
Quoted 3 lines
grub-core/kern/xen/cmdline.c new file +3
-0+* against likely-invalid data. +*/ + if ( (!(current_char >= 0x20) || !(current_char <= 0x7E) )
grub_isprint()?That would work, I wasn't aware that existed. Maybe a mention of some valuable GRUB internal API functions that are likely to remain stable could be added to the GRUB development manual? (Or just a reference to header files where useful things like this are defined.)
Certainly it is a good idea. In general you can assume the GRUB has a lot of POSIX compatible functions which names are prefixed with "grub_".
Quoted 75 lines
Quoted 4 lines
Quoted 1 line
+ && (
current_char!= '\0' ||allow_null== false))I would drop redundant spaces between "(" and ")" and move "&&" to the end of first line of "if".
Will do, though I'm likely to rewrite this conditional anyway so that anything other than '\0' will be rejected when
allow_null == true.Quoted 7 lines
grub-core/kern/xen/cmdline.c line 54
Quoted 5 lines
grub-core/kern/xen/cmdline.c new file +5
-0+return false; + +if (current_word_pos == current_word_len) + { + current_word_len *=2 ;You can do this in the argument of the function below...
I mean, yes, technically I can, but that's a lot less readable to me. I can't find anywhere else in GRUB that uses that style (using
grep -ri '\*='to search), and can find a few spots that use a style similar to the one I've used here:*
util/grub-install.cin functiondevice_map_check_duplicates
*grub-core/osdep/windows/platform.cin functionget_efi_variable
*grub-core/osdep/unix/platform.cin functionget_ofpathnameQuoted 11 lines
grub-core/kern/xen/cmdline.c line 64
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+ current_word =grub_realloc (current_word, current_word_len); +if (current_word ==NULL ) + { + current_word_len /=2 ; +return false; + } + } + + current_word[current_word_pos] = current_char; + current_word_pos++;Quoted 1 line
Again, you can do this operation in the "[]" above...
Will do. (This does seem to be a much more common way to write things in GRUB than what I've done.)
Quoted 10 lines
grub-core/kern/xen/cmdline.c line 72
Quoted 8 lines
grub-core/kern/xen/cmdline.c new file +8
-0+return true; +} + +static bool +append_word_to_list (void ) +{ +/* No-op on empty words. */ +if (current_word_pos ==0 )This should be probably an argument for the function...
See above for parser state and global variables rationale.
Quoted 12 lines
Quoted 12 lines
grub-core/kern/xen/cmdline.c new file +7
-0+return true; + + current_char ='\0' ; +if (append_char_to_word (true) == false) + { + grub_error (GRUB_ERR_BUG, + "couldn't append null terminator to word duringXen cmdline parsing");
grub-core/kern/xen/cmdline.c new file +4
-0+grub_print_error (); +grub_exit (); + } +Quoted 8 lines
grub-core/kern/xen/cmdline.c line 88
Quoted 5 lines
grub-core/kern/xen/cmdline.c new file +5
-0+ current_word_len =grub_strlen (current_word) +1 ; + current_word =grub_realloc (current_word, current_word_len); +if (current_word ==NULL ) +return false; + word_list_len++;Again this, OK ++word_list_len to be precise, can be done in a function argument below...
Quoted 9 lines
grep -ri 'alloc.*++'doesn't show me any instance of this style anywhere else in the GRUB codebase, and I find it much more difficult to read since now I have to think about incrementingword_list_len's value and returning it and multiplying the returned value all at the same time.grub-core/osdep/unix/platform.cuses the style I've used here.Quoted 2 lines
Quoted 2 lines
+
word_list=grub_realloc(word_list,word_list_len* sizeof (char *));
word_list = grub_realloc (word_list, ++word_list_len * sizeof (char *a));
Is it really difficult to read? I do not think so...
[...]
Quoted 107 lines
Quoted 44 lines
Quoted 44 lines
grub-core/kern/xen/cmdline.c new file +4
-0+void +grub_parse_xen_cmdline (void ) +{ + const char *cmdline = (const char *)
grub_xen_start_page_addr->cmd_line;grub-core/kern/xen/cmdline.c new file +14
-0+grub_size_t cmdline_len; +bool cmdline_valid = false; +char **param_keys =NULL ; +char **param_vals =NULL ; +grub_size_t param_dict_len =0 ; +grub_size_t param_dict_pos =0 ; +enum parse_flags parse_flags =0 ; +grub_size_t i =0 ; + +/* +* The following algorithm is used to parse the Xen command line: +* +* - The command line is split into space-separated words. +* - Single and double quotes may be used to suppress the splitting
grub-core/kern/xen/cmdline.c new file +2
-0+* behavior of spaces. +* - Double quotes are appended to the current word verbatim if they
+ * appear within a single-quoted string portion, and vice
versa.grub-core/kern/xen/cmdline.c new file +2
-0+* - Backslashes may be used to cause the next character to be +* appended to the current word verbatim. This is only useful when
+ * used to escape quotes, spaces, and backslashes, but for
simplicitygrub-core/kern/xen/cmdline.c new file +2
-0+* we allow backslash-escaping anything. +* - After splitting the command line into words, each word is checked to
grub-core/kern/xen/cmdline.c new file +2
-0+* see if it contains an equals sign. +* - If it does, it is split on the equals sign into a key-value pair. The
+ * key is then treated as an variable name, and the value is
treated asgrub-core/kern/xen/cmdline.c new file +2
-0+* the variable's value. +* - If it does not, the entire word is treated as a variable name. The
grub-core/kern/xen/cmdline.c new file +2
-0+* variable's value is implicitly considered to be `1`. +* - All variables detected on the command line are checked to see if their
Quoted 8 lines
Quoted 5 lines
+ * names begin with the string
xen_grub_env_. Variables that
do not pass
+ * this check are discarded, variables that do pass this check
are
+ * exported so they are available to the GRUB configuration.I think not all from this valuable comment landed in the documentation. Please fix it...
Comparing the two side-by-side:
+----------------------------------+----------------------------------+ | Documentation | Comment | +==================================+==================================+ | The command line will be split | The command line is split into | | into space-delimited words. | space-separated words. Single | | Single and double quotes may be | and double quotes may be used to | | used to quote words or portions | suppress the splitting behavior | | of words that contain spaces. | of spaces. | +----------------------------------+----------------------------------+ | (Self-evident, any other | Double quotes are appended to | | behavior involving quotes would | the current word verbatim if | | be extremely unexpected.) | they appear within a single- | | | quoted string, and vice versa. | +----------------------------------+----------------------------------+ | Arbitrary characters may be | Backslashes may be used to cause | | backslash-escaped to make them a | the next character to be | | literal component of a word | appended to the current word | | rather than being parsed as | verbatim. This is only useful | | quotes or word separators. | when used to escape quotes, | | | spaces, and backslashes, but for | | | simplicity we allow backslash- | | | escaping anything. | +----------------------------------+----------------------------------+ | Each word should be a variable | After splitting the command line | | assignment in the format | into words, each word is checked | | ``variable'' or | to see if it contains an equals | | ``variable=value''. | sign. | +----------------------------------+----------------------------------+ | If a variable name and value are | If it does, it is split on the | | both specified, the variable | equals sign into a key-value | | will be set to the specified | pair. The key is then treated as | | value. | a variable name, and the value | | | treated as the variable's value. | +----------------------------------+----------------------------------+ | If only a variable name is | If it does not, the entire word | | specified, the variable's value | is treated as a variable name. | | will be set to ``1''. | The variable's value is | | | implicitly considered to be '1'. | +----------------------------------+----------------------------------+ | Variable names must begin with | All variables detected on the | | the string ``xen_grub_env_''... | command line are checked to see | | If any variable contains an | if their names begin with the | | illegal name, that variable will | string `xen_grub_env_`. | | be ignored. | Variables that do not pass this | | | check are discarded, | +----------------------------------+----------------------------------+ | ...you can pass environment | variables that do pass this | | variables from Xen's dom0 to the | check are exported so they are | | VM through the Xen-provided | available to the GRUB | | kernel command line. | configuration. | +----------------------------------+----------------------------------+
Quoted 5 lines
The only missing detail I see is that single quotes are legal in double-quoted strings and vice versa, though I guess I can make it more explicit that the variables passed on the command line are exported before getting to the example that shows this. Is there anything else you see that's missing?
Exactly, I was thing about single/double quotes here. If other stuff is in the documentation then OK...
Quoted 43 lines
Quoted 14 lines
Quoted 14 lines
grub-core/kern/xen/cmdline.c new file +14
-0+*/ + + current_word_len =PARSER_BASE_WORD_LEN ; + current_word =grub_malloc (current_word_len); +if (current_word ==NULL ) + goto cleanup; + +for (i =0 ; i <MAX_GUEST_CMDLINE ; i++) + { +if (cmdline[i] =='\0' ) + { + cmdline_valid = true; +break ; + }Quoted 8 lines
grub-core/kern/xen/cmdline.c line 176
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +6
-0+ } + +if (cmdline_valid == false) + { +grub_error (GRUB_ERR_BAD_ARGUMENT , +"Command line from Xen is not NUL-terminated" );GRUB errors usually start with lowercase...
Will fix.
Quoted 9 lines
Quoted 9 lines
grub-core/kern/xen/cmdline.c new file +9
-0+grub_print_error (); + goto cleanup; + } + + cmdline_len =grub_strlen (cmdline); +for (i =0 ; i < cmdline_len; i++) + { + current_char = cmdline[i]; +Quoted 8 lines
grub-core/kern/xen/cmdline.c line 190
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +2
-0+/* +* If the previous character was a backslash, append the current
grub-core/kern/xen/cmdline.c new file +3
-0+* character to the word verbatim +*/ +if (parse_flags &PARSER_HIT_BACKSLASH )s/parse_flags/parser_state/
Quoted 4 lines
Hmm, I don't like '
parser_state' as a name because the parser's "state" is the global variables ingrub-core/kern/xen/cmdline.. Maybe 'splitter_state' instead, since this is just the bit of state that the word splitter is concerned with?
I am OK with both...
Daniel
Quoted 197 lines · On Mon, 4 Aug 2025 17:17:43 +0200 Daniel Kiper <[email protected]> wrote:
Quoted 186 lines · Aaron Rainbolt
Quoted 93 lines · On Fri, 1 Aug 2025 14:55:36 +0200 Daniel Kiper <[email protected]> wrote:
Quoted 84 lines · Aaron Rainbolt
Xen traditionally allows customizing guest behavior by passing arguments to the VM kernel via the kernel command line. This is no longer possible when using GRUB with Xen, as the kernel command line is decided by the GRUB configuration file within the guest, not data passed to the guest by Xen.
To work around this limitation, enable GRUB to parse a command line passed to it by Xen, and expose data from the command line to the GRUB configuration as environment variables. These variables can be used in the GRUB configuration for any desired purpose, such as extending the kernel command line passed to the guest. The command line format is inspired by the Linux kernel's command line format.
To reduce the risk of misuse, abuse, or accidents in production, the command line will only be parsed if it consists entirely of 7-bit ASCII characters, only alphabetical characters and underscores are permitted in variable names, and all variable names must start with the string "
xen_grub_env_". This also allows room for expanding the command line arguments accepted by GRUB in the future, should other arguments end up becoming desirable in the future.Signed-off-by Aaron Rainbolt <[email protected]>--- docs/grub.texi | 50 +++++ grub-core/Makefile.core.def | 2 + grub-core/kern/i386/xen/pvh.c | 14 ++ grub-core/kern/main.c | 12 ++ grub-core/kern/xen/cmdline.c | 343 ++++++++++++++++++++++++++++++++++ include/grub/xen.h | 2 + 6 files changed, 423 insertions(+) create mode 100644 grub-core/kern/xen/cmdline.cdocs/grub.texi +0
-0@@ -3271,6 +3271,7 @@ GRUB. Others may be used freely in GRUBconfiguration files. @menu
* Special environment variables::
* Environment block::docs/grub.texi +1
-0+* Passing environment variables through Xen:: @end menu@@ -3871,6 +3872,55 @@ using BIOS or EFI functions (no ATA, USBor IEEE1275). @command{grub-mkconfig} uses this facility to implement @samp{GRUB_SAVEDEFAULT} (@pxref{Simple configuration}).
+@node Passing environment variables through Xen +@section Passing environment variables through Xen
docs/grub.texi +2
-0+ +If you are using a GRUB image as the kernel for a PV or PVH Xenvirtual +machine, you can pass environment variables from Xen's dom0 to the VM through +the Xen-provided kernel command line. When combined with a properly configured +guest, this can be used to customize the guest's behavior on bootup via the +VM's Xen configuration file. +
+GRUB will parse the kernel command line passed to it by Xen during bootup. +The command line will be split into space-delimited words. Single and +double quotes may be used to quote words or portions of words that contain +spaces. Arbitrary characters may be backslash-escaped to make them a literal +component of a word rather than being parsed as quotes or word separators. The +command line must consist entirely of printable 7-bit ASCII characters and +spaces. If a non-printing ASCII character is found anywhere in the command +line, the entire command line will be ignored by GRUB. + +Each word should be a variable assignment in the format ``variable'' or +``variable=value''. Variable names must contain only the characters A-Z, a-z, +and underscore (``_''). Variable names must begin with the string +``xen_grub_env_''. Variable values can contain arbitrary printable 7-bit +ASCII characters and space. If any variable contains an illegal name, that +variable will be ignored. + +If a variable name and value are both specified, the variable will be set to +the specified value. If only a variable name is specified, the variable's +value will be set to ``1''. +
+The following is a simple example of how to use this functionality to append +arbitrary variables to a guest's kernel command line: +
+@exampledocs/grub.texi using BIOS or EFI functions (no ATA, USB or IEEE1275). · line 3912
Quoted 5 lines
docs/grub.texi +5
-0+# In the Xen configuration file for the guest +name = "linux_vm" +type = "pvh" +kernel = "/path/to/grub-i386-xen_pvh.bin" +extra = "xen_grub_env_kernelappend='loglevel=3'"s/kernelappend/kernel_append/
Quoted 5 lines
or maybe even
s/kernelappend/linux_append/
to make it clear it is appended to the "linux" command line...
Will do.
Quoted 10 lines
Quoted 8 lines
docs/grub.texi +7
-0+memory = 1024 +disk = [ "file:/srv/vms/linux_vm.img,sda,w" ] + +# In the guest's GRUB configuration file +menuentry "Linux VM with dom0-specified kernel parameters" @{ + search --set=root --label linux_vm --hint hd0,msdos1 + linux /boot/vmlinuz root=LABEL=linux_vm$@{xen_grub_env_kernelappend@}
Ditto...
Will do.
Quoted 43 lines
Quoted 43 lines
docs/grub.texi +4
-0+ initrd /boot/initrd.img +@} +@end example + @node Modules @chapter Modules(quoted diff) +0
-0b/grub-core/Makefile.core.def index b3f7119..df0f266 100644
grub-core/Makefile.core.def +2
-0@@ -248,6 +248,7 @@ kernel = { xen = term/xen/console.c; xen = disk/xen/xendisk.c; xen = commands/boot.c; + xen = kern/xen/cmdline.c; i386_xen_pvh = commands/boot.c; i386_xen_pvh = disk/xen/xendisk.c;@@ -255,6 +256,7 @@ kernel = { i386_xen_pvh = kern/i386/xen/tsc.c; i386_xen_pvh = kern/i386/xen/pvh.c; i386_xen_pvh = kern/xen/init.c; + i386_xen_pvh = kern/xen/cmdline.c; i386_xen_pvh = term/xen/console.c; ia64_efi = kern/ia64/efi/startup.S;(quoted diff) +0
-0
b/grub-core/kern/i386/xen/pvh.cindex 91fbca8..12df2d8 100644grub-core/kern/i386/xen/pvh.c +2
-0@@ -321,6 +321,8 @@ voidgrub_xen_setup_pvh (void) {grub_addr_t par; +const char *xen_cmdline; +int i;grub_xen_cpuid_base ();grub_xen_setup_hypercall_page ();@@ -352,6 +354,18 @@ grub_xen_setup_pvh (void)grub_xen_mm_init_regions ();Quoted 8 lines
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 359
Quoted 4 lines
grub-core/kern/i386/xen/pvh.c +3
-0grub_rsdp_addr = pvh_start_info->rsdp_paddr; + + xen_cmdline = (const char *) pvh_start_info->cmdline_paddr; +for (i =0 ; i <MAX_GUEST_CMDLINE ; i++)Oh,
MAX_GUEST_CMDLINEis a too generic. May I ask you to rename it toGRUB_XEN_MAX_GUEST_CMDLINE? This should be done in separate patch preceding this one.Sure.
Quoted 13 lines
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 361
Quoted 2 lines
grub-core/kern/i386/xen/pvh.c +2
-0+ { +if (xen_cmdline[i] =='\0' )I cannot see much sense in this check. Please look below...
grub-core/kern/i386/xen/pvh.c grub_xen_setup_pvh (void) · line 366
Quoted 5 lines
grub-core/kern/i386/xen/pvh.c +3
-0+ { + grub_strncpy ((char *) grub_xen_start_page_addr->cmd_line, + (char *) pvh_start_info->cmdline_paddr,s/char */const char */
Quoted 2 lines
Is it always guaranteed that
pvh_start_info->cmdline_paddrhaveMAX_GUEST_CMDLINEsize? If yes then...Quoted 9 lines
It is not guaranteed. I tested this under Qubes OS, and it is unfortunately very possible to pass a guest command line longer than
MAX_GUEST_CMDLINEviapvh_start_info->cmdline_paddr. I do not know of any documentation specifying what the "real" maximum length is in this instance (if any), but in any event the string ultimately has to be crammed into an array that is onlyMAX_GUEST_CMDLINElong. Originally I wrote this to truncate the command line in this situation, but later decided that discarding the command line would be safer than truncation.
Quoted 3 lines
I think you are confusing source,
grub_xen_start_page_addr->cmd_line, and destination,pvh_start_info->cmdline_paddr. I am asking about the destination...
The destination is grub_xen_start_page_addr->cmd_line. pvh_start_info->cmdline_paddr is the *source*, not the destination. grub_xen_start_page_addr->cmd_line is a MAX_GUEST_CMDLINE-long int8_t array, so yes, the destination is guaranteed to always have MAX_GUEST_CMDLINE size.
Quoted 23 lines
Quoted 5 lines
(When booting a VM in PV mode, Xen does guarantee the command line will not be longer than
MAX_GUEST_CMDLINEand will simply return a truncated command line. There is no way to detect this condition to my awareness, so in PV mode, we simply live with the truncation since we aren't given another option.)OK...
Quoted 7 lines
Quoted 6 lines
grub_memset((void *)pvh_start_info->cmdline_paddr, 0,MAX_GUEST_CMDLINE);grub_strncpy((char *)grub_xen_start_page_addr->cmd_line, (const char *)pvh_start_info->cmdline_paddr,MAX_GUEST_CMDLINE- 1);... and you are done...
Quoted 7 lines
This would truncate the command line rather than discarding it. If the goal is consistency with Xen's PV mode, then I can switch to this, but I don't like the idea of booting a guest with corrupted data inserted randomly into the grub.cfg file. (Like mentioned above, there isn't any other option when using PV mode, but just because PV mode does things dangerously doesn't mean we have to when running in PVH mode.)
Quoted 3 lines
OK, but please remember you have to ensure the string is NUL-terminated after
grub_strncpy(). Potentially you could also usegrub_strlen()to make a check and add NUL in proper place...
The code does ensure the string is NUL-terminated I believe, unless grub_strncpy doesn't behave like POSIX strncpy. If a '\0' is found anywhere in pvh_start_info->cmdline_paddr (the source), then we grub_strncpy the string to grub_xen_start_page_addr->cmd_line, specifying the size of the destination buffer as MAX_GUEST_CMDLINE. strncpy pads the rest of the buffer with NUL bytes. In the worst case scenario, the source is exactly MAX_GUEST_CMDLINE-1 bytes long plus a NUL at the end, in which case strncpy will copy MAX_GUEST_CMDLINE-1 bytes and then add one byte of NUL padding. If the sources consists of MAX_GUEST_CMDLINE non-NUL bytes, the copy won't happen at all because a NUL will never be found in the first MAX_GUEST_CMDLINE bytes of the source.
Using grub_strlen as a sanity check sounds good. If after the copy, grub_strlen((char *) grub_xen_start_page_addr->cmd_line) != (i - 1), then we know something is wrong and can halt the system.
Quoted 102 lines
Quoted 102 lines
Quoted 26 lines
Quoted 26 lines
grub-core/kern/i386/xen/pvh.c +4
-0+ MAX_GUEST_CMDLINE); +break ; + } + } }
grub_err_tgrub-core/kern/main.c +1
-0@@ -37,6 +37,10 @@#include <grub/machine/memory.h> #endif +#if defined (GRUB_MACHINE_XEN) || defined(
GRUB_MACHINE_XEN_PVH) +#include <grub/xen.h>grub-core/kern/main.c +2
-0+#endif +static bool cli_disabled = false;static bool cli_need_auth = false;@@ -351,6 +355,14 @@ grub_main (void)grub_env_export ("root" );grub_env_export ("prefix" );Quoted 11 lines
Quoted 8 lines
grub-core/kern/main.c +2
-0+/* +* Parse command line parameters from Xen and export them as environment
grub-core/kern/main.c +3
-0+* variables +*/ +#if defined (GRUB_MACHINE_XEN) || defined(
GRUB_MACHINE_XEN_PVH)
+grub_parse_xen_cmdline();Please move this call to the
grub-core/kern/xen/init.c:grub_machine_init().Will do.
Quoted 49 lines
Quoted 37 lines
grub-core/kern/main.c +2
-0+#endif +/* Reclaim space used for modules. */ reclaim_module_space ();(quoted diff) +0
-0
b/grub-core/kern/xen/cmdline.cnew file mode 100644 index 0000000..03dd88fgrub-core/kern/xen/cmdline.c new file +5
-0@@ -0,0 +1,343 @@ +/* +* GRUB -- GRand Unified Bootloader +* Copyright (C) 2025 Free Software Foundation, Inc. +* +* GRUB is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * GRUB is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with GRUB. If not, see
<http://www.gnu.org/licenses/>.
+ */grub-core/kern/xen/cmdline.c new file +2
-0+ +#include <grub/env.h> grub-core/kern/xen/cmdline.c line 29
Quoted 10 lines
grub-core/kern/xen/cmdline.c new file +10
-0+#include <grub/misc.h> +#include <grub/mm.h> +#include <grub/xen.h> + +enum parse_flags +{ +PARSER_HIT_BACKSLASH =0x1 , +PARSER_IN_SINGLE_QUOTES =0x2 , +PARSER_IN_DOUBLE_QUOTES =0x4 , +};typedef
parse_flagsparse_flags_t;Quoted 1 line
... and use
parse_flags_tinstead below...Will do.
Quoted 1 line
And probably this should be a local variable...
See below for comments on globals in the parser.
Quoted 4 lines
grub-core/kern/xen/cmdline.c
Quoted 2 lines
grub-core/kern/xen/cmdline.c new file +2
-0+ +#define PARSER_BASE_WORD_LEN 16This constant begs for a few words of comment...
Quoted 7 lines
Quoted 5 lines
Will add. This is just the initial length of the dynamically allocated buffer for storing each "word" of the command line, but it is confusing as written. Perhaps it should be renamed to
PARSER_WORD_BUF_START_LENor similar, to make it clear this isn't a string length, but a buffer length?s/length/size/ then... However, then why 16 not, e.g., 32?
My original iteration of the patch didn't require xen_grub_env_ at the beginning of every variable name, so 16 was a reasonable estimate of how long most "words" would end up, and I wanted to use the smallest reasonable value here. That being said, xen_grub_env_ is required now, which is already 13 bytes long, so maybe 32 is a more reasonable value. (Or, depending on where GRUB's allocator aligns things, maybe this should be a large number like MAX_GUEST_CMDLINE, so that we don't ever have to reallocate?)
Quoted 28 lines
Quoted 21 lines
Quoted 9 lines
grub-core/kern/xen/cmdline.c line 38
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +6
-0+static grub_size_t word_list_len; +static char **word_list; +static grub_size_t current_word_len; +static grub_size_t current_word_pos; +static char *current_word; +static char current_char;I have a feeling that most if not all of this variables should be local in a given function...
I made them globals because making them local would have required an awful lot of parameter "shuttling" that I believed made the code less readable. For instance, the
append_word_to_listfunction right now has no parameters and can be called very simply by the parser whenever it is needed. If all variables used were local, the function would have to have a signature akin to:static bool append_word_to_list(grub_size_t
*current_word_pos_ref,
grub_size_t*current_word_len_ref, char*current_word,grub_size_t*word_list_len_ref, char **word_list)Quoted 6 lines
IMO this is difficult to read and frustrating to call (possibly even error-prone). Ultimately the variables are "local" to the parser, and the functions are just there to split up the parser's algorithm to avoid repetition. They all ultimately operate on the same state, so having the state variables static but global within the file fits the current parser design well.
Quoted 3 lines
First of all, think about the design. If you are sure it is optimal then please use struct and a pointer to pass as many argument as you need...
Will do.
Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
Quoted 8 lines
grub-core/kern/xen/cmdline.c new file +5
-0+static bool +append_char_to_word (bool allow_null) +{ +/* +* Fail if the current char is outside of the range 0x20 to
0x7E. If
+ *allow_nullis true, make an exception for0x00. This is a
safeguardCould you elaborate here when
allow_null== true is useful?
Quoted 5 lines
Quoted 3 lines
Usually when appending characters to a word, you aren't going to be appending null characters, thus
append_char_to_wordusually rejectss/null/NUL/...
Will switch terminology from now on.
Quoted 13 lines
Quoted 3 lines
those so as to make it harder to mess things up. However, the string does need to be null-terminated, and thus once a command line word is
Ditto... In general, even it is correct, I prefer to use NUL instead of null/NULL to avoid confusion...
Quoted 6 lines
fully loaded into
current_word, it is necessary to add the null terminator on the end. In this instance the parser setscurrent_charto '\0' and then calls theappend_char_to_wordfunction withallow_nullset to true, so that the function knows that the addition of a null is intentional here.
Quoted 8 lines
Quoted 5 lines
(In retrospect, if
allow_nullis set to true, the only thingappend_char_to_wordshould append is a null character, it should reject anything else in that instance. Otherwise someone could accidentally append something other than a null when they meant to append a null.)Is not it simpler to open code this instead of complicating this function?
Due to the possibility of having to reallocate the buffer, I don't think so. If however we switch to using a buffer than doesn't need reallocation, then it would be simpler to do that. I'll experiment with it before sending the next patch version.
Quoted 12 lines
Quoted 11 lines
Quoted 5 lines
grub-core/kern/xen/cmdline.c line 48
Quoted 3 lines
grub-core/kern/xen/cmdline.c new file +3
-0+* against likely-invalid data. +*/ + if ( (!(current_char >= 0x20) || !(current_char <= 0x7E) )
grub_isprint()?That would work, I wasn't aware that existed. Maybe a mention of some valuable GRUB internal API functions that are likely to remain stable could be added to the GRUB development manual? (Or just a reference to header files where useful things like this are defined.)
Quoted 3 lines
Certainly it is a good idea. In general you can assume the GRUB has a lot of POSIX compatible functions which names are prefixed with "
grub_".
Nice, good to know.
Quoted 84 lines
Quoted 84 lines
Quoted 4 lines
Quoted 1 line
+ && (
current_char!= '\0' ||allow_null== false))I would drop redundant spaces between "(" and ")" and move "&&" to the end of first line of "if".
Will do, though I'm likely to rewrite this conditional anyway so that anything other than '\0' will be rejected when
allow_null == true.Quoted 7 lines
grub-core/kern/xen/cmdline.c line 54
Quoted 5 lines
grub-core/kern/xen/cmdline.c new file +5
-0+return false; + +if (current_word_pos == current_word_len) + { + current_word_len *=2 ;You can do this in the argument of the function below...
I mean, yes, technically I can, but that's a lot less readable to me. I can't find anywhere else in GRUB that uses that style (using
grep -ri '\*='to search), and can find a few spots that use a style similar to the one I've used here:*
util/grub-install.cin functiondevice_map_check_duplicates
*grub-core/osdep/windows/platform.cin functionget_efi_variable
*grub-core/osdep/unix/platform.cin functionget_ofpathnameQuoted 12 lines
grub-core/kern/xen/cmdline.c line 64
Quoted 11 lines
+
current_word=grub_realloc(current_word,current_word_len);grub-core/kern/xen/cmdline.c new file +9
-0+if (current_word ==NULL ) + { + current_word_len /=2 ; +return false; + } + } + + current_word[current_word_pos] = current_char; + current_word_pos++;Quoted 1 line
Again, you can do this operation in the "[]" above...
Will do. (This does seem to be a much more common way to write things in GRUB than what I've done.)
Quoted 10 lines
grub-core/kern/xen/cmdline.c line 72
Quoted 8 lines
grub-core/kern/xen/cmdline.c new file +8
-0+return true; +} + +static bool +append_word_to_list (void ) +{ +/* No-op on empty words. */ +if (current_word_pos ==0 )This should be probably an argument for the function...
See above for parser state and global variables rationale.
Quoted 12 lines
Quoted 12 lines
grub-core/kern/xen/cmdline.c new file +7
-0+return true; + + current_char ='\0' ; +if (append_char_to_word (true) == false) + { + grub_error (GRUB_ERR_BUG, + "couldn't append null terminator to wordduring Xen cmdline parsing");
grub-core/kern/xen/cmdline.c new file +4
-0+grub_print_error (); +grub_exit (); + } +Quoted 8 lines
grub-core/kern/xen/cmdline.c line 88
Quoted 5 lines
grub-core/kern/xen/cmdline.c new file +5
-0+ current_word_len =grub_strlen (current_word) +1 ; + current_word =grub_realloc (current_word, current_word_len); +if (current_word ==NULL ) +return false; + word_list_len++;Again this, OK ++word_list_len to be precise, can be done in a function argument below...
grep -ri 'alloc.*++'doesn't show me any instance of this style anywhere else in the GRUB codebase, and I find it much more difficult to read since now I have to think about incrementingword_list_len's value and returning it and multiplying the returned value all at the same time.grub-core/osdep/unix/platform.cuses the style I've used here.
Quoted 7 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
+
word_list=grub_realloc(word_list,word_list_len* sizeof (char *));
word_list=grub_realloc(word_list, ++word_list_len * sizeof (char *a));Is it really difficult to read? I do not think so...
I find it harder to read personally, but I'm fine with switching to it if you'd prefer.
Quoted 121 lines
[...]
Quoted 119 lines
Quoted 47 lines
Quoted 47 lines
grub-core/kern/xen/cmdline.c new file +4
-0+void +grub_parse_xen_cmdline (void ) +{ + const char *cmdline = (const char *)
grub_xen_start_page_addr->cmd_line;grub-core/kern/xen/cmdline.c new file +11
-0+grub_size_t cmdline_len; +bool cmdline_valid = false; +char **param_keys =NULL ; +char **param_vals =NULL ; +grub_size_t param_dict_len =0 ; +grub_size_t param_dict_pos =0 ; +enum parse_flags parse_flags =0 ; +grub_size_t i =0 ; + +/* +* The following algorithm is used to parse the Xen command line:
grub-core/kern/xen/cmdline.c new file +3
-0+* +* - The command line is split into space-separated words. +* - Single and double quotes may be used to suppress the splitting
grub-core/kern/xen/cmdline.c new file +2
-0+* behavior of spaces. +* - Double quotes are appended to the current word verbatim if they
+ * appear within a single-quoted string portion, and vice
versa.
+ * - Backslashes may be used to cause the next character
to be
+ * appended to the current word verbatim. This is only
useful when
+ * used to escape quotes, spaces, and backslashes, but
for simplicitygrub-core/kern/xen/cmdline.c new file +2
-0+* we allow backslash-escaping anything. +* - After splitting the command line into words, each word is checked to
grub-core/kern/xen/cmdline.c new file +2
-0+* see if it contains an equals sign. +* - If it does, it is split on the equals sign into a key-value pair. The
+ * key is then treated as an variable name, and the
value is treated asgrub-core/kern/xen/cmdline.c new file +2
-0+* the variable's value. +* - If it does not, the entire word is treated as a variable name. The
grub-core/kern/xen/cmdline.c new file +2
-0+* variable's value is implicitly considered to be `1`. +* - All variables detected on the command line are checked to see if their
+ * names begin with the stringxen_grub_env_. VariablesQuoted 8 lines
Quoted 5 lines
that do not pass
+ * this check are discarded, variables that do pass this
check are
+ * exported so they are available to the GRUB
configuration.I think not all from this valuable comment landed in the documentation. Please fix it...
Comparing the two side-by-side:
+----------------------------------+----------------------------------+ | Documentation | Comment | +==================================+==================================+ | The command line will be split | The command line is split into | | into space-delimited words. | space-separated words. Single | | Single and double quotes may be | and double quotes may be used to | | used to quote words or portions | suppress the splitting behavior | | of words that contain spaces. | of spaces. | +----------------------------------+----------------------------------+ | (Self-evident, any other | Double quotes are appended to | | behavior involving quotes would | the current word verbatim if | | be extremely unexpected.) | they appear within a single- | | | quoted string, and vice versa. | +----------------------------------+----------------------------------+ | Arbitrary characters may be | Backslashes may be used to cause | | backslash-escaped to make them a | the next character to be | | literal component of a word | appended to the current word | | rather than being parsed as | verbatim. This is only useful | | quotes or word separators. | when used to escape quotes, | | | spaces, and backslashes, but for | | | simplicity we allow backslash- | | | escaping anything. | +----------------------------------+----------------------------------+ | Each word should be a variable | After splitting the command line | | assignment in the format | into words, each word is checked | | ``variable'' or | to see if it contains an equals | | ``variable=value''. | sign. | +----------------------------------+----------------------------------+ | If a variable name and value are | If it does, it is split on the | | both specified, the variable | equals sign into a key-value | | will be set to the specified | pair. The key is then treated as | | value. | a variable name, and the value | | | treated as the variable's value. | +----------------------------------+----------------------------------+ | If only a variable name is | If it does not, the entire word | | specified, the variable's value | is treated as a variable name. | | will be set to ``1''. | The variable's value is | | | implicitly considered to be '1'. | +----------------------------------+----------------------------------+ | Variable names must begin with | All variables detected on the | | the string ``xen_grub_env_''... | command line are checked to see | | If any variable contains an | if their names begin with the | | illegal name, that variable will | string `xen_grub_env_`. | | be ignored. | Variables that do not pass this | | | check are discarded, | +----------------------------------+----------------------------------+ | ...you can pass environment | variables that do pass this | | variables from Xen's dom0 to the | check are exported so they are | | VM through the Xen-provided | available to the GRUB | | kernel command line. | configuration. | +----------------------------------+----------------------------------+
Quoted 8 lines
Quoted 5 lines
The only missing detail I see is that single quotes are legal in double-quoted strings and vice versa, though I guess I can make it more explicit that the variables passed on the command line are exported before getting to the example that shows this. Is there anything else you see that's missing?
Exactly, I was thing about single/double quotes here. If other stuff is in the documentation then OK...
Will add.
--
Aaron
Quoted 44 lines
Quoted 44 lines
Quoted 15 lines
Quoted 15 lines
grub-core/kern/xen/cmdline.c new file +15
-0+*/ + + current_word_len =PARSER_BASE_WORD_LEN ; + current_word =grub_malloc (current_word_len); +if (current_word ==NULL ) + goto cleanup; + +for (i =0 ; i <MAX_GUEST_CMDLINE ; i++) + { +if (cmdline[i] =='\0' ) + { + cmdline_valid = true; +break ; + } + }Quoted 8 lines
Quoted 6 lines
grub-core/kern/xen/cmdline.c new file +5
-0+ +if (cmdline_valid == false) + { + grub_error (GRUB_ERR_BAD_ARGUMENT, + "Command line from Xen is notNUL-terminated");
GRUB errors usually start with lowercase...
Will fix.
Quoted 17 lines
Quoted 12 lines
grub-core/kern/xen/cmdline.c new file +11
-0+grub_print_error (); + goto cleanup; + } + + cmdline_len =grub_strlen (cmdline); +for (i =0 ; i < cmdline_len; i++) + { + current_char = cmdline[i]; + +/* +* If the previous character was a backslash, append the current
grub-core/kern/xen/cmdline.c line 190
Quoted 3 lines
grub-core/kern/xen/cmdline.c new file +3
-0+* character to the word verbatim +*/ +if (parse_flags &PARSER_HIT_BACKSLASH )s/parse_flags/parser_state/
Quoted 8 lines
Quoted 4 lines
Hmm, I don't like '
parser_state' as a name because the parser's "state" is the global variables ingrub-core/kern/xen/cmdline.. Maybe 'splitter_state' instead, since this is just the bit of state that the word splitter is concerned with?I am OK with both...
Daniel
_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel