- Cross compiling Linux ARM kernel modules
- 1. Target system
- 2. Download linux kernel source
- 3. Download cross compiler toolchain
- 4. Take out kernel build config
- 5. Build the kernel
- Cross-Compiling Under Linux
- Contents
- Building for i386 on an x86_64 machine
- Cross-compiling under Linux for MS Windows
- Example usage
- Contrib libraries
- Flags
- environment variables
- SDL’s Script
- Note about WINE
- Autoconf/Automake unit testing suites
- Testing the created executables
- Cross-compile Linux kernel with additional modules
- Кросскомпиляция модуля helloworld
- 1 ответ 1
- Основные зависимости
- Типовая структура
- Подготовка дерева исходников ядра
Cross compiling Linux ARM kernel modules
This guide will allow you to cross-compile a loadable kernel module (LKM; a.k.a. device driver) for a ARM Linux system.
1. Target system
I will use this configuration as an example, but you can apply the same method for other environments.
- ARMv7 (32-bit)
- ARM qemu emulating vexpress-a9 board
- Linux is running in qemu.
2. Download linux kernel source
You must download the exact version which is running in the qemu.
Note that source for 3.2.0 is named linux-3.2.tar.gz , not linux-3.2.0.tar.gz .
3. Download cross compiler toolchain
Linaro’s prebuilt toolchain generally works well. Download one from https://releases.linaro.org/components/toolchain/binaries.
Pick a version, and choose the appropriate architecture. In our case, it would be arm-linux-gnueabihf (ARM 32-bit, linux, little endian, hard float).
There are three kinds of files: gcc-linaro- , runtime-gcc-linaro- , and sysroot-eglibc-linaro- . You only need the first one. For more info, refer to this Linaro wiki page.
For instance, go to 4.9-2017.01/arm-linux-gnueabihf/ directory and download gcc-linaro-4.9.4-2017.01-x86_64_arm-linux-gnueabihf.tar.xz .
4. Take out kernel build config
We need to build the kernel first, and then build a kernel module. But to compile a kernel, we must have the exact build configuration of the currently running Linux system. Fortunately, you can get a copy from a running system. Look at these locations:
Copy the file out of the qemu using scp or something.
5. Build the kernel
You need auto-generated files in order to build a kernel module. Otherwise you may encounter an error message like this:
To build a kernel with given config file,
Complete kernel build may not be necessary because what you need is generated header files.
Источник
Cross-Compiling Under Linux
Contents
Building for i386 on an x86_64 machine
Reminder: If when compiling from source you decide you’d like to recompile with a different set of options, or stop the build in order to change some of the options you’ve selected, you must first run `make distclean` (`make clean` only removes object files) in order to remove generated configuration files before you run the configure script again with your new options. If you accidentally stop the build (by hitting ctrl-c or something) and do not wish to change any of the options, you can safely restart the build by simply typing the `make` command and it will continue right where it left off.
%debian if ./configure complains about not being able to find gtk-config, install the ‘libgtk2.0-dev’ package %%
If the compile fails with the error «had to relocate PCH», try adding «—disable-precomp-headers’ to your ./configure line.
You can create windows binaries without even booting to Windows! see Cross-Compiling Under Linux.
You may need to build 32-bit apps on an x86_64 Linux box (Suse or RHEL WS3 which is what I have). On my box at least, the 32-bit gtk libs aren’t installed, so I opted to build the plain X11 version, but the config below should work for either one.
Configure like this:
On RHEL WS 3, there are some missing lib symlinks in /usr/lib, e.g. no libX11.so (should be a symlink to libX11.so.X.Y). You’ll have to make those manually. They should be pretty obvious config or build failures.
Also, the configure script tries to search in /usr/lib64 and /usr/X11R6/lib64; remove those from SEARCH_LIBS near the top of the configure script (not doing this would make it try to link with e.g. -lXinerama, which exists but only in the 64 bit world.)
Cross-compiling under Linux for MS Windows
- Install The Mingw Cross-Compiler.
- Compile wxWidgets
- Download wxWidgets source
- Compile with ./configure —prefix=/usr/local/i586-mingw32 —host=i586-mingw32msvc —build=i686-linux —your_optional_switches
Host string differs depending on mingw installations, you should check your mingw cross compiler for the exact value. Build option can also be different if you’re not using Linux on x86, of course. For example, if you use mingw32 from Debian or Ubuntu packages under Linux on x86-64 architecture the command would be: ./configure —prefix=/usr/local/i586-mingw32msvc —host=i586-mingw32msvc —build=x86_64-linux —your_optional_switches
You may use ‘checkinstall make install’ instead of ‘make install’ in order to create a package and allow clean removal of the binaries.
- Embedding icons in your cross-compiled binary: Cross-Compiling Windows Resources
- Embedding other files: Embedding PNG Images
- Several tips, tricks and workarounds as well as Eclipse configuration: wxWindows application compile (for Linux) and cross-compile (for Windows) under Linux/Eclipse/CDT
- IBM DeveloperWorks article
- Cross compiling RLS AVON with MinGW on Linux (simple instructions for installing environment, compiling wxWidgets, and compiling an certain wxWidgets application)
Note: The SDL scripts and these directions cannot be mixed. Note: By disabling threads (with —disable-threads), you can avoid a dependency on the ming dll
Example usage
Once installed, save the following file as winhello.c (stolen from Installing and Using the MinGW Cross-Compiler on Mac OS X):
To build the example, execute the following command:
and run it, for example, with wine: wine winhello.exe
Contrib libraries
Couldn’t compile the contrib directory with the wxMSW 2.4.2 sources, use the latest cvs.
Flags
You might need these flags when compiling:
And these while linking:
environment variables
VZ: Note that this is unnecessary when using autoconf cross-compilation support.
In order to use the cross-compiler tools you need to replace the normal tools in makefiles. This is easier to do just exporting some environment variables before running configure/make:
SDL’s Script
See also: BuildCVS.txt in the tar of the SDL scripts
http://www.libsdl.org/extras/win32/cross/ contains scripts that automate the compiler build process described above.
Download build-cross.sh, cross-configure.sh, and cross-make.sh.
Run the script build-cross.sh.
Download the CVS version wxAll and uncompress it.
Copy cross-configure.sh and cross-make.sh to the wxWidgets-2.5.2 directory.
Run cross-configure.sh and cross-make.sh and you should be done. 🙂
From MXE page — «MXE (M cross environment) is a GNU Makefile that compiles a cross compiler and cross compiles many free libraries such as SDL and Qt.»
MXE can be used to cross-compile wxWidgets projects. You can install MXE according to the steps in the tutorial, go to the MXE directory and issue the following command:
Now, ensure that you have /usr/bin in the PATH and compile your project with the following command:
Note about WINE
Make sure to turn off binfmt support before running configure (Debian: /etc/init.d/binfmt-support stop), which invokes wine for .exe files; otherwise configure will think it does NOT use a cross-compiler.
Autoconf/Automake unit testing suites
(maybe this section should go somewhere else?)
It is possible to autotest your code using wine (you are using unit tests, right?). This makes it very easy to script code under Unix to build multiple platforms, then test, without intervention. This section focusses on testing console-able objects.
First familiarise yourself with building test binaries with autoconf and automake. I recommend cppunit (for C++ systems). There’s plentiful documentation on cppunit’s website on integrating cppunit with Makefile.am. One show-stopping step is the ability to test msw binaries in the same way (make check) one tests unix binaries.
To take advantage of wine (running your tests automatically with wine), first make sure that wine may run headless. If you have access to a graphical terminal then this isn’t important (if you’re Ok with having wine spout gobbledygock to a window with every run). Make sure your test-directory Makefile.am’s have all TESTS tokens suffixed with $(EXEEXT):
Next add a configure.ac (you have upgraded to using .ac instead of .in, right?) line manipulating the macro TESTS_ENVIRONMENT:
In this I assume that WINE has been set with AC_CHECK_PROGS or something (even `WINE = wine’). This will have all tests run in the following format:
Where dir is the path and tst is the test name (remember that EXEEXT). That’s it: wine will return the exit code of your running binary. You can also put a special shell or other token in there, but that exceeds the focus of this documentation. This assumed automake-1.9 and autoconf-2.57 but I’m fairly certain it works in earlier versions of both (uncertain about autoconf-2.13 style).
Testing the created executables
To test your mingw32 installation with a sample not using wxWidgets, look above («Example usage»).
To test your mingw32 installation with a real wxWidgets example, take minimal.cpp from the official examples. Fortunately, I didn’t have to fiddle around with the flags myself, I use wx-config for that — not the system-wide one, but the one compiled with the cross-Windows libraries below /usr/local/i586-mingw32!
Attention, there are are two caveats here that could cost you lots of time (it did cost me lots of time, hope I’ll save yours 😉
- When compiling, be sure to include the -c option. -o with an .o object file isn’t enough, mingw32 will try to link!
- When linking, be sure to include first your object files and then the libraries (given by wx-config). When compiling, the order isn’t too important, but if you exchange libraries and object files at the linking stage, you’ll get lots of undefined references. The reason is that a linker processes the libraries in order of their appearance (see documentation of «-l» at http://sourceware.org/binutils/docs/ld/Options.html).
Finally, when executing your program with wine, qemu (works great!) or even on a real Windows box, don’t forget that even if you linked everything statically, you’ll also need mingwm10.dll in addition to your executable. Put in in the same directory and execute the binary from there, and everything works. I found mingwm10.dll gzipped in /usr/share/doc/mingw32-runtime/
Источник
Cross-compile Linux kernel with additional modules
I am new to cross-compilation. I have to cross-compile a Linux kernel because I intend to use a wifi module with my TS-7500 SBC (ARM processor) and it does not support it. I have the drivers for my wifi module and through internet surfing I have come to know a general procedure of cross-compilation. However I am somewhat confused on the extra module portion. Here is the information from official website of TS-7500 regarding these extra modules:
Appendix — Compiling TS-Kernel with Custom Options In order to compile a separate kernel module and come out with a .ko file for inclusion in the already existing kernel, these are the steps to take following step 08 and ending at step 09 above. Note: Steps after step 02 are unverified/untested. They represent an accurate procedure which one would go through.
01.) Open menuconfig and modularize the kernel feature using «M». For example, to modularize cifs.ko, one would use the arrow and Enter keys to navigate to Filesystems -> Network File Systems -> CIFS Support.
Press «M» to modularize CIFS support into the kernel then keep hitting «exit» until you’re prompted to save changes, choose «yes».
02.) Compile the kernel with the modules and copy the modules to the Linux PC
03.) Retrieve the module which was copied to the Linux PC with a command like cp so that it can be installed into the kernel on the MiniSD card.
04.) Install the module into the kernel by copy and pasting from partition 4 of the card to partition 2 on the SBC.
05.) Finally, in order to use the new module, you must enable it. This can be included in a startup script such as linuxrc.
I am confused about serial 2. Can anyone explain this to me and where am I supposed to provide address of the drivers I want to install?
Источник
Кросскомпиляция модуля helloworld
Добрый день.
Пытаюсь собрать модуль helloworld под другую машину. Хост x86_64, таргет armhf.
Установил кросскомилятор /usr/bin/arm-linux-gnueabihf-gcc, скачал исходники ядра под данную машину
/projects/linux-3.4.113/
Пытаюсь собрать (пробовал через makefile, переменные, но поскольку ничего не получилось, пытаюсь уже в лоб):
/usr/bin/arm-linux-gnueabihf-gcc -I
/projects/linux-3.4.113/ -c ./helloworld.c
(и много всяких мелких вариаций похожей команды)
На что раз за разом получаю ругань о том, что linux/modules.h не найден.
Может кто объяснить что я делаю не так, и как надо правильно? Исходный код helloworld:
Содержимое Makefile, которым пытался собирать модуль:
/projects/linux-3.4.113/include по крайней мере пути к хеадерам ядра идут начиная с этой точки.
/projects/linux-3.4.113/ ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-gcc . Да, кроме самих исходников нужен будет конфиг ядра и подготовить дерево исходников для сборки модулей примерно так: make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-gcc modules_prepare
1 ответ 1
Основные зависимости
Для сборки внешних модулей ядра обязательно надо иметь:
- Исходные кода ядра, крайне желательно точно той же версии, что и на запущенном ядре (достаточно будет заголовочные файлы ядра с Makefile ‘ами [содержимое пакета linux-headers* в большинстве пакетных дистрибутивов])
- Конфиг ядра под которое собираешь или максимально близкий.
- [Кросс-]компилятор, make и прочую dev-мишуру
Типовая структура
hello.c:
Kbuild или Makefile, первое предпочтительнее. В простейшем случаее содержит одну строчку:
Подготовка дерева исходников ядра
Далее подразумевается, что исходники ядра распакованы в /tmp/linux , префикс кросс компилятора armv6j-hardfloat-linux-gnueabi , а целевая архитектура arm .
Желательно сделать oldconfig и ответить на сотню другую вопросов, но вполне хватит и silentoldconfig. Внимание на — в конце CROSS_COMPILE — это не ошибка, так и должно быть.
Стоит проверить, что поддержка модулей в ядре включена:
Подготовка дерева для сборки модулей:
Перед кросс компиляцией настоятельно советую потренироваться и собрать helloworld для текущего нативного ядра, всё точно также, но не надо указывать CROSS_COMPILE и ARCH .
Источник