1#!/usr/bin/python3
2#
3# Copyright (C) 2020 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18import argparse
19import json
20import os.path
21import subprocess
22from collections import defaultdict
23from datetime import datetime
24
25from pyclibrary import CParser
26
27LICENSE_HEADER = """/*
28 * Copyright (C) 2020 The Android Open Source Project
29 *
30 * Licensed under the Apache License, Version 2.0 (the "License");
31 * you may not use this file except in compliance with the License.
32 * You may obtain a copy of the License at
33 *
34 *      http://www.apache.org/licenses/LICENSE-2.0
35 *
36 * Unless required by applicable law or agreed to in writing, software
37 * distributed under the License is distributed on an "AS IS" BASIS,
38 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
39 * See the License for the specific language governing permissions and
40 * limitations under the License.
41 */
42"""
43
44# Paths for output, relative to system/chre
45CHPP_PARSER_INCLUDE_PATH = "chpp/include/chpp/common"
46CHPP_PARSER_SOURCE_PATH = "chpp/common"
47
48
49def system_chre_abs_path():
50    """Gets the absolute path to the system/chre directory containing this script."""
51    script_dir = os.path.dirname(os.path.realpath(__file__))
52    # Assuming we're at system/chre/chpp/api_parser (i.e. up 2 to get to system/chre)
53    chre_project_base_dir = os.path.normpath(script_dir + "/../..")
54    return chre_project_base_dir
55
56
57class CodeGenerator:
58    """Given an ApiParser object, generates a header file with structure definitions in CHPP format.
59    """
60
61    def __init__(self, api, commit_hash):
62        """
63        :param api: ApiParser object
64        """
65        self.api = api
66        self.json = api.json
67        # Turn "chre_api/include/chre_api/chre/wwan.h" into "wwan"
68        self.service_name = self.json['filename'].split('/')[-1].split('.')[0]
69        self.capitalized_service_name = self.service_name[0].upper() + self.service_name[1:]
70        self.commit_hash = commit_hash
71
72    # ----------------------------------------------------------------------------------------------
73    # Header generation methods (plus some methods shared with encoder generation)
74    # ----------------------------------------------------------------------------------------------
75
76    def _autogen_notice(self):
77        out = []
78        out.append("// This file was automatically generated by {}\n".format(
79            os.path.basename(__file__)))
80        out.append("// Date: {} UTC\n".format(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')))
81        out.append("// Source: {} @ commit {}\n\n".format(self.json['filename'], self.commit_hash))
82        out.append("// DO NOT modify this file directly, as those changes will be lost the next\n")
83        out.append("// time the script is executed\n\n")
84        return out
85
86    def _dump_to_file(self, output_filename, contents, dry_run, skip_clang_fomat):
87        """Outputs contents to output_filename, or prints contents if dry_run is True"""
88        if dry_run:
89            print("---- {} ----".format(output_filename))
90            print(contents)
91            print("---- end of {} ----\n".format(output_filename))
92        else:
93            with open(output_filename, 'w') as f:
94                f.write(contents)
95
96            if not skip_clang_fomat:
97                clang_format_path = os.path.normpath(
98                    "../../../../prebuilts/clang/host/linux-x86/clang-stable/bin/clang-format")
99                args = [clang_format_path, '-i', output_filename]
100                result = subprocess.run(args)
101                result.check_returncode()
102
103    def _is_array_type(self, type_info):
104        # If this is an array type, declarators will be a tuple containing a list of
105        # a single int element giving the size of the array
106        return len(type_info.declarators) == 1 and isinstance(type_info.declarators[0], list)
107
108    def _get_array_len(self, type_info):
109        return type_info.declarators[0][0]
110
111    def _get_chpp_type_from_chre(self, chre_type):
112        """Given 'chreWwanCellInfo' returns 'struct ChppWwanCellInfo', etc."""
113        prefix = self._get_struct_or_union_prefix(chre_type)
114
115        # First see if we have an explicit name override (e.g. for anonymous types)
116        for annotation in self.api.annotations[chre_type]["."]:
117            if annotation['annotation'] == "rename_type":
118                return prefix + annotation['type_override']
119
120        # Otherwise, use the existing type name, just replace the "chre" prefix with "Chpp"
121        if chre_type.startswith('chre'):
122            return prefix + 'Chpp' + chre_type[4:]
123        else:
124            raise RuntimeError("Couldn't figure out new type name for {}".format(chre_type))
125
126    def _get_chre_type_with_prefix(self, chre_type):
127        """Given 'chreWwanCellInfo' returns 'struct chreWwanCellInfo', etc."""
128        return self._get_struct_or_union_prefix(chre_type) + chre_type
129
130    def _get_chpp_header_type_from_chre(self, chre_type):
131        """Given 'chreWwanCellInfo' returns 'struct ChppWwanCellInfoWithHeader', etc."""
132        return self._get_chpp_type_from_chre(chre_type) + 'WithHeader'
133
134    def _get_member_comment(self, member_info):
135        for annotation in member_info['annotations']:
136            if annotation['annotation'] == "fixed_value":
137                return "  // Input ignored; always set to {}".format(annotation['value'])
138            elif annotation['annotation'] == "var_len_array":
139                return "  // References {} instances of {}".format(
140                    annotation['length_field'], self._get_member_type(member_info))
141        return ""
142
143    def _get_member_type(self, member_info, underlying_vla_type=False):
144        """Gets the CHPP type specification prefix for a struct/union member.
145
146        :param member_info: a dict element from self.api.structs_and_unions[struct]['members']
147        :param underlying_vla_type: (used only for var-len array types) False to output
148            'struct ChppOffset', and True to output the type that ChppOffset references
149        :return: type specification string that prefixes the field name, e.g. 'uint8_t'
150        """
151        # 4 cases to handle:
152        #   1) Annotation gives explicit type that we should use
153        #   2) Annotation says this is a variable length array (so use ChppOffset if
154        #      underlying_vla_type is False)
155        #   3) This is a struct/union type, so use the renamed (CHPP) type name
156        #   4) Regular type, e.g. uint32_t, so just use the type spec as-is
157        for annotation in member_info['annotations']:
158            if annotation['annotation'] == "rewrite_type":
159                return annotation['type_override']
160            elif not underlying_vla_type and annotation['annotation'] == "var_len_array":
161                return "struct ChppOffset"
162
163        if not underlying_vla_type and len(member_info['type'].declarators) > 0 and \
164                member_info['type'].declarators[0] == "*":
165            # This case should either be handled by rewrite_type (e.g. to uint32_t as
166            # opaque/ignored), or var_len_array
167            raise RuntimeError("Pointer types require annotation\n{}".format(
168                member_info))
169
170        if member_info['is_nested_type']:
171            return self._get_chpp_type_from_chre(member_info['nested_type_name'])
172
173        return member_info['type'].type_spec
174
175    def _get_member_type_suffix(self, member_info):
176        if self._is_array_type(member_info['type']):
177            return "[{}]".format(self._get_array_len(member_info['type']))
178        return ""
179
180    def _get_struct_or_union_prefix(self, chre_type):
181        return 'struct ' if not self.api.structs_and_unions[chre_type]['is_union'] else 'union '
182
183    def _gen_header_includes(self):
184        """Generates #include directives for use in <service>_types.h"""
185        out = ["#include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n\n"]
186
187        includes = ["chpp/app.h", "chpp/macros.h", "chre_api/chre/version.h"]
188        includes.extend(self.json['output_includes'])
189        for incl in sorted(includes):
190            out.append("#include \"{}\"\n".format(incl))
191        out.append("\n")
192        return out
193
194    def _gen_struct_or_union(self, name):
195        """Generates the definition for a single struct/union type"""
196        out = []
197        if not name.startswith('anon'):
198            out.append("//! See {{@link {}}} for details\n".format(name))
199        out.append("{} {{\n".format(self._get_chpp_type_from_chre(name)))
200        for member_info in self.api.structs_and_unions[name]['members']:
201            out.append("  {} {}{};{}\n".format(self._get_member_type(member_info),
202                                               member_info['name'],
203                                               self._get_member_type_suffix(member_info),
204                                               self._get_member_comment(member_info)))
205
206        out.append("} CHPP_PACKED_ATTR;\n\n")
207        return out
208
209    def _gen_header_struct(self, chre_type):
210        """Generates the definition for the type with header (WithHeader)"""
211        out = []
212        out.append("//! CHPP app header plus {}\n".format(
213            self._get_chpp_header_type_from_chre(chre_type)))
214
215        out.append("{} {{\n".format(self._get_chpp_header_type_from_chre(chre_type)))
216        out.append("  struct ChppAppHeader header;\n")
217        out.append("  {} payload;\n".format(self._get_chpp_type_from_chre(chre_type)))
218        out.append("} CHPP_PACKED_ATTR;\n\n")
219
220        return out
221
222    def _gen_structs_and_unions(self):
223        """Generates definitions for all struct/union types required for the root structs."""
224        out = []
225        out.append("CHPP_PACKED_START\n\n")
226
227        sorted_structs = self._sorted_structs(self.json['root_structs'])
228        for type_name in sorted_structs:
229            out.extend(self._gen_struct_or_union(type_name))
230
231        for chre_type in self.json['root_structs']:
232            out.extend(self._gen_header_struct(chre_type))
233
234        out.append("CHPP_PACKED_END\n\n")
235        return out
236
237    def _sorted_structs(self, root_nodes):
238        """Implements a topological sort on self.api.structs_and_unions.
239
240        Elements are ordered by definition dependency, i.e. if A includes a field of type B,
241        then B will appear before A in the returned list.
242        :return: list of keys in self.api.structs_and_unions, sorted by dependency order
243        """
244        result = []
245        visited = set()
246
247        def sort_helper(collection, key):
248            for dep in sorted(collection[key]['dependencies']):
249                if dep not in visited:
250                    visited.add(dep)
251                    sort_helper(collection, dep)
252            result.append(key)
253
254        for node in sorted(root_nodes):
255            sort_helper(self.api.structs_and_unions, node)
256        return result
257
258    # ----------------------------------------------------------------------------------------------
259    # Encoder function generation methods (CHRE --> CHPP)
260    # ----------------------------------------------------------------------------------------------
261
262    def _get_chpp_member_sizeof_call(self, member_info):
263        """Returns invocation used to determine the size of the provided member when encoded.
264
265        Will be either sizeof(<type in CHPP struct>) or a function call if the member contains a VLA
266        :param member_info: a dict element from self.api.structs_and_unions[struct]['members']
267        :return: string
268        """
269        type_name = None
270        if member_info['is_nested_type']:
271            chre_type = member_info['nested_type_name']
272            if self.api.structs_and_unions[chre_type]['has_vla_member']:
273                return "{}(in->{})".format(self._get_chpp_sizeof_function_name(chre_type),
274                                           member_info['name'])
275            else:
276                type_name = self._get_chpp_type_from_chre(chre_type)
277        else:
278            type_name = member_info['type'].type_spec
279        return "sizeof({})".format(type_name)
280
281    def _gen_chpp_sizeof_function(self, chre_type):
282        """Generates a function to determine the encoded size of the CHRE struct, if necessary."""
283        out = []
284
285        # Note that this function *should* work with unions as well, but at the time of writing
286        # it'll only be used with structs, so names, etc. are written with that in mind
287        struct_info = self.api.structs_and_unions[chre_type]
288        if not struct_info['has_vla_member']:
289            # No codegen necessary, just sizeof on the CHPP structure name is sufficient
290            return out
291
292        core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_type)
293        parameter_name = core_type_name[0].lower() + core_type_name[1:]
294        chpp_type_name = self._get_chpp_header_type_from_chre(chre_type)
295        out.append("//! @return number of bytes required to represent the given\n"
296                   "//! {} along with the CHPP header as\n"
297                   "//! {}\n"
298                   .format(chre_type, chpp_type_name))
299        out.append("static size_t {}(\n        const {}{} *{}) {{\n"
300                   .format(self._get_chpp_sizeof_function_name(chre_type),
301                           self._get_struct_or_union_prefix(chre_type), chre_type,
302                           parameter_name))
303
304        # sizeof(this struct)
305        out.append("  size_t encodedSize = sizeof({});\n".format(chpp_type_name))
306
307        # Plus count * sizeof(type) for each var-len array included in this struct
308        for member_info in self.api.structs_and_unions[chre_type]['members']:
309            for annotation in member_info['annotations']:
310                if annotation['annotation'] == "var_len_array":
311                    # If the VLA field itself contains a VLA, then we'd need to generate a for
312                    # loop to calculate the size of each element individually - I don't think we
313                    # have any of these in the CHRE API today, so leaving this functionality out.
314                    # Also note that to support that case we'd also want to recursively call this
315                    # function to generate sizeof functions for nested fields.
316                    if member_info['is_nested_type'] and \
317                            self.api.structs_and_unions[member_info['nested_type_name']][
318                                'has_vla_member']:
319                        raise RuntimeError(
320                            "Nested variable-length arrays is not currently supported ({} "
321                            "in {})".format(member_info['name'], chre_type))
322
323                    out.append("  encodedSize += {}->{} * sizeof({});\n".format(
324                        parameter_name, annotation['length_field'],
325                        self._get_member_type(member_info, True)))
326
327        out.append("  return encodedSize;\n}\n\n")
328        return out
329
330    def _gen_chpp_sizeof_functions(self):
331        """For each root struct, generate necessary functions to determine their encoded size."""
332        out = []
333        for struct in self.json['root_structs']:
334            out.extend(self._gen_chpp_sizeof_function(struct))
335        return out
336
337    def _gen_conversion_includes(self):
338        """Generates #include directives for the conversion source file"""
339        out = ["#include \"chpp/macros.h\"\n"
340               "#include \"chpp/memory.h\"\n"
341               "#include \"chpp/common/{}_types.h\"\n\n".format(self.service_name)]
342        out.append("#include <stddef.h>\n#include <stdint.h>\n#include <string.h>\n\n")
343        return out
344
345    def _get_chpp_sizeof_function_name(self, chre_struct):
346        """Function name used to compute the encoded size of the given struct at runtime"""
347        core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_struct)
348        return "chpp{}SizeOf{}FromChre".format(self.capitalized_service_name, core_type_name)
349
350    def _get_encoding_function_name(self, chre_type):
351        core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_type)
352        return "chpp{}Convert{}FromChre".format(self.capitalized_service_name, core_type_name)
353
354    def _gen_encoding_function_signature(self, chre_type):
355        out = []
356        out.append("void {}(\n".format(self._get_encoding_function_name(chre_type)))
357        out.append("    const {}{} *in,\n".format(
358            self._get_struct_or_union_prefix(chre_type), chre_type))
359        out.append("    {} *out".format(self._get_chpp_type_from_chre(chre_type)))
360        if self.api.structs_and_unions[chre_type]['has_vla_member']:
361            out.append(",\n")
362            out.append("    uint8_t *payload,\n")
363            out.append("    size_t payloadSize,\n")
364            out.append("    uint16_t *vlaOffset")
365        out.append(")")
366        return out
367
368    def _gen_vla_encoding(self, member_info, annotation):
369        out = []
370
371        variable_name = member_info['name']
372        chpp_type = self._get_member_type(member_info, True)
373
374        if member_info['is_nested_type']:
375            out.append("\n  {} *{} = ({} *) &payload[*vlaOffset];\n".format(
376                chpp_type, variable_name, chpp_type))
377
378        out.append("  out->{}.length = in->{} * {};\n".format(
379            member_info['name'], annotation['length_field'],
380            self._get_chpp_member_sizeof_call(member_info)))
381
382        out.append("  CHPP_ASSERT((size_t)(*vlaOffset + out->{}.length) <= payloadSize);\n".format(
383            member_info['name']))
384
385        out.append("  if (out->{}.length > 0 &&\n"
386                   "      *vlaOffset + out->{}.length <= payloadSize) {{\n".format(
387            member_info['name'], member_info['name']))
388
389        if member_info['is_nested_type']:
390            out.append("    for (size_t i = 0; i < in->{}; i++) {{\n".format(
391                annotation['length_field']))
392            out.append("      {}".format(
393                self._get_assignment_statement_for_field(member_info, in_vla_loop=True)))
394            out.append("    }\n")
395        else:
396            out.append("memcpy(&payload[*vlaOffset], in->{}, in->{} * sizeof({}));\n".format(
397                member_info['name'], annotation['length_field'], chpp_type))
398
399        out.append("    out->{}.offset = *vlaOffset;\n".format(member_info['name']))
400        out.append("    *vlaOffset += out->{}.length;\n".format(member_info['name']))
401
402        out.append("  } else {\n")
403        out.append("    out->{}.offset = 0;\n".format(member_info['name']))
404        out.append("  }\n");
405
406        return out
407
408    # ----------------------------------------------------------------------------------------------
409    # Encoder / decoder function generation methods (CHRE <--> CHPP)
410    # ----------------------------------------------------------------------------------------------
411
412    def _get_assignment_statement_for_field(self, member_info, in_vla_loop=False,
413                                            containing_field_name=None,
414                                            decode_mode=False):
415        """Returns a statement to assign the provided member
416
417        :param member_info:
418        :param in_vla_loop: True if we're currently inside a loop and should append [i]
419        :param containing_field_name: Additional member name to use to access the target field, or
420        None; for example the normal case is "out->field = in->field", but if we're generating
421        assignments in the parent conversion function (e.g. as used for union variants), we need to
422        do "out->nested_field.field = in->nested_field.field"
423        :param decode_mode: True converts from CHPP to CHRE. False from CHRE to CHPP
424        :return: assignment statement as a string
425        """
426        array_index = "[i]" if in_vla_loop else ""
427        output_accessor = "" if in_vla_loop else "out->"
428        containing_field = containing_field_name + "." if containing_field_name is not None else ""
429
430        output_variable = "{}{}{}{}".format(output_accessor, containing_field, member_info['name'],
431                                            array_index)
432        input_variable = "in->{}{}{}".format(containing_field, member_info['name'], array_index)
433
434        if decode_mode and in_vla_loop:
435            output_variable = "{}Out{}".format(member_info['name'], array_index)
436            input_variable = "{}In{}".format(member_info['name'], array_index)
437
438        if member_info['is_nested_type']:
439            chre_type = member_info['nested_type_name']
440            has_vla_member = self.api.structs_and_unions[chre_type]['has_vla_member']
441            if decode_mode:
442                # Use decoding function
443                vla_params = ", inSize" if has_vla_member else ""
444                out = "if (!{}(&{}, &{}{})) {{\n".format(
445                    self._get_decoding_function_name(chre_type), input_variable,
446                    output_variable, vla_params)
447                if has_vla_member:
448                    out += "  CHPP_FREE_AND_NULLIFY({}Out);\n".format(member_info['name'])
449                out += "  return false;\n"
450                out += "}\n"
451                return out
452            else:
453                # Use encoding function
454                vla_params = ", payload, payloadSize, vlaOffset" if has_vla_member else ""
455                return "{}(&{}, &{}{});\n".format(
456                    self._get_encoding_function_name(chre_type), input_variable, output_variable,
457                    vla_params)
458        elif self._is_array_type(member_info['type']):
459            # Array of primitive type (e.g. uint32_t[8]) - use memcpy
460            return "memcpy({}, {}, sizeof({}));\n".format(output_variable, input_variable,
461                                                          output_variable)
462        else:
463            # Regular assignment
464            return "{} = {};\n".format(output_variable, input_variable)
465
466    def _gen_union_variant_conversion_code(self, member_info, annotation, decode_mode):
467        """Generates a switch statement to encode the "active"/"used" field within a union.
468
469        Handles cases where a union has multiple types, but there's another peer/adjacent field
470        which tells you which field in the union is to be used. Outputs code like this:
471        switch (in->{discriminator field}) {
472            case {first discriminator value associated with a fields}:
473                {conversion code for the field associated with this discriminator value}
474                ...
475        :param chre_type: CHRE type of the union
476        :param annotation: Reference to JSON annotation data with the discriminator mapping data
477        :param decode_mode: False encodes from CHRE to CHPP. True decodes from CHPP to CHRE
478        :return: list of strings
479        """
480        out = []
481        chre_type = member_info['nested_type_name']
482        struct_info = self.api.structs_and_unions[chre_type]
483
484        # Start off by zeroing out the union field so any padding is set to a consistent value
485        out.append("  memset(&out->{}, 0, sizeof(out->{}));\n".format(member_info['name'],
486                                                                      member_info['name']))
487
488        # Next, generate the switch statement that will copy over the proper values
489        out.append("  switch (in->{}) {{\n".format(annotation['discriminator']))
490        for value, field_name in annotation['mapping']:
491            out.append("    case {}:\n".format(value))
492
493            found = False
494            for nested_member_info in struct_info['members']:
495                if nested_member_info['name'] == field_name:
496                    out.append("      {}".format(
497                        self._get_assignment_statement_for_field(
498                            nested_member_info,
499                            containing_field_name=member_info['name'],
500                            decode_mode=decode_mode)))
501                    found = True
502                    break
503
504            if not found:
505                raise RuntimeError("Invalid mapping - couldn't find target field {} in struct {}"
506                                   .format(field_name, chre_type))
507
508            out.append("      break;\n")
509
510        out.append("    default:\n"
511                   "      CHPP_ASSERT(false);\n"
512                   "  }\n")
513
514        return out
515
516    def _gen_conversion_function(self, chre_type, already_generated, decode_mode):
517        out = []
518
519        struct_info = self.api.structs_and_unions[chre_type]
520        for dependency in sorted(struct_info['dependencies']):
521            if dependency not in already_generated:
522                out.extend(
523                    self._gen_conversion_function(dependency, already_generated, decode_mode))
524
525        # Skip if we've already generated code for this type, or if it's a union (in which case we
526        # handle the assignment in the parent structure to enable support for discrimination of
527        # which field in the union to use)
528        if chre_type in already_generated or struct_info['is_union']:
529            return out
530        already_generated.add(chre_type)
531
532        out.append("static ")
533        if decode_mode:
534            out.extend(self._gen_decoding_function_signature(chre_type))
535        else:
536            out.extend(self._gen_encoding_function_signature(chre_type))
537        out.append(" {\n")
538
539        for member_info in self.api.structs_and_unions[chre_type]['members']:
540            generated_by_annotation = False
541            for annotation in member_info['annotations']:
542                if annotation['annotation'] == "fixed_value":
543                    if self._is_array_type(member_info['type']):
544                        out.append("  memset(&out->{}, {}, sizeof(out->{}));\n".format(
545                            member_info['name'], annotation['value'], member_info['name']))
546                    else:
547                        out.append("  out->{} = {};\n".format(member_info['name'],
548                                                              annotation['value']))
549                    generated_by_annotation = True
550                    break
551                elif annotation['annotation'] == "enum":
552                    # TODO: generate range verification code?
553                    pass
554                elif annotation['annotation'] == "var_len_array":
555                    if decode_mode:
556                        out.extend(self._gen_vla_decoding(member_info, annotation))
557                    else:
558                        out.extend(self._gen_vla_encoding(member_info, annotation))
559                    generated_by_annotation = True
560                    break
561                elif annotation['annotation'] == "union_variant":
562                    out.extend(self._gen_union_variant_conversion_code(
563                        member_info, annotation, decode_mode))
564                    generated_by_annotation = True
565                    break
566
567            if not generated_by_annotation:
568                out.append("  {}".format(
569                    self._get_assignment_statement_for_field(member_info, decode_mode=decode_mode)))
570
571        if decode_mode:
572            out.append("\n  return true;\n")
573
574        out.append("}\n\n")
575        return out
576
577    def _gen_conversion_functions(self, decode_mode):
578        out = []
579        already_generated = set()
580        for struct in self.json['root_structs']:
581            out.extend(self._gen_conversion_function(struct, already_generated, decode_mode))
582        return out
583
584    def _strip_prefix_and_service_from_chre_struct_name(self, struct):
585        """Strip 'chre' and service prefix, e.g. 'chreWwanCellResultInfo' -> 'CellResultInfo'"""
586        chre_stripped = struct[4:]
587        upcased_service_name = self.service_name[0].upper() + self.service_name[1:]
588        if not struct.startswith('chre') or not chre_stripped.startswith(upcased_service_name):
589            # If this happens, we need to update the script to handle it. Right we assume struct
590            # naming follows the pattern "chre<Service_name><Thing_name>"
591            raise RuntimeError("Unexpected structure name {}".format(struct))
592
593        return chre_stripped[len(self.service_name):]
594
595    # ----------------------------------------------------------------------------------------------
596    # Memory allocation generation methods
597    # ----------------------------------------------------------------------------------------------
598
599    def _get_chpp_sizeof_call(self, chre_type):
600        """Returns invocation used to determine the size of the provided CHRE struct (with the CHPP
601        app header) after encoding.
602
603        Like _get_chpp_member_sizeof_call(), except for a top-level type assigned to the variable
604        "in" rather than a member within a structure (e.g. a VLA field)
605        :param chre_type: CHRE type name
606        :return: string
607        """
608        if self.api.structs_and_unions[chre_type]['has_vla_member']:
609            return "{}(in)".format(self._get_chpp_sizeof_function_name(chre_type))
610        else:
611            return "sizeof({})".format(self._get_chpp_header_type_from_chre(chre_type))
612
613    def _get_encode_allocation_function_name(self, chre_type):
614        core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_type)
615        return "chpp{}{}FromChre".format(self.capitalized_service_name, core_type_name)
616
617    def _gen_encode_allocation_function_signature(self, chre_type, gen_docs=False):
618        out = []
619        if gen_docs:
620            out.append("/**\n"
621                       " * Converts from given CHRE structure to serialized CHPP type.\n"
622                       " *\n"
623                       " * @param in Fully-formed CHRE structure.\n"
624                       " * @param out Upon success, will point to a buffer allocated with "
625                       "chppMalloc().\n"
626                       " * It is the responsibility of the caller to set the values of the CHPP "
627                       "app layer header, and to free the buffer when it is no longer needed via "
628                       "chppFree() or CHPP_FREE_AND_NULLIFY().\n"
629                       " * @param outSize Upon success, will be set to the size of the output "
630                       "buffer, in bytes.\n"
631                       " *\n"
632                       " * @return true on success, false if memory allocation failed.\n"
633                       " */\n")
634        out.append("bool {}(\n".format(self._get_encode_allocation_function_name(chre_type)))
635        out.append("    const {}{} *in,\n".format(
636            self._get_struct_or_union_prefix(chre_type), chre_type))
637        out.append("    {} **out,\n".format(self._get_chpp_header_type_from_chre(chre_type)))
638        out.append("    size_t *outSize)")
639        return out
640
641    def _gen_encode_allocation_function(self, chre_type):
642        out = []
643
644        out.extend(self._gen_encode_allocation_function_signature(chre_type))
645        out.append(" {\n")
646        out.append("  CHPP_NOT_NULL(out);\n")
647        out.append("  CHPP_NOT_NULL(outSize);\n\n")
648        out.append("  size_t payloadSize = {};\n".format(
649            self._get_chpp_sizeof_call(chre_type)))
650        out.append("  *out = chppMalloc(payloadSize);\n")
651
652        out.append("  if (*out != NULL) {\n")
653
654        struct_info = self.api.structs_and_unions[chre_type]
655        if struct_info['has_vla_member']:
656            out.append("    uint8_t *payload = (uint8_t *) &(*out)->payload;\n")
657            out.append("    uint16_t vlaOffset = sizeof({});\n".format(
658                self._get_chpp_type_from_chre(chre_type)))
659
660        out.append("    {}(in, &(*out)->payload".format(
661            self._get_encoding_function_name(chre_type)))
662        if struct_info['has_vla_member']:
663            out.append(", payload, payloadSize, &vlaOffset")
664        out.append(");\n")
665        out.append("    *outSize = payloadSize;\n")
666        out.append("    return true;\n")
667        out.append("  }\n")
668
669        out.append("  return false;\n}\n\n")
670        return out
671
672    def _gen_encode_allocation_functions(self):
673        out = []
674        for chre_type in self.json['root_structs']:
675            out.extend(self._gen_encode_allocation_function(chre_type))
676        return out
677
678    def _gen_encode_allocation_function_signatures(self):
679        out = []
680        for chre_type in self.json['root_structs']:
681            out.extend(self._gen_encode_allocation_function_signature(chre_type, True))
682            out.append(";\n\n")
683        return out
684
685    # ----------------------------------------------------------------------------------------------
686    # Decoder function generation methods (CHPP --> CHRE)
687    # ----------------------------------------------------------------------------------------------
688
689    def _get_decoding_function_name(self, chre_type):
690        core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_type)
691        return "chpp{}Convert{}ToChre".format(self.capitalized_service_name, core_type_name)
692
693    def _gen_decoding_function_signature(self, chre_type):
694        out = []
695        out.append("bool {}(\n".format(self._get_decoding_function_name(chre_type)))
696        out.append("    const {} *in,\n".format(self._get_chpp_type_from_chre(chre_type)))
697        out.append("    {} *out".format(self._get_chre_type_with_prefix(chre_type)))
698        if self.api.structs_and_unions[chre_type]['has_vla_member']:
699            out.append(",\n")
700            out.append("    size_t inSize")
701        out.append(")")
702        return out
703
704    def _gen_vla_decoding(self, member_info, annotation):
705        out = []
706
707        variable_name = member_info['name']
708        chpp_type = self._get_member_type(member_info, True)
709        if member_info['is_nested_type']:
710            chre_type = self._get_chre_type_with_prefix(member_info['nested_type_name'])
711        else:
712            chre_type = chpp_type
713
714        out.append("\n")
715        out.append("  if (in->{}.length == 0) {{\n".format(variable_name))
716        out.append("    out->{} = NULL;\n".format(variable_name))
717        out.append("  }\n")
718        out.append("  else {\n")
719        out.append("    if (in->{}.offset + in->{}.length > inSize ||\n".format(
720            variable_name, variable_name))
721        out.append("        in->{}.length != in->{} * sizeof({})) {{\n".format(
722            variable_name, annotation['length_field'], chpp_type))
723
724        out.append("      return false;\n")
725        out.append("    }\n\n")
726
727        if member_info['is_nested_type']:
728            out.append("    const {} *{}In =\n".format(chpp_type, variable_name))
729            out.append("        (const {} *) &((const uint8_t *)in)[in->{}.offset];\n\n".format(
730                chpp_type, variable_name))
731
732        out.append("    {} *{}Out = chppMalloc(in->{} * sizeof({}));\n".format(
733            chre_type, variable_name, annotation['length_field'], chre_type))
734        out.append("    if ({}Out == NULL) {{\n".format(variable_name))
735        out.append("      return false;\n")
736        out.append("    }\n\n")
737
738        if member_info['is_nested_type']:
739            out.append("    for (size_t i = 0; i < in->{}; i++) {{\n".format(
740                annotation['length_field'], variable_name))
741            out.append("      {}".format(self._get_assignment_statement_for_field(
742                member_info, in_vla_loop=True, decode_mode=True)))
743            out.append("    }\n")
744        else:
745            out.append("    memcpy({}Out, &((const uint8_t *)in)[in->{}.offset],\n".format(
746                variable_name, variable_name))
747            out.append("      in->{} * sizeof({}));\n".format(
748                annotation['length_field'], chre_type))
749
750        out.append("    out->{} = {}Out;\n".format(variable_name, variable_name))
751        out.append("  }\n\n")
752
753        return out
754
755    def _get_decode_allocation_function_name(self, chre_type):
756        core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_type)
757        return "chpp{}{}ToChre".format(self.capitalized_service_name, core_type_name)
758
759    def _gen_decode_allocation_function_signature(self, chre_type, gen_docs=False):
760        out = []
761        if gen_docs:
762            out.append("/**\n"
763                       " * Converts from serialized CHPP structure to a CHRE type.\n"
764                       " *\n"
765                       " * @param in Fully-formed CHPP structure.\n"
766                       " * @param in Size of the CHPP structure in bytes.\n"
767                       " *\n"
768                       " * @return If successful, a pointer to a CHRE structure allocated with "
769                       "chppMalloc(). If unsuccessful, null.\n"
770                       " * It is the responsibility of the caller to free the buffer when it is no "
771                       "longer needed via chppFree() or CHPP_FREE_AND_NULLIFY().\n"
772                       " */\n")
773
774        out.append("{} *{}(\n".format(
775            self._get_chre_type_with_prefix(chre_type),
776            self._get_decode_allocation_function_name(chre_type)))
777        out.append("    const {} *in,\n".format(self._get_chpp_type_from_chre(chre_type)))
778        out.append("    size_t inSize)")
779        return out
780
781    def _gen_decode_allocation_function(self, chre_type):
782        out = []
783
784        out.extend(self._gen_decode_allocation_function_signature(chre_type))
785        out.append(" {\n")
786
787        out.append("  {} *out = NULL;\n\n".format(
788            self._get_chre_type_with_prefix(chre_type)))
789
790        out.append("  if (inSize >= sizeof({})) {{\n".format(
791            self._get_chpp_type_from_chre(chre_type)))
792
793        out.append("    out = chppMalloc(sizeof({}));\n".format(
794            self._get_chre_type_with_prefix(chre_type)))
795        out.append("    if (out != NULL) {\n")
796
797        struct_info = self.api.structs_and_unions[chre_type]
798
799        out.append("      if (!{}(in, out".format(self._get_decoding_function_name(chre_type)))
800        if struct_info['has_vla_member']:
801            out.append(", inSize")
802        out.append(")) {")
803        out.append("        CHPP_FREE_AND_NULLIFY(out);\n")
804        out.append("      }\n")
805
806        out.append("    }\n")
807        out.append("  }\n\n")
808        out.append("  return out;\n")
809        out.append("}\n")
810        return out
811
812    def _gen_decode_allocation_functions(self):
813        out = []
814        for chre_type in self.json['root_structs']:
815            out.extend(self._gen_decode_allocation_function(chre_type))
816        return out
817
818    def _gen_decode_allocation_function_signatures(self):
819        out = []
820        for chre_type in self.json['root_structs']:
821            out.extend(self._gen_decode_allocation_function_signature(chre_type, True))
822            out.append(";\n\n")
823        return out
824
825    # ----------------------------------------------------------------------------------------------
826    # Public methods
827    # ----------------------------------------------------------------------------------------------
828
829    def generate_header_file(self, dry_run=False, skip_clang_format=False):
830        """Creates a C header file for this API and writes it to the file indicated in the JSON."""
831        filename = self.service_name + "_types.h"
832        if not dry_run:
833            print("Generating {} ... ".format(filename), end='', flush=True)
834        output_file = os.path.join(system_chre_abs_path(), CHPP_PARSER_INCLUDE_PATH, filename)
835        header = self.generate_header_string()
836        self._dump_to_file(output_file, header, dry_run, skip_clang_format)
837        if not dry_run:
838            print("done")
839
840    def generate_header_string(self):
841        """Returns a C header with structure definitions for this API."""
842        # To defer concatenation (speed things up), build the file as a list of strings then only
843        # concatenate once at the end
844        out = [LICENSE_HEADER]
845
846        header_guard = "CHPP_{}_TYPES_H_".format(self.service_name.upper())
847
848        out.append("#ifndef {}\n#define {}\n\n".format(header_guard, header_guard))
849        out.extend(self._autogen_notice())
850        out.extend(self._gen_header_includes())
851        out.append("#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n")
852        out.extend(self._gen_structs_and_unions())
853
854        out.append("\n// Encoding functions (CHRE --> CHPP)\n\n")
855        out.extend(self._gen_encode_allocation_function_signatures())
856
857        out.append("\n// Decoding functions (CHPP --> CHRE)\n\n")
858        out.extend(self._gen_decode_allocation_function_signatures())
859
860        out.append("#ifdef __cplusplus\n}\n#endif\n\n")
861        out.append("#endif  // {}\n".format(header_guard))
862        return ''.join(out)
863
864    def generate_conversion_file(self, dry_run=False, skip_clang_format=False):
865        """Generates a .c file with functions for encoding CHRE structs into CHPP and vice versa."""
866        filename = self.service_name + "_convert.c"
867        if not dry_run:
868            print("Generating {} ... ".format(filename), end='', flush=True)
869        contents = self.generate_conversion_string()
870        output_file = os.path.join(system_chre_abs_path(), CHPP_PARSER_SOURCE_PATH, filename)
871        self._dump_to_file(output_file, contents, dry_run, skip_clang_format)
872        if not dry_run:
873            print("done")
874
875    def generate_conversion_string(self):
876        """Returns C code for encoding CHRE structs into CHPP and vice versa."""
877        out = [LICENSE_HEADER, "\n"]
878
879        out.extend(self._autogen_notice())
880        out.extend(self._gen_conversion_includes())
881
882        out.append("\n// Encoding (CHRE --> CHPP) size functions\n\n")
883        out.extend(self._gen_chpp_sizeof_functions())
884        out.append("\n// Encoding (CHRE --> CHPP) conversion functions\n\n")
885        out.extend(self._gen_conversion_functions(False))
886        out.append("\n// Encoding (CHRE --> CHPP) top-level functions\n\n")
887        out.extend(self._gen_encode_allocation_functions())
888
889        out.append("\n// Decoding (CHPP --> CHRE) conversion functions\n\n")
890        out.extend(self._gen_conversion_functions(True))
891        out.append("\n// Decoding (CHPP --> CHRE) top-level functions\n\n")
892        out.extend(self._gen_decode_allocation_functions())
893
894        return ''.join(out)
895
896
897class ApiParser:
898    """Given a file-specific set of annotations (extracted from JSON annotations file), parses a
899    single API header file into data structures suitable for use with code generation.
900    """
901
902    def __init__(self, json_obj):
903        """Initialize and parse the API file described in the provided JSON-derived object.
904
905        :param json_obj: Extracted file-specific annotations from JSON
906        """
907        self.json = json_obj
908        self.structs_and_unions = {}
909        self._parse_annotations()
910        self._parse_api()
911
912    def _parse_annotations(self):
913        # Convert annotations list to a more usable data structure: dict keyed by structure name,
914        # containing a dict keyed by field name, containing a list of annotations (as they
915        # appear in the JSON). In other words, we can easily get all of the annotations for the
916        # "version" field in "chreWwanCellInfoResult" via
917        # annotations['chreWwanCellInfoResult']['version']. This is also a defaultdict, so it's safe
918        # to access if there are no annotations for this structure + field; it'll just give you
919        # an empty list in that case.
920        self.annotations = defaultdict(lambda: defaultdict(list))
921        for struct_info in self.json['struct_info']:
922            for annotation in struct_info['annotations']:
923                self.annotations[struct_info['name']][annotation['field']].append(annotation)
924
925    def _files_to_parse(self):
926        """Returns a list of files to supply as input to CParser"""
927        # Input paths for CParser are stored in JSON relative to <android_root>/system/chre
928        # Reformulate these to absolute paths, and add in some default includes that we always
929        # supply
930        chre_project_base_dir = system_chre_abs_path()
931        default_includes = ["chpp/api_parser/parser_defines.h",
932                            "chre_api/include/chre_api/chre/version.h"]
933        files = default_includes + self.json['includes'] + [self.json['filename']]
934        return [os.path.join(chre_project_base_dir, file) for file in files]
935
936    def _parse_structs_and_unions(self):
937        # Starting with the root structures (i.e. those that will appear at the top-level in one
938        # or more CHPP messages), build a data structure containing all of the information we'll
939        # need to emit the CHPP structure definition and conversion code.
940        structs_and_unions_to_parse = self.json['root_structs'].copy()
941        while len(structs_and_unions_to_parse) > 0:
942            type_name = structs_and_unions_to_parse.pop()
943            if type_name in self.structs_and_unions:
944                continue
945
946            entry = {
947                'appears_in': set(),  # Other types this type is nested within
948                'dependencies': set(),  # Types that are nested in this type
949                'has_vla_member': False,  # True if this type or any dependency has a VLA member
950                'members': [],  # Info about each member of this type
951            }
952            if type_name in self.parser.defs['structs']:
953                defs = self.parser.defs['structs'][type_name]
954                entry['is_union'] = False
955            elif type_name in self.parser.defs['unions']:
956                defs = self.parser.defs['unions'][type_name]
957                entry['is_union'] = True
958            else:
959                raise RuntimeError("Couldn't find {} in parsed structs/unions".format(type_name))
960
961            for member_name, member_type, _ in defs['members']:
962                member_info = {
963                    'name': member_name,
964                    'type': member_type,
965                    'annotations': self.annotations[type_name][member_name],
966                    'is_nested_type': False,
967                }
968
969                if member_type.type_spec.startswith('struct ') or \
970                        member_type.type_spec.startswith('union '):
971                    member_info['is_nested_type'] = True
972                    member_type_name = member_type.type_spec.split(' ')[1]
973                    member_info['nested_type_name'] = member_type_name
974                    entry['dependencies'].add(member_type_name)
975                    structs_and_unions_to_parse.append(member_type_name)
976
977                entry['members'].append(member_info)
978
979                # Flip a flag if this structure has at least one variable-length array member, which
980                # means that the encoded size can only be computed at runtime
981                if not entry['has_vla_member']:
982                    for annotation in self.annotations[type_name][member_name]:
983                        if annotation['annotation'] == "var_len_array":
984                            entry['has_vla_member'] = True
985
986            self.structs_and_unions[type_name] = entry
987
988        # Build reverse linkage of dependency chain (i.e. lookup between a type and the other types
989        # it appears in)
990        for type_name, type_info in self.structs_and_unions.items():
991            for dependency in type_info['dependencies']:
992                self.structs_and_unions[dependency]['appears_in'].add(type_name)
993
994        # Bubble up "has_vla_member" to types each type it appears in, i.e. if this flag is set to
995        # True on a leaf node, then all its ancestors should also have the flag set to True
996        for type_name, type_info in self.structs_and_unions.items():
997            if type_info['has_vla_member']:
998                types_to_mark = list(type_info['appears_in'])
999                while len(types_to_mark) > 0:
1000                    type_to_mark = types_to_mark.pop()
1001                    self.structs_and_unions[type_to_mark]['has_vla_member'] = True
1002                    types_to_mark.extend(list(self.structs_and_unions[type_to_mark]['appears_in']))
1003
1004    def _parse_api(self):
1005        file_to_parse = self._files_to_parse()
1006        self.parser = CParser(file_to_parse, cache='parser_cache')
1007        self._parse_structs_and_unions()
1008
1009
1010def run(args):
1011    with open('chre_api_annotations.json') as f:
1012        js = json.load(f)
1013
1014    commit_hash = subprocess.getoutput("git describe --always --long --dirty --exclude '*'")
1015    for file in js:
1016        if args.file_filter:
1017            matched = False
1018            for matcher in args.file_filter:
1019                if matcher in file['filename']:
1020                    matched = True
1021                    break
1022            if not matched:
1023                print("Skipping {} - doesn't match filter(s) {}".format(file['filename'],
1024                                                                        args.file_filter))
1025                continue
1026        print("Parsing {} ... ".format(file['filename']), end='', flush=True)
1027        api_parser = ApiParser(file)
1028        code_gen = CodeGenerator(api_parser, commit_hash)
1029        print("done")
1030        code_gen.generate_header_file(args.dry_run, args.skip_clang_format)
1031        code_gen.generate_conversion_file(args.dry_run, args.skip_clang_format)
1032
1033
1034if __name__ == "__main__":
1035    parser = argparse.ArgumentParser(description='Generate CHPP serialization code from CHRE APIs.')
1036    parser.add_argument('-n', dest='dry_run', action='store_true',
1037                        help='Print the output instead of writing to a file')
1038    parser.add_argument('--skip-clang-format', dest='skip_clang_format', action='store_true',
1039                        help='Skip running clang-format on the output files (doesn\'t apply to dry '
1040                             'runs)')
1041    parser.add_argument('file_filter', nargs='*',
1042                        help='Filters the input files (filename field in the JSON) to generate a '
1043                             'subset of the typical output, e.g. "wifi" to just generate conversion'
1044                             ' routines for wifi.h')
1045    args = parser.parse_args()
1046    run(args)
1047