Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate BuildConfig headers in GN #2270

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/lighting-app/nrf5/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import("//build_overrides/chip.gni")
import("//build_overrides/nrf5_sdk.gni")
import("//build_overrides/openthread.gni")
mspang marked this conversation as resolved.
Show resolved Hide resolved

import("${nrf5_sdk_build_root}/nrf5_sdk.gni")

Expand Down
2 changes: 2 additions & 0 deletions examples/lighting-app/nrf5/main/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
* limitations under the License.
*/

#include <platform/CHIPDeviceConfig.h>

#include <stdbool.h>
#include <stdint.h>

Expand Down
2 changes: 0 additions & 2 deletions examples/lock-app/nrf5/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,6 @@ executable("lock_app") {
ldscript = "${nrf5_platform_dir}/app/ldscripts/chip-nrf52840-example.ld"

ldflags = [ "-T" + rebase_path(ldscript, root_build_dir) ]

defines = [ "CHIP_ENABLE_OPENTHREAD=1" ]
}

group("nrf5") {
Expand Down
2 changes: 2 additions & 0 deletions examples/lock-app/nrf5/main/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
* limitations under the License.
*/

#include <platform/CHIPDeviceConfig.h>

#include <stdbool.h>
#include <stdint.h>

Expand Down
2 changes: 2 additions & 0 deletions examples/platform/nrf528xx/app/chipinit.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#include "chipinit.h"

#include <platform/CHIPDeviceConfig.h>

#include <stdbool.h>
#include <stdint.h>

Expand Down
158 changes: 158 additions & 0 deletions gn/chip/buildconfig_header.gni
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
# Copyright (c) 2020 Project CHIP Authors
#
# 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.

# Copyright 2015 The Chromium Authors. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Generates a header with preprocessor defines specified by the build file.
#
# In the GN template, specify build defines in the template as a list
# of strings that encode key/value pairs like this:
#
# defines = [ "ENABLE_FOO=1", "ENABLE_BAR=$enable_bar" ]
#
# The GN values "true" and "false" will be mapped to 0 and 1 for boolean
# #if defines to be expressed naturally. This means you can't directly make a
# define that generates C++ value of true or false for use in code. If you
# REALLY need this, you can also use the string "(true)" and "(false)" to
# prevent the rewriting.

# To check the value of the define in C code:
#
# #include "path/to/here/header_file.h"
#
# #if ENABLE_FOO
# ...
# #endif
#
# const char kSpamServerUrl[] = SPAM_SERVER_URL;
#
# Template parameters
#
# defines [required, list of strings]
# Defines as described above.
#
# header [required, string]
# File name for generated header. By default, this will go in the
# generated file directory for this target, and you would include it
# with:
# #include "<path_to_this_BUILD_file>/<header>"
#
# header_dir [optional, string]
# Override the default location of the generated header. The string will
# be treated as a subdirectory of the root_gen_dir. For example:
# header_dir = "foo/bar"
# Then you can include the header as:
# #include "foo/bar/baz.h"
#
# deps, public_deps, testonly, visibility
# Normal meaning.
#
# Example
#
# buildconfig_header("foo_buildconfig") {
# header = "foo_buildconfig.h"
#
# defines = [
# # This uses the GN build argument enable_doom_melon as the definition.
# "ENABLE_DOOM_MELON=$enable_doom_melon",
#
# # This force-enables the define
# "ENABLE_SPACE_LASER=true",
#
# # This will expand to the quoted C string when used in source code.
# "SPAM_SERVER_URL=\"http://www.example.com/\"",
# ]
# }

import("//build_overrides/chip.gni")

template("buildconfig_header") {
source_set_name = target_name
gen_target_name = "gen_${target_name}"

action(gen_target_name) {
script = "${chip_root}/gn/chip/write_buildconfig_header.py"

if (defined(invoker.header_dir)) {
header_file = "${invoker.header_dir}/${invoker.header}"
} else {
# Compute the path from the root to this file.
header_file = rebase_path(".", "//") + "/${invoker.header}"
}

include_dir = "${root_gen_dir}/include"

outputs = [ "${include_dir}/${header_file}" ]

# Always write --defines to the file so it's not empty. Empty will confuse GN
# into thinking the response file isn't used.
response_file_contents = [ "--defines" ]
if (defined(invoker.defines)) {
response_file_contents += invoker.defines
}

args = [
"--output",
header_file, # Not rebased, Python script puts it inside gen-dir.
"--rulename",
get_label_info(":$target_name", "label_no_toolchain"),
"--gen-dir",
rebase_path(include_dir, root_build_dir),
"--definitions",
"{{response_file_name}}",
]

visibility = [ ":${source_set_name}" ]
}

source_set(source_set_name) {
sources = get_target_outputs(":${gen_target_name}")

deps = [ ":${gen_target_name}" ]

forward_variables_from(invoker,
[
"deps",
"public_deps",
"testonly",
"visibility",
])
}
}
132 changes: 132 additions & 0 deletions gn/chip/write_buildconfig_header.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
#!/usr/bin/env python
# Copyright (c) 2020 Project CHIP Authors
#
# 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.

# Copyright 2015 The Chromium Authors. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# This writes headers for build defines. See buildconfig_header.gni for
# usage of this system as a whole.
#
# The parameters are passed in a response file so we don't have to worry
# about command line lengths. The name of the response file is passed on the
# command line.
#
# The format of the response file is:
# [--defines <list of one or more defines values>]

import optparse
import os
import shlex
import sys


class Options:
def __init__(self, output, rulename, header_guard, defines):
self.output = output
self.rulename = rulename
self.header_guard = header_guard
self.defines = defines


def GetOptions():
parser = optparse.OptionParser()
parser.add_option('--output', help="Output header name inside --gen-dir.")
parser.add_option('--rulename',
help="Helpful name of build rule for including in the " +
"comment at the top of the file.")
parser.add_option('--gen-dir',
help="Path to root of generated file directory tree.")
parser.add_option('--definitions',
help="Name of the response file containing the defines.")
cmdline_options, cmdline_flags = parser.parse_args()

# Compute header guard by replacing some chars with _ and upper-casing.
header_guard = cmdline_options.output.upper()
header_guard = \
header_guard.replace('/', '_').replace('\\', '_').replace('.', '_')
header_guard += '_'

# The actual output file is inside the gen dir.
output = os.path.join(cmdline_options.gen_dir, cmdline_options.output)

# Definition file in GYP is newline separated, in GN they are shell formatted.
# shlex can parse both of these.
with open(cmdline_options.definitions, 'r') as def_file:
defs = shlex.split(def_file.read())
defines_index = defs.index('--defines')

# Everything after --defines are defines. true/false are remapped to 1/0,
# everything else is passed through.
defines = []
for define in defs[defines_index + 1 :]:
equals_index = define.index('=')
key = define[:equals_index]
value = define[equals_index + 1:]

# Canonicalize and validate the value.
if value == 'true':
value = '1'
elif value == 'false':
value = '0'
defines.append((key, str(value)))

return Options(output=output,
rulename=cmdline_options.rulename,
header_guard=header_guard,
defines=defines)


def WriteHeader(options):
with open(options.output, 'w') as output_file:
output_file.write("// Generated by gn/chip/write_buildconfig_header.py\n")
if options.rulename:
output_file.write('// From "' + options.rulename + '"\n')

output_file.write('\n#ifndef %s\n' % options.header_guard)
output_file.write('#define %s\n\n' % options.header_guard)

for pair in options.defines:
output_file.write('#define %s %s\n' % pair)

output_file.write('\n#endif // %s\n' % options.header_guard)


options = GetOptions()
WriteHeader(options)
12 changes: 6 additions & 6 deletions src/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@

import("//build_overrides/chip.gni")

config("public_includes") {
include_dirs = [ "include" ]
}

config("includes") {
include_dirs = [ "." ]
include_dirs = [
"include",
".",
"${root_gen_dir}/include",
]

configs = [ ":public_includes" ]
defines = [ "CHIP_SEPARATE_CONFIG_H=1" ]
}
5 changes: 4 additions & 1 deletion src/app/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ static_library("app") {
"${chip_root}/src/system",
]

public_configs = [ ":app_config" ]
public_configs = [
":app_config",
"${chip_root}/src:includes",
]
}

copy("codec_headers") {
Expand Down
Loading