1# Copyright (c) 2022, Google, Inc. All rights reserved
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14#
15
16# Invoke a protoc command with a custom plugin for protobuf-driven code
17# generation and build a library from the generated sources.
18#
19# args:
20# MODULE : module name (required)
21# MODULE_PROTOC_PLUGIN: path to a python protoc plugin (required)
22# MODULE_PROTOC_PLUGIN_FLAGS: optional flags for the custom plugin
23#                             shared via env variable
24# MODULE_PROTOS: list of PROTO files
25# MODULE_PROTO_PACKAGE: a path that matches the directory structure of
26#                       the PROTO package utilized in the module.
27
28PROTOC_TOOL := $(if $(wildcard out/host/linux-x86/bin/aprotoc),out/host/linux-x86/bin/aprotoc,prebuilts/libprotobuf/bin/protoc)
29
30ifeq ($(MODULE_PROTOC_PLUGIN),)
31$(error No MODULE_PROTOC_PLUGIN provided for $(MODULE))
32endif
33
34# WARNING: this implies all sources are under the same package.
35# TODO(b/259511922): support multiple packages.
36MODULE_SRCS := $(call TOBUILDDIR,$(patsubst %.proto,%.c,$(MODULE_PROTOS)))
37MODULE_PROTO_OUT_DIR := $(sort $(dir $(subst $(MODULE_PROTO_PACKAGE),,$(MODULE_SRCS))))
38
39# TODO: support multiple, disparate packages;
40# the output directory for the tool should be at the root of
41# the package path.
42$(MODULE_SRCS): PROTOC_TOOL := $(PROTOC_TOOL)
43$(MODULE_SRCS): MODULE_PROTOC_PLUGIN := $(MODULE_PROTOC_PLUGIN)
44$(MODULE_SRCS): MODULE_PROTOC_PLUGIN_FLAGS := $(MODULE_PROTOC_PLUGIN_FLAGS)
45$(MODULE_SRCS): MODULE_PROTO_PACKAGE := $(MODULE_PROTO_PACKAGE)
46$(MODULE_SRCS): MODULE_PROTO_OUT_DIR := $(MODULE_PROTO_OUT_DIR)
47$(MODULE_SRCS): $(BUILDDIR)/%.c: %.proto $(MODULE_PROTOC_PLUGIN)
48	@$(MKDIR)
49	@echo generating $@ from PROTO
50	$(NOECHO)$(PROTOC_TOOL) \
51		--plugin=protoc-gen-custom-plugin=$(MODULE_PROTOC_PLUGIN) \
52		--custom-plugin_out=$(MODULE_PROTO_OUT_DIR) \
53		--custom-plugin_opt=pkg:$(MODULE_PROTO_PACKAGE),$(MODULE_PROTOC_PLUGIN_FLAGS) \
54		$<
55
56MODULE_EXPORT_INCLUDES += $(MODULE_PROTO_OUT_DIR)/include
57
58# Ensure that all auto-generated code, including headers, is
59# emitted before downstream dependencies
60MODULE_EXPORT_SRCDEPS += $(MODULE_SRCS)
61
62# Build the PROTO module into a library
63include make/library.mk
64
65MODULE_PROTOS :=
66PROTOC_TOOL :=
67MODULE_PROTO_OUT_DIR :=
68MODULE_PROTOC_PLUGIN :=
69MODULE_PROTOC_PLUGIN_FLAGS :=
70MODULE_PROTO_PACKAGE :=
71