What is uimage in linux

What is Initrd Image? How to Create Initrd Image in Linux

The boot process of a Linux system involves a number of stages. These include the BIOS initialization, reading the MBR, the bootloader, kernel initialization and the init process.

The initrd (initial ramdisk) plays a very significant role in booting up the system. This tutorial discusses initrd ramdisk and how we can create it if it needs to be recreated.

GRUB bootloader and initrd

A bootloader is the first software program that runs during the startup process. It is responsible for booting the operating system. Bootloader loads the kernel into the memory and the kernel mounts the root partition so that it can start the first process, i.e. init process. Let us have a look at the commands that the bootloader executes for these tasks:

The first command «root (hd0,0)» tells the bootloader that kernel image is present on first partition of the hard disk hd0 (i.e. hd0,0). This is the location of the kernel image.

The second command is the kernel image itself. In this case, it is «/vmlinuz-2.6.18-238.el5». The arguments passed to this command are ro and root. ro specifies the read only mode and root tells the partition on which root filesystem resides. The kernel mounts this root partition in read-only mode.

The third command is the location of initrd. Now to understand what initrd is, let’s look at an issue that the kernel faces while mounting the root partition.

The Chicken Egg Module Problem

We just saw that the kernel has to mount the root partition in read-only mode. But the root filesystem can be on a partition with one or more of following capabilities:

The kernel needs modules for these devices as they are not compiled into kernel itself. So, the kernel will load modules for these devices at runtime. These modules are present in “/lib/modules/” directory. This directory is present on the root filesystem itself and the root partition is not mounted yet (that is what this all is about). So, how can kernel access the modules for mounting the root partition residing on the root partition itself (without mounting it)?

Here initrd comes to rescue. The initrd ramdisk contains the modules required for mounting the root partition. This initrd resides on the same partition on which kernel image is present. So the kernel loads the initrd in memory, accesses the modules and mounts the root partition in read-only mode.

Creating initrd

When the filesystem hardware or software changes, then we need to recreate the initrd. initrd can be created with “mkinitrd” command. The location of initrd is /boot directory. The kernel version for which the initrd image is being created needs to be passed as an argument to the mkinitrd command. The current kernel version can be checked with uname command.

We can use this command to pass the required argument with command substitution:

The $(uname -r) will substitute the output of the command «uname -r» in its place.

The initrd image is a compressed image. You can check this with file command:

Источник

What is uimage in linux

vmlinux is bootable, uncompressed, compressible kernel image, vm on behalf of Virtual Memory (expressed Linux support virtual memory) is obtained from the user to the kernel source code compiler, in essence, elf format.; vmlinux is the most primitive kernel file

  • elf format file
    • ELF (Executable and Linkable Format) Executable Linkable Format, is a binary interface UNIX lab released;
    • Elf file format, in addition to over-binary code, executable files include some information, such as the symbol table and the like.
Читайте также:  Приложение quik для windows

kernel mirror mode: Image

  • Image processing is the result of objcopy kernel code contains only the binary data, it is not the elf format, but has not been compressed.
    • objcopy:
      • Copy contents of a target file to another object file (to convert the file into another one target format object file format);
      • By using an output target of binary (binary -o), you can generate a binary file of the original, In essence, all the information symbols and relocation information deleted, leaving only the binary data.

kernel image formats: zImage

  • ARM Linux zImage is commonly used as a compressed image file, which is the result obicopy, generated by vmlinux Image, then the binary data Plus Decompression of codes compressed gzip Made;
  • Linux multi-image file format stored on NAND, applies to a small core;

Mirror kernel mode: bzImage

bz denotes Big zImage, which zImage format is similar but with a different compression algorithms, attention,The higher the compression ratio bzImage is the compressed kernel image

zImage / bzImage: theyNot only is a compressed fileAnd in these two documents The beginning of the compressed code embedded solvability . Difference between the two is that the old core decompression to zImageLow memory(First 640K), bzImage decompression kernel toHigh memory(1M or more). If the core is relatively small, it may take one or zImage bzImage, two ways to guide runtime system is the same. Large kernel using bzImage, can not be used zImage.

Mirror kernel mode: uImage

uImage is dedicated uboot image filesIt isBefore zImage plusOneLength of 0x40 header information (tag) (that is to say uImage is a binary file), In the header information that describes the type of the image file, loading position, generation time, size and other information. In other words, if started from 0x40 uImage position, the zImage uImage and there is no difference. The command format is #make uImage. Linux multi-image file format stored on the NAND.

Источник

Исследуем OpenWRT: чем отличаются образы uImage и sysupgrade


В комментариях к статье “Прошиваем роутер Upvel UR-313N4G на OpenWRT” между вашим покорным слугой и уважаемым Maysoft завязался спор насчет различий в структуре образов uImage и sysupgrade прошивки OpenWRT. Я обещал Maysoft разобраться в проблеме, и вот перед вами эта статья.

Как известно, в каталоге загрузок OpenWRT доступны, по большей части, прошивки двух типов — uImage и sysupgrade, например:

Официальный FAQ пишет об их различиях весьма скупо:

What is the difference between the different image formats?
a factory image is one built for the bootloader flasher or stock software flasher
a sysupgrade image (previously named trx image) is designed to be flashed from within openwrt itself
The two have the same content, but a factory image would have extra header information or whatever the platform needs. Generally speaking, the factory image is to be used with the OEM GUI or OEM flashing utilities to convert the device to OpenWrt. After that, use the sysupgrade images.

Согласно документации, содержание образов идентично, за исключением того, что в образе factory присутствуют дополнительные заголовки, чтобы этот образ можно было прошить через Web-интерфейс оригинальной прошивки.

Отлично, сравним размер прошивок:

openwrt-15.05-rc3-ramips-rt305x-dir-320-b1-initramfs-uImage.bin — 3253035 байт.

openwrt-15.05-rc3-ramips-rt305x-dir-320-b1-squashfs-sysupgrade.bin — 3407876 байт.

Ого, прошивка sysupgrade почти на 140 Кб больше uImage, а по документации они должны быть примерно одного размера, причем uImage за счет этой самой “extra header information” — немного больше.

Конечно, достаточно посмотреть в сборочные скрипты, чтобы понять, чем различаются uImage и sysupgrade-образы, но это, согласитесь, неспортивно. Сегодня мы будем анализировать прошивки “в лоб”, как будто у нас нет исходников, а уже в конце заглянем в сборочные скрипты, чтобы подтвердить наши догадки.

Читайте также:  Russian font для windows 10

Основным средством анализа прошивок на данный момент является утилита binwalk, доступная под Linux. Переименуем файлы прошивок покороче, чтобы нам было удобнее, и начнем анализ.

Кажется, вся прошивка представляет собой образ uImage — в начале следует заголовок длиной 64 (0x40) байт, а вслед за нам — поток данных, сжатый алгоритмом LZMA, размером 3252971 байт. Сложим 64 и 3252971, получим 3253035 байт, то есть размер скачанного образа. Следовательно, кроме образа uImage в файле больше ничего нет. Binwalk умеет распаковывать найденные LZMA-потоки. В принципе, можно вручную отрезать от файла первые 64 байта и распаковать остаток командой lzma -d, но зачем, когда есть такой удобный инструмент?

Посмотрим, что у нас получилось

Файл с именем 40 (смещение в исходном файле) — и есть распакованный поток. Натравим на него binwalk:

А здесь у нас что-то, на первый взгляд, непонятное — binwalk обнаружил ядро Linux по смещению 0x2AEB14 и три сжатых потока данных, следующих за ядром. Дело в том, что binwalk для анализа использует эвристики и то, что получается у него на выходе — не истина в последней инстанции, а информация к размышлению.
Здравый смысл подсказывает, что ядро должно начинаться со смещения 0, а сжатый поток — быть один и содержать initramfs — начальную файловую систему, загружаемую в RAM. О том же говорит и документация на ядро:

What is initramfs?
— All 2.6 Linux kernels contain a gzipped «cpio» format archive, which is extracted into rootfs when the kernel boots up. After extracting, the kernel checks to see if rootfs contains a file «init», and if so it executes it as PID 1.

Populating initramfs:
— The 2.6 kernel build process always creates a gzipped cpio format initramfs archive and links it into the resulting kernel binary. By default, this archive is empty (consuming 134 bytes on x86).

Здесь же упоминается и формат потока — CPIO.

Посмотрим, что binwalk сможет извлечь из нашего образа:

Итак, успешно распаковался только поток по смещению 33E2C8. Если мы все правильно делаем, то это должен быть CPIO-контейнер с файловой системой:

В конце архива мы видим файл с именем TRAILER. который. согласно документации, является меткой конца архива.

Значит, структура прошивки initramfs-uImage такова:

Теперь возьмемся за образ squashfs-sysupgrade. Из названия следует, что в образе содержится (кроме ядра) файловая система squashfs. Посмотрим, так ли это:

Возьмемся за арифметику: 64 + 1142606 (image size) = 1142670, как раз по этому смещению начинается образ squashfs, а заканчивается он по смещению 1142670 + 2221946 = 3364616. Размер образа, между тем, 3407876 байт, значит, у нас есть еще 3407876 — 3364616 = 43260 байт неидентифицированной информации. Посмотрим, что там, hexdump’ом

Тут явно какая-то заглушка. Вернемся к ней позднее.

Посмотрим, что у нас в каталоге с распакованным образом:

Распакуем LZMA-поток по смещению 40:

Здесь у нас ядро Linux и небольшой initramfs-образ с четырьмя файлами. Остальное, видимо, переместилось в образ squashfs:

Действительно, основная файловая система содержится в образе squashfs.

Теперь разберемся с заглушкой в конце образа. Есть подозрение, что она как-то относится к ФС JFFS2, потому что при прошивке образа sysupgrade и последующей загрузке в dmesg появляются строки:

а при прошивке и загрузке образа uImage этих строк нет. Поиск в “ванильном“ ядре по этим строкам ничего не дает, а вот в дереве исходных кодов OpenWRT такие строки есть:

Ага, вот и наша заглушка 0xDEADCODE. Если драйвер JFFS2 находит эту метку, то он считает ее концом предыдущей файловой системы и стирает все, начиная с нулевого байта метки и заканчивая концом накопителя. Таким образом сама метка также затирается.
После этого драйвер создает на этом месте новый экземпляр JFFS2.
Итак, получается следующая структура образа:

Таким образом:

  1. uImage содержит минимально необходимый функционал для запуска OpenWRT и за счет этого его структуру можно легко изменить так, чтобы она проходила проверки на корректность в Web-интерфейсах оригинальных прошивок.
  2. Sysupgrade устроен сложнее и использует Linux-специфичные инструменты — SquashFS и JFFS2.
  3. Оба типа образов не содержат начального загрузчика (и не должны)
  4. При прошивке через начальный загрузчик (через UART или аварийное восстановление) можно сразу шить sysuprade.
  5. При прошивке через mtd_write, если эта утилита доступна через telnet из официальной прошивки, также можно сразу шить sysupgrade.
Читайте также:  Microsoft windows server standard core 2019 open value 16 license level d government

В заключении заглянем сборочные скрипты OpenWRT, чтобы убедиться в своих выводах. Начнем с файла /target/linux/ramips/Makefile. Но если вы думаете, что это обычный GNU Makefile, то это не так. Вот как описывают улучшенный Makefile сами разработчики:

Looking at one of the package makefiles, you’d hardly recognize it as a makefile. Through what can only be described as blatant disregard and abuse of the traditional make format, the makefile has been transformed into an object oriented template which simplifies the entire ordeal.

Кажется, сборка образа запускается в строке 564:

Цель BuildFirmware/Default8M описана в строках 195 и 196:

Она состоит из двух позиций: squashfs и initramfs. Цели BuildFirmware/OF и BuildFirmware/OF/initramfs описаны в том же файле чуть выше

По имени цели MkImageLzmaDtb можно догадаться, что она создает образ uImage по описанию из DTS-файла. Для цели BuildFirmware/OF/initramfs к этому образу добавляется раздел initramfs с основной файловой системой, после чего образ копируется в выходной каталог. Для цели BuildFirmware/OF исходный образ обрабатывается функцией MkImageSysupgrade, которая с помощью команды “cat” прицепляет к нему раздел squashfs, а затем, взывает функцию prepare_generic_squashfs, определенную в файле image.mk.

А утилита padjffs2, написанная на C, записывает отметку 0xDEADCODE в конец файла образа:

В общем, мир OpenWRT прекрасен и удивителен, особенно доставляют комментарии типа:

# The real magic happens inside these templates

Источник

Image vs zImage vs uImage

What is the difference between them?

I know that u-boot needs a kernel in uImage format.

The system I use first boots from stage 1 loader and then it calls u-boot. I want to discard u-boot and directly boot from stage 1 loader. Which type of kernel image do I have to use?

1 Answer 1

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is «not compressed» even though it actually is.

Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it’s pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

Источник

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