修改GRUB2源码与编译安装流程

it2026-01-10  8

能进来这个文章的,基本也不需要我介绍GRUB是什么了。 如果我们需要GRUB的源代码,或者把我们自己编写的模块加入GRUB中,我们要怎么做呢?

首先我们创建一个目录,下载并解压grub的源码。

mkdir grub cd grub wget ftp://ftp.gnu.org/gnu/grub/grub-2.04.tar.gz tar zxvf grub-2.04.tar.gz

然后我们就可以得到这样的目录 不知道为什么,有时候直接把文件拖进虚拟机,这个文件夹会丢失很多文件(就算是压缩包也会在里面丢文件,可能是centos系统和VMware的问题),所以还是建议通过网络重新下载。

在grub-core文件夹里有个hello的文件夹,然后里面有个hello.c文件。

这个“hello”属于grub的一个指令模块,是grub专门写的一个编写grub模块的一个测试demo。

/* hello.c - test module for dynamic loading */ /* * GRUB -- GRand Unified Bootloader * Copyright (C) 2003,2007 Free Software Foundation, Inc. * Copyright (C) 2003 NIIBE Yutaka <gniibe@m17n.org> * * 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/types.h> #include <grub/misc.h> #include <grub/mm.h> #include <grub/err.h> #include <grub/dl.h> #include <grub/extcmd.h> #include <grub/i18n.h> GRUB_MOD_LICENSE ("GPLv3+"); static grub_err_t grub_cmd_hello (grub_extcmd_context_t ctxt __attribute__ ((unused)), int argc __attribute__ ((unused)), char **args __attribute__ ((unused))) { grub_printf ("%s\n", _("Hello World")); return 0; } static grub_extcmd_t cmd; GRUB_MOD_INIT(hello) { cmd = grub_register_extcmd ("hello", grub_cmd_hello, 0, 0, N_("Say `Hello World'."), 0); } GRUB_MOD_FINI(hello) { grub_unregister_extcmd (cmd); }

在默认的情况下,我们在grub的命令行界面敲入 “hello”时,grub命令行就会输出“Hello World”的字符串。

目前来说,怎么写指令模块我还没摸熟,但是我们可以通过修改这个hello.c来测试我们的grub是否被修改了。 我们将字符串“Hello World” 改为 “HuaWei NB!” 。 然后保存。 接下来进行我们的编译安装步骤。 回到“grub-2.04”目录下

su #输入密码后切换管理员 ./configure --prefix=/usr --sysconfdir=/etc make make install

都执行完后,输入指令进行安装(特别注意这里的是grub2-install 而不是grub-install输错了系统无法正常引导进系统,搞不好就重装系统了)

grub2-install /dev/sda

参数说明: dev/sda :当前系统所安装在的哪个磁盘,是磁盘,不是磁盘分区,如果输入的是分区,将会报错。

可以通过fdisk -l 指令查看所有磁盘及分区

fdisk -l

重启验证一下。(在grub界面的时候键入c,就可以进入grub的命令行,Ubuntu需要在启动时一直敲击esc才会出现grub界面) 到此,安装成功。

还有一点要说的是,我们的grub命令行使用的每个模块,都存放在"/boot/grub2/i386-pc"目录下

把修改过的hello.mod复制到其他的系统中,依然是可以使用的。比如我修改编译安装grub的系统是centos,我把这个hello.mod复制到Ubuntu或者是deepin系统中,替换其原有的hello.mod,我无需全部重新编译安装,可以直接使用。 替换到深度系统的grub中的hello.mod后,在grub命令行中输入hello指令。 而且注意这里Linux内核都不一样,grub版本也不一样,也是能用的。(其他版本未验证,初步结果)

最新回复(0)