Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 43e812fc authored by Treehugger Robot's avatar Treehugger Robot Committed by Gerrit Code Review
Browse files

Merge changes I86da8ca8,Ibb58fae9,I9c6a9fa3,I4d1ab599,I818c0f4a, ...

* changes:
  Change libbt-platform-protos dependency
  Update the readme to use build.py and explain Rust
  Add build.py to simplify building locally
  Build support for Rust via Cargo
  Add option to build libbluetooth as staticlib
  Prevent building some codecs when not supported
  Build support and abstractions for Linux build
  Add source_root parameter to bluetooth_packetgen
  Fix bison 3.7 incompatability
  Host tools support
parents 584e6e5a 39c39618
Loading
Loading
Loading
Loading
+53 −20
Original line number Diff line number Diff line
@@ -21,14 +21,10 @@
# file to your new one or GN won't know about it.

group("all") {
  deps = [
    ":bluetooth",
  ]
  deps = [ ":bluetooth" ]

  if (use.test) {
    deps += [
      ":bluetooth_tests"
    ]
    deps += [ ":bluetooth_tests" ]
  }
}

@@ -43,24 +39,34 @@ group("bluetooth") {
if (use.test) {
  group("bluetooth_tests") {
    deps = [
      "//bt/btcore:net_test_btcore",
      "//bt/common:bluetooth_test_common",
      "//bt/service:bluetoothtbd_test",
      "//bt/profile/avrcp:net_test_avrcp",
      "//bt/btcore:net_test_btcore",
      "//bt/types:net_test_types",
      "//bt/service:bluetoothtbd_test",
      "//bt/stack:net_test_btm_iso",
      "//bt/types:net_test_types",

      #"//bt/packet:net_test_btpackets",
    ]
  }
}

if (host_cpu == target_cpu && host_os == target_os) {
  group("tools") {
    deps = [
      "//bt/gd/dumpsys/bundler:bluetooth_flatbuffer_bundler",
      "//bt/gd/packet/parser:bluetooth_packetgen",
    ]
  }
}

if (defined(use.android) && use.android) {
  group("android_bluetooth_tests") {
    deps = [
      "//bt/test/suite:net_test_bluetooth",
      "//bt/device:net_test_device",
      "//bt/hci:net_test_hci",
      "//bt/osi:net_test_osi",
      "//bt/device:net_test_device",
      "//bt/test/suite:net_test_bluetooth",
    ]
  }
}
@@ -71,11 +77,13 @@ config("target_defaults") {
    "//bt/linux_include",
    "//bt/types",
    "//bt/include",

    # For flatbuffer generated headers
    "${root_gen_dir}/bt/gd/",
    "${root_gen_dir}/bt/gd/dumpsys/bundler",
  ]

  cflags = [
    "-DEXPORT_SYMBOL=__attribute__((visibility(\"default\")))",
    "-DFALLTHROUGH_INTENDED=[[clang::fallthrough]]",
    "-fPIC",
    "-Wno-non-c-typedef-for-linkage",
    "-Wno-unreachable-code-return",
@@ -91,19 +99,38 @@ config("target_defaults") {
    "-Wno-unused-variable",
    "-Wno-unused-const-variable",
    "-Wno-format",
    "-Wno-pessimizing-move",
    "-Wno-unknown-warning-option",
    "-Wno-final-dtor-non-final-class",
  ]

  cflags_cc = [
    "-std=c++17",
  ]
  cflags_cc = [ "-std=c++17" ]

  defines = [
    "HAS_NO_BDROID_BUILDCFG",
    "OS_GENERIC",
    "OS_LINUX_GENERIC",
    "EXPORT_SYMBOL=__attribute__((visibility(\"default\")))",
    "FALLTHROUGH_INTENDED=[[clang::fallthrough]]",
  ]

  configs = [
    ":external_libchrome",
  # If not configured as a dynamic library, default to static library
  if (!(defined(use.bt_dynlib) && use.bt_dynlib)) {
    defines = [
      "STATIC_LIBBLUETOOTH",
    ]
  }

  if (!(defined(use.bt_nonstandard_codecs) && use.bt_nonstandard_codecs)) {
    defines += [ "EXCLUDE_NONSTANDARD_CODECS" ]
  }

  configs = [ ":external_libchrome" ]
}

group("libbt-platform-protos-lite") {
  deps = [
    "//external/proto_logging/stats/enums/bluetooth:libbt-platform-protos-lite",
  ]
}

@@ -135,6 +162,12 @@ config("external_tinyxml2") {
  configs = [ ":pkg_tinyxml2" ]
}

config("external_flatbuffers") {
  lib_dirs = [ "${libdir}" ]

  libs = [ "flatbuffers" ]
}

# Package configurations to extract dependencies from env
pkg_config("pkg_gtest") {
  pkg_deps = [ "gtest" ]
@@ -184,10 +217,10 @@ if (defined(use.bt_nonstandard_codecs) && use.bt_nonstandard_codecs) {
  }

  pkg_config("pkg_libldacBT_enc") {
    pkg_deps = [ "ldacBT-enc", ]
    pkg_deps = [ "ldacBT-enc" ]
  }

  pkg_config("pkg_libldacBT_abr") {
    pkg_deps = [ "ldacBT-abr", ]
    pkg_deps = [ "ldacBT-abr" ]
  }
}

Cargo.toml

0 → 100644
+58 −0
Original line number Diff line number Diff line
#
#  Copyright 2021 Google, Inc.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at:
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

[package]
name = "bt_shim_ffi"
version = "0.0.1"
edition = "2018"

[dependencies]
# BT dependencies
bt_common = { path = "gd/rust/common" }
bt_facade_helpers = { path = "gd/rust/facade" }
bt_hal = { path = "gd/rust/hal" }
bt_hci = { path = "gd/rust/hci" }
bt_main = { path = "gd/rust/main" }
bt_packets = { path = "gd/rust/packets" }

# All external dependencies. Keep all versions at build/rust/Cargo.toml
bindgen = "0.51"
bytes = "1.0"
cxx = { version = "0.5.9", features = ["c++17"] }
env_logger = "0.8"
futures = "0.3"
grpcio = { version = "0.7", features = ["protobuf", "protobuf-codec", "openssl"] }
grpcio-sys = { version = "*", features = ["openssl"] }
lazy_static = "1.4"
log = "0.4"
nix = "0.19"
num-derive = "0.3"
num-traits = "0.2"
paste = "1.0"
proc-macro2 = "1.0.24"
protobuf = "2.0"
protoc-grpcio = "2.0"
protoc-rust = "2.0"
quote = "1.0.8"
thiserror = "1.0"
syn = { version = "1.0.58", features = ['default', 'full'] }
tokio = { version = "1.0", features = ['bytes', 'fs', 'io-util', 'libc', 'macros', 'memchr', 'mio', 'net', 'num_cpus', 'rt', 'rt-multi-thread', 'sync', 'time', 'tokio-macros'] }
tokio-stream = "0.1"
walkdir = "2.2"


[lib]
path = "gd/rust/shim/src/lib.rs"
crate-type = ["staticlib"]
+67 −68
Original line number Diff line number Diff line
@@ -5,8 +5,29 @@ Just build AOSP - Fluoride is there by default.

## Building and running on Linux

Instructions for Ubuntu, tested on 14.04 with Clang 3.5.0 and 16.10 with Clang
 3.8.0
Instructions for a Debian based distribution:
* Debian Bullseye or newer
* Ubuntu 20.10 or newer
* Clang-11 or Clang-12
* Flex 2.6.x
* Bison 3.x.x (tested with 3.0.x, 3.2.x and 3.7.x)

You'll want to download some pre-requisite packages as well. If you're currently
configured for AOSP development, you should have all required packages.
Otherwise, you can use the following apt-get list:

```sh
sudo apt-get install repo git-core gnupg flex bison gperf build-essential \
  zip curl zlib1g-dev gcc-multilib g++-multilib \
  x11proto-core-dev libx11-dev lib32z-dev libncurses5 \
  libgl1-mesa-dev libxml2-utils xsltproc unzip liblz4-tool libssl-dev \
  libc++-dev libevent-dev \
  flatbuffers-compiler libflatbuffers1 \
  openssl openssl-dev
```

You will also need a recent-ish version of Rust and Cargo. Please follow the
instructions on [Rustup](https://rustup.rs/) to install a recent version.

### Download source

@@ -16,96 +37,74 @@ cd ~/fluoride
git clone https://android.googlesource.com/platform/packages/modules/Bluetooth/system
```

Install dependencies (require sudo access):
Install dependencies (require sudo access). This adds some Ubuntu dependencies
and also installs GN (which is the build tool we're using).

```sh
cd ~/fluoride/bt
build/install_deps.sh
```

Then fetch third party dependencies:

```sh
cd ~/fluoride/bt
mkdir third_party
cd third_party
git clone https://github.com/google/googletest.git
git clone https://android.googlesource.com/platform/external/aac
git clone https://android.googlesource.com/platform/external/libchrome
git clone https://android.googlesource.com/platform/external/libldac
git clone https://android.googlesource.com/platform/external/modp_b64
git clone https://android.googlesource.com/platform/external/tinyxml2
```

And third party dependencies of third party dependencies:
The following third-party dependencies are necessary but currently unavailable
via a package manager. You may have to build these from source and install them
to your local environment.

```sh
cd fluoride/bt/third_party/libchrome/base/third_party
mkdir valgrind
cd valgrind
curl https://chromium.googlesource.com/chromium/src/base/+/master/third_party/valgrind/valgrind.h?format=TEXT | base64 -d > valgrind.h
curl https://chromium.googlesource.com/chromium/src/base/+/master/third_party/valgrind/memcheck.h?format=TEXT | base64 -d > memcheck.h
```
TODO(abhishekpandit) - Provide a pre-packaged option for these or proper build
instructions from source.

NOTE: If packages/modules/Bluetooth/system is checked out under AOSP, then create symbolic links instead
of downloading sources
* libchrome
* modp_b64
* tinyxml2

```
cd packages/modules/Bluetooth/system
mkdir third_party
cd third_party
ln -s ../../../external/aac aac
ln -s ../../../external/libchrome libchrome
ln -s ../../../external/libldac libldac
ln -s ../../../external/modp_b64 modp_b64
ln -s ../../../external/tinyxml2 tinyxml2
ln -s ../../../external/googletest googletest
```
### Stage your build environment

### Generate your build files
For host build, we depend on a few other repositories:
* [Platform2](https://chromium.googlesource.com/chromiumos/platform2/)
* [Rust crates](https://chromium.googlesource.com/chromiumos/third_party/rust_crates/)
* [Proto logging](https://android.googlesource.com/platform/frameworks/proto_logging/)

Clone these all somewhere and create your staging environment.
```sh
cd ~/fluoride/bt
gn gen out/Default
export STAGING_DIR=path/to/your/staging/dir
mkdir ${STAGING_DIR}
mkdir -p ${STAGING_DIR}/external
ln -s $(readlink -f ${PLATFORM2_DIR}/common-mk) ${STAGING_DIR}/common-mk
ln -s $(readlink -f ${PLATFORM2_DIR}/.gn) ${STAGING_DIR}/.gn
ln -s $(readlink -f ${RUST_CRATE_DIR}) ${STAGING_DIR}/external/rust
ln -s $(readlink -f ${PROTO_LOG_DIR}) ${STAGING_DIR}/external/proto_logging
```

### Build

```sh
cd ~/fluoride/bt
ninja -C out/Default all
```
We provide a build script to automate building assuming you've staged your build
environment already as above.

This will build all targets (the shared library, executables, tests, etc) and
 put them in out/Default. To build an individual target, replace "all" with the
 target of your choice, e.g. ```ninja -C out/Default net_test_osi```.

### Run

```sh
cd ~/fluoride/bt/out/Default
LD_LIBRARY_PATH=./ ./bluetoothtbd -create-ipc-socket=fluoride
./build.py --output ${OUTPUT_DIR} --platform-dir ${STAGING_DIR} --clang
```

### Eclipse IDE Support
This will build all targets to the output directory you've given. You can also
build each stage separately (if you want to iterate on something specific):

1. Follows the Chromium project
 [Eclipse Setup Instructions](https://chromium.googlesource.com/chromium/src.git/+/master/docs/linux/eclipse_dev.md)
 until "Optional: Building inside Eclipse" section (don't do that section, we
 will set it up differently)
* prepare - Generate the GN rules
* tools - Generate host tools
* rust - Build the rust portion of the build
* main - Build all the C/C++ code
* test - Build all targets and run the tests
* clean - Clean the output directory

2. Generate Eclipse settings:
You can choose to run only a specific stage by passing an arg via `--target`.

  ```sh
  cd packages/modules/Bluetooth/system
  gn gen --ide=eclipse out/Default
  ```
Currently, Rust builds are a separate stage that uses Cargo to build. See
[gd/rust/README.md](gd/rust/README.md) for more information.

3. In Eclipse, do File->Import->C/C++->C/C++ Project Settings, choose the XML
 location under packages/modules/Bluetooth/system/out/Default

4. Right click on the project. Go to Preferences->C/C++ Build->Builder Settings.
 Uncheck "Use default build command", but instead using "ninja -C out/Default"
### Run

5. Goto Behaviour tab, change clean command to "-t clean"
By default on Linux, we statically link libbluetooth so you can just run the
binary directly:

```sh
cd ~/fluoride/bt/out/Default
./bluetoothtbd -create-ipc-socket=fluoride
```

build.py

0 → 100755
+413 −0
Original line number Diff line number Diff line
#!/usr/bin/env python3

#  Copyright 2021 Google, Inc.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at:
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
""" Build BT targets on the host system.

For building, you will first have to stage a platform directory that has the
following structure:
|-common-mk
|-bt
|-external
|-|-rust
|-|-|-vendor

The simplest way to do this is to check out platform2 to another directory (that
is not a subdir of this bt directory), symlink bt there and symlink the rust
vendor repository as well.
"""
import argparse
import multiprocessing
import os
import shutil
import six
import subprocess
import sys

# Use flags required by common-mk (find -type f | grep -nE 'use[.]' {})
COMMON_MK_USES = [
    'asan',
    'coverage',
    'cros_host',
    'fuzzer',
    'fuzzer',
    'msan',
    'profiling',
    'tcmalloc',
    'test',
    'ubsan',
]

# Default use flags.
USE_DEFAULTS = {
    'android': False,
    'bt_nonstandard_codecs': False,
    'test': False,
}

VALID_TARGETS = [
    'prepare',  # Prepare the output directory (gn gen + rust setup)
    'tools',  # Build the host tools (i.e. packetgen)
    'rust',  # Build only the rust components + copy artifacts to output dir
    'main',  # Build the main C++ codebase
    'test',  # Build and run the unit tests
    'clean',  # Clean up output directory
    'all',  # All targets except test and clean
]


class UseFlags():

    def __init__(self, use_flags):
        """ Construct the use flags.

        Args:
            use_flags: List of use flags parsed from the command.
        """
        self.flags = {}

        # Import use flags required by common-mk
        for use in COMMON_MK_USES:
            self.set_flag(use, False)

        # Set our defaults
        for use, value in USE_DEFAULTS.items():
            self.set_flag(use, value)

        # Set use flags - value is set to True unless the use starts with -
        # All given use flags always override the defaults
        for use in use_flags:
            value = not use.startswith('-')
            self.set_flag(use, value)

    def set_flag(self, key, value=True):
        setattr(self, key, value)
        self.flags[key] = value


class HostBuild():

    def __init__(self, args):
        """ Construct the builder.

        Args:
            args: Parsed arguments from ArgumentParser
        """
        self.args = args

        # Set jobs to number of cpus unless explicitly set
        self.jobs = self.args.jobs
        if not self.jobs:
            self.jobs = multiprocessing.cpu_count()

        # Normalize all directories
        self.output_dir = os.path.abspath(self.args.output)
        self.platform_dir = os.path.abspath(self.args.platform_dir)
        self.sysroot = self.args.sysroot
        self.use_board = os.path.abspath(self.args.use_board) if self.args.use_board else None
        self.libdir = self.args.libdir

        # If default target isn't set, build everything
        self.target = 'all'
        if hasattr(self.args, 'target') and self.args.target:
            self.target = self.args.target

        self.use = UseFlags(self.args.use if self.args.use else [])

        # Validate platform directory
        assert os.path.isdir(self.platform_dir), 'Platform dir does not exist'
        assert os.path.isfile(os.path.join(self.platform_dir, '.gn')), 'Platform dir does not have .gn at root'

        # Make sure output directory exists (or create it)
        os.makedirs(self.output_dir, exist_ok=True)

        # Set some default attributes
        self.libbase_ver = None

        self.configure_environ()

    def configure_environ(self):
        """ Configure environment variables for GN and Cargo.
        """
        self.env = os.environ.copy()

        # Make sure cargo home dir exists and has a bin directory
        cargo_home = os.path.join(self.output_dir, 'cargo_home')
        os.makedirs(cargo_home, exist_ok=True)
        os.makedirs(os.path.join(cargo_home, 'bin'), exist_ok=True)

        # Configure Rust env variables
        self.env['CARGO_TARGET_DIR'] = self.output_dir
        self.env['CARGO_HOME'] = os.path.join(self.output_dir, 'cargo_home')

        # Configure some GN variables
        if self.use_board:
            self.env['PKG_CONFIG_PATH'] = os.path.join(self.use_board, self.libdir, 'pkgconfig')
            libdir = os.path.join(self.use_board, self.libdir)
            if self.env.get('LIBRARY_PATH'):
                libpath = self.env['LIBRARY_PATH']
                self.env['LIBRARY_PATH'] = '{}:{}'.format(libdir, libpath)
            else:
                self.env['LIBRARY_PATH'] = libdir

    def run_command(self, target, args, cwd=None, env=None):
        """ Run command and stream the output.
        """
        # Set some defaults
        if not cwd:
            cwd = self.platform_dir
        if not env:
            env = self.env

        log_file = os.path.join(self.output_dir, '{}.log'.format(target))
        with open(log_file, 'wb') as lf:
            rc = 0
            process = subprocess.Popen(args, cwd=cwd, env=env, stdout=subprocess.PIPE)
            while True:
                line = process.stdout.readline()
                print(line.decode('utf-8'), end="")
                lf.write(line)
                if not line:
                    rc = process.poll()
                    if rc is not None:
                        break

                    time.sleep(0.1)

            if rc != 0:
                raise Exception("Return code is {}".format(rc))

    def _get_basever(self):
        if self.libbase_ver:
            return self.libbase_ver

        self.libbase_ver = os.environ.get('BASE_VER', '')
        if not self.libbase_ver:
            base_file = os.path.join(self.sysroot, 'usr/share/libchrome/BASE_VER')
            try:
                with open(base_file, 'r') as f:
                    self.libbase_ver = f.read().strip('\n')
            except:
                self.libbase_ver = 'NOT-INSTALLED'

        return self.libbase_ver

    def _gn_default_output(self):
        return os.path.join(self.output_dir, 'out/Default')

    def _gn_configure(self):
        """ Configure all required parameters for platform2.

        Mostly copied from //common-mk/platform2.py
        """
        clang = self.args.clang

        def to_gn_string(s):
            return '"%s"' % s.replace('"', '\\"')

        def to_gn_list(strs):
            return '[%s]' % ','.join([to_gn_string(s) for s in strs])

        def to_gn_args_args(gn_args):
            for k, v in gn_args.items():
                if isinstance(v, bool):
                    v = str(v).lower()
                elif isinstance(v, list):
                    v = to_gn_list(v)
                elif isinstance(v, six.string_types):
                    v = to_gn_string(v)
                else:
                    raise AssertionError('Unexpected %s, %r=%r' % (type(v), k, v))
                yield '%s=%s' % (k.replace('-', '_'), v)

        gn_args = {
            'platform_subdir': 'bt',
            'cc': 'clang' if clang else 'gcc',
            'cxx': 'clang++' if clang else 'g++',
            'ar': 'llvm-ar' if clang else 'ar',
            'pkg-config': 'pkg-config',
            'clang_cc': clang,
            'clang_cxx': clang,
            'OS': 'linux',
            'sysroot': self.sysroot,
            'libdir': os.path.join(self.sysroot, self.libdir),
            'build_root': self.output_dir,
            'platform2_root': self.platform_dir,
            'libbase_ver': self._get_basever(),
            'enable_exceptions': os.environ.get('CXXEXCEPTIONS', 0) == '1',
            'external_cflags': [],
            'external_cxxflags': [],
            'enable_werror': False,
        }

        if clang:
            # Make sure to mark the clang use flag as true
            self.use.set_flag('clang', True)
            gn_args['external_cxxflags'] += ['-I/usr/include/']

        # EXTREME HACK ALERT
        #
        # In my laziness, I am supporting building against an already built
        # sysroot path (i.e. chromeos board) so that I don't have to build
        # libchrome or modp_b64 locally.
        if self.use_board:
            includedir = os.path.join(self.use_board, 'usr/include')
            gn_args['external_cxxflags'] += [
                '-I{}'.format(includedir),
                '-I{}/libchrome'.format(includedir),
                '-I{}/gtest'.format(includedir),
                '-I{}/gmock'.format(includedir),
                '-I{}/modp_b64'.format(includedir),
            ]
        gn_args_args = list(to_gn_args_args(gn_args))
        use_args = ['%s=%s' % (k, str(v).lower()) for k, v in self.use.flags.items()]
        gn_args_args += ['use={%s}' % (' '.join(use_args))]

        gn_args = [
            'gn',
            'gen',
        ]

        if self.args.verbose:
            gn_args.append('-v')

        gn_args += [
            '--root=%s' % self.platform_dir,
            '--args=%s' % ' '.join(gn_args_args),
            self._gn_default_output(),
        ]

        print('DEBUG: PKG_CONFIG_PATH is', self.env['PKG_CONFIG_PATH'])

        self.run_command('configure', gn_args)

    def _gn_build(self, target):
        """ Generate the ninja command for the target and run it.
        """
        args = ['%s:%s' % ('bt', target)]
        ninja_args = ['ninja', '-C', self._gn_default_output()]
        if self.jobs:
            ninja_args += ['-j', str(self.jobs)]
        ninja_args += args

        if self.args.verbose:
            ninja_args.append('-v')

        self.run_command('build', ninja_args)

    def _rust_configure(self):
        """ Generate config file at cargo_home so we use vendored crates.
        """
        template = """
        [source.systembt]
        directory = "{}/external/rust/vendor"

        [source.crates-io]
        replace-with = "systembt"
        local-registry = "/nonexistent"
        """
        contents = template.format(self.platform_dir)
        with open(os.path.join(self.env['CARGO_HOME'], 'config'), 'w') as f:
            f.write(contents)

    def _rust_build(self):
        """ Run `cargo build` from platform2/bt directory.
        """
        self.run_command('rust', ['cargo', 'build'], cwd=os.path.join(self.platform_dir, 'bt'), env=self.env)

    def _target_prepare(self):
        """ Target to prepare the output directory for building.

        This runs gn gen to generate all rquired files and set up the Rust
        config properly. This will be run
        """
        self._gn_configure()
        self._rust_configure()

    def _target_tools(self):
        """ Build the tools target in an already prepared environment.
        """
        self._gn_build('tools')

        # Also copy bluetooth_packetgen to CARGO_HOME so it's available
        shutil.copy(
            os.path.join(self._gn_default_output(), 'bluetooth_packetgen'), os.path.join(self.env['CARGO_HOME'], 'bin'))

    def _target_rust(self):
        """ Build rust artifacts in an already prepared environment.
        """
        self._rust_build()

    def _target_main(self):
        """ Build the main GN artifacts in an already prepared environment.
        """
        self._gn_build('all')

    def _target_test(self):
        """ Runs the host tests.
        """
        raise Exception('Not yet implemented')

    def _target_clean(self):
        """ Delete the output directory entirely.
        """
        shutil.rmtree(self.output_dir)

    def _target_all(self):
        """ Build all common targets (skipping test and clean).
        """
        self._target_prepare()
        self._target_tools()
        self._target_rust()
        self._target_main()

    def build(self):
        """ Builds according to self.target
        """
        print('Building target ', self.target)

        if self.target == 'prepare':
            self._target_prepare()
        elif self.target == 'tools':
            self._target_tools()
        elif self.target == 'rust':
            self._target_rust()
        elif self.target == 'main':
            self._target_main()
        elif self.target == 'test':
            self.use.set_flag('test')
            self._target_all()
            self._target_test()
        elif self.target == 'clean':
            self._target_clean()
        elif self.target == 'all':
            self._target_all()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Simple build for host.')
    parser.add_argument('--output', help='Output directory for the build.', required=True)
    parser.add_argument('--platform-dir', help='Directory where platform2 is staged.', required=True)
    parser.add_argument('--clang', help='Use clang compiler.', default=False, action="store_true")
    parser.add_argument('--use', help='Set a specific use flag.')
    parser.add_argument('--target', help='Run specific build target')
    parser.add_argument('--sysroot', help='Set a specific sysroot path', default='/')
    parser.add_argument('--libdir', help='Libdir - default = usr/lib64', default='usr/lib64')
    parser.add_argument('--use-board', help='Use a built x86 board for dependencies. Provide path.')
    parser.add_argument('--jobs', help='Number of jobs to run', default=0, type=int)
    parser.add_argument('--verbose', help='Verbose logs for build.')

    args = parser.parse_args()
    build = HostBuild(args)
    build.build()
+36 −0

File added.

Preview size limit exceeded, changes collapsed.

Loading