Building linux with clang

Building Linux with Clang/LLVMВ¶

This document covers how to build the Linux kernel with Clang and LLVM utilities.

AboutВ¶

The Linux kernel has always traditionally been compiled with GNU toolchains such as GCC and binutils. Ongoing work has allowed for Clang and LLVM utilities to be used as viable substitutes. Distributions such as Android, ChromeOS, and OpenMandriva use Clang built kernels. LLVM is a collection of toolchain components implemented in terms of C++ objects. Clang is a front-end to LLVM that supports C and the GNU C extensions required by the kernel, and is pronounced “klang,” not “see-lang.”

ClangВ¶

The compiler used can be swapped out via CC= command line argument to make . CC= should be set when selecting a config and during a build.

Cross CompilingВ¶

A single Clang compiler binary will typically contain all supported backends, which can help simplify cross compiling.

CROSS_COMPILE is not used to prefix the Clang compiler binary, instead CROSS_COMPILE is used to set a command line flag: —target= . For example:

LLVM UtilitiesВ¶

LLVM has substitutes for GNU binutils utilities. Kbuild supports LLVM=1 to enable them.

They can be enabled individually. The full list of the parameters:

Currently, the integrated assembler is disabled by default. You can pass LLVM_IAS=1 to enable it.

Supported ArchitecturesВ¶

LLVM does not target all of the architectures that Linux supports and just because a target is supported in LLVM does not mean that the kernel will build or work without any issues. Below is a general summary of architectures that currently work with CC=clang or LLVM=1 . Level of support corresponds to “S” values in the MAINTAINERS files. If an architecture is not present, it either means that LLVM does not target it or there are known issues. Using the latest stable version of LLVM or even the development tree will generally yield the best results. An architecture’s defconfig is generally expected to work well, certain configurations may have problems that have not been uncovered yet. Bug reports are always welcome at the issue tracker below!

Источник

Building Linux with Clang/LLVMВ¶

This document covers how to build the Linux kernel with Clang and LLVM utilities.

AboutВ¶

The Linux kernel has always traditionally been compiled with GNU toolchains such as GCC and binutils. Ongoing work has allowed for Clang and LLVM utilities to be used as viable substitutes. Distributions such as Android, ChromeOS, and OpenMandriva use Clang built kernels. LLVM is a collection of toolchain components implemented in terms of C++ objects. Clang is a front-end to LLVM that supports C and the GNU C extensions required by the kernel, and is pronounced “klang,” not “see-lang.”

ClangВ¶

The compiler used can be swapped out via CC= command line argument to make . CC= should be set when selecting a config and during a build.

Cross CompilingВ¶

A single Clang compiler binary will typically contain all supported backends, which can help simplify cross compiling.

CROSS_COMPILE is not used to prefix the Clang compiler binary, instead CROSS_COMPILE is used to set a command line flag: —target= . For example:

LLVM UtilitiesВ¶

LLVM has substitutes for GNU binutils utilities. Kbuild supports LLVM=1 to enable them.

They can be enabled individually. The full list of the parameters:

The integrated assembler is enabled by default. You can pass LLVM_IAS=0 to disable it.

Omitting CROSS_COMPILEВ¶

As explained above, CROSS_COMPILE is used to set —target= .

If CROSS_COMPILE is not specified, the —target= is inferred from ARCH .

That means if you use only LLVM tools, CROSS_COMPILE becomes unnecessary.

For example, to cross-compile the arm64 kernel:

If LLVM_IAS=0 is specified, CROSS_COMPILE is also used to derive —prefix=

to search for the GNU assembler and linker.

Supported ArchitecturesВ¶

LLVM does not target all of the architectures that Linux supports and just because a target is supported in LLVM does not mean that the kernel will build or work without any issues. Below is a general summary of architectures that currently work with CC=clang or LLVM=1 . Level of support corresponds to “S” values in the MAINTAINERS files. If an architecture is not present, it either means that LLVM does not target it or there are known issues. Using the latest stable version of LLVM or even the development tree will generally yield the best results. An architecture’s defconfig is generally expected to work well, certain configurations may have problems that have not been uncovered yet. Bug reports are always welcome at the issue tracker below!

Читайте также:  Scsi контроллер драйвер для windows 10

Источник

Clang. Часть 1: введение

Что такое Clang?

Я провёл последние несколько месяцев, работая с Clang, фронтендом LLVM. Clang умеет парсить и анализировать любой исходный код на языках семейства С (C, C++, ObjectiveC, и т.п. ) и имеет удивительную модульную структуру, которая делает его простым в использовании.

Если вы ищете статический анализатор кода, я настоятельно рекомендую Clang, он существенно превосходит другие статические анализаторы (такие, как CIL. ) и хорошо документирован. Также список рассылки Clang очень активен и полезен, если вы застряли на чём-то.

Лично я использую Clang для статического анализа драйверов ввода-вывода ядра Linux, включая драйвера камеры и драйвера DRM графической карты. Код ядра, особенно код драйвера, может быть очень сложным и трудным для анализа, но Clang позволяет нам легко поддерживать его. Давайте посмотрим, что можно сделать с его помощью.

Как работает Clang?

В большинстве случаев, Clang запустит препроцессор (который разворачивает все макросы) и парсит исходник, превращая его в абстрактное синтаксическое дерево (AST). C AST работать гораздо проще, чем с исходным кодом, но вы всегда можете получить ссылки на исходник. Фактически, каждая структура в Clang-е, используемая для представления кода (AST, CFG и т.п.), всегда имеет ссылку на оригинальный исходник, полезный для целей анализа, рефакторинга и т.п.

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

Clang AST

Практически каждый компилятор и статический анализатор использует AST для представления исходного кода. AST, используемое в Clang, очень детализированное и сложное, но вы получите удовольствие, изучая различные классы элементов Clang AST. Ниже приводится краткое введение в Clang AST, но самый простой путь изучить его, это просто делать дампы AST для простых исходников, и смотреть, какое AST им соответствует.

В общем, Clang AST сделано из двух очень гибких классов: Decl и Stmt. У обоих есть множество подклассов, вот несколько примеров:

FunctionDecl — прототип или объявление функции
BinaryOperator — бинарный оператор, например (a + b)
CallExpr — вызов функции, например, foo(x);

Большинство классов имеют «говорящие» имена, например, ForStmt, IfStmt, и ReturnStmt. Вы поймёте суть AST, поиграв с ним несколько минут. Вы можете найти документацию по классам AST, поискав что-либо вроде “Clang FunctionDecl.”

Как использовать Clang?

Clang может использоваться как прямая замена gcc и предлагает несколько крутых инструментов статического анализа. Как программист (а не как нормальный пользователь!), вы можете получить доступ к всей мощи clang, используя его как библиотеку одним из трёх способов, в зависимости от того, как вы решите.

Для начала, ознакомьтесь с описанием интерфейсов clang. В дополнение к тому, что написано в этом описании, я выделю другие существенные различия между различными интерфейсами clang.

Clang Plugin

Ваш код является плагином, и запускается каждый раз заново для каждого файла исходника, что означает, что вы не можете сохранять глобальную информацию или другую контекстную информацию между двумя разными исходными файлами (но вы можете запустить плагин для множества файлов последовательно). Плагин запускается путём передачи соответствующих опций системе компиляции (Clang, Make и т.п.) через аргументы командной строки. Это похоже на то, как вы включаете оптимизацию в GCC (т.е. «-O1»). Вы не можете запустить какую-либо свою задачу до или после того, как исходный файл будет проанализирован.

LibTooling (Clang Tool)

Ваш код — обычная программа на С++, с нормальной функцией main(). LibTooling используется для запуска некоторого анализа на исходном коде (с множеством файлов, при желании) без запуска обычного процесса компиляции. Новый экземпляр кода для анализа (и новый AST) будет создан для каждого нового файла исходника (как и в случае Clang Plugin), но вы можете сохранять контекстную информацию между файлами исходников в своих глобальных переменных. Так как у вас есть функция main(), вы можете запускать какие-либо задачи перед или после того, как clang завершит анализ ваших исходных файлов.

LibClang

LibClang хорош тем, что это стабильный API. Clang периодически меняется, и если вы используете Plugin или Libtooling, вам нужно будет править ваш код, чтобы отслеживать эти изменения (но это не так сложно!). Если вам нужен доступ к Clang API из языков, отличных от C++ (например, из Python), вы должны использовать LibClang.

Примечание: LibClang не даёт полный доступ к AST (только высокоуровневый доступ), но другие два варианта дают. Как правило, нам нужен полный доступ к AST.

Если вы не можете решить, что использовать, я бы порекомендовал начать с интерфейса LibTooling. Он проще, и работает так, как вы ожидаете. Он предлагает гибкость и полный доступ к AST, как и Plugin, без потери глобального контекста между исходными файлами. LibTooling не сложнее в использовании, чем Plugin.

Читайте также:  Как настроить беспроводную мышь windows 10

Начинаем работать с Clang

Сейчас, когда вы знаете основы, давайте начнём! Эта инструкция будет работать на любой версии Linux (и, возможно, OS X), но тестировалось на Ubuntu. Вы можете получить LLVM и Clang, проделав следующие шаги (взято из официальной инструкции к Clang):

Скачать и установить (например, с помощью apt-get) все необходимые пакеты.
(Типичный дистрибутив Linux идёт со всем необходимым, кроме subversion).
Смените директорию на ту, в которую вы хотите установить LLVM (например,

/static_analysis/). Будем называть её директорией верхнего уровня. Выполните следующие команды в терминале:

Компиляция LLVM и Clang займёт некоторое время.

Для проверки запустите:

Можно протестировать Clang, запустив классический пример Hello World:

В этом руководстве я использую Clang 3.4 на Ubuntu 13.04, но вы можете использовать другие варианты и того, и другого.

Сейчас перейдём к программированию на Clang.

Источник

Building the Linux kernel

The Linux kernel can be built with clang/LLVM for X64 and ARM64. We can use the Checked C version of clang/LLVM instead, allowing us to try out using Checked C in the kernel. With some patches the Linux kernel can be built using clang/LLVM for ARM32, but it is not booting with those patches.

For X64 and ARM64, a stable recent version of the Linux kernel can be used. For example, Linux 4.19 RC3 can be used. For ARM32, a fork of 4.19 RC1 with patches applied is available at ttps://github.com/Prabhuk/linux_kernel_clang_build

Add installation of prerequisites

Instructions to build the kernel for X86_64

Please follow the instructions to build Checked C Clang.

Boot the built image under QEMU:

Instructions to build ARM

  1. Linux Kernel code (referred as kernel code or kernel going forward), is typically compiled using gcc.
  2. Certain gcc optimizations used by kernel code are available only in gcc and these optimizations are applied through use of compiler flags.
  3. There is no guaranteed binary interoperability for binary code that is generated by different compilers.
  4. However, the libraries that confirm to the platform ABI can interoperate though the libraries themselves are incompatible C libraries.
  1. https://softwareengineering.stackexchange.com/questions/235706/are-c-object-files-created-with-different-compilers-binary-compatible
  2. https://kevinaboos.wordpress.com/2013/10/03/static-analysis-of-linux-kernel-drivers-using-clang/
  3. LLVMLinux patches repo: https://github.com/Fuzion24/LLVM-Linux-Kernel
  4. Google’s efforts: https://lkml.org/lkml/2017/8/22/912
  5. https://github.com/nathanchance/android-kernel-clang
  6. https://lwn.net/Articles/734071/
  7. ARM32: http://lists.llvm.org/pipermail/llvm-dev/2018-March/121810.html
  8. ChromiumOS kernel: https://chromium.googlesource.com/chromiumos/third_party/kernel/+/v4.9
  9. https://github.com/dnschneid/crouton/wiki/Build-chrome-os-kernel-and-kernel-modules
  10. Android kernel: https://android.googlesource.com/kernel/common/+log/f0907aa15ed9f9c7541bb244ed3f52c376ced19c
  11. https://clang.llvm.org/docs/CrossCompilation.html

Building for ARM 64 and x86 architectures:

Источник

Getting Started: Building and Running Clang

This page gives you the shortest path to checking out Clang and demos a few options. This should get you up and running with the minimum of muss and fuss. If you like what you see, please consider getting involved with the Clang community. If you run into problems, please file bugs in LLVM Bugzilla.

Release Clang Versions

Clang is released as part of regular LLVM releases. You can download the release versions from https://llvm.org/releases/.

Clang is also provided in all major BSD or GNU/Linux distributions as part of their respective packaging systems. From Xcode 4.2, Clang is the default compiler for Mac OS X.

Building Clang and Working with the Code

On Unix-like Systems

If you would like to check out and build Clang, the current procedure is as follows:

  1. Get the required tools.
    • See Getting Started with the LLVM System — Requirements.
    • Note also that Python is needed for running the test suite. Get it at: https://www.python.org/downloads/
    • Standard build process uses CMake. Get it at: https://cmake.org/download/
  2. Check out the LLVM project:
    • Change directory to where you want the llvm directory placed.
    • git clone https://github.com/llvm/llvm-project.git
    • The above command is very slow. It can be made faster by creating a shallow clone. Shallow clone saves storage and speeds up the checkout time. This is done by using the command:
      • git clone --depth=1 https://github.com/llvm/llvm-project.git (using this only the latest version of llvm can be built)
      • For normal users looking to just compile, this command works fine. But if someone later becomes a contributor, since they can’t push code from a shallow clone, it needs to be converted into a full clone:
        • cd llvm-project
        • git fetch --unshallow
  3. Build LLVM and Clang:
    • cd llvm-project
    • mkdir build (in-tree build is not supported)
    • cd build
    • cmake -DLLVM_ENABLE_PROJECTS=clang -G "Unix Makefiles" ../llvm
    • make
    • This builds both LLVM and Clang for debug mode.
    • Note: For subsequent Clang development, you can just run make clang.
    • CMake allows you to generate project files for several IDEs: Xcode, Eclipse CDT4, CodeBlocks, Qt-Creator (use the CodeBlocks generator), KDevelop3. For more details see Building LLVM with CMake page.
  4. If you intend to use Clang’s C++ support, you may need to tell it how to find your C++ standard library headers. In general, Clang will detect the best version of libstdc++ headers available and use them — it will look both for system installations of libstdc++ as well as installations adjacent to Clang itself. If your configuration fits neither of these scenarios, you can use the -DGCC_INSTALL_PREFIX cmake option to tell Clang where the gcc containing the desired libstdc++ is installed.
  5. Try it out (assuming you add llvm/build/bin to your path):
    • clang --help
    • clang file.c -fsyntax-only (check for correctness)
    • clang file.c -S -emit-llvm -o - (print out unoptimized llvm code)
    • clang file.c -S -emit-llvm -o - -O3
    • clang file.c -S -O3 -o - (output native machine code)
  6. Run the testsuite:
    • make check-clang
Читайте также:  Проблемы при обновлении линукс

Using Visual Studio

The following details setting up for and building Clang on Windows using Visual Studio:

  1. Get the required tools:
    • Git. Source code control program. Get it from: https://git-scm.com/download
    • CMake. This is used for generating Visual Studio solution and project files. Get it from: https://cmake.org/download/
    • Visual Studio 2017 or later
    • Python. It is used to run the clang test suite. Get it from: https://www.python.org/download/
    • GnuWin32 tools The Clang and LLVM test suite use various GNU core utilities, such as grep, sed, and find. The gnuwin32 packages are the oldest and most well-tested way to get these tools. However, the MSys utilities provided by git for Windows have been known to work. Cygwin has worked in the past, but is not well tested. If you don’t already have the core utilies from some other source, get gnuwin32 from http://getgnuwin32.sourceforge.net/.
  2. Check out LLVM and Clang:
    • git clone https://github.com/llvm/llvm-project.git

Note: Some Clang tests are sensitive to the line endings. Ensure that checking out the files does not convert LF line endings to CR+LF. If you’re using git on Windows, make sure your core.autocrlf setting is false.

  • Run CMake to generate the Visual Studio solution and project files:
    • cd llvm-project
    • mkdir build (for building without polluting the source dir)
    • cd build
    • If you are using Visual Studio 2017: cmake -DLLVM_ENABLE_PROJECTS=clang -G "Visual Studio 15 2017" -A x64 -Thost=x64 ..\llvm
      -Thost=x64 is required, since the 32-bit linker will run out of memory.
    • To generate x86 binaries instead of x64, pass -A Win32.
    • See the LLVM CMake guide for more information on other configuration options for CMake.
    • The above, if successful, will have created an LLVM.sln file in the build directory.
  • Build Clang:
    • Open LLVM.sln in Visual Studio.
    • Build the «clang» project for just the compiler driver and front end, or the «ALL_BUILD» project to build everything, including tools.
  • Try it out (assuming you added llvm/debug/bin to your path). (See the running examples from above.)
  • See Hacking on clang — Testing using Visual Studio on Windows for information on running regression tests on Windows.
  • Using Ninja alongside Visual Studio

    We recommend that developers who want the fastest incremental builds use the Ninja build system. You can use the generated Visual Studio project files to edit Clang source code and generate a second build directory next to it for running the tests with these steps:

    1. Check out clang and LLVM as described above
    2. Open a developer command prompt with the appropriate environment.
      • If you open the start menu and search for «Command Prompt», you should see shortcuts created by Visual Studio to do this. To use native x64 tools, choose the one titled «x64 Native Tools Command Prompt for VS 2017».
      • Alternatively, launch a regular cmd prompt and run the appropriate vcvarsall.bat incantation. To get the 2017 x64 tools, this would be:
        "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
    3. mkdir build_ninja (or build, or use your own organization)
    4. cd build_ninja
    5. set CC=cl (necessary to force CMake to choose MSVC over mingw GCC if you have it installed)
    6. set CXX=cl
    7. cmake -GNinja ..\llvm
    8. ninja clang This will build just clang.
    9. ninja check-clang This will run the clang tests.

    Clang Compiler Driver (Drop-in Substitute for GCC)

    The clang tool is the compiler driver and front-end, which is designed to be a drop-in replacement for the gcc command. Here are some examples of how to use the high-level driver:

    The ‘clang’ driver is designed to work as closely to GCC as possible to maximize portability. The only major difference between the two is that Clang defaults to gnu99 mode while GCC defaults to gnu89 mode. If you see weird link-time errors relating to inline functions, try passing -std=gnu89 to clang.

    Examples of using Clang

    Preprocessing:

    Type checking:

    GCC options:

    Pretty printing from the AST:

    Note, the -cc1 argument indicates the compiler front-end, and not the driver, should be run. The compiler front-end has several additional Clang specific features which are not exposed through the GCC compatible driver interface.

    Источник

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