Build linux with busybox

Build linux with busybox

В данной статье мы соберем Linux Kernel и запустим на qemu с busybox.

Для начала скачайте Busybox:

Нужный вам Linux Kernel:

Несмотря на безудержный рост графических оболочек и «дружелюбных» интерфейсов, представить себе UNIX без командной строки и основных утилит в наши дни невозможно. Многочисленные интерпретаторы и базовые системные утилиты не стоят на месте, растут и развиваются, что неизбежно ведет и к увеличению их объема. В то же время существуют сферы деятельности, в которых компактность любых приложений по очевидным причинам очень важна, например, во встраиваемых устройствах. Вместе с тем во многих случаях не требуется значительная часть той функциональности, которая присуща базовым утилитам «общего назначения».

Для решения этих проблем еще в середине 90-х Брюсом Перенсом (Bruce Perens) был создан пакет BusyBox. Сейчас проект позиционируется как «швейцарский нож для встраиваемых Linux-систем» и в первую очередь ориентирован на использование в небольших дистрибутивах GNU/Linux. Распространяется под второй версией лицензии GNU GPL.

BusyBox представляет собой единственный исполняемый файл, при запуске которого загружается полноценный командный интерфейс. Как гласит официальная документация BusyBox, для формирования минимальной версии GNU/Linux к этому достаточно добавить лишь ядро ОС и каталоги /etc, /dev.

Одна из главных целей, которую преследуют разработчики BusyBox, – оптимизированность и компактность кода – расчет на ограниченность памяти. Это не только вновь говорит о плюсах его использования во встраиваемых устройствах, но и хорошо сочетается с другим подходом в духе UNIX way: высокий уровень настраиваемости (в бинарный файл BusyBox можно включить только необходимые компоненты).

Еще на стадии компиляции (а точнее, до самого процесса сборки) можно выбрать только те базовые утилиты, которые нужны. Реализовано это в стиле настройки ядра Linux. Вместо более распространенного среди собираемых с automake приложений способа в виде скрипта «configure» для предварительной конфигурации BusyBox нужно выполнить одну из следующих команд:

Аргумент «config» инициирует запуск «вопросника» со списком доступных опций и базовых утилит, предлагающего проставлять «Y» или «N» на месте нужных и ненужных возможностей соответственно.

Аргумент «menuconfig» вызывает более удобную конфигурацию в виде меню с интерфейсом на базе curses.

Аргумент «defconfig» автоматически включает все доступные опции, подготавливая к сборке BusyBox «общего назначения».

Так же, как и в случае с ядром Linux, после настройки создается конфигурационный файл .config, к которому можно затем всегда возвращаться командой:

Это актуально при переходе на более новую версию BusyBox со старой конфигурацией (чтобы при настройке работать только с появившимися в очередном релизе опциями).

По умолчанию, если до вызова «make menuconfig» не существовал файл .config, make автоматически предварительно запускается с аргументом «defconfig». Таким образом, пользователю останется только отключить ненужные возможности. Предусмотрен и обратный вариант: запуск make с «allnoconfig» отключает все опции, чтобы после этого можно было выбрать только то, что нужно.

Далее все традиционно:

Помимо альтернативного набора coreutils (ls, cat, mv, cp, rm, chmod, df, ln, date, wc, nice, test…) в состав BusyBox входит и множество других программ.

Читайте также:  Шаблон имени файла linux

Для работы с архивами есть такие утилиты, как tar, gzip, bzip2, ar, zip, rpm, dpkg. Для обработки содержимого файлов есть как awk, sed, patch, так и текстовые редакторы ed и vi.

Широко представлены сетевые средства: и клиентские, и серверные. Среди демонов выделю httpd, dnsd, telnetd, inetd, udhcpd. Для FTP есть ftpget, ftpput и клиент tftp. Кроме того, присутствует и собственная версия GNU wget. Из прочих стандартных утилит: ifconfig, route, traceroute, ping/ping6, netstat, nslookup, arp и arping.

Далее в меню ставим галочку в:
-> Busybox Settings
-> Build Options
[ ] Build BusyBox as a static binary (no shared libs)

сохраняем и выходим.

CONFIG_PREFIX=./../busybox_rootfs — указывает на папочку, куда busybox сложит выходные файлы.

NOTE initramfs:

Initrd (сокращение от англ. Initial RAM Disk, диск в оперативной памяти для начальной инициализации) — временная файловая система, используемая ядром Linux при начальной загрузке. Initrd обычно используется для начальной инициализации перед монтированием «настоящих» файловых систем.

Начиная с версии ядра 2.6 пришли к понятию initramfs. Это, обычно сжатый cpio архив, в котором располагается мини-система busybox, которая выполняет ту же роль, что и initrd.

Можно использовать ее для тестирования какой либо функциональности встраиваемой системы — когда вы просто хотите поместить всю систему в память, чтоб она быстро работала, при этом вам не важно, сохранятся ли ваши изменения после перезагрузки.

Содержимое initramfs делается путем создания cpio-архива.

Все файлы, инструменты, библиотеки, настройки конфигурации (если они применимы), и т.д. помещаются в cpio-архив. Этот архив затем сжимается с использованием утилиты gzip и сохраняется в том же месте, что и ядро Linux. Далее, загрузчик передаст его ядру Linux во время загрузки, чтобы ядро знало о том, что требуется initramfs.

При его обнаружении, ядро Linux создаст файловую систему tmpfs, извлечет на нее содержимое архива и затем запустит сценарий init, расположенный в корневом каталоге файловой системы tmpfs.

Теперь создадим initramfs с нашим построенным busybox:

Note: node можно не создавать через mknod, а скопировать из основной ОС.

Далее копируем все из папки busybox_rootfs в папку rootfs. Таким образом, в нашем initrd появятся утилиты Linux, которые реализует busybox.

Создаем в корне rootfs файл init :

Делаем его исполняемым:

Создаем сам initramfs:

Собираем ядро

Сжатый образ ядра — /arch/x86_64/boot/bzImage .

Копируем bzImage и rootfs.cpio.gz в отдельную директорию, заходим в нее и

Запускаем qemu

Дополнение

Initrd встроенный в ядро

Кроме того, вы можете скомпилировать initrd вместе с ядром. Для этого надо при конфигурировании ядра указать путь к rootfs (см. ниже):

А в /path_to_rootfs/rootfs у вас должен находится сам rootfs ( /bin, /dev /dev/sda /dev/console и т.д. — см. описание выше). Не забываем создать и init скрипт.

Тогда после компиляции ядра, qemu можно запускать, не указывая initrd:

Переключение с Initrd на rootfs на диске

Сначала создадим диск, на который поместим rootfs:

Создаем rootfs тут (в /mnt), также как и было описано выше ( /bin, /dev /dev/sda /dev/console и т.д. — см. описание выше). Не забываем создать и init скрипт.

Теперь у нас на образе диска hdd находится rootfs.

Читайте также:  Division by zero windows это

Для запуска qemu c диском используем сл. команду:

Когда ядро загрузится с initrd, для переключения к rootfs на диске, выполним следующие команды:

Загрузка без Initrd

Т.к. у на rootfs есть уже на диске, то грузиться с initrd не обязательно. Для того чтобы сразу грузить rootfs с диска, надо ядру (в загрузчике) передать параметр root.

В qemu это делается через append:

Note: для компиляции под 32-bit intel используем:

  • Busybox — в build options выставить в CFLAGS флаги -m32 -march=i386, в LDFLAGS флаг -m32
  • Linux kernel — вместо x86_64_defconfig используем i386_defconfig
  • qemu — для запуска используем команду qemu-system-i386

Источник

chrisdone / gist:02e165a0004be33734ac2334f215380e

Configure the kernel according the following:

Build the kernel:

Configure Busybox according the following:

Create an initramfs:

Add a $INITRAMFS_BUILD/init script to the initramfs with the following content:

Create the initramfs archive:

Run and see ( a x to quit)

Note: for better performance, add the -enable-kvm option if your host has KVM enabled:

We assume that a toolchain is available in /opt/toolchains/x86_64-unknown-linux-gnu with prefix x86_64-unknown-linux-gnu , gcc version 5.x, kernel headers series 4.3.x, glibc C library and C++ support. These are reasonable defaults if you are using a toolchain generated by crosstool-NG. Adapt to your own situation. Notes:

  • You cannot use the native toolchain of your host computer (see Buildroot documentation to understand why).
  • If you do not have a toolchain already, you can build one using crosstool-NG (or Buildroot itself) and reuse it for other projects.
  • crosstool-NG is the recommended tool to build your own toolchain but avoid using uClibc (no IPV6 support), prefer uClibc-ng or glibc.
  • You can also use the built-in toolchain of Buildroot but be aware that it will take way longer than using an existing toolchain. Be also aware that in many cases you will have to re-build the toolchain after modifying the Buildroot configuration.
  • No yet convinced? Please use crosstool-NG, build and use your own toolchain.

Configure Buildroot according the following:

Save the configuration and build:

Add a $BUILDROOT_BUILD/overlay/init script to the overlay with the following content:

Build the root filesystem:

Run and see ( a x to quit)

Note: for better performance, add the -enable-kvm option if your host has KVM enabled.

Add and run a custom user application

Create a new directory for the custom user applications:

Add an application source file $APPS/hello_world.c with the following content:

Add a $APPS/Makefile with the following content (replace the CROSS_COMPILE definition with whatever is appropriate in your specific case):

Compile the application, copy it in the Buildroot overlay directory and re-build the root filesystem:

Run and see ( a x to quit)

Note: for better performance, add the -enable-kvm option if your host has KVM enabled.

Add loadable module support to the Linux kernel

Change the kernel configuration according the following:

Re-build the kernel and its modules (none, in our case) and install the modules in the Buildroot overlay directory:

Add a custom user module

Create a new directory for the custom user modules:

Читайте также:  Стандартные обои windows 1920x1080

Add a module source file $MODULES/hello_world.c with the following content:

Add a $MODULES/Makefile with the following content:

Compile the module, install it in the Buildroot overlay directory and re-build the root filesystem:

Run and see ( a x to quit)

Note: for better performance, add the -enable-kvm option if your host has KVM enabled.

Источник

gavz / gist:9613c2ca79048a62cde6ae3386db0c14

Configure the kernel according the following:

Build the kernel:

Configure Busybox according the following:

Create an initramfs:

Add a $INITRAMFS_BUILD/init script to the initramfs with the following content:

Create the initramfs archive:

Run and see ( a x to quit)

Note: for better performance, add the -enable-kvm option if your host has KVM enabled:

We assume that a toolchain is available in /opt/toolchains/x86_64-unknown-linux-gnu with prefix x86_64-unknown-linux-gnu , gcc version 5.x, kernel headers series 4.3.x, glibc C library and C++ support. These are reasonable defaults if you are using a toolchain generated by crosstool-NG. Adapt to your own situation. Notes:

  • You cannot use the native toolchain of your host computer (see Buildroot documentation to understand why).
  • If you do not have a toolchain already, you can build one using crosstool-NG (or Buildroot itself) and reuse it for other projects.
  • crosstool-NG is the recommended tool to build your own toolchain but avoid using uClibc (no IPV6 support), prefer uClibc-ng or glibc.
  • You can also use the built-in toolchain of Buildroot but be aware that it will take way longer than using an existing toolchain. Be also aware that in many cases you will have to re-build the toolchain after modifying the Buildroot configuration.
  • No yet convinced? Please use crosstool-NG, build and use your own toolchain.

Configure Buildroot according the following:

Save the configuration and build:

Add a $BUILDROOT_BUILD/overlay/init script to the overlay with the following content:

Build the root filesystem:

Run and see ( a x to quit)

Note: for better performance, add the -enable-kvm option if your host has KVM enabled.

Add and run a custom user application

Create a new directory for the custom user applications:

Add an application source file $APPS/hello_world.c with the following content:

Add a $APPS/Makefile with the following content (replace the CROSS_COMPILE definition with whatever is appropriate in your specific case):

Compile the application, copy it in the Buildroot overlay directory and re-build the root filesystem:

Run and see ( a x to quit)

Note: for better performance, add the -enable-kvm option if your host has KVM enabled.

Add loadable module support to the Linux kernel

Change the kernel configuration according the following:

Re-build the kernel and its modules (none, in our case) and install the modules in the Buildroot overlay directory:

Add a custom user module

Create a new directory for the custom user modules:

Add a module source file $MODULES/hello_world.c with the following content:

Add a $MODULES/Makefile with the following content:

Compile the module, install it in the Buildroot overlay directory and re-build the root filesystem:

Run and see ( a x to quit)

Note: for better performance, add the -enable-kvm option if your host has KVM enabled.

Источник

Оцените статью